branch_name
stringclasses
149 values
text
stringlengths
23
89.3M
directory_id
stringlengths
40
40
languages
listlengths
1
19
num_files
int64
1
11.8k
repo_language
stringclasses
38 values
repo_name
stringlengths
6
114
revision_id
stringlengths
40
40
snapshot_id
stringlengths
40
40
refs/heads/master
<file_sep># Be sure to restart your server when you modify this file. AutomatedBrowser::Application.config.session_store :cookie_store, key: '_automated_browser_session' <file_sep>class BrowserController < ApplicationController def buttons end def google browser.get "http://www.google.com" redirect_to :action => "buttons" end def betpack browser.get "http://www.betpack.com" redirect_to :action => "buttons" end private def browser @@browser ||= AutomatedBrowser::Application::BROWSER_INSTANCE end end
9da08f5346ad629d1a3ae5fb8dba993272798db8
[ "Ruby" ]
2
Ruby
rudedoc/auto_fox
e620e216b38f2f2aa15503779c34216754e63c64
e508fc11f08e0376b36d2087009df03f1307a605
refs/heads/master
<file_sep> /** * First we will load all of this project's JavaScript dependencies which * includes Vue and other libraries. It is a great starting point when * building robust, powerful web applications using Vue and Laravel. */ require('./bootstrap'); window.Vue = require('vue'); /** * Next, we will create a fresh Vue application instance and attach it to * the page. Then, you may begin adding components to this application * or customize the JavaScript scaffolding to fit your unique needs. */ Vue.component('client', require('./components/Client.vue')); Vue.component('rol', require('./components/Rol.vue')); Vue.component('user', require('./components/User.vue')); Vue.component('mbrp_questionnaire', require('./components/Mbrp_questionnaire.vue')); Vue.component('mbrp_quest_cli', require('./components/Mbrp_quest_cli.vue')); Vue.component('mbrp_parameter', require('./components/Mbrp_parameter.vue')); Vue.component('brs_quest', require('./components/Brs_quest.vue')); Vue.component('urica_quest', require('./components/Urica_quest.vue')); Vue.component('hwbTracker_cli', require('./components/HwbTracker_cli.vue')); Vue.component('radarExample', require('./components/RadarExample.vue')); Vue.component('categoria', require('./components/Categoria.vue')); Vue.component('articulo', require('./components/Articulo.vue')); Vue.component('proveedor', require('./components/Proveedor.vue')); import ElementUI from 'element-ui'; import 'element-ui/lib/theme-chalk/index.css'; Vue.use(require('vue-moment')); Vue.use(ElementUI); const app = new Vue({ el: '#app', data :{ menu : 0, minibar:'' } }); <file_sep><?php namespace App; use Illuminate\Database\Eloquent\Model; class Mbrp_programme extends Model { // protected $table = 'mbrp_programmes'; protected $primaryKey = 'id'; protected $fillable = ['name','description','brs_q','urica_q','datc_q','spsi_q','mh_q','pf_q']; public function mbrp_questionnaires() { return $this->hasMany('App\Mbrp_questionnaire', 'mbrp_programme_id'); //return $this->hasMany('App\Mbrp_questionnaire'); } } <file_sep><?php namespace App; use Illuminate\Database\Eloquent\Model; class Person extends Model { protected $table = 'persons'; protected $primaryKey = 'id'; protected $fillable = ['first_name','last_name','id_document','address','phone','email']; public function client() { return $this->hasOne('App\Client'); } public function provedor() { return $this->hasOne('App\Proveedor'); } public function user() { return $this->hasOne('App\User'); } } <file_sep><?php use Illuminate\Support\Facades\Schema; use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class CreateMhTestsTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('mh_tests', function (Blueprint $table) { $table->increments('id'); $table->smallInteger('dep_score')->default(0); $table->unsignedTinyInteger('dep1')->default(0); $table->unsignedTinyInteger('dep2')->default(0); $table->unsignedTinyInteger('dep3')->default(0); $table->unsignedTinyInteger('dep4')->default(0); $table->unsignedTinyInteger('dep5')->default(0); $table->unsignedTinyInteger('dep6')->default(0); $table->unsignedTinyInteger('dep7')->default(0); $table->unsignedTinyInteger('dep8')->default(0); $table->unsignedTinyInteger('dep9')->default(0); $table->smallInteger('anx_score')->default(0); $table->unsignedTinyInteger('anx1')->default(0); $table->unsignedTinyInteger('anx2')->default(0); $table->unsignedTinyInteger('anx3')->default(0); $table->unsignedTinyInteger('anx4')->default(0); $table->unsignedTinyInteger('anx5')->default(0); $table->unsignedTinyInteger('anx6')->default(0); $table->unsignedTinyInteger('anx7')->default(0); $table->unsignedTinyInteger('anx8')->default(0); $table->unsignedTinyInteger('anx9')->default(0); $table->smallInteger('tra_score')->default(0); $table->unsignedTinyInteger('tra1')->default(0); $table->unsignedTinyInteger('tra2')->default(0); $table->unsignedTinyInteger('tra3')->default(0); $table->unsignedTinyInteger('tra4')->default(0); $table->smallInteger('sw_score')->default(0); $table->timestamps(); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::dropIfExists('mh_tests'); } } <file_sep><?php use Illuminate\Support\Facades\Schema; use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class CreateMbrpQuestionnairesTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('mbrp_questionnaires', function (Blueprint $table) { $table->increments('id'); $table->integer('client_id')->unsigned(); $table->tinyInteger('client_age')->unsigned(); $table->string('stage',15); $table->integer('mbrp_programme_id')->unsigned(); $table->dateTime('date_engaged')->nullable(); $table->dateTime('date_completed')->nullable(); $table->boolean('is_completed')->nullable(); $table->string('end_reason',5)->nullable(); $table->boolean('brs_q')->default(0); $table->integer('brs_test_id')->unsigned()->nullable(); $table->boolean('urica_q')->default(0); $table->integer('urica_test_id')->unsigned()->nullable(); $table->boolean('datc_q')->default(0); $table->integer('datc_test_id')->unsigned()->nullable(); $table->boolean('spsi_q')->default(0); $table->integer('spsi_test_id')->unsigned()->nullable(); $table->boolean('mh_q')->default(0); $table->integer('mh_test_id')->unsigned()->nullable(); $table->boolean('pf_q')->default(0); $table->unsignedTinyInteger('pf1')->default(0); $table->unsignedTinyInteger('pf2')->default(0); $table->unsignedTinyInteger('pf3')->default(0); $table->unsignedTinyInteger('pf4')->default(0); $table->unsignedTinyInteger('pf5')->default(0); $table->unsignedTinyInteger('pf6')->default(0); $table->unsignedTinyInteger('pf7')->default(0); $table->unsignedTinyInteger('pf8')->default(0); $table->unsignedTinyInteger('pf9')->default(0); $table->unsignedTinyInteger('pf10')->default(0); $table->unsignedTinyInteger('pf11')->default(0); $table->text('pf_comments')->nullable(); $table->timestamps(); $table->foreign('mbrp_programme_id')->references('id')->on('mbrp_programmes'); $table->foreign('client_id')->references('id')->on('clients'); $table->foreign('brs_test_id')->references('id')->on('brs_tests')->onDelete('cascade'); $table->foreign('urica_test_id')->references('id')->on('urica_tests')->onDelete('cascade'); $table->foreign('datc_test_id')->references('id')->on('datc_tests')->onDelete('cascade'); $table->foreign('spsi_test_id')->references('id')->on('spsi_tests')->onDelete('cascade'); $table->foreign('mh_test_id')->references('id')->on('mh_tests')->onDelete('cascade'); /* $table->integer('idproveedor')->unsigned(); $table->foreign('idproveedor')->references('id')->on('proveedores'); $table->integer('idusuario')->unsigned(); $table->foreign('idusuario')->references('id')->on('users'); $table->string('tipo_comprobante', 20); $table->string('serie_comprobante', 7)->nullable(); $table->string('num_comprobante', 10); $table->dateTime('fecha_hora'); $table->decimal('impuesto', 4, 2); $table->decimal('total', 11, 2); $table->string('estado', 20); */ }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::dropIfExists('mbrp_questionnaires'); } } <file_sep><?php use Illuminate\Support\Facades\Schema; use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class CreateMbrpProgrammesTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('mbrp_programmes', function (Blueprint $table) { $table->increments('id'); $table->string('name',50)->unique(); $table->text('description')->nullable(); $table->boolean('active')->default(1); $table->boolean('brs_q')->default(0); $table->boolean('urica_q')->default(0); $table->boolean('datc_q')->default(0); $table->boolean('spsi_q')->default(0); $table->boolean('mh_q')->default(0); $table->boolean('pf_q')->default(0); $table->timestamps(); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::dropIfExists('mbrp_programmes'); } } <file_sep><?php use Illuminate\Support\Facades\Schema; use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class CreateSpsiTestsTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('spsi_tests', function (Blueprint $table) { $table->increments('id'); $table->smallInteger('ppo_score')->default(0); $table->smallInteger('npo_score')->default(0); $table->smallInteger('rps_score')->default(0); $table->smallInteger('ics_score')->default(0); $table->smallInteger('as_score')->default(0); $table->smallInteger('sps_score')->default(0); $table->unsignedTinyInteger('spsi1')->default(0); $table->unsignedTinyInteger('spsi2')->default(0); $table->unsignedTinyInteger('spsi3')->default(0); $table->unsignedTinyInteger('spsi4')->default(0); $table->unsignedTinyInteger('spsi5')->default(0); $table->unsignedTinyInteger('spsi6')->default(0); $table->unsignedTinyInteger('spsi7')->default(0); $table->unsignedTinyInteger('spsi8')->default(0); $table->unsignedTinyInteger('spsi9')->default(0); $table->unsignedTinyInteger('spsi10')->default(0); $table->unsignedTinyInteger('spsi11')->default(0); $table->unsignedTinyInteger('spsi12')->default(0); $table->unsignedTinyInteger('spsi13')->default(0); $table->unsignedTinyInteger('spsi14')->default(0); $table->unsignedTinyInteger('spsi15')->default(0); $table->unsignedTinyInteger('spsi16')->default(0); $table->unsignedTinyInteger('spsi17')->default(0); $table->unsignedTinyInteger('spsi18')->default(0); $table->unsignedTinyInteger('spsi19')->default(0); $table->unsignedTinyInteger('spsi20')->default(0); $table->unsignedTinyInteger('spsi21')->default(0); $table->unsignedTinyInteger('spsi22')->default(0); $table->unsignedTinyInteger('spsi23')->default(0); $table->unsignedTinyInteger('spsi24')->default(0); $table->unsignedTinyInteger('spsi25')->default(0); $table->timestamps(); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::dropIfExists('spsi_tests'); } } <file_sep><?php namespace App\Http\Controllers; use Illuminate\Http\Request; use App\Mbrp_parameter; class Mbrp_parameterController extends Controller { // public function index(Request $request) { if (!$request->ajax()) return redirect('/'); $buscar = $request->buscar; $criterio = $request->criterio; if ($buscar==''){ $parameters = Mbrp_parameter::orderBy('id', 'desc')->paginate(10); } else{ $parameters = Mbrp_parameter::where($criterio, 'like', '%'. $buscar . '%')->orderBy('id', 'desc')->paginate(10); } return [ 'pagination' => [ 'total' => $parameters->total(), 'current_page' => $parameters->currentPage(), 'per_page' => $parameters->perPage(), 'last_page' => $parameters->lastPage(), 'from' => $parameters->firstItem(), 'to' => $parameters->lastItem(), ], 'parameters' => $parameters ]; } public function selectParameter(Request $request) { $field = $request->field; if (!$request->ajax()) return redirect('/'); $Parameters = Mbrp_parameter::where('field', '=', $field)->where('active', '=', 1) ->select('id','name','code','description','score','order','param_type','bottom_value','top_value') ->orderBy('order', 'asc')->get(); return ['parameters' => $Parameters]; } public function store(Request $request) { if (!$request->ajax()) return redirect('/'); $parameter = new Mbrp_parameter(); $parameter->name = $request->name; $parameter->code = $request->code; $parameter->description = $request->description; $parameter->score = $request->score; $parameter->active = '1'; $parameter->field = $request->field; $parameter->order = $request->order; $parameter->param_type = $request->param_type; $parameter->bottom_value = $request->bottom_value; $parameter->top_value = $request->top_value; $parameter->opt_prison = $request->opt_prison; $parameter->opt_community = $request->opt_community; $parameter->save(); } /** * Update the specified resource in storage. * * @param \Illuminate\Http\Request $request * @param int $id * @return \Illuminate\Http\Response */ public function update(Request $request) { if (!$request->ajax()) return redirect('/'); $parameter = Mbrp_parameter::findOrFail($request->id); $parameter->name = $request->name; $parameter->code = $request->code; $parameter->description = $request->description; $parameter->score = $request->score; $parameter->active = $request->active; $parameter->field = $request->field; $parameter->order = $request->order; $parameter->param_type = $request->param_type; $parameter->bottom_value = $request->bottom_value; $parameter->top_value = $request->top_value; $parameter->opt_prison = $request->opt_prison; $parameter->opt_community = $request->opt_community; $parameter->save(); } public function desactivar(Request $request) { if (!$request->ajax()) return redirect('/'); $parameter = Mbrp_parameter::findOrFail($request->id); $parameter->active = '0'; $parameter->save(); } public function activar(Request $request) { if (!$request->ajax()) return redirect('/'); $parameter = Mbrp_parameter::findOrFail($request->id); $parameter->active = '1'; $parameter->save(); } } <file_sep><?php namespace App; use Illuminate\Database\Eloquent\Model; class Mbrp_questionnaire extends Model { protected $table = 'mbrp_questionnaires'; protected $primaryKey = 'id'; protected $fillable = [ 'client_id', 'client_age', 'mbrp_programme_id', 'date_engaged', 'date_completed', 'is_completed', 'end_reason','stage', 'brs_q','urica_q','datc_q','spsi_q','mh_q','pf_q' ]; public function mbrp_programme(){ return $this->belongsTo('App\Mbrp_programme', 'mbrp_programme_id'); //return $this->belongsTo('App\Mbrp_programme'); } public function client(){ return $this->belongsTo('App\Client'); } public function brsTest(){ return $this->hasOne('App\BrsTest','id','brs_test_id'); } public function uricaTest(){ return $this->hasOne('App\UricaTest','id','urica_test_id'); } public function datcTest(){ return $this->hasOne('App\DatcTest','id','datc_test_id'); } public function spsiTest(){ return $this->hasOne('App\SpsiTest','id','spsi_test_id'); } public function mhTest(){ return $this->hasOne('App\MhTest','id','mh_test_id'); } // } <file_sep><?php namespace App; use Illuminate\Database\Eloquent\Model; class Client extends Model { // protected $fillable = [ 'id','reference','initials', 'dob','contact', 'contact_phone' ]; public function person() { return $this->belongsTo('App\Person'); } public function mbrp_questionnaire() { return $this->hasMany('App\Mbrp_questionnaire'); } } <file_sep><?php use Illuminate\Support\Facades\Schema; use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class CreateMbrpParametersTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('mbrp_parameters', function (Blueprint $table) { $table->increments('id'); $table->string('name',50); $table->string('code',10)->nullable(); $table->string('description',255)->nullable(); $table->integer('score')->nullable(); $table->boolean('active')->default(1); $table->string('field',50)->nullable()->default(''); $table->tinyInteger('order')->unsigned(); $table->string('param_type',50)->nullable()->default(''); $table->tinyInteger('bottom_value')->nullable()->default(0); $table->tinyInteger('top_value')->nullable()->default(0); $table->boolean('opt_prison')->default(0); $table->boolean('opt_community')->default(0); $table->timestamps(); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::dropIfExists('mbrp_parameters'); } } <file_sep><?php use Illuminate\Support\Facades\Schema; use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class CreateUricaTestsTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('urica_tests', function (Blueprint $table) { $table->increments('id'); $table->string('urica_highest',10)->nullable(); $table->smallInteger('pr_score')->default(0); $table->smallInteger('con_score')->default(0); $table->smallInteger('ac_score')->default(0); $table->smallInteger('ma_score')->default(0); $table->unsignedTinyInteger('urica1')->default(0); $table->unsignedTinyInteger('urica2')->default(0); $table->unsignedTinyInteger('urica3')->default(0); $table->unsignedTinyInteger('urica4')->default(0); $table->unsignedTinyInteger('urica5')->default(0); $table->unsignedTinyInteger('urica6')->default(0); $table->unsignedTinyInteger('urica7')->default(0); $table->unsignedTinyInteger('urica8')->default(0); $table->unsignedTinyInteger('urica9')->default(0); $table->unsignedTinyInteger('urica10')->default(0); $table->unsignedTinyInteger('urica11')->default(0); $table->unsignedTinyInteger('urica12')->default(0); $table->unsignedTinyInteger('urica13')->default(0); $table->unsignedTinyInteger('urica14')->default(0); $table->unsignedTinyInteger('urica15')->default(0); $table->unsignedTinyInteger('urica16')->default(0); $table->unsignedTinyInteger('urica17')->default(0); $table->unsignedTinyInteger('urica18')->default(0); $table->unsignedTinyInteger('urica19')->default(0); $table->unsignedTinyInteger('urica20')->default(0); $table->unsignedTinyInteger('urica21')->default(0); $table->unsignedTinyInteger('urica22')->default(0); $table->unsignedTinyInteger('urica23')->default(0); $table->unsignedTinyInteger('urica24')->default(0); $table->unsignedTinyInteger('urica25')->default(0); $table->unsignedTinyInteger('urica26')->default(0); $table->unsignedTinyInteger('urica27')->default(0); $table->unsignedTinyInteger('urica28')->default(0); $table->unsignedTinyInteger('urica29')->default(0); $table->unsignedTinyInteger('urica30')->default(0); $table->unsignedTinyInteger('urica31')->default(0); $table->unsignedTinyInteger('urica32')->default(0); $table->timestamps(); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::dropIfExists('urica_tests'); } } <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('roles', function () { // dd(App\Categoria::with('articulos')->get()); // dd(App\Mbrp_questionnaire::find(4)->mbrp_programme); //dd(App\Mbrp_programme::find(1)); // DB::listen(function($query){ // echo "<pre>{$query->sql} </pre>"; // }); //dd(App\Mbrp_programme::with('mbrp_questionaries:name')->get()); // dd(App\Mbrp_questionnaire::with('Mbrp_programme')->get()); //dd(App\Mbrp_programme::find(2)->mbrp_questionnaires); //}); // DB::listen(function($query){ // echo "<pre>{$query->sql} </pre>"; // }); Route::group(['middleware'=>['guest']],function(){ Route::get('/','Auth\LoginController@showLoginForm'); Route::get('/login','Auth\LoginController@showLoginForm'); Route::post('/login', 'Auth\LoginController@login')->name('login'); }); Route::group(['middleware'=>['auth']],function(){ Route::post('/logout', 'Auth\LoginController@logout')->name('logout'); Route::get('/main', function () { return view('contenido/contenido'); })->name('main'); Route::group(['middleware' => ['ClientRole']], function () { }); Route::group(['middleware' => ['Worker']], function () { Route::get('/client', 'ClientController@index'); Route::post('/client/register', 'ClientController@store'); Route::put('/client/update', 'ClientController@update'); Route::get('/client/selectClient', 'ClientController@selectClient'); Route::get('/hwbTracker', 'HwbTrackerController@index'); Route::post('/hwbTracker/register', 'HwbTrackerController@store'); Route::put('/hwbTracker/update', 'HwbTrackerController@update'); Route::delete('/hwbTracker/{id}', 'HwbTrackerController@destroy'); // Route::put('/mbrp_questionnaire/delete', 'HwbTrackerController@delete'); Route::get('/mbrp_parameter/selectParameter', 'Mbrp_parameterController@selectParameter'); Route::get('/mbrp_programme/selectProgrammes', 'Mbrp_programmeController@selectProgrammes'); Route::get('/mbrp_questionnaire', 'Mbrp_questionnaireController@index'); Route::post('/mbrp_questionnaire/register', 'Mbrp_questionnaireController@store'); Route::put('/mbrp_questionnaire/update', 'Mbrp_questionnaireController@update'); Route::put('/mbrp_questionnaire/registerbrs', 'Mbrp_questionnaireController@registerBrs'); Route::put('/mbrp_questionnaire/updatebrs', 'Mbrp_questionnaireController@updateBrs'); Route::put('/mbrp_questionnaire/updateurica', 'Mbrp_questionnaireController@updateUrica'); Route::delete('/mbrp_questionnaire/{id}', 'Mbrp_questionnaireController@destroy'); }); Route::group(['middleware' => ['Administrador']], function () { Route::get('/client', 'ClientController@index'); Route::post('/client/register', 'ClientController@store'); Route::put('/client/update', 'ClientController@update'); Route::get('/client/selectClient', 'ClientController@selectClient'); Route::get('/hwbTracker', 'HwbTrackerController@index'); Route::post('/hwbTracker/register', 'HwbTrackerController@store'); Route::put('/hwbTracker/update', 'HwbTrackerController@update'); Route::delete('/hwbTracker/{id}', 'HwbTrackerController@destroy'); // Route::put('/mbrp_questionnaire/delete', 'HwbTrackerController@delete'); Route::get('/mbrp_parameter', 'Mbrp_parameterController@index'); Route::post('/mbrp_parameter/register', 'Mbrp_parameterController@store'); Route::put('/mbrp_parameter/update', 'Mbrp_parameterController@update'); Route::put('/mbrp_parameter/desactivar', 'Mbrp_parameterController@desactivar'); Route::put('/mbrp_parameter/activar', 'Mbrp_parameterController@activar'); Route::get('/mbrp_parameter/selectParameter', 'Mbrp_parameterController@selectParameter'); Route::get('/mbrp_programme/selectProgrammes', 'Mbrp_programmeController@selectProgrammes'); Route::get('/mbrp_questionnaire', 'Mbrp_questionnaireController@index'); Route::post('/mbrp_questionnaire/register', 'Mbrp_questionnaireController@store'); Route::put('/mbrp_questionnaire/update', 'Mbrp_questionnaireController@update'); Route::put('/mbrp_questionnaire/registerbrs', 'Mbrp_questionnaireController@registerBrs'); Route::put('/mbrp_questionnaire/updatebrs', 'Mbrp_questionnaireController@updateBrs'); Route::put('/mbrp_questionnaire/updateurica', 'Mbrp_questionnaireController@updateUrica'); Route::delete('/mbrp_questionnaire/{id}', 'Mbrp_questionnaireController@destroy'); Route::get('/categoria', 'CategoriaController@index'); Route::post('/categoria/registrar', 'CategoriaController@store'); Route::put('/categoria/actualizar', 'CategoriaController@update'); Route::put('/categoria/desactivar', 'CategoriaController@desactivar'); Route::put('/categoria/activar', 'CategoriaController@activar'); Route::get('/categoria/selectCategoria', 'CategoriaController@selectCategoria'); Route::get('/articulo', 'ArticuloController@index'); Route::post('/articulo/registrar', 'ArticuloController@store'); Route::put('/articulo/actualizar', 'ArticuloController@update'); Route::put('/articulo/desactivar', 'ArticuloController@desactivar'); Route::put('/articulo/activar', 'ArticuloController@activar'); Route::get('/proveedor', 'ProveedorController@index'); Route::post('/proveedor/registrar', 'ProveedorController@store'); Route::put('/proveedor/actualizar', 'ProveedorController@update'); Route::get('/rol', 'RolController@index'); Route::get('/rol/selectRol', 'RolController@selectRol'); Route::get('/user', 'UserController@index'); Route::post('/user/registrar', 'UserController@store'); Route::put('/user/actualizar', 'UserController@update'); Route::put('/user/desactivar', 'UserController@desactivar'); Route::put('/user/activar', 'UserController@activar'); }); }); //Route::get('/home', 'HomeController@index')->name('home'); <file_sep><?php namespace App\Http\Controllers; use Illuminate\Http\Request; use Illuminate\Support\Facades\DB; use App\HwbTracker; class HwbTrackerController extends Controller { /** * Display a listing of the resource. * * @return \Illuminate\Http\Response */ public function index(Request $request) { if (!$request->ajax()) return redirect('/'); $buscar = $request->buscar; $criterio = $request->criterio; if ($buscar==''){ $hwb_tracker = HwbTracker::with('client')->orderBy('id', 'desc')->paginate(5); } else{ $hwb_tracker = HwbTracker::with('client')->where($criterio, 'like', '%'. $buscar . '%')->orderBy('id', 'desc')->paginate(5); } return [ 'pagination' => [ 'total' => $hwb_tracker->total(), 'current_page' => $hwb_tracker->currentPage(), 'per_page' => $hwb_tracker->perPage(), 'last_page' => $hwb_tracker->lastPage(), 'from' => $hwb_tracker->firstItem(), 'to' => $hwb_tracker->lastItem(), ], 'hwb_tracker' => $hwb_tracker ]; } public function getTracker(Request $request) { if (!$request->ajax()) return redirect('/'); $hwb_tracker = HwbTracker::findOrFail($request->id); return $hwb_tracker; } /** * Store a newly created resource in storage. * * @param \Illuminate\Http\Request $request * @return \Illuminate\Http\Response */ public function store(Request $request) { if (!$request->ajax()) return redirect('/'); $hwb_tracker = new HwbTracker(); $hwb_tracker->client_id = $request->client_id; $hwb_tracker->description = $request->description; $hwb_tracker->date_track = $request->date_track; $hwb_tracker->sn_value = $request->sn_value; $hwb_tracker->pcls_value = $request->pcls_value; $hwb_tracker->emp_value = $request->emp_value; $hwb_tracker->nps_value = $request->nps_value; $hwb_tracker->ips_value = $request->ips_value; $hwb_tracker->smk_value = $request->smk_value; $hwb_tracker->sh_value = $request->sh_value; $hwb_tracker->ph_value = $request->ph_value; $hwb_tracker->mh_value = $request->mh_value; $hwb_tracker->dau_value = $request->dau_value; $hwb_tracker->sn_notes = $request->sn_notes; $hwb_tracker->pcls_notes = $request->pcls_notes; $hwb_tracker->emp_notes = $request->emp_notes; $hwb_tracker->nps_notes = $request->nps_notes; $hwb_tracker->ips_notes = $request->ips_notes; $hwb_tracker->smk_notes = $request->smk_notes; $hwb_tracker->sh_notes = $request->sh_notes; $hwb_tracker->ph_notes = $request->ph_notes; $hwb_tracker->mh_notes = $request->mh_notes; $hwb_tracker->dau_notes = $request->dau_notes; $hwb_tracker->save(); return $hwb_tracker; } /** * Update the specified resource in storage. * * @param \Illuminate\Http\Request $request * @param int $id * @return \Illuminate\Http\Response */ public function update(Request $request) { if (!$request->ajax()) return redirect('/'); $hwb_tracker = HwbTracker::findOrFail($request->id); $hwb_tracker->client_id = $request->client_id; $hwb_tracker->description = $request->description; $hwb_tracker->date_track = $request->date_track; $hwb_tracker->sn_value = $request->sn_value; $hwb_tracker->pcls_value = $request->pcls_value; $hwb_tracker->emp_value = $request->emp_value; $hwb_tracker->nps_value = $request->nps_value; $hwb_tracker->ips_value = $request->ips_value; $hwb_tracker->smk_value = $request->smk_value; $hwb_tracker->sh_value = $request->sh_value; $hwb_tracker->ph_value = $request->ph_value; $hwb_tracker->mh_value = $request->mh_value; $hwb_tracker->dau_value = $request->dau_value; $hwb_tracker->sn_notes = $request->sn_notes; $hwb_tracker->pcls_notes = $request->pcls_notes; $hwb_tracker->emp_notes = $request->emp_notes; $hwb_tracker->nps_notes = $request->nps_notes; $hwb_tracker->ips_notes = $request->ips_notes; $hwb_tracker->smk_notes = $request->smk_notes; $hwb_tracker->sh_notes = $request->sh_notes; $hwb_tracker->ph_notes = $request->ph_notes; $hwb_tracker->mh_notes = $request->mh_notes; $hwb_tracker->dau_notes = $request->dau_notes; $hwb_tracker->save(); } /** * Remove the specified resource from storage. * * @param int $id * @return \Illuminate\Http\Response */ public function destroy($id) { // if (!$request->ajax()) return redirect('/'); $hwb_tracker = HwbTracker::findOrFail($id); $hwb_tracker -> delete(); } public function delete(Request $request) { try { $hwb_tracker = HwbTracker::findOrFail($request->id); $hwb_tracker -> delete(); return response()->json('Cuestionario borrado'); } catch (Exception $e) { return response()->json($e->getMessage(), 500); } } } <file_sep><?php namespace App; use Illuminate\Database\Eloquent\Model; class Mbrp_parameter extends Model { // protected $table = 'mbrp_parameters'; protected $primaryKey = 'id'; protected $fillable = ['name','code','description','score','active','field','order','param_type','bottom_value','top_value','opt_prison', 'opt_community']; } <file_sep><?php use Illuminate\Support\Facades\Schema; use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class CreateHwbTrackersTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('hwb_trackers', function (Blueprint $table) { $table->increments('id'); $table->integer('client_id')->unsigned(); $table->text('description')->nullable(); $table->dateTime('date_track'); $table->unsignedTinyInteger('sn_value')->default(0); $table->unsignedTinyInteger('pcls_value')->default(0); $table->unsignedTinyInteger('emp_value')->default(0); $table->unsignedTinyInteger('nps_value')->default(0); $table->unsignedTinyInteger('ips_value')->default(0); $table->unsignedTinyInteger('smk_value')->default(0); $table->unsignedTinyInteger('sh_value')->default(0); $table->unsignedTinyInteger('ph_value')->default(0); $table->unsignedTinyInteger('mh_value')->default(0); $table->unsignedTinyInteger('dau_value')->default(0); $table->text('sn_notes')->nullable(); $table->text('pcls_notes')->nullable(); $table->text('emp_notes')->nullable(); $table->text('nps_notes')->nullable(); $table->text('ips_notes')->nullable(); $table->text('smk_notes')->nullable(); $table->text('sh_notes')->nullable(); $table->text('ph_notes')->nullable(); $table->text('mh_notes')->nullable(); $table->text('dau_notes')->nullable(); $table->timestamps(); $table->foreign('client_id')->references('id')->on('clients'); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::dropIfExists('hwb_trackers'); } } <file_sep><?php namespace App; use Illuminate\Database\Eloquent\Model; class UricaTest extends Model { // protected $fillable = [ 'urica_highest', 'pr_score', 'con_score', 'ac_score','ma_score', 'urica1','urica2','urica3','urica4','urica5','urica6','urica7', 'urica8','urica9','urica10','urica11','urica12','urica13','urica14', 'urica15','urica16','urica17','urica18','urica19','urica20','urica21', 'urica22','urica23','urica24','urica25','urica26','urica27','urica28', 'urica29','urica30','urica31','urica32' ]; } <file_sep><?php namespace App\Http\Controllers; use Illuminate\Http\Request; use Illuminate\Support\Facades\DB; use App\Mbrp_questionnaire; use App\BrsTest; use App\UricaTest; use App\DatcTest; use App\SpsiTest; use App\MhTest; class Mbrp_questionnaireController extends Controller { /** * Display a listing of the resource. * * @return \Illuminate\Http\Response */ public function index(Request $request) { if (!$request->ajax()) return redirect('/'); $buscar = $request->buscar; $criterio = $request->criterio; if ($buscar==''){ $mbrp_questionnaire = Mbrp_questionnaire::with('client','mbrp_programme','brsTest','uricaTest')->orderBy('id', 'desc')->paginate(5); } else{ $mbrp_questionnaire = Mbrp_questionnaire::with('client','mbrp_programme','brsTest','uricaTest')->where($criterio, 'like', '%'. $buscar . '%')->orderBy('id', 'desc')->paginate(5); /* $mbrp_questionnaire = Mbrp_questionnaire::with('client','mbrp_programme') ->join('mbrp_programmes','mbrp_questionnaires.mbrp_programme_id','=','mbrp_programmes.id') ->where($criterio, 'like', '%'. $buscar . '%')->orderBy('mbrp_questionnaires.id', 'desc')->paginate(5); */ } return [ 'pagination' => [ 'total' => $mbrp_questionnaire->total(), 'current_page' => $mbrp_questionnaire->currentPage(), 'per_page' => $mbrp_questionnaire->perPage(), 'last_page' => $mbrp_questionnaire->lastPage(), 'from' => $mbrp_questionnaire->firstItem(), 'to' => $mbrp_questionnaire->lastItem(), ], 'mbrp_questionnaire' => $mbrp_questionnaire ]; } public function getQuestionnaire(Request $request) { if (!$request->ajax()) return redirect('/'); $mbrp_questionnaire = Mbrp_questionnaire::findOrFail($request->id); return $mbrp_questionnaire; } /** * Store a newly created resource in storage. * * @param \Illuminate\Http\Request $request * @return \Illuminate\Http\Response */ public function store(Request $request) { if (!$request->ajax()) return redirect('/'); $mbrp_questionnaire = new Mbrp_questionnaire(); $mbrp_questionnaire->client_id = $request->client_id; $mbrp_questionnaire->client_age = $request->client_age; $mbrp_questionnaire->stage = $request->stage; $mbrp_questionnaire->mbrp_programme_id = $request->mbrp_programme_id; $mbrp_questionnaire->date_engaged = $request->date_engaged; $mbrp_questionnaire->date_completed = $request->date_completed; $mbrp_questionnaire->is_completed = $request->is_completed; $mbrp_questionnaire->end_reason = $request->end_reason; $mbrp_questionnaire->brs_q = $request->brs_q; $mbrp_questionnaire->urica_q = $request->urica_q; $mbrp_questionnaire->datc_q = $request->datc_q; $mbrp_questionnaire->spsi_q = $request->spsi_q; $mbrp_questionnaire->mh_q = $request->mh_q; $mbrp_questionnaire->pf_q = $request->pf_q; $mbrp_questionnaire->pf1 = 0; $mbrp_questionnaire->pf2 = 0; $mbrp_questionnaire->pf3 = 0; $mbrp_questionnaire->pf4 = 0; $mbrp_questionnaire->pf5 = 0; $mbrp_questionnaire->pf6 = 0; $mbrp_questionnaire->pf7 = 0; $mbrp_questionnaire->pf8 = 0; $mbrp_questionnaire->pf9 = 0; $mbrp_questionnaire->pf10 = 0; $mbrp_questionnaire->pf11 = 0; $mbrp_questionnaire->pf_comments = ''; $brs_test = new BrsTest(); $brs_test->save(); $mbrp_questionnaire->brs_test_id=$brs_test->id; $urica_test = new UricaTest(); $urica_test->save(); $mbrp_questionnaire->urica_test_id=$urica_test->id; $mbrp_questionnaire->save(); return $mbrp_questionnaire; } /** * Update the specified resource in storage. * * @param \Illuminate\Http\Request $request * @param int $id * @return \Illuminate\Http\Response */ public function update(Request $request) { if (!$request->ajax()) return redirect('/'); $mbrp_questionnaire = Mbrp_questionnaire::findOrFail($request->id); $mbrp_questionnaire->client_id = $request->client_id; $mbrp_questionnaire->client_age = $request->client_age; $mbrp_questionnaire->stage = $request->stage; $mbrp_questionnaire->mbrp_programme_id = $request->mbrp_programme_id; $mbrp_questionnaire->date_engaged = $request->date_engaged; $mbrp_questionnaire->date_completed = $request->date_completed; $mbrp_questionnaire->is_completed = $request->is_completed; $mbrp_questionnaire->end_reason = $request->end_reason; $mbrp_questionnaire->brs_q = $request->brs_q; $mbrp_questionnaire->urica_q = $request->urica_q; $mbrp_questionnaire->datc_q = $request->datc_q; $mbrp_questionnaire->spsi_q = $request->spsi_q; $mbrp_questionnaire->mh_q = $request->mh_q; $mbrp_questionnaire->pf_q = $request->pf_q; $mbrp_questionnaire->save(); } public function registerBrs(Request $request) { if (!$request->ajax()) return redirect('/'); $brs_test = new BrsTest(); $brs_test->brs1 = $request->brs1; $brs_test->brs2 = $request->brs2; $brs_test->brs3 = $request->brs3; $brs_test->brs4 = $request->brs4; $brs_test->brs5 = $request->brs5; $brs_test->brs6 = $request->brs6; $brs_test->brs_score = $request->brs_score; $brs_test->save(); $mbrp_questionnaire = Mbrp_questionnaire::findOrFail($request->id); $mbrp_questionnaire->brs_test_id=$brs_test->id; $mbrp_questionnaire->save(); return $brs_test; } public function updateBrs(Request $request) { if (!$request->ajax()) return redirect('/'); $brs_test = BrsTest::findOrFail($request->id); $brs_test->brs1 = $request->brs1; $brs_test->brs2 = $request->brs2; $brs_test->brs3 = $request->brs3; $brs_test->brs4 = $request->brs4; $brs_test->brs5 = $request->brs5; $brs_test->brs6 = $request->brs6; $brs_test->brs_score = $request->brs_score; $brs_test->save(); } public function updateUrica(Request $request) { if (!$request->ajax()) return redirect('/'); $urica_test = UricaTest::findOrFail($request->id); $urica_test->urica1 = $request->urica1; $urica_test->urica2 = $request->urica2; $urica_test->urica3 = $request->urica3; $urica_test->urica4 = $request->urica4; $urica_test->urica5 = $request->urica5; $urica_test->urica6 = $request->urica6; $urica_test->urica7 = $request->urica7; $urica_test->urica8 = $request->urica8; $urica_test->urica9 = $request->urica9; $urica_test->urica10 = $request->urica10; $urica_test->urica11 = $request->urica11; $urica_test->urica12 = $request->urica12; $urica_test->urica13 = $request->urica13; $urica_test->urica14 = $request->urica14; $urica_test->urica15 = $request->urica15; $urica_test->urica16 = $request->urica16; $urica_test->urica17 = $request->urica17; $urica_test->urica18 = $request->urica18; $urica_test->urica19 = $request->urica19; $urica_test->urica20 = $request->urica20; $urica_test->urica21 = $request->urica21; $urica_test->urica22 = $request->urica22; $urica_test->urica23 = $request->urica23; $urica_test->urica24 = $request->urica24; $urica_test->urica25 = $request->urica25; $urica_test->urica26 = $request->urica26; $urica_test->urica27 = $request->urica27; $urica_test->urica28 = $request->urica28; $urica_test->urica29 = $request->urica29; $urica_test->urica30 = $request->urica30; $urica_test->urica31 = $request->urica31; $urica_test->urica32 = $request->urica32; $urica_test->urica_highest = $request->urica_highest; $urica_test->pr_score = $request->pr_score; $urica_test->con_score = $request->con_score; $urica_test->ac_score = $request->ac_score; $urica_test->ma_score = $request->ma_score; $urica_test->save(); } /** * Remove the specified resource from storage. * * @param int $id * @return \Illuminate\Http\Response */ public function destroy($id) { // if (!$request->ajax()) return redirect('/'); $mbrp_questionnaire = Mbrp_questionnaire::findOrFail($id); $mbrp_questionnaire -> delete(); } public function delete(Request $request) { try { $mbrp_questionnaire = Mbrp_questionnaire::findOrFail($request->id); $mbrp_questionnaire -> delete(); return response()->json('Cuestionario borrado'); } catch (Exception $e) { return response()->json($e->getMessage(), 500); } } } <file_sep><?php namespace App\Http\Controllers; use Illuminate\Http\Request; use Illuminate\Support\Facades\DB; use App\User; use App\Person; class UserController extends Controller { public function index(Request $request) { //if (!$request->ajax()) return redirect('/'); $buscar = $request->buscar; $criterio = $request->criterio; if ($buscar==''){ $persons = User::join('persons','users.id','=','persons.id') ->join('roles','users.idrol','=','roles.id') ->select('persons.id','persons.first_name','persons.last_name','persons.address','persons.phone','persons.email','users.usuario','users.password','users.condicion','users.idrol','roles.nombre as rol') ->orderBy('persons.id', 'desc')->paginate(5); } else{ $persons = User::join('persons','users.id','=','persons.id') ->join('roles','users.idrol','=','roles.id') ->select('persons.id','persons.first_name','persons.last_name','persons.address','persons.phone','persons.email','users.usuario','users.password','users.condicion','users.idrol','roles.nombre as rol') ->where('persons.'.$criterio, 'like', '%'. $buscar . '%')->orderBy('id', 'desc')->paginate(5); } return [ 'pagination' => [ 'total' => $persons->total(), 'current_page' => $persons->currentPage(), 'per_page' => $persons->perPage(), 'last_page' => $persons->lastPage(), 'from' => $persons->firstItem(), 'to' => $persons->lastItem(), ], 'persons' => $persons ]; } public function store(Request $request) { if (!$request->ajax()) return redirect('/'); try{ DB::beginTransaction(); $person = new Person(); $person->first_name = $request->first_name; $person->last_name = $request->last_name; $person->address = $request->address; $person->phone = $request->phone; $person->email = $request->email; $person->save(); $user = new User(); $user->id = $person->id; $user->idrol = $request->idrol; $user->usuario = $request->usuario; $user->password = <PASSWORD>( $request->password); $user->condicion = '1'; $user->save(); DB::commit(); } catch (Exception $e){ DB::rollBack(); } } public function update(Request $request) { if (!$request->ajax()) return redirect('/'); try{ DB::beginTransaction(); $user = User::findOrFail($request->id); $person = Person::findOrFail($user->id); $person->first_name = $request->first_name; $person->last_name = $request->last_name; $person->address = $request->address; $person->phone = $request->phone; $person->email = $request->email; $person->save(); $user->usuario = $request->usuario; $user->password = <PASSWORD>( $request->password); $user->condicion = '1'; $user->idrol = $request->idrol; $user->save(); DB::commit(); } catch (Exception $e){ DB::rollBack(); } } public function desactivar(Request $request) { if (!$request->ajax()) return redirect('/'); $user = User::findOrFail($request->id); $user->condicion = '0'; $user->save(); } public function activar(Request $request) { if (!$request->ajax()) return redirect('/'); $user = User::findOrFail($request->id); $user->condicion = '1'; $user->save(); } } <file_sep><?php use Illuminate\Support\Facades\Schema; use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class CreateDatcTestsTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('datc_tests', function (Blueprint $table) { $table->increments('id'); $table->smallInteger('dtc_score')->default(0); $table->unsignedTinyInteger('dtc1')->default(0); $table->unsignedTinyInteger('dtc2')->default(0); $table->unsignedTinyInteger('dtc3')->default(0); $table->unsignedTinyInteger('dtc4')->default(0); $table->unsignedTinyInteger('dtc5')->default(0); $table->unsignedTinyInteger('dtc6')->default(0); $table->unsignedTinyInteger('dtc7')->default(0); $table->unsignedTinyInteger('dtc8')->default(0); $table->smallInteger('atc_score')->default(0); $table->unsignedTinyInteger('atc1')->default(0); $table->unsignedTinyInteger('atc2')->default(0); $table->unsignedTinyInteger('atc3')->default(0); $table->unsignedTinyInteger('atc4')->default(0); $table->unsignedTinyInteger('atc5')->default(0); $table->unsignedTinyInteger('atc6')->default(0); $table->unsignedTinyInteger('atc7')->default(0); $table->unsignedTinyInteger('atc8')->default(0); $table->timestamps(); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::dropIfExists('datc_tests'); } } <file_sep><?php namespace App; use Illuminate\Database\Eloquent\Model; class MhTest extends Model { // } <file_sep><?php namespace App; use Illuminate\Database\Eloquent\Model; class SpsiTest extends Model { // } <file_sep><?php namespace App\Http\Controllers; use Illuminate\Http\Request; use Illuminate\Support\Facades\DB; use App\Client; use App\Person; class ClientController extends Controller { public function index(Request $request) { if (!$request->ajax()) return redirect('/'); $buscar = $request->buscar; $criterio = $request->criterio; if ($buscar==''){ $persons = Client::join('persons','clients.id','=','persons.id') ->select('persons.id','clients.reference', 'clients.initials', 'persons.first_name', 'persons.last_name', 'persons.id_document','persons.address','persons.phone', 'persons.email','clients.dob','clients.contact','clients.contact_phone') ->orderBy('persons.id', 'desc')->paginate(10); } else{ $persons = Client::join('persons','clients.id','=','persons.id') ->select('persons.id','clients.reference', 'clients.initials', 'persons.first_name', 'persons.last_name', 'persons.id_document','persons.address','persons.phone', 'persons.email','clients.dob','clients.contact','clients.contact_phone') ->where('persons.'.$criterio, 'like', '%'. $buscar . '%') ->orderBy('persons.id', 'desc')->paginate(10); } return [ 'pagination' => [ 'total' => $persons->total(), 'current_page' => $persons->currentPage(), 'per_page' => $persons->perPage(), 'last_page' => $persons->lastPage(), 'from' => $persons->firstItem(), 'to' => $persons->lastItem(), ], 'persons' => $persons ]; } public function selectClient(Request $request){ if (!$request->ajax()) return redirect('/'); $filtro = $request->filtro; $clients = Client::join('persons','clients.id','=','persons.id') ->where('clients.reference', 'like', '%'. $filtro . '%') ->orWhere('persons.id_document', 'like', '%'. $filtro . '%') ->orWhere('persons.last_name', 'like', '%'. $filtro . '%') ->orWhere('clients.initials', 'like', '%'. $filtro . '%') ->select('clients.id','clients.reference','clients.initials', 'clients.dob') ->orderBy('clients.reference', 'asc')->get(); return ['clients' => $clients]; } public function store(Request $request) { if (!$request->ajax()) return redirect('/'); try{ DB::beginTransaction(); $person = new Person(); $person->first_name = $request->first_name; $person->last_name = $request->last_name; $person->id_document = $request->id_document; $person->address = $request->address; $person->phone = $request->phone; $person->email = $request->email; $person->save(); $client = new Client(); $client->reference = $request->reference; $client->initials = $request->initials; $client->dob = $request->dob; $client->contact = $request->contact; $client->contact_phone = $request->contact_phone; $client->id = $person->id; $client->save(); DB::commit(); } catch (Exception $e){ DB::rollBack(); } } public function update(Request $request) { if (!$request->ajax()) return redirect('/'); try{ DB::beginTransaction(); $client = Client::findOrFail($request->id); $person = Person::findOrFail($client->id); $person->first_name = $request->first_name; $person->last_name = $request->last_name; $person->id_document = $request->id_document; $person->address = $request->address; $person->phone = $request->phone; $person->email = $request->email; $person->save(); $client->reference = $request->reference; $client->initials = $request->initials; $client->dob = $request->dob; $client->contact = $request->contact; $client->contact_phone = $request->contact_phone; $client->save(); DB::commit(); } catch (Exception $e){ DB::rollBack(); } } } <file_sep><?php namespace App; use Illuminate\Database\Eloquent\Model; class HwbTracker extends Model { protected $fillable = [ 'client_id', 'description', 'date_track', 'sn_value', 'pcls_value','emp_value','nps_value','ips_value', 'smk_value','sh_value','ph_value','mh_value','dau_value', 'sn_notes', 'pcls_notes','emp_notes','nps_notes','ips_notes', 'smk_notes','sh_notes','ph_notes','mh_notes','dau_notes', ]; public function client(){ return $this->belongsTo('App\Client'); } // } <file_sep><?php use Illuminate\Support\Facades\Schema; use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class CreateBrsTestsTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('brs_tests', function (Blueprint $table) { $table->increments('id'); $table->unsignedTinyInteger('brs1')->default(0); $table->unsignedTinyInteger('brs2')->default(0); $table->unsignedTinyInteger('brs3')->default(0); $table->unsignedTinyInteger('brs4')->default(0); $table->unsignedTinyInteger('brs5')->default(0); $table->unsignedTinyInteger('brs6')->default(0); $table->smallInteger('brs_score')->default(0); $table->timestamps(); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::dropIfExists('brs_tests'); } } <file_sep><?php namespace App; use Illuminate\Database\Eloquent\Model; class BrsTest extends Model { // protected $fillable = [ 'brs1', 'brs2', 'brs3', 'brs4','brs5','brs6','brs_score' ]; }
9b6cfcc175046ad1f858d6b2da7fff3aae7b2d88
[ "JavaScript", "PHP" ]
26
JavaScript
jladan78/forward
d2af2ee8794b205cbeb38d8123a4649cde4f8d69
7280221864b32cbc47eded78134345bd8afa81c7
refs/heads/master
<repo_name>NozaM8/G11<file_sep>/src/java/smallGroup/P1_SumOfDoubleFromStr.java package java.smallGroup; import java.text.DecimalFormat; public class P1_SumOfDoubleFromStr { public static void main(String[] args) { String str = "aaa1.1bbb2.2ccc4.4fff1.5"; // 9.20 String temp = ""; // 12.4 double sum = 0; for (int i=0; i<str.length(); i++){ if (Character.isDigit(str.charAt(i))){ temp += str.charAt(i); } if (str.charAt(i)=='.'){ temp += str.charAt(i); } if (Character.isDigit(str.charAt(i))) { if (!temp.equals("")){ sum += Double.parseDouble(temp); temp = ""; } } } DecimalFormat df = new DecimalFormat("0.00"); System.out.println(df.format(sum)); } }
992212c75d44c039879bb1f2b7b2196c9cd87624
[ "Java" ]
1
Java
NozaM8/G11
e216264eb6e7dd1f9186685da471d53092c4d6f2
f41997d8c58c51e6eefbc375831314c31768e76f
refs/heads/master
<repo_name>nikolasx/mynpm<file_sep>/src/index.js /** * Created by lixiong on 2018/3/27 0027. */ <file_sep>/README.md # mynpm 常用前端方法
4bf60d7629e4b5244646224b12a702471821fd08
[ "JavaScript", "Markdown" ]
2
JavaScript
nikolasx/mynpm
fb238e93ee1646dac32342e26209ae5e7b7a5328
aac9659f17e9d7780cc1f2c27a29d29096594ece
refs/heads/master
<repo_name>gray-industries/projecter<file_sep>/projector.gemspec require File.expand_path('../lib/version', __FILE__) Gem::Specification.new do |gem| gem.authors = ['<NAME>'] gem.email = ['<EMAIL>'] gem.description = 'Projecter - Stub Ruby projects' gem.summary = <<-EOF Projecter allows for easily stubbing Ruby projects from simply RubyGems to larger Thor applications. It is based largely off of the work of Jesse Kempf at Opower. EOF gem.files = `git ls-files`.split($OUTPUT_RECORD_SEPARATOR) gem.executables = gem.files.grep(/^bin\//).map { |f| File.basename(f) } gem.test_files = gem.files.grep(/^(test|spec|features)\//) gem.name = 'projecter' gem.require_paths = ['lib'] gem.version = Projecter::VERSION # dependencies... gem.add_dependency('thor', '0.19.1') gem.add_dependency('sysexits', '1.0.2') gem.add_dependency('awesome_print', '~> 1.1.0') gem.add_dependency('abstract_type', '~> 0.0.7') gem.add_dependency('multi_json', '~> 1.10.1') # development dependencies. gem.add_development_dependency('rspec', '~> 3.2') gem.add_development_dependency('simplecov', '~> 0.9') gem.add_development_dependency('guard', '~> 2.12') gem.add_development_dependency('guard-rspec', '~> 4.5') gem.add_development_dependency('rubocop', '~> 0.29') gem.add_development_dependency('guard-rubocop', '~> 1.2') gem.add_development_dependency('rainbow', '2.0') gem.add_development_dependency('metric_fu', '~> 4.11') gem.add_development_dependency('rake', '~> 10.3') gem.add_development_dependency('yard', '~> 0.8.7') gem.add_development_dependency('redcarpet', '~> 3.2') gem.add_development_dependency('pry-nav') end <file_sep>/spec/resources.rb def resource(filename) File.expand_path("../resources/#{filename}", __FILE__) end module Loginator module Test module Resources end end end <file_sep>/templates/mainapp.tt #!/usr/bin/env ruby require 'thor' # Set up the load path so we can load things from our own lib $LOAD_PATH << File.expand_path('../../lib', __FILE__) require '<%= config[:project] %>' # Skeleton CLI class class <%= config[:classname] %>CLI < Thor check_unknown_options! end # # Load all commands # <%= config[:classname] %>.before_command_load cmd_root = '../../lib/commands/*' Dir[File.expand_path(cmd_root, __FILE__)].each do |cmd| require cmd end <%= config[:classname] %>.after_command_load # Janky way of avoiding starting the CLI if we're running under rspec. <%= config[:classname] %>CLI.start unless $PROGRAM_NAME =~ /rspec/ <file_sep>/lib/commands/create.rb require 'thor' require 'find' class ProjecterCLI < Thor # The create command is responsible for driving project creation. # XXX: This should be simpler. Eventually refactor once we have # composable projects, different project types besides lib/thorapp. include Thor::Actions add_runtime_options! source_root(File.expand_path('../../..', __FILE__)) desc 'create PROJECT', 'Create a new Thor CLI skeleton in ./PROJECT' method_options uses_templates: false, uses_files: false, library: false # rubocop:disable Metrics/AbcSize def create(project) @project = project run("git init #{@project}", capture: true) unless File.exist?(File.join(@project, '.git')) create_project_dirs projecter_file( 'Gemfile' => 'Gemfile', 'Guardfile' => 'Guardfile', 'Rakefile' => 'Rakefile', 'dot-gitignore' => '.gitignore', 'dot-metrics' => '.metrics', 'dot-rspec' => '.rspec', 'dot-rubocop.yml' => '.rubocop.yml' ) lib_templates = { 'gemspec.tt' => "#{project}.gemspec", 'README.md.tt' => 'README.md', 'LICENSE.md.tt' => 'LICENSE.md', 'mainlib.rb.tt' => ['lib', "#{project}.rb"], 'version.rb.tt' => ['lib', project, 'version.rb'], 'spec_helper.rb.tt' => %w(spec spec_helper.rb), 'spec_fixtures.rb.tt' => %w(spec fixtures.rb), 'spec_resources.rb.tt' => %w(spec resources.rb) } app_templates = { 'mainapp.tt' => ['bin', project], 'version-cmd.rb.tt' => %w(lib commands version.rb) } templates = lib_templates templates.merge!(app_templates) unless options.library? projecter_template( templates, project: project, classname: project .split(/[_-]/) .map(&:capitalize) .join, library_only: options.library? ) inside(@project) do # XXX: KLUDGE: Add an empty .gitignore file in each empty directory # XXX: KLUDGE: so that git can track the dir. Find.find('.') do |path| next if path.start_with?('./.git/') next unless FileTest.directory?(path) next unless Dir.entries(path) == %w(. ..) create_file File.join(path, '.gitignore'), '' end run('git add .gitignore', capture: true) run('git add .', capture: true) run("git commit --allow-empty -m 'Created #{@project} using Projecter #{Projecter::VERSION}.'", capture: true) end end # rubocop:enable Metrics/AbcSize private def projecter_file(mapping) mapping.each do |src, dst| copy_file(File.join('files', src), File.join(@project, dst)) end end def projecter_template(mapping, bindings) mapping.each do |src, dst| dst = [dst] unless dst.is_a?(Array) srcname = File.join('templates', src) dstname = File.join(*[@project, dst].flatten) template(srcname, dstname, bindings) if dst.include?('bin') chmod(dstname, 0755) unless (File.stat(dstname).mode & 0755) == 0755 end end end # rubocop:disable Metrics/AbcSize def create_project_dirs source_dirs = ['lib', "lib/#{@project}"] %w(bin lib/commands).map { |d| source_dirs << d } unless options.library? test_resource_dirs = %w(fixtures resources) test_kinds = %w(unit integration acceptance) test_dirs = (test_resource_dirs + test_kinds.product(source_dirs)).map { |path| ['spec', path].join('/') } project_dirs = source_dirs + test_dirs project_dirs << 'templates' if options.uses_templates? project_dirs << 'files' if options.uses_files? project_dirs.each do |dir| empty_directory File.join(@project, dir) end end # rubocop:enable Metrics/AbcSize def library? @library ||= options.library? end end <file_sep>/lib/commands/version.rb class ProjecterCLI < Thor desc 'version', 'show projecter version' def version puts "projecter #{Projecter::VERSION}" end end <file_sep>/spec/lib/commands/create_spec.rb require 'commands/create' shared_examples_for 'a project' do let(:project) { 'test_project' } after do subject.create(project) end it 'creates project lib dir' do expect(subject).to receive(:empty_directory).with(File.join(project, 'lib', project)) end %w(unit integration acceptance).each do |dir| it "creates spec/#{dir}/lib/project" do expect(subject).to receive(:empty_directory).with(File.join(project, 'spec', dir, 'lib', project)) end end end RSpec.describe ProjecterCLI do describe '#create_project_dirs' do let(:project) { 'test_project' } let(:options) do { library: library } end subject do described_class.class_options( quiet: true, pretend: true ) described_class.new([], library: library) end before do allow(subject).to receive(:empty_directory).and_return(true) end after do subject.create(project) end context 'when in library mode' do let(:library) { true } it_behaves_like 'a project' it 'does not create lib/commands' do expect(subject).not_to receive(:empty_directory).with(File.join(project, 'lib/commands')) subject.create(project) end it 'does not create a main app' do expect(subject).not_to receive(:chmod).with(File.join(project, 'bin', project), 0755) subject.create(project) end end context 'when not in library mode' do let(:library) { false } let(:main_app) { File.join(project, 'bin', project) } it_behaves_like 'a project' before do allow(File).to receive(:stat).with(main_app) { double('dirent', mode: 0644) } allow(subject).to receive(:chmod).with(main_app, 0755).and_return(true) end it 'makes the main app executable' do expect(File).to receive(:stat).with(main_app) { double('dirent', mode: 0644) } expect(subject).to receive(:chmod).with(main_app, 0755).and_return(true) end %w(unit integration acceptance).each do |dir| it "creates spec/#{dir}/lib/commands" do expect(subject).to receive(:empty_directory).with(File.join(project, 'spec', dir, 'lib/commands')) end end end end end <file_sep>/bin/projecter #!/usr/bin/env ruby require 'rubygems' require 'thor' # Set up the load path so we can load things from our own lib $LOAD_PATH << File.expand_path('../../lib', __FILE__) require 'projecter' # Skeleton CLI class class ProjecterCLI < Thor check_unknown_options! end # load all commands cmd_root = '../../lib/commands/*' Dir[File.expand_path(cmd_root, __FILE__)].each do |cmd| require cmd end ProjecterCLI.start unless $PROGRAM_NAME =~ /rspec/ <file_sep>/templates/gemspec.tt # -*- encoding: utf-8 -*- # vim: ft=ruby require File.expand_path('../lib/<%= config[:project] %>/version', __FILE__) Gem::Specification.new do |gem| gem.authors = ['<PASSWORD>'] gem.email = ['<PASSWORD>'] gem.licenses = ['MIT'] gem.description = 'I am an application stub' gem.summary = 'app stub' gem.files = `git ls-files`.split($OUTPUT_RECORD_SEPARATOR) gem.executables = gem.files.grep(/^bin\//).map { |f| File.basename(f) } gem.test_files = gem.files.grep(/^(test|spec|features)\//) gem.name = '<%= config[:project] %>' gem.require_paths = %w(lib) gem.version = <%= config[:classname] %>::VERSION # dependencies... gem.add_dependency('thor', '0.19.1') gem.add_dependency('sysexits', '1.0.2') gem.add_dependency('awesome_print', '~> 1.1.0') gem.add_dependency('abstract_type', '~> 0.0.7') gem.add_dependency('multi_json', '~> 1.10.1') # development dependencies. gem.add_development_dependency('rspec', '~> 3.2') gem.add_development_dependency('simplecov', '~> 0.9') gem.add_development_dependency('guard', '~> 2.12') gem.add_development_dependency('guard-rspec', '~> 4.5') gem.add_development_dependency('rubocop', '~> 0.29') gem.add_development_dependency('guard-rubocop', '~> 1.2') gem.add_development_dependency('rainbow', '2.0') gem.add_development_dependency('metric_fu', '~> 4.11') gem.add_development_dependency('rake', '~> 10.3') gem.add_development_dependency('yard', '~> 0.8.7') gem.add_development_dependency('redcarpet', '~> 3.2') gem.add_development_dependency('pry-nav') end <file_sep>/lib/projecter.rb require 'version' module Projecter end <file_sep>/spec/fixtures.rb def fixture(filename) File.expand_path("../fixtures/#{filename}", __FILE__) end module Loginator module Test module Fixtures end end end <file_sep>/README.md # Projecter [![Code Climate](https://codeclimate.com/github/gray-industries/projecter/badges/gpa.svg)](https://codeclimate.com/github/gray-industries/projecter) [![Build Status](https://travis-ci.org/gray-industries/projecter.svg?branch=master)](https://travis-ci.org/gray-industries/projecter) Projecter is a simple CLI application generator. ## Installation $ gem install projecter ## Usage Using projecter's quite a bit like running `bundle gem gemname`. It gives you a gem layout, plus a skeleton of a Thor CLI application. When you $ projecter create $PROJECT you get a new gem in $PROJECT, complete with its own fresh git repo. ### Directory Layout If you create an app called `myapp`, projecter creates the following directories: - `lib/commands/`: `myapp`'s subcommands. - `lib/myapp/`: `myapp`'s library. - `spec/fixtures`: test fixtures. - `spec/resources`: configs, other files needed to run tests. - `spec/unit/lib/{commands,myapp}/`: unit tests. - `spec/integration/lib/{commands,myapp}/`: integration tests. - `spec/acceptance/lib/{commands,myapp}/`: large scale system or subsystem tests; stress tests; performance tests; interface conformance tests for demonstrating the adherence of APIs, CLIs, etc. to established standards. Each leaf directory contains an empty `.gitignore` file. This is because git does not track directories, and without an empty file the directory would not appear in the repo. ## Contributing 1. Fork it 2. Create your feature branch (`git checkout -b my-new-feature`) 3. Commit your changes (`git commit -am 'Added some feature'`) 4. Push to the branch (`git push origin my-new-feature`) 5. Create new Pull Request
08cb34e46c3f6d82f9254fceb55c82aa3c877c4c
[ "Markdown", "Ruby" ]
11
Ruby
gray-industries/projecter
d51647889969a48a3996b6a16c104ba26e6118c0
37c8a28d8b2d8faae7340603e156e864eb16fcfb
refs/heads/master
<repo_name>Hellwz/Stack_Box<file_sep>/Assets/PlayerController.cs using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; using UnityEngine.SceneManagement; public class PlayerController : MonoBehaviour { public GameObject StartPanel; public GameObject OverPanel; bool playing; void Start() //S一定要大写 { playing=false; StartPanel.SetActive(true); OverPanel.SetActive(false); } public float Speed; public float Range; public GameObject boxPrefab; public Vector2 moveDir = Vector2.right; public float timer; public float interval=0.5f; public Text scoreText; public Text overScoreText; public int score = 0; public AudioClip drop; public AudioClip over; // Update is called once per frame void Update () { if (!playing) return; if(transform.position.x > Range) moveDir = Vector2.left; if(transform.position.x < -Range) moveDir = Vector2.right; Vector2 moveAmount = moveDir * Speed * Time.deltaTime; transform.Translate(moveAmount); timer += Time.deltaTime; //Box if(Input.GetKeyDown(KeyCode.Mouse0) && timer>interval) { SpawnBox(); timer = 0; StartCoroutine(Up()); } } void SpawnBox() { Instantiate(boxPrefab, transform.position + Vector3.down * 0.9f, boxPrefab.transform.rotation); StartCoroutine(FindObjectOfType<CameraFollow>().exView()); score++; scoreText.text = "SCORE : " + score; Speed += 0.5f; AudioSource.PlayClipAtPoint(drop,transform.position); } IEnumerator Up() { float tar = 1.5f, tmp = 0; while (tmp < tar) { tmp += Time.deltaTime * (1 / interval); transform.position += Vector3.up * Time.deltaTime; yield return null; } } public void gameStart() { playing=true; StartPanel.SetActive(false); scoreText.text = "SCORE : " + score; } public bool isOver = false; public void gameOver() { if (isOver == true) return; else isOver = true; playing=false; scoreText.text = ""; overScoreText.text = "SCORE : " + score; OverPanel.SetActive(true); FindObjectOfType<CameraFollow>().stopBGM(); AudioSource.PlayClipAtPoint(over,transform.position); } public void restart() { SceneManager.LoadScene(0); } } <file_sep>/Assets/CameraFollow.cs using System.Collections; using System.Collections.Generic; using UnityEngine; public class CameraFollow : MonoBehaviour { public Transform target; public float followSpeed; // Use this for initialization void Start () {} // Update is called once per frame void LateUpdate () { float tarPos = target.position.y; float nowPos = transform.position.y; Vector2 moveAmount = ((tarPos - nowPos) * Vector2.up).normalized * followSpeed * Time.deltaTime; if (Mathf.Abs(tarPos - nowPos) > 0.1f) { transform.Translate(moveAmount); } } public float exSize = 0.3f; public IEnumerator exView() { float tmp = 0; while (tmp < exSize) { tmp += Time.deltaTime / 2; Camera.main.orthographicSize += Time.deltaTime / 2; yield return null; } } public void stopBGM() { AudioSource AS = gameObject.GetComponent<AudioSource>(); AS.Stop(); } } <file_sep>/Assets/Box.cs using System.Collections; using System.Collections.Generic; using UnityEngine; public class Box : MonoBehaviour { public GameObject effectPrefab; bool effect; //只产生一次效果 void OnCollisionEnter2D(Collision2D col) { if (!effect) { effect = true; GameObject hit = Instantiate(effectPrefab, transform.position, effectPrefab.transform.rotation); Destroy(hit, 2f); } if (col.gameObject.CompareTag("Ground")) FindObjectOfType<PlayerController>().gameOver(); } } <file_sep>/README.md # Stack_Box A PC Game of Stacking Boxes Made with Unity
36a8d348e7a189e34a923a651328a025d26cc50d
[ "Markdown", "C#" ]
4
C#
Hellwz/Stack_Box
52bccbfe1d02eb1bb57bec2bbb5f38e4b56a9e17
0bc11d95258d142f5b1bc8b2d79806d2080ac869
refs/heads/master
<repo_name>shvetsi/MonitoringAssistant<file_sep>/ClientApp/app/components/reports/reports.module.ts import { NgModule } from "@angular/core"; import { CommonModule } from "@angular/common"; import { FormsModule, ReactiveFormsModule } from "@angular/forms"; import { Report } from "../../shared/models/report"; import { ReportsHistoryComponent } from "./reportsHistory/reports-history.component"; import { ReportComponent } from "./report/report.component"; import { ReportsRoutingModule } from "./reports-routing.module"; import { SharedResourcesModule } from "../sharedComponents/shared.resources.module"; @NgModule({ imports:[ CommonModule, FormsModule, ReactiveFormsModule, ReportsRoutingModule, SharedResourcesModule ], declarations:[ ReportsHistoryComponent, ReportComponent ] }) export class ReportsModule{}<file_sep>/ClientApp/app/shared/dto/incidentDto.ts import { EnvironmentInfoDto } from "./environmentInfoDto"; import { Incident } from "../models/incident"; export class IncidentDto { id: string = ""; environment: EnvironmentInfoDto = new EnvironmentInfoDto(); description = ""; actions: string[] = []; attachments: string[] = []; static mapToDto(incident: Incident) { return { id: incident.id, environment: EnvironmentInfoDto.mapToDto(incident.environment), description: incident.description, actions: incident.actions, attachments: [] } } static mapFromDto(incident: IncidentDto): Incident { return { id: incident.id, environment: EnvironmentInfoDto.mapFromDto(incident.environment), description: incident.description, actions: incident.actions, attachments: [] } } }<file_sep>/ClientApp/app/shared/models/report.ts import { Incident } from "./incident"; export class Report { id = "" user = "" date: Date = new Date(); incidents: Incident[] = [] }<file_sep>/ClientApp/app/components/reports/report/report.component.ts import { Component, EventEmitter } from "@angular/core" import { Router, ActivatedRoute } from "@angular/router"; import { Incident } from "../../../shared/models/incident"; import { Report } from "../../../shared/models/report"; import { EnvironmentInfo } from "../../../shared/models/environmentInfo"; import { ReportsService } from "../../../shared/services/reports.service"; @Component({ selector: "new-report", templateUrl: "report.component.html", styleUrls: ["report.component.css"] }) export class ReportComponent { editMode = false; report: Report = new Report(); constructor(private router: Router, private activeRoute: ActivatedRoute, private reportsService: ReportsService) { } ngOnInit() { if(this.activeRoute.params != undefined) this.activeRoute.params.subscribe(p => { if(p["id"]){ this.reportsService.getReport(p["id"]).subscribe( result => { this.report = result; }, error => {} ) } }); } addIncident(){ let inc = new Incident() this.report.incidents.unshift(inc) this.saveReport() } updateFiles(inc: Incident, $event: any){ console.log("onChanged") this.reportsService.uploadFile(this.report.id, inc.id, $event) .subscribe((data: any) => { console.log(data) inc.attachments.push(data) console.log(inc.attachments) }) } deleteIncident(incident: Incident){ console.log("deleteIncident"); console.log(incident); let i = this.report.incidents.indexOf(incident); if( i > -1) this.report.incidents.splice(i, 1); } saveReport(){ this.reportsService.saveReport(this.report); } }<file_sep>/Infrastructure/MongoStorage.cs using System.Collections.Generic; using MongoDB.Driver; using MonitoringAssistant.Models; namespace MonitoringAssistant.Infrastructure { public class MongoStorage: IStorage { IMongoDatabase _mongoDB; IMongoCollection<Incident> _incidents; IMongoCollection<Report> _reports; public MongoStorage(IMongoDatabase mongoDB) { _mongoDB = mongoDB; _incidents = _mongoDB.GetCollection<Incident>("Incidents"); _reports = _mongoDB.GetCollection<Report>("Reports"); } public IEnumerable<Incident> GetIncidents() { return _incidents.Find(incident => true).ToList(); } public IEnumerable<Report> GetReports() { return _reports.Find(report => true).ToList(); } public Report GetReport(string id) { return _reports.Find(report => report.Id == id).FirstOrDefault(); } //TODO: remove CountDocuments public string UpdateReport(Report report) { if(!string.IsNullOrEmpty(report.Id)) { _reports.ReplaceOne(r => r.Id == report.Id, report); return report.Id; } report.Id = _reports.CountDocuments(f => true).ToString(); _reports.InsertOne(report); return report.Id; } } }<file_sep>/ClientApp/app/shared/services/reports.service.ts import { Injectable } from '@angular/core'; import { Http, Response, RequestOptions, ResponseContentType } from '@angular/http'; import 'rxjs/add/operator/map'; import { Report } from '../../shared/models/report'; import { Observable } from 'rxjs/Observable'; import { forEach } from "@angular/router/src/utils/collection"; import { Incident } from '../../shared/models/incident'; import { EnvironmentInfo } from '../../shared/models/environmentInfo'; import { ReportDto } from '../dto/reportDto'; import { IncidentDto } from '../dto/incidentDto'; @Injectable() export class ReportsService { private readonly reportsEndpoint = "/api/reports" private readonly filesEndpoint = "/api/files" constructor(private http: Http) { } getReports(){ return this.http.get(this.reportsEndpoint) .map(res => this.extractReports(res)) } getReport(id: string){ return this.http.get(`${this.reportsEndpoint}/${id}`) .map(res => this.extractReport(res)) } downloadFile(fileName: string) { let result = this.http.get(`${this.filesEndpoint}/${fileName}`).map(res => res.text()) console.log(result); return result; } uploadFile(reportId: string, incidentId: string, file: File){ let formData = new FormData() formData.append("file", file) let result = this.http.post(`${this.filesEndpoint}/${reportId}/${incidentId}`, formData).map(res => res.text()) console.log(result); return result; } saveReport(report: Report){ console.log(report); let reportDto = ReportDto.mapToDto(report) this.http.post(this.reportsEndpoint, reportDto) .subscribe(res => { console.log(`res = ${res.json()}`) report.id = res.json()}) let formData = new FormData(); report.incidents.forEach(incident => { incident.attachments.forEach(file => formData.append("files", file)); console.log(formData); this.http.post(`${this.filesEndpoint}/${report.id}/${incident.id}`, formData) .map(res => res.json).subscribe(); }); } private extractReports(response: Response){ console.log(response.json()); let reportDtos: ReportDto[] = response.json() as ReportDto[]; let reports = reportDtos.map(r => this.mapFromDto(r)) console.log(reports); return reports; } private extractReport(response: Response){ console.log(response.json()); let reportDto = response.json() as ReportDto; let report = this.mapFromDto(reportDto); console.log(report); return report; } mapFromDto(reportDto: ReportDto) { let report = ReportDto.mapFromDto(reportDto); reportDto.incidents.forEach(i => { let incident = IncidentDto.mapFromDto(i); i.attachments.forEach(a => { this.downloadFile(a) .subscribe((data) => { incident.attachments.push(data); }); }) report.incidents.push(incident); }) return report; } private handleError(error: any, caught: Observable<any>): any{ let message = ""; return Observable.throw(caught); } private createEnvironment(json: any) { let env: EnvironmentInfo = { dataCenter: json.dataCenter, environment: json.environment, project: json.project, machines: json.machines } } }<file_sep>/Controllers/FilesController.cs using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; using Microsoft.Net.Http.Headers; using MonitoringAssistant.Infrastructure; namespace MonitoringAssistant.Controllers { [Route("/api/files")] public class FilesController : Controller { readonly IHostingEnvironment _host; readonly string _uploadsPath; private readonly StorageFaсade _storageFacade; public FilesController(IHostingEnvironment host, StorageFaсade storageFacade) { this._storageFacade = storageFacade; this._host = host; _uploadsPath = Path.Combine(host.WebRootPath, "uploads"); } // [HttpPost("{reportId}/{incidentId}")] // public async Task<IActionResult> UploadFiles(string reportId, string incidentId, IFormCollection files) // { // if (!Directory.Exists(_uploadsPath)) // Directory.CreateDirectory(_uploadsPath); // var report = _storageFacade.GetReport(reportId); // var incident = report?.Incidents.FirstOrDefault(i => i.Id == incidentId); // if(incident != null) // { // var list = new List<string>(); // foreach (var f in files.Files) // { // var fileName = Guid.NewGuid() + Path.GetExtension(f.FileName); // var filePath = Path.Combine(_uploadsPath, fileName); // using (var fileStream = new FileStream(filePath, FileMode.Create)) // { // await f.CopyToAsync(fileStream); // } // list.Add(fileName); // } // incident.Attachments = list.ToArray(); // _storageFacade.UpdateReport(report); // } // return Ok(); // } [HttpPost("{reportId}/{incidentId}")] public async Task<IActionResult> UploadFile(string reportId, string incidentId, IFormFile file) { if (!Directory.Exists(_uploadsPath)) Directory.CreateDirectory(_uploadsPath); var report = _storageFacade.GetReport(reportId); var incident = report?.Incidents.FirstOrDefault(i => i.Id == incidentId); if(incident == null) return NotFound("There is no such report or incident."); if(file == null) return NotFound("File can't be null"); var list = new List<string>(incident.Attachments); var fileName = Guid.NewGuid() + Path.GetExtension(file.FileName); var fullPath = Path.Combine(_uploadsPath, fileName); using (var fileStream = new FileStream(fullPath, FileMode.Create)) { await file.CopyToAsync(fileStream); } list.Add(fileName); incident.Attachments = list.ToArray(); _storageFacade.UpdateReport(report); byte[] fileBytes = System.IO.File.ReadAllBytes(fullPath); return Ok("data:image/png;base64," + Convert.ToBase64String(fileBytes)); } [HttpGet("{fileName}")] public async Task<IActionResult> DownloadFile(string fileName) { try { if (!Directory.Exists(_uploadsPath)) return NoContent(); var fullPath = Path.Combine(_uploadsPath, fileName); var cd = new ContentDispositionHeaderValue("attachment") { FileName = fileName }; Response.Headers.Add(HeaderNames.ContentDisposition, cd.ToString()); byte[] fileBytes = System.IO.File.ReadAllBytes(fullPath); return Ok("data:image/png;base64," + Convert.ToBase64String(fileBytes)); } catch { return NotFound(fileName); } } } }<file_sep>/Controllers/ReportsController.cs using System.Collections.Generic; using System.Diagnostics; using Microsoft.AspNetCore.Mvc; using MonitoringAssistant.Infrastructure; using MonitoringAssistant.Models; namespace MonitoringAssistant.Controllers { [Route("/api/[controller]")] public class ReportsController: Controller { private readonly StorageFaсade _storageFacade; public ReportsController(StorageFaсade storageFacade) { _storageFacade = storageFacade; } [HttpGet] public IActionResult GetReports() { Debug.WriteLine("GetReports"); return Ok(_storageFacade.GetReports()); } [HttpGet("{id}")] public IActionResult GetReport(string id) { Debug.WriteLine($"GetReport with id {id}"); return Ok(_storageFacade.GetReport(id)); } [HttpPost] public IActionResult UpdateReport([FromBody] Report report) { Debug.WriteLine("CreateReport"); if (!ModelState.IsValid) return BadRequest(ModelState); var id = _storageFacade.UpdateReport(report); return Ok(id); } } }<file_sep>/ClientApp/app/components/kibana/kibana.component.ts import { Component } from "@angular/core" import { Router } from "@angular/router" @Component({ selector: "kibana", templateUrl: "kibana.component.html", styleUrls: ["kibana.component.css"] }) export class KibanaComponent{ }<file_sep>/ClientApp/app/shared/dto/environmentInfoDto.ts import { EnvironmentInfo } from "../models/environmentInfo"; export class EnvironmentInfoDto{ dataCenter = ""; environment = ""; project = ""; machines: string[] = []; static mapToDto(env: EnvironmentInfo): EnvironmentInfoDto { return { dataCenter: env.dataCenter, environment: env.environment, project: env.project, machines: env.machines } } static mapFromDto(env: EnvironmentInfoDto): EnvironmentInfo { return { dataCenter: env.dataCenter, environment: env.environment, project: env.project, machines: env.machines } } }<file_sep>/ClientApp/app/components/sharedComponents/shared.resources.module.ts import { NgModule } from "@angular/core"; import { CommonModule } from "@angular/common"; import { FormsModule } from "@angular/forms"; import { EnvironmentComponent } from "./environment/environment.component"; import { IncidentItemComponent } from "./incident-item/incident-item.component"; export { EnvironmentComponent } from "./environment/environment.component"; export { IncidentItemComponent } from "./incident-item/incident-item.component"; @NgModule({ imports:[ CommonModule, FormsModule ], declarations:[ EnvironmentComponent, IncidentItemComponent ], exports:[ EnvironmentComponent, IncidentItemComponent ] }) export class SharedResourcesModule {}<file_sep>/ClientApp/app/app.shared.module.ts import { NgModule } from '@angular/core'; import { CommonModule } from '@angular/common'; import { FormsModule } from '@angular/forms'; import { HttpModule } from '@angular/http'; import { RouterModule } from '@angular/router'; import { AppRoutingModule } from './app-routing.module'; import { AppComponent } from './app.component'; import { HomeComponent } from './components/home/home.component'; import { MonitoringComponent } from "./components/monitoring/monitoring.component"; import { ReportsService } from './shared/services/reports.service'; import { SharedResourcesModule } from './components/sharedComponents/shared.resources.module'; import { ReportsModule } from './components/reports/reports.module'; @NgModule({ declarations: [ AppComponent, HomeComponent, MonitoringComponent ], imports: [ CommonModule, HttpModule, FormsModule, AppRoutingModule, ReportsModule, SharedResourcesModule ], providers: [ReportsService] }) export class AppModuleShared { } <file_sep>/Controllers/IncidentsController.cs using System.Collections.Generic; using Microsoft.AspNetCore.Mvc; using MonitoringAssistant.Infrastructure; using MonitoringAssistant.Models; namespace MonitoringAssistant.Controllers { [Route("api/[controller]")] public class IncidentsController: Controller { StorageFaсade _storageFacade; public IncidentsController(StorageFaсade storageFacade) { _storageFacade = storageFacade; } [HttpGet("/api/incidents")] public IEnumerable<Incident> GetIncidents() { return _storageFacade.GetIncidents(); } } }<file_sep>/Models/Report.cs using System; namespace MonitoringAssistant.Models { public class Report { public string Id { get; set; } public string User { get; set; } public DateTime Date { get; set; } public Incident[] Incidents { get; set; } } }<file_sep>/Models/EnvironmentInfo.cs namespace MonitoringAssistant.Models { public class EnvironmentInfo { public string DataCenter { get; set; } public string Environment { get; set; } public string Project { get; set; } public string[] Machines { get; set; } } }<file_sep>/ClientApp/app/components/reports/reportsHistory/reports-history.component.ts import { Component } from "@angular/core"; import { Router } from "@angular/router"; import { Report } from "./../../../shared/models/report" import { ReportsService } from "../../../shared/services/reports.service"; @Component({ selector: "reports-history", templateUrl: "reports-history.component.html" }) export class ReportsHistoryComponent { title = "Reports history" reports: Report[] = []; private selectedReport: any; constructor(private router: Router, private reportsService: ReportsService) { } ngOnInit() { this.getReports() } getReports() { this.reportsService.getReports().subscribe(reports => this.reports = reports); // [{id: "1", userName: "user", creationDate: new Date()}, // {id: "2", userName: "user", creationDate: new Date()}] } public onSelect(report: Report){ this.router.navigate(["/reports",report.id]).then( success => this.selectedReport = success ? report : this.selectedReport); } public goBack(){ console.log("goBack"); this.router.navigate(["/home"]) } }<file_sep>/Infrastructure/StorageFaсade.cs using System.Collections.Generic; using MonitoringAssistant.Models; namespace MonitoringAssistant.Infrastructure { public class StorageFaсade { IStorage _storage; public StorageFaсade(IStorage storage) { _storage = storage; } public IEnumerable<Incident> GetIncidents() { return _storage.GetIncidents(); } public IEnumerable<Report> GetReports() { return _storage.GetReports(); } public Report GetReport(string id) { return _storage.GetReport(id); } public string UpdateReport(Report report) { return _storage.UpdateReport(report); } } }<file_sep>/Infrastructure/IStorage.cs using System.Collections.Generic; using MonitoringAssistant.Models; namespace MonitoringAssistant.Infrastructure { public interface IStorage { IEnumerable<Incident> GetIncidents(); IEnumerable<Report> GetReports(); Report GetReport(string id); string UpdateReport(Report report); } }<file_sep>/ClientApp/app/shared/dto/reportDto.ts import { IncidentDto } from "./incidentDto"; import { Report } from "../models/report"; export class ReportDto { id = "" user = "" date: Date = new Date(); incidents: IncidentDto[] = [] static mapToDto(report: Report): ReportDto { let inc = report.incidents.map(i => IncidentDto.mapToDto(i)) return { id: report.id, user: report.user, date: report.date, incidents: inc } } static mapFromDto(report: ReportDto): Report { return { id: report.id, user: report.user, date: report.date, incidents: [] } } }<file_sep>/ClientApp/app/components/reports/reports-routing.module.ts import { NgModule } from "@angular/core"; import { RouterModule } from "@angular/router"; import { ReportsHistoryComponent } from "./reportsHistory/reports-history.component"; import { ReportComponent } from "./report/report.component"; @NgModule({ imports:[ RouterModule.forChild([ { path: "", redirectTo: "/reports", pathMatch: "full" }, { path: "reports", component: ReportsHistoryComponent, children: [ { path:":id", component: ReportComponent, //canDeactivate: [CanDeactivateGuard] } ] },{ path: "newReport", component: ReportComponent } ]) ], exports: [RouterModule] }) export class ReportsRoutingModule{}<file_sep>/ClientApp/app/components/sharedComponents/incident-item/incident-item.component.ts import { Component, Input, Output, EventEmitter } from "@angular/core" import { Router } from "@angular/router"; import { Incident } from "../../../shared/models/incident"; import * as FileSaver from 'file-saver'; @Component({ selector: "incident-item", templateUrl: "incident-item.component.html", styleUrls: [ "incident-item.component.css" ] }) export class IncidentItemComponent{ @Input() incident: Incident = new Incident(); @Input() editMode: boolean = false; @Output() onChanged = new EventEmitter<File>(); addedAction: string = ""; modeCaption: string = this.editMode ? "Save" : "Edit"; constructor(){} changeEditMode(){ this.editMode = !this.editMode; this.modeCaption = this.editMode ? "Save" : "Edit"; if(!this.editMode) this.onChanged.emit(); } addImage(event: any) { console.log("addImage"); let file: File = event.target.files[0]; this.onChanged.emit(file); } addAction() { if(this.addedAction != "" && this.incident.actions.indexOf(this.addedAction) < 0) { this.incident.actions.push(this.addedAction); this.addedAction = ""; this.onChanged.emit(); } } deleteAction(action: string) { let index = this.incident.actions.indexOf(action) if(index >= 0){ this.incident.actions.splice(index, 1); this.onChanged.emit(); } } }<file_sep>/Models/Incident.cs using System; using System.Collections.Generic; using MongoDB.Bson; using MongoDB.Bson.Serialization.Attributes; namespace MonitoringAssistant.Models { public class Incident { public string Id { get; set; } public EnvironmentInfo Environment { get; set; } public string Description { get; set; } public string[] Actions { get; set; } public string[] Attachments { get; set; } } }<file_sep>/ClientApp/app/components/monitoring/monitoring.component.ts import { Component } from "@angular/core" import { Router } from "@angular/router"; import { EnvironmentInfo } from '../../shared/models/environmentInfo'; @Component({ selector: "monitoring", templateUrl: "monitoring.component.html", styleUrls: ["monitoring.component.css"] }) export class MonitoringComponent { constructor(private router: Router){} title="Monitoring tools" environmentInfo: EnvironmentInfo = new EnvironmentInfo(); ngOnInit() { } }<file_sep>/ClientApp/app/shared/models/environmentInfo.ts export class EnvironmentInfo{ dataCenter = ""; environment = ""; project = ""; machines: string[] = []; }<file_sep>/ClientApp/app/shared/models/incident.ts import { EnvironmentInfo } from "./environmentInfo"; import { Guid } from "../guid"; export class Incident { readonly id: string = Guid.newGuid(); environment: EnvironmentInfo = new EnvironmentInfo(); description = ""; actions: string[] = []; attachments: any[] = []; }<file_sep>/ClientApp/app/components/home/home.component.ts import { Component } from "@angular/core" import { Router } from "@angular/router"; @Component({ selector: "my-home", templateUrl: "home.component.html", styleUrls: ["home.component.css"] }) export class HomeComponent{ constructor(private router: Router){} title = 'Shift Assistant'; goToMonitoring() { this.router.navigate(["/monitoring"]); } createNewReport() { console.log("createNew"); this.router.navigate(["/newReport"]) } openReportsHistory() { this.router.navigate(["/reports"]); } }<file_sep>/ClientApp/app/components/sharedComponents/environment/environment.component.ts import { Component, Input } from "@angular/core"; import { EnvironmentInfo } from "../../../shared/models/environmentInfo"; import { Router } from "@angular/router"; @Component({ selector: "environment", templateUrl: "environment.component.html", styleUrls: ["environment.component.css"] }) export class EnvironmentComponent { @Input() environmentInfo: EnvironmentInfo = new EnvironmentInfo(); @Input() editMode: boolean = true; dataCenters: string[]=["GC", "Ireland"]; environments: string[]=["Prod", "Stg", "QA"]; projects: string[]=["ETL", "Push", "Pull", "Search"]; machines: string[]=["1", "2", "3", "4"]; selectedMachines: string[] = []; constructor(private router: Router) { } ngOnInit() { if(this.environmentInfo.dataCenter == "" && this.environmentInfo.environment == "" && this.environmentInfo.project == "" && this.environmentInfo.machines == []) { this.environmentInfo.dataCenter = this.dataCenters[0]; this.environmentInfo.environment = this.environments[0]; this.environmentInfo.project = this.projects[0]; this.environmentInfo.machines = this.selectedMachines; } } machineSelectionChanged(isChecked: boolean, machineName: string){ if(isChecked && !(this.selectedMachines.indexOf(machineName) < 0)) this.selectedMachines.concat([machineName]) else this.selectedMachines.splice(this.selectedMachines.indexOf(machineName), 1); } }
9ed1b2ac8d7c97dce5d4b73727b1f68efb840067
[ "C#", "TypeScript" ]
27
TypeScript
shvetsi/MonitoringAssistant
c8588e54e930d58fdf1db8963952fd66e51a5581
d61d5c9a4fb28026e596b133b23f44f871404dfa
refs/heads/main
<repo_name>Lavinia-dsci/pracgit<file_sep>/scondpython.py # Display the output print("Nes python file")
b18d7ba0eb89909a913cbf49133bb5715be2c22f
[ "Python" ]
1
Python
Lavinia-dsci/pracgit
60029880525771f36a76762144b22d017115c00e
a4b4aa12f94801ad1d7b2e61d58a9ad4209f28fd
refs/heads/main
<file_sep><?php namespace App\Http\Controllers\Course; use App\Http\Controllers\Controller; use Illuminate\Http\Request; use App\Model\CourseTypeModel; class CourseTypeController extends Controller { /** * 课程分类的添加 * */ public function create(){ return view('course.type.create'); } public function add(){ $data['type_name']=request()->chapter_name; //唯一处理 $type_data=CourseTypeModel::where('type_name',$data['type_name'])->first(); if(!empty($type_data)){ return ['code'=>0003,'msg'=>'分类已经存在']; } $data['type_add_time']=time(); $res=CourseTypeModel::insert($data); if($res){ return ['code'=>0001,'msg'=>'添加成功']; }else{ return ['code'=>0002,'msg'=>'添加失败']; } } } <file_sep><?php namespace App\Http\Controllers\Admin; use App\Http\Controllers\Controller; use Illuminate\Http\Request; //引入角色model use App\Model\RolesModel; //引入权限model use App\Model\PowerModel; //引入角色权限表 use App\Model\RolesPowerModel as RP; class RolePowerController extends Controller { /** * 角色权限展示方法 */ public function index(){ //查询 $data=RP::select('online_role_power.*','ro_name') ->leftjoin('online_role','online_role_power.ro_id','=','online_role.ro_id') ->where(['rp_del'=>0]) ->get(); //循环获取权限 foreach($data as $k=>$v){ $pow_id=explode(',',$v['pow_id']); foreach($pow_id as $k1=>$v1){ $v['pow_name'].=PowerModel::where(['pow_id'=>$v1])->value('pow_name').','; } //去除多余字符 $v['pow_name']=rtrim($v['pow_name'],','); } //渲染视图 return view('admin/role_power/index',compact('data')); } /** * 角色权限添加方法 */ public function create(){ //查询角色 $roles_data=RolesModel::select('ro_id','ro_name')->get(); //查询权限 $power_data=PowerModel::select('pow_id','pow_name')->get(); //渲染视图 return view('admin/role_power/create',compact('roles_data','power_data')); } /** * 验证角色 唯一 */ public function unique(){ //接值 $ro_id=request()->except('_token'); //查询 $roles=RP::where(['ro_id'=>$ro_id,'rp_del'=>0])->count(); //判断 if($roles==0){ //返回 return json_encode(['status'=>'ok']); }else{ //返回 return json_encode(['status'=>'no']); } } /** * 执行添加 */ public function store(){ //接值 $data=request()->except('_token'); //判断 if(empty($data['ro_id'])){ //返回 return json_encode(['status'=>'fail','field'=>'roles','msg'=>'<b style="color: red">× 请选择角色。</b>']); }else{ //where 条件 $where=[ ['ro_id','=',$data['ro_id']], ['rp_del','=',0] ]; //查询 $roles=RP::where($where)->count(); //判断 if($roles!=0){ //返回 return json_encode(['status'=>'fail','field'=>'roles','msg'=>'<b style="color: red">× 该角色已存在,请重新选择。</b>']); } } if(empty($data['pow_id'])){ //返回 return json_encode(['status'=>'fail','field'=>'power','msg'=>'<b style="color: red">× 请选择权限。</b>']); } //添加时间 $data['rp_time']=time(); //添加 $bol=RP::insert($data); //判断 if($bol){ //成功返回 return json_encode(['status'=>'ok']); }else{ //失败返回 return json_encode(['status'=>'no']); } } /** * 编辑页面 */ public function edit($id){ //查询角色 $roles_data=RolesModel::select('ro_id','ro_name')->get(); //查询权限 $power_data=PowerModel::select('pow_id','pow_name')->get(); //查询 $info=RP::where(['rp_id'=>$id,'rp_del'=>0])->first(); //处理权限 $info->pow_id=explode(',',$info->pow_id); //渲染视图 return view('admin/role_power/edit',compact('roles_data','power_data','info')); } /** * 修改 验证角色唯一 */ public function unique_update($id){ //接值 $ro_id=request()->except('_token'); //where 条件 $where=[ ['ro_id','=',$ro_id], ['rp_id','!=',$id], ['rp_del','=',0] ]; //查询 $roles=RP::where($where)->count(); //判断 if($roles==0){ //返回 return json_encode(['status'=>'ok']); }else{ //返回 return json_encode(['status'=>'no']); } } /** * 修改 */ public function update($id){ //接值 $data=request()->except('_token'); //判断 if(empty($data['ro_id'])){ //返回 return json_encode(['status'=>'fail','field'=>'roles','msg'=>'<b style="color: red">× 请选择角色。</b>']); }else{ //where 条件 $where=[ ['ro_id','=',$data['ro_id']], ['rp_id','!=',$id], ['rp_del','=',0] ]; //查询 $roles=RP::where($where)->count(); //判断 if($roles!=0){ //返回 return json_encode(['status'=>'fail','field'=>'roles','msg'=>'<b style="color: red">× 该角色已存在,请重新选择。</b>']); } } if(empty($data['pow_id'])){ //返回 return json_encode(['status'=>'fail','field'=>'power','msg'=>'<b style="color: red">× 请选择权限。</b>']); } //添加时间 $data['rp_time']=time(); //添加 $bol=RP::where(['rp_id'=>$id,'rp_del'=>0])->update($data); //判断 if($bol!==false){ //成功返回 return json_encode(['status'=>'ok']); }else{ //失败返回 return json_encode(['status'=>'no']); } } /** * 删除 */ public function destroy($id){ //修改状态值 $bol=RP::where(['rp_id'=>$id,'rp_del'=>0])->update(['rp_del'=>1]); //判断 if($bol!==false){ //跳转 return redirect('/role_power'); }else{ //跳转 return redirect('/role_power'); } } } <file_sep><?php namespace App\Http\Controllers\Admin; use App\Http\Controllers\Controller; use Illuminate\Http\Request; use App\Model\ArticleModel; class ArticleController extends Controller { //展示 public function index(){ $ati_name = request()->ati_name; $where = []; if($ati_name){ $where[] = ['ati_name','like',"%$ati_name%"]; } $where2=[ 'id_del'=>0 ]; $data = ArticleModel::where($where)->where($where2)->paginate(2); return view('/article/index',['data'=>$data,'ati_name'=>$ati_name]); } // 添加 public function create(){ return view('/article/create'); } // 执行添加 public function story(Request $request){ // 接值 $ati_name = $request->post("ati_name");//资讯标题 $ati_ishot = $request->post("ati_ishot");//资讯热度 $ati_content = $request->post("ati_content");//资讯内容 $ati_res = $request->post("ati_res");//资讯作者 // dd($ati_res); // 判断是否为空 if(!$ati_name){ echo json_encode(['code'=>1,"msg"=>"标题不能为空"]);die; } if(!$ati_ishot){ echo json_encode(['code'=>1,"msg"=>"标题不能为空"]);die; } if(!$ati_content){ echo json_encode(['code'=>1,"msg"=>"标题不能为空"]);die; } if(!$ati_res){ echo json_encode(['code'=>1,"msg"=>"标题不能为空"]);die; } // 实例化model $articleModel = new ArticleModel; $articleModel->ati_name=$ati_name; $articleModel->ati_ishot=$ati_ishot; $articleModel->ati_content=$ati_content; $articleModel->ati_res=$ati_res; $articleModel->ati_addtime=time(); // 添加数据进数据库 $res = $articleModel->save(); if($res){ echo json_encode(['code'=>0,"msg"=>"添加成功"]);die; }else{ echo json_encode(['code'=>1,"msg"=>"添加失败"]);die; } } // 删除 public function del($id){ // echo 12345;die; $res = ArticleModel::where("ati_id",$id)->update(['id_del'=>1]); // dd($res); if($res){ return redirect("/article"); }else{ return redirect("/article"); } } // 修改 public function update($id){ $data = ArticleModel::where('ati_id',$id)->first(); // dd($data); return view("article.update",['data'=>$data]); } // 执行修改 public function update2(Request $request,$id){ // 接值 $ati_name = $request->post("ati_name");//资讯标题 $ati_ishot = $request->post("ati_ishot");//资讯热度 $ati_content = $request->post("ati_content");//资讯内容 $ati_res = $request->post("ati_res");//资讯作者 $ati_id = $request->post("ati_id"); // dd($ati_id); $data = [ 'ati_name'=>$ati_name, 'ati_ishot'=>$ati_ishot, 'ati_content'=>$ati_content, 'ati_res'=>$ati_res, 'ati_id'=>$ati_id ]; $res = ArticleModel::where("ati_id",$id)->update($data); // dd($res); if($res){ echo json_encode(['code'=>0,'msg'=>"ok"]); }else{ echo json_encode(['code'=>1,'msg'=>"no"]); } } } <file_sep><?php namespace App\Http\Controllers\Admin; use App\Http\Controllers\Controller; use Illuminate\Http\Request; //引入权限model use App\Model\PowerModel; class PowerController extends Controller { /** * 权限展示方法 */ public function index(){ //查询 $data=PowerModel::get(); //渲染视图 return view('admin/power/index',compact('data')); } /** * 权限添加方法 */ public function create(){ //渲染视图 return view('admin/power/create'); } /** * 权限执行添加 */ public function store(){ //接值 $data=request()->except('_token'); //验证 if(empty($data['pow_name'])){ return json_encode(['status'=>'no','field'=>'pow_name','msg'=>"<b style='color: red'>× 权限名称不可为空,请填写。</b>"]); }else{ //查询 $count=PowerModel::where(['pow_name'=>$data['pow_name']])->count(); if($count!=0){ return json_encode(['status'=>'no','field'=>'pow_name','msg'=>"<b style='color: red'>× 此权限名称已存在,请重新填写。</b>"]); } } if(empty($data['pow_url'])){ return json_encode(['status'=>'no','field'=>'pow_url','msg'=>"<b style='color: red'>× 权限不可为空,请填写。</b>"]); }else{ //查询 $count=PowerModel::where(['pow_name'=>$data['pow_url']])->count(); if($count!=0){ return json_encode(['status'=>'no','field'=>'pow_url','msg'=>"<b style='color: red'>× 此权限已存在,请重新填写。</b>"]); } } //添加时间 $data['pow_time']=time(); //添加 $bol=PowerModel::insert($data); //判断 if($bol){ return json_encode(['status'=>"ok"]); }else{ return json_encode(['status'=>"no"]); } } /** * 权限名称验证唯一 */ public function unique(){ //接值 $pow_name=request()->except('_token'); //查询 $count=PowerModel::where(['pow_name'=>$pow_name])->count(); //判断返回 if($count==0){ return 'ok'; }else{ return 'no'; } } /** * 权限验证唯一 */ public function url_unique(){ //接值 $pow_url=request()->except('_token'); //查询 $count=PowerModel::where(['pow_url'=>$pow_url])->count(); //判断返回 if($count==0){ return 'ok'; }else{ return 'no'; } } /** * 编辑页面 */ public function edit($id){ //查询单条 $info=PowerModel::where(['pow_id'=>$id])->first(); //渲染视图 return view('admin/power/edit',compact('info')); } /** * 修改时的权限名称验证唯一 */ public function unique_update($id){ //接值 $pow_name=request()->except('_token'); //where 条件 $where=[ ['pow_name','=',$pow_name], ['pow_id','!=',$id] ]; //查询 $count=PowerModel::where($where)->count(); //判断返回 if($count==0){ return 'ok'; }else{ return 'no'; } } /** * 修改 权限验证唯一 */ public function url_unique_update($id){ //接值 $pow_url=request()->except('_token'); //where 条件 $where=[ ['pow_url','=',$pow_url], ['pow_id','!=',$id] ]; //查询 $count=PowerModel::where($where)->count(); //判断返回 if($count==0){ return 'ok'; }else{ return 'no'; } } /** * 修改 */ public function update($id){ //接值 $data=request()->except('_token'); //验证 if(empty($data['pow_name'])){ return json_encode(['status'=>'no','field'=>'pow_name','msg'=>"<b style='color: red'>× 权限名称不可为空,请填写。</b>"]); }else{ //where 条件 $where=[ ['pow_name','=',$data['pow_name']], ['pow_id','!=',$id] ]; //查询 $count=PowerModel::where($where)->count(); if($count!=0){ return json_encode(['status'=>'no','field'=>'pow_name','msg'=>"<b style='color: red'>× 此权限名称已存在,请重新填写。</b>"]); } } if(empty($data['pow_url'])){ return json_encode(['status'=>'no','field'=>'pow_url','msg'=>"<b style='color: red'>× 权限不可为空,请填写。</b>"]); }else{ //where 条件 $where=[ ['pow_url','=',$data['pow_url']], ['pow_id','!=',$id] ]; //查询 $count=PowerModel::where($where)->count(); if($count!=0){ return json_encode(['status'=>'no','field'=>'pow_url','msg'=>"<b style='color: red'>× 此权限已存在,请重新填写。</b>"]); } } //添加时间 $data['pow_time']=time(); //修改 $bol=PowerModel::where('pow_id',$id)->update($data); //判断 if($bol!==false){ return json_encode(['status'=>"ok"]); }else{ return json_encode(['status'=>"no"]); } } /** * 权限删除 */ public function destroy($id){ //删除 $bol=PowerModel::where('pow_id',$id)->delete(); //判断 if($bol){ return redirect('/power'); }else{ return redirect('/power'); } } } <file_sep><?php namespace App\Model; use Illuminate\Database\Eloquent\Model; class RolesModel extends Model { //指定表名 protected $table='online_role'; //指定主键 protected $primaryKey='ro_id'; //关闭时间戳 public $timestamps=false; } <file_sep><?php namespace App\Http\Controllers\Admin; use App\Http\Controllers\Controller; use Illuminate\Http\Request; //引入管理员model use App\Model\AdminModel; class AdminController extends Controller { /** * 管理员展示方法 */ public function index(){ //查询 $data=AdminModel::where('admin_del',0)->get(); //渲染视图 return view('admin/admin/index',compact('data')); } /** * 管理员添加方法 */ public function create(){ //渲染视图 return view('admin/admin/create'); } /** * 管理员名称验证唯一 */ public function unique(){ //接值 $admin_name=request()->except('_token'); //查询 $count=AdminModel::where(['admin_name'=>$admin_name,'admin_del'=>0])->count(); //判断返回 if($count==0){ return 'ok'; }else{ return 'no'; } } /** * 管理员执行添加 */ public function store(){ //接值 $data=request()->except('_token'); //验证 if(empty($data['admin_name'])){ return json_encode(['status'=>'no','field'=>'admin_name','msg'=>"<b style='color: red'>× 管理员名称不可为空,请填写。</b>"]); }else{ //查询 $count=AdminModel::where(['admin_name'=>$data['admin_name'],'admin_del'=>0])->count(); if($count!=0){ return json_encode(['status'=>'no','field'=>'admin_name','msg'=>"<b style='color: red'>× 此管理员名称已存在,请重新填写。</b>"]); } } if(empty($data['admin_pwd'])){ return json_encode(['status'=>'no','field'=>'admin_pwd','msg'=>"<b style='color: red'>× 密码不可为空,请填写。</b>"]); } //验证正则 $reg='/^\w{6,}$/'; if(!preg_match($reg,$data['admin_pwd'])){ return json_encode(['status'=>'no','field'=>'admin_pwd','msg'=>"<b style='color: red'>× 密码最低6位,请重新填写。</b>"]); } if(empty($data['admin_pwds'])){ return json_encode(['status'=>'no','field'=>'admin_pwds','msg'=>"<b style='color: red'>× 确认密码不可为空,请填写。</b>"]); } //验证正则 $reg='/^\w{6,}$/'; if(!preg_match($reg,$data['admin_pwd'])){ return json_encode(['status'=>'no','field'=>'admin_pwds','msg'=>"<b style='color: red'>× 确认密码最低6位,请重新填写。</b>"]); } if($data['admin_pwds']!=$data['admin_pwd']){ return json_encode(['status'=>'no','field'=>'admin_pwds','msg'=>"<b style='color: red'>× 两次密码不一致,请重新填写。</b>"]); } //处理密码 unset($data['admin_pwds']); $data['admin_pwd']=password_hash($data['<PASSWORD>'], PASSWORD_BCRYPT); //添加时间 $data['admin_time']=time(); //添加 $bol=AdminModel::insert($data); //判断 if($bol){ return json_encode(['status'=>"ok"]); }else{ return json_encode(['status'=>"no"]); } } /** * 编辑页面 */ public function edit($id){ //查询单条 $info=AdminModel::where(['admin_id'=>$id,'admin_del'=>0])->first(); //渲染视图 return view('admin/admin/edit',compact('info')); } /** * 修改时的管理员名称验证唯一 */ public function unique_update($id){ //接值 $admin_name=request()->except('_token'); //where 条件 $where=[ ['admin_name','=',$admin_name], ['admin_id','!=',$id], ['admin_del','=',0] ]; //查询 $count=AdminModel::where($where)->count(); //判断返回 if($count==0){ return 'ok'; }else{ return 'no'; } } /** * 修改 */ public function update($id){ //接值 $data=request()->except('_token'); //验证 if(empty($data['admin_name'])){ return json_encode(['status'=>'no','field'=>'admin_name','msg'=>"<b style='color: red'>× 管理员名称不可为空,请填写。</b>"]); }else{ //where 条件 $where=[ ['admin_name','=',$data['admin_name']], ['admin_id','!=',$id], ['admin_del','=',0] ]; //查询 $count=AdminModel::where($where)->count(); if($count!=0){ return json_encode(['status'=>'no','field'=>'admin_name','msg'=>"<b style='color: red'>× 此管理员名称已存在,请重新填写。</b>"]); } } if(empty($data['admin_pwd'])){ return json_encode(['status'=>'no','field'=>'admin_pwd','msg'=>"<b style='color: red'>× 密码不可为空,请填写。</b>"]); } //验证正则 $reg='/^\w{6,}$/'; if(!preg_match($reg,$data['admin_pwd'])){ return json_encode(['status'=>'no','field'=>'admin_pwd','msg'=>"<b style='color: red'>× 密码最低6位,请重新填写。</b>"]); } if(empty($data['admin_pwds'])){ return json_encode(['status'=>'no','field'=>'admin_pwds','msg'=>"<b style='color: red'>× 确认密码不可为空,请填写。</b>"]); } //验证正则 $reg='/^\w{6,}$/'; if(!preg_match($reg,$data['admin_pwd'])){ return json_encode(['status'=>'no','field'=>'admin_pwds','msg'=>"<b style='color: red'>× 确认密码最低6位,请重新填写。</b>"]); } if($data['admin_pwds']!=$data['admin_pwd']){ return json_encode(['status'=>'no','field'=>'admin_pwds','msg'=>"<b style='color: red'>× 两次密码不一致,请重新填写。</b>"]); } //处理密码 unset($data['admin_pwds']); $data['admin_pwd']=password_hash($data['admin_pwd'], PASSWORD_BCRYPT); //添加时间 $data['admin_time']=time(); //添加 $bol=AdminModel::where(['admin_id'=>$id,'admin_del'=>0])->update($data); //判断 if($bol){ return json_encode(['status'=>"ok"]); }else{ return json_encode(['status'=>"no"]); } } /** * 删除 */ public function destroy($id){ //删除 $bol=AdminModel::where('admin_id',$id)->update(['damin_del'=>1]); //判断 if($bol){ return redirect('/admin'); }else{ return redirect('/admin'); } } }<file_sep><?php namespace App\Http\Middleware; use Closure; //引入管理员model use App\Model\AdminModel as Admin; //引入管理员 角色 model use App\Model\AdminRolesModel as AR; //引入角色 model use App\Model\RolesModel as Roles; //引入角色 权限 model use App\Model\RolesPowerModel as RP; //引入 权限 model use App\Model\PowerModel as Power; class CheckAuthority { /** * Handle an incoming request. * * @param \Illuminate\Http\Request $request * @param \Closure $next * @return mixed */ public function handle($request, Closure $next) { //取出session信息 $admin=session('admin_info'); //取出session 中的 管理员 id $admin_id=$admin->admin_id; //获取访问的路由 $url=$request->route()->uri; //判断路由 if($url!='/'){ $url='/'.$url; }else{ //首页访问 return $next($request); } //查询用户是否存在 $admin_info=Admin::where(['admin_id'=>$admin_id,'admin_del'=>0])->value('admin_id'); if(!empty($admin_info)){ //查询角色 $roles=AR::where(['admin_id'=>$admin_info,'ar_del'=>0])->first(); //判断 if(!empty($roles)){ //获取最高角色的id $roles_id=Roles::where(['ro_name'=>'root'])->value('ro_id'); //判断角色是否是最高角色 if($roles->ro_id==$roles_id){ //最高角色 直接进入 return $next($request); }else{ //不是最高角色 查权限 //根据角色id找权限 $power=RP::where(['ro_id'=>$roles->ro_id,'rp_del'=>0])->first(); //分割权限id $power_id=explode(',',$power->pow_id); //权限数组 $power=[]; //循环查询权限 foreach($power_id as $k=>$v){ //存权限 $power[]=Power::where(['pow_id'=>$v])->value('pow_url'); } //判断权限是否存在 if(in_array($url,$power)){ //具有权限 进入 return $next($request); }else{ ///没有权限 返回 return back()->with('msg','非常抱歉,您不具备访问此功能的权限。'); } } }else{ //没有角色 return back()->with('msg','非常抱歉,您不具备访问此功能的权限。'); } }else{ //用户不存在 return back()->with('msg','非常抱歉,您不具备访问此功能的权限。'); } } } <file_sep><?php namespace App\Http\Controllers\Admin; use App\Http\Controllers\Controller; use Illuminate\Http\Request; use App\Model\TeacherModel; class TeacherController extends Controller { //讲师展示 public function index(){ // 接搜索值 $lereg_name = request()->lereg_name; $where = []; if($lereg_name){ $where[] = ['lereg_name','like',"%$lereg_name%"]; } // print_r($lereg_name); // $where = [ // 'is_del'=>0, // ]; $data = TeacherModel::where($where)->orderBy("lereg_id","desc")->paginate(3); // dd($data); // $where2 = [ // 'lereg_is'=>0, // ]; $typedata = TeacherModel::get(); // dd($typedata); return view("teacher.index",['data'=>$data,'lereg_name'=>$lereg_name]); } //删除 public function del($id){ $res = TeacherModel::where("lereg_id",$id)->update(['is_del'=>1]); if($res){ return redirect("/teacher"); }else{ return redirect("/teacher"); } } // 修改 public function upd($id){ $data = TeacherModel::where('lereg_id',$id)->first(); return view("teacher.upd",['data'=>$data]); } // 执行修改 public function update($id){ // 接收ajax传来的值 $data=request()->post(); // dd($data); // $lereg_name = request()->post('lereg_name'); // // var_dump($lereg_name); // $lereg_res = request()->lereg_res; // $lereg_id = request()->lereg_id; // $lereg_edu = request()->lereg_edu; // $lereg_school = Request()->lereg_school; // $lereg_magor = request()->lereg_magor; // $lereg_time = request()->lereg_time; // $lereg_qual = request()->lereg_qual; // $lereg_style = request()->lereg_style; // // 转化为数组 // $data = [ // 'lereg_name'=>$lereg_name, // 'lereg_res'=>$lereg_res, // 'lereg_edu'=>$lereg_edu, // 'lereg_school'=>$lereg_school, // 'lereg_magor'=>$lereg_magor, // 'lereg_qual'=>$lereg_qual, // 'lereg_time'=>$lereg_time, // 'lereg_id'=>$lereg_id, // 'lereg_style'=>$lereg_style // ]; $lereg_qual=request()->lereg_qual; //件上传验证 if(empty($lereg_qual)){ return ['code'=>0002,'msg'=>'请上传文件'];die; } $lereg_qual=$this->fileImg($lereg_qual); $data['lereg_qual']=$lereg_qual; $res = TeacherModel::where("lereg_id",$id)->update($data); // dd($res); if($res){ return ['code'=>0001]; }else{ return ['code'=>0002]; } } //图片上传处理 public function fileImg($lereg_qual){ if ($lereg_qual->isValid()){ $path = $lereg_qual->store('images'); } return $path; } // 讲师审核展示 public function indexis(){ $lereg_name = request()->lereg_name; $where = []; if($lereg_name){ $where[] = ['lereg_name','like',"%$lereg_name%"]; } $data = TeacherModel::paginate(3); // dd($data); return view('/teacher/indexis',['data'=>$data,'lereg_name'=>$lereg_name]); } // 通过讲师审核 public function tongguoshenhe(){ $lereg_id = request()->get("lereg_id"); $where = [ 'lereg_id'=>$lereg_id ]; $res = TeacherModel::where($where)->update(['lereg_is'=>1]); if($res){ echo json_encode(['code'=>0]); }else{ echo json_encode(['code'=>1]); } } //审核未通过 public function weitongguo(){ $lereg_id = request()->get("lereg_id"); $where = [ 'lereg_id'=>$lereg_id ]; $res = TeacherModel::where($where)->update(['lereg_is'=>2]); if($res){ echo json_encode(['code'=>0]); }else{ echo json_encode(['code'=>1]); } } } <file_sep><?php namespace App\Http\Controllers\Course; use App\Http\Controllers\Controller; use Illuminate\Http\Request; use App\Model\CourseModel; use App\Model\CourseChapterModel; use App\Model\CourseSectionModel; class KnobController extends Controller { /** * 节添加 */ public function create(){ //获取课程数据 $course_where=[ ['course_del','=',0], ]; $courese_data=CourseModel::select('course_id','course_name')->where($course_where)->get(); // dd($courese_data); return view('course.knob.create',compact('courese_data')); } /** * 获取章程数据 */ public function chapter(){ $course_id=request()->course_id; // dd($course_id); if(empty($course_id)){ return ['code'=>0002,'msg'=>'请先选择课程']; } //获取章程数据 $chapter_where=[ ['chapter_del','=',0], ['course_id','=',$course_id] ]; $chapter_data=CourseChapterModel::where($chapter_where)->get()->toArray(); return json_encode($chapter_data); } /** * 接确认添加 */ public function add(){ $data=request()->post(); if(empty($data['section_name'])){ return ['code'=>0002,'msg'=>'节名称不能为空'];die; } if(empty($data['course_id'])){ return ['code'=>0002,'msg'=>'请选择课程'];die; } if(empty($data['chapter_id'])){ return ['code'=>0002,'msg'=>'请选择章程'];die; } $section_name=CourseSectionModel::where('section_name',$data['section_name'])->first(); if(!empty($section_name)){ return ['code'=>0002,'msg'=>'节名称已存在']; } $data['section_add_time']=time(); $res=CourseSectionModel::insert($data); if($res){ return ['code'=>0001,'msg'=>'添加成功']; }else{ return ['code'=>0002,'msg'=>'添加失败']; } } } <file_sep><?php namespace App\Model; use Illuminate\Database\Eloquent\Model; class PowerModel extends Model { //指定表名 protected $table='online_power'; //指定主键 protected $primaryKey='pow_id'; //关闭时间戳 public $timestamps=false; } <file_sep><?php namespace App\Model; use Illuminate\Database\Eloquent\Model; class CourseTypeModel extends Model { protected $table = 'course_type'; protected $primaryKey = 'type_id'; public $timestamps = false; } <file_sep><?php namespace App\Model; use Illuminate\Database\Eloquent\Model; class ExamModel extends Model { //////表名 protected $table = 'exam'; //主键 protected $primaryKey = 'exam_id'; //时间戳 public $timestamps = false; //黑名单 用create添加的时候加黑名单 protected $guarded = []; } <file_sep><?php use Illuminate\Support\Facades\Route; /* |-------------------------------------------------------------------------- | Web Routes |-------------------------------------------------------------------------- | | Here is where you can register web routes for your application. These | routes are loaded by the RouteServiceProvider within a group which | contains the "web" middleware group. Now create something great! | */ Route::get('/', function () { return view('admin.indexs'); })->middleware('checkLogin','checkAuthority')->name('indexs'); /** * 后台登录页面 */ Route::view('login','admin/login'); /** * 执行登录 */ Route::post('loginDo','Admin\LoginController@loginDo'); /** * 退出登录 */ Route::get('loginOut','Admin\LoginController@loginOut'); /** * 后台 RBAC 模块 */ /** * 管理员管理 路由组 */ Route::prefix('admin')->middleware('checkLogin','checkAuthority')->group(function(){ //管理员展示页面 Route::get('/','Admin\AdminController@index'); //管理员添加页面 Route::get('create','Admin\AdminController@create'); //管理员名称验证唯一 Route::post('admin_name_unique','Admin\AdminController@unique'); //执行添加 Route::post('store','Admin\AdminController@store'); //编辑页面 Route::get('edit/{id}','Admin\AdminController@edit'); //修改 管理员名称验证唯一 Route::post('admin_name_unique_update/{id}','Admin\AdminController@unique_update'); //修改 Route::post('update/{id}','Admin\AdminController@update'); //删除 Route::get('destroy/{id}','Admin\RolesController@destroy'); }); /** * 角色管理 路由组 */ Route::prefix('roles')->middleware('checkLogin','checkAuthority')->group(function(){ //角色展示页面 Route::get('/','Admin\RolesController@index'); //角色添加页面 Route::get('create','Admin\RolesController@create'); //角色名称验证唯一 Route::post('ro_name_unique','Admin\RolesController@unique'); //执行添加 Route::post('store','Admin\RolesController@store'); //编辑页面 Route::get('edit/{id}','Admin\RolesController@edit'); //修改 角色名称验证唯一 Route::post('ro_name_unique_update/{id}','Admin\RolesController@unique_update'); //修改 Route::post('update/{id}','Admin\RolesController@update'); //删除 Route::get('destroy/{id}','Admin\RolesController@destroy'); }); /** * 权限管理 路由组 */ Route::prefix('power')->middleware('checkLogin','checkAuthority')->group(function(){ //权限展示页面 Route::get('/','Admin\PowerController@index'); //权限添加页面 Route::get('create','Admin\PowerController@create'); //权限名称验证唯一 Route::post('pow_name_unique','Admin\PowerController@unique'); //权限验证唯一 Route::post('pow_url_unique','Admin\PowerController@url_unique'); //执行添加 Route::post('store','Admin\PowerController@store'); //编辑页面 Route::get('edit/{id}','Admin\PowerController@edit'); //修改 权限名称验证唯一 Route::post('pow_name_unique_update/{id}','Admin\PowerController@unique_update'); //修改 权限验证唯一 Route::post('pow_url_unique_update/{id}','Admin\PowerController@url_unique_update'); //修改 Route::post('update/{id}','Admin\PowerController@update'); //删除 Route::get('destroy/{id}','Admin\PowerController@destroy'); }); /** * 管理员角色管理 路由组 */ Route::prefix('admin_role')->middleware('checkLogin','checkAuthority')->group(function(){ //管理员角色展示页面 Route::get('/','Admin\AdminRolesController@index'); //管理员角色添加页面 Route::get('create','Admin\AdminRolesController@create'); //管理员角色 验证管理员唯一 Route::post('admin_unique','Admin\AdminRolesController@admin_unique'); //执行添加 Route::post('store','Admin\AdminRolesController@store'); //编辑页面 Route::get('edit/{id}','Admin\AdminRolesController@edit'); //修改 验证管理员唯一 Route::post('admin_unique_update/{id}','Admin\AdminRolesController@admin_unique_update'); //修改 Route::post('update/{id}','Admin\AdminRolesController@update'); //删除 Route::get('destroy/{id}','Admin\AdminRolesController@destroy'); }); /** * 角色权限管理 路由组 */ Route::prefix('role_power')->middleware('checkLogin','checkAuthority')->group(function(){ //角色权限展示页面 Route::get('/','Admin\RolePowerController@index'); //角色权限添加页面 Route::get('create','Admin\RolePowerController@create'); //角色 验证唯一 Route::post('unique','Admin\RolePowerController@unique'); //执行添加 Route::post('store','Admin\RolePowerController@store'); //编辑页面 Route::get('edit/{id}','Admin\RolePowerController@edit'); //修改 验证角色唯一 Route::post('unique_update/{id}','Admin\RolePowerController@unique_update'); //修改 Route::post('update/{id}','Admin\RolePowerController@update'); //删除 Route::get('destroy/{id}','Admin\RolePowerController@destroy'); }); //课程 Route::prefix("/course")->middleware('checkLogin','checkAuthority')->group(function(){ Route::get("/create","Course\CourseController@create");//课程添加 Route::get("/addimg","Course\CourseController@addimg");//图片上传处理 Route::post("/add","Course\CourseController@add");//课程确认添加 Route::post("/chapter","Course\CourseController@chapter");//获取章程数据 Route::post("/section","Course\CourseController@section");//获取节数据 Route::post("/courseclass","Course\CourseController@courseclass");//获取课时数据 Route::get("/index","Course\CourseController@list")->name("course");//课程展示 Route::get("/del","Course\CourseController@del");//课程添加 Route::post("/addimg","Course\CourseController@addimg");//图片上传处理 Route::post("/upload","Course\CourseController@upload");//视频上传处理 Route::prefix('/type')->group(function(){ Route::get("/create","Course\CourseTypeController@create");//课程分类添加 Route::post("/add","Course\CourseTypeController@add");//课程分类确认添加 Route::get("/index","Course\CourseTypeController@index");//课程分类展示 }); Route::prefix('section')->group(function(){ Route::get("/create","Course\SectionController@create");//章程添加 Route::post("/add","Course\SectionController@add");//章程确认添加 }); Route::prefix('knob')->group(function(){ Route::get("/create","Course\KnobController@create");//节添加 Route::post("/add","Course\KnobController@add");//节确认添加 Route::post("/chapter","Course\KnobController@chapter");//获取章程数据 }); Route::prefix('hour')->group(function(){ Route::get("/create","Course\HourController@create");//课时添加 Route::post("/add","Course\HourController@add");//课时确认添加 Route::post("/chapter","Course\HourController@chapter");//获取章程数据 Route::post("/section","Course\HourController@section");//获取节数据 }); Route::prefix('/video')->group(function(){ Route::get("/create","Course\VideoController@create");//视频添加 Route::post("/add","Course\VideoController@add");//视频确认添加 }); }); //题库 Route::prefix("/question")->group(function(){ Route::get("/index","Admin\QuestionController@index")->name("question");//题库展示 Route::get("/jianindex","Admin\QuestionController@jianindex");//简答题展示 Route::get("/jianadd","Admin\QuestionController@jianadd");//简答题添加 Route::post("/jianaddo","Admin\QuestionController@jianaddo");//简答题执行添加 Route::get("/danindex","Admin\QuestionController@danindex");//单选题题展示 Route::get("/danadd","Admin\QuestionController@danadd");//单选题添加 Route::post("/danadddo","Admin\QuestionController@danadddo");//单选题执行添加 Route::post("danupdate/{id}","Admin\QuestionController@danupdate"); Route::get("/duoindex","Admin\QuestionController@duoindex");//多选题展示 Route::get("/duoadd","Admin\QuestionController@duoadd");//多选题添加 Route::post("/duoadddo","Admin\QuestionController@duoadddo");//多选题执行添加 Route::get("/del/{id}","Admin\QuestionController@del");//删除 Route::get("/upd/{id}","Admin\QuestionController@upd");//修改 Route::post("/jianupdate","Admin\QuestionController@update");//执行修改 Route::get("/huifuindex","Admin\QuestionController@huifuindex");//恢复删除页面 Route::get("/huifudel/{id}","Admin\QuestionCont roller@huifudel");//执行恢复 Route::get("/course/{id}","Admin\QuestionController@course");//关联课程 Route::get("/courses","Admin\QuestionController@courses");//四级联动查询章信息 Route::get("/sectionn","Admin\QuestionController@sectionn");//四级联动查询节数据 Route::get("/coursec","Admin\QuestionController@coursec");//四级联动查询课时数据 Route::get("/coursecreate","Admin\QuestionController@coursecreate");//关联课程执行添加 Route::post("/duoupdate","Admin\QuestionController@duoupdate");//多选题修改 Route::get("/search","Admin\QuestionController@search");// Route::get("/dancount","Admin\QuestionController@dancount");//多选题\简答题\单选题 ajax 验证题干唯一性 }); //考试模块 Route::prefix("exam")->group(function(){ Route::get("/add","Admin\ExamController@add");//添加考题 //考试展示 Route::get("/index","Admin\ExamController@index"); //执行添加 Route::post("/adddo","Admin\ExamController@adddo"); // 添加单选题 Route::get("/danadd/{id}","Admin\ExamController@danadd"); // 添加多选题 Route::get("/duoadd/{id}","Admin\ExamController@duoadd"); // 添加简答题 Route::get("/jianadd/{id}","Admin\ExamController@jianadd"); //执行添加单选题 Route::get("/danadddo","Admin\ExamController@danadddo"); Route::get("/duoadddo","Admin\ExamController@duoadddo");//添加多选题 Route::get("/jianadddo","Admin\ExamController@jianadddo");//添加简答题 Route::get("/looks/{id}","Admin\ExamController@looks");//查看考题 Route::get("/delete/{id}","Admin\ExamController@delete");//查看考题删除 Route::get("/examdel/{id}","Admin\ExamController@examdel");//停用 //启用 Route::get("/examdel2/{id}","Admin\ExamController@examdel2"); //验证名称唯一性 Route::get("/exam_name","Admin\ExamController@exam_name"); }); // 资讯模块 Route::prefix('/article')->group(function(){ //资讯展示 Route::get('/',"Admin\articleController@index")->name("atiIndexs"); //资讯添加页面 Route::get('/create',"Admin\articleController@create"); //资讯执行添加 Route::post('/story',"Admin\articleController@story"); //资讯 修改页面 Route::get('/update/{id}',"Admin\articleController@update"); //资讯 删除 Route::get('/del/{id}',"Admin\articleController@del"); //资讯 修改 Route::post('/update2/{id}',"Admin\articleController@update2"); }); //讲师模块 Route::prefix("/teacher")->middleware('checkLogin','checkAuthority')->group(function(){ //讲师 展示 Route::get("/","Admin\TeacherController@index")->name("teacher"); //讲师 删除 Route::get("/del/{id}","Admin\TeacherController@del"); //讲师 修改页面 Route::get("/upd/{id}","Admin\TeacherController@upd"); //讲师 执行修改 Route::post("/update/{id}","Admin\TeacherController@update"); Route::get("/indexis","Admin\TeacherController@indexis")->name("indexis");//讲师审核展示 Route::get("/tongguoshenhe","Admin\TeacherController@tongguoshenhe");//通过讲师审核 Route::get("/weitongguo","Admin\TeacherController@weitongguo");//未通过审核 }); <file_sep><?php namespace App\Http\Controllers\Admin; use App\Http\Controllers\Controller; use Illuminate\Http\Request; //引入角色model use App\Model\RolesModel; class RolesController extends Controller { /** * 角色展示方法 */ public function index(){ //查询 $data=RolesModel::get(); //渲染视图 return view('admin/roles/index',compact('data')); } /** * 角色添加方法 */ public function create(){ //渲染视图 return view('admin/roles/create'); } /** * 角色名称验证唯一 */ public function unique(){ //接值 $ro_name=request()->except('_token'); //查询 $count=RolesModel::where(['ro_name'=>$ro_name])->count(); //判断返回 if($count==0){ return 'ok'; }else{ return 'no'; } } /** * 角色执行添加 */ public function store(){ //接值 $data=request()->except('_token'); //验证 if(empty($data['ro_name'])){ return json_encode(['status'=>'no','field'=>'ro_name','msg'=>"<b style='color: red'>× 角色名称不可为空,请填写。</b>"]); }else{ //查询 $count=RolesModel::where(['ro_name'=>$data['ro_name']])->count(); if($count!=0){ return json_encode(['status'=>'no','field'=>'ro_name','msg'=>"<b style='color: red'>× 此角色名称已存在,请重新填写。</b>"]); } } //添加时间 $data['ro_time']=time(); //添加 $bol=RolesModel::insert($data); //判断 if($bol){ return json_encode(['status'=>"ok"]); }else{ return json_encode(['status'=>"no"]); } } /** * 编辑页面 */ public function edit($id){ //查询单条 $info=RolesModel::where(['ro_id'=>$id])->first(); //渲染视图 return view('admin/roles/edit',compact('info')); } /** * 修改时的角色名称验证唯一 */ public function unique_update($id){ //接值 $ro_name=request()->except('_token'); //where 条件 $where=[ ['ro_name','=',$ro_name], ['ro_id','!=',$id] ]; //查询 $count=RolesModel::where($where)->count(); //判断返回 if($count==0){ return 'ok'; }else{ return 'no'; } } /** * 修改 */ public function update($id){ //接值 $data=request()->except('_token'); //验证 if(empty($data['ro_name'])){ return json_encode(['status'=>'no','field'=>'ro_name','msg'=>"<b style='color: red'>× 角色名称不可为空,请填写。</b>"]); }else{ //where 条件 $where=[ ['ro_name','=',$data['ro_name']], ['ro_id','!=',$id] ]; //查询 $count=RolesModel::where($where)->count(); if($count!=0){ return json_encode(['status'=>'no','field'=>'ro_name','msg'=>"<b style='color: red'>× 此角色名称已存在,请重新填写。</b>"]); } } //添加时间 $data['ro_time']=time(); //修改 $bol=RolesModel::where('ro_id',$id)->update($data); //判断 if($bol!==false){ return json_encode(['status'=>"ok"]); }else{ return json_encode(['status'=>"no"]); } } /** * 权限删除 */ public function destroy($id){ //删除 $bol=RolesModel::where('ro_id',$id)->delete(); //判断 if($bol){ return redirect('/roles'); }else{ return redirect('/roles'); } } } <file_sep><?php namespace App\Http\Controllers\Course; use App\Http\Controllers\Controller; use Illuminate\Http\Request; use App\Model\CourseTypeModel; use App\Model\CourseModel; use App\Model\CourseClassModel; use App\Model\CourseChapterModel; use App\Model\CourseSectionModel; use App\Model\LectModel; use App\Model\VideoModel; class VideoController extends Controller { /** *视频添加 */ public function create(){ //获取课程数据 $course_where=[ ['course_del','=',0], ]; $courese_data=CourseModel::select('course_id','course_name')->where($course_where)->get(); return view('course.video.create',compact('courese_data')); } /** * 视频确认添加 */ public function add(){ $data=request()->post(); if(empty($data['course_id'])){ return ['code'=>0002,'msg'=>'请先选择课程']; } if(empty($data['chapter_id'])){ return ['code'=>0002,'msg'=>'请先选择章程']; } if(empty($data['section_id'])){ return ['code'=>0002,'msg'=>'请先选择节']; } if(empty($data['class_id'])){ return ['code'=>0002,'msg'=>'请先选择课时']; } if(empty($data['video_url'])){ return ['code'=>0002,'msg'=>'请上传视频']; } if(empty($data['video_time'])){ return ['code'=>0002,'msg'=>'请正确填写视频时长']; } $data['video_add_time']=time(); $res=VideoModel::insert($data); if($res){ return ['code'=>0001,'msg'=>'视频添加成功']; }else{ return ['code'=>0002,'msg'=>'视频添加失败']; } } } <file_sep><?php namespace App\Http\Controllers\Admin; use App\Http\Controllers\Controller; use Illuminate\Http\Request; //引入管理员model use App\Model\AdminModel; class LoginController extends Controller { /** * 执行登录 */ public function loginDo(){ //接值 $data=request()->except('_token'); //判断 if(empty($data['admin_name'])){ //返回 return json_encode(['status'=>'no','msg'=>'用户名不可为空,请填写。']); } if(empty($data['admin_pwd'])){ //返回 return json_encode(['status'=>'no','msg'=>'密码不可为空,请填写。']); } //查询 $admin_info=AdminModel::where(['admin_name'=>$data['admin_name']])->first(); //判断 if(!empty($admin_info)){ //存在 验证密码 if(password_verify($data['admin_pwd'],$admin_info->admin_pwd)){ //登录成功 //存session session(['admin_info'=>$admin_info]); //返回 return json_encode(['status'=>'ok','msg'=>'登录成功']); }else{ //登录失败 return json_encode(['status'=>'no','msg'=>'用户名或密码错误,请重新填写。']); } }else{ //不存在 return json_encode(['status'=>'no','msg'=>'用户名或密码错误,请重新填写。']); } } /** * 退出登录 */ public function loginOut(){ //清除session request()->session()->forget('admin_info'); //跳转登录页面 return redirect('login'); } } <file_sep><?php namespace App\Http\Controllers\Admin; use App\Http\Controllers\Controller; use Illuminate\Http\Request; use App\Model\QuestionModel; use App\Model\CourseModel;//课程 use App\Model\CourseClassModel;//课时表 use App\Model\CourseChapterModel;//课程章 use App\Model\CourseSectionModel;//课程节 class QuestionController extends Controller { //查询 // public function search(){ // $question_name = request()->get("question_name"); // $where = [ // 'question_name'=>$question_name // ]; // } //题库zhanshi public function dancount(){ $question_name = request()->get("question_name"); $res = QuestionModel::where("question_name",$question_name)->count(); echo $res; } public function index(){ // 搜索 $question_name = request()->get('question_name'); // dd($question_name); $wheres = []; if($question_name){ $wheres[] = ['question_name',"like","%$question_name%"]; } //查询表 $where = [ 'is_del'=>0, ]; $data = QuestionModel::leftjoin("course","question.course_id","=","course.course_id") ->leftjoin("course_section","question.section_id","=","course_section.section_id") ->leftjoin("course_class","question.class_id","=","course_class.class_id") ->leftjoin("course_chapter","question.chapter_id","=","course_chapter.chapter_id") ->where($where) ->where($wheres) ->orderBy("question_time","desc") ->paginate(5); // dd($data); // $typewhere = [ // 'question_type_id'=>2, // ]; // $typedata = QuestionModel::where($typewhere)->get(); // dd($typedata['question_cor']); // foreach ($typedata as $key => $value){ // $len = strlen($value->question_cor); // for($i=1;$i<$len;$i++){ // $str = str_split($value->question_cor); // } // } $question_cor = $data; // dd($data); return view("question.index",['data'=>$data,'question_name'=>$question_name]); } // public function danindex(){ // //单选题展示 // return view("question.danindex"); // } public function danadd(){ //单选题添加 return view("question.danadd"); } public function danadddo(Request $request){ //接值 //题目类型 $question_name = $request->post("question_name"); $question_type_id = $request->post("question_type_id"); // 题目难度 $question_diff = $request->post("question_diff"); //答案 $question_cor = $request->post("question_cor"); // dd($question_cor); //选项A内容 $cor_a = $request->post("cor_a"); // 选项B内容 $cor_b = $request->post("cor_b"); // 选项C内容 $cor_c = $request->post("cor_c"); // 选项D内容 $cor_d = $request->post("cor_d"); if(!$question_name){ echo json_encode(['code'=>1,"msg"=>"题干不可为空"]);die; } if(!$question_type_id){ echo json_encode(['code'=>1,"msg"=>"题目类型不可为空"]);die; } if(!$question_diff){ echo json_encode(['code'=>1,"msg"=>"题目难度不可为空"]);die; } if(!$question_cor){ echo json_encode(['code'=>1,"msg"=>"答案不可为空"]);die; } if(!$cor_a){ echo json_encode(['code'=>1,"msg"=>"A内容不可为空"]);die; } if(!$cor_b){ echo json_encode(['code'=>1,"msg"=>"B内容不可为空"]);die; } if(!$cor_c){ echo json_encode(['code'=>1,"msg"=>"C内容不可为空"]);die; } if(!$cor_d){ echo json_encode(['code'=>1,"msg"=>"D内容不可为空"]);die; } $questionModel = new QuestionModel(); // $questionModel->question_type_id=$question_type_id; $questionModel->question_diff=$question_diff; $questionModel->question_cor=$question_cor; $questionModel->cor_a=$cor_a; $questionModel->cor_b=$cor_b; $questionModel->cor_c=$cor_c; $questionModel->cor_d=$cor_d; $questionModel->question_name=$question_name; $questionModel->question_time=time(); $res = $questionModel->save(); if($res){ echo json_encode(['code'=>0,"msg"=>"添加成功"]);die; }else{ echo json_encode(['code'=>1,"msg"=>"添加失败"]);die; } } // public function duoindex(){ // // 多选题展示 // return view("question.duoindex"); // } public function duoadd(){ // 多选题添加 return view("question.duoadd"); } public function duoadddo(Request $request){ //接值 //题目类型 $question_name = $request->post("question_name"); $question_type_id = $request->post("question_type_id"); // 题目难度 $question_diff = $request->post("question_diff"); //答案 $question_cor = $request->post("question_cor"); $question_cor = implode(",",$question_cor); // dd($question_cor); //选项A内容 $cor_a = $request->post("cor_a"); // 选项B内容 $cor_b = $request->post("cor_b"); // 选项C内容 $cor_c = $request->post("cor_c"); // 选项D内容 $cor_d = $request->post("cor_d"); if(!$question_type_id){ echo json_encode(['code'=>1,"msg"=>"题目类型不可为空"]);die; } if(!$question_diff){ echo json_encode(['code'=>1,"msg"=>"题目难度不可为空"]);die; } if(!$question_cor){ echo json_encode(['code'=>1,"msg"=>"答案不可为空"]);die; } if(!$cor_a){ echo json_encode(['code'=>1,"msg"=>"A内容不可为空"]);die; } if(!$cor_b){ echo json_encode(['code'=>1,"msg"=>"B内容不可为空"]);die; } if(!$cor_c){ echo json_encode(['code'=>1,"msg"=>"C内容不可为空"]);die; } if(!$cor_d){ echo json_encode(['code'=>1,"msg"=>"D内容不可为空"]);die; } $questionModel = new QuestionModel(); // $questionModel->question_type_id=$question_type_id; $questionModel->question_diff=$question_diff; $questionModel->question_cor=$question_cor; $questionModel->cor_a=$cor_a; $questionModel->cor_b=$cor_b; $questionModel->cor_c=$cor_c; $questionModel->cor_d=$cor_d; $questionModel->question_name=$question_name; $questionModel->question_time=time(); $res = $questionModel->save(); if($res){ echo json_encode(['code'=>0,"msg"=>"添加成功"]);die; }else{ echo json_encode(['code'=>1,"msg"=>"添加失败"]);die; } } // public function jianindex(){ // // 简答题展示 // return view("question.jianindex"); // } public function jianadd(){ return view("question.jianadd"); } public function jianaddo(Request $request){ // 接值 //接值 //题目类型 $question_name = $request->post("question_name"); $question_type_id = $request->post("question_type_id"); // 题目难度 $question_diff = $request->post("question_diff"); //答案 $cor_a = $request->post("cor_a"); if(!$question_name){ echo json_encode(['code'=>1,"msg"=>"题目题干不可为空"]);die; } if(!$question_type_id){ echo json_encode(['code'=>1,"msg"=>"题目类型不可为空"]);die; } if(!$question_diff){ echo json_encode(['code'=>1,"msg"=>"题目难度不可为空"]);die; } if(!$cor_a){ echo json_encode(['code'=>1,"msg"=>"A内容不可为空"]);die; } $questionModel = new QuestionModel(); // $questionModel->question_type_id=$question_type_id; $questionModel->question_diff=$question_diff; $questionModel->cor_a=$cor_a; $questionModel->question_name=$question_name; $questionModel->question_time=time(); $res = $questionModel->save(); if($res){ echo json_encode(['code'=>0,"msg"=>"添加成功"]);die; }else{ echo json_encode(['code'=>1,"msg"=>"添加失败"]);die; } } //删除 public function del($id){ $res = QuestionModel::where("question_id",$id)->update(['is_del'=>1]); if($res){ return redirect("/question/index"); }else{ return redirect("/question/index"); } } // 修改 public function upd($id){ //根据id获取数据 $data = QuestionModel::where("question_id",$id)->first(); $question_type_id = $data->question_type_id; if($question_type_id==1){ return view("question.danupdate",['data'=>$data]); }else if($question_type_id==2){ $question_cor = $data['question_cor']; $question_cor = str_split($question_cor); foreach ($question_cor as $key => $value) { if($value==','){ unset($question_cor[$key]); } } // $question_cor = implode("",$question_cor); $a = $question_cor[0]; $b = $question_cor[2]; // foreach ($question_cor as $key => $value) { // $a .=$value; // $b=$value[1]; // } // dd($a); // dd($question_cor); return view("question.duoupdate",['data'=>$data,'question_cor'=>$question_cor,'a'=>$a,'b'=>$b]); }else if($question_type_id==3){ return view("question.jianupd",['data'=>$data]); } } //执行修改 public function update(Request $request){ $question_id = $request->post("question_id"); //题目类型 $question_name = $request->post("question_name"); $question_type_id = $request->post("question_type_id"); // 题目难度 $question_diff = $request->post("question_diff"); //答案 $cor_a = $request->post("cor_a"); $where = [ 'question_id'=>$question_id, ]; $data = [ 'question_name'=>$question_name, 'question_type_id'=>$question_type_id, 'question_time'=>time(), 'question_diff'=>$question_diff, 'cor_a'=>$cor_a, ]; $res = QuestionModel::where($where)->update($data); if($res!==false){ echo json_encode(['code'=>0,"msg"=>"修改成功"]); }else{ echo json_encode(['code'=>1,'msg'=>"修改失败"]); } } public function danupdate(Request $request,$id){ //接值 // echo $id; //题目类型 $question_name = $request->post("question_name"); $question_type_id = $request->post("question_type_id"); // 题目难度 $question_diff = $request->post("question_diff"); //答案 $question_cor = $request->post("question_cor"); // dd($question_cor); //选项A内容 $cor_a = $request->post("cor_a"); // 选项B内容 $cor_b = $request->post("cor_b"); // 选项C内容 $cor_c = $request->post("cor_c"); // 选项D内容 $cor_d = $request->post("cor_d"); $where = [ 'question_id'=>$id, ]; $data = [ 'question_name'=>$question_name, 'question_type_id'=>$question_type_id, 'question_time'=>time(), 'question_diff'=>$question_diff, 'question_cor'=>$question_cor, 'cor_a'=>$cor_a, 'cor_d'=>$cor_d, 'cor_c'=>$cor_c, 'cor_b'=>$cor_b ]; $res = QuestionModel::where($where)->update($data); if($res!==false){ echo json_encode(['code'=>0,"msg"=>"修改成功"]); }else{ echo json_encode(['code'=>1,'msg'=>"修改失败"]); } } // 恢复删除页面 public function huifuindex(){ $where = [ 'is_del'=>1 ]; $data = QuestionModel::where($where)->get(); return view("question.huifudel",['data'=>$data]); } //执行恢复 public function huifudel($id){ $where = [ 'is_del'=>0, ]; $wheres = [ 'question_id'=>$id ]; $res = QuestionModel::where($wheres)->update($where); if($res){ return redirect("/question/index"); }else{ return redirect("/question/index"); } } public function course($id){ //课程 $course = CourseModel::select('course_id',"course_name")->get(); // 章 $course_chapter = CourseChapterModel::select("chapter_id","chapter_name")->get(); // 节 $course_section = CourseSectionModel::select("section_id","section_name")->get(); // 课时 $course_class = CourseClassModel::select("class_id","class_name")->get(); return view("question.course",['question_id'=>$id,'course'=>$course,'chapter'=>$course_chapter,'section'=>$course_section,'class'=>$course_class]); } public function courses(){ $course_id = request()->get("course_id"); // 根据课程id查询课程章 $where = [ 'course_id'=>$course_id ]; $course_chapter = CourseChapterModel::where($where)->get(); // echo json_encode(['data'=>$course_chapter]); return response()->json($course_chapter); } public function sectionn(){ $chapter_id = request()->get("chapter_id"); $where = [ 'chapter_id'=>$chapter_id ]; $section = CourseSectionModel::where($where)->get(); return response()->json($section); } public function coursec(){ $section_id = request()->get("section_id"); $where = [ 'section_id'=>$section_id ]; $class = CourseClassModel::where($where)->get(); return response()->json($class); } public function coursecreate(Request $request){ $course_id = $request->get("course_id"); $chapter_id = $request->get("chapter_id"); $section_id = $request->get("section_id"); $class_id = $request->get("class_id"); $question_id = $request->get("question_id"); $question = new QuestionModel(); $data = [ 'course_id'=>$course_id, 'chapter_id'=>$chapter_id, 'section_id'=>$section_id, 'class_id'=>$class_id ]; $where = [ 'question_id'=>$question_id ]; $res = QuestionModel::where($where)->update($data); if($res){ echo json_encode(['code'=>0,'msg'=>"ok"]); }else{ echo json_encode(['code'=>1,'msg'=>"no"]); } } public function duoupdate(Request $request){ $question_id = $request->post("question_id"); $question_name = $request->post("question_name"); $question_type_id = $request->post("question_type_id"); // 题目难度 $question_diff = $request->post("question_diff"); //答案 $question_cor = $request->post("question_cor"); $question_cor = implode(",",$question_cor); // dd($question_cor); //选项A内容 $cor_a = $request->post("cor_a"); // 选项B内容 $cor_b = $request->post("cor_b"); // 选项C内容 $cor_c = $request->post("cor_c"); // 选项D内容 $cor_d = $request->post("cor_d"); $where = [ 'question_id'=>$question_id ]; $data = [ 'question_name'=>$question_name, 'question_type_id'=>$question_type_id, 'question_diff'=>$question_diff, 'question_cor'=>$question_cor, 'cor_a'=>$cor_a, 'cor_b'=>$cor_b, 'cor_c'=>$cor_c, 'cor_d'=>$cor_d ]; $res = QuestionModel::where($where)->update($data); if($res!==false){ echo json_encode(['code'=>0,"msg"=>"修改成功"]); }else{ echo json_encode(['code'=>1,'msg'=>"修改失败"]); } } }<file_sep><?php namespace App\Http\Controllers\Admin; use App\Http\Controllers\Controller; use Illuminate\Http\Request; use App\Model\QuestionModel; use App\Model\CourseModel;//课程 use App\Model\CourseClassModel;//课时表 use App\Model\CourseChapterModel;//课程章 use App\Model\CourseSectionModel;//课程节 use App\Model\ExamModel; use App\Model\ExamQuestionModel; class ExamController extends Controller { // public function index(){ $data = ExamModel::paginate(7); //获取到分数 // $score = ExamQuestionModel::select("score")->get(); // $zong_score = ""; // // dd($score['score']); // foreach($score as $k=>$v){ // // dd($v); // $boor = integer($v['score']); // $zong_score += $boor; // } // dd($zong_score); return view("exam.index",['data'=>$data]); } public function add(){ //查询题库表 单选题 多选题 简答题并给相应的分数 来作为考试选题的下拉框 return view("exam.add"); } public function adddo(){ $exam_name = request()->post("exam_name"); $start_time = request()->post("start_time"); $end_time = request()->post("end_time"); if(!$exam_name){ echo json_encode(['code'=>1,'msg'=>'题干不可为空']);die; } if(!$start_time){ echo json_encode(['code'=>1,'msg'=>'开始时间不可为空']);die; } if(!$end_time){ echo json_encode(['code'=>1,'msg'=>'结束时间不可为空']);die; } $exam = new ExamModel(); $exam->exam_name = $exam_name; $exam->start_time=$start_time; $exam->end_time=$end_time; $exam->is_del=0; $res = $exam->save(); if($res){ echo json_encode(['code'=>0,'msg'=>'添加成功']); }else{ echo json_encode(['code'=>1,'msg'=>"添加失败"]); } } public function danadd($exam_id){ // echo $exam_id; $danwhere = [ 'question_type_id'=>1 ]; $dan = QuestionModel::where($danwhere)->get(); return view("exam.danadd",['dan'=>$dan,'exam_id'=>$exam_id]); } public function duoadd($exam_id){ $duowhere = [ 'question_type_id'=>2 ]; $duo = QuestionModel::where($duowhere)->get(); return view("exam.duoadd",['duo'=>$duo,'exam_id'=>$exam_id]); } public function jianadd($exam_id){ $jianwhere = [ 'question_type_id'=>3 ]; $jian = QuestionModel::where($jianwhere)->get(); return view("exam.jianadd",['jian'=>$jian,'exam_id'=>$exam_id]); } public function danadddo(){ $question_id = request()->get("question_id"); $exam_id = request()->get("exam_id"); $ExamQuestionModel = new ExamQuestionModel(); $ExamQuestionModel->question_id=$question_id; $ExamQuestionModel->exam_id=$exam_id; $ExamQuestionModel->eq_time = time(); $ExamQuestionModel->score=3; $res = $ExamQuestionModel->save(); if($res){ echo json_encode(['code'=>0]); }else{ echo json_encode(['code'=>1]); } } public function duoadddo(){ $question_id = request()->get("question_id"); $exam_id = request()->get("exam_id"); $ExamQuestionModel = new ExamQuestionModel(); $ExamQuestionModel->question_id=$question_id; $ExamQuestionModel->exam_id=$exam_id; $ExamQuestionModel->eq_time = time(); $ExamQuestionModel->score=4; $res = $ExamQuestionModel->save(); if($res){ echo json_encode(['code'=>0]); }else{ echo json_encode(['code'=>1]); } } public function jianadddo(){ $question_id = request()->get("question_id"); $exam_id = request()->get("exam_id"); $ExamQuestionModel = new ExamQuestionModel(); $ExamQuestionModel->question_id=$question_id; $ExamQuestionModel->exam_id=$exam_id; $ExamQuestionModel->eq_time = time(); $ExamQuestionModel->score=5; $res = $ExamQuestionModel->save(); if($res){ echo json_encode(['code'=>0]); }else{ echo json_encode(['code'=>1]); } } public function looks($exam_id){ $where = [ 'exam.exam_id'=>$exam_id ]; $data = ExamQuestionModel::where($where) ->leftjoin("exam","exam_question.exam_id","=","exam.exam_id") ->leftjoin("question","exam_question.question_id","=","question.question_id") ->paginate(5); return view("exam.questionindex",['data'=>$data]); } public function delete($id){ $where = [ 'eq_id'=>$id ]; $res = ExamQuestionModel::where($where)->delete(); if($res){ return redirect("/exam/index"); }else{ return redirect("/exam/index"); } } public function examdel($exam_id){ $where = [ 'exam_id'=>$exam_id ]; $res = ExamModel::where($where)->update(['is_del'=>1]); if($res){ return redirect("/exam/index"); }else{ return redirect("/exam/index"); } } public function examdel2($exam_id){ $where = [ 'exam_id'=>$exam_id ]; $res = ExamModel::where($where)->update(['is_del'=>0]); if($res){ return redirect("/exam/index"); }else{ return redirect("/exam/index"); } } public function exam_name(){ $exam_name=request()->get("exam_name"); $res = ExamModel::where("exam_name",$exam_name)->count(); echo $res; } } <file_sep><?php namespace App\Http\Controllers\Admin; use App\Http\Controllers\Controller; use Illuminate\Http\Request; //引入管理员model use App\Model\AdminModel; //引入角色model use App\Model\RolesModel; //引入管理员角色 model use App\Model\AdminRolesModel as AR; class AdminRolesController extends Controller { /** * 管理员角色展示方法 */ public function index(){ //查询 $data=AR::select('online_admin_role.*','admin_name') ->leftjoin('online_admin','online_admin_role.admin_id','=','online_admin.admin_id') ->where(['ar_del'=>0]) ->get(); //循环获取角色名称 foreach($data as $k=>$v){ //切割 $ro_id=explode(',',$v->ro_id); //循环查询角色名称 foreach($ro_id as $k1=>$v1){ $v->ro_name.=RolesModel::where('ro_id',$v1)->value('ro_name').','; } //去除多余字符 $v->ro_name=substr($v->ro_name,0,strlen($v->ro_name)-1); } //渲染视图 return view('admin/admin_roles/index',compact('data')); } /** * 管理员角色添加方法 */ public function create(){ //查询管理员 $admin_data=AdminModel::where(['admin_del'=>0])->get(); //查询角色 $roles_data=RolesModel::get(); //渲染视图 return view('admin/admin_roles/create',compact('admin_data','roles_data')); } /** * 管理员角色 验证管理员唯一 */ public function admin_unique(){ //接收管理员id $admin=request()->except('_token'); //查询 $admin_id=AR::where(['admin_id'=>$admin,'ar_del'=>0])->count(); //判断 if($admin_id==0){ //返回 return json_encode(["status"=>"ok"]); }else{ //返回 return json_encode(['status'=>'no']); } } /** * 执行添加 */ public function store(){ //接值 $data=request()->except('_token'); //判断 if(empty($data['admin_id'])){ //返回 return json_encode(['status'=>'fail','field'=>'admin','msg'=>'<b style="color: red">× 请选择管理员。</b>']); }else{ //验证唯一 $admin_id=AR::where(['admin_id'=>$data['admin_id'],'ar_del'=>0])->count(); //判断 if($admin_id!=0){ //返回 return json_encode(['status'=>'fail','field'=>'admin','msg'=>'<b style="color: red">× 该管理员已存在,请重新选择。</b>']); } } if(empty($data['ro_id'])){ //返回 return json_encode(['status'=>'fail','field'=>'ro','msg'=>'<b style="color: red">× 请选择角色</b>']); } //添加时间 $data['ar_time']=time(); //添加 $bol=AR::insert($data); //判断 if($bol){ //成功返回 return json_encode(['status'=>'ok']); }else{ //失败返回 return json_encode(['status'=>'no']); } } /** * 编辑页面 */ public function edit($id){ //查询管理员 $admin_data=AdminModel::where(['admin_del'=>0])->get(); //查询角色 $roles_data=RolesModel::get(); //查询当前数据 $info=AR::where('ar_id',$id)->first(); //处理角色id $info->ro_id=explode(',',$info->ro_id); //渲染视图 return view('admin/admin_roles/edit',compact('admin_data','roles_data','info')); } /** * 修改 验证管理员 */ public function admin_unique_update($id){ //接收管理员id $admin_id=request()->except('_token'); //where 条件 $where=[ ['admin_id','=',$admin_id], ['ar_id','!=',$id], ['ar_del','=',0] ]; //查询 $admin_id=AR::where($where)->count(); //判断 if($admin_id==0){ //返回 return json_encode(["status"=>"ok"]); }else{ //返回 return json_encode(['status'=>'no']); } } /** * 修改 */ public function update($id){ //接值 $data=request()->except('_token'); //判断 if(empty($data['admin_id'])){ //返回 return json_encode(['status'=>'fail','field'=>'admin','msg'=>'<b style="color: red">× 请选择管理员。</b>']); }else{ //where 条件 $where=[ ['admin_id','=',$data['admin_id']], ['ar_id','!=',$id], ['ar_del','=',0] ]; //验证唯一 $admin_id=AR::where($where)->count(); //判断 if($admin_id!=0){ //返回 return json_encode(['status'=>'fail','field'=>'admin','msg'=>'<b style="color: red">× 该管理员已存在,请重新选择。</b>']); } } if(empty($data['ro_id'])){ //返回 return json_encode(['status'=>'fail','field'=>'ro','msg'=>'<b style="color: red">× 请选择角色</b>']); } //添加时间 $data['ar_time']=time(); //添加 $bol=AR::where('ar_id',$id)->update($data); //判断 if($bol!==false){ //成功返回 return json_encode(['status'=>'ok']); }else{ //失败返回 return json_encode(['status'=>'no']); } } /** * 删除 */ public function destroy($id){ //删除 修改状态值 $bol=AR::where('ar_id',$id)->update(['ar_del'=>1]); //判断 if($bol!==false){ return redirect('/admin_role'); }else{ return redirect('/admin_role'); } } } <file_sep><?php namespace App\Model; use Illuminate\Database\Eloquent\Model; class ArticleModel extends Model { //指定表名 protected $table='article'; //指定主键 protected $primaryKey='ati_id'; //关闭时间戳 public $timestamps=false; } <file_sep><?php namespace App\Http\Controllers\Course; use App\Http\Controllers\Controller; use Illuminate\Http\Request; use App\Model\CourseTypeModel; use App\Model\CourseModel; use App\Model\CourseClassModel; use App\Model\CourseChapterModel; use App\Model\CourseSectionModel; use App\Model\LectModel; class CourseController extends Controller { /** * 课程添加页面 */ public function create(){ //查询课程分类信息 $type_data=CourseTypeModel::select('type_id','type_name')->get(); //查询讲师信息 $lect_data=LectModel::select('lect_id','lect_name')->get(); return view('course.create',compact('type_data','lect_data')); } /** * 课程确认添加 */ public function add(){ $data=request()->except('_token'); //唯一验证 $name_data=CourseModel::where('course_name',$data['course_name'])->first(); if(!empty($name_data)){ return ['code'=>0003,'msg'=>'课程名称已存在'];die; } $file = request()->file('course_img'); //文件上传验证 if(empty($file)){ return ['code'=>0002,'msg'=>'请上传文件'];die; } $fileImg=$this->fileImg($file); $data['course_add_time']=time(); $data['course_img']=$fileImg; $res=CourseModel::insert($data); if($res){ return ['code'=>0001,'msg'=>'添加成功']; }else{ return ['code'=>0002,'msg'=>'添加失败']; } } /** * 课程列表页面 */ public function list(){ $course_where=[ ['course_del','=',0] ]; $course_data=CourseModel::leftjoin('course_type','course.course_type','=','course_type.type_id')->leftjoin('lect','course.lect_id','=','lect.lect_id')->where($course_where)->get(); return view('course.list',compact('course_data')); } //图片上传处理 public function fileImg($file){ if ($file->isValid()){ $path = $file->store('images'); } return $path; } /** * 获取章程数据 */ public function chapter(){ $course_id=request()->course_id; if(empty($course_id)){ return ['code'=>0002,'msg'=>'请先选择课程']; } //获取章程数据 $chapter_where=[ ['chapter_del','=',0], ['course_id','=',$course_id] ]; $chapter_data=CourseChapterModel::where($chapter_where)->get()->toArray(); return json_encode($chapter_data); } /** * 获取节数据 */ public function section(){ $chapter_id=request()->chapter_id; if(empty($chapter_id)){ return ['code'=>0002,'msg'=>'请先选择章程'];die; } //获取章程数据 $section_where=[ ['section_del','=',0], ['chapter_id','=',$chapter_id] ]; $section_data=CourseSectionModel::where($section_where)->get()->toArray(); // dd($section_data); return json_encode($section_data); } /** * 获取课时数据 */ public function courseclass(){ $section_id=request()->section_id; if(empty($section_id)){ return ['code'=>0002,'msg'=>'请先选择节'];die; } //获取章程数据 $class_where=[ ['class_del','=',0], ['section_id','=',$section_id] ]; $class_data=CourseClassModel::where($class_where)->get()->toArray(); // dd($class_data); return json_encode($class_data); } public function del(){ $course_id=request()->course_id; //判断删除的课程下是否有章程 $chapter_data=CourseChapterModel::where('course_id',$course_id)->first(); // dd($chapter_data); if(!empty($chapter_data)){ return ['code'=>0002,'msg'=>'本课程下有章程,不可以删除'];die; } //逻辑删 $res=CourseModel::where('course_id',$course_id)->update(['course_del'=>1]); if($res){ return ['code'=>0001,'msg'=>'删除成功']; }else{ return ['code'=>0002,'msg'=>'删除失败']; } } /** * 视频上传处理 */ public function upload(){ $filePath = "./imgs"; $baseFileName = $_REQUEST['filename']; $ext = explode(".",$baseFileName)[1]; $fileName=explode(".",$baseFileName)[0]; $arr = $_FILES['page']; $tmpName = $arr['tmp_name']; $content = file_get_contents($tmpName); $fileName = $filePath."/{$fileName}.{$ext}"; $path=trim($fileName,'.'); // dd($path); // dd($fileName); file_put_contents($fileName,$content,FILE_APPEND); $arr = array( 'error'=>0, 'path'=>$path, 'type'=>$ext ); echo json_encode($arr); } // function post($url, $params = false, $header = array()){ // $ch = curl_init(); // $cookieFile = 'sdadsd_cookiejar.txt'; // curl_setopt($ch, CURLOPT_POST, 1); // curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 60); // curl_setopt($ch, CURLOPT_COOKIEJAR, $cookieFile); // curl_setopt($ch, CURLOPT_COOKIEFILE,$cookieFile); // curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); // curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1); // curl_setopt($ch, CURLOPT_SSL_VERIFYPEER,FALSE); // curl_setopt($ch, CURLOPT_HTTPGET, true); // curl_setopt($ch, CURLOPT_TIMEOUT, 30); // if($params !== false){ curl_setopt($ch, CURLOPT_POSTFIELDS , $params);} // curl_setopt($ch, CURLOPT_USERAGENT,'Mozilla/5.0 (Windows NT 5.1; rv:21.0) Gecko/20100101 Firefox/21.0'); // curl_setopt($ch, CURLOPT_URL,$url); // curl_setopt($ch, CURLOPT_HTTPHEADER, $header); // $result = curl_exec($ch); // curl_close($ch); // return $result; // } // public function addimg(){ // $arr = $_FILES["Filedata"]; // $tmpName = $arr['tmp_name']; // $ext = explode(".",$arr['name'])[1]; // $newFileName = md5(time()).".".$ext; // $newFilePath = "./uploads/".$newFileName; // move_uploaded_file($tmpName, $newFilePath); // $newFilePath = trim($newFilePath,"."); // echo $newFilePath; // } } <file_sep><?php namespace App\Model; use Illuminate\Database\Eloquent\Model; class AdminModel extends Model { //指定表名 protected $table='online_admin'; //指定主键 protected $primaryKey='admin_id'; //关闭时间戳 public $timestamps=false; } <file_sep><?php namespace App\Http\Controllers\Course; use App\Http\Controllers\Controller; use Illuminate\Http\Request; use App\Model\CourseModel; use App\Model\CourseTypeModel; use App\Model\CourseChapterModel; use App\Model\CourseSectionModel; class SectionController extends Controller { /** * 章程添加 */ public function create(){ //获取所有课程 $course_where=[ ['course_del','=',0] ]; $course_data=CourseModel::select('course_id','course_name')->where($course_where)->get(); return view('course.section.create',compact('course_data')); } /** * 章程确认添加 */ public function add(){ $data=request()->post(); if(empty($data['chapter_name'])){ return ['code'=>0002,'msg'=>'章程名称不能为空'];die; } if(empty($data['course_id'])){ return ['code'=>0002,'msg'=>'请选择所属课程'];die; } $chapter_data=CourseChapterModel::where('chapter_name',$data['chapter_name'])->first(); if(!empty($chapter_data)){ return ['code'=>0002,'msg'=>'章程名称已存在']; } $data['chapter_add_time']=time(); $res=CourseChapterModel::insert($data); if($res){ return ['code'=>0001,'msg'=>'添加成功']; }else{ return ['code'=>0002,'msg'=>'添加失败']; } } }
70cc34e8ce4ab7f8e5a7d0a7a2479bcad2942eec
[ "PHP" ]
23
PHP
lv-xiaoyang/online_admin
1ce60c93fa0cb35e85ce6aeb2dcc521df100420f
2202371a97f135eada7a65b42946c5733949b102
refs/heads/master
<repo_name>pahirampascual/backup-mainProject<file_sep>/resources/js/frontend/media.js function myFunction (x) { if (x.matches) { // If media query matches document.getElementById("quicklinks-jobs").style.display = "none"; document.getElementById("showthissponsor").style.display = "block"; // document.body.style.backgroundColor = "black"; } else { document.getElementById("quicklinks-jobs").style.display = "block"; document.getElementById("showthissponsor").style.display = "none"; } } var x = window.matchMedia("(max-width: 700px)") myFunction(x) // Call listener function at run time x.addListener(myFunction) function showonly (y) { if (y.matches) { // If media query matches document.getElementById("sponsored").style.display = "none"; // document.body.style.backgroundColor = "black"; } else { document.getElementById("sponsored").style.display = "block"; } } var y = window.matchMedia("(max-width: 700px)") showonly(y) // Call listener function at run time y.addListener(showonly) $('#blogCarousel').carousel({ interval: 5000 });<file_sep>/app/Http/Controllers/CategoriesController.php <?php namespace App\Http\Controllers; use Illuminate\Http\Request; class CategoriesController extends Controller { // public function categoriesPage() { return view('contents/categories'); } } <file_sep>/public/js/scripts.js $(document).on('click', '#following', function(){ var sortFollowing = document.getElementById("following"); var sortGlobal = document.getElementById("global"); sortFollowing.classList.remove("sortFF-btn"); sortFollowing.classList.add("sortGlobal-btn"); sortGlobal.classList.remove("sortGlobal-btn"); sortGlobal.classList.add("sortFF-btn"); }); $(document).on('click', '#global', function(){ var sortFollowing = document.getElementById("following"); var sortGlobal = document.getElementById("global"); sortGlobal.classList.remove("sortFF-btn"); sortGlobal.classList.add("sortGlobal-btn"); sortFollowing.classList.remove("sortGlobal-btn"); sortFollowing.classList.add("sortFF-btn"); });<file_sep>/resources/js/frontend/profile-scripts.js // -------------------------BERNA SCRIPT START'S HERE // retrieve $(document).on('click', '.item-rm', function(){ confirm("Are you sure you want to remove this item?\n"); }); // tooltip $(document).ready(function(){ $('[data-toggle="tooltip"]').tooltip(); }); // profile navigation window.profileNavigation = function (evt, tabName) { var i, x, tablinks; x = document.getElementsByClassName("profileTab"); for (i = 0; i < x.length; i++) { x[i].style.display = "none"; } tablinks = document.getElementsByClassName("tablink"); for (i = 0; i < x.length; i++) { tablinks[i].className = tablinks[i].className.replace(" on-active", ""); } document.getElementById(tabName).style.display = "block"; evt.currentTarget.className += " on-active"; } $(document).on('click', '#oldest', function(){ var sortOff = document.getElementById("oldest"); var sortOn = document.getElementById("latest"); sortOff.classList.remove("sortOff-btn"); sortOff.classList.add("sortOn-btn"); sortOn.classList.remove("sortOn-btn"); sortOn.classList.add("sortOff-btn"); }); $(document).on('click', '#latest', function(){ var sortOff = document.getElementById("oldest"); var sortOn = document.getElementById("latest"); sortOn.classList.remove("sortOff-btn"); sortOn.classList.add("sortOn-btn"); sortOff.classList.remove("sortOn-btn"); sortOff.classList.add("sortOff-btn"); }); window.readURL = function (input) { if (input.files && input.files[0]) { var reader = new FileReader(); reader.onload = function (e) { $('#blah') .css("background", "linear-gradient(rgba(0, 0, 0, 0.8), rgba(0, 0, 0, .8)),url('"+e.target.result+"')"); }; reader.readAsDataURL(input.files[0]); } } window.readURLPROF = function (input) { if (input.files && input.files[0]) { var reader = new FileReader(); reader.onload = function (e) { $('#prof') .attr('src', e.target.result) .width(188) .height(187); }; reader.readAsDataURL(input.files[0]); } } $(document).on('click', '#OpenImgUpload', function(){ var coverIMG = document.getElementById("blah").src; $('#imgupload').trigger('click'); $('#OpenImgUpload').hide(); $('.img-cclose').show(); $('.img-close').hide(); $('#OpenImgUpload1').show(); }); $('#OpenImgUpload1').click(function(){ location.reload(); }); $(document).on('click', '#OpenImgUploadPROF', function(){ var profIMG = document.getElementById("prof").src; $('#imguploadPROF').trigger('click'); $('#OpenImgUpload').hide(); $('#save_prof').show(); $('.img-cclose').show(); $('#OpenImgUpload1').show(); }); $('.img-cclose').hide(); $('.img-close').hide(); $('#OpenImgUpload123').hide(); $('#OpenImgUpload1').hide(); $('#save_prof').hide(); window.textAreaAdjust = function (o) { o.style.height = "1px"; o.style.height = (25+o.scrollHeight)+"px"; } // -------------------------BERNA SCRIPT END'S HERE
0f528b7b4cde6e05b370a98afc8293a3e5cf210e
[ "JavaScript", "PHP" ]
4
JavaScript
pahirampascual/backup-mainProject
00c32ca509b5160634f3e4424661f79a795b3cc6
8f0b9baa1175cf1568cced50cf3daf7672fc9cca
refs/heads/master
<repo_name>nofate/icfp2011<file_sep>/dummy #!/bin/sh scala name.nofate.icfp2011.DummyBotApp $1<file_sep>/run #!/bin/sh scala name.nofate.icfp2011.BotApp $1
c4a2eb7029d6ad25a10289bfc6a32a0c611866ae
[ "Shell" ]
2
Shell
nofate/icfp2011
87f86d7b9a9a86513bcff7183b1cab038130a0a6
ef63ab4ca03bc172875fb01cfb8365e57fc3af87
refs/heads/main
<repo_name>Piyush-Singhania/Project-Planner<file_sep>/README.md # project-planner ## Url to visit and test https://projectsplanner.netlify.app/ ## Stack Used ``` html, css, js, vue.js ``` ## Description ``` A task creating and managing web app (todo) build using Vue.js and firebase firestore as the database to store all your tasks. ``` ## Project setup ``` npm install ``` ### Compiles and hot-reloads for development ``` npm run serve ``` ### Compiles and minifies for production ``` npm run build ``` ### Customize configuration See [Configuration Reference](https://cli.vuejs.org/config/). <file_sep>/src/firebase/config.js import firebase from "firebase/app"; import "firebase/firestore"; const firebaseConfig = { apiKey: "AIzaSyAc3INE-MtOC56nGONt9y1KdSrEQjwCbYw", authDomain: "vue-3-projects.firebaseapp.com", projectId: "vue-3-projects", storageBucket: "vue-3-projects.appspot.com", messagingSenderId: "79712493233", appId: "1:79712493233:web:db1cf4c07fcdb8099c0c90", }; //Initialize firebase firebase.initializeApp(firebaseConfig); const projectFirestore = firebase.firestore(); const timestamp = firebase.firestore.FieldValue.serverTimestamp; export { projectFirestore, timestamp };
7b91bb9d2b31215e859f403a6a2a7634029c944a
[ "Markdown", "JavaScript" ]
2
Markdown
Piyush-Singhania/Project-Planner
e63c1b7ac93451136ab284177fbf4ed3fe231dd5
4f45b3e18bed5223c5cceb7c172813dff2e3f543
refs/heads/master
<file_sep>import matplotlib import matplotlib.pyplot as plt def plot_trended_study_time(df, num_date_labels=8): fig, ax = plt.subplots(figsize=(16, 10)) ax.scatter(df["date"], df["seconds"], alpha=0.5, s=10) xlim = ax.get_xlim() loc_interval = int((xlim[1] - xlim[0]) / num_date_labels) loc = matplotlib.ticker.MultipleLocator(loc_interval) ax.xaxis.set_major_locator(loc) loc = matplotlib.ticker.MultipleLocator(60 * 60) ax.yaxis.set_major_locator(loc) loc = matplotlib.ticker.MultipleLocator(30 * 60) ax.yaxis.set_minor_locator(loc) def minutes(x, pos): return "{:,.1f}".format(x / 60) fmtr = matplotlib.ticker.FuncFormatter(minutes) _ = ax.yaxis.set_major_formatter(fmtr) ax.plot( df["date"], df["seconds"].rolling(window=7, center=False).mean(), c="r", label="7 day rolling avg", ) ax.plot( df["date"], df["seconds"].rolling(window=30, center=False).mean(), c="g", label="30 day rolling avg", ) ax.legend(loc="upper left", fontsize=12) ax.grid(True, "major", axis="y", c="k") ax.grid(True, "minor", axis="y", alpha=0.5) ax.set_title("Minutes Spent Studying", fontsize=20) return ax def plot_card_catalog_growth(df, num_date_labels=8): fig, ax = plt.subplots(figsize=(16, 10)) ax.stackplot( df.index, [ df["> year"], df["< year"], df["< month"], df["< 6 months"], df["< week"], df["due"], ], labels=["> year", "< year", "< 6 months", "< month", "< week", "due"], colors=["#309143", "#51b364", "#8ace7e", "#f0bd27", "#ff684c", "b60a1c"], ) ax.legend(loc="upper left", fontsize=12) ax.set_title("Card Growth By Ease", fontsize=20) xlim = ax.get_xlim() loc_interval = int((xlim[1] - xlim[0]) / num_date_labels) loc = matplotlib.ticker.MultipleLocator(loc_interval) ax.xaxis.set_major_locator(loc) return ax <file_sep>report: jupyter nbconvert --execute --to=html anki_progress.ipynb <file_sep>""" Utilities for extracting and cleaning our Anki data This README of schema definitions was super helpful in constructing these functions https://github.com/ankidroid/Anki-Android/wiki/Database-Structure """ import sqlite3 from contextlib import contextmanager from datetime import datetime, timedelta from itertools import zip_longest from typing import Dict, List import pandas as pd DB_PATH = "C:/Users/Nick/AppData/Roaming/Anki2/Nick/" @contextmanager def connect_to_db(database: str): path = DB_PATH conn = sqlite3.connect(path + database) cur = conn.cursor() yield cur conn.commit() conn.close() def get_study_time() -> pd.DataFrame: """ Get the number of seconds spent studying per day. Gets the min date and the max date from the data and fills with 0s where appropriate. """ sql = """ SELECT strftime('%Y-%m-%d', datetime(round(id / 1000), 'unixepoch', 'localtime')) as review_date, sum(time / 1000.0) as seconds from revlog group by review_date order by review_date """ with connect_to_db("collection.anki2") as cursor: cursor.execute(sql) records = cursor.fetchall() populated_df = pd.DataFrame( {"date": [x[0] for x in records], "seconds": [x[1] for x in records]} ) populated_df["date"] = pd.to_datetime(populated_df["date"]) min_date = populated_df["date"].min() max_date = populated_df["date"].max() every_day_series = pd.date_range(min_date, max_date) every_day_frame = every_day_series.to_frame(name="date") merged = every_day_frame.merge( populated_df, left_index=True, right_on="date", how="left" ) del merged["date_x"] del merged["date_y"] merged = merged.fillna(0) merged = merged.reset_index(drop=True) return merged def get_reviewed_cards() -> List[int]: """ Query all cards that appear in the review log table and also have a valid card id (not deleted) """ sql = """ select distinct r.cid from revlog r left join cards c on c.id = r.cid where r.ivl > 0 and c.id is not null """ with connect_to_db("collection.anki2") as cursor: cursor.execute(sql) reviewed_cards = [x[0] for x in cursor.fetchall()] return reviewed_cards def get_card_status_by_day(card_id: int) -> pd.DataFrame: """ From the first day we've reviewed it to today, what status ('hard', 'good', 'easy', 'due') was each card in? """ sql = f""" select cid, strftime('%Y-%m-%d', datetime(id / 1000, 'unixepoch', 'localtime')), ivl from revlog where cid = {card_id} and ivl > 0 """ card_statuses = dict() with connect_to_db("collection.anki2") as cursor: cursor.execute(sql) data = cursor.fetchall() # look at pairs of days until there are no more, # fill with today when we run out of values to_datetime = lambda x: datetime(*map(int, x.split("-"))) row_a = [(to_datetime(date), delta) for _, date, delta in data] row_b = row_a[1:] for pair in zip_longest(row_a, row_b, fillvalue=(datetime.now(), 0)): (review_date, delta), (next_review_date, _) = pair due_date = review_date + timedelta(days=delta) days_to_next_review = (next_review_date - review_date).days for day in range(days_to_next_review): date = review_date + timedelta(days=day) date_str = datetime.strftime(date, "%Y-%m-%d") past_due = date > (due_date) if past_due: card_statuses[date_str] = "due" else: if delta < 7: card_statuses[date_str] = "< week" elif delta < 30: card_statuses[date_str] = "< month" elif delta < 180: card_statuses[date_str] = "< 6 months" elif delta < 365: card_statuses[date_str] = "< year" else: card_statuses[date_str] = "> year" df = pd.DataFrame( { "card_id": card_id, "date": list(card_statuses.keys()), "status": list(card_statuses.values()), } ) return df def get_all_card_statuses_by_day() -> pd.DataFrame: reviewed_cards = get_reviewed_cards() dfs = [] for card_id in reviewed_cards: dfs.append(get_card_status_by_day(card_id)) df = pd.concat(dfs).reset_index(drop=True) return df
51ee3c94c9656c486d4676285a84cd5f8544a504
[ "Python", "Makefile" ]
3
Python
NapsterInBlue/anki_progress
a900266b4bb5594faf0bce17fde472724a3fdd47
2d7648050afdd7d82bca31f3ada780c4d1233fa3
refs/heads/master
<repo_name>Nik3991/base_data_structures<file_sep>/ds/Stack.h #ifndef STACK_H #define STACK_H #include <iostream> using namespace std; template <typename T> class Stack { struct Node { Node(T _value, Node* _next_ptr = nullptr) : m_value(move(_value)), m_next_ptr(_next_ptr) {} T m_value; Node* m_next_ptr; }; public: Stack() : m_size(0) {} void push(T _value) { Node* new_node_ptr = new Node(_value); new_node_ptr->m_next_ptr = m_first_ptr; m_first_ptr = new_node_ptr; ++m_size; } T pop() { if (m_size) { T value = m_first_ptr->m_value; Node* tmp_node_ptr = m_first_ptr->m_next_ptr; delete m_first_ptr; m_first_ptr = tmp_node_ptr; --m_size; return value; } else { // size == 0 throw out_of_range("stack size == 0"); } } size_t size() { return m_size; } ~Stack() { Node* current_node_ptr = m_first_ptr; while (current_node_ptr) { Node* tmp_ptr = current_node_ptr->m_next_ptr; delete current_node_ptr; current_node_ptr = tmp_ptr; } } private: size_t m_size; Node* m_first_ptr {nullptr}; }; #endif // STACK_H <file_sep>/ds/SpaceArray.h #ifndef SPACEARRAY_H #define SPACEARRAY_H #include <iostream> #include <tuple> #include "IArray.h" using namespace std; template <typename T> class SpaceArray : public IArray<T> { public: SpaceArray(const size_t _size = 10) : m_single_array_size(_size), m_full_size(0) { m_data_ptr = new T*[1]; m_data_ptr[0] = new T[m_single_array_size]; m_arrays_count = 1; m_elements_count = new size_t[m_arrays_count]; m_elements_count[0] = 0; } virtual void add(const T value, size_t _index) { size_t array_index, position_to_add; tie(array_index, position_to_add) = get_position(_index); bool array_with_free_position_found = false; size_t ix_of_array_with_free_position = array_index; for (;ix_of_array_with_free_position < m_arrays_count; ++ix_of_array_with_free_position) { if (m_elements_count[ix_of_array_with_free_position] < m_single_array_size) { array_with_free_position_found = true; break; } } if ((array_index == m_arrays_count) || !array_with_free_position_found) { // space array is full - - - - - - - - - - - - - - - - - - size_t* tmp_last_indexes = new size_t[m_arrays_count + 1]; memcpy(tmp_last_indexes, m_elements_count, m_arrays_count * sizeof(size_t)); tmp_last_indexes[m_arrays_count] = 0; delete [] m_elements_count; m_elements_count = tmp_last_indexes; T** tmp_data_array = new T*[m_arrays_count + 1]; memcpy(tmp_data_array, m_data_ptr, m_arrays_count * sizeof(T*)); tmp_data_array[m_arrays_count] = new T[m_single_array_size]; delete [] m_data_ptr; m_data_ptr = tmp_data_array; ++m_arrays_count; // - - - - - - - - - - - - - - - - - - - - - - - - - - - - } bool elements_should_be_moved = (ix_of_array_with_free_position != array_index); if (elements_should_be_moved) { for (size_t iy = ix_of_array_with_free_position; iy > array_index; --iy) { T* destination_ptr = m_data_ptr[iy] + 1; T* source_ptr = m_data_ptr[iy]; size_t shift = iy == ix_of_array_with_free_position ? 0 : 1; size_t count_of_bytes = (m_elements_count[iy] - shift) * sizeof (T); memcpy(destination_ptr, source_ptr, count_of_bytes); m_data_ptr[iy][0] = m_data_ptr[iy - 1][m_elements_count[iy - 1] - 1]; } } T* destination_ptr = m_data_ptr[array_index] + position_to_add + 1; T* source_ptr = m_data_ptr[array_index] + position_to_add; size_t count_of_bytes = (m_elements_count[array_index] - position_to_add - elements_should_be_moved) * sizeof (T); memcpy(destination_ptr, source_ptr, count_of_bytes); m_data_ptr[array_index][position_to_add] = std::move(value); ++m_elements_count[ix_of_array_with_free_position]; ++m_full_size; } virtual T& operator[](size_t _index) { size_t array_index, position; if (_index == m_full_size - 1) { array_index = m_arrays_count - 1; position = m_elements_count[array_index] - 1; } else { tie(array_index, position) = get_position(_index); } return m_data_ptr[array_index][position]; } virtual T get(size_t _index) const { size_t array_index, position; if (_index == m_full_size - 1) { array_index = m_arrays_count - 1; position = m_elements_count[array_index] - 1; } else { tie(array_index, position) = get_position(_index); } return m_data_ptr[array_index][position]; } virtual void remove(size_t _index) { size_t array_index, position_to_remove; if (_index == m_full_size - 1) { array_index = m_arrays_count - 1; position_to_remove = m_elements_count[array_index] - 1; } else { tie(array_index, position_to_remove) = get_position(_index); } /* position_to_remove | 0 1 2 3 array_index -> 0: [.][.][.][.] 1: [.][.][.][.] 2: [.][.][.][.] */ // remove element from array memcpy(m_data_ptr[array_index] + position_to_remove, m_data_ptr[array_index] + (position_to_remove + 1), (m_elements_count[array_index] - position_to_remove) * sizeof (T)); --m_elements_count[array_index]; --m_full_size; if (!m_elements_count[array_index] && m_arrays_count > 1) { // one of arrays is empty now // before operation: // 0: [.][.][.][.] // 1: [ ][ ][ ][ ] // 2: [.][.][.][.] T** new_data_ptr = new T*[m_arrays_count - 1]; memcpy(new_data_ptr, m_data_ptr, array_index * sizeof (T*)); memcpy(new_data_ptr + array_index, m_data_ptr + array_index + 1, (m_arrays_count - 1 - array_index) * sizeof (T*)); delete [] m_data_ptr[array_index]; delete [] m_data_ptr; m_data_ptr = new_data_ptr; size_t* new_elements_count_ptr = new size_t[m_arrays_count - 1]; memcpy(new_elements_count_ptr, m_elements_count, array_index * sizeof (size_t)); memcpy(new_elements_count_ptr + array_index, m_elements_count + array_index + 1, (m_arrays_count - 1 - array_index) * sizeof (size_t)); delete [] m_elements_count; m_elements_count = new_elements_count_ptr; --m_arrays_count; // after operation: // 0: [.][.][.][.] // 1: [.][.][.][.] } } virtual size_t size() const { return m_full_size; } void print() { for (size_t ix = 0; ix < m_arrays_count; ++ix) { cout << "array " << ix << ": "; for (size_t iy = 0; iy < m_single_array_size; ++iy) { if (iy < m_elements_count[ix]) { cout << m_data_ptr[ix][iy] << " "; } else { cout << ". "; } } cout << endl; } } virtual ~SpaceArray() { for (size_t ix = 0; ix < m_arrays_count; ++ix) { delete [] m_data_ptr[ix]; } delete [] m_data_ptr; } private: tuple<size_t, size_t> get_position(size_t _index) const { size_t array_index = 0, position = 0, size = 0; for (; array_index < m_arrays_count; ++array_index) { size_t current_count = size + m_elements_count[array_index]; if (current_count >= _index && (_index < m_single_array_size * (array_index + 1))) { break; } size += m_elements_count[array_index]; } position = _index - size; return make_tuple(array_index, position); } T** m_data_ptr {nullptr}; size_t* m_elements_count {nullptr}; size_t m_arrays_count; size_t m_full_size; const size_t m_single_array_size; }; #endif // SPACEARRAY_H <file_sep>/ds/MatrixArray.h #ifndef MATRIXARRAY_H #define MATRIXARRAY_H #include <iostream> #include <memory> using namespace std; #include "IArray.h" template <typename T> class MatrixArray : public IArray<T> { public: template <typename K> class iterator { public: iterator(K* _data_ptr, size_t _index, size_t _capacity) : m_ptr(_data_ptr), m_index(_index), m_capacity(_capacity) {} bool operator==(iterator& _i) const { return m_ptr == _i.m_ptr; } bool operator!=(iterator& _i) const { return !(*this == _i); } K& operator*() { return *m_ptr[m_index / m_capacity][m_index % m_capacity]; } void operator++() { ++m_index; } void operator--() { --m_index; } private: size_t m_index {0}; size_t m_capacity {0}; K** m_ptr {nullptr}; }; MatrixArray(size_t _capacity = 10) : m_capacity(_capacity), m_full_capacity(_capacity) { m_data_ptr = new T*[1]; m_data_ptr[0] = new T [_capacity]; } void add(const T _value, size_t _index) { if (m_size == m_full_capacity) { // create additional array if matrix vector is full size_t new_data_size = (m_full_capacity / m_capacity) + 1; T** tmp_data_ptr = new T*[new_data_size]; memcpy(tmp_data_ptr, m_data_ptr, new_data_size * sizeof (T*)); tmp_data_ptr[new_data_size - 1] = new T[m_capacity]; delete [] m_data_ptr; m_data_ptr = tmp_data_ptr; m_full_capacity += m_capacity; // - - - - - - - - - - - - - - - - - - - - - - - - } int ix_of_last_array = m_size / m_capacity; int ix_array_to_insert = _index / m_capacity; if (ix_of_last_array != ix_array_to_insert) { // move elements if new element should be inserted in the middle of the matrix T* destination_ptr = m_data_ptr[ix_of_last_array] + 1; T* source_ptr = m_data_ptr[ix_of_last_array]; size_t count_of_bytes = (m_size % m_capacity) * sizeof(T); memcpy(destination_ptr, source_ptr, count_of_bytes); for (int ix = ix_of_last_array - 1; ix >= ix_array_to_insert; --ix) { m_data_ptr[ix + 1][0] = m_data_ptr[ix][m_capacity - 1]; if (ix > ix_array_to_insert) { T* destination_ptr = m_data_ptr[ix] + 1; T* source_ptr = m_data_ptr[ix]; size_t count_of_bytes = (m_capacity - 1) * sizeof(T); memcpy(destination_ptr, source_ptr, count_of_bytes); } } // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - } // move elements in destination array _index %= m_capacity; T* destination_ptr = m_data_ptr[ix_array_to_insert] + _index + 1; T* source_ptr = m_data_ptr[ix_array_to_insert] + _index; size_t count_of_bytes = (m_capacity - _index - 1) * sizeof (T); memcpy(destination_ptr, source_ptr, count_of_bytes); // - - - - - - - - - - - - - - - - - m_data_ptr [ix_array_to_insert] [_index] = std::move(_value); ++m_size; } iterator<T> begin() { return iterator<T>(m_data_ptr, 0, m_capacity); } iterator<T> end() { return iterator<T>(m_data_ptr, m_size, m_capacity); } T& operator[](size_t _index) { return m_data_ptr [_index / m_capacity] [_index % m_capacity]; } T get(size_t _index) const { return m_data_ptr [_index / m_capacity] [_index % m_capacity]; } void remove(size_t _index) { size_t array_index = _index / m_capacity; size_t value_index = _index % m_capacity; size_t bytes = (m_capacity - value_index) * sizeof (T); memcpy(m_data_ptr[array_index] + value_index, m_data_ptr[array_index] + value_index + 1, bytes); size_t last_index = (m_size - 1) / m_capacity; if (last_index > array_index) { for (size_t ix = array_index + 1; ix <= last_index; ++ix) { m_data_ptr[ix - 1][m_capacity - 1] = m_data_ptr[ix][0]; memcpy(m_data_ptr[ix], m_data_ptr[ix] + 1, (m_capacity - 1) * sizeof (T)); } } --m_size; size_t new_last_index = (m_size - 1) / m_capacity; if (new_last_index < last_index) { // last array in matrix now empty and should be removed T** new_data_ptr = new T*[last_index]; memcpy(new_data_ptr, m_data_ptr, last_index * sizeof (T*)); delete [] m_data_ptr[last_index]; delete [] m_data_ptr; m_data_ptr = new_data_ptr; m_full_capacity -= m_capacity; // - - - - - - - - - - - - - - - - - - - - - - - - - - - } } size_t size() const { return m_size; } void print() { size_t current_index = 0; size_t count = m_full_capacity / m_capacity; for (size_t ix = 0; ix < count; ++ix) { cout << "array " << ix << ": "; for (size_t iy = 0; iy < m_capacity; ++iy) { if (current_index < m_size) { cout << m_data_ptr[ix][iy] << " "; } else { cout << ". "; } ++current_index; } cout << endl; } } ~MatrixArray() { size_t size = m_full_capacity / m_capacity; for (size_t ix = 0; ix < size; ++ix) { delete [] m_data_ptr[ix]; } delete [] m_data_ptr; } private: T** m_data_ptr {nullptr}; size_t m_size {0}; size_t m_full_capacity; const size_t m_capacity; }; #endif // MATRIXARRAY_H <file_sep>/ds/main.cpp #include <iostream> #include <random> #include <chrono> #include <vector> #include <stack> #include <queue> #include <fstream> #include <thread> using namespace std; using namespace std::chrono; #include "SingleArray.h" #include "VectorArray.h" #include "MatrixArray.h" #include "SpaceArray.h" #include "Stack.h" #include "Queue.h" #include "PriorityQueue.h" template <typename Collection, typename Type, typename ...Args> void test_get(ofstream& _output, int _items_count, int _get_items, Args ...args) { Collection collection(args...); for (int ix = 0; ix < _items_count; ++ix) { collection.add(Type(ix), collection.size()); } // - - - - - - - - - - - - - - - - - - volatile Type t; auto start = high_resolution_clock::now(); for (int ix = 0; ix < _get_items; ++ix) { t = ++collection[0]; } auto end = high_resolution_clock::now(); auto time = duration_cast<milliseconds>(end - start); _output << " get from (0); elements count = " << _get_items << " result time = " << time.count() << " ms" << endl; // - - - - - - - - - - - - - - - - - - start = high_resolution_clock::now(); for (int ix = 0; ix < _get_items; ++ix) { t = ++collection[collection.size() / 2]; } end = high_resolution_clock::now(); time = duration_cast<milliseconds>(end - start); _output << " get from (c.size() / 2); elements count = " << _get_items << " result time = " << time.count() << " ms" << endl; // - - - - - - - - - - - - - - - - - - start = high_resolution_clock::now(); for (int ix = 0; ix < _get_items; ++ix) { t = ++collection[collection.size() - 1]; } end = high_resolution_clock::now(); time = duration_cast<milliseconds>(end - start); _output << " get from (c.size()); elements count = " << _get_items << " result time = " << time.count() << " ms" << endl; } template <typename Collection, typename Type, typename ...Args> void test_remove(ofstream& _output, int _items_count, int _remove_items, Args ...args) { Collection collection(args...); // - - - - - - - - - - - - - - - - - - - - - for (int ix = 0; ix < _items_count; ++ix) { collection.add(Type(ix), collection.size()); } // - - - - - - - - - - - - - - - - - - - - - auto start = high_resolution_clock::now(); for (int ix = 0; ix < _remove_items; ++ix) { collection.remove(0); } auto end = high_resolution_clock::now(); auto time = duration_cast<milliseconds>(end - start); _output << " remove from (0); elements count = " << _remove_items << " result time = " << time.count() << " ms" << endl; // - - - - - - - - - - - - - - - - - - - - - for (int ix = 0; ix < _remove_items; ++ix) { collection.add(Type(ix), collection.size()); } // - - - - - - - - - - - - - - - - - - - - - start = high_resolution_clock::now(); for (int ix = 0; ix < _remove_items; ++ix) { collection.remove(collection.size() / 2); } end = high_resolution_clock::now(); time = duration_cast<milliseconds>(end - start); _output << " remove from (c.size() / 2); elements count = " << _remove_items << " result time = " << time.count() << " ms" << endl; // - - - - - - - - - - - - - - - - - - - - - for (int ix = 0; ix < _remove_items; ++ix) { collection.add(Type(ix), collection.size()); } // - - - - - - - - - - - - - - - - - - - - - start = high_resolution_clock::now(); for (int ix = 0; ix < _remove_items; ++ix) { collection.remove(collection.size() - 1); } end = high_resolution_clock::now(); time = duration_cast<milliseconds>(end - start); _output << " remove from (c.size()); elements count = " << _remove_items << " result time = " << time.count() << " ms" << endl; } template <typename Collection, typename Type, typename ...Args> void test_add(ofstream& _output, size_t _items_count, Args ...args) { { Collection collection(args...); auto start = high_resolution_clock::now(); for (int ix = 0; ix < _items_count; ++ix) { collection.add(Type(ix), 0); } auto end = high_resolution_clock::now(); auto time = duration_cast<milliseconds>(end - start); _output << " add to (0); elements = " << _items_count << " result time = " << time.count() << " ms" << endl; } { Collection collection(args...); auto start = high_resolution_clock::now(); for (int ix = 0; ix < _items_count; ++ix) { collection.add(Type(ix), collection.size() / 2); } auto end = high_resolution_clock::now(); auto time = duration_cast<milliseconds>(end - start); _output << " add to (c.size() / 2); elements = " << _items_count << " result time = " << time.count() << " ms" << endl; } { Collection collection(args...); auto start = high_resolution_clock::now(); for (int ix = 0; ix < _items_count; ++ix) { collection.add(Type(ix), collection.size()); } auto end = high_resolution_clock::now(); auto time = duration_cast<milliseconds>(end - start); _output << " add to (c.size()); elements = " << _items_count << " result time = " << time.count() << " ms" << endl; } } template <typename Collection, typename Type, typename ...Args> void test(const char* _message, const char * _file, int _items_count, int _elements_to_remove, int _get_times, Args ...args) { ofstream output; output.open(_file); if (output) { cout << "TEST OF " << _message << " START WORK" << endl; output << " - - - - - - - START TEST OF " << _message << " - - - - - - -" << endl << endl; test_add<Collection, Type>(output, _items_count, args...); output << endl; test_get<Collection, Type>(output, _items_count, _get_times, args...); output << endl; test_remove<Collection, Type>(output, _items_count, _elements_to_remove, args...); output << endl; output << " - - - - - - - - END TEST OF " << _message << " - - - - - - -" << endl << endl; output.flush(); output.close(); cout << "TEST OF " << _message << " END WORK" << endl << endl; } else { cout << " can`t open file to write test result for" << _message << endl; } } template <typename T> struct StackWrapper : public Stack<T> { void add(T _value, size_t _index) { (void)_index; this->push(_value); } T& operator[](size_t _index) { (void)_index; static int i = this->pop(); return i; } T get(size_t _index) { (void) _index; return this->pop(); } void remove(size_t _index) {(void)_index;} }; template <typename T> struct QueueWrapper : public Queue<T> { void add(T _value, size_t _index) { (void)_index; this->enqueue(_value); } T& operator[](size_t _index) { (void)_index; static int i = this->dequeue(); return i; } T get(size_t _index) { (void) _index; return this->dequeue(); } void remove(size_t _index) {(void)_index;} }; template <typename T, typename P> struct PriorityQueueWrapper : public PriorityQueue<T, P> { void add(T _value, size_t _index) { (void)_index; P priority(0); this->enqueue(_value, priority); } T& operator[](size_t _index) { (void)_index; static int i = this->dequeue(); return i; } T get(size_t _index) { (void) _index; return this->dequeue(); } void remove(size_t _index) {(void)_index;} }; template <typename T> struct StdVectorWrapper : public vector<T> { void add(T _value, size_t _index) { this->emplace(this->begin() + _index, _value); } T get(size_t _index) { return vector<T>::at(_index); } void remove(size_t _index) { vector<T>::erase(vector<T>::begin() + _index); } }; template <typename T> struct StdQueueWrapper : public queue<T> { void add(T _value, size_t _index) { (void)_index; queue<T>::push(_value); } T& operator[](size_t _index) { (void)_index; return this->front(); } T get(size_t _index) { (void)_index; T result = queue<T>::front(); queue<T>::pop(); return result; } void remove(size_t _index) {(void)_index;} }; template <typename T> struct StdStackWrapper : public stack<T> { void add(T _value, size_t _index) { (void)_index; stack<T>::push(_value); } T& operator[](size_t _index) { (void)_index; return this->top(); } T get(size_t _index) { (void)_index; T result = stack<T>::top(); stack<T>::pop(); return result; } void remove(size_t _index) {(void)_index;} }; int main() { int count_of_elements = 1000000; int elements_to_remove = 100000; int elements_to_get = 100000; test<VectorArray<int>, int, int, double>(static_cast<const char*>("VectorArray<int>(10, 0.2)"), static_cast<const char*>("vector_array_10_02.txt"), count_of_elements, elements_to_remove, elements_to_get, 10, 0.2); test<VectorArray<int>, int, int, double>(static_cast<const char*>("VectorArray<int>(10, 1.0)"), static_cast<const char*>("vector_array_10_10.txt"), count_of_elements, elements_to_remove, elements_to_get, 10, 1.0); // - - - - - - - - - - - - - - - - - - - - - - - - - - test<StdVectorWrapper<int>, int>(static_cast<const char*>("StdVectorWrapper<int>"), static_cast<const char*>("std_vector.txt"), count_of_elements, elements_to_remove, elements_to_get); // - - - - - - - - - - - - - - - - - - - - - - - - - - test<MatrixArray<int>, int, int>(static_cast<const char*>("MatrixArray<int>(100)"), static_cast<const char*>("matrix_array_100.txt"), count_of_elements, elements_to_remove, elements_to_get, 100); test<MatrixArray<int>, int, int>(static_cast<const char*>("MatrixArray<int>(1000)"), static_cast<const char*>("matrix_array_1000.txt"), count_of_elements, elements_to_remove, elements_to_get, 1000); test<MatrixArray<int>, int, int>(static_cast<const char*>("MatrixArray<int>(10000)"), static_cast<const char*>("matrix_array_10000.txt"), count_of_elements, elements_to_remove, elements_to_get, 10000); // - - - - - - - - - - - - - - - - - - - - - - - - - - test<SpaceArray<int>, int, int>(static_cast<const char*>("SpaceArray<int>(100)"), static_cast<const char*>("space_array_100.txt"), count_of_elements, elements_to_remove, elements_to_get, 100); test<SpaceArray<int>, int, int>(static_cast<const char*>("SpaceArray<int>(1000)"), static_cast<const char*>("space_array_1000.txt"), count_of_elements, elements_to_remove, elements_to_get, 1000); test<SpaceArray<int>, int, int>(static_cast<const char*>("SpaceArray<int>(10000)"), static_cast<const char*>("space_array_10000.txt"), count_of_elements, elements_to_remove, elements_to_get, 10000); // - - - - - - - - - - - - - - - - - - - - - - - - - - test<StackWrapper<int>, int>(static_cast<const char*>("StackWrapper<int>"), static_cast<const char*>("stack_wrapper.txt"), count_of_elements, elements_to_remove, elements_to_get); test<StdStackWrapper<int>, int>(static_cast<const char*>("StdStackWrapper<int>"), static_cast<const char*>("std_stack_wrapper.txt"), count_of_elements, elements_to_remove, elements_to_get); // - - - - - - - - - - - - - - - - - - - - - - - - - - test<QueueWrapper<int>, int>(static_cast<const char*>("QueueWrapper<int>"), static_cast<const char*>("queue_wrapper.txt"), count_of_elements, elements_to_remove, elements_to_get); test<StdQueueWrapper<int>, int>(static_cast<const char*>("StdQueueWrapper<int>"), static_cast<const char*>("std_queue_wrapper.txt"), count_of_elements, elements_to_remove, elements_to_get); // - - - - - - - - - - - - - - - - - - - - - - - - - - test<SingleArray<int>, int>(static_cast<const char*>("SingleArray<int>"), static_cast<const char*>("single_array.txt"), count_of_elements, elements_to_remove, elements_to_get); return 0; } <file_sep>/ds/Queue.h #ifndef QUEUE_H #define QUEUE_H #include <iostream> using namespace std; template <typename T> class Queue { struct Node { Node(T _value, Node* _next_ptr = nullptr) : m_value(move(_value)), m_next_ptr(_next_ptr) {} T m_value; Node* m_next_ptr; }; public: Queue() : m_size(0) {} void enqueue(T _value) { if (!m_size) { m_first_ptr = new Node(_value); m_last_ptr = m_first_ptr; } else { Node* new_node_ptr = new Node(_value); m_last_ptr->m_next_ptr = new_node_ptr; m_last_ptr = new_node_ptr; } ++m_size; } T dequeue() { if (m_size) { T value = m_first_ptr->m_value; Node* next_node_ptr = m_first_ptr->m_next_ptr; if (m_last_ptr == m_first_ptr) { m_last_ptr = nullptr; } delete m_first_ptr; m_first_ptr = next_node_ptr; --m_size; return value; } else { // size == 0 throw out_of_range("queue size == 0"); } } size_t size() { return m_size; } void print() { Node* current_node_ptr = m_first_ptr; while (current_node_ptr) { cout << current_node_ptr->m_value << " "; current_node_ptr = current_node_ptr->m_next_ptr; } } ~Queue() { Node* current_node = m_first_ptr; while (current_node) { Node* tmp_ptr = current_node->m_next_ptr; delete current_node; current_node = tmp_ptr; } } private: size_t m_size; Node* m_first_ptr {nullptr}; Node* m_last_ptr {nullptr}; }; #endif // QUEUE_H <file_sep>/ds/IArray.h #ifndef IARRAY_H #define IARRAY_H #include <memory> template <typename T> class IArray { public: virtual void add(const T value, size_t _index) = 0; //virtual Iter begin() = 0; //virtual Iter end() = 0; virtual T& operator[](size_t _index) = 0; virtual T get(size_t _index) const = 0; virtual void remove(size_t _index) = 0; virtual size_t size() const = 0; virtual ~IArray() {} }; #endif // IARRAY_H <file_sep>/ds/SingleArray.h #ifndef SINGLEARRAY_H #define SINGLEARRAY_H #include <memory> #include <iostream> #include "IArray.h" using namespace std; template <typename T> class SingleArray : public IArray<T> { public: template <typename K> class iterator { public: iterator(K* _data_ptr) { m_ptr = _data_ptr; } bool operator==(iterator& _i) const { return m_ptr == _i.m_ptr; } bool operator!=(iterator& _i) const { return !(*this == _i); } K& operator*() { return *m_ptr; } void operator++() { ++m_ptr; } void operator--() { --m_ptr; } private: K* m_ptr {nullptr}; }; SingleArray() { m_data_ptr = new T[0]; } iterator<T> begin() { return iterator<T>(m_data_ptr); } iterator<T> end() { return iterator<T>(m_data_ptr + m_size); } void add(const T value, size_t _index) { T* tmp_ptr = new T[m_size + 1]; memcpy(tmp_ptr, m_data_ptr, _index * sizeof (T)); memcpy(tmp_ptr + _index + 1, m_data_ptr + _index, (m_size - _index) * sizeof (T)); delete[] m_data_ptr; m_data_ptr = tmp_ptr; m_data_ptr[_index] = std::move(value); ++m_size; } T& operator[](size_t _index) { return m_data_ptr[_index]; } T get(size_t _index) const { return m_data_ptr[_index]; } void remove(size_t _index) { --m_size; T* tmp_ptr = new T[m_size]; memcpy(tmp_ptr, m_data_ptr, _index * sizeof (T)); memcpy(tmp_ptr + _index, m_data_ptr + _index + 1, (m_size - _index) * sizeof (T)); delete [] m_data_ptr; m_data_ptr = tmp_ptr; } size_t size() const { return m_size; } void print() { cout << "array: "; for (int ix = 0; ix < m_size; ++ix) { cout << m_data_ptr[ix] << " "; } cout << endl; } ~SingleArray() { delete [] m_data_ptr; } private: size_t m_size {0}; T* m_data_ptr {nullptr}; }; #endif // SINGLEARRAY_H <file_sep>/ds/PriorityQueue.h #ifndef PRIORITYQUEUE_H #define PRIORITYQUEUE_H #include <iostream> #include "Queue.h" template <typename T, typename P> class PriorityQueue { struct Node { Node() = default; ~Node() = default; Queue<T> m_queue; P m_priority; Node* m_next_ptr {nullptr}; }; public: PriorityQueue() = default; void enqueue(T _value, P _priority) { Node* prev_ptr = nullptr; Node* current_ptr = m_first; while (current_ptr && _priority < current_ptr->m_priority) { prev_ptr = current_ptr; current_ptr = current_ptr->m_next_ptr; } if (current_ptr) { if (current_ptr->m_priority < _priority) { // _priority biggest than the current priority Node* new_node_ptr = new Node(); new_node_ptr->m_priority = _priority; new_node_ptr->m_queue.enqueue(_value); new_node_ptr->m_next_ptr = current_ptr; if (prev_ptr) { prev_ptr->m_next_ptr = new_node_ptr; new_node_ptr->m_next_ptr = current_ptr; } if (current_ptr == m_first) { // new top proirity element added m_first = new_node_ptr; } } else { // _priority equal to the current priority current_ptr->m_queue.enqueue(_value); } } else { // current element == nullptr Node* new_node_ptr = new Node(); new_node_ptr->m_priority = _priority; new_node_ptr->m_queue.enqueue(_value); if (prev_ptr) { // new last element added prev_ptr->m_next_ptr = new_node_ptr; } else { // first element created m_first = new_node_ptr; } } ++m_size; } T dequeue() { if (m_size) { T value = m_first->m_queue.dequeue(); if (!m_first->m_queue.size()) { Node* tmp_node_ptr = m_first->m_next_ptr; delete m_first; m_first = tmp_node_ptr; } --m_size; return value; } else { throw out_of_range("PriorityQueue size == 0"); } } size_t size() { return m_size; } void print() { Node* current_node_ptr = m_first; while (current_node_ptr) { cout << "proirity = " << current_node_ptr->m_priority << ": "; current_node_ptr->m_queue.print(); cout << endl; current_node_ptr = current_node_ptr->m_next_ptr; } } ~PriorityQueue() { Node* current_ptr = m_first; while (current_ptr) { Node* tmp_next_node = current_ptr->m_next_ptr; delete current_ptr; current_ptr = tmp_next_node; } } private: size_t m_size {0}; Node* m_first {nullptr}; }; #endif // PRIORITYQUEUE_H
6718a0c17e10420ac08f87d76799ec95ee85e8b9
[ "C++" ]
8
C++
Nik3991/base_data_structures
21940096359f7bb49169fc123845257732736c66
673f6a0d8b4a195ec8ee993730b583deb887f0d4
refs/heads/master
<repo_name>johnobc11/projectTARAbackend<file_sep>/ptaraback/admin.py from django.contrib import admin #from .models import ptaraUsers # Register your models here. #admin.site.register(ptaraUsers)<file_sep>/ptaraback/migrations/0005_auto_20180228_0909.py # -*- coding: utf-8 -*- # Generated by Django 1.9 on 2018-02-28 09:09 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('ptaraback', '0004_auto_20180227_2203'), ] operations = [ migrations.AddField( model_name='ptarausers', name='last_login', field=models.DateTimeField(blank=True, null=True, verbose_name='last login'), ), migrations.AlterField( model_name='ptarausers', name='id', field=models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID'), ), migrations.AlterField( model_name='ptarausers', name='password', field=models.CharField(max_length=128, verbose_name='password'), ), ] <file_sep>/projectTARA/urls.py """projectTARA URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/1.9/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: url(r'^$', views.home, name='home') Class-based views 1. Add an import: from other_app.views import Home 2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home') Including another URLconf 1. Add an import: from blog import urls as blog_urls 2. Import the include() function: from django.conf.urls import url, include 3. Add a URL to urlpatterns: url(r'^blog/', include(blog_urls)) """ from django.conf.urls import include, url from django.contrib import admin from rest_framework.authtoken.views import obtain_auth_token from projectTARA.routers import HybridRouter from rest_framework import routers from rest_framework.urlpatterns import format_suffix_patterns from ptaraback.views import * from rest_framework.routers import DefaultRouter #router = HybridRouter() #router = HybridRouter() #router = DefaultRouter() #register REST API endpoints with DRF router #router.register(r'register', UserCreateViewSet, base_name="register") #router.register(r'login', UserLoginView, base_name="login") #router.add_api_view(r'register', url(r'^register/$', UserViewSet.as_view({'get': 'list'}), name=r"reg")) urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^token-auth/', obtain_auth_token), url(r'^register/', UserCreateView.as_view(), name='register'), url(r'^login/', UserLoginView.as_view(), name='login'), #url(r'^login/$', UserViewSet.as_view(), name='register'), #url(r'^api/', include(router.urls, namespace='api')), # root view of our REST api, generated by Django REST Framework's router #url(r'^api/', include(router.urls, namespace='api')), ] #urlpatterns = format_suffix_patterns(urlpatterns) #urlpatterns = router.urls <file_sep>/ptaraback/views.py from django.shortcuts import render from rest_framework import views, mixins, permissions, exceptions from rest_framework.generics import CreateAPIView from rest_framework.permissions import AllowAny from rest_framework.response import Response from rest_framework.views import APIView #from ptaraback.serializers import * from django.contrib.auth import get_user_model from ptaraback.models import * from rest_framework.response import Response from rest_framework.status import HTTP_200_OK, HTTP_400_BAD_REQUEST from .serializers import ( UserCreateSerializer, UserLoginSerializer ) User = get_user_model() from rest_framework import viewsets # Create your views here. class UserCreateView(CreateAPIView): queryset = User.objects.all() permission_classes = [ permissions.AllowAny ] serializer_class = UserCreateSerializer#Serializer class UserLoginView(APIView): permission_classes = [permissions.AllowAny] serializer_class = UserLoginSerializer def post(self, request, *args, **kwargs): data = request.data serializer = UserLoginSerializer(data=data) if serializer.is_valid(raise_exception=True): new_data = serializer.data return Response(new_data, status=HTTP_200_OK) return Response(serializer.errors, status=HTTP_400_BAD_REQUEST) """ class UsersList(APIView): def get(self, request): users = ptaraUsers.objects.all() serializer = UserSerializer(users, many=True) return Response(serializer.data) def post(self): pass""" """ class UserFormView(View): form_class = UserForm #display blank form def get(self, request): form = self.form_class(None) return render(request, {'form': form}) #process form data def post(self, request): form = self.form_class(request.POST) if form.is_valid(): user = form.save(commit=False) #clean (normalized data) username = form.cleaned_data['username'] password = form.cleaned_data['password'] user.set_password(<PASSWORD>) user.save() user = authenticate(username=username, password=<PASSWORD>) if user is not None: if user.is_active: login(request, user) request.user() #return redirect() return render(request, {'form': form})""" """ class PtarabackList(mixins.ListModelMixin, mixins.RetrieveModelMixin, viewsets.GenericViewSet): permission_classes = (permissions.IsAuthenticated, ) authentication_classes = (TokenAuthentication, ) queryset = User.objects.all() lookup_field = 'id' serializer_class = UserSerializer def get_queryset(self): return User.objects.all() class ObtainAuthToken(views.APIView): throttle_classes = () permission_classes = () authentication_classes = [TokenAuthentication, ] # parser_classes = (parsers.FormParser, parsers.MultiPartParser, parsers.JSONParser,) # renderer_classes = (renderers.JSONRenderer,) serializer_class = AuthTokenSerializer def post(self, request, *args, **kwargs): serializer = self.serializer_class(data=request.data) serializer.is_valid(raise_exception=True) user = serializer.validated_data['user'] token, created = Token.objects.get_or_create(user=user) return Response({'token': token.key}) obtain_auth_token = ObtainAuthToken.as_view()""" <file_sep>/ptaraback/apps.py from django.apps import AppConfig class PtarabackConfig(AppConfig): name = 'ptaraback' <file_sep>/ptaraback/forms.py from .models import ptaraUsers from django import forms class UserForm(forms.ModelForm): password = forms.CharField(widget=forms.PasswordInput) class Meta: model = ptaraUsers fields = '__all__'<file_sep>/ptaraback/serializers.py from django.contrib.auth import authenticate, get_user_model from django.utils.translation import ugettext_lazy as _ from django.db.models import Q from rest_framework import serializers #from rest_framework_mongoengine.serializers import DocumentSerializer from rest_framework.exceptions import ValidationError from rest_framework.fields import CharField, EmailField #from ptaraback.models import ptaraUsers User = get_user_model() class UserCreateSerializer(serializers.ModelSerializer): #id = serializers.IntegerField(read_only=False) email = EmailField(label='Email address') #email2 = EmailField(label='Confirm Email') class Meta: model = User fields = [ 'username', 'email', 'password', ] extra_kwargs = {'password': {'write_only': True}} """def validate(self, data): email = data['email'] qs_email = User.objects.filter(email=email) if qs_email.exists(): raise ValidationError("Email already used and registered") return data""" """def email_validation(self, value): data = self.get_initial() email = data.get("email2") email2 = value if email != email2: raise ValidationError("Unmatched email") qs_email = User.objects.filter(email=email) if qs_email.exists(): raise ValidationError("Email already used and registered") return value def email_validation2(self, value): data = self.get_initial() email = data.get("email") email2 = value if email != email2: raise ValidationError("Unmatched email") return value""" def create(self, validated_data): """user = ptaraUsers.objects.create( username=validated_data['username'], email = validated_data['email'], )""" username = validated_data['username'] email = validated_data['email'] password = validated_data['password'] user_obj = User( username = username, email = email ) user_obj.set_password(validated_data['password']) user_obj.save() return validated_data class UserLoginSerializer(serializers.ModelSerializer): #token = CharField(allow_blank=True, read_only=True) username = CharField(required=False, allow_blank=True) email = EmailField(label='Email Address', required=False, allow_blank=True) class Meta: model = User fields = [ 'username', 'email', 'password', #'token', ] extra_kwargs = {'password': {'write_only': True}} def validate(self, data): user_obj = None email = data.get("email", None) username = data.get("username", None) password = data["password"] if not email and not username: raise ValidationError("Username and email is required to login") user = User.objects.filter( Q(email=email) | Q(username=username) ).distinct() user = user.exclude(email_isnull=True).exclude(email_iexact='') if user.exists() and user.count() == 1: user_obj = user.first() else: raise ValidationError("This username or email is not valid") if user_obj: if not user_obj.check_password(password): raise ValidationError("Incorrect credentials - try again") return data """ class AuthTokenSerializer(serializers.Serializer): username = serializers.CharField(label=_("Username")) password = serializers.CharField(label=_("Password"), style={'input_type': 'password'}) def validate(self, attrs): username = attrs.get('username') password = attrs.get('password') if username and password: user = authenticate(username=username, password=password) if user: # From Django 1.10 onwards the `authenticate` call simply # returns `None` for is_active=False users. # (Assuming the default `ModelBackend` authentication backend.) if not user.is_active: msg = _('User account is disabled.') raise serializers.ValidationError(msg) else: msg = _('Unable to log in with provided credentials.') raise serializers.ValidationError(msg) else: msg = _('Must include "username" and "password".') raise serializers.ValidationError(msg) attrs['user'] = user return attrs""" """ class UserSerializer2(serializers.ModelSerializer): id = serializers.IntegerField(read_only=False) class Meta: model = ptaraUsers fields = '__all__'""" <file_sep>/ptaraback/models.py import datetime import binascii import os from django.contrib.auth.base_user import AbstractBaseUser from django.db import models from django.db.models.signals import post_save from django.dispatch import receiver from rest_framework.authtoken.models import Token from django.conf import settings # from django.utils import timezone # from django.utils.encoding import python_2_unicode_compatible # from django.utils.translation import ugettext_lazy as _ # from django.contrib.auth.hashers import check_password, make_password # from django.contrib.auth.models import _user_has_perm, _user_get_all_permissions, _user_has_module_perms """ class ptaraUsers(models.Model): id = models.AutoField(primary_key=True) email = models.EmailField() username = models.CharField(max_length=100) password = models.CharField(max_length=100, null=True)""" # token is: 4<PASSWORD> @receiver(post_save, sender=settings.AUTH_USER_MODEL) def create_auth_token(sender, instance=None, created=False, **kwargs): if created: Token.objects.create(user=instance) <file_sep>/projectTARA/settings.py """ Django settings for projectTARA project. Generated by 'django-admin startproject' using Django 1.9. For more information on this file, see https://docs.djangoproject.com/en/1.9/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/1.9/ref/settings/ """ import os import sys import mongoengine # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/1.9/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = '<KEY>' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', 'rest_framework_mongoengine', 'rest_framework.authtoken', #'mongoengine.django.mongo_auth', 'ptaraback' ] MIDDLEWARE_CLASSES = [ #'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', #'django.contrib.auth.middleware.SessionAuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'projectTARA.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'templates')] , 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'projectTARA.wsgi.application' DBNAME = 'admin' _MONGODB_USER = 'johnO' _MONGO_PASSWD = '<PASSWORD>' _MONGO_HOST = 'localhost' _MONGODB_NAME = 'test' _MONGO_DATABASE_HOST = \ 'mongodb://%s:%s@%s/%s' \ % (_MONGODB_USER, _MONGO_PASSWD, _MONGO_HOST, _MONGODB_NAME) # Database # https://docs.djangoproject.com/en/1.9/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'user', 'USER': 'postgres', 'PASSWORD': 'let<PASSWORD>', 'HOST': '127.0.0.1', 'PORT': '5432', } } #AUTH_USER_MODEL = 'mongo_auth.MongoUser' def is_test(): """ Checks, if we're running the server for real or in unit-test. We might need a better implementation of this function. """ if 'test' in sys.argv or 'testserver' in sys.argv: print("Using a test mongo database") return True else: print("Using a default mongo database") return False if is_test(): db = 'test' else: db = 'default' mongoengine.connect(DBNAME, host=_MONGO_DATABASE_HOST) REST_FRAMEWORK = { 'DEFAULT_PERMISSION_CLASSES': ( 'rest_framework.permissions.IsAuthenticated', ), 'DEFAULT_AUTHENTICATION_CLASSES': ( #'rest_framework_jwt.authentication.JSONWebTokenAuthentication', 'rest_framework.authentication.TokenAuthentication', ) } """ AUTH_USER_MODEL = 'mongo_auth.MongoUser' MONGOENGINE_USER_DOCUMENT = 'ptaraback.models.User' # Don't confuse Django's AUTHENTICATION_BACKENDS with DRF's AUTHENTICATION_CLASSES! AUTHENTICATION_BACKENDS = ( 'mongoengine.django.auth.MongoEngineBackend', #'django.contrib.auth.backends.ModelBackend' ) DEFAULT_AUTHENTICATION_CLASSES = ( 'rest_framework.authentication.SessionAuthentication', )""" LOGIN_URL = '/login/' LOGIN_REDIRECT_URL = '/' # Password validation # https://docs.djangoproject.com/en/1.9/ref/settings/#auth-password-validators AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, ] # Internationalization # https://docs.djangoproject.com/en/1.9/topics/i18n/ LANGUAGE_CODE = 'en-us' TIME_ZONE = 'UTC' USE_I18N = True USE_L10N = True USE_TZ = True # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/1.9/howto/static-files/ STATIC_URL = '/static/' <file_sep>/ptaraback/migrations/0002_auto_20180227_0901.py # -*- coding: utf-8 -*- # Generated by Django 1.9 on 2018-02-27 09:01 from __future__ import unicode_literals from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('ptaraback', '0001_initial'), ] operations = [ migrations.RenameModel( old_name='Users', new_name='ptaraUsers', ), ]
ba2ea3019c16d91e0d7066c6ac1145613980c235
[ "Python" ]
10
Python
johnobc11/projectTARAbackend
51c54cf24579da7c95f565fecfb0a47e4204cba8
16c66fdf99516d1ed941fdef38c851bdb631800d
refs/heads/master
<file_sep>package br.edu.nassau.pweb.dao; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; import br.edu.nassau.pweb.model.Usuario; public class DaoUsuarioImpl extends GenericDao implements DaoUsuario{ public void save(Usuario usuario) throws SQLException{ String sql = "INSERT INTO usuarios (nome, login, senha) VALUES (?,?,?)"; PreparedStatement st = null; try { openConn(); st = conn.prepareStatement(sql); st.setString(1, usuario.getNome()); st.setString(2, usuario.getLogin()); st.setString(3, usuario.getSenha()); st.execute(); } catch (SQLException e) { e.printStackTrace(); }finally{ if(st != null) st.close(); closeConn(); } } public void update(Usuario usuario) throws SQLException{ String sql = "UPDATE usuarios SET nome=?, login=?, senha=? WHERE id=?"; PreparedStatement st =null; try { openConn(); st = conn.prepareStatement(sql); st.setString(1, usuario.getNome()); st.setString(2, usuario.getLogin()); st.setString(3, usuario.getSenha()); st.setInt(4, usuario.getId()); st.execute(); } catch (SQLException e){ e.printStackTrace(); } finally { if(st != null) st.close(); closeConn(); } } public void remove(Usuario usuario) throws SQLException{ remove(usuario.getId()); } public void remove(Integer id) throws SQLException{ String sql = "DELETE from usuarios WHERE id = ?"; PreparedStatement st = null; try { openConn(); st = conn.prepareStatement(sql); st.setInt(1, id); st.execute(); } catch (SQLException e){ e.printStackTrace(); } finally { if(st != null) st.close(); closeConn(); } } public Usuario get(int id) throws SQLException{ String sql = "SELECT * FROM usuarios WHERE id=?"; PreparedStatement st = null; try { openConn(); st = conn.prepareStatement(sql); st.setInt(1, id); ResultSet resultSet = st.executeQuery(); if( resultSet.next() ){ int idRs = resultSet.getInt("id"); String nome = resultSet.getString("nome"); String login = resultSet.getString("login"); String senha = resultSet.getString("senha"); Usuario usuario = new Usuario(); usuario.setId(idRs); usuario.setNome(nome); usuario.setLogin(login); usuario.setSenha(senha); return usuario; } } catch (SQLException e) { e.printStackTrace(); } finally { if(st != null) st.close(); closeConn(); } return null; } public List<Usuario> list() throws SQLException{ String sql = "SELECT * FROM usuarios"; PreparedStatement st = null; try { openConn(); st = conn.prepareStatement(sql); ResultSet resultSet = st.executeQuery(); List<Usuario> usuarios = new ArrayList<Usuario>(); while( resultSet.next() ){ int id = resultSet.getInt("id"); String nome = resultSet.getString("nome"); String login = resultSet.getString("login"); String senha = resultSet.getString("senha"); Usuario u = new Usuario(); u.setId(id); u.setNome(nome); u.setLogin(login); u.setSenha(senha); usuarios.add(u); } return usuarios; } catch (SQLException e) { e.printStackTrace(); }finally{ if(st != null) st.close(); conn.close(); } return list(); } }
e20cb5e733c2083a2992604799f6be67fbf07392
[ "Java" ]
1
Java
MinnusV/PWEB20152
86607416fa9c017df58e6d07dab478021d1cf23e
17b9a902ee413d43fb3e66f1aa535bef6a432956
refs/heads/master
<repo_name>imiyoo2010/uwsgi-docs<file_sep>/Lua.rst Using Lua/WSAPI with uWSGI ========================== Compilation notes ----------------- Before compiling the plugin take a look at the :file:`plugins/lua/uwsgiplugin.py` configuration file. If you have installed Lua in some exotic directory you may need to adjust the ``CFLAGS`` and ``LIBS`` values. For example, on a Debian/Ubuntu system you should use something like this: .. code-block:: python import os, sys NAME='lua' CFLAGS = ['-I/usr/include/lua5.1/'] LDFLAGS = [] GCC_LIST = ['lua_plugin'] LIBS = ['-llua5.1'] The ``lua.ini`` buildconf will build uWSGI with embedded Lua support. The ``luap.ini`` buildconf will build Lua support as a plugin. .. code-block:: sh python uwsgiconfig.py --build lua # embedded python uwsgiconfig.py --build luap # plugin # if you have already build the uWSGI core with the default config file... python uwsgiconfig.py --plugin plugins/lua # or if you have used another config file (for example core.ini) python uwsgiconfig.py --plugin plugins/lua core .. note:: It should also be possible to compile Lua against ``luajit`` -- just edit the library and header paths in the :file:`plugins/lua/uwsgiplugin.py` file. Your first WSAPI application ---------------------------- We will use the official WSAPI example, let's call it :file:`pippo.lua`: .. code-block:: lua function hello(wsapi_env) local headers = { ["Content-type"] = "text/html" } local function hello_text() coroutine.yield("<html><body>") coroutine.yield("<p>Hello Wsapi!</p>") coroutine.yield("<p>PATH_INFO: " .. wsapi_env.PATH_INFO .. "</p>") coroutine.yield("<p>SCRIPT_NAME: " .. wsapi_env.SCRIPT_NAME .. "</p>") coroutine.yield("</body></html>") end return 200, headers, coroutine.wrap(hello_text) end return hello Now run uWSGI with the ``lua`` option (remember to add ``--plugins lua`` as the first command line option if you are using it as a plugin) .. code-block:: sh ./uwsgi -s :3031 -M -p 4 --lua pippo.lua -m The Lua plugin's official uwsgi protocol modifier number is ``6``, so remember to set it in your web server configuration with the ``uWSGIModifier1``/``uwsgi_modifier1`` directive. Abusing coroutines ------------------ One of the most exciting feature of Lua is coroutine (cooperative multithreading) support. uWSGI can benefit from this using its async core. The Lua plugin will initialize a ``lua_State`` for every async core. We will use a CPU-bound version of our pippo.lua to test it: .. code-block:: lua function hello(wsapi_env) local headers = { ["Content-type"] = "text/html" } local function hello_text() coroutine.yield("<html><body>") coroutine.yield("<p>Hello Wsapi!</p>") coroutine.yield("<p>PATH_INFO: " .. wsapi_env.PATH_INFO .. "</p>") coroutine.yield("<p>SCRIPT_NAME: " .. wsapi_env.SCRIPT_NAME .. "</p>") for i=0, 10000, 1 do coroutine.yield(i .. "<br/>") end coroutine.yield("</body></html>") end return 200, headers, coroutine.wrap(hello_text) end return hello and run uWSGI with 8 async cores... .. code-block:: sh ./uwsgi -s :3031 -M -p 4 --lua pippo.lua -m --async 8 And just like that, you can manage 8 concurrent requests within a single worker! Threading --------- The Lua plugin is "thread-safe" as uWSGI maps a lua_State to each internal pthread. For example you can run the Sputnik_ wiki engine very easily. Use LuaRocks_ to install Sputnik and ``versium-sqlite3``. A database-backed storage is required as the default filesystem storage does not support being accessed by multiple interpreters concurrently. Create a wsapi compliant file: .. code-block:: lua require('sputnik') return sputnik.wsapi_app.new{ VERSIUM_STORAGE_MODULE = "versium.sqlite3", VERSIUM_PARAMS = {'/tmp/sputnik.db'}, SHOW_STACK_TRACE = true, TOKEN_SALT = 'xxx', BASE_URL = '/', } And run your threaded uWSGI server .. code-block:: sh ./uwsgi --plugins lua --lua sputnik.ws --threads 20 -s :3031 .. _Sputnik: http://sputnik.freewisdom.org/ .. _LuaRocks: http://www.luarocks.org/ A note on memory ---------------- As we all know, uWSGI is parsimonious with memory. Memory is a precious resource. Do not trust software that does not care for your memory! The Lua garbage collector is automatically called after each request. An option to set the frequency at which the GC runs will be available soon. <file_sep>/ConfigLogic.rst Configuration logic =================== Starting from 1.1 certain logic constructs are available. The following statements are currently supported: * ``for`` .. ``endfor`` * ``if-dir`` / ``if-not-dir`` * ``if-env`` / ``if-not-env`` * ``if-exists`` / ``if-not-exists`` * ``if-file`` / ``if-not-file`` * ``if-option`` / ``if-not-option`` -- undocumented * ``if-reload`` / ``if-not-reload`` -- undocumented Each of these statements exports a context value you can access with the special placeholder ``%(_)``. For example, the "for" statement sets ``%(_)`` to the current iterated value. .. warning:: Recursive logic is not supported and will cause uWSGI to promptly exit. for --- For iterates over space-separated strings. The following three code blocks are equivalent. .. code-block:: ini [uwsgi] master = true ; iterate over a list of ports for = 3031 3032 3033 3034 3035 socket = 127.0.0.1:%(_) endfor = module = helloworld .. code-block:: xml <uwsgi> <master/> <for>3031 3032 3033 3034 3035</for> <socket>127.0.0.1:%(_)</socket> <endfor/> <module>helloworld</module> </uwsgi> .. code-block:: sh uwsgi --for="3031 3032 3033 3034 3035" --socket="127.0.0.1:%(_)" --endfor --module helloworld if-env ------ Check if an environment variable is defined, putting its value in the context placeholder. .. code-block:: ini [uwsgi] if-env = PATH print = Your path is %(_) check-static = /var/www endif = socket = :3031 if-exists --------- Check for the existence of a file or directory. The context placeholder is set to the filename found. .. code-block:: ini [uwsgi] http = :9090 ; redirect all requests if a file exists if-exists = /tmp/maintainance.txt route = .* redirect:/offline endif = .. note:: The above example uses :doc:`InternalRouting`. if-file ------- Check if the given path exists and is a regular file. The context placeholder is set to the filename found. .. code-block:: xml <uwsgi> <plugins>python</plugins> <http-socket>:8080</http-socket> <if-file>settings.py</if-file> <module>django.core.handlers.wsgi:WSGIHandler()</module> <endif/> </uwsgi> if-dir ------ Check if the given path exists and is a directory. The context placeholder is set to the filename found. .. code-block:: yaml uwsgi: socket: 4040 processes: 2 if-file: config.ru rack: %(_) endif: <file_sep>/Carbon.rst Integration with Graphite/Carbon ================================ Graphite (http://graphite.wikidot.com/) is a kick-ass realtime graphing application built on top of three components: - Whisper - a data storage system - Carbon - a server for receiving data - A Python web application for rendering and managing graphs The uWSGI Carbon plugin allows you to send uWSGI's internal statistics to one or more Carbon servers. It is compiled in by default as of uWSGI 1.0, though it can also be built as a plugin. Quickstart ---------- For the sake of illustration, let's say your Carbon server is listening on ``127.0.0.1:2003`` and your uWSGI instance is on the machine ``debian32``, listening on ``127.0.0.1:3031`` with 4 processes. By adding the ``--carbon`` option to your uWSGI instance, your server will periodically send its statistics to the carbon server. The default period is 60 seconds. .. code-block:: sh uwsgi --socket 127.0.0.1:3031 --carbon 127.0.0.1:2003 --processes 4 The metrics are named ``uwsgi.<hostname>.<id>.requests`` and ``uwsgi.<hostname>.<id>.worker<n>.requests``. * ``hostname`` will be mapped to the machine hostname * ``id`` is the name of the first uWSGI socket with dots replaced by underscores * ``n`` is the number of the worker process, 1-based. .. code-block:: xxx uwsgi.debian32.127_0_0_1:3031.requests uwsgi.debian32.127_0_0_1:3031.worker1.requests uwsgi.debian32.127_0_0_1:3031.worker2.requests uwsgi.debian32.127_0_0_1:3031.worker3.requests uwsgi.debian32.127_0_0_1:3031.worker4.requests <file_sep>/LogFormat.rst Formatting uWSGI requests logs ============================== uWSGI has a ``--logformat`` option for building custom request loglines. The syntax is simple: .. code-block:: ini [uwsgi] logformat = i am a logline reporting "%(method)``%(uri) %(proto)" returning with status %(status)`` All of the %() marked variables are substituted using specific rules. Three kinds of logvars are defined: offsetof ******** These are taken blindly from the internal ``wsgi_request`` structure of the current request. * ``%(uri)`` -> REQUEST_URI * ``%(method)`` -> REQUEST_METHOD * ``%(user)`` -> REMOTE_USER * ``%(addr)`` -> REMOTE_ADDR * ``%(host)`` -> HTTP_HOST * ``%(proto)`` -> SERVER_PROTOCOL * ``%(uagent)`` -> HTTP_USER_AGENT (starting from 1.4.5) * ``%(referer)`` -> HTTP_REFERER (starting from 1.4.5) functions ********* These are simple functions called for generating the logvar value * ``%(status)`` -> HTTP response status code * ``%(micros)`` -> response time in microseconds * ``%(msecs)`` -> respone time in milliseconds * ``%(time)`` -> timestamp of the start of the request * ``%(ctime)`` -> ctime of the start of the request * ``%(epoch)`` -> the current time in unix format * ``%(size)`` -> response body size + response headers size (since 1.4.5) * ``%(ltime) -> human-formatted (apache style)`` request time (since 1.4.5) * ``%(hsize)`` -> response headers size (since 1.4.5) * ``%(rsize)`` -> response body size (since 1.4.5) * ``%(cl)`` -> request content body size (since 1.4.5) * ``%(pid)`` -> pid of the worker handling the request (since 1.4.6) * ``%(wid)`` -> id of the worker handling the request (since 1.4.6) * ``%(switches)`` -> number of async switches (since 1.4.6) * ``%(vars)`` -> number of CGI vars in the request (since 1.4.6) * ``%(headers)`` -> number of generated response headers (since 1.4.6) * ``%(core)`` -> the core running the request (since 1.4.6) * ``%(vsz)`` -> address space/virtual memory usage (in bytes) (since 1.4.6) * ``%(rss)`` -> RSS memory usage (in bytes) (since 1.4.6) * ``%(vszM)`` -> address space/virtual memory usage (in megabytes) (since 1.4.6) * ``%(rssM)`` -> RSS memory usage (in megabytes) (since 1.4.6) * ``%(pktsize)`` -> size of the internal request uwsgi packet (since 1.4.6) * ``%(modifier1)`` -> modifier1 of the request (since 1.4.6) * ``%(modifier2)`` -> modifier2 of the request (since 1.4.6) User-defined logvars ******************** You can define logvars within your request handler. The variables live only per-request. .. code-block:: python import uwsgi def application(env, start_response): uwsgi.set_logvar('foo', 'bar') # returns 'bar' print uwsgi.get_logvar('foo') uwsgi.set_logvar('worker_id', str(uwsgi.worker_id())) ... With the following log format you will be able to access code-defined logvars. .. code-block:: sh uwsgi --logformat "worker id =``%(worker_id) for request \"%(method) %(uri)`` %(proto)\" test = %(foo)" Apache style combined request logging ************************************* To generate Apache compatible logs: .. code-block:: ini [uwsgi] ... log-format =``%(addr) - %(user) [%(ltime)] "%(method) %(uri) %(proto)" %(status) %(size)`` "%(referer)" "%(uagent)" ... Hacking logformat ***************** To add more C-based variables, open logging.c and add them to the end of the file. .. code-block:: c if (!uwsgi_strncmp(ptr, len, "uri", 3)) { logchunk->pos = offsetof(struct wsgi_request, uri); logchunk->pos_len = offsetof(struct wsgi_request, uri_len); } else if (!uwsgi_strncmp(ptr, len, "method", 6)) { logchunk->pos = offsetof(struct wsgi_request, method); logchunk->pos_len = offsetof(struct wsgi_request, method_len); } else if (!uwsgi_strncmp(ptr, len, "user", 4)) { logchunk->pos = offsetof(struct wsgi_request, remote_user); logchunk->pos_len = offsetof(struct wsgi_request, remote_user_len); } else if (!uwsgi_strncmp(ptr, len, "addr", 4)) { logchunk->pos = offsetof(struct wsgi_request, remote_addr); logchunk->pos_len = offsetof(struct wsgi_request, remote_addr_len); } else if (!uwsgi_strncmp(ptr, len, "host", 4)) { logchunk->pos = offsetof(struct wsgi_request, host); logchunk->pos_len = offsetof(struct wsgi_request, host_len); } else if (!uwsgi_strncmp(ptr, len, "proto", 5)) { logchunk->pos = offsetof(struct wsgi_request, protocol); logchunk->pos_len = offsetof(struct wsgi_request, protocol_len); } else if (!uwsgi_strncmp(ptr, len, "status", 6)) { logchunk->type = 3; logchunk->func = uwsgi_lf_status; logchunk->free = 1; } For function-based vars the prototype is: .. code-block:: c ssize_t uwsgi_lf_foobar(struct wsgi_request *wsgi_req, char **buf); where ``buf`` is the destination buffer for the logvar value (this will be automatically freed if you set ``logchunk->free`` as in the "status" related C-code previously reported). .. code-block:: c ssize_t uwsgi_lf_status(struct wsgi_request *wsgi_req, char **buf) { *buf = uwsgi_num2str(wsgi_req->status); return strlen(*buf); } <file_sep>/Changelog-2.0.rst Changelog-2.0 ============= This is a memo for what we plan to include in uWSGI 2.0 (LTS) Metric subsystem **************** think about persistent storage Better Erlang integration ************************* remove dependancies with libei Corerouters backup nodes ************************ On-demand threading mode ************************ Instead of pre-spawning threads in each worker, just spawn a single one that will generate a new one at each request. Emperor binary patching *********************** Emperor clustering ****************** The Legion subsystem will be integrated with the Emperor, allowing the cluster to distribute multiple application on multiple nodes in a balanced way. Broodlord mode will be updated accordingly. <file_sep>/Async.rst uWSGI asynchronous/nonblocking modes (updated to uWSGI 1.9) =========================================================== .. warning:: Beware! Async modes will not speedup your app, they are aimed at improving concurrency. Do not expect enabling some of the modes will work flawlessly, asynchronous/evented/nonblocking systems require app cooperation, so if your app is not developed following specific async engine rules you are doing wrong. Do not trust people suggesting you to blindly use async/evented/nonblocking systems !!! Glossary -------- uWSGI, following its modular approach, split async engines in two families: Suspend/Resume engine ********************* They simply implement coroutine/greenthreads techniques. They have no event engine, so you have to use the one supplied by uWSGI. An Event engine is generally a library exporting primitives for platform-independent non-blocking I/O (Examples are libevent, libev, libuv...). The uWSGI event engine is automatically enabled using the ``--async <n>`` option Currently the uWSGI distribution includes the following suspend/resume engines: * ``uGreen`` - Unbit's greenthread implementation (based on `swapcontext()`) * ``Greenlet`` - Python greenlet module * ``Stackless`` Stackless Python * ``Fiber`` - Ruby 1.9 fibers Running the uWSGI async mode without a proper suspend/resume engine will raise a warning, so for a minimal non-blocking app you will need something like that: .. code-block:: sh uwsgi --async 100 --ugreen --socket :3031 An important aspect of suspend/resume engines is that they can easily destroy your process if it is not aware of them. Some of the language plugins (most notably Python) has hooks to cooperate flawlessly with coroutine/greenthreads. Other languages may fail miserably. Always check the uWSGI mailing list or IRC channel for updated information. Older uWSGI releases supported an additional system: callbacks. Callbacks is the approach used by popular systems like node.js. This approach requires HEAVY app cooperation, and for complex projects like uWSGI dealing with this is extremely complex. For that reason, callback approach IS NOT SUPPORTED (even if technically possible) Loop engines ************ Loop engines are packages/libraries exporting both suspend/resume techniques and an event system. When loaded, they override the way uWSGI manages connections and signal handlers (uWSGI-signals NOT POSIX signals !). Currently uWSGI supports the following loop engines: * ``Gevent`` (Python, libev, greenlet) * ``Coro::AnyEvent`` (Perl, coro, anyevent) Although they are generally used by a specific language, pure-C uWSGI plugins (like the CGI one) can use them without problems to increase concurrency. Async switches -------------- To enable one of the async mode, you use the --async option (or some shortcut for it exported by loop engine plugins). The argument of the --async option is the number of 'cores' to initialize. Each core can manage a single request, so the more core you spawn, more requests you will be able to manage (and more memory you will use...). The job of the suspend/resume engines is stopping the current request management and moving to another core, and eventually come back to the old one and so on. Technically, cores ar simple memory structures holding request's data, but to give the user the illusion of a multithread system we use that term. The switch between cores needs app cooperation. There are various way to accomplish that, and generally if you are using a loop engine, all is automagic (or require very little effort) .. warning:: If you are in doubt DO NOT USE ASYNC MODE. Running uWSGI in Async mode --------------------------- To start uWSGI in async mode pass the ``async`` option with the number of "async cores" you want. .. code-block:: sh ./uwsgi --socket :3031 -w tests.cpubound_async --async 10 This will start uWSGI with 10 async cores. Each async core can manage a request, so with this setup you can accept 10 concurrent requests with only one process. You can also start more processes (with the ``processes`` option). Each one will have its pool of async cores. When using :term:`harakiri` mode, every time an async core accepts a request the harakiri timer is reset. So even if a request blocks the async system, harakiri will save you. The ``tests.cpubound_async`` app is included in the source distribution. It's very simple: .. code-block:: python def application(env, start_response): start_response( '200 OK', [ ('Content-Type','text/html') ]) for i in range(1,10000): yield "<h1>%s</h1>" % i Every time the application calls ``yield`` from the response function, the execution of the app is stopped, and a new request or a previously suspended request on another async core will take over. This means the number of async core is the number of requests that can be queued. If you run the ``tests.cpubound_async`` app on a non-async server, it will block all processing, not accepting other requests until the heavy cycle of 10000 ``<h1>`` s is done. Waiting for I/O --------------- If you are not under a loop engine, you can use the uWSGI api to wait for I/O events Currently only 2 functions are exported * :py:func:`uwsgi.wait_fd_read` * :py:func:`uwsgi.wait_fd_write` These functions may be called in succession to wait for multiple file descriptors: .. code-block:: python uwsgi.wait_fd_read(fd0) uwsgi.wait_fd_read(fd1) uwsgi.wait_fd_read(fd2) yield "" # Yield the app, let uWSGI do its magic Sleeping -------- On occasion you might want to sleep in your app, for example to throttle bandwidth. Instead of using the blocking ``time.sleep(N)`` function, use ``uwsgi.async_sleep(N)`` to yield control for N seconds. .. seealso:: See :file:`tests/sleeping_async.py` for an example. Suspend/Resume -------------- Yielding from the main application routine is not very practical as most of the time your app is more advanced than a simple callable and formed of tons of functions and various levels of call depth. Worry not! You can force a suspend (using coroutine/greenthread) simply calling ``uwsgi.suspend()`` .. code-block:: python uwsgi.wait_fd_read(fd0) uwsgi.suspend() uwsgi.suspend() will automatically call the chosen suspend engine (uGreen, greenlet...) Static files ------------ Static file serving will automatically use the loaded async engine.<file_sep>/Spooler.rst The uWSGI Spooler ================= The Spooler is a queue manager built in to uWSGI that works like a printing/mail system. For example you can enqueue massive sending of emails, image processing, video encoding, etc. and let the spooler do the hard work in background while your users get their requests served by normal workers. Using the message passing feature of the uWSGI server you can even send your spool request to a remote uWSGI server. You choose a directory (or directories) as a spool. uWSGI will then repeatedly look for files in this spool directory and use them as arguments for callables. After the callable returns, the file is removed. To use the spooler you need to pass the ``-Q`` argument (``spooler`` option), followed by the directory you want to use as your spool scratch space. .. code-block:: sh ./uwsgi -Q myspool -s /tmp/uwsgi.sock --buffer-size 8192 --wsgi testapp --sharedarea 10 If you think you'll be passing large messages, set a bigger buffer size using the ``buffer-size`` (``-b``) option. Setting the spooler callable ---------------------------- Add a new function to your script: .. code-block:: py def myspooler(env): print env for i in range(1,100): time.sleep(1) return uwsgi.SPOOL_OK uwsgi.spooler = myspooler Using the uwsgi.spooler attribute you will set the callable to execute for every spool/queue/message file. .. warning:: Using ``uwsgi.spooler`` is a low-level approach. Use the Python decorators or the Ruby DSL if you use those languages. To enqueue a request (a dictionary of strings!) use :func:`uwsgi.send_to_spooler`: .. code-block:: py uwsgi.send_to_spooler({'Name':'Serena', 'System':'Linux', 'Tizio':'Caio'}) How does the uWSGI server recognize a spooler request? ------------------------------------------------------ The queue/message/spool files are normally dictionaries that contain only strings encoded in the uwsgi protocol format. This also means that can use the uWSGI server to manage remote messaging. Setting the uwsgi modifier 1 to ``UWSGI_MODIFIER_SPOOL_REQUEST`` (numeric value 17) you will inform the uWSGI server that the request is a spooling request. This is what ``uwsgi.send_to_spooler`` does in the background, but you can use your webserver support for uwsgi_modifiers for doing funny things like passing spooler message without using your wsgi apps resource but only the spooler. An example of just this, using Nginx: .. code-block:: nginx location /sendmassmail { uwsgi_pass 192.168.1.1:3031; uwsgi_modifier1 17; uwsgi_param ToGroup customers; } Supposing you have a callable that sends email to a group specified in the ``ToGroup`` dictionary key, this would allow you to enqueue mass mails using Nginx only. Tips and tricks --------------- You can re-enqueue a spooler request by returning ``uwsgi.SPOOL_RETRY`` in your callable: .. code-block:: py def call_me_again_and_again(env): return uwsgi.SPOOL_RETRY You can set the spooler poll frequency using :py:func:`uwsgi.set_spooler_frequency`, where N is the number of seconds to sleep before redoing a spooler scan. You can use this to build a cron-like system. .. code-block:: py # run function every 22 secs s_freq = 22 def emu_cron(env): # run your function long_func("Hello World") # and re-enqueue it return uwsgi.SPOOL_RETRY uwsgi.set_spooler_frequency(s_freq) uwsgi.spooler = emu_cron # start the emu_cron uwsgi.send_to_spooler({'Name':'Alessandro'}) * You can also schedule spool a task to be specified only after a specific UNIX timestamp has passed by specifying the 'at' argument. .. code-block:: py import time, uwsgi # uwsgi.spool is a synonym of uwsgi.send_to_spooler uwsgi.spool(foo='bar',at=time.time()+60) # Let's do something in a minute, okay? * You can attach a binary ``body`` larger than the dictionary size limit with the ``body`` parameter. (Remember that it will be loaded into memory in the spooler though.) .. code-block:: py uwsgi.spool({"body": my_pdf_data}) * You could use the :doc:`Caching <caching framework>` as shared memory to send progress data, etc. back to your application.<file_sep>/KSM.rst Using Linux KSM in uWSGI ======================== Kernel Samepage Merging <http://www.linux-kvm.org/page/KSM> is a feature of Linux kernels >= 2.6.32 which allows processes to share pages of memory with the same content. This is accomplished by a kernel task that scans specific memory areas and compares periodically, and when possible, merges them. Born as an enhancement for KVM it can be used for processes using common data such as uWSGI processes with language interpreters and standard libraries. If you are lucky, using KSM could exponentially reduce the memory usage of your uWSGI instances. Especially in massive :doc:`Emperor<Emperor>` deployments enabling KSM in each vassal may result in massive memory savings. KSM in uWSGI was the idea of <NAME> of Asidev s.r.l. http://www.asidev.com/en/company.html .Many thanks to him. Enabling the KSM daemon ----------------------- To enable the KSM kernel daemon, simply set ``/sys/kernel/mm/ksm/run`` to 1, like so: .. code-block:: sh echo 1 > /sys/kernel/mm/ksm/run .. note:: Remember to do this on machine startup, as the KSM daemon does not run by default. .. note:: Note that KSM is an opt-in feature that has to be explicitly requested by processes, so just enabling KSM will not be a savior for everything on your machine. Enabling KSM support in uWSGI ----------------------------- If you have compiled uWSGI on a kernel with KSM support, you will be able to use the ``ksm`` option. This option will instruct uWSGI to register process memory mappings to the KSM daemon after each request or master cycle. If no page mapping has changed from the last scan, no expensive syscalls are used. (Each mapping requires a ``madvise`` call.) Performance impact ------------------ Checking for process mappings requires parsing the /proc/self/maps file after each request. In some setups this may hurt performance. You can tune the frequency of the uWSGI page scanner by passing an argument to the ``ksm`` option. .. code-block:: sh # Scan for process mappings every 10 requests (or 10 master cycles) ./uwsgi -s :3031 -M -p 8 -w myapp --ksm=10 Check if KSM is working well ---------------------------- The /sys/kernel/mm/ksm/pages_shared and /sys/kernel/mm/ksm/pages_sharing files contain statistics regarding KSM's efficiency. Higher values means lesser memory consumption for your uWSGI instances. KSM statistics using collectd ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ A simple bash script like this is useful for keeping an eye on KSM's efficiency. .. code-block:: sh #!/bin/bash export LC_ALL=C if [ -e /sys/kernel/mm/ksm/pages_sharing ]; then pages_sharing=`cat /sys/kernel/mm/ksm/pages_sharing`; page_size=`getconf PAGESIZE`; saved=$(echo "scale=0;$pages_sharing * $page_size"|bc); echo "PUTVAL <%= cn %>/ksm/gauge-saved interval=60 N:$saved" fi In your collectd configuration, add something like this. .. code-block:: ini LoadPlugin exec <Plugin exec> Exec "nobody" "/usr/local/bin/ksm_stats.sh" </Plugin> <file_sep>/SPDY.rst The SPDY router (uWSGI 1.9) =========================== Starting from uWSGI 1.9 the HTTPS router has been extended to support version 3 of the SPDY protocol. To run the HTTPS router with SPDY support use the ``--https2`` option: .. code-block:: sh uwsgi --https2 addr=0.0.0.0:8443,cert=foobart.crt,key=foobar.key,spdy=1 --module werkzeug.testapp:test_app This will start an HTTPS router on port 8443 with SPDY support, forwarding requests to the werkzeug test app the instance is running. If you go to https://address:8443/ with a SPDY-enabled browser you will see additional WSGI vars reported by werkzeug: * ``SPDY`` set to 'on' * ``SPDY.version`` reports protocol version (generally '3') * ``SPDY.stream`` reports the stream identifier (an odd number) Notes ***** * You need at least OpenSSL version 1.x to use SPDY (all of the modern Linux distros should have it). * During uploads the window size is constantly updated. * The ``--http-timeout`` directive is used to set the SPDY timeout. This is the maximum amount of inactivity time after the SPDY connection is closed. * ``PING`` requests from the browsers are ALL acknowledged. * On connect, the SPDY router sends a settings packet to the client with optimal values. * If a stream fails in some catastrophic way, the whole connection is closed hard. * RST messages are always honoured TODO **** * Add old SPDY v2 support (is it worth it?) * Allow PUSHing of resources from the uWSGI cache * Allow tuning internal buffers <file_sep>/PSGIquickstart.rst Quickstart for perl/PSGI applications ===================================== still need to be ported, check the old version here: http://projects.unbit.it/uwsgi/wiki/QuickstartPSGI <file_sep>/SharedArea.rst SharedArea -- share data between workers ======================================== .. warning:: SharedArea is a very low-level mechanism. For an easier-to-use alternative, see the :doc:`Caching<Caching>` and :doc:`Queue<Queue>` frameworks. You can share data between workers (sessions, counters etc. etc.) by enabling the ``sharedarea`` (``-A``) option with the number of pages you want to allocate. If you need an 8 KiB shared area on a system with 4 KiB pages, you would use ``sharedarea=2``. The shared data area is then usable through the :ref:`uWSGI API<SharedAreaAPI>`. This area is completely SMP safe as all operations are governed by a rw_lock. .. warning:: The shared area might not be supported under Python 3. It's unclear whether this is true. .. TODO: Fix the above...<file_sep>/Namespaces.rst Jailing your apps using Linux Namespaces ======================================== If you have a recent Linux kernel (>2.6.26) you can use its support for namespaces for added security. What are namespaces? -------------------- They are an elegant (more elegant than most of the jailing systems you might find in other operating systems) way to "detach" your processes from a specific layer of the kernel and assign them to a new one. The 'chroot' system available on UNIX/Posix systems is a primal form of namespaces: a process sees a completely new file system root and has no access to the original one. Linux extends this concept to the other OS layers (PIDs, users, IPC, networking etc.), so a specific process can live in a "virtual OS" with a new group of pids, a new set of users, a completely unshared IPC system (semaphores, shared memory etc.), a dedicated network interface and its own hostname. uWSGI can "jail" its processes using Linux namespaces. Being a networked application, it will not switch networking namespaces, and to keep sysadmins reasonably sane, users are kept untouched too. All this put together, a namespace-constrained uWSGI stack will not see other processes running in the system, will not be able to access other processes' IPC, will not be able to access the original root filesystem and will have a dedicated hostname. A real world example: Jailing the uWSGI Control Center in Ubuntu 10.10 ---------------------------------------------------------------------- Let's start by creating a new root filesystem for our jail. You'll need ``debootstrap``. We're placing our rootfs in ``/ns/001``, and then create a 'uwsgi' user that will run the uWSGI server. We will use the chroot command to 'adduser' in the new rootfs, and we will install the Flask package, required by uwsgicc. All this needs to be executed as root. .. code-block:: sh mkdir -p /ns/001 debootstrap maverick /ns/001 chroot /ns/001 # in the chroot jail now adduser uwsgi apt-get install mercurial python-flask su - uwsgi # as uwsgi now git clone https://github.com/unbit/uwsgicc.git . exit # out of uwsgi exit # out of the jail Now on your real system run .. code-block:: sh uwsgi --socket 127.0.0.1:3031 --chdir /home/uwsgi/uwsgi --uid uwsgi --gid uwsgi --module uwsgicc --master --processes 4 --namespace /ns/001:mybeautifulhostname If all goes well, uWSGI will set ``/ns/001`` as the new root filesystem, assign ``mybeautifulhostname`` as the hostname and hide the PIDs and IPC of the host system. The first thing you should note is the uWSGI master becoming the pid 1 (the "init" process). All processes generated by the uWSGI stack will be reparented to it if something goes wrong. If the master dies, all jailed processes die. Now point your webbrowser to your webserver and you should see the uWSGI Control Center interface. Pay attention to the information area. The nodename (used by cluster subsystem) matches the real hostname as it does not make sense to have multiple jail in the same cluster group. In the hostname field instead you will see the hostname you have set. Another important thing is that you can see all the jail processes from your real system (they will have a different set of PIDs), so if you want to take control of the jail you can easily do it. .. note:: A good way to limit hardware usage of jails is to combine them with the cgroups subsystem. .. seealso:: :doc:`Cgroups` Reloading uWSGI --------------- When running jailed, uWSGI uses another system for reloading: it'll simply tell workers to bugger off and then exit. The parent process living outside the namespace will see this and respawn the stack in a new jail. How secure is this sort of jailing? ----------------------------------- Hard to say! All software tends to be secure until a hole is found. Additional filesystems ---------------------- When app is jailed to namespace it only has access to its virtual jail root filesystem. If there is any other filesystem mounted inside the jail directory, it won't be accessible, unless you use ``namespace-keep-mount``. .. code-block:: ini # app1 jail is located here namespace = /apps/app1 # nfs share mounted on the host side namespace-keep-mount = /apps/app1/nfs This will bind /apps/app1/nfs to jail, so that jailed app can access it under /nfs directory .. code-block:: ini # app1 jail is located here namespace = /apps/app1 # nfs share mounted on the host side namespace-keep-mount = /mnt/nfs1:/nfs If the filesystem that we want to bind is mounted in path not contained inside our jail, than we can use "<source>:<dest>" syntax for --namespace-keep-mount. In this case the /mnt/nfs1 will be binded to /nfs directory inside the jail. <file_sep>/_options/parse_c.py # Parse "struct uwsgi_option ..._options[] = { }" lists into Python files for inclusion into optdefs. # Good luck! from pycparser import CParser from pycparser.c_ast import NodeVisitor, Constant import re import sys DIRECTIVE_RE = re.compile("^#(.+)$", re.MULTILINE) class DictWrapper(object): def __init__(self, dict): self.dict = dict def __getattr__(self, key): return self.dict[key] class OptionParser(NodeVisitor): def __init__(self): self.commands = [] def visit_ExprList(self, node): bits = [n[1] for n in node.children()] if isinstance(bits[0], Constant) and bits[0].type == "string": self.add_option(node, bits) self.generic_visit(node) def parse_file(self, filename): parser = CParser() buf = file(filename).read() buf = DIRECTIVE_RE.sub("", buf)#r"/* directive \1 elided */", buf) t = parser.parse(buf, filename) self.visit(t) def add_option(self, node, bits): cmd = { "names": [bits[0].value.replace('"', '')], "argument": bits[1].name.replace("_argument", ""), "short_name": None, "help": bits[3].value.replace('"', ''), "type": None } if bits[2].type == "char": cmd["short_name"] = bits[2].value.replace("'", "") setter = bits[4].name if setter == "uwsgi_opt_true" or cmd["argument"] == "no": cmd["type"] = "True" elif setter == "uwsgi_opt_set_str": cmd["type"] = "str" elif setter == "uwsgi_opt_set_int": cmd["type"] = "int" elif setter == "uwsgi_opt_set_64bit": cmd["type"] = "long" elif setter == "uwsgi_opt_add_string_list": cmd["type"] = "[str]" else: print >>sys.stderr, "Setter? %s, %r" % (setter, cmd) cmd["type"] = repr(setter.replace("uwsgi_opt_", "").replace("_", " ")) for tcmd in self.commands: if cmd["help"] == tcmd.help: tcmd.names.append(cmd["names"][0]) return False self.commands.append(DictWrapper(cmd)) def write_py(self, stream): W = stream.write W("\n") W("\n") W("def XXX_config():\n") W('\tconfig = Config("XXX")\n') W('\t\n') W('\twith config.section("XXX", docs = []) as s:\n') for cmd in self.commands: tp = cmd.type if cmd.argument == "optional": tp = "optional(%s)" % tp if len(cmd.names) == 1: names = '"%s"' % cmd.names[0] else: names = "(%s)" % (", ".join('"%s"' % n for n in cmd.names)) W('\t\ts.o(%s, %s, "%s"' % (names, tp, cmd.help)) if cmd.short_name: W(', short_name="%s"' % cmd.short_name) W(")\n") W("\t\n") W("\treturn config\n") def main(filename): op = OptionParser() op.parse_file(filename) op.write_py(sys.stdout) if __name__ == '__main__': main(sys.argv[1])
daa905cc41481d40ce460c647ee6c9af3dbeca9b
[ "Python", "reStructuredText" ]
13
reStructuredText
imiyoo2010/uwsgi-docs
c515eade7cdb6ae4cb4d2e191eb1e185cffcdefd
2739f9ef8d502072fad3ddfee0b787a96fdbf060
refs/heads/master
<file_sep>//generate the dynamic data using KO methods: observable, binding, data-bind. function ViewModel(mapModel) { var self = this; //generate a location list. self.locSearchInput = ko.observable(''); self.locationList = ko.computed(function() { var list = []; if (self.locSearchInput() === '') { mapModel.totallist.forEach(function(location) { list.push(location[0]); }); mapModel.markers.forEach(function(marker) { marker.setMap(mapModel.map); }); //console.log(list); return list; } else { mapModel.totallist.forEach(function(location) { if (location[0].toLowerCase().indexOf(self.locSearchInput().toLowerCase()) >= 0) { list.push(location[0]); } }); mapModel.markers.forEach(function(marker) { if (list.indexOf(marker.title) >= 0) { marker.setMap(mapModel.map); } else { marker.setMap(null); } }); return list; } }); self.searchContent = function(location){ mapModel.markers.forEach(function(marker) { if (location == marker.title) { var wikipediaURL = 'http://zh.wikipedia.org/w/api.php?action=opensearch&search=' + location + '&format=json'; $.ajax(wikipediaURL, { dataType: 'jsonp' }) .done(function(data) { if (data[2][0] !== undefined) { var title = "<h2> " + data[0] + "</h2>"; mapModel.infowindow.setContent(title+data[2][0]); } else { mapModel.infowindow.setContent('No WikiPedia article found.'); } }) .fail(function() { mapModel.infowindow.setContent('Wikipedia Articles Could Not Be Loaded'); }); mapModel.infowindow.open(mapModel.map,marker); marker.setMap(mapModel.map); mapModel.map.setCenter(marker.getPosition()); } }); }; } //create map, data here are fixed. function MapModel() { var self = this; self.totallist = []; self.markers = []; //initialize the basic map with markers by google map nearBySearch. self.initialize = function() { var pyrmont = new google.maps.LatLng(30.51853, 114.36214); self.map = new google.maps.Map(document.getElementById('map-canvas'), { center: pyrmont, zoom: 13 }); var request = { location: pyrmont, radius: 50000, types: ['university'], }; var callback = function(results, status) { if (status == google.maps.places.PlacesServiceStatus.OK) { for (var i = 0; i < results.length; i++) { self.createMarker(results[i]); } } }; self.infowindow = new google.maps.InfoWindow(); var service = new google.maps.places.PlacesService(self.map); service.nearbySearch(request, callback); }; //create markers. self.createMarker = function(place) { var placeLoc = place.geometry.location; var marker = new google.maps.Marker({ title: place.name, position: place.geometry.location }); self.markers.push(marker); self.totallist.push([place.name,placeLoc[0],placeLoc[1]]); marker.setMap(self.map); google.maps.event.addListener(marker, 'click', function() { self.searchContent(marker.title); }); }; //using a wikipedia API to show more information. self.searchContent = function(location){ self.markers.forEach(function(marker) { if (location == marker.title) { var wikipediaURL = 'http://zh.wikipedia.org/w/api.php?action=opensearch&search=' + location + '&format=json'; $.ajax(wikipediaURL, { dataType: 'jsonp' }) .done(function(data) { if (data[2][0] !== undefined) { var title = "<h2>" + data[0] + "</h2>" ; self.infowindow.setContent(title +data[2][0]); } else { self.infowindow.setContent('No WikiPedia article found.'); } }) .fail(function() { self.infowindow.setContent('Wikipedia Articles Could Not Be Loaded'); }); self.infowindow.open(self.map,marker); marker.setMap(self.map); self.map.setCenter(marker.getPosition()); } }); }; } //load when open window $(window).load(function() { var mapModel = new MapModel(); mapModel.initialize(); var viewModel; var create = function() { viewModel = new ViewModel(mapModel); ko.applyBindings(viewModel); }; //in case list showing before markers being pushed. setTimeout(create, 3000); });
d1c3d1f87bfa2a040ff33f1f8d0def2342eeea47
[ "JavaScript" ]
1
JavaScript
zvdifo/P5-neighborhoodMap
adadf327f2dfaf665e8e644b07f1aa7ccd288d69
f0cac7cc2faeaae524d316349b2e6eed513dc4bb
refs/heads/master
<file_sep>% matplotlib notebook import matplotlib.pyplot as plt import numpy as np def circle_bound(x): y = np.sqrt(1-x**2) #print(y) return y def make_pi(tot_points): circ_points=0 for i in range(tot_points): point_x = np.random.uniform(0,1) point_y = np.random.uniform(0,1) if circle_bound(point_x) >= point_y: circ_points = circ_points+1 pi = 4 * (circ_points/tot_points) return pi
fb643c7fe868a3b9103f59f362d77e0ac803f995
[ "Python" ]
1
Python
jenniferokane/rcsc18_lessons
375166347e3e22387c645fa6a89907f01f9c983d
8294b1ede48fa1245df9160838511a5608235160
refs/heads/main
<file_sep># PetAdoption ## Speed Code Part 1 with SwiftUI [![IMAGE ALT TEXT](http://img.youtube.com/vi/Zm_HxZjBQNs/0.jpg)](http://www.youtube.com/watch?v=Zm_HxZjBQNs "Speed Code Part 1") ## Speed Code Part 2 with SwiftUI [![IMAGE ALT TEXT](http://img.youtube.com/vi/4OvgQOKb3ps/0.jpg)](http://www.youtube.com/watch?v=4OvgQOKb3ps "Speed Code Part 2") <file_sep>// // MasterView.swift // PetAdoption // // Created by <NAME> on 23/1/21. // import SwiftUI struct MasterView: View { @State var selectedTabBarType: TabBarType = .home enum TabBarType: String, Identifiable, CaseIterable { case home, message, favorite, profile var image: String { "ic.\(rawValue)" } var id: String { rawValue.capitalized } } var body: some View { GeometryReader { geometry in NavigationView { VStack { switch selectedTabBarType { case .home: HomeView() default: Color.white } HStack { ForEach(TabBarType.allCases) { eachTab in Spacer() TabBarItemView(tabBarType: eachTab, isActive: eachTab == selectedTabBarType) .onTapGesture { selectedTabBarType = eachTab } } Spacer() } .frame(maxWidth: .infinity, minHeight: geometry.safeAreaInsets.bottom + 49) .overlay(Divider(), alignment: .top) } .edgesIgnoringSafeArea(.bottom) } } } } struct TabBarItemView: View { var tabBarType: MasterView.TabBarType var isActive: Bool var body: some View { HStack { Image(tabBarType.image) isActive ? Text(tabBarType.id) .font(.system(size: 14, weight: .regular)) .lineLimit(1) .frame(width: 50) : nil } .padding(6) .foregroundColor(isActive ? .white : .accent) .background(isActive ? Color.primaryDark : .clear) .cornerRadius(isActive ? 16 : 0) } } struct MasterViewPreview: PreviewProvider { static var previews: some View { MasterView() } } <file_sep>// // ContentView.swift // PetAdoption // // Created by <NAME> on 17/1/21. // import SwiftUI struct ContentView: View { @State var currentIndex: Int = 0 @State var isPresented: Bool = false private let _maxIndex = 2 var body: some View { ZStack { Color.primaryColor .frame(maxWidth: .infinity, maxHeight: .infinity) .edgesIgnoringSafeArea(.all) VStack(alignment: .center, spacing: 20) { PagingView(index: $currentIndex, maxIndex: _maxIndex) { SplashView(image: "splash.image.1", title: "Make new Friends", description: "Here you can meet your dream friend and joy with them") SplashView(image: "splash.image.2", title: "Don't Shop! Adopt", description: "Most adoptable pets come from loving homes that simply cannot care for them anymore.") SplashView(image: "splash.image.3", title: "Adopt a new friend", description: "There's a saying. If you want someone to love you forever, adopt a new friend, feed it and keep it around.") } PagingControlView(index: $currentIndex, maxIndex: _maxIndex) HStack { Button(action:{ if currentIndex <= 0 { return } currentIndex -= 1 }) { Text("Back") .foregroundColor(.white) .font(.system(size: 18, weight: .medium)) } .frame(width: 115, height: 80, alignment: .center) .background(Color.primaryDark) .clipShape(RoundedCorner(radius: 35, corners: [.topRight, .bottomRight])) Spacer() Button(action:{ isPresented.toggle() }) { Text("Start") .foregroundColor(.primaryColor) .font(.system(size: 18, weight: .medium)) } .fullScreenCover(isPresented: $isPresented, content: { MasterView() }) .frame(width: 115, height: 80, alignment: .center) .background(Color.white) .clipShape(RoundedCorner(radius: 35, corners: [.topLeft, .bottomLeft])) } } } } } struct SplashView: View { let image: String let title: String let description: String var body: some View { VStack(alignment: .center, spacing: 20) { Image(image) .frame(maxWidth: .infinity) VStack(alignment: .leading, spacing: 10) { Text(title) .font(.system(size: 30, weight: .medium)) Text(description) .font(.system(size: 16, weight: .regular)) } .foregroundColor(.white) .padding(.leading) .padding(.trailing) } } } struct PagingView<Content>: View where Content: View { @Binding var index: Int let maxIndex: Int let content: () -> Content @State private var _offset: CGFloat = .zero @State private var _isDragging = false init(index: Binding<Int>, maxIndex: Int, @ViewBuilder content: @escaping() -> Content) { self._index = index self.maxIndex = maxIndex self.content = content } var body: some View { GeometryReader { geometry in ScrollView(.horizontal, showsIndicators: false) { HStack(spacing: 0) { self.content() .frame(width: geometry.size.width, height: geometry.size.height) .clipped() } } .content.offset(x: self.offset(in: geometry), y: 0) .frame(width: geometry.size.width, alignment: .leading) .gesture( DragGesture().onChanged { value in _isDragging = true _offset = -CGFloat(self.index) * geometry.size.width + value.translation.width } .onEnded { value in let predictedEndOffset = -CGFloat(self.index) * geometry.size.width + value.predictedEndTranslation.width let predictedIndex = Int(round(predictedEndOffset / -geometry.size.width)) self.index = clampedIndex(from: predictedIndex) withAnimation(.easeOut) { _isDragging = false } } ) }.clipped() } func offset(in geometry: GeometryProxy) -> CGFloat { if _isDragging { return max(min(self._offset, 0), -CGFloat(self.maxIndex) * geometry.size.width) } return -CGFloat(self.index) * geometry.size.width } func clampedIndex(from predictedIndex: Int) -> Int { let newIndex = min(max(predictedIndex, self.index - 1), self.index + 1) guard newIndex >= 0 else { return 0 } guard newIndex <= maxIndex else { return maxIndex } return newIndex } } struct PagingControlView: View { @Binding var index: Int let maxIndex: Int var normalPageControl: some View { Circle() .stroke(Color.white) .frame(width: 8, height: 8) } var selectedPageControl: some View { RoundedRectangle(cornerRadius: 4) .fill(Color.primaryDark) .frame(width: 20, height: 9) } var body: some View { HStack(spacing: 8) { ForEach(0...maxIndex, id: \.self) { index in self.index == index ? selectedPageControl : nil self.index == index ? nil : normalPageControl } } } } struct RoundedCorner: Shape { var radius: CGFloat = 0.0 var corners: UIRectCorner = [] func path(in rect: CGRect) -> Path { let path = UIBezierPath(roundedRect: rect, byRoundingCorners: corners, cornerRadii: .init(width: radius, height: radius)) return Path(path.cgPath) } } struct ContentView_Previews: PreviewProvider { static var previews: some View { ContentView() } } <file_sep>// // PetDetailView.swift // PetAdoption // // Created by <NAME> on 23/1/21. // import SwiftUI struct PetDetailView: View { @State var isFavorite: Bool = false @State var currentIndex: Int = 0 let pet: Pet private var _trailingView: some View { Image(systemName: isFavorite ? "heart.fill" : "heart") .foregroundColor(.primaryColor) .frame(width: 36, height: 36) .background(Color.white) .cornerRadius(18) .onTapGesture { isFavorite.toggle() } } var body: some View { VStack { ScrollView (.vertical) { ZStack(alignment: Alignment.bottom) { PagingView(index: $currentIndex, maxIndex: pet.images.count - 1) { ForEach(pet.images, id:\.self) { image in Image(image) .resizable() .clipShape(RoundedCorner(radius: 32, corners: [.bottomLeft, .bottomRight])) } } HStack(spacing: 8) { ForEach(0...(pet.images.count - 1), id: \.self) { index in Circle() .fill(currentIndex == index ? Color.primaryColor : Color.primaryDark) .frame(width: currentIndex == index ? 12 : 8, height: currentIndex == index ? 12 : 8) } } .padding(.bottom, 10) }.frame(height: 355, alignment: .center) HStack(spacing: 20) { BoxDetailView(title: "Age", description: "\(pet.age) Months") BoxDetailView(title: "Weight", description: "\(pet.weight) kg") BoxDetailView(title: "Sex", description: pet.gender.rawValue.capitalized) } .padding(.top, 10) VStack(alignment: .leading, spacing: 10) { HStack { Text(pet.name) .font(.system(size: 18, weight: .medium)) Spacer() Text(pet.breed.description) .font(.system(size: 18, weight: .regular)) } .padding(.top) HStack { Image("location") Text("<NAME>, Cambodia") .font(.system(size: 14)) .foregroundColor(.gray) Spacer() } Spacer().frame(height: 8) Text("About") .font(.system(size: 18, weight: .medium)) Text(pet.description) .font(.system(size: 16, weight: .regular)) .lineSpacing(5) } .foregroundColor(.darkText) .padding() .frame(maxWidth: .infinity, alignment: .leading) } HStack { Button(action: {}) { HStack { Image("paw") Text("Adopt") .font(.system(size: 18, weight: .medium)) } .padding(14) .frame(maxWidth: .infinity) .foregroundColor(.white) .background(Color.primaryColor) .cornerRadius(15) } Button(action: {}) { Image(systemName: "phone.fill") .frame(width: 50, height: 50) .foregroundColor(.white) .background(Color.primaryDark) .cornerRadius(15) } } .padding(.top) .padding(.leading) .padding(.trailing) } .edgesIgnoringSafeArea(.top) .navigationBarTitleDisplayMode(.inline) .navigationBarItems(trailing: _trailingView) } } struct BoxDetailView: View { let title: String let description: String var body: some View { VStack { Text(title) .font(.system(size: 14, weight: .regular)) Text(description) .font(.system(size: 16, weight: .medium)) } .padding(10) .foregroundColor(.darkText) .frame(width: 100, height: 65, alignment: .center) .background(RoundedRectangle(cornerRadius: 15).stroke(Color.lightGrey)) } } struct PetDetailPreview: PreviewProvider { static var previews: some View { NavigationView { PetDetailView(pet: Pet.dogs.first!) } } } <file_sep>// // PetAdoptionApp.swift // PetAdoption // // Created by <NAME> on 17/1/21. // import SwiftUI @main struct PetAdoptionApp: App { var body: some Scene { WindowGroup { ContentView() } } } <file_sep>// // HomeView.swift // PetAdoption // // Created by <NAME> on 23/1/21. // import SwiftUI struct HomeView: View { @State private var _selectedPetType: Pet.PetType = .dogs var profileView: some View { Image("profile") .resizable() .aspectRatio(contentMode: .fill) .frame(width: 36, height: 36) .clipShape(Circle()) } init() { UINavigationBar.appearance().backgroundColor = .clear UINavigationBar.appearance().tintColor = .white UINavigationBar.appearance().setBackgroundImage(UIImage(), for: .default) UINavigationBar.appearance().shadowImage = UIImage() } var body: some View { VStack { HStack { TextField("Search", text: .constant("")) .foregroundColor(.gray) .font(.system(size: 16, weight: .regular)) .padding() Image(systemName: "magnifyingglass") .frame(width: 40, height: 40) .foregroundColor(.white) .background(Color.primaryColor) .cornerRadius(10) } .frame(height: 40) .background(RoundedRectangle(cornerRadius: 10).stroke(Color.lightGrey, lineWidth: 1)) .padding() PetTypeView(selectedPetType: $_selectedPetType) ScrollView { LazyVGrid(columns: [GridItem(.flexible()), GridItem(.flexible())], spacing: 20) { ForEach(_selectedPetType.pets) { pet in PetView(pet: pet) } } } Spacer() } .background(Color.white) .navigationBarTitle("", displayMode: .inline) .navigationBarItems(trailing: profileView) .toolbar(content: { ToolbarItem(placement: .navigationBarLeading) { HStack { Image("location") .foregroundColor(.primaryColor) TextField("Search for Location", text: .constant("Phnom Penh, KH")) .foregroundColor(.darkText) Spacer().frame(width: 50) Image(systemName: "xmark") .foregroundColor(.darkText) } .padding(.leading, 10) .padding(.trailing, 10) .frame(width: 280, height: 36) .background(Color.primaryLight) .clipShape(RoundedRectangle(cornerRadius: 20)) } }) } } private extension Pet.PetType { var pets: [Pet] { switch self { case .dogs: return Pet.dogs case .cats: return Pet.cats default: return [] } } } struct PetTypeView: View { @Binding var selectedPetType: Pet.PetType var body: some View { ScrollView(.horizontal, showsIndicators: false) { HStack { ForEach(Pet.PetType.allCases) { petType in Button(action: { selectedPetType = petType }) { VStack { Image(petType.rawValue) .foregroundColor(selectedPetType == petType ? .secondaryDark : .darkText) .frame(width: 64, height: 64) .background(selectedPetType == petType ? Color.secondaryColor : .clear) .cornerRadius(15) .overlay(RoundedRectangle(cornerRadius: 15).stroke(Color.lightGrey, lineWidth: 1)) Text(petType.id) .font(.system(size: 16, weight: .regular)) .foregroundColor(.darkText) } } } } .padding(.leading) .padding(.trailing) } } } struct PetView: View { let pet: Pet @State var isFavorite: Bool = false var body: some View { NavigationLink( destination: PetDetailView(pet: pet)) { VStack { ZStack(alignment: .topTrailing) { Image(pet.images.first!) .resizable() .frame(height: 160) .clipShape(RoundedCorner(radius: 15, corners: [.topLeft, .topRight])) Button(action: { isFavorite.toggle() }) { Image(systemName: isFavorite ? "heart.fill" : "heart") .foregroundColor(.primaryColor) .frame(width: 32, height: 32) .background(Color.white) .clipShape(Circle()) .padding(10) } } HStack { Text(pet.displayType) .frame(width: 70, height: 22) .font(.system(size: 12, weight: .medium)) .foregroundColor(pet.isAdult ? .primaryYellow : .primaryColor) .background(pet.isAdult ? Color.secondaryYellow : Color.primaryLight) .cornerRadius(10) Spacer() Image(pet.gender.rawValue) .foregroundColor(pet.isAdult ? Color.primaryYellow : Color.primaryColor) } .padding(.leading) .padding(.trailing) VStack(spacing: 4) { Text(pet.name) .font(.system(size: 18, weight: .medium)) Text(pet.breed.description) .font(.system(size: 14, weight: .regular)) } .foregroundColor(.darkText) .frame(maxWidth: .infinity, alignment: .leading) .padding(.leading) .padding(.bottom, 10) } .background(RoundedRectangle(cornerRadius: 15).stroke(Color.lightGrey, lineWidth: 1)) .padding(.leading) .padding(.trailing) } } } struct HomeViewPreviewProvider: PreviewProvider { static var previews: some View { NavigationView { HomeView() } } } <file_sep>// // Pet.swift // PetAdoption // // Created by <NAME> on 20/1/21. // import Foundation protocol Breed { var description: String { get } } struct Pet: Identifiable { let id: UUID = UUID() let name: String let age: Int let type: PetType let gender: Gender let images: [String] let breed: Breed let weight: Double var description: String { "The \(name) is a bright, sensitive dog who enjoys play with his human family and responds well to training. As herders bred to move cattle, they are fearless and independent. They are vigilant watchdogs, with acute senses and a “big dog” bark. Families who can meet their bold but kindly Pembroke’s need for activity and togetherness will never have a more loyal, loving pet." } enum PetType: String, Identifiable, CaseIterable { var id: String { return self.rawValue.capitalized } case dogs, cats, birds, rabbits, hamsters } enum Gender: String { case male, female } var isAdult: Bool { return age > 8 } var displayType: String { if isAdult { return "Adult" } switch type { case .birds: return "Chick" case .dogs: return "Puppy" case .cats: return "Kitten" case .rabbits: return "Bunny" case .hamsters: return "Pups" } } static let dogs = [ Pet(name: "Bruno", age: 7, type: .dogs, gender: .male, images: ["golden", "golden.1", "golden.2"], breed: DogBreed.golden, weight: 2), Pet(name: "Maya", age: 16, type: .dogs, gender: .female, images: ["maya", "maya.1", "maya.2"], breed: DogBreed.samoyed, weight: 2), Pet(name: "Indra", age: 14, type: .dogs, gender: .female, images: ["shiba", "shiba.1", "shiba.2"], breed: DogBreed.shiba, weight: 4), Pet(name: "Mao", age: 22, type: .dogs, gender: .male, images: ["husky", "husky.1", "husky.2"], breed: DogBreed.husky, weight: 5), Pet(name: "Nora", age: 7, type: .dogs, gender: .male, images: ["corgi.cover"], breed: DogBreed.corgi, weight: 1.5), Pet(name: "Dora", age: 3, type: .dogs, gender: .female, images: ["malamute", "malamute.1"], breed: DogBreed.malamute, weight: 0.8), ] static let cats = [ Pet(name: "Tou", age: 3, type: .cats, gender: .male, images: ["ragdoll"], breed: CatBreed.ragdoll, weight: 0.5), Pet(name: "Toy", age: 12, type: .cats, gender: .female, images: ["birman", "birman.1"], breed: CatBreed.birman, weight: 3), Pet(name: "Reach", age: 24, type: .cats, gender: .male, images: ["bth"], breed: CatBreed.britishShortHair, weight: 3), Pet(name: "Haru", age: 7, type: .cats, gender: .female, images: ["scottish-fold"], breed: CatBreed.scottishFold, weight: 1.2), Pet(name: "Pok", age: 18, type: .cats, gender: .female, images: ["sc"], breed: CatBreed.siameseCat, weight: 3), Pet(name: "King", age: 22, type: .cats, gender: .male, images: ["pc"], breed: CatBreed.persianCat, weight: 3) ] } enum CatBreed: String, Breed { var description: String { return rawValue.capitalized } case britishShortHair case ragdoll case birman case siameseCat case scottishFold case persianCat } enum DogBreed: String, Breed { var description: String { return rawValue.capitalized } case golden case husky case samoyed case shiba case corgi case malamute }
3c0d5d6dfacbc9f34fdf402eb65dd28754ae2bec
[ "Markdown", "Swift" ]
7
Markdown
thachgiasoft/pet-adoption
ecc25d68399e1d3644460f3deba2504d67c40b4c
cc8f077e89d74c9e02769c24c7011dd1c6dff6a6
refs/heads/master
<file_sep>package com.luna.common.baidu; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONObject; import com.google.common.collect.ImmutableMap; import com.google.common.collect.Maps; import com.luna.common.http.HttpUtils; import com.luna.common.http.HttpUtilsConstant; import com.luna.common.utils.StringUtils; import org.apache.http.HttpResponse; import java.io.IOException; import java.util.*; import java.util.regex.Pattern; /** * @author Luna@win10 * @date 2020/5/25 15:37 */ public class BaiduCreationApi { /** * @param domain 合法domain=“娱乐”格式,如国际、国内、军事、财经、科技、房产、娱乐、教育、社会、旅游、体育、汽车、游戏,通过接口获取 * @return * @throws IOException */ public static List<JSONObject> hotEvent(String domain) throws IOException { String body = "{\"domain\":\"" + domain + "\"}"; HttpResponse httpResponse = HttpUtils.doPost(BaiduApiContent.HOST, BaiduApiContent.HOT_EVENT, ImmutableMap.of("Content-Type", HttpUtilsConstant.JSON), ImmutableMap.of("access_token", BaiduApiContent.BAIDU_KEY), body); JSONObject response = HttpUtils.getResponse(httpResponse); List<JSONObject> content = JSON.parseArray(response.getString("content"), JSONObject.class); return content; } /** * 自动返回最近一周的最新脉络 * * @return * @throws IOException */ public static Map<String, List<JSONObject>> eventContext() throws IOException { HttpResponse httpResponse = HttpUtils.doPost(BaiduApiContent.HOST, BaiduApiContent.EVENT_CONTEXT, ImmutableMap.of("Content-Type", HttpUtilsConstant.JSON), ImmutableMap.of("access_token", BaiduApiContent.BAIDU_KEY), ""); JSONObject response = HttpUtils.getResponse(httpResponse); List<JSONObject> content = JSON.parseArray(response.getString("content"), JSONObject.class); Map<String, List<JSONObject>> map = Maps.newHashMap(); for (int i = 0; i < content.size(); i++) { String event_name = content.get(i).getString("event_name"); List<JSONObject> vein = JSON.parseArray(content.get(i).getString("vein"), JSONObject.class); map.put(event_name, vein); } return map; } /** 匹配中文正则表达式 */ private final static String PATTERN = "[\\u4e00-\\u9fa5]+"; /** * 文本匹配 判断toMatch里是否存在prepare * * @param prepare 判断字符 * @param toMatch 原始字符 * @return */ public static boolean checkKnowledge(String prepare, String toMatch) { if (StringUtils.isEmpty(prepare) || StringUtils.isEmpty(toMatch)) { return false; } Pattern pattern = Pattern.compile(PATTERN); // OCR识别出的文字用换行符分隔 String[] split = toMatch.split("\n"); for (String str : split) { if (pattern.matcher(str).find()) { // 匹配到中文 // 判断是否是知识点 if (str.replaceAll(" ", "").contains(prepare.replaceAll(" ", ""))) { return true; } } } return false; } /** * 获取城市天气情况 * * @param city * @return * @throws IOException */ public static Map<String, String> writing(String city) throws IOException { HttpResponse httpResponse = HttpUtils.doPost(BaiduApiContent.HOST, BaiduApiContent.WRITING, ImmutableMap.of("Content-Type", HttpUtilsConstant.X_WWW_FORM_URLENCODED), ImmutableMap.of("access_token", BaiduApiContent.BAIDU_KEY, "project_id", "41168", "city", city), ImmutableMap.of()); JSONObject response = HttpUtils.getResponse(httpResponse); JSONObject jsonObject = JSON.parseObject(response.get("result").toString()); Map<String, String> map = new HashMap<>(); String summary = jsonObject.getString("summary"); String texts = jsonObject.getString("texts"); String title = jsonObject.getString("title"); map.put("summary", summary); map.put("texts", texts); map.put("title", title); return map; } } <file_sep>package com.luna.common.message; import java.util.Map; import java.util.concurrent.TimeUnit; import com.luna.common.config.TencentConfigValue; import com.luna.common.config.TencentSmsConfigValue; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.redis.core.StringRedisTemplate; import org.springframework.stereotype.Component; import com.luna.common.tencent.TencentConstant; import com.luna.common.tencent.TencentMessage; import com.luna.common.utils.CommonUtils; import com.luna.common.utils.Md5Utils; /** * @author Luna@win10 * @date 2020/5/16 10:12 */ @Component public class RedisUtil { @Autowired StringRedisTemplate stringRedisTemplate; /** * 获取Redis缓存验证码内容 * * @param mark * @return */ public String getAutchCode(String mark) { String s = ""; if (CommonUtils.isMobilePhoneNumber(mark)) { mark = "+86" + mark; s = stringRedisTemplate.opsForValue().get(mark); } else if (CommonUtils.isEmailAddress(mark)) { s = stringRedisTemplate.opsForValue().get(mark); } return s; } } <file_sep>package com.luna.common.baidu; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONException; import com.alibaba.fastjson.JSONObject; import java.io.IOException; /** * @author Luna@win10 * @date 2020/5/4 9:18 */ public class BaiduAddress { public static JSONObject Ip2Address(String ip) { return null; } }
1aab934ed9ad146b31e23f6ddeec417f8778c178
[ "Java" ]
3
Java
luna1024/luna-commons
3c27668959be03140bead9a9cd2a35e582a52a56
359f15d068b5348c14049c26de8c6b8952c3cb96
refs/heads/main
<repo_name>crowdsecurity/php-cs-bouncer<file_sep>/src/Fixes/Gregwar/Captcha/CaptchaBuilder.php <?php namespace CrowdSecBouncer\Fixes\Gregwar\Captcha; use Gregwar\Captcha\CaptchaBuilder as GregwarCaptchaBuilder; /** * Override to : * - fix "implicit conversion error on PHP 8.1". * * @see https://github.com/crowdsecurity/php-cs-bouncer/issues/62 and * @see https://github.com/Gregwar/Captcha/pull/101/files * * @SuppressWarnings(PHPMD.ElseExpression) * * @codeCoverageIgnore */ class CaptchaBuilder extends GregwarCaptchaBuilder { /** * Writes the phrase on the image. */ protected function writePhrase($image, $phrase, $font, $width, $height) { $length = mb_strlen($phrase); if (0 === $length) { return \imagecolorallocate($image, 0, 0, 0); } // Gets the text size and start position $size = (int) round($width / $length) - $this->rand(0, 3) - 1; $box = \imagettfbbox($size, 0, $font, $phrase); $textWidth = $box[2] - $box[0]; $textHeight = $box[1] - $box[7]; $x = (int) round(($width - $textWidth) / 2); $y = (int) round(($height - $textHeight) / 2) + $size; if (!$this->textColor) { $textColor = [$this->rand(0, 150), $this->rand(0, 150), $this->rand(0, 150)]; } else { $textColor = $this->textColor; } $col = \imagecolorallocate($image, $textColor[0], $textColor[1], $textColor[2]); // Write the letters one by one, with random angle for ($i = 0; $i < $length; ++$i) { $symbol = mb_substr($phrase, $i, 1); $box = \imagettfbbox($size, 0, $font, $symbol); $w = $box[2] - $box[0]; $angle = $this->rand(-$this->maxAngle, $this->maxAngle); $offset = $this->rand(-$this->maxOffset, $this->maxOffset); \imagettftext($image, $size, $angle, $x, $y + $offset, $col, $font, $symbol); $x += $w; } return $col; } } <file_sep>/src/Configuration.php <?php declare(strict_types=1); namespace CrowdSecBouncer; use CrowdSec\Common\Configuration\AbstractConfiguration; use Symfony\Component\Config\Definition\Builder\ArrayNodeDefinition; use Symfony\Component\Config\Definition\Builder\NodeDefinition; use Symfony\Component\Config\Definition\Builder\TreeBuilder; /** * The Library configuration. You'll find here all configuration possible. Used when instantiating the library. * * @author CrowdSec team * * @see https://crowdsec.net CrowdSec Official Website * * @copyright Copyright (c) 2020+ CrowdSec * @license MIT License */ class Configuration extends AbstractConfiguration { /** * @var string[] */ protected $keys = [ 'use_curl', 'forced_test_ip', 'forced_test_forwarded_ip', 'debug_mode', 'disable_prod_log', 'log_directory_path', 'display_errors', 'cache_system', 'captcha_cache_duration', 'excluded_uris', 'trust_ip_forward_array', 'bouncing_level', 'hide_mentions', 'custom_css', 'color', 'text', ]; /** * {@inheritdoc} * * @throws \InvalidArgumentException */ public function getConfigTreeBuilder(): TreeBuilder { $treeBuilder = new TreeBuilder('config'); /** @var ArrayNodeDefinition $rootNode */ $rootNode = $treeBuilder->getRootNode(); $this->addConnectionNodes($rootNode); $this->addDebugNodes($rootNode); $this->addBouncerNodes($rootNode); $this->addCacheNodes($rootNode); $this->addTemplateNodes($rootNode); return $treeBuilder; } /** * Bouncer settings. * * @param NodeDefinition|ArrayNodeDefinition $rootNode * * @return void * * @throws \InvalidArgumentException */ private function addBouncerNodes($rootNode) { $rootNode->children() ->enumNode('bouncing_level') ->values( [ Constants::BOUNCING_LEVEL_DISABLED, Constants::BOUNCING_LEVEL_NORMAL, Constants::BOUNCING_LEVEL_FLEX, ] ) ->defaultValue(Constants::BOUNCING_LEVEL_NORMAL) ->end() ->arrayNode('trust_ip_forward_array') ->arrayPrototype() ->scalarPrototype()->end() ->end() ->end() ->arrayNode('excluded_uris') ->scalarPrototype()->end() ->end() ->end(); } /** * Cache settings. * * @param NodeDefinition|ArrayNodeDefinition $rootNode * * @return void * * @throws \InvalidArgumentException */ private function addCacheNodes($rootNode) { $rootNode->children() ->enumNode('cache_system') ->values( [ Constants::CACHE_SYSTEM_PHPFS, Constants::CACHE_SYSTEM_REDIS, Constants::CACHE_SYSTEM_MEMCACHED, ] ) ->defaultValue(Constants::CACHE_SYSTEM_PHPFS) ->end() ->integerNode('captcha_cache_duration') ->min(1)->defaultValue(Constants::CACHE_EXPIRATION_FOR_CAPTCHA) ->end() ->end(); } /** * LAPI connection settings. * * @param NodeDefinition|ArrayNodeDefinition $rootNode * * @return void */ private function addConnectionNodes($rootNode) { $rootNode->children() ->booleanNode('use_curl')->defaultValue(false)->end() ->end(); } /** * Debug settings. * * @param NodeDefinition|ArrayNodeDefinition $rootNode * * @return void */ private function addDebugNodes($rootNode) { $rootNode->children() ->scalarNode('forced_test_ip')->defaultValue('')->end() ->scalarNode('forced_test_forwarded_ip')->defaultValue('')->end() ->booleanNode('debug_mode')->defaultValue(false)->end() ->booleanNode('disable_prod_log')->defaultValue(false)->end() ->scalarNode('log_directory_path')->end() ->booleanNode('display_errors')->defaultValue(false)->end() ->end(); } /** * @param $rootNode * @return void */ private function addTemplateNodes($rootNode) { $defaultSubtitle = 'This page is protected against cyber attacks and your IP has been banned by our system.'; $rootNode->children() ->arrayNode('color')->addDefaultsIfNotSet() ->children() ->arrayNode('text')->addDefaultsIfNotSet() ->children() ->scalarNode('primary')->defaultValue('black')->end() ->scalarNode('secondary')->defaultValue('#AAA')->end() ->scalarNode('button')->defaultValue('white')->end() ->scalarNode('error_message')->defaultValue('#b90000')->end() ->end() ->end() ->arrayNode('background')->addDefaultsIfNotSet() ->children() ->scalarNode('page')->defaultValue('#eee')->end() ->scalarNode('container')->defaultValue('white')->end() ->scalarNode('button')->defaultValue('#626365')->end() ->scalarNode('button_hover')->defaultValue('#333')->end() ->end() ->end() ->end() ->end() ->arrayNode('text')->addDefaultsIfNotSet() ->children() ->arrayNode('captcha_wall')->addDefaultsIfNotSet() ->children() ->scalarNode('tab_title')->defaultValue('Oops..')->end() ->scalarNode('title')->defaultValue('Hmm, sorry but...')->end() ->scalarNode('subtitle')->defaultValue('Please complete the security check.')->end() ->scalarNode('refresh_image_link')->defaultValue('refresh image')->end() ->scalarNode('captcha_placeholder')->defaultValue('Type here...')->end() ->scalarNode('send_button')->defaultValue('CONTINUE')->end() ->scalarNode('error_message')->defaultValue('Please try again.')->end() ->scalarNode('footer')->defaultValue('')->end() ->end() ->end() ->arrayNode('ban_wall')->addDefaultsIfNotSet() ->children() ->scalarNode('tab_title')->defaultValue('Oops..')->end() ->scalarNode('title')->defaultValue('🤭 Oh!')->end() ->scalarNode('subtitle')->defaultValue($defaultSubtitle)->end() ->scalarNode('footer')->defaultValue('')->end() ->end() ->end() ->end() ->end() ->booleanNode('hide_mentions')->defaultValue(false)->end() ->scalarNode('custom_css')->defaultValue('')->end() ->end(); } } <file_sep>/tools/coding-standards/php-cs-fixer/.php-cs-fixer.dist.php <?php if (!file_exists(__DIR__ . '/../../../src')) { exit(1); } $config = new PhpCsFixer\Config("crowdsec-php-bouncer-lib"); return $config ->setRules([ '@Symfony' => true, '@PSR12:risky' => true, '@PHPUnit75Migration:risky' => true, 'array_syntax' => ['syntax' => 'short'], 'fopen_flags' => false, 'protected_to_private' => false, 'native_constant_invocation' => true, 'combine_nested_dirname' => true, 'phpdoc_to_comment' => false, 'concat_space' => ['spacing'=> 'one'], ]) ->setRiskyAllowed(true) ->setFinder( PhpCsFixer\Finder::create() ->in(__DIR__ . '/../../../src')->exclude(['templates']) ->in(__DIR__ . '/../../../tests') ) ;<file_sep>/tests/Integration/WatcherClient.php <?php declare(strict_types=1); namespace CrowdSecBouncer\Tests\Integration; use CrowdSec\Common\Client\AbstractClient; use CrowdSec\LapiClient\ClientException; use CrowdSec\LapiClient\Constants; class WatcherClient extends AbstractClient { public const WATCHER_LOGIN_ENDPOINT = '/v1/watchers/login'; public const WATCHER_DECISIONS_ENDPOINT = '/v1/decisions'; public const WATCHER_ALERT_ENDPOINT = '/v1/alerts'; public const HOURS24 = '+24 hours'; /** @var string */ private $token; /** * @var string[] */ private $headers; public function __construct(array $configs) { $this->configs = $configs; $this->headers = ['User-Agent' => 'LAPI_WATCHER_TEST/' . Constants::VERSION]; $agentTlsPath = getenv('AGENT_TLS_PATH'); if (!$agentTlsPath) { throw new \Exception('Using TLS auth for agent is required. Please set AGENT_TLS_PATH env.'); } $this->configs['auth_type'] = Constants::AUTH_TLS; $this->configs['tls_cert_path'] = $agentTlsPath . '/agent.pem'; $this->configs['tls_key_path'] = $agentTlsPath . '/agent-key.pem'; $this->configs['tls_verify_peer'] = false; parent::__construct($this->configs); } /** * Make a request. * * @throws ClientException */ private function manageRequest( string $method, string $endpoint, array $parameters = [] ): array { $this->logger->debug('', [ 'type' => 'WATCHER_CLIENT_REQUEST', 'method' => $method, 'endpoint' => $endpoint, 'parameters' => $parameters, ]); return $this->request($method, $endpoint, $parameters, $this->headers); } /** Set the initial watcher state */ public function setInitialState(): void { $this->deleteAllDecisions(); $now = new \DateTime(); $this->addDecision($now, '12h', '+12 hours', TestHelpers::BAD_IP, 'captcha'); $this->addDecision($now, '24h', self::HOURS24, TestHelpers::BAD_IP . '/' . TestHelpers::IP_RANGE, 'ban'); $this->addDecision($now, '24h', '+24 hours', TestHelpers::JAPAN, 'captcha', Constants::SCOPE_COUNTRY); } /** Set the second watcher state */ public function setSecondState(): void { $this->logger->info('', ['message' => 'Set "second" state']); $this->deleteAllDecisions(); $now = new \DateTime(); $this->addDecision($now, '36h', '+36 hours', TestHelpers::NEWLY_BAD_IP, 'ban'); $this->addDecision( $now, '48h', '+48 hours', TestHelpers::NEWLY_BAD_IP . '/' . TestHelpers::IP_RANGE, 'captcha' ); $this->addDecision($now, '24h', self::HOURS24, TestHelpers::JAPAN, 'captcha', Constants::SCOPE_COUNTRY); $this->addDecision($now, '24h', self::HOURS24, TestHelpers::IP_JAPAN, 'ban'); $this->addDecision($now, '24h', self::HOURS24, TestHelpers::IP_FRANCE, 'ban'); } public function setSimpleDecision(string $type = 'ban'): void { $this->deleteAllDecisions(); $now = new \DateTime(); $this->addDecision($now, '12h', '+12 hours', TestHelpers::BAD_IP, $type); } /** * Ensure we retrieved a JWT to connect the API. */ private function ensureLogin(): void { if (!$this->token) { $data = [ 'scenarios' => [], ]; $credentials = $this->manageRequest( 'POST', self::WATCHER_LOGIN_ENDPOINT, $data ); $this->token = $credentials['token']; $this->headers['Authorization'] = 'Bearer ' . $this->token; } } public function deleteAllDecisions(): void { // Delete all existing decisions. $this->ensureLogin(); $this->manageRequest( 'DELETE', self::WATCHER_DECISIONS_ENDPOINT, [] ); } protected function getFinalScope($scope, $value) { $scope = (Constants::SCOPE_IP === $scope && 2 === count(explode('/', $value))) ? Constants::SCOPE_RANGE : $scope; /** * Must use capital first letter as the crowdsec agent seems to query with first capital letter * during getStreamDecisions. * * @see https://github.com/crowdsecurity/crowdsec/blob/ae6bf3949578a5f3aa8ec415e452f15b404ba5af/pkg/database/decisions.go#L56 */ return ucfirst($scope); } public function addDecision( \DateTime $now, string $durationString, string $dateTimeDurationString, string $value, string $type, string $scope = Constants::SCOPE_IP ) { $stopAt = (clone $now)->modify($dateTimeDurationString)->format('Y-m-d\TH:i:s.000\Z'); $startAt = $now->format('Y-m-d\TH:i:s.000\Z'); $body = [ 'capacity' => 0, 'decisions' => [ [ 'duration' => $durationString, 'origin' => 'cscli', 'scenario' => $type . ' for scope/value (' . $scope . '/' . $value . ') for ' . $durationString . ' for PHPUnit tests', 'scope' => $this->getFinalScope($scope, $value), 'type' => $type, 'value' => $value, ], ], 'events' => [ ], 'events_count' => 1, 'labels' => null, 'leakspeed' => '0', 'message' => 'setup for PHPUnit tests', 'scenario' => 'setup for PHPUnit tests', 'scenario_hash' => '', 'scenario_version' => '', 'simulated' => false, 'source' => [ 'scope' => $this->getFinalScope($scope, $value), 'value' => $value, ], 'start_at' => $startAt, 'stop_at' => $stopAt, ]; $result = $this->manageRequest( 'POST', self::WATCHER_ALERT_ENDPOINT, [$body] ); } } <file_sep>/tests/Integration/GeolocationTest.php <?php declare(strict_types=1); namespace CrowdSecBouncer\Tests\Integration; use CrowdSec\LapiClient\Bouncer as BouncerClient; use CrowdSec\RemediationEngine\CacheStorage\PhpFiles; use CrowdSec\RemediationEngine\LapiRemediation; use CrowdSecBouncer\AbstractBouncer; use CrowdSecBouncer\Constants; use PHPUnit\Framework\TestCase; use Psr\Log\LoggerInterface; /** * @covers \CrowdSecBouncer\AbstractBouncer::getRemediationForIp * * @uses \CrowdSecBouncer\AbstractBouncer::__construct * @uses \CrowdSecBouncer\AbstractBouncer::capRemediationLevel * @uses \CrowdSecBouncer\AbstractBouncer::configure * @uses \CrowdSecBouncer\AbstractBouncer::getConfig * @uses \CrowdSecBouncer\AbstractBouncer::getConfigs * @uses \CrowdSecBouncer\AbstractBouncer::getLogger * @uses \CrowdSecBouncer\AbstractBouncer::getRemediationEngine * @uses \CrowdSecBouncer\AbstractBouncer::handleCache * @uses \CrowdSecBouncer\AbstractBouncer::handleClient * @uses \CrowdSecBouncer\AbstractBouncer::refreshBlocklistCache * @uses \CrowdSecBouncer\Configuration::addBouncerNodes * @uses \CrowdSecBouncer\Configuration::addCacheNodes * @uses \CrowdSecBouncer\Configuration::addConnectionNodes * @uses \CrowdSecBouncer\Configuration::addDebugNodes * @uses \CrowdSecBouncer\Configuration::addTemplateNodes * @uses \CrowdSecBouncer\Configuration::cleanConfigs * @uses \CrowdSecBouncer\Configuration::getConfigTreeBuilder * @uses \CrowdSecBouncer\AbstractBouncer::clearCache */ final class GeolocationTest extends TestCase { /** @var WatcherClient */ private $watcherClient; /** @var LoggerInterface */ private $logger; /** @var bool */ private $useCurl; /** @var bool */ private $useTls; /** * @var array */ private $configs; private function addTlsConfig(&$bouncerConfigs, $tlsPath) { $bouncerConfigs['tls_cert_path'] = $tlsPath . '/bouncer.pem'; $bouncerConfigs['tls_key_path'] = $tlsPath . '/bouncer-key.pem'; $bouncerConfigs['tls_ca_cert_path'] = $tlsPath . '/ca-chain.pem'; $bouncerConfigs['tls_verify_peer'] = true; } protected function setUp(): void { $this->useTls = (string) getenv('BOUNCER_TLS_PATH'); $this->useCurl = (bool) getenv('USE_CURL'); $this->logger = TestHelpers::createLogger(); $bouncerConfigs = [ 'auth_type' => $this->useTls ? \CrowdSec\LapiClient\Constants::AUTH_TLS : Constants::AUTH_KEY, 'api_key' => getenv('BOUNCER_KEY'), 'api_url' => getenv('LAPI_URL'), 'use_curl' => $this->useCurl, 'user_agent_suffix' => 'testphpbouncer', ]; if ($this->useTls) { $this->addTlsConfig($bouncerConfigs, $this->useTls); } $this->configs = $bouncerConfigs; $this->watcherClient = new WatcherClient($this->configs); // Delete all decisions $this->watcherClient->deleteAllDecisions(); } public function maxmindConfigProvider(): array { return TestHelpers::maxmindConfigProvider(); } private function handleMaxMindConfig(array $maxmindConfig): array { // Check if MaxMind database exist if (!file_exists($maxmindConfig['database_path'])) { $this->fail('There must be a MaxMind Database here: ' . $maxmindConfig['database_path']); } return [ 'cache_duration' => 0, 'enabled' => true, 'type' => 'maxmind', 'maxmind' => [ 'database_type' => $maxmindConfig['database_type'], 'database_path' => $maxmindConfig['database_path'], ], ]; } /** * @dataProvider maxmindConfigProvider * * @throws \Symfony\Component\Cache\Exception\CacheException * @throws \Psr\Cache\InvalidArgumentException */ public function testCanVerifyIpAndCountryWithMaxmindInLiveMode(array $maxmindConfig): void { // Init context $this->watcherClient->setInitialState(); // Init bouncer $geolocationConfig = $this->handleMaxMindConfig($maxmindConfig); $bouncerConfigs = [ 'api_key' => TestHelpers::getBouncerKey(), 'api_url' => TestHelpers::getLapiUrl(), 'geolocation' => $geolocationConfig, 'use_curl' => $this->useCurl, 'cache_system' => Constants::CACHE_SYSTEM_PHPFS, 'fs_cache_path' => TestHelpers::PHP_FILES_CACHE_ADAPTER_DIR, 'stream_mode' => false, ]; $client = new BouncerClient($bouncerConfigs); $cache = new PhpFiles($bouncerConfigs); $lapiRemediation = new LapiRemediation($bouncerConfigs, $client, $cache); $bouncer = $this->getMockForAbstractClass(AbstractBouncer::class, [$bouncerConfigs, $lapiRemediation]); $bouncer->clearCache(); $this->assertEquals( 'captcha', $bouncer->getRemediationForIp(TestHelpers::IP_JAPAN), 'Get decisions for a clean IP but bad country (captcha)' ); $this->assertEquals( 'bypass', $bouncer->getRemediationForIp(TestHelpers::IP_FRANCE), 'Get decisions for a clean IP and clean country' ); // Disable Geolocation feature $geolocationConfig['enabled'] = false; $bouncerConfigs['geolocation'] = $geolocationConfig; $client = new BouncerClient($bouncerConfigs); $cache = new PhpFiles($bouncerConfigs); $lapiRemediation = new LapiRemediation($bouncerConfigs, $client, $cache); $bouncer = $this->getMockForAbstractClass(AbstractBouncer::class, [$bouncerConfigs, $lapiRemediation]); $bouncer->clearCache(); $this->assertEquals( 'bypass', $bouncer->getRemediationForIp(TestHelpers::IP_JAPAN), 'Get decisions for a clean IP and bad country but with geolocation disabled' ); // Enable again geolocation and change testing conditions $this->watcherClient->setSecondState(); $geolocationConfig['enabled'] = true; $bouncerConfigs['geolocation'] = $geolocationConfig; $client = new BouncerClient($bouncerConfigs); $cache = new PhpFiles($bouncerConfigs); $lapiRemediation = new LapiRemediation($bouncerConfigs, $client, $cache); $bouncer = $this->getMockForAbstractClass(AbstractBouncer::class, [$bouncerConfigs, $lapiRemediation]); $bouncer->clearCache(); $this->assertEquals( 'ban', $bouncer->getRemediationForIp(TestHelpers::IP_JAPAN), 'Get decisions for a bad IP (ban) and bad country (captcha)' ); $this->assertEquals( 'ban', $bouncer->getRemediationForIp(TestHelpers::IP_FRANCE), 'Get decisions for a bad IP (ban) and clean country' ); } /** * @group integration * * @dataProvider maxmindConfigProvider * * @throws \Symfony\Component\Cache\Exception\CacheException|\Psr\Cache\InvalidArgumentException */ public function testCanVerifyIpAndCountryWithMaxmindInStreamMode(array $maxmindConfig): void { // Init context $this->watcherClient->setInitialState(); // Init bouncer $geolocationConfig = $this->handleMaxMindConfig($maxmindConfig); $bouncerConfigs = [ 'api_key' => TestHelpers::getBouncerKey(), 'api_url' => TestHelpers::getLapiUrl(), 'stream_mode' => true, 'geolocation' => $geolocationConfig, 'use_curl' => $this->useCurl, 'cache_system' => Constants::CACHE_SYSTEM_PHPFS, 'fs_cache_path' => TestHelpers::PHP_FILES_CACHE_ADAPTER_DIR, ]; $client = new BouncerClient($bouncerConfigs); $cache = new PhpFiles($bouncerConfigs); $lapiRemediation = new LapiRemediation($bouncerConfigs, $client, $cache); $bouncer = $this->getMockForAbstractClass(AbstractBouncer::class, [$bouncerConfigs, $lapiRemediation]); $cacheAdapter = $bouncer->getRemediationEngine()->getCacheStorage(); $cacheAdapter->clear(); // Warm BlockList cache up $bouncer->refreshBlocklistCache(); $this->logger->debug('', ['message' => 'Refresh the cache just after the warm up. Nothing should append.']); $bouncer->refreshBlocklistCache(); $this->assertEquals( 'captcha', $bouncer->getRemediationForIp(TestHelpers::IP_JAPAN), 'Should captcha a clean IP coming from a bad country (captcha)' ); // Add and remove decision $this->watcherClient->setSecondState(); $this->assertEquals( 'captcha', $bouncer->getRemediationForIp(TestHelpers::IP_JAPAN), 'Should still captcha a bad IP (ban) coming from a bad country (captcha) as cache has not been refreshed' ); // Pull updates $bouncer->refreshBlocklistCache(); $this->assertEquals( 'ban', $bouncer->getRemediationForIp(TestHelpers::IP_JAPAN), 'The new decision should now be added, so the previously captcha IP should now be ban' ); } } <file_sep>/tests/Integration/AbstractBouncerTest.php <?php declare(strict_types=1); namespace CrowdSecBouncer\Tests\Integration; use CrowdSec\Common\Client\RequestHandler\Curl; use CrowdSec\Common\Client\RequestHandler\FileGetContents; use CrowdSec\Common\Logger\FileLog; use CrowdSec\LapiClient\Bouncer as BouncerClient; use CrowdSec\RemediationEngine\CacheStorage\Memcached; use CrowdSec\RemediationEngine\CacheStorage\PhpFiles; use CrowdSec\RemediationEngine\CacheStorage\Redis; use CrowdSec\RemediationEngine\LapiRemediation; use CrowdSecBouncer\AbstractBouncer; use CrowdSecBouncer\Bouncer; use CrowdSecBouncer\BouncerException; use CrowdSecBouncer\Constants; use CrowdSecBouncer\Tests\PHPUnitUtil; use org\bovigo\vfs\vfsStream; use PHPUnit\Framework\TestCase; use Psr\Log\LoggerInterface; /** * @covers \CrowdSecBouncer\AbstractBouncer::clearCache * @covers \CrowdSecBouncer\AbstractBouncer::pruneCache * @covers \CrowdSecBouncer\AbstractBouncer::testCacheConnection * * @uses \CrowdSecBouncer\AbstractBouncer::__construct * @uses \CrowdSecBouncer\AbstractBouncer::capRemediationLevel * @uses \CrowdSecBouncer\AbstractBouncer::configure * @uses \CrowdSecBouncer\AbstractBouncer::getConfig * @uses \CrowdSecBouncer\AbstractBouncer::getConfigs * @uses \CrowdSecBouncer\AbstractBouncer::getLogger * @uses \CrowdSecBouncer\AbstractBouncer::getRemediationEngine * * @covers \CrowdSecBouncer\AbstractBouncer::handleCache * @covers \CrowdSecBouncer\AbstractBouncer::handleClient * @covers \CrowdSecBouncer\AbstractBouncer::refreshBlocklistCache * * @uses \CrowdSecBouncer\Configuration::addBouncerNodes * @uses \CrowdSecBouncer\Configuration::addCacheNodes * @uses \CrowdSecBouncer\Configuration::addConnectionNodes * @uses \CrowdSecBouncer\Configuration::addDebugNodes * @uses \CrowdSecBouncer\Configuration::addTemplateNodes * @uses \CrowdSecBouncer\Configuration::cleanConfigs * @uses \CrowdSecBouncer\Configuration::getConfigTreeBuilder * * @covers \CrowdSecBouncer\AbstractBouncer::bounceCurrentIp * @covers \CrowdSecBouncer\AbstractBouncer::getTrustForwardedIpBoundsList * @covers \CrowdSecBouncer\AbstractBouncer::handleForwardedFor * @covers \CrowdSecBouncer\AbstractBouncer::handleRemediation * @covers \CrowdSecBouncer\AbstractBouncer::shouldTrustXforwardedFor * * @uses \CrowdSecBouncer\AbstractBouncer::getBanHtml * @uses \CrowdSecBouncer\AbstractBouncer::handleBanRemediation * @uses \CrowdSecBouncer\AbstractBouncer::sendResponse * @uses \CrowdSecBouncer\Template::__construct * @uses \CrowdSecBouncer\Template::render * @uses \CrowdSecBouncer\AbstractBouncer::buildCaptchaCouple * @uses \CrowdSecBouncer\AbstractBouncer::displayCaptchaWall * * @covers \CrowdSecBouncer\AbstractBouncer::getCache * * @uses \CrowdSecBouncer\AbstractBouncer::getCaptchaHtml * * @covers \CrowdSecBouncer\AbstractBouncer::handleCaptchaRemediation * @covers \CrowdSecBouncer\AbstractBouncer::handleCaptchaResolutionForm * @covers \CrowdSecBouncer\AbstractBouncer::initCaptchaResolution * @covers \CrowdSecBouncer\AbstractBouncer::shouldNotCheckResolution * @covers \CrowdSecBouncer\AbstractBouncer::checkCaptcha * @covers \CrowdSecBouncer\AbstractBouncer::refreshCaptcha * @covers \CrowdSecBouncer\AbstractBouncer::getRemediationForIp * @covers \CrowdSecBouncer\AbstractBouncer::run * @covers \CrowdSecBouncer\AbstractBouncer::shouldBounceCurrentIp */ final class AbstractBouncerTest extends TestCase { private const EXCLUDED_URI = '/favicon.ico'; /** @var WatcherClient */ private $watcherClient; /** @var bool */ private $useTls; /** * @var LoggerInterface */ private $logger; /** * @var string */ private $debugFile; /** * @var string */ private $prodFile; /** * @var vfsStreamDirectory */ private $root; /** * @var array */ private $configs; protected function setUp(): void { $this->useTls = (string) getenv('BOUNCER_TLS_PATH'); $this->root = vfsStream::setup('/tmp'); $this->configs['log_directory_path'] = $this->root->url(); $currentDate = date('Y-m-d'); $this->debugFile = 'debug-' . $currentDate . '.log'; $this->prodFile = 'prod-' . $currentDate . '.log'; $this->logger = new FileLog(['log_directory_path' => $this->root->url(), 'debug_mode' => true]); $bouncerConfigs = [ 'auth_type' => $this->useTls ? \CrowdSec\LapiClient\Constants::AUTH_TLS : Constants::AUTH_KEY, 'api_key' => getenv('BOUNCER_KEY'), 'api_url' => getenv('LAPI_URL'), 'user_agent_suffix' => 'testphpbouncer', 'fs_cache_path' => $this->root->url() . '/.cache', 'redis_dsn' => getenv('REDIS_DSN'), 'memcached_dsn' => getenv('MEMCACHED_DSN'), 'excluded_uris' => [self::EXCLUDED_URI], 'stream_mode' => false, 'trust_ip_forward_array' => [['005.006.007.008', '005.006.007.008']], ]; if ($this->useTls) { $this->addTlsConfig($bouncerConfigs, $this->useTls); } $this->configs = $bouncerConfigs; $this->watcherClient = new WatcherClient($this->configs); // Delete all decisions $this->watcherClient->deleteAllDecisions(); } private function addTlsConfig(&$bouncerConfigs, $tlsPath) { $bouncerConfigs['tls_cert_path'] = $tlsPath . '/bouncer.pem'; $bouncerConfigs['tls_key_path'] = $tlsPath . '/bouncer-key.pem'; $bouncerConfigs['tls_ca_cert_path'] = $tlsPath . '/ca-chain.pem'; $bouncerConfigs['tls_verify_peer'] = true; } public function testConstructAndSomeMethods() { $bouncerConfigs = array_merge($this->configs, ['unexpected_config' => 'test']); $client = new BouncerClient($bouncerConfigs); $cache = new PhpFiles($bouncerConfigs); $lapiRemediation = new LapiRemediation($bouncerConfigs, $client, $cache); $logger = new FileLog(); $bouncer = $this->getMockForAbstractClass(AbstractBouncer::class, [$bouncerConfigs, $lapiRemediation, $logger]); $this->assertEquals(false, $bouncer->getConfig('stream_mode'), 'Stream mode config'); $this->assertEquals(FileLog::class, \get_class($bouncer->getLogger()), 'Logger Init'); $this->assertEquals([['005.006.007.008', '005.006.007.008']], $bouncer->getConfig('trust_ip_forward_array'), 'Forwarded array config'); $remediation = $bouncer->getRemediationEngine(); $this->assertEquals('CrowdSec\RemediationEngine\LapiRemediation', \get_class($remediation), 'Remediation Init'); $this->assertEquals('CrowdSec\RemediationEngine\CacheStorage\PhpFiles', \get_class($remediation->getCacheStorage()), 'Remediation cache Init'); $this->assertEquals([['005.006.007.008', '005.006.007.008']], $bouncer->getConfig('trust_ip_forward_array'), 'Forwarded array config'); $this->assertEquals(Constants::BOUNCING_LEVEL_NORMAL, $bouncer->getConfig('bouncing_level'), 'Bouncing level config'); $this->assertEquals(null, $bouncer->getConfig('unexpected_config'), 'Should clean config'); $configs = $bouncer->getConfigs(); $this->assertArrayHasKey('text', $configs, 'Config should have text key'); $this->assertArrayHasKey('color', $configs, 'Config should have color key'); } /** * @group captcha * * @return void * * @throws BouncerException * @throws \CrowdSec\RemediationEngine\CacheStorage\CacheStorageException * @throws \PHPUnit\Framework\ExpectationFailedException * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException */ public function testCaptchaFlow() { $this->watcherClient->setSimpleDecision('captcha'); // Init bouncer $bouncerConfigs = [ 'auth_type' => $this->useTls ? Constants::AUTH_TLS : Constants::AUTH_KEY, 'api_key' => TestHelpers::getBouncerKey(), 'api_url' => TestHelpers::getLapiUrl(), 'stream_mode' => false, 'cache_system' => Constants::CACHE_SYSTEM_PHPFS, 'fs_cache_path' => $this->root->url() . '/.cache', 'forced_test_ip' => TestHelpers::BAD_IP, ]; if ($this->useTls) { $this->addTlsConfig($bouncerConfigs, $this->useTls); } $client = new BouncerClient($bouncerConfigs); $cache = new PhpFiles($bouncerConfigs); $lapiRemediation = new LapiRemediation($bouncerConfigs, $client, $cache); // Mock sendResponse and redirectResponse to avoid PHP UNIT header already sent or exit error $bouncer = $this->getMockForAbstractClass(AbstractBouncer::class, [$bouncerConfigs, $lapiRemediation], '', true, true, true, [ 'sendResponse', 'redirectResponse', 'getHttpMethod', 'getPostedVariable', 'getHttpRequestHeader', ]); $bouncer->clearCache(); $cache = $bouncer->getRemediationEngine()->getCacheStorage(); $cacheKey = $cache->getCacheKey(Constants::SCOPE_IP, TestHelpers::BAD_IP); $item = $cache->getItem($cacheKey); $this->assertEquals( false, $item->isHit(), 'The remediation should not be cached' ); $cacheKeyCaptcha = $cache->getCacheKey(Constants::CACHE_TAG_CAPTCHA, TestHelpers::BAD_IP); $item = $cache->getItem($cacheKeyCaptcha); $this->assertEquals( false, $item->isHit(), 'The captcha variables should not be cached' ); // Step 1 : access a page should display a captcha wall $bouncer->bounceCurrentIp(); $item = $cache->getItem($cacheKey); $this->assertEquals( true, $item->isHit(), 'The remediation should be cached' ); $cacheKeyCaptcha = $cache->getCacheKey(Constants::CACHE_TAG_CAPTCHA, TestHelpers::BAD_IP); $item = $cache->getItem($cacheKeyCaptcha); $this->assertEquals( true, $item->isHit(), 'The captcha variables should be cached' ); $this->assertEquals( true, $item->isHit(), 'The captcha variables should be cached' ); $cached = $item->get(); $this->assertEquals( true, $cached['has_to_be_resolved'], 'The captcha variables should be cached' ); $phraseToGuess = $cached['phrase_to_guess']; $this->assertEquals( 5, strlen($phraseToGuess), 'The captcha variables should be cached' ); $this->assertEquals( '/', $cached['resolution_redirect'], 'The captcha variables should be cached' ); $this->assertNotEmpty($cached['inline_image'], 'The captcha variables should be cached'); $this->assertEquals( false, $cached['resolution_failed'], 'The captcha variables should be cached' ); // Step 2 :refresh $bouncer->method('getHttpMethod')->willReturnOnConsecutiveCalls('POST', 'POST', 'POST', 'POST'); $bouncer->method('getPostedVariable')->willReturnOnConsecutiveCalls('1', '1', '1', '1', '1', 'bad-phrase', 'bad-phrase'); $_SERVER['HTTP_REFERER'] = 'UNIT-TEST'; $_SERVER['REQUEST_METHOD'] = 'POST'; $_POST['refresh'] = '1'; $_POST['crowdsec_captcha'] = '1'; $bouncer->bounceCurrentIp(); $cacheKeyCaptcha = $cache->getCacheKey(Constants::CACHE_TAG_CAPTCHA, TestHelpers::BAD_IP); $item = $cache->getItem($cacheKeyCaptcha); $cached = $item->get(); $phraseToGuess2 = $cached['phrase_to_guess']; $this->assertNotEquals( $phraseToGuess2, $phraseToGuess, 'Phrase should have been refresh' ); $this->assertEquals( '/', $cached['resolution_redirect'], 'Referer is only for the first step if post' ); // STEP 3 : resolve captcha but failed $_SERVER['REQUEST_METHOD'] = 'POST'; unset($_POST['refresh']); $_POST['phrase'] = 'bad-phrase'; $_POST['crowdsec_captcha'] = '1'; $bouncer->bounceCurrentIp(); $cacheKeyCaptcha = $cache->getCacheKey(Constants::CACHE_TAG_CAPTCHA, TestHelpers::BAD_IP); $item = $cache->getItem($cacheKeyCaptcha); $cached = $item->get(); $this->assertEquals( true, $cached['resolution_failed'], 'Failed should be cached' ); // STEP 4 : resolve captcha success $client = new BouncerClient($bouncerConfigs); $cache = new PhpFiles($bouncerConfigs); $lapiRemediation = new LapiRemediation($bouncerConfigs, $client, $cache); // Mock sendResponse and redirectResponse to avoid PHP UNIT header already sent or exit error $bouncer = $this->getMockForAbstractClass(AbstractBouncer::class, [$bouncerConfigs, $lapiRemediation], '', true, true, true, [ 'sendResponse', 'redirectResponse', 'getHttpMethod', 'getPostedVariable', 'getHttpRequestHeader', ]); $bouncer->method('getHttpMethod')->willReturnOnConsecutiveCalls('POST'); $bouncer->method('getPostedVariable')->willReturnOnConsecutiveCalls('1', null, '1', $phraseToGuess2); $_SERVER['REQUEST_METHOD'] = 'POST'; $_POST['phrase'] = $phraseToGuess2; $_POST['crowdsec_captcha'] = '1'; $bouncer->bounceCurrentIp(); $cacheKeyCaptcha = $cache->getCacheKey(Constants::CACHE_TAG_CAPTCHA, TestHelpers::BAD_IP); $item = $cache->getItem($cacheKeyCaptcha); $cached = $item->get(); $this->assertEquals( false, $cached['has_to_be_resolved'], 'Resolved should be cached' ); } /** * @group ban * * @return void * * @throws BouncerException * @throws \CrowdSec\RemediationEngine\CacheStorage\CacheStorageException * @throws \PHPUnit\Framework\ExpectationFailedException * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException */ public function testBanFlow() { $this->watcherClient->setSimpleDecision('ban'); // Init bouncer $bouncerConfigs = [ 'auth_type' => $this->useTls ? Constants::AUTH_TLS : Constants::AUTH_KEY, 'api_key' => TestHelpers::getBouncerKey(), 'api_url' => TestHelpers::getLapiUrl(), 'stream_mode' => false, 'cache_system' => Constants::CACHE_SYSTEM_PHPFS, 'fs_cache_path' => $this->root->url() . '/.cache', 'forced_test_ip' => TestHelpers::BAD_IP, ]; if ($this->useTls) { $this->addTlsConfig($bouncerConfigs, $this->useTls); } $client = new BouncerClient($bouncerConfigs); $cache = new PhpFiles($bouncerConfigs); $lapiRemediation = new LapiRemediation($bouncerConfigs, $client, $cache); // Mock sendResponse and redirectResponse to avoid PHP UNIT header already sent or exit error $bouncer = $this->getMockForAbstractClass(AbstractBouncer::class, [$bouncerConfigs, $lapiRemediation], '', true, true, true, [ 'sendResponse', 'redirectResponse', 'getHttpMethod', 'getPostedVariable', 'getHttpRequestHeader', ]); $bouncer->clearCache(); $cache = $bouncer->getRemediationEngine()->getCacheStorage(); $cacheKey = $cache->getCacheKey(Constants::SCOPE_IP, TestHelpers::BAD_IP); $item = $cache->getItem($cacheKey); $this->assertEquals( false, $item->isHit(), 'The remediation should not be cached' ); $bouncer->bounceCurrentIp(); $item = $cache->getItem($cacheKey); $this->assertEquals( true, $item->isHit(), 'The remediation should be cached' ); } public function testRun() { $this->assertEquals( false, file_exists($this->root->url() . '/' . $this->prodFile), 'Prod File should not exist' ); $this->assertEquals( false, file_exists($this->root->url() . '/' . $this->debugFile), 'Debug File should not exist' ); // Test 2: not bouncing exclude URI $client = new BouncerClient($this->configs, null, $this->logger); $cache = new PhpFiles($this->configs, $this->logger); $lapiRemediation = new LapiRemediation($this->configs, $client, $cache, $this->logger); // Mock sendResponse and redirectResponse to avoid PHP UNIT header already sent or exit error $bouncer = $this->getMockForAbstractClass(AbstractBouncer::class, [$this->configs, $lapiRemediation, $this->logger], '', true, true, true, [ 'sendResponse', 'redirectResponse', 'getHttpMethod', 'getPostedVariable', 'getHttpRequestHeader', 'getRemoteIp', 'getRequestUri', ]); $bouncer->method('getRequestUri')->willReturnOnConsecutiveCalls(self::EXCLUDED_URI); $bouncer->method('getRemoteIp')->willReturnOnConsecutiveCalls('127.0.0.2'); $this->assertEquals(false, $bouncer->run(), 'Should not bounce excluded uri'); PHPUnitUtil::assertRegExp( $this, '/.*100.*Will not bounce as URI is excluded/', file_get_contents($this->root->url() . '/' . $this->debugFile), 'Debug log content should be correct' ); // Test 3: bouncing URI $client = new BouncerClient($this->configs, null, $this->logger); $cache = new PhpFiles($this->configs, $this->logger); $lapiRemediation = new LapiRemediation($this->configs, $client, $cache, $this->logger); // Mock sendResponse and redirectResponse to avoid PHP UNIT header already sent or exit error $bouncer = $this->getMockForAbstractClass(AbstractBouncer::class, [$this->configs, $lapiRemediation, $this->logger], '', true, true, true, [ 'sendResponse', 'redirectResponse', 'getHttpMethod', 'getPostedVariable', 'getHttpRequestHeader', 'getRemoteIp', 'getRequestUri', ]); $bouncer->method('getRequestUri')->willReturnOnConsecutiveCalls('/home'); $bouncer->method('getRemoteIp')->willReturnOnConsecutiveCalls('127.0.0.3'); $this->assertEquals(true, $bouncer->run(), 'Should bounce uri'); // Test 4: not bouncing URI if disabled $bouncerConfigs = array_merge($this->configs, ['bouncing_level' => Constants::BOUNCING_LEVEL_DISABLED]); $client = new BouncerClient($bouncerConfigs, null, $this->logger); $cache = new PhpFiles($bouncerConfigs, $this->logger); $lapiRemediation = new LapiRemediation($bouncerConfigs, $client, $cache, $this->logger); // Mock sendResponse and redirectResponse to avoid PHP UNIT header already sent or exit error $bouncer = $this->getMockForAbstractClass(AbstractBouncer::class, [$bouncerConfigs, $lapiRemediation, $this->logger], '', true, true, true, [ 'sendResponse', 'redirectResponse', 'getHttpMethod', 'getPostedVariable', 'getHttpRequestHeader', 'getRemoteIp', 'getRequestUri', ]); $bouncer->method('getRequestUri')->willReturnOnConsecutiveCalls('/home'); $bouncer->method('getRemoteIp')->willReturnOnConsecutiveCalls('127.0.0.4'); $this->assertEquals(false, $bouncer->run(), 'Should not bounce if disabled'); PHPUnitUtil::assertRegExp( $this, '/.*100.*Will not bounce as bouncing is disabled/', file_get_contents($this->root->url() . '/' . $this->debugFile), 'Debug log content should be correct' ); // Test 5: throw error if config says so $bouncerConfigs = array_merge( $this->configs, [ 'display_errors' => true, 'api_url' => 'bad-url', ] ); $client = new BouncerClient($bouncerConfigs, null, $this->logger); $cache = new PhpFiles($bouncerConfigs, $this->logger); $lapiRemediation = new LapiRemediation($bouncerConfigs, $client, $cache, $this->logger); // Mock sendResponse and redirectResponse to avoid PHP UNIT header already sent or exit error $bouncer = $this->getMockForAbstractClass(AbstractBouncer::class, [$bouncerConfigs, $lapiRemediation, $this->logger], '', true, true, true, [ 'sendResponse', 'redirectResponse', 'getHttpMethod', 'getPostedVariable', 'getHttpRequestHeader', 'getRemoteIp', 'getRequestUri', ]); $bouncer->method('getRequestUri')->willReturnOnConsecutiveCalls('/home'); $bouncer->method('getRemoteIp')->willReturnOnConsecutiveCalls('127.0.0.5'); $error = ''; try { $bouncer->run(); } catch (BouncerException $e) { $error = $e->getMessage(); } $errorExpected = '/Could not resolve host/'; PHPUnitUtil::assertRegExp( $this, $errorExpected, $error, 'Should have throw an error' ); PHPUnitUtil::assertRegExp( $this, '/.*400.*EXCEPTION_WHILE_BOUNCING/', file_get_contents($this->root->url() . '/' . $this->prodFile), 'Prod log content should be correct' ); // Test 6: NOT throw error if config says so $bouncerConfigs = array_merge( $this->configs, [ 'display_errors' => false, 'api_url' => 'bad-url', ] ); $client = new BouncerClient($bouncerConfigs, null, $this->logger); $cache = new PhpFiles($bouncerConfigs, $this->logger); $lapiRemediation = new LapiRemediation($bouncerConfigs, $client, $cache, $this->logger); // Mock sendResponse and redirectResponse to avoid PHP UNIT header already sent or exit error $bouncer = $this->getMockForAbstractClass(AbstractBouncer::class, [$bouncerConfigs, $lapiRemediation, $this->logger], '', true, true, true, [ 'sendResponse', 'redirectResponse', 'getHttpMethod', 'getPostedVariable', 'getHttpRequestHeader', 'getRemoteIp', 'getRequestUri', ]); $bouncer->method('getRequestUri')->willReturnOnConsecutiveCalls('/home'); $bouncer->method('getRemoteIp')->willReturnOnConsecutiveCalls('127.0.0.6'); $error = ''; try { $bouncer->run(); } catch (BouncerException $e) { $error = $e->getMessage(); } $this->assertEquals('', $error, 'Should not throw error'); PHPUnitUtil::assertRegExp( $this, '/.*400.*EXCEPTION_WHILE_BOUNCING/', file_get_contents($this->root->url() . '/' . $this->prodFile), 'Prod log content should be correct' ); // Test 7 : no-forward $bouncerConfigs = array_merge( $this->configs, [ 'forced_test_forwarded_ip' => Constants::X_FORWARDED_DISABLED, ] ); $client = new BouncerClient($bouncerConfigs, null, $this->logger); $cache = new PhpFiles($bouncerConfigs, $this->logger); $lapiRemediation = new LapiRemediation($bouncerConfigs, $client, $cache, $this->logger); // Mock sendResponse and redirectResponse to avoid PHP UNIT header already sent or exit error $bouncer = $this->getMockForAbstractClass(AbstractBouncer::class, [$bouncerConfigs, $lapiRemediation, $this->logger], '', true, true, true, [ 'sendResponse', 'redirectResponse', 'getHttpMethod', 'getPostedVariable', 'getHttpRequestHeader', 'getRemoteIp', 'getRequestUri', ]); $bouncer->method('getRequestUri')->willReturnOnConsecutiveCalls('/home'); $bouncer->method('getRemoteIp')->willReturnOnConsecutiveCalls('127.0.0.7'); $bouncer->run(); PHPUnitUtil::assertRegExp( $this, '/.*100.*X-Forwarded-for usage is disabled/', file_get_contents($this->root->url() . '/' . $this->debugFile), 'Debug log content should be correct' ); // Test 8 : forced X-Forwarded-for usage $bouncerConfigs = array_merge( $this->configs, [ 'forced_test_forwarded_ip' => '1.2.3.5', ] ); $client = new BouncerClient($bouncerConfigs, null, $this->logger); $cache = new PhpFiles($bouncerConfigs, $this->logger); $lapiRemediation = new LapiRemediation($bouncerConfigs, $client, $cache, $this->logger); // Mock sendResponse and redirectResponse to avoid PHP UNIT header already sent or exit error $bouncer = $this->getMockForAbstractClass(AbstractBouncer::class, [$bouncerConfigs, $lapiRemediation, $this->logger], '', true, true, true, [ 'sendResponse', 'redirectResponse', 'getHttpMethod', 'getPostedVariable', 'getHttpRequestHeader', 'getRemoteIp', 'getRequestUri', ]); $bouncer->method('getRequestUri')->willReturnOnConsecutiveCalls('/home'); $bouncer->method('getRemoteIp')->willReturnOnConsecutiveCalls('127.0.0.8'); $bouncer->run(); PHPUnitUtil::assertRegExp( $this, '/.*100.*X-Forwarded-for usage is forced.*"x_forwarded_for_ip":"1.2.3.5"/', file_get_contents($this->root->url() . '/' . $this->debugFile), 'Debug log content should be correct' ); // Test 9 non-authorized $bouncerConfigs = $this->configs; $client = new BouncerClient($bouncerConfigs, null, $this->logger); $cache = new PhpFiles($bouncerConfigs, $this->logger); $lapiRemediation = new LapiRemediation($bouncerConfigs, $client, $cache, $this->logger); // Mock sendResponse and redirectResponse to avoid PHP UNIT header already sent or exit error $bouncer = $this->getMockForAbstractClass(AbstractBouncer::class, [$bouncerConfigs, $lapiRemediation, $this->logger], '', true, true, true, [ 'sendResponse', 'redirectResponse', 'getHttpMethod', 'getPostedVariable', 'getHttpRequestHeader', 'getRemoteIp', 'getRequestUri', ]); $bouncer->method('getRequestUri')->willReturnOnConsecutiveCalls('/home'); $bouncer->method('getRemoteIp')->willReturnOnConsecutiveCalls('127.0.0.9'); $bouncer->method('getHttpRequestHeader')->willReturnOnConsecutiveCalls('1.2.3.5'); // HTTP_X_FORWARDED_FOR $bouncer->run(); PHPUnitUtil::assertRegExp( $this, '/.*300.*Detected IP is not allowed for X-Forwarded-for usage.*"x_forwarded_for_ip":"1.2.3.5"/', file_get_contents($this->root->url() . '/' . $this->prodFile), 'Prod log content should be correct' ); // Test 10 authorized $bouncerConfigs = $this->configs; $client = new BouncerClient($bouncerConfigs, null, $this->logger); $cache = new PhpFiles($bouncerConfigs, $this->logger); $lapiRemediation = new LapiRemediation($bouncerConfigs, $client, $cache, $this->logger); // Mock sendResponse and redirectResponse to avoid PHP UNIT header already sent or exit error $bouncer = $this->getMockForAbstractClass(AbstractBouncer::class, [$bouncerConfigs, $lapiRemediation, $this->logger], '', true, true, true, [ 'sendResponse', 'redirectResponse', 'getHttpMethod', 'getPostedVariable', 'getHttpRequestHeader', 'getRemoteIp', 'getRequestUri', ]); $bouncer->method('getRequestUri')->willReturnOnConsecutiveCalls('/home'); $bouncer->method('getRemoteIp')->willReturnOnConsecutiveCalls('5.6.7.8'); $bouncer->method('getHttpRequestHeader')->willReturnOnConsecutiveCalls('127.0.0.10'); // HTTP_X_FORWARDED_FOR $bouncer->run(); PHPUnitUtil::assertRegExp( $this, '/.*100.*Detected IP is allowed for X-Forwarded-for usage.*"original_ip":"5.6.7.8","x_forwarded_for_ip":"127.0.0.10"/', file_get_contents($this->root->url() . '/' . $this->debugFile), 'Debug log content should be correct' ); } public function testPrivateAndProtectedMethods() { // handleCache $configs = array_merge($this->configs, ['cache_system' => 'redis']); $mockRemediation = $this->getMockBuilder(LapiRemediation::class) ->disableOriginalConstructor() ->onlyMethods(['pruneCache', 'clearCache', 'refreshDecisions', 'getCacheStorage']) ->getMock(); $bouncer = $this->getMockForAbstractClass(AbstractBouncer::class, [$configs, $mockRemediation]); $result = PHPUnitUtil::callMethod( $bouncer, 'handleCache', [$configs, new FileLog()] ); $this->assertInstanceOf(Redis::class, $result); $configs = array_merge($this->configs, ['cache_system' => 'memcached']); $mockRemediation = $this->getMockBuilder(LapiRemediation::class) ->disableOriginalConstructor() ->onlyMethods(['pruneCache', 'clearCache', 'refreshDecisions', 'getCacheStorage']) ->getMock(); $bouncer = $this->getMockForAbstractClass(AbstractBouncer::class, [$configs, $mockRemediation]); $result = PHPUnitUtil::callMethod( $bouncer, 'handleCache', [$configs, new FileLog()] ); $this->assertInstanceOf(Memcached::class, $result); $configs = array_merge($this->configs, ['cache_system' => 'phpfs']); $mockRemediation = $this->getMockBuilder(LapiRemediation::class) ->disableOriginalConstructor() ->onlyMethods(['pruneCache', 'clearCache', 'refreshDecisions', 'getCacheStorage']) ->getMock(); $bouncer = $this->getMockForAbstractClass(AbstractBouncer::class, [$configs, $mockRemediation]); $result = PHPUnitUtil::callMethod( $bouncer, 'handleCache', [$configs, new FileLog()] ); $this->assertInstanceOf(PhpFiles::class, $result); $error = ''; try { $configs = array_merge($this->configs, ['cache_system' => 'phpfs']); $mockRemediation = $this->getMockBuilder(LapiRemediation::class) ->disableOriginalConstructor() ->onlyMethods(['pruneCache', 'clearCache', 'refreshDecisions', 'getCacheStorage']) ->getMock(); $bouncer = $this->getMockForAbstractClass(AbstractBouncer::class, [$configs, $mockRemediation]); PHPUnitUtil::callMethod( $bouncer, 'handleCache', [array_merge($configs, ['cache_system' => 'bad-cache-name']), new FileLog()] ); } catch (BouncerException $e) { $error = $e->getMessage(); } PHPUnitUtil::assertRegExp( $this, '/Unknown selected cache technology: bad-cache-name/', $error, 'Should have throw an error' ); // handleClient $configs = $this->configs; $mockRemediation = $this->getMockBuilder(LapiRemediation::class) ->disableOriginalConstructor() ->onlyMethods(['pruneCache', 'clearCache', 'refreshDecisions', 'getCacheStorage']) ->getMock(); $bouncer = $this->getMockForAbstractClass(AbstractBouncer::class, [$configs, $mockRemediation]); $result = PHPUnitUtil::callMethod( $bouncer, 'handleClient', [$configs, new FileLog()] ); $this->assertEquals(FileGetContents::class, \get_class($result->getRequestHandler())); $configs = array_merge($this->configs, ['use_curl' => true]); $mockRemediation = $this->getMockBuilder(LapiRemediation::class) ->disableOriginalConstructor() ->onlyMethods(['pruneCache', 'clearCache', 'refreshDecisions', 'getCacheStorage']) ->getMock(); $bouncer = $this->getMockForAbstractClass(AbstractBouncer::class, [$configs, $mockRemediation]); $result = PHPUnitUtil::callMethod( $bouncer, 'handleClient', [$configs, new FileLog()] ); $this->assertEquals(Curl::class, \get_class($result->getRequestHandler())); } /** * @group integration */ public function testCanVerifyIpInLiveMode(): void { // Init context $this->watcherClient->setInitialState(); // Init bouncer $bouncerConfigs = [ 'auth_type' => $this->useTls ? Constants::AUTH_TLS : Constants::AUTH_KEY, 'api_key' => TestHelpers::getBouncerKey(), 'api_url' => TestHelpers::getLapiUrl(), 'redis_dsn' => getenv('REDIS_DSN'), 'memcached_dsn' => getenv('MEMCACHED_DSN'), 'fs_cache_path' => $this->root->url() . '/.cache', 'stream_mode' => false, ]; if ($this->useTls) { $this->addTlsConfig($bouncerConfigs, $this->useTls); } $client = new BouncerClient($bouncerConfigs); $cache = new PhpFiles($bouncerConfigs); $lapiRemediation = new LapiRemediation($bouncerConfigs, $client, $cache); $bouncer = $this->getMockForAbstractClass(AbstractBouncer::class, [$bouncerConfigs, $lapiRemediation]); // Test cache adapter $cacheAdapter = $bouncer->getRemediationEngine()->getCacheStorage(); $cacheAdapter->clear(); $this->assertEquals( 'ban', $bouncer->getRemediationForIp(TestHelpers::BAD_IP), 'Get decisions for a bad IP (for the first time, it should be a cache miss)' ); $this->assertEquals( 'ban', $bouncer->getRemediationForIp(TestHelpers::BAD_IP), 'Call the same thing for the second time (now it should be a cache hit)' ); $cleanRemediation1stCall = $bouncer->getRemediationForIp(TestHelpers::CLEAN_IP); $this->assertEquals( 'bypass', $cleanRemediation1stCall, 'Get decisions for a clean IP for the first time (it should be a cache miss)' ); // Call the same thing for the second time (now it should be a cache hit) $cleanRemediation2ndCall = $bouncer->getRemediationForIp(TestHelpers::CLEAN_IP); $this->assertEquals('bypass', $cleanRemediation2ndCall); // Clear cache $this->assertTrue($bouncer->clearCache(), 'The cache should be clearable'); // Call one more time (should miss as the cache has been cleared) $remediation3rdCall = $bouncer->getRemediationForIp(TestHelpers::BAD_IP); $this->assertEquals('ban', $remediation3rdCall); // Reconfigure the bouncer to set maximum remediation level to "captcha" $bouncerConfigs['bouncing_level'] = Constants::BOUNCING_LEVEL_FLEX; $client = new BouncerClient($bouncerConfigs); $cache = new PhpFiles($bouncerConfigs); $lapiRemediation = new LapiRemediation($bouncerConfigs, $client, $cache); $bouncer = $this->getMockForAbstractClass(AbstractBouncer::class, [$bouncerConfigs, $lapiRemediation]); $cappedRemediation = $bouncer->getRemediationForIp(TestHelpers::BAD_IP); $this->assertEquals('captcha', $cappedRemediation, 'The remediation for the banned IP should now be "captcha"'); // Reset the max remediation level to its origin state $bouncerConfigs['bouncing_level'] = Constants::BOUNCING_LEVEL_NORMAL; $client = new BouncerClient($bouncerConfigs); $cache = new PhpFiles($bouncerConfigs); $lapiRemediation = new LapiRemediation($bouncerConfigs, $client, $cache); $bouncer = $this->getMockForAbstractClass(AbstractBouncer::class, [$bouncerConfigs, $lapiRemediation]); $this->logger->info('', ['message' => 'set "Large IPV4 range banned" state']); $this->watcherClient->deleteAllDecisions(); $this->watcherClient->addDecision( new \DateTime(), '24h', WatcherClient::HOURS24, TestHelpers::BAD_IP . '/' . TestHelpers::LARGE_IPV4_RANGE, 'ban' ); $cappedRemediation = $bouncer->getRemediationForIp(TestHelpers::BAD_IP); $this->assertEquals( 'ban', $cappedRemediation, 'The remediation for the banned IPv4 range should be ban' ); $this->logger->info('', ['message' => 'set "IPV6 range banned" state']); $this->watcherClient->deleteAllDecisions(); $this->watcherClient->addDecision( new \DateTime(), '24h', WatcherClient::HOURS24, TestHelpers::BAD_IPV6 . '/' . TestHelpers::IPV6_RANGE, 'ban' ); $cappedRemediation = $bouncer->getRemediationForIp(TestHelpers::BAD_IPV6); $this->assertEquals( 'ban', $cappedRemediation, 'The remediation for a banned IPv6 range should be ban in live mode' ); $this->watcherClient->deleteAllDecisions(); $this->watcherClient->addDecision( new \DateTime(), '24h', WatcherClient::HOURS24, TestHelpers::BAD_IPV6, 'ban' ); $cappedRemediation = $bouncer->getRemediationForIp(TestHelpers::BAD_IPV6); $this->assertEquals( 'ban', $cappedRemediation, 'The remediation for a banned IPv6 should be ban' ); } /** * @group integration */ public function testCanVerifyIpInStreamMode(): void { // Init context $this->watcherClient->setInitialState(); // Init bouncer $bouncerConfigs = [ 'auth_type' => $this->useTls ? Constants::AUTH_TLS : Constants::AUTH_KEY, 'api_key' => TestHelpers::getBouncerKey(), 'api_url' => TestHelpers::getLapiUrl(), 'stream_mode' => true, 'redis_dsn' => getenv('REDIS_DSN'), 'memcached_dsn' => getenv('MEMCACHED_DSN'), 'fs_cache_path' => $this->root->url() . '/.cache', ]; if ($this->useTls) { $this->addTlsConfig($bouncerConfigs, $this->useTls); } $client = new BouncerClient($bouncerConfigs); $cache = new PhpFiles($bouncerConfigs); $lapiRemediation = new LapiRemediation($bouncerConfigs, $client, $cache); $bouncer = $this->getMockForAbstractClass(AbstractBouncer::class, [$bouncerConfigs, $lapiRemediation]); // Test cache adapter $cacheAdapter = $bouncer->getRemediationEngine()->getCacheStorage(); $cacheAdapter->clear(); // As we are in stream mode, no live call should be done to the API. // Warm BlockList cache up $bouncer->refreshBlocklistCache(); $this->assertEquals( 'ban', $bouncer->getRemediationForIp(TestHelpers::BAD_IP), 'Get decisions for a bad IP for the first time (as the cache has been warmed up should be a cache hit)' ); // Reconfigure the bouncer to set maximum remediation level to "captcha" $bouncerConfigs['bouncing_level'] = Constants::BOUNCING_LEVEL_FLEX; $client = new BouncerClient($bouncerConfigs); $cache = new PhpFiles($bouncerConfigs); $lapiRemediation = new LapiRemediation($bouncerConfigs, $client, $cache); $bouncer = $this->getMockForAbstractClass(AbstractBouncer::class, [$bouncerConfigs, $lapiRemediation]); $cappedRemediation = $bouncer->getRemediationForIp(TestHelpers::BAD_IP); $this->assertEquals('captcha', $cappedRemediation, 'The remediation for the banned IP should now be "captcha"'); $bouncerConfigs['bouncing_level'] = Constants::BOUNCING_LEVEL_NORMAL; $client = new BouncerClient($bouncerConfigs); $cache = new PhpFiles($bouncerConfigs); $lapiRemediation = new LapiRemediation($bouncerConfigs, $client, $cache); $bouncer = $this->getMockForAbstractClass(AbstractBouncer::class, [$bouncerConfigs, $lapiRemediation]); $this->assertEquals( 'bypass', $bouncer->getRemediationForIp(TestHelpers::CLEAN_IP), 'Get decisions for a clean IP for the first time (as the cache has been warmed up should be a cache hit)' ); // Preload the remediation to prepare the next tests. $this->assertEquals( 'bypass', $bouncer->getRemediationForIp(TestHelpers::NEWLY_BAD_IP), 'Preload the bypass remediation to prepare the next tests' ); // Add and remove decision $this->watcherClient->setSecondState(); // Pull updates $bouncer->refreshBlocklistCache(); $this->assertEquals( 'ban', $bouncer->getRemediationForIp(TestHelpers::NEWLY_BAD_IP), 'The new decision should now be added, so the previously clean IP should now be bad' ); $this->assertEquals( 'bypass', $bouncer->getRemediationForIp(TestHelpers::BAD_IP), 'The old decisions should now be removed, so the previously bad IP should now be clean' ); // Set up a new instance. $bouncerConfigs = [ 'auth_type' => $this->useTls ? Constants::AUTH_TLS : Constants::AUTH_KEY, 'api_key' => TestHelpers::getBouncerKey(), 'api_url' => TestHelpers::getLapiUrl(), 'stream_mode' => true, 'redis_dsn' => getenv('REDIS_DSN'), 'memcached_dsn' => getenv('MEMCACHED_DSN'), 'fs_cache_path' => $this->root->url() . '/.cache', ]; if ($this->useTls) { $bouncerConfigs['tls_cert_path'] = $this->useTls . '/bouncer.pem'; $bouncerConfigs['tls_key_path'] = $this->useTls . '/bouncer-key.pem'; $bouncerConfigs['tls_ca_cert_path'] = $this->useTls . '/ca-chain.pem'; $bouncerConfigs['tls_verify_peer'] = true; } $client = new BouncerClient($bouncerConfigs); $cache = new PhpFiles($bouncerConfigs); $lapiRemediation = new LapiRemediation($bouncerConfigs, $client, $cache); $bouncer = $this->getMockForAbstractClass(AbstractBouncer::class, [$bouncerConfigs, $lapiRemediation]); $this->assertEquals( 'ban', $bouncer->getRemediationForIp(TestHelpers::NEWLY_BAD_IP) ); $this->logger->info('', ['message' => 'set "Large IPV4 range banned" + "IPV6 range banned" state']); $this->watcherClient->deleteAllDecisions(); $this->watcherClient->addDecision( new \DateTime(), '24h', WatcherClient::HOURS24, TestHelpers::BAD_IP . '/' . TestHelpers::LARGE_IPV4_RANGE, 'ban' ); $this->watcherClient->addDecision( new \DateTime(), '24h', WatcherClient::HOURS24, TestHelpers::BAD_IPV6 . '/' . TestHelpers::IPV6_RANGE, 'ban' ); // Pull updates $bouncer->refreshBlocklistCache(); $cappedRemediation = $bouncer->getRemediationForIp(TestHelpers::BAD_IP); $this->assertEquals( 'ban', $cappedRemediation, 'The remediation for the banned IP with a large range should be "ban" even in stream mode' ); $cappedRemediation = $bouncer->getRemediationForIp(TestHelpers::BAD_IPV6); $this->assertEquals( 'bypass', $cappedRemediation, 'The remediation for the banned IPV6 with a too large range should now be "bypass" as we are in stream mode' ); // Test cache connection $bouncer->testCacheConnection(); } } <file_sep>/.githooks/commit-msg #!/usr/bin/env bash if [ -z "$1" ]; then echo "Missing argument (commit message). Did you try to run this manually?" exit 1 fi commitTitle="$(cat $1 | head -n1)" # ignore merge if echo "$commitTitle" | grep -qE "^Merge"; then echo "Commit hook: ignoring merge" exit 0 fi # check commit message REGEX='^(feat|fix|docs|style|refactor|ci|test|chore|comment)\(.*\)\:.*' if ! echo "$commitTitle" | grep -qE ${REGEX}; then echo "Your commit title '$commitTitle' did not follow conventional commit message rules:" echo "Please comply with the regex ${REGEX}" exit 1 fi <file_sep>/tests/Unit/TemplateTest.php <?php declare(strict_types=1); namespace CrowdSecBouncer\Tests\Unit; /** * Test for templating. * * @author CrowdSec team * * @see https://crowdsec.net CrowdSec Official Website * * @copyright Copyright (c) 2022+ CrowdSec * @license MIT License */ use CrowdSecBouncer\Template; use PHPUnit\Framework\TestCase; /** * @covers \CrowdSecBouncer\Template::__construct * @covers \CrowdSecBouncer\Template::render */ final class TemplateTest extends TestCase { public function testRender() { $template = new Template('ban.html.twig', __DIR__ . '/../../src/templates'); $render = $template->render( [ 'text' => [ 'ban_wall' => [ 'title' => 'BAN TEST TITLE', ], ], ] ); $this->assertStringContainsString('<h1>BAN TEST TITLE</h1>', $render, 'Ban rendering should be as expected'); $this->assertStringNotContainsString('<p class="footer">', $render, 'Ban rendering should not contain footer'); $render = $template->render( [ 'text' => [ 'ban_wall' => [ 'title' => 'BAN TEST TITLE', 'footer' => 'This is a footer test', ], ], ] ); $this->assertStringContainsString('<p class="footer">This is a footer test</p>', $render, 'Ban rendering should contain footer'); $template = new Template('captcha.html.twig', __DIR__ . '/../../src/templates'); $render = $template->render( [ 'text' => [ 'captcha_wall' => [ 'title' => 'CAPTCHA TEST TITLE', ], ], ] ); $this->assertStringContainsString('CAPTCHA TEST TITLE', $render, 'Captcha rendering should be as expected'); $this->assertStringContainsString('<form method="post" id="captcha" action="#">', $render, 'Captcha rendering should be as expected'); } } <file_sep>/src/BouncerException.php <?php declare(strict_types=1); namespace CrowdSecBouncer; use CrowdSec\Common\Exception; /** * Exception interface for all exceptions thrown by CrowdSec Bouncer. * * @author CrowdSec team * * @see https://crowdsec.net CrowdSec Official Website * * @copyright Copyright (c) 2020+ CrowdSec * @license MIT License */ class BouncerException extends Exception { } <file_sep>/docs/DEVELOPER.md ![CrowdSec Logo](images/logo_crowdsec.png) # CrowdSec Bouncer PHP library ## Developer guide <!-- START doctoc generated TOC please keep comment here to allow auto update --> <!-- DON'T EDIT THIS SECTION, INSTEAD RE-RUN doctoc TO UPDATE --> **Table of Contents** - [Local development](#local-development) - [DDEV setup](#ddev-setup) - [DDEV installation](#ddev-installation) - [Prepare DDEV PHP environment](#prepare-ddev-php-environment) - [DDEV Usage](#ddev-usage) - [Add CrowdSec bouncer and watcher](#add-crowdsec-bouncer-and-watcher) - [Use composer to update or install the lib](#use-composer-to-update-or-install-the-lib) - [Find IP of your docker services](#find-ip-of-your-docker-services) - [Unit test](#unit-test) - [Integration test](#integration-test) - [Coding standards](#coding-standards) - [PHPCS Fixer](#phpcs-fixer) - [PHPSTAN](#phpstan) - [PHP Mess Detector](#php-mess-detector) - [PHPCS and PHPCBF](#phpcs-and-phpcbf) - [PSALM](#psalm) - [PHP Unit Code coverage](#php-unit-code-coverage) - [Generate CrowdSec tools and settings on start](#generate-crowdsec-tools-and-settings-on-start) - [Redis debug](#redis-debug) - [Memcached debug](#memcached-debug) - [Discover the CrowdSec LAPI](#discover-the-crowdsec-lapi) - [Use the CrowdSec cli (`cscli`)](#use-the-crowdsec-cli-cscli) - [Add decision for an IP or a range of IPs](#add-decision-for-an-ip-or-a-range-of-ips) - [Add decision to ban or captcha a country](#add-decision-to-ban-or-captcha-a-country) - [Delete decisions](#delete-decisions) - [Create a bouncer](#create-a-bouncer) - [Create a watcher](#create-a-watcher) - [Use the web container to call LAPI](#use-the-web-container-to-call-lapi) - [Commit message](#commit-message) - [Allowed message `type` values](#allowed-message-type-values) - [Release process](#release-process) <!-- END doctoc generated TOC please keep comment here to allow auto update --> ## Local development There are many ways to install this library on a local PHP environment. We are using [DDEV](https://ddev.readthedocs.io/en/stable/) because it is quite simple to use and customize. Of course, you may use your own local stack, but we provide here some useful tools that depends on DDEV. ### DDEV setup For a quick start, follow the below steps. #### DDEV installation For the DDEV installation, please follow the [official instructions](https://ddev.readthedocs.io/en/stable/users/install/ddev-installation/). #### Prepare DDEV PHP environment The final structure of the project will look like below. ``` crowdsec-bouncer-project (choose the name you want for this folder) │ │ (your php project sources; could be a simple index.php file) │ └───.ddev │ │ │ │ (DDEV files) │ └───my-code (do not change this folder name) │ │ └───crowdsec-bouncer-lib (do not change this folder name) │ │ (Clone of this repo) ``` - Create an empty folder that will contain all necessary sources: ```bash mkdir crowdsec-bouncer-project ``` - Create a DDEV php project: ```bash cd crowdsec-bouncer-project ddev config --project-type=php --php-version=8.2 --project-name=crowdsec-bouncer-lib ``` - Add some DDEV add-ons: ```bash ddev get ddev/ddev-redis ddev get ddev/ddev-memcached ddev get julienloizelet/ddev-tools ddev get julienloizelet/ddev-crowdsec-php ``` - Clone this repo sources in a `my-code/crowdsec-bouncer-lib` folder: ```bash mkdir -p my-code/crowdsec-bouncer-lib cd my-code/crowdsec-bouncer-lib && git clone <EMAIL>:crowdsecurity/php-cs-bouncer.git ./ ``` - Launch DDEV ```bash cd .ddev && ddev start ``` This should take some times on the first launch as this will download all necessary docker images. ### DDEV Usage #### Add CrowdSec bouncer and watcher - To create a new bouncer in the CrowdSec container, run: ```bash ddev create-bouncer [name] ``` It will return the bouncer key. - To create a new watcher, run: ```bash ddev create-watcher [name] [password] ``` **N.B.** : Since we are using TLS authentication for agent, you should avoid to create a watcher with this method. #### Use composer to update or install the lib Run: ```bash ddev composer update --working-dir ./my-code/crowdsec-bouncer-lib ``` #### Find IP of your docker services In most cases, you will test to bounce your current IP. As we are running on a docker stack, this is the local host IP. To find it, just run: ```bash ddev find-ip ``` You will have to know also the IP of the `ddev-router` container as it acts as a proxy, and you should set it in the `trust_ip_forward_array` setting. To find this IP, just run: ```bash ddev find-ip ddev-router ``` #### Unit test ```bash ddev php ./my-code/crowdsec-bouncer-lib/vendor/bin/phpunit ./my-code/crowdsec-bouncer-lib/tests/Unit --testdox ``` #### Integration test First, create a bouncer and keep the result key. ```bash ddev create-bouncer ``` Then, as we use a TLS ready CrowdSec container, you have to copy some certificates and key: ```bash cd crowdsec-bouncer-project mkdir cfssl cp -r ../.ddev/okaeli-add-on/custom_files/crowdsec/cfssl/* cfssl ``` Finally, run ```bash ddev exec BOUNCER_KEY=your-bouncer-key AGENT_TLS_PATH=/var/www/html/cfssl LAPI_URL=https://crowdsec:8080 MEMCACHED_DSN=memcached://memcached:11211 REDIS_DSN=redis://redis:6379 /usr/bin/php ./my-code/crowdsec-bouncer-lib/vendor/bin/phpunit --testdox --colors --exclude-group ignore ./my-code/crowdsec-bouncer-lib/tests/Integration/AbstractBouncerTest.php ``` For geolocation Unit Test, you should first put 2 free MaxMind databases in the `tests` folder : `GeoLite2-City.mmdb` and `GeoLite2-Country.mmdb`. You can download these databases by creating a MaxMind account and browse to [the download page](https://www.maxmind.com/en/accounts/current/geoip/downloads). Then, you can run: ```bash ddev exec BOUNCER_KEY=your-bouncer-key AGENT_TLS_PATH=/var/www/html/cfssl LAPI_URL=https://crowdsec:8080 MEMCACHED_DSN=memcached://memcached:11211 REDIS_DSN=redis://redis:6379 /usr/bin/php ./my-code/crowdsec-bouncer-lib/vendor/bin/phpunit --testdox --colors --exclude-group ignore ./my-code/crowdsec-bouncer-lib/tests/Integration/GeolocationTest.php ``` **N.B**.: If you want to test with `tls` authentification, you have to add `BOUNCER_TLS_PATH` environment variable and specify the path where you store certificates and keys. For example: ```bash ddev exec USE_CURL=1 AGENT_TLS_PATH=/var/www/html/cfssl BOUNCER_TLS_PATH=/var/www/html/cfssl LAPI_URL=https://crowdsec:8080 MEMCACHED_DSN=memcached://memcached:11211 REDIS_DSN=redis://redis:6379 /usr/bin/php ./my-code/crowdsec-bouncer-lib/vendor/bin/phpunit --testdox --colors --exclude-group ignore ./my-code/crowdsec-bouncer-lib/tests/Integration/AbstractBouncerTest.php ``` #### Coding standards We set up some coding standards tools that you will find in the `tools/coding-standards` folder. In order to use these, you will need to work with a PHP version >= 7.4 and run first: ``` ddev composer update --working-dir=./my-code/crowdsec-bouncer-lib/tools/coding-standards ``` ##### PHPCS Fixer We are using the [PHP Coding Standards Fixer](https://cs.symfony.com/). With ddev, you can do the following: ```bash ddev phpcsfixer my-code/crowdsec-bouncer-lib/tools/coding-standards/php-cs-fixer ../ ``` ##### PHPSTAN To use the [PHPSTAN](https://github.com/phpstan/phpstan) tool, you can run: ```bash ddev phpstan /var/www/html/my-code/crowdsec-bouncer-lib/tools/coding-standards phpstan/phpstan.neon /var/www/html/my-code/crowdsec-bouncer-lib/src ``` ##### PHP Mess Detector To use the [PHPMD](https://github.com/phpmd/phpmd) tool, you can run: ```bash ddev phpmd ./my-code/crowdsec-bouncer-lib/tools/coding-standards phpmd/rulesets.xml ../../src ``` ##### PHPCS and PHPCBF To use [PHP Code Sniffer](https://github.com/squizlabs/PHP_CodeSniffer) tools, you can run: ```bash ddev phpcs ./my-code/crowdsec-bouncer-lib/tools/coding-standards my-code/crowdsec-bouncer-lib/src PSR12 ``` and: ```bash ddev phpcbf ./my-code/crowdsec-bouncer-lib/tools/coding-standards my-code/crowdsec-bouncer-lib/src PSR12 ``` ##### PSALM To use [PSALM](https://github.com/vimeo/psalm) tools, you can run: ```bash ddev psalm ./my-code/crowdsec-bouncer-lib/tools/coding-standards ./my-code/crowdsec-bouncer-lib/tools/coding-standards/psalm ``` ##### PHP Unit Code coverage In order to generate a code coverage report, you have to: - Enable `xdebug`: ```bash ddev xdebug ``` To generate a html report, you can run: ```bash ddev exec XDEBUG_MODE=coverage BOUNCER_KEY=your-bouncer-key AGENT_TLS_PATH=/var/www/html/cfssl LAPI_URL=https://crowdsec:8080 REDIS_DSN=redis://redis:6379 MEMCACHED_DSN=memcached://memcached:11211 /usr/bin/php ./my-code/crowdsec-bouncer-lib/tools/coding-standards/vendor/bin/phpunit --configuration ./my-code/crowdsec-bouncer-lib/tools/coding-standards/phpunit/phpunit.xml ``` You should find the main report file `dashboard.html` in `tools/coding-standards/phpunit/code-coverage` folder. If you want to generate a text report in the same folder: ```bash ddev exec XDEBUG_MODE=coverage BOUNCER_KEY=your-bouncer-key LAPI_URL=https://crowdsec:8080 MEMCACHED_DSN=memcached://memcached:11211 REDIS_DSN=redis://redis:6379 /usr/bin/php ./my-code/crowdsec-bouncer-lib/tools/coding-standards/vendor/bin/phpunit --configuration ./my-code/crowdsec-bouncer-lib/tools/coding-standards/phpunit/phpunit.xml --coverage-text=./my-code/crowdsec-bouncer-lib/tools/coding-standards/phpunit/code-coverage/report.txt ``` #### Generate CrowdSec tools and settings on start We use a post-start DDEV hook to: - Create a bouncer - Set bouncer key, api url and other needed values in the `scripts/auto-prepend/settings.php` file (useful to test standalone mode). - Create a watcher that we use in end-to-end tests Just copy the file and restart: ```bash cp .ddev/config_overrides/config.crowdsec.yaml .ddev/config.crowdsec.yaml ddev restart ``` #### Redis debug You should enter the `Redis` container: ```bash ddev exec -s redis redis-cli ``` Then, you could play with the `redis-cli` command line tool: - Display keys and databases: `INFO keyspace` - Display stored keys: `KEYS *` - Display key value: `GET [key]` - Remove a key: `DEL [key]` #### Memcached debug @see https://lzone.de/cheat-sheet/memcached First, find the IP of the `Memcached` container: ```bash ddev find-ip memcached ``` Then, you could use `telnet` to interact with memcached: ``` telnet <MEMCACHED_IP> 11211 ``` - `stats` - `stats items`: The first number after `items` is the slab id. Request a cache dump for each slab id, with a limit for the max number of keys to dump: - `stats cachedump 2 100` - `get <mykey>` : Read a value - `delete <mykey>`: Delete a key ## Discover the CrowdSec LAPI This library interacts with a CrowdSec agent that you have installed on an accessible server. The easiest way to interact with the local API (LAPI) is to use the `cscli` tool,but it is also possible to contact it through a certain URL (e.g. `https://crowdsec:8080`). ### Use the CrowdSec cli (`cscli`) Please refer to the [CrowdSec cscli documentation](https://docs.crowdsec.net/docs/cscli/) for an exhaustive list of commands. **N.B**.: If you are using DDEV, just replace `cscli` with `ddev exec -s crowdsec cscli`. Here is a list of command that we often use to test the PHP library: #### Add decision for an IP or a range of IPs First example is a `ban`, second one is a `captcha`: ```bash cscli decisions add --ip <SOME_IP> --duration 12h --type ban cscli decisions add --ip <SOME_IP> --duration 4h --type captcha ``` For a range of IPs: ```bash cscli decisions add --range 1.2.3.4/30 --duration 12h --type ban ``` #### Add decision to ban or captcha a country ```bash cscli decisions add --scope Country --value JP --duration 4h --type ban ``` #### Delete decisions - Delete all decisions: ```bash cscli decisions delete --all ``` - Delete a decision with an IP scope ```bash cscli decisions delete -i <SOME_IP> ``` #### Create a bouncer ```bash cscli bouncers add <BOUNCER_NAME> -o raw ``` With DDEV, an alias is available: ```bash ddev create-bouncer <BOUNCER_NAME> ``` #### Create a watcher ```bash cscli machines add <SOME_LOGIN> --password <<PASSWORD>> -o raw ``` With DDEV, an alias is available: ```bash ddev create-watcher <SOME_LOGIN> <SOME_PASSWORD> ``` ### Use the web container to call LAPI Please see the [CrowdSec LAPI documentation](https://crowdsecurity.github.io/api_doc/index.html?urls.primaryName=LAPI) for an exhaustive list of available calls. If you are using DDEV, you can enter the web by running: ```bash ddev exec bash ```` Then, you should use some `curl` calls to contact the LAPI. For example, you can get the list of decisions with commands like: ```bash curl -H "X-Api-Key: <YOUR_BOUNCER_KEY>" https://crowdsec:8080/v1/decisions | jq curl -H "X-Api-Key: <YOUR_BOUNCER_KEY>" https://crowdsec:8080/v1/decisions?ip=1.2.3.4 | jq curl -H "X-Api-Key: <YOUR_BOUNCER_KEY>" https://crowdsec:8080/v1/decisions/stream?startup=true | jq curl -H "X-Api-Key: <YOUR_BOUNCER_KEY>" https://crowdsec:8080/v1/decisions/stream | jq ``` ## Commit message In order to have an explicit commit history, we are using some commits message convention with the following format: <type>(<scope>): <subject> Allowed `type` are defined below. `scope` value intends to clarify which part of the code has been modified. It can be empty or `*` if the change is a global or difficult to assign to a specific part. `subject` describes what has been done using the imperative, present tense. Example: feat(admin): Add css for admin actions You can use the `commit-msg` git hook that you will find in the `.githooks` folder: ``` cp .githooks/commit-msg .git/hooks/commit-msg chmod +x .git/hooks/commit-msg ``` ### Allowed message `type` values - chore (automatic tasks; no production code change) - ci (updating continuous integration process; no production code change) - comment (commenting;no production code change) - docs (changes to the documentation) - feat (new feature for the user) - fix (bug fix for the user) - refactor (refactoring production code) - style (formatting; no production code change) - test (adding missing tests, refactoring tests; no production code change) ## Release process We are using [semantic versioning](https://semver.org/) to determine a version number. To verify the current tag, you should run: ``` git describe --tags `git rev-list --tags --max-count=1` ``` Before publishing a new release, there are some manual steps to take: - Change the version number in the `Constants.php` file - Update the `CHANGELOG.md` file Then, you have to [run the action manually from the GitHub repository](https://github.com/crowdsecurity/php-cs-bouncer/actions/workflows/release.yml) Alternatively, you could use the [GitHub CLI](https://github.com/cli/cli): - create a draft release: ``` gh workflow run release.yml -f tag_name=vx.y.z -f draft=true ``` - publish a prerelease: ``` gh workflow run release.yml -f tag_name=vx.y.z -f prerelease=true ``` - publish a release: ``` gh workflow run release.yml -f tag_name=vx.y.z ``` Note that the GitHub action will fail if the tag `tag_name` already exits. <file_sep>/src/AbstractBouncer.php <?php declare(strict_types=1); namespace CrowdSecBouncer; use CrowdSec\Common\Client\RequestHandler\Curl; use CrowdSec\Common\Client\RequestHandler\FileGetContents; use CrowdSec\LapiClient\Bouncer as BouncerClient; use CrowdSec\RemediationEngine\AbstractRemediation; use CrowdSec\RemediationEngine\CacheStorage\AbstractCache; use CrowdSec\RemediationEngine\CacheStorage\CacheStorageException; use CrowdSec\RemediationEngine\CacheStorage\Memcached; use CrowdSec\RemediationEngine\CacheStorage\PhpFiles; use CrowdSec\RemediationEngine\CacheStorage\Redis; use CrowdSecBouncer\Fixes\Gregwar\Captcha\CaptchaBuilder; use Gregwar\Captcha\PhraseBuilder; use IPLib\Factory; use Monolog\Handler\NullHandler; use Monolog\Logger; use Psr\Cache\CacheException; use Psr\Cache\InvalidArgumentException; use Psr\Log\LoggerInterface; use Symfony\Component\Config\Definition\Processor; /** * The class that apply a bounce. * * @author CrowdSec team * * @see https://crowdsec.net CrowdSec Official Website * * @copyright Copyright (c) 2021+ CrowdSec * @license MIT License */ abstract class AbstractBouncer { /** @var array */ protected $configs = []; /** @var LoggerInterface */ protected $logger; /** @var AbstractRemediation */ protected $remediationEngine; public function __construct( array $configs, AbstractRemediation $remediationEngine, LoggerInterface $logger = null ) { // @codeCoverageIgnoreStart if (!$logger) { $logger = new Logger('null'); $logger->pushHandler(new NullHandler()); } // @codeCoverageIgnoreEnd $this->logger = $logger; $this->configure($configs); $this->remediationEngine = $remediationEngine; $configs = $this->getConfigs(); // Clean configs for lighter log unset($configs['text'], $configs['color']); $this->logger->debug('Instantiate bouncer', [ 'type' => 'BOUNCER_INIT', 'logger' => \get_class($this->getLogger()), 'remediation' => \get_class($this->getRemediationEngine()), 'configs' => $configs, ]); } /** * Apply a bounce for current IP depending on remediation associated to this IP * (e.g. display a ban wall, captcha wall or do nothing in case of a bypass). * * @throws BouncerException * @throws CacheException * @throws InvalidArgumentException * @throws \Symfony\Component\Cache\Exception\InvalidArgumentException */ public function bounceCurrentIp(): void { // Retrieve the current IP (even if it is a proxy IP) or a testing IP $forcedTestIp = $this->getConfig('forced_test_ip'); $ip = $forcedTestIp ?: $this->getRemoteIp(); $ip = $this->handleForwardedFor($ip, $this->configs); $this->logger->info('Bouncing current IP', [ 'ip' => $ip, ]); $remediation = $this->getRemediationForIp($ip); $this->handleRemediation($remediation, $ip); } /** * This method clear the full data in cache. * * @return bool If the cache has been successfully cleared or not * * @throws BouncerException */ public function clearCache(): bool { try { return $this->getRemediationEngine()->clearCache(); } catch (\Exception $e) { throw new BouncerException('Error while clearing cache: ' . $e->getMessage(), (int) $e->getCode(), $e); } } /** * Retrieve Bouncer configuration by name. * * @return mixed */ public function getConfig(string $name) { return (isset($this->configs[$name])) ? $this->configs[$name] : null; } /** * Retrieve Bouncer configurations. */ public function getConfigs(): array { return $this->configs; } /** * Get current http method. */ abstract public function getHttpMethod(): string; /** * Get value of an HTTP request header. Ex: "X-Forwarded-For". */ abstract public function getHttpRequestHeader(string $name): ?string; /** * Returns the logger instance. * * @return LoggerInterface the logger used by this library */ public function getLogger(): LoggerInterface { return $this->logger; } /** * Get the value of a posted field. */ abstract public function getPostedVariable(string $name): ?string; public function getRemediationEngine(): AbstractRemediation { return $this->remediationEngine; } /** * Get the remediation for the specified IP. * * @return string the remediation to apply (ex: 'ban', 'captcha', 'bypass') * * @throws BouncerException */ public function getRemediationForIp(string $ip): string { try { return $this->capRemediationLevel($this->getRemediationEngine()->getIpRemediation($ip)); } catch (\Exception $e) { throw new BouncerException($e->getMessage(), (int) $e->getCode(), $e); } } /** * Get the current IP, even if it's the IP of a proxy. */ abstract public function getRemoteIp(): string; /** * Get current request uri. */ abstract public function getRequestUri(): string; /** * This method prune the cache: it removes all the expired cache items. * * @return bool If the cache has been successfully pruned or not * * @throws BouncerException */ public function pruneCache(): bool { try { return $this->getRemediationEngine()->pruneCache(); } catch (\Exception $e) { throw new BouncerException('Error while pruning cache: ' . $e->getMessage(), (int) $e->getCode(), $e); } } /** * Used in stream mode only. * This method should be called periodically (ex: crontab) in an asynchronous way to update the bouncer cache. * * @return array Number of deleted and new decisions * * @throws BouncerException */ public function refreshBlocklistCache(): array { try { return $this->getRemediationEngine()->refreshDecisions(); } catch (\Exception $e) { $message = 'Error while refreshing decisions: ' . $e->getMessage(); throw new BouncerException($message, (int) $e->getCode(), $e); } } /** * Handle a bounce for current IP. * * @throws BouncerException * @throws CacheException * @throws InvalidArgumentException * @throws \Symfony\Component\Cache\Exception\InvalidArgumentException */ public function run(): bool { $result = false; try { if ($this->shouldBounceCurrentIp()) { $this->bounceCurrentIp(); $result = true; } } catch (\Exception $e) { $this->logger->error('Something went wrong during bouncing', [ 'type' => 'EXCEPTION_WHILE_BOUNCING', 'message' => $e->getMessage(), 'code' => $e->getCode(), 'file' => $e->getFile(), 'line' => $e->getLine(), ]); if (true === $this->getConfig('display_errors')) { throw new BouncerException($e->getMessage(), (int) $e->getCode(), $e); } } return $result; } /** * If the current IP should be bounced or not, matching custom business rules. */ public function shouldBounceCurrentIp(): bool { $excludedURIs = $this->getConfig('excluded_uris') ?? []; $uri = $this->getRequestUri(); if ($uri && \in_array($uri, $excludedURIs)) { $this->logger->debug('Will not bounce as URI is excluded', [ 'type' => 'SHOULD_NOT_BOUNCE', 'message' => 'This URI is excluded from bouncing: ' . $uri, ]); return false; } $bouncingDisabled = (Constants::BOUNCING_LEVEL_DISABLED === $this->getConfig('bouncing_level')); if ($bouncingDisabled) { $this->logger->debug('Will not bounce as bouncing is disabled', [ 'type' => 'SHOULD_NOT_BOUNCE', 'message' => Constants::BOUNCING_LEVEL_DISABLED, ]); return false; } return true; } /** * Process a simple cache test. * * @throws BouncerException * @throws InvalidArgumentException */ public function testCacheConnection(): void { try { $cache = $this->getRemediationEngine()->getCacheStorage(); $cache->getItem(AbstractCache::CONFIG); } catch (\Exception $e) { $message = 'Error while testing cache connection: ' . $e->getMessage(); throw new BouncerException($message, (int) $e->getCode(), $e); } } /** * @throws BouncerException * @throws CacheStorageException */ protected function handleCache(array $configs, LoggerInterface $logger): AbstractCache { $cacheSystem = $configs['cache_system'] ?? Constants::CACHE_SYSTEM_PHPFS; switch ($cacheSystem) { case Constants::CACHE_SYSTEM_PHPFS: $cache = new PhpFiles($configs, $logger); break; case Constants::CACHE_SYSTEM_MEMCACHED: $cache = new Memcached($configs, $logger); break; case Constants::CACHE_SYSTEM_REDIS: $cache = new Redis($configs, $logger); break; default: throw new BouncerException("Unknown selected cache technology: $cacheSystem"); } return $cache; } protected function handleClient(array $configs, LoggerInterface $logger): BouncerClient { $requestHandler = empty($configs['use_curl']) ? new FileGetContents($configs) : new Curl($configs); return new BouncerClient($configs, $requestHandler, $logger); } /** * Handle remediation for some IP. * * @throws CacheException * @throws InvalidArgumentException * @throws \Symfony\Component\Cache\Exception\InvalidArgumentException * @throws BouncerException */ protected function handleRemediation(string $remediation, string $ip): void { switch ($remediation) { case Constants::REMEDIATION_CAPTCHA: $this->handleCaptchaRemediation($ip); break; case Constants::REMEDIATION_BAN: $this->logger->debug('Will display a ban wall', [ 'ip' => $ip, ]); $this->handleBanRemediation(); break; case Constants::REMEDIATION_BYPASS: default: } } /** * @codeCoverageIgnore */ protected function redirectResponse(string $redirect): void { header("Location: $redirect"); exit(0); } /** * Send HTTP response. * * @throws BouncerException * * @codeCoverageIgnore */ protected function sendResponse(string $body, int $statusCode): void { switch ($statusCode) { case 401: header('HTTP/1.0 401 Unauthorized'); header('Cache-Control: no-store, no-cache, must-revalidate, max-age=0'); header('Cache-Control: post-check=0, pre-check=0', false); header('Pragma: no-cache'); break; case 403: header('HTTP/1.0 403 Forbidden'); header('Cache-Control: no-store, no-cache, must-revalidate, max-age=0'); header('Cache-Control: post-check=0, pre-check=0', false); header('Pragma: no-cache'); break; default: throw new BouncerException("Unhandled code $statusCode"); } echo $body; exit(0); } /** * Build a captcha couple. * * @return array an array composed of two items, a "phrase" string representing the phrase and a "inlineImage" * representing the image data */ private function buildCaptchaCouple(): array { $captchaBuilder = new CaptchaBuilder(); return [ 'phrase' => $captchaBuilder->getPhrase(), 'inlineImage' => $captchaBuilder->build()->inline(), ]; } /** * Cap the remediation to a fixed value given by the bouncing level configuration. * * @param string $remediation (ex: 'ban', 'captcha', 'bypass') * * @return string $remediation The resulting remediation to use (ex: 'ban', 'captcha', 'bypass') */ private function capRemediationLevel(string $remediation): string { $orderedRemediations = $this->getRemediationEngine()->getConfig('ordered_remediations') ?? []; $bouncingLevel = $this->getConfig('bouncing_level') ?? Constants::BOUNCING_LEVEL_NORMAL; // Compute max remediation level switch ($bouncingLevel) { case Constants::BOUNCING_LEVEL_DISABLED: $maxRemediationLevel = Constants::REMEDIATION_BYPASS; break; case Constants::BOUNCING_LEVEL_FLEX: $maxRemediationLevel = Constants::REMEDIATION_CAPTCHA; break; case Constants::BOUNCING_LEVEL_NORMAL: default: $maxRemediationLevel = Constants::REMEDIATION_BAN; break; } $currentIndex = (int) array_search($remediation, $orderedRemediations); $maxIndex = (int) array_search( $maxRemediationLevel, $orderedRemediations ); $finalRemediation = $remediation; if ($currentIndex < $maxIndex) { $finalRemediation = $orderedRemediations[$maxIndex]; $this->logger->debug('Original remediation has been capped', [ 'origin' => $remediation, 'final' => $finalRemediation, ]); } $this->logger->info('Final remediation', [ 'remediation' => $finalRemediation, ]); return $finalRemediation; } /** * Check if the captcha filled by the user is correct or not. * We are permissive with the user: * - case is not sensitive * - (0 is interpreted as "o" and 1 in interpreted as "l"). * * @param string $expected The expected phrase * @param string $try The phrase to check (the user input) * @param string $ip The IP of the use (for logging purpose) * * @return bool If the captcha input was correct or not * * @SuppressWarnings(PHPMD.StaticAccess) */ private function checkCaptcha(string $expected, string $try, string $ip): bool { $solved = PhraseBuilder::comparePhrases($expected, $try); $this->logger->info('Captcha has been solved', [ 'type' => 'CAPTCHA_SOLVED', 'ip' => $ip, 'resolution' => $solved, ]); return $solved; } /** * Configure this instance. * * @param array $config An array with all configuration parameters */ private function configure(array $config): void { // Process and validate input configuration. $configuration = new Configuration(); $processor = new Processor(); $this->configs = $processor->processConfiguration($configuration, [$configuration->cleanConfigs($config)]); } /** * @throws InvalidArgumentException * @throws BouncerException * * @codeCoverageIgnore */ private function displayCaptchaWall(string $ip): void { $captchaVariables = $this->getCache()->getIpVariables( Constants::CACHE_TAG_CAPTCHA, ['resolution_failed', 'inline_image'], $ip ); $body = $this->getCaptchaHtml( (bool) $captchaVariables['resolution_failed'], (string) $captchaVariables['inline_image'], '' ); $this->sendResponse($body, 401); } /** * Returns a default "CrowdSec 403" HTML template. * The input $config should match the TemplateConfiguration input format. * * @return string The HTML compiled template */ private function getBanHtml(): string { $template = new Template('ban.html.twig'); return $template->render($this->configs); } private function getCache(): AbstractCache { return $this->getRemediationEngine()->getCacheStorage(); } /** * Returns a default "CrowdSec Captcha (401)" HTML template. */ private function getCaptchaHtml( bool $error, string $captchaImageSrc, string $captchaResolutionFormUrl ): string { $template = new Template('captcha.html.twig'); return $template->render(array_merge( $this->configs, [ 'error' => $error, 'captcha_img' => $captchaImageSrc, 'captcha_resolution_url' => $captchaResolutionFormUrl, ] )); } /** * @return array [[string, string], ...] Returns IP ranges to trust as proxies as an array of comparables ip bounds */ private function getTrustForwardedIpBoundsList(): array { return $this->getConfig('trust_ip_forward_array') ?? []; } /** * @throws BouncerException * @throws BouncerException * * @codeCoverageIgnore */ private function handleBanRemediation(): void { $body = $this->getBanHtml(); $this->sendResponse($body, 403); } /** * @throws BouncerException * @throws CacheException * @throws InvalidArgumentException * @throws \Symfony\Component\Cache\Exception\InvalidArgumentException */ private function handleCaptchaRemediation(string $ip): void { // Check captcha resolution form $this->handleCaptchaResolutionForm($ip); $cachedCaptchaVariables = $this->getCache()->getIpVariables( Constants::CACHE_TAG_CAPTCHA, ['has_to_be_resolved'], $ip ); $mustResolve = false; if (null === $cachedCaptchaVariables['has_to_be_resolved']) { // Set up the first captcha remediation. $mustResolve = true; $this->logger->debug('First captcha resolution', [ 'ip' => $ip, ]); $this->initCaptchaResolution($ip); } // Display captcha page if this is required. if ($cachedCaptchaVariables['has_to_be_resolved'] || $mustResolve) { $this->logger->debug('Will display a captcha wall', [ 'ip' => $ip, ]); $this->displayCaptchaWall($ip); } $this->logger->info('Captcha wall is not required (already solved)', [ 'ip' => $ip, ]); } /** * @throws CacheException * @throws InvalidArgumentException * @throws \Symfony\Component\Cache\Exception\InvalidArgumentException * * @SuppressWarnings(PHPMD.ElseExpression) */ private function handleCaptchaResolutionForm(string $ip): void { $cachedCaptchaVariables = $this->getCache()->getIpVariables( Constants::CACHE_TAG_CAPTCHA, [ 'has_to_be_resolved', 'phrase_to_guess', 'resolution_redirect', ], $ip ); if ($this->shouldNotCheckResolution($cachedCaptchaVariables) || $this->refreshCaptcha($ip)) { return; } // Handle a captcha resolution try if ( null !== $this->getPostedVariable('phrase') && null !== $cachedCaptchaVariables['phrase_to_guess'] ) { $duration = $this->getConfig('captcha_cache_duration') ?? Constants::CACHE_EXPIRATION_FOR_CAPTCHA; if ( $this->checkCaptcha( (string) $cachedCaptchaVariables['phrase_to_guess'], (string) $this->getPostedVariable('phrase'), $ip ) ) { // User has correctly filled the captcha $this->getCache()->setIpVariables( Constants::CACHE_TAG_CAPTCHA, ['has_to_be_resolved' => false], $ip, $duration, [Constants::CACHE_TAG_CAPTCHA] ); $unsetVariables = [ 'phrase_to_guess', 'inline_image', 'resolution_failed', 'resolution_redirect', ]; $this->getCache()->unsetIpVariables( Constants::CACHE_TAG_CAPTCHA, $unsetVariables, $ip, $duration, [Constants::CACHE_TAG_CAPTCHA] ); $redirect = $cachedCaptchaVariables['resolution_redirect'] ?? '/'; $this->redirectResponse($redirect); } else { // The user failed to resolve the captcha. $this->getCache()->setIpVariables( Constants::CACHE_TAG_CAPTCHA, ['resolution_failed' => true], $ip, $duration, [Constants::CACHE_TAG_CAPTCHA] ); } } } /** * Handle X-Forwarded-For HTTP header to retrieve the IP to bounce. * * @SuppressWarnings(PHPMD.ElseExpression) */ private function handleForwardedFor(string $ip, array $configs): string { $forwardedIp = null; if (empty($configs['forced_test_forwarded_ip'])) { $xForwardedForHeader = $this->getHttpRequestHeader('X-Forwarded-For'); if (null !== $xForwardedForHeader) { $ipList = array_map('trim', array_values(array_filter(explode(',', $xForwardedForHeader)))); $forwardedIp = end($ipList); } } elseif (Constants::X_FORWARDED_DISABLED === $configs['forced_test_forwarded_ip']) { $this->logger->debug('X-Forwarded-for usage is disabled', [ 'type' => 'DISABLED_X_FORWARDED_FOR_USAGE', 'original_ip' => $ip, ]); } else { $forwardedIp = (string) $configs['forced_test_forwarded_ip']; $this->logger->debug('X-Forwarded-for usage is forced', [ 'type' => 'FORCED_X_FORWARDED_FOR_USAGE', 'original_ip' => $ip, 'x_forwarded_for_ip' => $forwardedIp, ]); } if (is_string($forwardedIp)) { if ($this->shouldTrustXforwardedFor($ip)) { $this->logger->debug('Detected IP is allowed for X-Forwarded-for usage', [ 'type' => 'AUTHORIZED_X_FORWARDED_FOR_USAGE', 'original_ip' => $ip, 'x_forwarded_for_ip' => $forwardedIp, ]); return $forwardedIp; } $this->logger->warning('Detected IP is not allowed for X-Forwarded-for usage', [ 'type' => 'NON_AUTHORIZED_X_FORWARDED_FOR_USAGE', 'original_ip' => $ip, 'x_forwarded_for_ip' => $forwardedIp, ]); } return $ip; } /** * @throws CacheException * @throws InvalidArgumentException * @throws \Symfony\Component\Cache\Exception\InvalidArgumentException */ private function initCaptchaResolution(string $ip): void { $captchaCouple = $this->buildCaptchaCouple(); $referer = $this->getHttpRequestHeader('REFERER'); $captchaVariables = [ 'phrase_to_guess' => $captchaCouple['phrase'], 'inline_image' => $captchaCouple['inlineImage'], 'has_to_be_resolved' => true, 'resolution_failed' => false, 'resolution_redirect' => 'POST' === $this->getHttpMethod() && !empty($referer) ? $referer : '/', ]; $duration = $this->getConfig('captcha_cache_duration') ?? Constants::CACHE_EXPIRATION_FOR_CAPTCHA; $this->getCache()->setIpVariables( Constants::CACHE_TAG_CAPTCHA, $captchaVariables, $ip, $duration, [Constants::CACHE_TAG_CAPTCHA] ); } /** * @throws CacheException * @throws InvalidArgumentException * @throws \Symfony\Component\Cache\Exception\InvalidArgumentException */ private function refreshCaptcha(string $ip): bool { if (null !== $this->getPostedVariable('refresh') && (int) $this->getPostedVariable('refresh')) { // Generate new captcha image for the user $captchaCouple = $this->buildCaptchaCouple(); $captchaVariables = [ 'phrase_to_guess' => $captchaCouple['phrase'], 'inline_image' => $captchaCouple['inlineImage'], 'resolution_failed' => false, ]; $duration = $this->getConfig('captcha_cache_duration') ?? Constants::CACHE_EXPIRATION_FOR_CAPTCHA; $this->getCache()->setIpVariables( Constants::CACHE_TAG_CAPTCHA, $captchaVariables, $ip, $duration, [Constants::CACHE_TAG_CAPTCHA] ); return true; } return false; } /** * Check if captcha resolution is required or not. */ private function shouldNotCheckResolution(array $captchaData): bool { $result = false; if (\in_array($captchaData['has_to_be_resolved'], [null, false])) { // Check not needed if 'has_to_be_resolved' cached flag has not been saved $result = true; } elseif ('POST' !== $this->getHttpMethod() || null === $this->getPostedVariable('crowdsec_captcha')) { // Check not needed if no form captcha form has been filled. $result = true; } return $result; } private function shouldTrustXforwardedFor(string $ip): bool { $parsedAddress = Factory::parseAddressString($ip, 3); if (null === $parsedAddress) { $this->logger->warning('IP is invalid', [ 'type' => 'INVALID_INPUT_IP', 'ip' => $ip, ]); return false; } $comparableAddress = $parsedAddress->getComparableString(); foreach ($this->getTrustForwardedIpBoundsList() as $comparableIpBounds) { if ($comparableAddress >= $comparableIpBounds[0] && $comparableAddress <= $comparableIpBounds[1]) { return true; } } return false; } } <file_sep>/docs/USER_GUIDE.md ![CrowdSec Logo](images/logo_crowdsec.png) # CrowdSec Bouncer PHP library ## User Guide <!-- START doctoc generated TOC please keep comment here to allow auto update --> <!-- DON'T EDIT THIS SECTION, INSTEAD RE-RUN doctoc TO UPDATE --> **Table of Contents** - [Description](#description) - [Prerequisites](#prerequisites) - [Features](#features) - [Usage](#usage) - [Create your own bouncer](#create-your-own-bouncer) - [Implementation](#implementation) - [Test your bouncer](#test-your-bouncer) - [Configurations](#configurations) - [Bouncer behavior](#bouncer-behavior) - [Local API Connection](#local-api-connection) - [Cache](#cache) - [Geolocation](#geolocation) - [Captcha and ban wall settings](#captcha-and-ban-wall-settings) - [Debug](#debug) - [Security note](#security-note) - [Other ready to use PHP bouncers](#other-ready-to-use-php-bouncers) <!-- END doctoc generated TOC please keep comment here to allow auto update --> ## Description This library allows you to create CrowdSec bouncers for PHP applications or frameworks like e-commerce, blog or other exposed applications. ## Prerequisites To be able to use a bouncer based on this library, the first step is to install [CrowdSec v1](https://doc.crowdsec.net/docs/getting_started/install_crowdsec/). CrowdSec is only in charge of the "detection", and won't block anything on its own. You need to deploy a bouncer to "apply" decisions. Please note that first and foremost a CrowdSec agent must be installed on a server that is accessible by this library. ## Features - CrowdSec Local API support - Handle `ip`, `range` and `country` scoped decisions - `Live mode` or `Stream mode` - Support IpV4 and Ipv6 (Ipv6 range decisions are yet only supported in `Live mode`) - Large PHP matrix compatibility: 7.2, 7.3, 7.4, 8.0, 8.1 and 8.2 - Built-in support for the most known cache systems Redis, Memcached and PhpFiles - Clear, prune and refresh the bouncer cache - Cap remediation level (ex: for sensitives websites: ban will be capped to captcha) ## Usage When a user is suspected by CrowdSec to be malevolent, a bouncer would either display a captcha to resolve or simply a page notifying that access is denied. If the user is considered as a clean user, he/she will access the page as normal. A ban wall could look like: ![Ban wall](images/screenshots/front-ban.jpg) A captcha wall could look like: ![Captcha wall](images/screenshots/front-captcha.jpg) Please note that it is possible to customize all the colors of these pages so that they integrate best with your design. On the other hand, all texts are also fully customizable. This will allow you, for example, to present translated pages in your users' language. ## Create your own bouncer ### Implementation You can use this library to develop your own PHP application bouncer. Any custom bouncer should extend the [`AbstractBouncer`](../src/AbstractBouncer.php) class. ```php namespace MyNameSpace; use CrowdSecBouncer\AbstractBouncer; class MyCustomBouncer extends AbstractBouncer { } ``` Then, you will have to implement all necessary methods : ```php namespace MyNameSpace; use CrowdSecBouncer\AbstractBouncer; class MyCustomBouncer extends AbstractBouncer { /** * Get current http method */ public function getHttpMethod(): string { // Your implementation } /** * Get value of an HTTP request header. Ex: "X-Forwarded-For" */ public function getHttpRequestHeader(string $name): ?string { // Your implementation } /** * Get the value of a posted field. */ public function getPostedVariable(string $name): ?string { // Your implementation } /** * Get the current IP, even if it's the IP of a proxy */ public function getRemoteIp(): string { // Your implementation } /** * Get current request uri */ public function getRequestUri(): string { // Your implementation } } ``` Once you have implemented these methods, you could retrieve all required configurations to instantiate your bouncer and then call the `run` method to apply a bounce for the current detected IP. Please see below for the list of available configurations. In order to instantiate the bouncer, you will have to create at least a `CrowdSec\RemediationEngine\LapiRemediation` object too. ```php use MyNameSpace\MyCustomBouncer; use CrowdSec\RemediationEngine\LapiRemediation; use CrowdSec\LapiClient\Bouncer as BouncerClient; use CrowdSec\RemediationEngine\CacheStorage\PhpFiles; $configs = [...]; $client = new BouncerClient($configs);// @see AbstractBouncer::handleClient method for a basic client creation $cacheStorage = new PhpFiles($configs);// @see AbstractBouncer::handleCache method for a basic cache storage creation $remediationEngine = new LapiRemediation($configs, $client, $cacheStorage); $bouncer = new MyCustomBouncer($configs, $remediationEngine); $bouncer->run(); ``` ### Test your bouncer To test your bouncer, you could add decision to ban your own IP for 5 minutes for example: ```bash cscli decisions add --ip <YOUR_IP> --duration 5m --type ban ``` You can also test a captcha: ```bash cscli decisions delete --all # be careful with this command! cscli decisions add --ip <YOUR_IP> --duration 15m --type captcha ``` To go further and learn how to include this library in your project, you should follow the [`DEVELOPER GUIDE`](DEVELOPER.md). ## Configurations The first parameter of the `AbstractBouncer` class constructor method is an array of settings. Below is the list of available settings: ### Bouncer behavior - `bouncing_level`: Select from `bouncing_disabled`, `normal_bouncing` or `flex_bouncing`. Choose if you want to apply CrowdSec directives (Normal bouncing) or be more permissive (Flex bouncing). With the `Flex mode`, it is impossible to accidentally block access to your site to people who don’t deserve it. This mode makes it possible to never ban an IP but only to offer a captcha, in the worst-case scenario. - `fallback_remediation`: Select from `bypass` (minimum remediation), `captcha` or `ban` (maximum remediation). Default to 'captcha'. Handle unknown remediations as. - `trust_ip_forward_array`: If you use a CDN, a reverse proxy or a load balancer, set an array of comparable IPs arrays: (example: `[['001.002.003.004', '001.002.003.004'], ['005.006.007.008', '005.006.007.008']]` for CDNs with IPs `1.2.3.4` and `5.6.7.8`). For other IPs, the bouncer will not trust the X-Forwarded-For header. - `excluded_uris`: array of URIs that will not be bounced. - `stream_mode`: true to enable stream mode, false to enable the live mode. Default to false. By default, the `live mode` is enabled. The first time a stranger connects to your website, this mode means that the IP will be checked directly by the CrowdSec API. The rest of your user’s browsing will be even more transparent thanks to the fully customizable cache system. But you can also activate the `stream mode`. This mode allows you to constantly feed the bouncer with the malicious IP list via a background task (CRON), making it to be even faster when checking the IP of your visitors. Besides, if your site has a lot of unique visitors at the same time, this will not influence the traffic to the API of your CrowdSec instance. ### Local API Connection - `auth_type`: Select from `api_key` and `tls`. Choose if you want to use an API-KEY or a TLS (pki) authentification. TLS authentication is only available if you use CrowdSec agent with a version superior to 1.4.0. - `api_key`: Key generated by the cscli (CrowdSec cli) command like `cscli bouncers add bouncer-php-library`. Only required if you choose `api_key` as `auth_type`. - `tls_cert_path`: absolute path to the bouncer certificate (e.g. pem file). Only required if you choose `tls` as `auth_type`. **Make sure this path is not publicly accessible.** [See security note below](#security-note). - `tls_key_path`: Absolute path to the bouncer key (e.g. pem file). Only required if you choose `tls` as `auth_type`. **Make sure this path is not publicly accessible.** [See security note below](#security-note). - `tls_verify_peer`: This option determines whether request handler verifies the authenticity of the peer's certificate. Only required if you choose `tls` as `auth_type`. When negotiating a TLS or SSL connection, the server sends a certificate indicating its identity. If `tls_verify_peer` is set to true, request handler verifies whether the certificate is authentic. This trust is based on a chain of digital signatures, rooted in certification authority (CA) certificates you supply using the `tls_ca_cert_path` setting below. - `tls_ca_cert_path`: Absolute path to the CA used to process peer verification. Only required if you choose `tls` as `auth_type` and `tls_verify_peer` is set to true. **Make sure this path is not publicly accessible.** [See security note below](#security-note). - `api_url`: Define the URL to your Local API server, default to `http://localhost:8080`. - `api_timeout`: In seconds. The timeout when calling Local API. Default to 120 sec. If set to a negative value, timeout will be unlimited. ### Cache - `fs_cache_path`: Will be used only if you choose PHP file cache as cache storage. **Make sure this path is not publicly accessible.** [See security note below](#security-note). - `redis_dsn`: Will be used only if you choose Redis cache as cache storage. - `memcached_dsn`: Will be used only if you choose Memcached as cache storage. - `clean_ip_cache_duration`: Set the duration we keep in cache the fact that an IP is clean. In seconds. Defaults to 5. - `bad_ip_cache_duration`: Set the duration we keep in cache the fact that an IP is bad. In seconds. Defaults to 20. - `captcha_cache_duration`: Set the duration we keep in cache the captcha flow variables for an IP. In seconds. Defaults to 86400.. In seconds. Defaults to 20. ### Geolocation - `geolocation`: Settings for geolocation remediation (i.e. country based remediation). - `geolocation[enabled]`: true to enable remediation based on country. Default to false. - `geolocation[type]`: Geolocation system. Only 'maxmind' is available for the moment. Default to `maxmind`. - `geolocation[cache_duration]`: This setting will be used to set the lifetime (in seconds) of a cached country associated to an IP. The purpose is to avoid multiple call to the geolocation system (e.g. maxmind database). Default to 86400. Set 0 to disable caching. - `geolocation[maxmind]`: MaxMind settings. - `geolocation[maxmind][database_type]`: Select from `country` or `city`. Default to `country`. These are the two available MaxMind database types. - `geolocation[maxmind][database_path]`: Absolute path to the MaxMind database (e.g. mmdb file) **Make sure this path is not publicly accessible.** [See security note below](#security-note). ### Captcha and ban wall settings - `hide_mentions`: true to hide CrowdSec mentions on ban and captcha walls. - `custom_css`: Custom css directives for ban and captcha walls - `color`: Array of settings for ban and captcha walls colors. - `color[text][primary]` - `color[text][secondary]` - `color[text][button]` - `color[text][error_message]` - `color[background][page]` - `color[background][container]` - `color[background][button]` - `color[background][button_hover]` - `text`: Array of settings for ban and captcha walls texts. - `text[captcha_wall][tab_title]` - `text[captcha_wall][title]` - `text[captcha_wall][subtitle]` - `text[captcha_wall][refresh_image_link]` - `text[captcha_wall][captcha_placeholder]` - `text[captcha_wall][send_button]` - `text[captcha_wall][error_message]` - `text[captcha_wall][footer]` - `text[ban_wall][tab_title]` - `text[ban_wall][title]` - `text[ban_wall][subtitle]` - `text[ban_wall][footer]` ### Debug - `debug_mode`: `true` to enable verbose debug log. Default to `false`. - `disable_prod_log`: `true` to disable prod log. Default to `false`. - `log_directory_path`: Absolute path to store log files. **Make sure this path is not publicly accessible.** [See security note below](#security-note). - `display_errors`: true to stop the process and display errors on browser if any. - `forced_test_ip`: Only for test or debug purpose. Default to empty. If not empty, it will be used instead of the real remote ip. - `forced_test_forwarded_ip`: Only for test or debug purpose. Default to empty. If not empty, it will be used instead of the real forwarded ip. If set to `no_forward`, the x-forwarded-for mechanism will not be used at all. ### Security note Some files should not be publicly accessible because they may contain sensitive data: - Log files - Cache files of the File system cache - TLS authentication files - Geolocation database files If you define publicly accessible folders in the settings, be sure to add rules to deny access to these files. In the following example, we will suppose that you use a folder `crowdsec` with sub-folders `logs`, `cache`, `tls` and `geolocation`. If you are using Nginx, you could use the following snippet to modify your website configuration file: ```nginx server { ... ... ... # Deny all attempts to access some folders of the crowdsec bouncer lib location ~ /crowdsec/(logs|cache|tls|geolocation) { deny all; } ... ... } ``` If you are using Apache, you could add this kind of directive in a `.htaccess` file: ```htaccess Redirectmatch 403 crowdsec/logs/ Redirectmatch 403 crowdsec/cache/ Redirectmatch 403 crowdsec/tls/ Redirectmatch 403 crowdsec/geolocation/ ``` **N.B.:** - There is no need to protect the `cache` folder if you are using Redis or Memcached cache systems. - There is no need to protect the `logs` folder if you disable debug and prod logging. - There is no need to protect the `tls` folder if you use Bouncer API key authentication type. - There is no need to protect the `geolocation` folder if you don't use the geolocation feature. ## Other ready to use PHP bouncers To have a more concrete idea on how to develop a bouncer from this library, you may look at the following bouncers : - [CrowdSec Bouncer extension for Magento 2](https://github.com/crowdsecurity/cs-magento-bouncer) - [CrowdSec Bouncer plugin for WordPress ](https://github.com/crowdsecurity/cs-wordpress-bouncer) - [CrowdSec Standalone Bouncer ](https://github.com/crowdsecurity/cs-standalone-php-bouncer) <file_sep>/README.md ![CrowdSec Logo](https://raw.githubusercontent.com/crowdsecurity/php-cs-bouncer/main/docs/images/logo_crowdsec.png) # CrowdSec Bouncer PHP library > The official PHP bouncer library for the CrowdSec LAPI ![project is maintained](https://img.shields.io/maintenance/yes/2023.svg) ![Version](https://img.shields.io/github/v/release/crowdsecurity/php-cs-bouncer?include_prereleases) [![Quality Gate Status](https://sonarcloud.io/api/project_badges/measure?project=crowdsecurity_php-cs-bouncer&metric=alert_status)](https://sonarcloud.io/dashboard?id=crowdsecurity_php-cs-bouncer) [![Test suite](https://github.com/crowdsecurity/php-cs-bouncer/actions/workflows/test-suite.yml/badge.svg)](https://github.com/crowdsecurity/php-cs-bouncer/actions/workflows/test-suite.yml) [![Coding standards](https://github.com/crowdsecurity/php-cs-bouncer/actions/workflows/coding-standards.yml/badge.svg)](https://github.com/crowdsecurity/php-cs-bouncer/actions/workflows/coding-standards.yml) ![Licence](https://img.shields.io/github/license/crowdsecurity/php-cs-bouncer) :books: <a href="https://doc.crowdsec.net">Documentation</a> :diamond_shape_with_a_dot_inside: <a href="https://hub.crowdsec.net">Hub</a> :speech_balloon: <a href="https://discourse.crowdsec.net">Discourse Forum</a> ## Overview This library allows you to create CrowdSec bouncers for PHP applications or frameworks like e-commerce, blog or other exposed applications. ## Usage See [User Guide](https://github.com/crowdsecurity/php-cs-bouncer/blob/main/docs/USER_GUIDE.md) ## Installation See [Installation Guide](https://github.com/crowdsecurity/php-cs-bouncer/blob/main/docs/INSTALLATION_GUIDE.md) ## Technical notes See [Technical notes](https://github.com/crowdsecurity/php-cs-bouncer/blob/main/docs/TECHNICAL_NOTES.md) ## Developer guide See [Developer guide](https://github.com/crowdsecurity/php-cs-bouncer/blob/main/docs/DEVELOPER.md) ## License [MIT](https://github.com/crowdsecurity/php-cs-bouncer/blob/main/LICENSE) <file_sep>/docs/TECHNICAL_NOTES.md ![CrowdSec Logo](images/logo_crowdsec.png) # CrowdSec Bouncer PHP library ## Technical notes <!-- START doctoc generated TOC please keep comment here to allow auto update --> <!-- DON'T EDIT THIS SECTION, INSTEAD RE-RUN doctoc TO UPDATE --> **Table of Contents** - [Why use *Symfony/Cache* and *Symfony/Config* component?](#why-use-symfonycache-and-symfonyconfig-component) - [Why not using Guzzle?](#why-not-using-guzzle) - [Why not using Swagger Codegen?](#why-not-using-swagger-codegen) - [Which PHP compatibility matrix?](#which-php-compatibility-matrix) - [Why not PHP 5.6?](#why-not-php-56) - [Why not 7.0.x nor 7.1.x ?](#why-not-70x-nor-71x-) - [Memcached and PHP 8.x](#memcached-and-php-8x) <!-- END doctoc generated TOC please keep comment here to allow auto update --> We explain here each important technical decision used to design this library. ## Why use *Symfony/Cache* and *Symfony/Config* component? The Cache component is compatible with many cache systems. The Config component provides several classes to help you find, load, combine, fill and validate configuration values of any kind, whatever their source may be (YAML, XML, INI files, or for instance a database). A great job done by this library, tested and maintained under LTS versions. This library is tested and maintained under LTS versions. ## Why not using Guzzle? The last Guzzle versions remove the User-Agent to prevent risks. Since LAPI or CAPI need a valid User-Agent, we can not use Guzzle to request CAPI/LAPI. ## Why not using Swagger Codegen? We were not able to use this client with ease ex: impossible to get JSON data, it seems there is a bug with unserialization, we received an empty array. ## Which PHP compatibility matrix? ### Why not PHP 5.6? Because this PHP version is no more supported since December 2018 (not even a security fix). Also, a lot of libraries are no more compatible with this version. We don't want to use an older version of these libraries because Composer can only install one version of each extension/package. So, being compatible with this old PHP version means to be not compatible with projects using a new version of these libraries. ### Why not 7.0.x nor 7.1.x ? These PHP versions are not anymore maintained for security fixes since 2019. We encourage you a lot to upgrade your PHP version. You can view the [full list of PHP versions lifecycle](https://www.php.net/supported-versions.php). To get a robust library and not provide security bug unmaintained, we use [components](https://packagist.org/packages/symfony/cache#v3.4.47) under [LTS versioning](https://symfony.com/releases/3.4). The oldest PHP version compatible with these libraries is PHP 7.2.x. ### Memcached and PHP 8.x In order to use Memcached with a PHP 8.x set up, you must have an installed version of the memcached php extension > 3.1.5. To check what is your current version, you could run : `php -r "echo phpversion('memcached');"` <file_sep>/src/Template.php <?php declare(strict_types=1); namespace CrowdSecBouncer; use Twig\Environment; use Twig\Error\LoaderError; use Twig\Error\RuntimeError; use Twig\Error\SyntaxError; use Twig\Loader\FilesystemLoader; use Twig\TemplateWrapper; /** * The template engine. * * @author CrowdSec team * * @see https://crowdsec.net CrowdSec Official Website * * @copyright Copyright (c) 2020+ CrowdSec * @license MIT License */ class Template { /** @var TemplateWrapper */ private $template; /** * @throws LoaderError * @throws RuntimeError * @throws SyntaxError */ public function __construct(string $path, string $templatesDir = Constants::TEMPLATES_DIR, array $options = []) { $loader = new FilesystemLoader($templatesDir); $env = new Environment($loader, $options); $this->template = $env->load($path); } public function render(array $config = []): string { return $this->template->render(['config' => $config]); } } <file_sep>/tests/Integration/TestHelpers.php <?php declare(strict_types=1); namespace CrowdSecBouncer\Tests\Integration; use CrowdSecBouncer\Constants; use Monolog\Formatter\LineFormatter; use Monolog\Handler\StreamHandler; use Monolog\Logger; use Symfony\Component\Cache\Exception\CacheException; class TestHelpers { public const BAD_IP = '1.2.3.4'; public const CLEAN_IP = '2.3.4.5'; public const NEWLY_BAD_IP = '3.4.5.6'; public const IP_RANGE = '24'; public const LARGE_IPV4_RANGE = '23'; public const BAD_IPV6 = '2001:0db8:85a3:0000:0000:8a2e:0370:7334'; public const IPV6_RANGE = '64'; public const JAPAN = 'JP'; public const IP_JAPAN = '192.168.3.11'; public const IP_FRANCE = '172.16.58.3'; public const PHP_FILES_CACHE_ADAPTER_DIR = __DIR__ . '/../var/phpFiles.cache'; public const LOG_LEVEL = Logger::ERROR; // set to Logger::DEBUG to get high verbosity public static function createLogger(): Logger { $log = new Logger('TESTS'); $handler = new StreamHandler('php://stdout', self::LOG_LEVEL); $handler->setFormatter(new LineFormatter("%datetime%|%level%|%context%\n")); $log->pushHandler($handler); return $log; } /** * @throws ErrorException * @throws CacheException */ public static function cacheAdapterConfigProvider(): array { return [ 'PhpFilesAdapter' => [Constants::CACHE_SYSTEM_PHPFS, 'PhpFilesAdapter'], 'RedisAdapter' => [Constants::CACHE_SYSTEM_REDIS, 'RedisAdapter'], 'MemcachedAdapter' => [Constants::CACHE_SYSTEM_MEMCACHED, 'MemcachedAdapter'], ]; } public static function maxmindConfigProvider(): array { return [ 'country database' => [[ 'database_type' => 'country', 'database_path' => __DIR__ . '/../GeoLite2-Country.mmdb', ]], 'city database' => [[ 'database_type' => 'city', 'database_path' => __DIR__ . '/../GeoLite2-City.mmdb', ]], ]; } public static function getLapiUrl(): string { return getenv('LAPI_URL'); } public static function getBouncerKey(): string { if ($bouncerKey = getenv('BOUNCER_KEY')) { return $bouncerKey; } return ''; } } <file_sep>/CHANGELOG.md # Changelog All notable changes to this project will be documented in this file. The format is based on [Keep a Changelog](https://keepachangelog.com/en/) and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). ## SemVer public API The [public API](https://semver.org/spec/v2.0.0.html#spec-item-1) of this library consists of all public or protected methods, properties and constants belonging to the `src` folder. --- ## [2.0.0](https://github.com/crowdsecurity/php-cs-bouncer/releases/tag/v2.0.0) - 2023-04-13 [_Compare with previous release_](https://github.com/crowdsecurity/php-cs-bouncer/compare/v1.4.0...v2.0.0) ### Changed - Update `gregwar/captcha` from `1.1.9` to `1.2.0` and remove some override fixes ### Removed - Remove all code about standalone bouncer --- ## [1.4.0](https://github.com/crowdsecurity/php-cs-bouncer/releases/tag/v1.4.0) - 2023-03-30 [_Compare with previous release_](https://github.com/crowdsecurity/php-cs-bouncer/compare/v1.3.0...v1.4.0) ### Changed - Do not rotate log files of standalone bouncer --- ## [1.3.0](https://github.com/crowdsecurity/php-cs-bouncer/releases/tag/v1.3.0) - 2023-03-24 [_Compare with previous release_](https://github.com/crowdsecurity/php-cs-bouncer/compare/v1.2.0...v1.3.0) ### Changed - Use `crowdsec/remediation-engine` `^3.1.1` instead of `^3.0.0` - Use Redis and PhpFiles cache without cache tags --- ## [1.2.0](https://github.com/crowdsecurity/php-cs-bouncer/releases/tag/v1.2.0) - 2023-03-09 [_Compare with previous release_](https://github.com/crowdsecurity/php-cs-bouncer/compare/v1.1.1...v1.2.0) ### Changed - Use `crowdsec/remediation-engine` `^3.0.0` instead of `^2.0.0` ### Added - Add a script to prune cache with a cron job (Standalone bouncer) --- ## [1.1.1](https://github.com/crowdsecurity/php-cs-bouncer/releases/tag/v1.1.1) - 2023-02-16 [_Compare with previous release_](https://github.com/crowdsecurity/php-cs-bouncer/compare/v1.1.0...v1.1.1) ### Fixed - Fix log messages for captcha remediation --- ## [1.1.0](https://github.com/crowdsecurity/php-cs-bouncer/releases/tag/v1.1.0) - 2023-02-16 [_Compare with previous release_](https://github.com/crowdsecurity/php-cs-bouncer/compare/v1.0.1...v1.1.0) ### Changed - Add more log messages during bouncing process --- ## [1.0.1](https://github.com/crowdsecurity/php-cs-bouncer/releases/tag/v1.0.1) - 2023-02-10 [_Compare with previous release_](https://github.com/crowdsecurity/php-cs-bouncer/compare/v1.0.0...v1.0.1) ### Fixed - Update `AbstractBouncer::testCacheConnection` method to throw an exception for Memcached if necessary --- ## [1.0.0](https://github.com/crowdsecurity/php-cs-bouncer/releases/tag/v1.0.0) - 2023-02-03 [_Compare with previous release_](https://github.com/crowdsecurity/php-cs-bouncer/compare/v0.36.0...v1.0.0) ### Changed - Change version to `1.0.0`: first stable release - Update `crowdsec/remediation-engine` to a new major version [2.0.0](https://github.com/crowdsecurity/php-remediation-engine/releases/tag/v2.0.0) - Use `crowdsec/common` [package](https://github.com/crowdsecurity/php-common) as a dependency for code factoring ### Added - Add public API declaration --- ## [0.36.0](https://github.com/crowdsecurity/php-cs-bouncer/releases/tag/v0.36.0) - 2023-01-26 [_Compare with previous release_](https://github.com/crowdsecurity/php-cs-bouncer/compare/v0.35.0...v0.36.0) ### Changed - *Breaking changes*: All the code has been refactored to use `crowdsec/remediation-engine` package: - Lot of public methods have been deleted or replaced by others - A bouncer should now extend an `AbstractBouncer` class and implements some abstract methods - Some settings names have been changed --- ## [0.35.0](https://github.com/crowdsecurity/php-cs-bouncer/releases/tag/v0.35.0) - 2022-12-16 [_Compare with previous release_](https://github.com/crowdsecurity/php-cs-bouncer/compare/v0.34.0...v0.35.0) ### Changed - Set default timeout to 120 and allow negative value for unlimited timeout --- ## [0.34.0](https://github.com/crowdsecurity/php-cs-bouncer/releases/tag/v0.34.0) - 2022-11-24 [_Compare with previous release_](https://github.com/crowdsecurity/php-cs-bouncer/compare/v0.33.0...v0.34.0) ### Changed - Do not cache bypass decision in stream mode - Replace unauthorized chars by underscore `_` in cache key ### Added - Add compatibility with PHP 8.2 ### Fixed - Fix decision duration parsing when it uses milliseconds --- ## [0.33.0](https://github.com/crowdsecurity/php-cs-bouncer/releases/tag/v0.33.0) - 2022-11-10 [_Compare with previous release_](https://github.com/crowdsecurity/php-cs-bouncer/compare/v0.32.0...v0.33.0) ### Changed - Do not use tags for `memcached` as it is discouraged ### Fixed - In stream mode, a clean IP decision (`bypass`) was not cached at all. The decision is now cached for ten years as expected --- ## [0.32.0](https://github.com/crowdsecurity/php-cs-bouncer/releases/tag/v0.32.0) - 2022-09-29 [_Compare with previous release_](https://github.com/crowdsecurity/php-cs-bouncer/compare/v0.31.0...v0.32.0) ### Changed - Refactor for coding standards (PHPMD, PHPCS) --- ## [0.31.0](https://github.com/crowdsecurity/php-cs-bouncer/releases/tag/v0.31.0) - 2022-09-23 [_Compare with previous release_](https://github.com/crowdsecurity/php-cs-bouncer/compare/v0.30.0...v0.31.0) ### Changed - Use Twig as template engine for ban and captcha walls --- ## [0.30.0](https://github.com/crowdsecurity/php-cs-bouncer/releases/tag/v0.30.0) - 2022-09-22 [_Compare with previous release_](https://github.com/crowdsecurity/php-cs-bouncer/compare/v0.29.0...v0.30.0) ### Changed - Update `symfony/cache` and `symfony/config` dependencies requirement --- ## [0.29.0](https://github.com/crowdsecurity/php-cs-bouncer/releases/tag/v0.29.0) - 2022-08-11 [_Compare with previous release_](https://github.com/crowdsecurity/php-cs-bouncer/compare/v0.28.0...v0.29.0) ### Added - Add TLS authentication feature --- ## [0.28.0](https://github.com/crowdsecurity/php-cs-bouncer/releases/tag/v0.28.0) - 2022-08-04 [_Compare with previous release_](https://github.com/crowdsecurity/php-cs-bouncer/compare/v0.27.0...v0.28.0) ### Changed - *Breaking change*: Rename `ClientAbstract` class to `AbstractClient` - Hide `api_key` in log ### Added - Add `disable_prod_log` configuration --- ## [0.27.0](https://github.com/crowdsecurity/php-cs-bouncer/releases/tag/v0.27.0) - 2022-07-29 [_Compare with previous release_](https://github.com/crowdsecurity/php-cs-bouncer/compare/v0.26.0...v0.27.0) ### Changed - *Breaking change*: Modify `getBouncerInstance` and `init` signatures ### Fixed - Fix wrongly formatted range scoped decision retrieving - Fix cache updated decisions count --- ## [0.26.0](https://github.com/crowdsecurity/php-cs-bouncer/releases/tag/v0.26.0) - 2022-07-28 [_Compare with previous release_](https://github.com/crowdsecurity/php-cs-bouncer/compare/v0.25.0...v0.26.0) ### Changed - *Breaking change*: Modify all constructors (`Bouncer`, `ApiCache`, `ApiClient`, `RestClient`) to use only configurations and logger as parameters - Use `shouldBounceCurrentIp` method of Standalone before bouncer instantiation - *Breaking change*: Modify `initLogger` method --- ## [0.25.0](https://github.com/crowdsecurity/php-cs-bouncer/releases/tag/v0.25.0) - 2022-07-22 [_Compare with previous release_](https://github.com/crowdsecurity/php-cs-bouncer/compare/v0.24.0...v0.25.0) ### Added - Add a `use_curl` setting to make LAPI rest requests with `cURL` instead of `file_get_contents` --- ## [0.24.0](https://github.com/crowdsecurity/php-cs-bouncer/releases/tag/v0.24.0) - 2022-07-08 [_Compare with previous release_](https://github.com/crowdsecurity/php-cs-bouncer/compare/v0.23.0...v0.24.0) ### Added - Add a `configs` attribute to Bouncer class --- ## [0.23.0](https://github.com/crowdsecurity/php-cs-bouncer/releases/tag/v0.23.0) - 2022-07-07 [_Compare with previous release_](https://github.com/crowdsecurity/php-cs-bouncer/compare/v0.22.1...v0.23.0) ### Added - Add test configuration to mock IPs and proxy behavior --- ## [0.22.1](https://github.com/crowdsecurity/php-cs-bouncer/releases/tag/v0.22.1) - 2022-06-03 [_Compare with previous release_](https://github.com/crowdsecurity/php-cs-bouncer/compare/v0.22.0...v0.22.1) ### Fixed - Handle custom error handler for Memcached tag aware adapter --- ## [0.22.0](https://github.com/crowdsecurity/php-cs-bouncer/releases/tag/v0.22.0) - 2022-06-02 [_Compare with previous release_](https://github.com/crowdsecurity/php-cs-bouncer/compare/v0.21.0...v0.22.0) ### Added - Add configurations for captcha and geolocation variables cache duration ### Changed - *Breaking change*: Use cache instead of session to store captcha and geolocation variables - *Breaking change*: Use symfony cache tag adapter - Change `geolocation/save_in_session` setting into `geolocation/save_result` ### Fixed - Fix deleted decision count during cache update --- ## [0.21.0](https://github.com/crowdsecurity/php-cs-bouncer/releases/tag/v0.21.0) - 2022-04-15 [_Compare with previous release_](https://github.com/crowdsecurity/php-cs-bouncer/compare/v0.20.1...v0.21.0) ### Changed - Change allowed versions of `symfony/cache` package --- ## [0.20.1](https://github.com/crowdsecurity/php-cs-bouncer/releases/tag/v0.20.1) - 2022-04-07 [_Compare with previous release_](https://github.com/crowdsecurity/php-cs-bouncer/compare/v0.20.0...v0.20.1) ### Added - Handle old lib version (`< 0.14.0`) settings values retro-compatibility for Standalone bouncer ### Fixed - Fix `AbstractBounce:displayCaptchaWall` function --- ## [0.20.0](https://github.com/crowdsecurity/php-cs-bouncer/releases/tag/v0.20.0) - 2022-03-31 [_Compare with previous release_](https://github.com/crowdsecurity/php-cs-bouncer/compare/v0.19.0...v0.20.0) ### Changed - Require a minimum of 1 for `clean_ip_cache_duration` and `bad_ip_cache_duration` settings - Do not use session for geolocation if `save_in_session` setting is not true. --- ## [0.19.0](https://github.com/crowdsecurity/php-cs-bouncer/releases/tag/v0.19.0) - 2022-03-24 [_Compare with previous release_](https://github.com/crowdsecurity/php-cs-bouncer/compare/v0.18.0...v0.19.0) ### Added - Add `excluded_uris` configuration to exclude some uris (was hardcoded to `/favicon.ico`) ### Changed - Change the redirection after captcha resolution to `/` (was `$_SERVER['REQUEST_URI']'`) ### Fixed - Fix Standalone bouncer session handling --- ## [0.18.0](https://github.com/crowdsecurity/php-cs-bouncer/releases/tag/v0.18.0) - 2022-03-18 [_Compare with previous release_](https://github.com/crowdsecurity/php-cs-bouncer/compare/v0.17.1...v0.18.0) ### Changed - *Breaking change*: Change `trust_ip_forward_array` symfony configuration node to an array of array. --- ## [0.17.1](https://github.com/crowdsecurity/php-cs-bouncer/releases/tag/v0.17.1) - 2022-03-17 [_Compare with previous release_](https://github.com/crowdsecurity/php-cs-bouncer/compare/v0.17.0...v0.17.1) ### Removed - Remove testing scripts for quality gate test --- ## [0.17.0](https://github.com/crowdsecurity/php-cs-bouncer/releases/tag/v0.17.0) - 2022-03-17 [_Compare with previous release_](https://github.com/crowdsecurity/php-cs-bouncer/compare/v0.16.0...v0.17.0) ### Changed - *Breaking change*: Refactor some logic of important methods (`init`, `run`, `safelyBounce`, `getBouncerInstance`) - *Breaking change*: Change the configurations' verification by using `symfony/config` logic whenever it is possible - *Breaking change*: Change scripts path, name and content (specifically auto-prepend-file' scripts and settings) - *Breaking change*: Change `IBounce` interface - *Breaking change*: Rename `StandAloneBounce` class by `StandaloneBounce` - Rewrite documentations ### Fixed - Fix `api_timeout` configuration ### Removed - Remove all unmaintained test and development docker files, sh scripts and associated documentation - Remove `StandaloneBounce::isConfigValid` method as all is already checked --- ## [0.16.0](https://github.com/crowdsecurity/php-cs-bouncer/releases/tag/v0.16.0) - 2022-03-10 [_Compare with previous release_](https://github.com/crowdsecurity/php-cs-bouncer/compare/v0.15.0...v0.16.0) ### Added - Add geolocation feature to get remediation from `Country` scoped decisions (using MaxMind databases) - Add end-to-end tests GitHub action - Add GitHub action to check links in markdown and update TOC ### Changed - *Breaking change*: Remove `live_mode` occurrences and use `stream_mode` instead - Change PHP scripts for testing examples (auto-prepend, cron) - Update docs ### Fixed - Fix debug log in `no-dev` environment - Fix empty logs in Unit Tests --- ## [0.15.0](https://github.com/crowdsecurity/php-cs-bouncer/releases/tag/v0.15.0) - 2022-02-24 [_Compare with previous release_](https://github.com/crowdsecurity/php-cs-bouncer/compare/v0.14.0...v0.15.0) ### Added - Add tests for PHP 8.1 (memcached is excluded) - Add GitHub action for Release process - Add `CHANGELOG.md` ### Changed - Use `BouncerException` for some specific errors ### Fixed - Fix auto-prepend script: set `debug_mode` and `display_errors` values before bouncer init - Fix `gregwar/captcha` for PHP 8.1 - Fix BouncerException arguments in `set_error_handler` method ### Removed - Remove `composer.lock` file --- ## [0.14.0](https://github.com/crowdsecurity/php-cs-bouncer/releases/tag/v0.14.0) - 2021-11-18 [_Compare with previous release_](https://github.com/crowdsecurity/php-cs-bouncer/compare/v0.13.3...v0.14.0) ### Changed - *Breaking change*: Fix typo in constant name (`boucing`=> `bouncing`) - Allow older versions of symfony config and monolog - Split debug logic in 2 : debug and display - Redirect if captcha is resolved - Update doc and scripts --- ## [0.13.3](https://github.com/crowdsecurity/php-cs-bouncer/releases/tag/v0.13.3) - 2021-09-21 [_Compare with previous release_](https://github.com/crowdsecurity/php-cs-bouncer/compare/v0.13.2...v0.13.3) ### Fixed - Fix session handling with standalone library --- ## [0.13.2](https://github.com/crowdsecurity/php-cs-bouncer/releases/tag/v0.13.2) - 2021-08-24 [_Compare with previous release_](https://github.com/crowdsecurity/php-cs-bouncer/compare/v0.13.1...v0.13.2) ### Added - Handle invalid ip format --- ## [0.13.1](https://github.com/crowdsecurity/php-cs-bouncer/releases/tag/v0.13.1) - 2021-07-01 [_Compare with previous release_](https://github.com/crowdsecurity/php-cs-bouncer/compare/v0.13.0...v0.13.1) ### Changed - Close php session after bouncing --- ## [0.13.0](https://github.com/crowdsecurity/php-cs-bouncer/releases/tag/v0.13.0) - 2021-06-24 [_Compare with previous release_](https://github.com/crowdsecurity/php-cs-bouncer/compare/v0.12.0...v0.13.0) ### Fixed - Fix standalone mode --- ## [0.12.0](https://github.com/crowdsecurity/php-cs-bouncer/releases/tag/v0.12.0) - 2021-06-24 [_Compare with previous release_](https://github.com/crowdsecurity/php-cs-bouncer/compare/v0.11.0...v0.12.0) ### Added - Add standalone mode --- ## [0.11.0](https://github.com/crowdsecurity/php-cs-bouncer/releases/tag/v0.11.0) - 2021-06-24 [_Compare with previous release_](https://github.com/crowdsecurity/php-cs-bouncer/compare/v0.10.0...v0.11.0) ### Added - Add a `Bounce` class to simplify specific implementations - Add a `Standalone` implementation of the `Bounce` class --- ## [0.10.0](https://github.com/crowdsecurity/php-cs-bouncer/releases/tag/v0.10.0) - 2021-01-23 [_Compare with previous release_](https://github.com/crowdsecurity/php-cs-bouncer/compare/v0.9.0...v0.10.0) ### Added - Add Ipv6 support --- ## [0.9.0](https://github.com/crowdsecurity/php-cs-bouncer/releases/tag/v0.9.0) - 2021-01-13 [_Compare with previous release_](https://github.com/crowdsecurity/php-cs-bouncer/compare/v0.8.6...v0.9.0) ### Added - Add custom remediation templates --- ## [0.8.6](https://github.com/crowdsecurity/php-cs-bouncer/releases/tag/v0.8.6) - 2021-01-05 [_Compare with previous release_](https://github.com/crowdsecurity/php-cs-bouncer/compare/v0.8.5...v0.8.6) ### Fixed - Fix version bump --- ## [0.8.5](https://github.com/crowdsecurity/php-cs-bouncer/releases/tag/v0.8.5) - 2021-01-05 [_Compare with previous release_](https://github.com/crowdsecurity/php-cs-bouncer/compare/v0.8.4...v0.8.5) ### Fixed - Fix memcached edge case with long duration cache (unwanted int to float conversion) --- ## [0.8.4](https://github.com/crowdsecurity/php-cs-bouncer/releases/tag/v0.8.4) - 2020-12-26 [_Compare with previous release_](https://github.com/crowdsecurity/php-cs-bouncer/compare/v0.8.3...v0.8.4) ### Fixed - Fix fallback remediation --- ## [0.8.3](https://github.com/crowdsecurity/php-cs-bouncer/releases/tag/v0.8.3) - 2020-12-24 [_Compare with previous release_](https://github.com/crowdsecurity/php-cs-bouncer/compare/v0.8.2...v0.8.3) ### Changed - Do not set expiration limits in stream mode --- ## [0.8.2](https://github.com/crowdsecurity/php-cs-bouncer/releases/tag/v0.8.2) - 2020-12-23 [_Compare with previous release_](https://github.com/crowdsecurity/php-cs-bouncer/compare/v0.8.1...v0.8.2) ### Fixed - Fix release process --- ## [0.8.1](https://github.com/crowdsecurity/php-cs-bouncer/releases/tag/v0.8.1) - 2020-12-22 [_Compare with previous release_](https://github.com/crowdsecurity/php-cs-bouncer/compare/v0.8.0...v0.8.1) ### Fixed - Fix release process --- ## [0.8.0](https://github.com/crowdsecurity/php-cs-bouncer/releases/tag/v0.8.0) - 2020-12-22 [_Compare with previous release_](https://github.com/crowdsecurity/php-cs-bouncer/compare/v0.7.0...v0.8.0) ### Added - Add redis+memcached test connection --- ## [0.7.0](https://github.com/crowdsecurity/php-cs-bouncer/releases/tag/v0.7.0) - 2020-12-22 [_Compare with previous release_](https://github.com/crowdsecurity/php-cs-bouncer/compare/v0.6.0...v0.7.0) ### Added - Make crowdsec mentions hidable - Add phpcs ### Changed - Update doc - Make a lint pass ### Fixed - Fix fallback remediation --- ## [0.6.0](https://github.com/crowdsecurity/php-cs-bouncer/releases/tag/v0.6.0) - 2020-12-20 [_Compare with previous release_](https://github.com/crowdsecurity/php-cs-bouncer/compare/v0.5.2...v0.6.0) ### Changed - Remove useless dockerfiles --- ## [0.5.2](https://github.com/crowdsecurity/php-cs-bouncer/releases/tag/v0.5.2) - 2020-12-19 [_Compare with previous release_](https://github.com/crowdsecurity/php-cs-bouncer/compare/v0.5.1...v0.5.2) ### Changed - Update docs --- ## [0.5.1](https://github.com/crowdsecurity/php-cs-bouncer/releases/tag/v0.5.1) - 2020-12-19 [_Compare with previous release_](https://github.com/crowdsecurity/php-cs-bouncer/compare/v0.5.0...v0.5.1) ### Changed - Make a lint pass --- ## [0.5.0](https://github.com/crowdsecurity/php-cs-bouncer/releases/tag/v0.5.0) - 2020-12-19 [_Compare with previous release_](https://github.com/crowdsecurity/php-cs-bouncer/compare/v0.4.4...v0.5.0) ### Added - Add cache expiration for bad ips - Include the GregWar Captcha generation lib - Build nice 403 and captcha templates - Log captcha resolutions ### Changed - Use the latest CrowdSec docker image - Use the "context" psr log feature for all logs to allow them to be parsable. - Remove useless predis dependence --- ## [0.4.4](https://github.com/crowdsecurity/php-cs-bouncer/releases/tag/v0.4.4) - 2020-12-15 [_Compare with previous release_](https://github.com/crowdsecurity/php-cs-bouncer/compare/v0.4.3...v0.4.4) ### Changed - Improve logging --- ## [0.4.3](https://github.com/crowdsecurity/php-cs-bouncer/releases/tag/v0.4.3) - 2020-12-13 [_Compare with previous release_](https://github.com/crowdsecurity/php-cs-bouncer/compare/v0.4.2...v0.4.3) ### Changed - Improve logging --- ## [0.4.2](https://github.com/crowdsecurity/php-cs-bouncer/releases/tag/v0.4.2) - 2020-12-12 [_Compare with previous release_](https://github.com/crowdsecurity/php-cs-bouncer/compare/v0.4.1...v0.4.2) ### Fixed - Fix durations bug --- ## [0.4.1](https://github.com/crowdsecurity/php-cs-bouncer/releases/tag/v0.4.1) - 2020-12-12 [_Compare with previous release_](https://github.com/crowdsecurity/php-cs-bouncer/compare/v0.4.0...v0.4.1) ### Added - Use GitHub flow --- ## [0.4.0](https://github.com/crowdsecurity/php-cs-bouncer/releases/tag/v0.4.0) - 2020-12-12 [_Compare with previous release_](https://github.com/crowdsecurity/php-cs-bouncer/compare/v0.3.0...v0.4.0) ### Added - Add release drafter - Reduce cache durations - Add remediation fallback --- ## [0.3.0](https://github.com/crowdsecurity/php-cs-bouncer/releases/tag/v0.3.0) - 2020-12-09 [_Compare with previous release_](https://github.com/crowdsecurity/php-cs-bouncer/compare/v0.2.0...v0.3.0) ### Added - Set PHP Files cache adapter as default - Replace phpdoc template with phpdocmd - Improve documentation add examples and a complete guide. - Auto warmup cache --- ## [0.2.0](https://github.com/crowdsecurity/php-cs-bouncer/releases/tag/v0.2.0) - 2020-12-08 ### Added - Initial release <file_sep>/docs/INSTALLATION_GUIDE.md ![CrowdSec Logo](images/logo_crowdsec.png) # CrowdSec Bouncer PHP library ## Installation Guide <!-- START doctoc generated TOC please keep comment here to allow auto update --> <!-- DON'T EDIT THIS SECTION, INSTEAD RE-RUN doctoc TO UPDATE --> **Table of Contents** - [Requirements](#requirements) - [Installation](#installation) <!-- END doctoc generated TOC please keep comment here to allow auto update --> ## Requirements - PHP >= 7.2.5 - required PHP extensions: `ext-curl`, `ext-gd`, `ext-json`, `ext-mbstring` ## Installation Use `Composer` by simply adding `crowdsec/bouncer` as a dependency: ```shell composer require crowdsec/bouncer ``` <file_sep>/src/Constants.php <?php declare(strict_types=1); namespace CrowdSecBouncer; use CrowdSec\RemediationEngine\Constants as RemConstants; /** * Every constant of the library are set here. * * @author CrowdSec team * * @see https://crowdsec.net CrowdSec Official Website * * @copyright Copyright (c) 2020+ CrowdSec * @license MIT License */ class Constants extends RemConstants { /** @var string The "disabled" bouncing level */ public const BOUNCING_LEVEL_DISABLED = 'bouncing_disabled'; /** @var string The "flex" bouncing level */ public const BOUNCING_LEVEL_FLEX = 'flex_bouncing'; /** @var string The "normal" bouncing level */ public const BOUNCING_LEVEL_NORMAL = 'normal_bouncing'; /** @var int The duration we keep a captcha flow in cache */ public const CACHE_EXPIRATION_FOR_CAPTCHA = 86400; /** @var string The "MEMCACHED" cache system */ public const CACHE_SYSTEM_MEMCACHED = 'memcached'; /** @var string The "PHPFS" cache system */ public const CACHE_SYSTEM_PHPFS = 'phpfs'; /** @var string The "REDIS" cache system */ public const CACHE_SYSTEM_REDIS = 'redis'; /** @var string Cache tag for captcha flow */ public const CACHE_TAG_CAPTCHA = 'captcha'; /** @var string The Default URL of the CrowdSec LAPI */ public const DEFAULT_LAPI_URL = 'http://localhost:8080'; /** @var string Path for html templates folder (e.g. ban and captcha wall) */ public const TEMPLATES_DIR = __DIR__ . '/templates'; /** @var string The last version of this library */ public const VERSION = 'v2.0.0'; /** @var string The "disabled" x-forwarded-for setting */ public const X_FORWARDED_DISABLED = 'no_forward'; } <file_sep>/tests/PHPUnitUtil.php <?php declare(strict_types=1); /** * Some helpers for Unit test. * * @author CrowdSec team * * @see https://crowdsec.net CrowdSec Official Website * * @copyright Copyright (c) 2022+ CrowdSec * @license MIT License */ namespace CrowdSecBouncer\Tests; use PHPUnit\Runner\Version; class PHPUnitUtil { public static function callMethod($obj, $name, array $args) { $class = new \ReflectionClass($obj); $method = $class->getMethod($name); $method->setAccessible(true); return $method->invokeArgs($obj, $args); } public static function getPHPUnitVersion(): string { return Version::id(); } public static function assertRegExp($testCase, $pattern, $string, $message = '') { if (version_compare(self::getPHPUnitVersion(), '9.0', '>=')) { $testCase->assertMatchesRegularExpression($pattern, $string, $message); } else { $testCase->assertRegExp($pattern, $string, $message); } } } <file_sep>/tests/Unit/AbstractBouncerTest.php <?php declare(strict_types=1); namespace CrowdSecBouncer\Tests\Unit; /** * Test for abstract bouncer. * * @author CrowdSec team * * @see https://crowdsec.net CrowdSec Official Website * * @copyright Copyright (c) 2022+ CrowdSec * @license MIT License */ use CrowdSec\Common\Logger\FileLog; use CrowdSec\RemediationEngine\LapiRemediation; use CrowdSecBouncer\AbstractBouncer; use CrowdSecBouncer\BouncerException; use CrowdSecBouncer\Constants; use CrowdSecBouncer\Tests\PHPUnitUtil; use org\bovigo\vfs\vfsStream; use PHPUnit\Framework\TestCase; /** * @covers \CrowdSecBouncer\AbstractBouncer::__construct * @covers \CrowdSecBouncer\AbstractBouncer::configure * @covers \CrowdSecBouncer\AbstractBouncer::getConfig * @covers \CrowdSecBouncer\AbstractBouncer::getConfigs * @covers \CrowdSecBouncer\AbstractBouncer::getLogger * @covers \CrowdSecBouncer\AbstractBouncer::getRemediationEngine * @covers \CrowdSecBouncer\AbstractBouncer::handleCache * @covers \CrowdSecBouncer\AbstractBouncer::handleClient * @covers \CrowdSecBouncer\Configuration::addBouncerNodes * @covers \CrowdSecBouncer\Configuration::addCacheNodes * @covers \CrowdSecBouncer\Configuration::addConnectionNodes * @covers \CrowdSecBouncer\Configuration::addDebugNodes * @covers \CrowdSecBouncer\Configuration::addTemplateNodes * @covers \CrowdSecBouncer\Configuration::cleanConfigs * @covers \CrowdSecBouncer\Configuration::getConfigTreeBuilder * @covers \CrowdSecBouncer\AbstractBouncer::shouldNotCheckResolution * @covers \CrowdSecBouncer\AbstractBouncer::bounceCurrentIp * @covers \CrowdSecBouncer\AbstractBouncer::capRemediationLevel * @covers \CrowdSecBouncer\AbstractBouncer::getRemediationForIp * @covers \CrowdSecBouncer\AbstractBouncer::getTrustForwardedIpBoundsList * @covers \CrowdSecBouncer\AbstractBouncer::handleForwardedFor * * @uses \CrowdSecBouncer\AbstractBouncer::handleRemediation * * @covers \CrowdSecBouncer\AbstractBouncer::shouldTrustXforwardedFor * @covers \CrowdSecBouncer\AbstractBouncer::shouldBounceCurrentIp * @covers \CrowdSecBouncer\AbstractBouncer::checkCaptcha * @covers \CrowdSecBouncer\AbstractBouncer::buildCaptchaCouple * @covers \CrowdSecBouncer\Fixes\Gregwar\Captcha\CaptchaBuilder::writePhrase * @covers \CrowdSecBouncer\AbstractBouncer::getCache * @covers \CrowdSecBouncer\AbstractBouncer::getBanHtml * @covers \CrowdSecBouncer\Template::__construct * @covers \CrowdSecBouncer\Template::render * @covers \CrowdSecBouncer\AbstractBouncer::getCaptchaHtml * @covers \CrowdSecBouncer\AbstractBouncer::clearCache * @covers \CrowdSecBouncer\AbstractBouncer::pruneCache * @covers \CrowdSecBouncer\AbstractBouncer::refreshBlocklistCache * @covers \CrowdSecBouncer\AbstractBouncer::testCacheConnection */ final class AbstractBouncerTest extends TestCase { private const EXCLUDED_URI = '/favicon.ico'; /** * @var string */ private $debugFile; /** * @var FileLog */ private $logger; /** * @var string */ private $prodFile; /** * @var vfsStreamDirectory */ private $root; protected $configs = [ // ============================================================================# // Bouncer configs // ============================================================================# 'use_curl' => false, 'debug_mode' => true, 'disable_prod_log' => false, 'log_directory_path' => __DIR__ . '/.logs', 'display_errors' => true, 'forced_test_ip' => '', 'forced_test_forwarded_ip' => '', 'bouncing_level' => Constants::BOUNCING_LEVEL_NORMAL, 'trust_ip_forward_array' => [['005.006.007.008', '005.006.007.008']], 'excluded_uris' => [self::EXCLUDED_URI], 'cache_system' => Constants::CACHE_SYSTEM_PHPFS, 'captcha_cache_duration' => Constants::CACHE_EXPIRATION_FOR_CAPTCHA, 'custom_css' => '', 'hide_mentions' => false, 'color' => [ 'text' => [ 'primary' => 'black', 'secondary' => '#AAA', 'button' => 'white', 'error_message' => '#b90000', ], 'background' => [ 'page' => '#eee', 'container' => 'white', 'button' => '#626365', 'button_hover' => '#333', ], ], 'text' => [ 'captcha_wall' => [ 'tab_title' => 'Oops..', 'title' => 'Hmm, sorry but...', 'subtitle' => 'Please complete the security check.', 'refresh_image_link' => 'refresh image', 'captcha_placeholder' => 'Type here...', 'send_button' => 'CONTINUE', 'error_message' => 'Please try again.', 'footer' => '', ], 'ban_wall' => [ 'tab_title' => 'Oops..', 'title' => '🤭 Oh!', 'subtitle' => 'This page is protected against cyber attacks and your IP has been banned by our system.', 'footer' => '', ], ], // ============================================================================# // Client configs // ============================================================================# 'auth_type' => Constants::AUTH_KEY, 'tls_cert_path' => '', 'tls_key_path' => '', 'tls_verify_peer' => true, 'tls_ca_cert_path' => '', 'api_key' => 'unit-test', 'api_url' => Constants::DEFAULT_LAPI_URL, 'api_timeout' => 1, // ============================================================================# // Remediation engine configs // ============================================================================# 'fallback_remediation' => Constants::REMEDIATION_CAPTCHA, 'ordered_remediations' => [Constants::REMEDIATION_BAN, Constants::REMEDIATION_CAPTCHA], 'fs_cache_path' => __DIR__ . '/.cache', 'redis_dsn' => 'redis://localhost:6379', 'memcached_dsn' => 'memcached://localhost:11211', 'clean_ip_cache_duration' => 1, 'bad_ip_cache_duration' => 1, 'stream_mode' => false, 'geolocation' => [ 'enabled' => false, 'type' => Constants::GEOLOCATION_TYPE_MAXMIND, 'cache_duration' => Constants::CACHE_EXPIRATION_FOR_GEO, 'maxmind' => [ 'database_type' => Constants::MAXMIND_COUNTRY, 'database_path' => '/some/path/GeoLite2-Country.mmdb', ], ], ]; protected function setUp(): void { unset($_SERVER['REMOTE_ADDR']); $this->root = vfsStream::setup('/tmp'); $this->configs['log_directory_path'] = $this->root->url(); $currentDate = date('Y-m-d'); $this->debugFile = 'debug-' . $currentDate . '.log'; $this->prodFile = 'prod-' . $currentDate . '.log'; $this->logger = new FileLog(['log_directory_path' => $this->root->url(), 'debug_mode' => true]); } public function testPrivateAndProtectedMethods() { // shouldNotCheckResolution $configs = $this->configs; $mockRemediation = $this->getMockBuilder(LapiRemediation::class) ->disableOriginalConstructor() ->onlyMethods(['getIpRemediation']) ->getMock(); $bouncer = $this->getMockForAbstractClass(AbstractBouncer::class, [$configs, $mockRemediation], '', true, true, true, ['getHttpMethod', 'getPostedVariable']); $result = PHPUnitUtil::callMethod( $bouncer, 'shouldNotCheckResolution', [['has_to_be_resolved' => false]] ); // has_to_be_resolved = false $this->assertEquals(true, $result); $result = PHPUnitUtil::callMethod( $bouncer, 'shouldNotCheckResolution', [['has_to_be_resolved' => null]] ); // has_to_be_resolved = null $this->assertEquals(true, $result); $bouncer->method('getHttpMethod')->willReturnOnConsecutiveCalls('POST', 'GET'); $bouncer->method('getPostedVariable')->willReturnOnConsecutiveCalls('1'); // has_to_be_resolved = true and POST method and crowdsec_captcha = 1 $result = PHPUnitUtil::callMethod( $bouncer, 'shouldNotCheckResolution', [['has_to_be_resolved' => true]] ); $this->assertEquals(false, $result); // has_to_be_resolved = true and POST method and captcha_variable = null $result = PHPUnitUtil::callMethod( $bouncer, 'shouldNotCheckResolution', [['has_to_be_resolved' => null]] ); $this->assertEquals(true, $result); // has_to_be_resolved = true and GET method $result = PHPUnitUtil::callMethod( $bouncer, 'shouldNotCheckResolution', [['has_to_be_resolved' => true]] ); $this->assertEquals(true, $result); // Classic tests $configs = $this->configs; $mockRemediation = $this->getMockBuilder(LapiRemediation::class) ->disableOriginalConstructor() ->onlyMethods(['getIpRemediation']) ->getMock(); $bouncer = $this->getMockForAbstractClass(AbstractBouncer::class, [$configs, $mockRemediation], '', true, true, true, ['getHttpRequestHeader']); $bouncer->method('getHttpRequestHeader')->willReturnOnConsecutiveCalls('1.2.3.4', '1.2.3.4'); $result = PHPUnitUtil::callMethod( $bouncer, 'handleForwardedFor', ['4.5.6.7', $configs] ); // 4.5.6.7 is not a trusted ip, so the result is passed ip $this->assertEquals('4.5.6.7', $result); $result = PHPUnitUtil::callMethod( $bouncer, 'handleForwardedFor', ['5.6.7.8', $configs] ); // 5.6.7.8 is a trusted ip, so the result is the forwarded ip $this->assertEquals('1.2.3.4', $result); // Test disabled $configs = array_merge($this->configs, ['forced_test_forwarded_ip' => 'no_forward']); $mockRemediation = $this->getMockBuilder(LapiRemediation::class) ->disableOriginalConstructor() ->onlyMethods(['getIpRemediation']) ->getMock(); $bouncer = $this->getMockForAbstractClass(AbstractBouncer::class, [$configs, $mockRemediation], '', true, true, true, ['getHttpRequestHeader']); $bouncer->method('getHttpRequestHeader')->willReturnOnConsecutiveCalls('1.2.3.4', '1.2.3.4'); $result = PHPUnitUtil::callMethod( $bouncer, 'handleForwardedFor', ['4.5.6.7', $configs] ); // 4.5.6.7 is not a trusted ip, so the result is passed ip $this->assertEquals('4.5.6.7', $result); $result = PHPUnitUtil::callMethod( $bouncer, 'handleForwardedFor', ['5.6.7.8', $configs] ); // 5.6.7.8 is a trusted ip, so the result should be the forwarded ip but the setting is disabled $this->assertEquals('5.6.7.8', $result); // Test force forwarded ip $configs = array_merge($this->configs, ['forced_test_forwarded_ip' => '192.168.127.12']); $mockRemediation = $this->getMockBuilder(LapiRemediation::class) ->disableOriginalConstructor() ->onlyMethods(['getIpRemediation']) ->getMock(); $bouncer = $this->getMockForAbstractClass(AbstractBouncer::class, [$configs, $mockRemediation], '', true, true, true, ['getHttpRequestHeader']); $bouncer->method('getHttpRequestHeader')->willReturnOnConsecutiveCalls('1.2.3.4', '1.2.3.4'); $result = PHPUnitUtil::callMethod( $bouncer, 'handleForwardedFor', ['4.5.6.7', $configs] ); // 4.5.6.7 is not a trusted ip so the result is the passed ip $this->assertEquals('4.5.6.7', $result); $result = PHPUnitUtil::callMethod( $bouncer, 'handleForwardedFor', ['5.6.7.8', $configs] ); // 5.6.7.8 is a trusted ip, so the result should be the forwarded ip but the setting is a forced ip $this->assertEquals('192.168.127.12', $result); // getTrustForwardedIpBoundsList $configs = $this->configs; $mockRemediation = $this->getMockBuilder(LapiRemediation::class) ->disableOriginalConstructor() ->onlyMethods(['pruneCache', 'clearCache', 'refreshDecisions', 'getCacheStorage']) ->getMock(); $bouncer = $this->getMockForAbstractClass(AbstractBouncer::class, [$configs, $mockRemediation]); $result = PHPUnitUtil::callMethod( $bouncer, 'getTrustForwardedIpBoundsList', [] ); $this->assertEquals([['005.006.007.008', '005.006.007.008']], $result); // capRemediationLevel $configs = $this->configs; $mockRemediation = $this->getMockBuilder(LapiRemediation::class) ->disableOriginalConstructor() ->onlyMethods(['pruneCache', 'clearCache', 'refreshDecisions', 'getCacheStorage']) ->getMock(); $bouncer = $this->getMockForAbstractClass(AbstractBouncer::class, [$configs, $mockRemediation]); $this->assertInstanceOf(LapiRemediation::class, $bouncer->getRemediationEngine()); $result = PHPUnitUtil::callMethod( $bouncer, 'capRemediationLevel', ['ban'] ); $this->assertEquals('ban', $result, 'Remediation should be capped as ban'); $this->configs['bouncing_level'] = Constants::BOUNCING_LEVEL_DISABLED; $configs = $this->configs; $mockRemediation = $this->getMockBuilder(LapiRemediation::class) ->disableOriginalConstructor() ->onlyMethods(['pruneCache', 'clearCache', 'refreshDecisions', 'getCacheStorage', 'getConfig']) ->getMock(); $mockRemediation->method('getConfig')->will( $this->returnValueMap( [ ['ordered_remediations', ['ban', 'captcha', 'bypass']], ] ) ); $bouncer = $this->getMockForAbstractClass(AbstractBouncer::class, [$configs, $mockRemediation]); $result = PHPUnitUtil::callMethod( $bouncer, 'capRemediationLevel', ['ban'] ); $this->assertEquals('bypass', $result, 'Remediation should be capped as bypass'); $this->configs['bouncing_level'] = Constants::BOUNCING_LEVEL_FLEX; $configs = $this->configs; $mockRemediation = $this->getMockBuilder(LapiRemediation::class) ->disableOriginalConstructor() ->onlyMethods(['pruneCache', 'clearCache', 'refreshDecisions', 'getCacheStorage', 'getConfig']) ->getMock(); $bouncer = $this->getMockForAbstractClass(AbstractBouncer::class, [$configs, $mockRemediation]); $mockRemediation->method('getConfig')->will( $this->returnValueMap( [ ['ordered_remediations', ['ban', 'captcha', 'bypass']], ] ) ); $result = PHPUnitUtil::callMethod( $bouncer, 'capRemediationLevel', ['ban'] ); $this->assertEquals('captcha', $result, 'Remediation should be capped as captcha'); // checkCaptcha $result = PHPUnitUtil::callMethod( $bouncer, 'checkCaptcha', ['test1', 'test2', '5.6.7.8'] ); $this->assertEquals(false, $result, 'Captcha should be marked as not resolved'); $result = PHPUnitUtil::callMethod( $bouncer, 'checkCaptcha', ['test1', 'test1', '5.6.7.8'] ); $this->assertEquals(true, $result, 'Captcha should be marked as resolved'); $result = PHPUnitUtil::callMethod( $bouncer, 'checkCaptcha', ['test1', 'TEST1', '5.6.7.8'] ); $this->assertEquals(true, $result, 'Captcha should be marked as resolved even for case non matching'); $result = PHPUnitUtil::callMethod( $bouncer, 'checkCaptcha', ['001', 'ool', '5.6.7.8'] ); $this->assertEquals(true, $result, 'Captcha should be marked as resolved even for some similar chars'); // buildCaptchaCouple $result = PHPUnitUtil::callMethod( $bouncer, 'buildCaptchaCouple', [] ); $this->assertArrayHasKey('phrase', $result, 'Captcha couple should have a phrase'); $this->assertArrayHasKey('inlineImage', $result, 'Captcha couple should have a inlineImage'); $this->assertIsString($result['phrase'], 'Captcha phrase should be ok'); $this->assertEquals(5, strlen($result['phrase']), 'Captcha phrase should be of length 5'); $this->assertStringStartsWith('data:image/jpeg;base64', $result['inlineImage'], 'Captcha image should be ok'); // getCache $result = PHPUnitUtil::callMethod( $bouncer, 'getCache', [] ); $this->assertInstanceOf(\CrowdSec\RemediationEngine\CacheStorage\AbstractCache::class, $result, 'Get cache should return remediation cache'); // getBanHtml $this->configs = array_merge($this->configs, [ 'text' => [ 'ban_wall' => [ 'title' => 'BAN TEST TITLE', ], ], ]); $configs = $this->configs; $mockRemediation = $this->getMockBuilder(LapiRemediation::class) ->disableOriginalConstructor() ->onlyMethods(['pruneCache', 'clearCache', 'refreshDecisions', 'getCacheStorage']) ->getMock(); $bouncer = $this->getMockForAbstractClass(AbstractBouncer::class, [$configs, $mockRemediation]); $result = PHPUnitUtil::callMethod( $bouncer, 'getBanHtml', [] ); $this->assertStringContainsString('<h1>BAN TEST TITLE</h1>', $result, 'Ban rendering should be as expected'); // getCaptchaHtml $this->configs = array_merge($this->configs, [ 'text' => [ 'captcha_wall' => [ 'title' => 'CAPTCHA TEST TITLE', ], ], ]); $configs = $this->configs; $mockRemediation = $this->getMockBuilder(LapiRemediation::class) ->disableOriginalConstructor() ->onlyMethods(['pruneCache', 'clearCache', 'refreshDecisions', 'getCacheStorage']) ->getMock(); $bouncer = $this->getMockForAbstractClass(AbstractBouncer::class, [$configs, $mockRemediation]); $result = PHPUnitUtil::callMethod( $bouncer, 'getCaptchaHtml', [false, 'fake-inline-image', 'fake-url'] ); $this->assertStringContainsString('CAPTCHA TEST TITLE', $result, 'Captcha rendering should be as expected'); $this->assertStringNotContainsString('<p class="error">', $result, 'Should be no error message'); $result = PHPUnitUtil::callMethod( $bouncer, 'getCaptchaHtml', [true, 'fake-inline-image', 'fake-url'] ); $this->assertStringContainsString('<p class="error">', $result, 'Should be no error message'); // shouldTrustXforwardedFor unset($_POST['crowdsec_captcha']); $result = PHPUnitUtil::callMethod( $bouncer, 'shouldTrustXforwardedFor', ['not-an-ip'] ); $this->assertEquals(false, $result, 'Should return false if ip is invalid'); } public function testGetRemediationForIpExeption() { $configs = $this->configs; $mockRemediation = $this->getMockBuilder(LapiRemediation::class) ->disableOriginalConstructor() ->onlyMethods(['getIpRemediation']) ->getMock(); $bouncer = $this->getMockForAbstractClass(AbstractBouncer::class, [$configs, $mockRemediation]); $this->assertInstanceOf(LapiRemediation::class, $bouncer->getRemediationEngine()); $mockRemediation->method('getIpRemediation')->willThrowException(new \Exception('Error in unit test', 123)); $errorMessage = ''; $errorCode = 0; try { $bouncer->getRemediationForIp('1.2.3.3'); } catch (BouncerException $e) { $errorMessage = $e->getMessage(); $errorCode = $e->getCode(); } $this->assertEquals(123, $errorCode); $this->assertEquals('Error in unit test', $errorMessage); } public function testShouldBounceCurrentIp() { $configs = $this->configs; $mockRemediation = $this->getMockBuilder(LapiRemediation::class) ->disableOriginalConstructor() ->onlyMethods(['getIpRemediation']) ->getMock(); $bouncer = $this->getMockForAbstractClass(AbstractBouncer::class, [$configs, $mockRemediation]); $result = $bouncer->shouldBounceCurrentIp(); $this->assertEquals(true, $result); $configs = array_merge($this->configs, ['bouncing_level' => 'bouncing_disabled']); $mockRemediation = $this->getMockBuilder(LapiRemediation::class) ->disableOriginalConstructor() ->onlyMethods(['getIpRemediation']) ->getMock(); $bouncer = $this->getMockForAbstractClass(AbstractBouncer::class, [$configs, $mockRemediation]); $result = $bouncer->shouldBounceCurrentIp(); $this->assertEquals(false, $result); $configs = $this->configs; $mockRemediation = $this->getMockBuilder(LapiRemediation::class) ->disableOriginalConstructor() ->onlyMethods(['getIpRemediation']) ->getMock(); $bouncer = $this->getMockForAbstractClass(AbstractBouncer::class, [$configs, $mockRemediation], '', true, true, true, ['getRequestUri']); $bouncer->method('getRequestUri')->willReturnOnConsecutiveCalls(self::EXCLUDED_URI, '/good-uri'); $result = $bouncer->shouldBounceCurrentIp(); $this->assertEquals(false, $result); $result = $bouncer->shouldBounceCurrentIp(); $this->assertEquals(true, $result); } public function testCacheMethodsException() { $configs = $this->configs; $mockRemediation = $this->getMockBuilder(LapiRemediation::class) ->disableOriginalConstructor() ->onlyMethods(['pruneCache', 'clearCache', 'refreshDecisions', 'getCacheStorage']) ->getMock(); $bouncer = $this->getMockForAbstractClass(AbstractBouncer::class, [$configs, $mockRemediation]); $this->assertInstanceOf(LapiRemediation::class, $bouncer->getRemediationEngine()); $mockRemediation->method('pruneCache')->willThrowException(new \Exception('unit test prune cache', 123)); $errorMessage = ''; $errorCode = 0; try { $bouncer->pruneCache(); } catch (BouncerException $e) { $errorMessage = $e->getMessage(); $errorCode = $e->getCode(); } $this->assertEquals(123, $errorCode); $this->assertEquals('Error while pruning cache: unit test prune cache', $errorMessage); $mockRemediation->method('clearCache')->willThrowException(new \Exception('unit test clear cache', 456)); $errorMessage = ''; $errorCode = 0; try { $bouncer->clearCache(); } catch (BouncerException $e) { $errorMessage = $e->getMessage(); $errorCode = $e->getCode(); } $this->assertEquals(456, $errorCode); $this->assertEquals('Error while clearing cache: unit test clear cache', $errorMessage); $mockRemediation->method('refreshDecisions')->willThrowException(new \Exception('unit test refresh', 789)); $errorMessage = ''; $errorCode = 0; try { $bouncer->refreshBlocklistCache(); } catch (BouncerException $e) { $errorMessage = $e->getMessage(); $errorCode = $e->getCode(); } $this->assertEquals(789, $errorCode); $this->assertEquals('Error while refreshing decisions: unit test refresh', $errorMessage); $mockRemediation->method('getCacheStorage')->willThrowException(new \Exception('unit test get cache storage', 101112)); $errorMessage = ''; $errorCode = 0; try { $bouncer->testCacheConnection(); } catch (BouncerException $e) { $errorMessage = $e->getMessage(); $errorCode = $e->getCode(); } $this->assertEquals(101112, $errorCode); $this->assertEquals('Error while testing cache connection: unit test get cache storage', $errorMessage); } }
704dd49a5eb8b00e3289249425f867e1c7716409
[ "Markdown", "PHP", "Shell" ]
21
PHP
crowdsecurity/php-cs-bouncer
2920637c300509739734a9c1f7a982078fc2d5bc
1e85777bdef52b81ba45d2ebb2da2c43cf9b14b0
refs/heads/master
<file_sep>#!/bin/bash # # Creates the Structure for a deb #rm -rf /tmp/pack <file_sep># - coding: utf-8 - # # Copyright (C) 2009 <NAME> # # This file is part of the Monocaffe Connection Manager # # Monocaffe Connection Manager is free software: you can redistribute # it and/or modify it under the terms of the GNU General Public License # as published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later version. # # Monocaffe Connection Manager is distributed in the hope that it will # be useful, but WITHOUT ANY WARRANTY; without even the implied warranty # of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License along # with the Monocaffe Connection Manager. If not, see # <http://www.gnu.org/licenses/>. # ''' Main Script for mcm gtk ''' import gtk from gtk import glade import pygtk import logging import os import sys import vte import webbrowser import gettext import locale pygtk.require("2.0") from mcm.common.connections import * from mcm.common.export import * from mcm.common.utils import * import mcm.common.constants from widgets import * for module in glade, gettext: module.bindtextdomain('mcm', constants.local_path) module.textdomain('mcm') class McmGtk(object): def __init__(self): self.xml = gtk.glade.XML(constants.glade_file) self.widgets = self.init_widgets() self.xml.signal_autoconnect(self.events()) # I don't feel like the status icon is a good idea now that mcm is what it is # self.init_status_icon(constants.glade_home) self.dao = Dao() self.connections = self.dao.read_xml() self.draw_tree() self.init_tips_menu() self.init_main_window() def about_event(self, widget): about = self.widgets['about'] about.connect("response", lambda d, r: d.hide()) about.run() def add_event(self, widget): id = self.get_last_id() dlg = AddConnectionDialog(id, self.connections.keys(), groups(self.connections), types(self.connections)) dlg.run() if dlg.response == gtk.RESPONSE_OK: cx = dlg.new_connection self.connections[cx.alias] = cx self.draw_tree() def assign_key_binding(self, key_binding, callback): accel_group = self.widgets['accel_group'] key, mod = gtk.accelerator_parse(key_binding) accel_group.connect_group(key, mod, gtk.ACCEL_VISIBLE, callback) def clear_cluster_event(self, widget): entry = self.widgets['cluster_entry'] entry.set_text("") def close_tab_event(self, accel_group, window, keyval=None, modifier=None, unk=None): terminals = self.widgets['terminals'] index = terminals.get_current_page() terminals.remove_page(index) if terminals.get_n_pages() <= 0: terminals.hide() return True def cluster_backspace(self, widget): return self.cluster_send_key('\b') def cluster_event(self, widget): command = widget.get_text() widget.set_text("") if len(command) < 1: return False return self.cluster_send_key(command) def cluster_intro_event(self, widget): return self.cluster_send_key('\n') def cluster_send_key(self, key): # Now get the notebook and all the tabs cluster_tabs = {} terminals = self.widgets['terminals'] pages = terminals.get_n_pages() for i in range(pages): scroll = terminals.get_nth_page(i) checkbox = terminals.get_tab_label(scroll) if checkbox.get_active(): term = scroll.get_child() cluster_tabs[i] = term for term in cluster_tabs.values(): term.feed_child(key) return True def connect_event(self, widget, path=None, vew_column=None): alias = None if widget.props.name == 'connect_button' or widget.props.name == 'mb_connect' or widget.props.name == 'connections_tree': alias = self.get_tree_selection() else: alias = widget.props.name self.do_connect(self.connections[alias]) def delete_event(self, widget): alias = self.get_tree_selection() dlg = UtilityDialogs() response = dlg.show_question_dialog(constants.deleting_connection_warning % alias, constants.are_you_sure) if response == gtk.RESPONSE_OK: del self.connections[alias] self.draw_tree() def do_connect(self, connection): '''Here I create a ScrolledWindow, attach a VteTerminal widget and all this gets attached to a new page on a NoteBook widget. Instead of using a label, I use a custom CheckButton widget since the default CheckButton widget covered the whole tab, making it very difficult to switch tabs by clicking on them.''' scroll = gtk.ScrolledWindow() # By setting the POLICY_AUTOMATIC, the ScrollWindow resizes itself when hidding the TreeView scroll.set_policy(gtk.POLICY_AUTOMATIC, gtk.POLICY_ALWAYS) v = vte.Terminal() scroll.add(v) terminals = self.widgets['terminals'] label = None menu_label = None if connection == None: label = McmCheckbox('localhost') menu_label = gtk.Label('localhost') else: label = McmCheckbox(connection.alias) label.set_tooltip_text(connection.description) menu_label = gtk.Label(connection.alias) self.set_window_title(label.get_title()) index = terminals.append_page_menu(scroll, label, menu_label) terminals.set_tab_reorderable(scroll, True) # Send the scroll widget to the event so the notebook know which child to close v.connect("child-exited", lambda term: self.close_tab_event(scroll, terminals)) v.connect("button-press-event", self.do_popup_console_menu) v.connect("key-press-event", self.terminal_key_event) pid = v.fork_command() if connection != None: v.feed_child(connection.gtk_cmd()) self.assign_key_binding(constants.tabs_switch_keys % (index + 1), self.switch_tab) self.assign_key_binding(constants.terminal_copy_keys, self.do_copy) self.assign_key_binding(constants.terminal_paste_keys, self.do_paste) terminals.show_all() terminals.set_current_page(index) self.draw_consoles() v.grab_focus() def do_localhost(self, accel_group, window=None, keyval=None, modifier=None): self.do_connect(None) return True def do_popup_console_menu(self, widget, event): '''Draw a Menu ready to be inserted in a vteterminal widget''' if event.button == 1: return False elif event.button == 3: menu = gtk.Menu() copy = gtk.MenuItem(constants.copy) paste = gtk.MenuItem(constants.paste) search = gtk.MenuItem(constants.google_search) title = gtk.MenuItem(constants.set_title) menu.append(copy) menu.append(paste) menu.append(search) menu.append(gtk.SeparatorMenuItem()) menu.append(title) copy.connect('activate', self.do_copy) paste.connect('activate', self.do_paste) search.connect('activate', self.do_search) title.connect('activate', self.do_set_title) menu.show_all() menu.popup(None, None, None, 3, event.time) return True else: return False def do_copy(self, widget, var2=None, var3=None, var4=None): terminals = self.widgets['terminals'] scroll = terminals.get_nth_page(terminals.get_current_page()) vte = scroll.get_child() vte.copy_clipboard() return True def do_paste(self, widget, var2=None, var3=None, var4=None): terminals = self.widgets['terminals'] scroll = terminals.get_nth_page(terminals.get_current_page()) vte = scroll.get_child() vte.paste_clipboard() return True def do_search(self, widget): self.do_copy(widget) clipb = widget.get_clipboard(gtk.gdk.SELECTION_CLIPBOARD) text = clipb.wait_for_text() webbrowser.open_new_tab(constants.google_search_url % text) def do_set_title(self, widget): terminals = self.widgets['terminals'] scroll = terminals.get_nth_page(terminals.get_current_page()) vte = scroll.get_child() vte.copy_clipboard() clipb = widget.get_clipboard(gtk.gdk.SELECTION_CLIPBOARD) text = clipb.wait_for_text() if len(text) > 30: text = text[0:30] label = McmCheckbox(text) terminals.set_tab_label(scroll, label) self.set_window_title(text) def draw_column(self, tree, title, id): tree.append_column(self.new_column(title, id)) def draw_consoles(self): cluster_tabs = {} terminals = self.widgets['terminals'] pages = terminals.get_n_pages() conf = McmConfig() for i in range(pages): scroll = terminals.get_nth_page(i) term = scroll.get_child() color = gtk.gdk.color_parse(conf.get_bg_color()) term.set_color_background(color) color = gtk.gdk.color_parse(conf.get_fg_color()) term.set_color_foreground(color) opacity = (conf.get_bg_transparency() * 65535) / 100 if conf.get_bg_transparent(): term.set_background_image_file("") term.set_background_transparent(True) term.set_opacity(opacity) term.set_background_saturation(opacity * 0.00001) else: if len(conf.get_bg_image()) > 1: term.set_background_image_file(conf.get_bg_image()) term.set_background_transparent(False) term.set_opacity(100) term.set_background_saturation(opacity * 0.00001) else: term.set_background_transparent(False) term.set_background_image_file("") term.set_font(conf.get_font()) term.set_word_chars(conf.get_word_chars()) term.set_scrollback_lines(conf.get_buffer_size()) def draw_connection_widgets(self, alias): if alias == None: return connection = None try: connection = self.connections[alias] except KeyError: return label = self.widgets['cx_type'] label.set_label("<b>%s</b>" % connection.get_type()) label = self.widgets['alias_label'] label.set_label("<b>%s</b>" % alias) self.draw_entry('user_entry', connection.user) self.draw_entry('host_entry', connection.host) self.draw_entry('port_entry', connection.port) self.draw_entry('password_entry', connection.password) self.draw_entry('options_entry', connection.options) self.draw_entry('description_entry', connection.description) def draw_entry(self, widget_name, text, tooltip_text=""): entry = self.widgets[widget_name] entry_default_color = gtk.gdk.color_parse("#FFFFFF") entry_default_state = gtk.STATE_NORMAL entry.set_text(text) entry.modify_base(entry_default_state, entry_default_color) entry.set_tooltip_text(tooltip_text) def draw_tree(self): tree = self.widgets['cx_tree'] if len(tree.get_columns()) == 0: self.draw_column(tree, "Alias", 0) #self.draw_column(tree, "Alias", 1) tree_store = gtk.TreeStore(str, str) tree.set_model(tree_store) groups = set() for cx in self.connections.values(): groups.add(cx.group) for grp in groups: grp_node = tree_store.append(None, [grp, None]) for cx in self.connections.values(): if grp == cx.group: tree_store.append(grp_node, [cx.alias, None]) def entry_changed_event(self, widget): widget.modify_base(gtk.STATE_NORMAL, gtk.gdk.color_parse("#FFADAD")) widget.set_tooltip_text(constants.press_enter_to_save) def events(self): events = { 'on_main_mcm_destroy': self.quit_event, 'on_connect_button_clicked': self.connect_event, 'on_arrow_button_clicked': self.hide_unhide_tree, # Menu Items 'on_mb_about_activate': self.about_event, 'on_mb_help_activate': self.help_event, 'on_mb_preferences_activate': self.preferences_event, 'on_mb_import_activate': self.import_csv_event, 'on_mb_export_html_activate': self.export_html_event, 'on_mb_export_csv_activate': self.export_csv_event, 'on_mb_quit_activate': self.quit_event, 'on_mb_add_activate': self.add_event, 'on_mb_delete_activate': self.delete_event, 'on_mb_connect_activate': self.connect_event, 'on_mb_cluster_toggled': self.hide_unhide_cluster_box, 'on_mb_view_tree_toggled': self.hide_unhide_tree, 'on_mb_tips_toggled': self.hide_unhide_tips, 'on_mb_update_tips_activate': self.update_tips, 'on_mb_http_server_activate': self.http_server, # Status Icon Items 'on_sib_quit_activate': self.quit_event, 'on_sib_preferences_activate': self.preferences_event, 'on_sib_add_activate': self.add_event, 'on_sib_quit_activate': self.quit_event, 'on_status_icon_menu_deactivate': self.on_status_icon_deactivate, 'on_sib_home_activate': self.do_localhost, # Tree signals 'on_connections_tree_row_activated': self.connect_event, 'on_home_button_clicked': self.do_localhost, 'on_connections_tree_cursor_changed': self.on_tree_item_clicked, # Entries Signales 'on_user_entry_activate': self.update_connection, 'on_user_entry_changed': self.entry_changed_event, 'on_host_entry_activate': self.update_connection, 'on_host_entry_changed': self.entry_changed_event, 'on_port_entry_activate': self.update_connection, 'on_port_entry_changed': self.entry_changed_event, 'on_options_entry_activate': self.update_connection, 'on_options_entry_changed': self.entry_changed_event, 'on_description_entry_activate': self.update_connection, 'on_description_entry_changed': self.entry_changed_event, 'on_pwd_entry_activate': self.update_connection, 'on_pwd_entry_changed': self.entry_changed_event, #Cluster Signals 'on_cluster_entry_changed': self.cluster_event, 'on_cluster_entry_activate': self.cluster_intro_event, 'on_cluster_entry_backspace': self.cluster_backspace, # Notebook Signals #'on_terminals_change_current_page': self.switch_tab_event, #'on_terminals_select_page': self.switch_tab_event, 'on_terminals_switch_page': self.switch_tab_event} return events def export_csv_event(self, widget): dlg = ExportDialog() dlg.run() if dlg.response == gtk.RESPONSE_OK: _csv = ExportCsv(dlg.get_filename(), self.connections) idlg = UtilityDialogs() idlg.show_info_dialog(constants.export_csv, constants.saved_file % dlg.get_filename()) def export_html_event(self, widget): dlg = ExportDialog() dlg.run() if dlg.response == gtk.RESPONSE_OK: _html = Html(dlg.get_filename(), constants.version, self.connections) _html.export() idlg = UtilityDialogs() idlg.show_info_dialog(constants.export_html, constants.saved_file % dlg.get_filename()) def f10_event(self, accel_group, window=None, keyval=None, modifier=None): return False def get_last_id(self): return get_last_id(self.connections) def get_tree_selection(self, tree=None): '''Gets the alias of the connection currently selected on the tree''' if tree == None: tree = self.widgets['cx_tree'] cursor = tree.get_selection() model = tree.get_model() (model, iter) = cursor.get_selected() if iter == None: return None alias = model.get_value(iter, 0) return alias def help_event(self, widget): webbrowser.open_new_tab(constants.mcm_help_url) def hide_unhide_cluster_box(self, widget): cl_box = self.widgets['cluster_entry'] if widget.active: cl_box.show_all() else: cl_box.hide() def hide_unhide_tips(self, widget): tips_bar = self.widgets['tips_hbox'] if widget.active: tips_bar.show_all() else: tips_bar.hide() def hide_unhide_tree(self, widget, window=None, key_val=None, modifier=None): # I have to define those parameters so the callbacks from the key bindings work vbox = self.widgets['vbox3'] mb = self.widgets['mb_view_tree'] if vbox.props.visible: mb.set_active(False) vbox.hide() else: mb.set_active(True) vbox.show_all() return True def http_server(self, widget): dlg = HttpServerDialog() dlg.run() def import_csv_event(self, widget): dlg = ImportCsvDialog() dlg.run() cxs = None if dlg.response == gtk.RESPONSE_OK: _csv = Csv(dlg.uri) cxs = _csv.do_import() dlg = ImportProgressDialog(cxs, self.connections) dlg.run() self.connections = dlg.connections self.draw_tree() def init_main_window(self): main_window = self.widgets['window'] settings = gtk.settings_get_default() settings.props.gtk_menu_bar_accel = None self.keymap = gtk.gdk.keymap_get_default() accel_group = gtk.AccelGroup() main_window.add_accel_group(accel_group) self.widgets['accel_group'] = accel_group self.assign_key_binding(constants.hide_connections_keys, self.hide_unhide_tree) self.assign_key_binding(constants.terminal_home_keys, self.do_localhost) self.assign_key_binding('F10', self.f10_event) self.assign_key_binding(constants.tab_close_keys, self.close_tab_event) main_window.connect("delete-event", self.x_event) # Until I figure if I want this I'll disable it mb_http_server = self.widgets['mb_http_server'] mb_http_server.hide() main_window.show() self.hide_unhide_cluster_box(self.widgets['mb_cluster']) def init_status_icon(self, glade_home): self.status_icon = gtk.StatusIcon() self.status_icon.set_from_file(constants.icon_file) self.status_icon.set_tooltip(constants.app_name) self.status_icon.set_visible(True) self.status_icon.connect('activate', self.on_status_icon_activate) self.status_icon.connect('popup-menu', self.on_status_icon_popup) def init_tips_menu(self): tips_hbox = self.widgets["tips_hbox"] # Make this global so I can update the tips self.tips_widget = McmTipsWidget(tips_hbox) def init_widgets(self): widgets = { 'window': self.xml.get_widget("main_mcm"), 'about': self.xml.get_widget("about_mcm"), 'cx_tree': self.xml.get_widget("connections_tree"), 'cx_type': self.xml.get_widget("combo_connection_type"), 'user_entry': self.xml.get_widget("user_entry"), 'host_entry': self.xml.get_widget("host_entry"), 'port_entry': self.xml.get_widget("port_entry"), 'password_entry': self.xml.get_widget("pwd_entry"), 'options_entry': self.xml.get_widget("options_entry"), 'description_entry': self.xml.get_widget("description_entry"), 'alias_label': self.xml.get_widget("alias_label"), 'status_icon_menu': self.xml.get_widget("status_icon_menu"), 'connections_menu': self.xml.get_widget("connections_menu"), 'terminals': self.xml.get_widget("terminals"), 'hbox1': self.xml.get_widget("hbox1"), 'vbox3': self.xml.get_widget("vbox3"), 'vbox1': self.xml.get_widget("vbox1"), 'aspectframe1': self.xml.get_widget("aspectframe1"), 'cluster_entry': self.xml.get_widget("cluster_entry"), 'mb_cluster': self.xml.get_widget("mb_cluster"), 'mb_view_tree': self.xml.get_widget("mb_view_tree"), 'statusbar': self.xml.get_widget("statusbar1"), 'mb_http_server': self.xml.get_widget("mb_http_server"), # Tips Menu 'tips_menubar': self.xml.get_widget("tips_menubar"), 'mi_tips': self.xml.get_widget("mi_tips"), 'tips_hbox': self.xml.get_widget("tips_hbox"), } return widgets def new_column(self, title, id): column = gtk.TreeViewColumn(title, gtk.CellRendererText(), text=id) column.set_resizable(True) column.set_sort_column_id(id) return column def on_status_icon_activate(self, widget): main_window = self.widgets['window'] if main_window.props.visible: main_window.hide() else: main_window.show() def on_status_icon_deactivate(self, widget): cx_menu = self.widgets['connections_menu'] for i in cx_menu.get_children(): cx_menu.remove(i) def on_tree_item_clicked(self, widget): self.draw_connection_widgets(self.get_tree_selection(widget)) def on_status_icon_popup(self, status, button, time): cx_menu = self.widgets['connections_menu'] for k in self.connections.keys(): cx_item = gtk.MenuItem(k) cx_item.props.name = k cx_item.connect('activate', self.connect_event) cx_item.show() cx_menu.append(cx_item) s_i_menu = self.widgets['status_icon_menu'] s_i_menu.popup(None, None, None, button, time) def preferences_event(self, widget): dlg = PreferencesDialog() dlg.run() if dlg.response == gtk.RESPONSE_OK: self.draw_consoles() def quit_event(self, widget, fck=None): dlg = UtilityDialogs() response = dlg.show_question_dialog(constants.quit_warning, constants.are_you_sure) if response == gtk.RESPONSE_OK: self.dao.save_to_xml(self.connections.values()) exit(0) else: return False def switch_tab(self, accel_group, window, keyval, modifier): # Key 0 is 48, Key 1 is 49 ... key 9 is 57 index = keyval - 49 terminals = self.widgets['terminals'] terminals.set_current_page(index) self.switch_tab_event(terminals, None, index) return True # This will stop the vte from getting the annoying alt key def switch_tab_event(self, notebook, page, page_num): page = notebook.get_nth_page(page_num) label_title = notebook.get_tab_label(page).get_title() self.set_window_title(label_title) def set_window_title(self, title="Monocaffe Connections Manager"): main_window = self.widgets['window'] main_window.set_title(constants.window_title % title) def tab_close_button(self, title): button = gtk.Button(title, gtk.STOCK_CLOSE, False) return button def terminal_key_event(self, widget, event): if event.state & gtk.gdk.CONTROL_MASK: pgup = self.keymap.get_entries_for_keyval(gtk.keysyms.Page_Up)[0][0] pgdn = self.keymap.get_entries_for_keyval(gtk.keysyms.Page_Down)[0][0] if event.hardware_keycode is pgup: terminals = self.widgets['terminals'] total = terminals.get_n_pages() page = terminals.get_current_page() + 1 if page < total: terminals.set_current_page(page) self.switch_tab_event(terminals, None, page) return True elif event.hardware_keycode is pgdn: terminals = self.widgets['terminals'] total = terminals.get_n_pages() page = terminals.get_current_page() - 1 if page >= 0: terminals.set_current_page(page) self.switch_tab_event(terminals, None, page) return True else: return False else: return False def update_connection(self, widget): alias = self.get_tree_selection() connection = self.connections[alias] wid_name = widget.get_name() property = widget.get_text() if wid_name == "user_entry": connection.user = property elif wid_name == "host_entry": connection.host = property elif wid_name == "port_entry": connection.port = property elif wid_name == "options_entry": connection.options = property elif wid_name == "description_entry": connection.description = property elif wid_name == "pwd_entry": connection.password = property self.connections[alias] = connection self.draw_connection_widgets(self.get_tree_selection()) def update_tips(self, widget): response = self.tips_widget.update() dlg = UtilityDialogs() if not response: dlg.show_error_dialog(constants.update_tips_error_1, constants.update_tips_error_2) else: dlg.show_info_dialog(constants.update_tips_success_1, constants.update_tips_success_2 % response) def x_event(self, x=None, y=None): self.quit_event(x) return True if __name__ == '__main__': # Start the logging stuff log_format = "%(asctime)s %(levelname)s: %(message)s" logging.basicConfig(level=logging.INFO, format = log_format) mcmgtk = McmGtk() gtk.main() <file_sep># - coding: utf-8 - # # Copyright (C) 2009 <NAME> # # This file is part of the Monocaffe Connection Manager # # Monocaffe Connection Manager is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # Monocaffe Connection Manager is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with the Monocaffe Connection Manager. If not, see <http://www.gnu.org/licenses/>. # ''' This is the main script for mcm ''' import os import sys import subprocess import logging from optparse import OptionParser from tables import Table from mcm.common.connections import * from mcm.common.utils import * class Mcm(object): def __init__(self): self.dialog_binary = '/usr/bin/dialog' self.dao = Dao() self.connections = self.dao.read_xml() def do_connect(self, connection): connection.print_connection(connection.conn_args()) try: subprocess.call(connection.conn_args()) except (KeyboardInterrupt, SystemExit): exit(0) def connect(self, alias): conn = self.connections[alias] self.do_connect(conn) def delete(self, alias): try: del self.connections[alias] self.save_and_exit() except KeyError: print("Unknown alias " + alias) def export_html(self, path): from mcm.common.export import Html html = Html(path, get_mcm_version(), self.dao.read_xml()) html.export() def add(self, cxs=None): cx = None if cxs == None: try: print "Adding a new alias. Follow instructions" print "Type of server (ssh, vnc, rdp, telnet, ftp) [default: SSH]:" cx_type = raw_input() cx_type = cx_type.upper() if len(cx_type) <= 0: cx_type = 'SSH' if cx_type != 'SSH' and cx_type != 'VNC' and cx_type != 'RDP' and cx_type != 'TELNET' and cx_type != 'FTP': raise TypeError("Unknown server type: " + cx_type) print "Alias for this connection:" cx_alias = raw_input() if self.connections != None: if self.connections.has_key(cx_alias): raise TypeError("This alias is already used. Try with another one") print "Hostname or IP Address:" cx_host = raw_input() print "Username:" cx_user = raw_input() print "Password:" cx_password = raw_input() print "Port:" cx_port = raw_input() print "Group:" cx_group = raw_input() if len(cx_group) <= 0: cx_group = None print "Options:" cx_options = raw_input() print("Description:") cx_desc = raw_input() cx = connections_factory(get_last_id(self.connections), cx_type, cx_user, cx_host, cx_alias, cx_password, cx_port, cx_group, cx_options, cx_desc) self.connections[cx_alias] = cx print("saved") print(cx) except (KeyboardInterrupt, SystemExit): exit(1) else: for d in cxs: # d is a dict alias = d['alias'].strip() if len(d) != 10: raise TypeError("Not a parseable Connection List") if self.connections.has_key(alias): print "Not saving %s" % alias continue cx = connections_factory(get_last_id(self.connections), d['type'], d['user'], d['host'], alias, d['password'], d['port'], d['group'], d['options'], d['description']) self.connections[alias] = cx print("saved") print(cx) self.save_and_exit() def list(self, alias=None): print "Usage: mcm [OPTIONS] [ALIAS]\n" t_headers = ['Alias', 'user', 'host', 'port'] t_rows = [] _ids = [] for conn in self.connections.values(): _ids.append(int(conn.id)) _ids.sort() for _id in _ids: for conn in self.connections.values(): if conn.id == str(_id): t_rows.append((conn.alias, conn.user, conn.host, conn.port)) table = Table(t_headers, t_rows) table.output() exit(0) def long_list(self): print '-'*80 print "Full list of connections" (sshs, vncs, rdps, tels, ftps) = ([], [], [], [], []) for conn in self.connections.values(): cx_type = conn.__class__.__name__.upper() if cx_type == 'SSH': sshs.append(conn) elif cx_type == 'VNC': vncs.append(conn) elif cx_type == 'RDP': rdps.append(conn) elif cx_type == 'TELNET': tels.append(conn) elif cx_type == 'FTP': ftps.append(conn) else: raise TypeError("Unknown Server Type: " + cx_type) self.long_print_conn("SSH", sshs) self.long_print_conn("VNC", vncs) self.long_print_conn("RDP", rdps) self.long_print_conn("TELNET", tels) self.long_print_conn("FTP", ftps) sys.exit(0) def show_menu(self): if os.path.exists(self.dialog_binary): alias = self.show_menu_dialog() self.connect(alias) else: self.list() def long_print_conn(self, type, connections): print '-'*80 print type print '-'*80 if len(connections) == 0: return t_headers = ['Alias', 'user', 'host', 'port', 'Password','Options', 'Description'] t_rows = [] for conn in connections: row = (conn.alias, conn.user, conn.host, conn.port, conn.password, conn.options, conn.description.strip()) t_rows.append(row) table = Table(t_headers, t_rows) table.output() def show_menu_dialog(self): '''Show a dialog, catch its output and return it for do_connect''' menu_size = 20 if len(self.connections) < menu_size: menu_size = str(len(self.connections)) else: menu_size = str(menu_size) dialog = [ self.dialog_binary, '--backtitle', 'Monocaffe Connections Manager ' + get_mcm_version(), '--clear', '--menu', '"Choose an Alias to connect to"', '0', '150', menu_size ] keys = self.connections.keys() keys.sort() for key in keys: conn = self.connections[key] dialog.append(key) dialog.append(conn.dialog_string()) fhandlr = open('/tmp/mcm_ans', 'w+') try: #print dialog res = subprocess.call(dialog, stderr=fhandlr) if res == 1: raise SystemExit() except (KeyboardInterrupt, SystemExit): sys.exit(0) fhandlr.seek(0) aliases = fhandlr.readlines() fhandlr.close() return aliases[0] def save_and_exit(self): self.dao.save_to_xml(self.connections.values()) exit(0) def import_csv(self, path): from mcm.common.utils import Csv _csv = Csv(path) cxs = _csv.do_import() self.add(cxs) if __name__ == '__main__': parser = OptionParser(usage="%prog [OPTIONS] [ALIAS]\nWith no options, prints the list of connections\nexample:\n %prog foo\t\tConnects to server foo", version="%prog 0.9") parser.add_option("-a", "--add", action="store_true", dest="add", help="add a new connection") parser.add_option("-l", "--list", action="store_true", dest="list", help="complete list of connections with all data") parser.add_option("-d", "--delete", action="store", dest="alias", help="delete the given connection alias") parser.add_option("--html", action="store", dest="html", help="Export the connections to the given HTML file") parser.add_option("--csv", action="store", dest="csv", help="Import the connections from the given CSV file") (options, args) = parser.parse_args() # Start the logging stuff log_format = "%(asctime)s %(levelname)s: %(message)s" logging.basicConfig(level=logging.INFO, format = log_format) #(export, drop) = os.path.split(os.getcwd()) #(export, drop) = os.path.split(export) #sys.path.insert(0, export) mcmt = Mcm() if not options.list and not options.add and not options.alias and not options.html and not options.csv and len(args) < 1: mcmt.show_menu() # I want only one option at a time if options.add and (options.list or options.alias or options.html or options.csv): parser.error("Only one option at a time") if options.list and options.alias and options.html and options.csv: parser.error("Only one option at a time") if options.add: mcmt.add() if options.list: mcmt.long_list() if options.alias: mcmt.delete(options.alias) if options.html: mcmt.export_html(options.html) if options.csv: mcmt.import_csv(options.csv) if len(args) > 0: mcmt.connect(args[0]) <file_sep>#!/bin/sh # # Install Script for Monocaffe Connections Manager # Please run as root # # This script is based on the one of pyjama. # # Clever way of testing for root userpriv=$(test -w \/ && echo "ok") if [ -z $userpriv ] then echo "Please run this script as root / sudo" exit 1 fi install_dir="/usr/share/apps/mcm" mcm_shell="/usr/share/apps/mcm/bin/mcm" echo "1/3 Copying files to ${install_dir}" mkdir ${install_dir} 2>/dev/null cp -R * ${install_dir} 2>/dev/null echo "2/3 Creating symlinks" ln -s ${mcm_shell} /usr/bin/mcm ln -s ${mcm_shell} /usr/bin/mcm-gtk echo "3/3 Creating menu-entry for Monocaffe Connections Manager" cp /usr/share/apps/mcm/gtk/mcm_icon.xpm /usr/share/pixmaps/mcm.xpm cp /usr/share/apps/mcm/gtk/mcm.desktop /usr/share/applications/ echo "Done. Monocaffe Connections Manager is ready" echo "Type mcm on a console or run mcm-gtk from the GNOME Menu" exit 0
5ae576787356fe423a5b07ae77aedad631bee520
[ "Python", "Shell" ]
4
Shell
cloudqq/Monocaffe-Connections-Manager
8e6fa97b42a2d8ae2a92479cf9d885322272c590
e7125df1ae8674b9ba29dfdc5186c0c0f42d3eb7
refs/heads/gh-pages
<file_sep>// run to reset: // localStorage.removeItem('visited-' + location.pathname); sessionStorage.removeItem('prev-' + location.pathname); if (location.search.match(/test-expand=true/)) { alert('Opted in to testing expand options'); localStorage.testExpand = 'true'; } else if (location.search.match(/test-expand=false/)) { alert('Opted out of testing expand options'); localStorage.testExpand = 'false'; } if (location.search.match(/test-preview=true/)) { alert('Opted in to testing hidden comment snippets'); localStorage.testPreview = 'true'; } else if (location.search.match(/test-preview=false/)) { alert('Opted out of testing hidden comment snippets'); localStorage.testPreview = 'false'; } // redirect http://slatestarcodex.com/tag/open/?latest (and similar) to their first post if (location.pathname.match(/^\/tag\/[^\/]+\//) && location.search === '?latest') { var rHref = document.querySelector('h2.pjgm-posttitle > a').href; if (rHref) { location = rHref; } } // Global variables are fun! var commentCountText, commentsList, divDiv, isReply; // *** Date utility functions function time_fromHuman(string) { /* Convert a human-readable date into a JS timestamp */ if (string.match(/^[0-9]{4}-[0-9]{2}-[0-9]{2}/)) { string = string.replace(' ', 'T'); // revert nice spacing string += ':00.000Z'; // complete ISO 8601 date time = Date.parse(string); // milliseconds since epoch // browsers handle ISO 8601 without explicit timezone differently // thus, we have to fix that by hand time += (new Date()).getTimezoneOffset() * 60e3; } else { string = string.replace(' at', ''); time = Date.parse(string); // milliseconds since epoch } return time; } function time_toHuman(time) { /* Convert a JS timestamp into a human-readable date */ // note: time is milliseconds since epoch // keep client offset from messing with server time time -= (new Date()).getTimezoneOffset() * 60e3; date = new Date(time); string = date.toISOString(); // to ISO 8601 string = string.slice(0, 16); // remove seconds, milliseconds and UTC mark string = string.replace('T', ' '); // use more readable separator return string; } // *** Sets up borders and populates comments list function border(since, updateTitle) { var commentList = document.querySelectorAll('.commentholder'); var mostRecent = since; var newComments = []; // Walk comments, setting borders as appropriate and saving new comments in a list for (var i = 0; i < commentList.length; ++i) { var postTime = time_fromHuman(commentList[i].querySelector('.comment-meta a').textContent); if (postTime > since) { commentList[i].classList.add('new-comment'); newComments.push({time: postTime, ele: commentList[i]}); if (postTime > mostRecent) { mostRecent = postTime; } } else { commentList[i].classList.remove('new-comment'); } } var newCount = newComments.length; // Maybe add new comment count to title if (updateTitle) { document.title = '(' + newCount + ') ' + document.title; } // Populate the floating comment list commentCountText.data = '' + newCount + ' comment' + (newCount == 1 ? '' : 's') + ' since '; commentsList.textContent = ''; if (newCount > 0 ) { divDiv.style.display = 'block'; newComments.sort(function(a, b){return a.time - b.time;}); for (i = 0; i < newCount; ++i) { var ele = newComments[i].ele; var newLi = document.createElement('li'); newLi.innerHTML = ele.querySelector('cite').textContent + ' <span class="comments-date">' + time_toHuman(newComments[i].time) + '</span>'; newLi.className = 'comment-list-item'; newLi.addEventListener('click', function(ele){return function(){ele.scrollIntoView(true);};}(ele)); commentsList.appendChild(newLi); } } else { divDiv.style.display = 'none'; } return mostRecent; } // *** Toggles visibility of comment which invoked it var commentToggle = function commentToggle(e, dontScroll) { var myComment = this.parentElement.parentElement; var myBody = myComment.querySelector('div.comment-body'); var myMeta = myComment.querySelector('div.comment-meta'); var myChildren = myComment.nextElementSibling; if (this.textContent == 'Hide') { this.textContent = 'Show'; myComment.style.opacity = '.6'; myBody.style.display = 'none'; myMeta.style.display = 'none'; if (myChildren) { myChildren.style.display = 'none'; } if (!dontScroll) myComment.scrollIntoView(true); // It's debatable if we should do this at all, but doing it only when hiding is probably better than doing it unconditionally. } else { this.textContent = 'Hide'; myComment.style.opacity = '1'; myBody.style.display = 'block'; myMeta.style.display = 'block'; if (myChildren) { myChildren.style.display = 'block'; } } }; if (localStorage.testPreview === 'true') { commentToggle = function commentToggle(e, dontScroll) { var myComment = this.parentElement.parentElement; if (this.textContent == 'Hide') { this.textContent = 'Show'; myComment.className += ' collapsed-comment'; if (!dontScroll) myComment.scrollIntoView(true); // It's debatable if we should do this at all, but doing it only when hiding is probably better than doing it unconditionally. } else { this.textContent = 'Hide'; myComment.className = myComment.className.replace(/ collapsed-comment/, ''); } }; var styleEle = document.createElement('style'); styleEle.type = 'text/css'; styleEle.textContent = '' + '.collapsed-comment { opacity: .6; }' + '.collapsed-comment > .comment-meta { display: none; }' + '.collapsed-comment > .comment-body { }' + '.collapsed-comment > .comment-body > * { display: none; }' + '.collapsed-comment > .comment-body > p:first-of-type { display: block; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; max-height: 24px; }' + '.collapsed-comment + ul { display: none; }' + ''; document.head.appendChild(styleEle); } // ** Set up highlights on first run function makeHighlight() { // *** Inject some css used by the floating list var styleEle = document.createElement('style'); styleEle.type = 'text/css'; styleEle.textContent = '.new-comment { border: 2px solid #5a5; }' + '.new-text { color: #C5C5C5; display: none; }' + '.new-comment .new-text { display: inline; }' + '.comments-floater { position: fixed; right: 4px; top: ' + (document.getElementById('wpadminbar') ? '36' : '4') + 'px; padding: 2px 5px; font-size: 14px; border-radius: 5px; background: rgba(250, 250, 250, 0.90); }' + // available space on the right = right bar (230px) + page margin ((screen.width - #pjgm-wrap.width) / 2) ' .comments-floater { max-width: calc(230px + (100% - 1258px) / 2); }' + '@media (max-width: 1274px) { .comments-floater { max-width: calc(230px + (100% - 1195px) / 2); } }' + '@media (max-width: 1214px) { .comments-floater { max-width: calc(230px + (100% - 1113px) / 2); } }' + '@media (max-width: 1134px) { .comments-floater { max-width: calc(230px + (100% - 866px) / 2); } }' + // at some point, it must cover the main content, we just keep space for [+] / [-] '@media (max-width: 850px) { .comments-floater { max-width: 230px; } }' + '.comments-scroller { word-wrap: break-word; max-height: 80vh; overflow-y: scroll; }' + '.comment-list-item { cursor: pointer; clear: both; }' + '.comments-date { font-size: 11px; display: block; }' + '@media (min-width:900px) { .comments-date { display: inline-block; text-align: right; float: right; padding-right: 1em; } }' + '.cct-span { white-space: nowrap; }' + // the full date will fit the input on large screens; on smaller screens, it will shrink to avoid wrapping '.date-input { margin-left: .5em; min-width: 3ex; max-width: 10em; width: calc(100% - 153px); }' + '@media (max-width: 300px) { .date-input { width: auto; } }' + '.hider { position: absolute; left: -25px; top: 6px; display: inline-block; width: 20px; text-align: center; }' + '.hider::before { content: "["; float: left; }' + '.hider::after { content: "]"; float: right; }' + ''; document.head.appendChild(styleEle); // *** Create and insert the floating list of comments, and its contents // The floating box. var floatBox = document.createElement('div'); floatBox.className = 'comments-floater'; // Container for the text node below. var cctSpan = document.createElement('span'); cctSpan.className = 'cct-span'; // The text node which says 'x comments since' commentCountText = document.createTextNode(''); // The text box with the date. var dateInput = document.createElement('input'); dateInput.className = 'date-input'; dateInput.addEventListener('blur', function(e) { var newDate = time_fromHuman(dateInput.value); if (isNaN(newDate)) { alert( 'Couldn\'t parse given date. ' + 'Use either YYYY-MM-DD HH:mm ' + 'or the format used for comments.' ); return; } border(newDate, false); }); dateInput.addEventListener('keypress', function(e) { if (e.keyCode === 13) { dateInput.blur(); } }); // Container for the comments list and the '[+]' divDiv = document.createElement('div'); divDiv.style.display = 'none'; // Scrollable container for the comments list var commentsScroller = document.createElement('div'); commentsScroller.className = 'comments-scroller'; commentsScroller.style.display = 'none'; // The '[+]' var hider = document.createElement('span'); hider.textContent = '+'; hider.className = 'hider'; hider.addEventListener('click', function(e) { if (commentsScroller.style.display != 'none') { commentsScroller.style.display = 'none'; hider.textContent = '+'; } else { commentsScroller.style.display = ''; hider.textContent = '-'; } }); // Actual list of comments commentsList = document.createElement('ul'); // Insert all the things we made into each other and ultimately the document. cctSpan.appendChild(commentCountText); floatBox.appendChild(cctSpan); floatBox.appendChild(dateInput); divDiv.appendChild(hider); commentsScroller.appendChild(commentsList); divDiv.appendChild(commentsScroller); floatBox.appendChild(divDiv); document.body.appendChild(floatBox); // *** Retrieve the last-visit time from storage, border all comments made after, and save the time of the latest comment in storage for next time var pathString = 'visited-' + location.pathname; var lastVisit = parseInt(localStorage[pathString]); if (isNaN(lastVisit)) { lastVisit = 0; // prehistory! Actually 1970, which predates all SSC comments, so we're good. } if (!isReply) { dateInput.value = time_toHuman(lastVisit); var mostRecent = border(lastVisit, false); localStorage[pathString] = mostRecent; } else { // Use the same threshold we used last time and leave that as is, but update the threshold to be used on fresh page loads. var prevVisit = parseInt(sessionStorage['prev-' + location.pathname]); if (isNaN(prevVisit)) { prevVisit = lastVisit; } dateInput.value = time_toHuman(prevVisit); var mostRecent = border(prevVisit, false); localStorage[pathString] = mostRecent; } sessionStorage.removeItem('last-submit'); sessionStorage.removeItem('prev-' + location.pathname); } // This logic helps determine if the page was loaded by posting a comment (approximately) function addUnloadListeners() { var commentOrLoginCausedUnload = false; var navListener = function(){ sessionStorage.setItem('last-submit', (new Date()).getTime()); sessionStorage.setItem('prev-' + location.pathname, time_fromHuman(document.querySelector('.date-input').value)); commentOrLoginCausedUnload = true; } var forms = document.querySelectorAll('.comment-form'); for (var i = 0; i < forms.length; ++i) { forms[i].addEventListener('submit', navListener); } var loginOrUpdateLinks = document.querySelectorAll('.comment-reply-login,.must-log-in>a,.logged-in-as>a:nth-child(2),#comment-order-reverse-button>a'); for (var i = 0; i < loginOrUpdateLinks.length; ++i) { loginOrUpdateLinks[i].addEventListener('click', navListener); } addEventListener('unload', function(){ if (!commentOrLoginCausedUnload) { sessionStorage.removeItem('last-submit'); sessionStorage.removeItem('prev-' + location.pathname); } }); var lastSubmit = parseInt(sessionStorage.getItem('last-submit')); if (isNaN(lastSubmit)) { lastSubmit = 0; } isReply = (new Date()).getTime() - lastSubmit < 1200000; } function makeShowHideNewTextParentLinks() { // *** Add buttons to show/hide threads // *** Add ~new~ to comments // *** Add link to parent comment var comments = document.querySelectorAll('li.comment'); for (var i=0; i < comments.length; ++i) { var commentHolder = comments[i].querySelector('div.commentholder'); // Show/Hide var hideLink = document.createElement('a'); hideLink.className = 'comment-reply-link comment-hide-link'; hideLink.style.textDecoration = 'underline'; hideLink.style.cursor = 'pointer'; hideLink.textContent = 'Hide'; hideLink.addEventListener('click', commentToggle); var divs = commentHolder.children; var replyEle = divs[divs.length-1]; replyEle.appendChild(hideLink); // ~new~ var newText = document.createElement('span'); newText.className = 'new-text'; newText.textContent = '~new~'; var meta = commentHolder.querySelector('div.comment-meta'); meta.appendChild(newText); // Parent link if (comments[i].parentElement.tagName === 'UL') { var parent = comments[i].parentElement.parentElement; var parentID = parent.firstElementChild.id; var parentLink = document.createElement('a'); parentLink.href = '#' + parentID; parentLink.className = 'comment-reply-link'; parentLink.style.textDecoration = 'underline'; parentLink.title = 'Parent comment'; parentLink.textContent = '↑'; var replyEle = commentHolder.querySelector('div.reply'); replyEle.appendChild(document.createTextNode(' ')); replyEle.appendChild(parentLink); } } } // ?? function boustrophedon(justChars, context) { function mangle(ele) { ele.style.textAlign = 'justify'; ele.style.position = 'relative'; var compStyle = getComputedStyle(ele); var lineHeight = compStyle.lineHeight; lineHeight = parseInt(lineHeight.substring(0, lineHeight.length-2)); var height = compStyle.height; height = parseInt(height.substring(0, height.length-2)); var lines = height / lineHeight; var backbase = ele.cloneNode(true); backbase.style.position = 'absolute'; backbase.style.top = '0px'; backbase.style.left = '0px'; if (justChars) { backbase.style.unicodeBidi = 'bidi-override'; backbase.style.direction = 'rtl'; } else { backbase.style.transform = 'scale(-1, 1)'; backbase.style['-webkit-transform'] = 'scale(-1, 1)'; } backbase.style.background = 'white'; for (var i = 1; i < lines; i+=2) { var copy = backbase.cloneNode(true); copy.style.clip = 'rect(' + i*lineHeight + 'px, auto, ' + (i+1)*lineHeight + 'px, auto)'; ele.appendChild(copy); } } var ps = context.querySelectorAll('div.pjgm-postcontent > p'); for (var i = 0; i < ps.length; ++i) { mangle(ps[i]); } } var posts = document.querySelectorAll('div.post'); for (var i = 0; i < posts.length; ++i) { if (posts[i].querySelector('span#boustrophedon')) { boustrophedon(false, posts[i]); } } if(location.host==='unsongbook.com'){(function(){var n,walk=document.createTreeWalker(document.body,NodeFilter.SHOW_TEXT,null,false);while(n=walk.nextNode())n.textContent=n.textContent.replace(/Berenst(a|e)in/g,function(m){return Math.random()<.1?m:(Math.random()<.5?'Berenstain':'Berenstein');}).replace(/BERENST(A|E)IN/g,function(m){return Math.random()<.1?m:(Math.random()<.5?'BERENSTAIN':'BERENSTEIN');});}());} // *** Add clickable markup buttons to comment forms function makeMarkupLinks() { function tag(ele, label) { var l = label.length; return function() { var start = ele.selectionStart; var end = ele.selectionEnd; if (ele.value.slice(start-2-l, start) === '<' + label + '>' && ele.value.slice(end, end+3+l) === '</' + label + '>') { ele.value = ele.value.slice(0, start-2-l) + ele.value.slice(start, end) + ele.value.slice(end+3+l); ele.setSelectionRange(start-2-l, end-2-l); } else { ele.value = ele.value.slice(0, start) + '<' + label + '>' + ele.value.slice(start, end) + '</' + label + '>' + ele.value.slice(end); ele.setSelectionRange(start+2+l, end+2+l); } ele.focus(); }; } var buttons = [ { name: 'Italic', fn: function(ele){ return tag(ele, 'i') } }, { name: 'Bold', fn: function(ele){ return tag(ele, 'b') } }, { name: 'Link', fn: function(ele){ return function() { var start = ele.selectionStart; var end = ele.selectionEnd; var offset = 0; var url = prompt('To where?'); if (url !== null) { if (url.match('"')) url = encodeURI(url); var text = ele.value.slice(start, end); if (start === end) { text = 'link text'; end += text.length; } ele.value = ele.value.slice(0, start) + '<a href="' + url + '">' + text + '</a>' + ele.value.slice(end); offset = 11 + url.length; ele.setSelectionRange(start + offset, end + offset); ele.focus(); } }; } }, { name: 'Quote', fn: function(ele){ return tag(ele, 'blockquote') } }, { name: 'Code', fn: function(ele){ return tag(ele, 'code') } }, { name: 'Strike', fn: function(ele){ return tag(ele, 'strike') } }, ] var rs = document.querySelectorAll('.comment-form-comment, .sce-comment-textarea'); for (var i = 0; i < rs.length; ++i) { var r = rs[i].appendChild(document.createElement('p')); for (var j = 0; j < buttons.length; ++j) { var button = document.createElement('input'); button.type = 'button'; button.value = buttons[j].name; button.style.width = 'auto'; button.style.marginRight = '.4em'; button.tabIndex = -1; button.addEventListener('click', buttons[j].fn(r.parentElement.querySelector('textarea'))); r.appendChild(button); } } } // Default comment expansion options function makeExpandOptions() { // TODO deal with links to comments function showActive() { var comments = document.querySelectorAll('li.comment'); var holders = []; for (var i = 0; i < comments.length; ++i) { var comment = comments[i]; var commentHolder = comment.querySelector('div.commentholder'); holders.push(commentHolder); comment.shouldShow = false; // relies on parents being visited before children if (commentHolder.classList.contains('new-comment')) { var toMark = comment; toMark.shouldShow = true; while (toMark.parentElement.tagName === 'UL') { toMark = toMark.parentElement.parentElement; if (toMark.shouldShow) break; toMark.shouldShow = true; // the top-most comment has parent != UL, but still mark it } } var link = comment.querySelector('.comment-hide-link'); if (link.textContent === 'Show') { commentToggle.call(link, null, true); } } for (var i = 0; i < comments.length; ++i) { var comment = comments[i]; var commentHolder = holders[i]; if (comment.shouldShow || comment.querySelector('div.comment-body').offsetParent === null) { continue; } if (!commentHolder.classList.contains('new-comment')) { var toHide = comment; while (toHide.parentElement.tagName === 'UL' && !toHide.parentElement.parentElement.shouldShow) { toHide = toHide.parentElement.parentElement; } var link = toHide.querySelector('.comment-hide-link'); commentToggle.call(link, null, true); } } } function showNone() { var topComments = document.querySelectorAll('.commentlist > .comment'); for (var i = 0; i < topComments.length; ++i) { var link = topComments[i].querySelector('.comment-hide-link'); if (link.textContent === 'Show') continue; commentToggle.call(link, null, true); } } function showAll() { var comments = document.querySelectorAll('li.comment'); var holders = []; for (var i = 0; i < comments.length; ++i) { var link = comments[i].querySelector('.comment-hide-link'); if (link.textContent === 'Hide') continue; commentToggle.call(link, null, true); } } var styleEle = document.createElement('style'); // TODO inline this in main script styleEle.type = 'text/css'; styleEle.textContent = '' + '.expand-links { font-size: 14px; padding-bottom: 10px; }' + '.expand-links span { padding-right: 10px }'; document.head.appendChild(styleEle); var expandPreference = localStorage.expandPreference; if (expandPreference !== 'all' && expandPreference !== 'active' && expandPreference !== 'none') { expandPreference = localStorage.expandPreference = 'all'; } var newDiv = document.createElement('div'); newDiv.className = 'expand-links'; newDiv.innerHTML = 'Expand (default): '; var allSpan = document.createElement('span') var allLink = document.createElement('a'); allLink.innerHTML = 'All'; allLink.style.textDecoration = 'underline'; allLink.style.cursor = 'pointer'; allLink.addEventListener('click', function(e) { showAll(); }); var allRadio = document.createElement('input'); allRadio.type = 'radio'; allRadio.name = 'expand-radio'; allRadio.value = 'all-radio'; allRadio.checked = expandPreference === 'all'; allRadio.addEventListener('click', function(){ localStorage.expandPreference = 'all'; }); allSpan.appendChild(allLink); allSpan.appendChild(document.createTextNode(' (')); allSpan.appendChild(allRadio); allSpan.appendChild(document.createTextNode(')')); newDiv.appendChild(allSpan); var activeSpan = document.createElement('span') var activeLink = document.createElement('a'); activeLink.innerHTML = 'Active'; activeLink.style.textDecoration = 'underline'; activeLink.style.cursor = 'pointer'; activeLink.addEventListener('click', function(e) { showActive(); }); var activeRadio = document.createElement('input'); activeRadio.type = 'radio'; activeRadio.name = 'expand-radio'; activeRadio.value = 'active-radio'; activeRadio.checked = expandPreference === 'active'; activeRadio.addEventListener('click', function(){ localStorage.expandPreference = 'active'; }); activeSpan.appendChild(activeLink); activeSpan.appendChild(document.createTextNode(' (')); activeSpan.appendChild(activeRadio); activeSpan.appendChild(document.createTextNode(')')); newDiv.appendChild(activeSpan); var noneSpan = document.createElement('span') var noneLink = document.createElement('a'); noneLink.innerHTML = 'None'; noneLink.style.textDecoration = 'underline'; noneLink.style.cursor = 'pointer'; noneLink.addEventListener('click', function(e) { showNone(); }); var noneRadio = document.createElement('input'); noneRadio.type = 'radio'; noneRadio.name = 'expand-radio'; noneRadio.value = 'none-radio'; noneRadio.checked = expandPreference === 'none'; noneRadio.addEventListener('click', function(){ localStorage.expandPreference = 'none'; }); noneSpan.appendChild(noneLink); noneSpan.appendChild(document.createTextNode(' (')); noneSpan.appendChild(noneRadio); noneSpan.appendChild(document.createTextNode(')')); newDiv.appendChild(noneSpan); var list = document.querySelector('.commentlist'); list.parentElement.insertBefore(newDiv, list); // Totally unnecessary, but what the hell. window.addEventListener('storage', function(e) { if (e.key !== 'expandPreference') return; switch (e.newValue) { case 'all': allRadio.checked = true; break; case 'active': activeRadio.checked = true; break; case 'none': noneRadio.checked = true; break; } }); if (expandPreference === 'active') { showActive(); } else if (expandPreference === 'none') { showNone(); } } // Add a link to the page without comments function makeNoCommentsLink() { var utils = document.querySelectorAll('.pjgm-postutility'); if (utils.length === 1) { var utilLinks = utils[0].querySelectorAll('a'); var permalink = utilLinks[utilLinks.length - 1]; if (permalink && permalink.textContent === 'permalink') { var noCommentsLink = document.createElement('a'); noCommentsLink.innerHTML = 'link without comments'; noCommentsLink.href = location.protocol + '//' + location.host + location.pathname + '?comments=false'; noCommentsLink.className = 'sd-button'; noCommentsLink.target = '_blank'; var or = document.createTextNode(' or '); permalink.parentNode.insertBefore(noCommentsLink, permalink.nextSibling); permalink.parentNode.insertBefore(or, noCommentsLink); } } } // Run on pages with comments if (document.querySelector('#comments')) { addUnloadListeners(); makeHighlight(); makeShowHideNewTextParentLinks(); makeMarkupLinks(); if (localStorage.testExpand === 'true') { makeExpandOptions(); } makeNoCommentsLink(); } <file_sep># Slate Star Comments This script adds some features to the comment system at [Slate Star Codex](http://slatestarcodex.com/). In particular: - New comments are highlighted and given the searchable text "\~new\~" so that you can C-f through them in the order they appear on the page. - An expandable box appears in the upper-right, which allows you to set the time after which comments are highlighted and gives you a list of new comments. Clicking an entries in the list will bring you to that entry. - A button to hide a comment and its subthread, appearing at the bottom of every comment. - For nested comments, a link to their parent. Suggestions and pull requests welcome, although I'm very conservative when it comes to changes in the UI.
bdf76d71b4f4f0d51e8ba5add679820908a6f8b5
[ "JavaScript", "Markdown" ]
2
JavaScript
bakkot/SlateStarComments
f2b1ea5925d347fcdf6b80a5da52de5401986dd8
f4783fdc0f2ba3efc6bb686469451fd997c906d0
refs/heads/master
<repo_name>deepek23/Student-Biodata<file_sep>/README.md # Student-Biodata College <file_sep>/WelcomeServlet.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. */ import java.io.IOException; import java.io.PrintWriter; import javax.servlet.ServletContext; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * * @author deepe */ public class WelcomeServlet extends HttpServlet { protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { try { response.setContentType("text/html"); PrintWriter out = response.getWriter(); String n = request.getParameter("username"); out.print("Welcome " + n); out.println("<!DOCTYPE html>\n" + "<html>\n" + "<head>\n" + "<link rel=\"stylesheet\" href=\"https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css\">\n" + "<style>\n" + "* {box-sizing: border-box;}\n" + "\n" + "body {\n" + " margin: 0;\n" + " font-family: Arial, Helvetica, sans-serif;\n" + "}\n" + "\n" + ".topnav {\n" + " overflow: hidden;\n" + " background-color: #e9e9e9;\n" + "}\n" + "\n" + ".topnav a {\n" + " float: left;\n" + " display: block;\n" + " color: black;\n" + " text-align: center;\n" + " padding: 14px 16px;\n" + " text-decoration: none;\n" + " font-size: 17px;\n" + "}\n" + "\n" + ".topnav a:hover {\n" + " background-color: #ddd;\n" + " color: black;\n" + "}\n" + "\n" + ".topnav a.active {\n" + " background-color: #2196F3;\n" + " color: white;\n" + "}\n" + "\n" + ".topnav .login-container {\n" + " float: right;\n" + "}\n" + "\n" + ".topnav input[type=text] {\n" + " padding: 6px;\n" + " margin-top: 8px;\n" + " font-size: 17px;\n" + " border: none;\n" + " width:120px;\n" + "}\n" + "\n" + ".topnav .login-container button {\n" + " float: right;\n" + " padding: 6px 10px;\n" + " margin-top: 8px;\n" + " margin-right: 16px;\n" + " background-color: #555;\n" + " color: white;\n" + " font-size: 17px;\n" + " border: none;\n" + " cursor: pointer;\n" + "}\n" + "\n" + ".topnav .login-container button:hover {\n" + " background-color: green;\n" + "}\n" + "\n" + "@media screen and (max-width: 600px) {\n" + " .topnav .login-container {\n" + " float: none;\n" + " }\n" + " .topnav a, .topnav input[type=text], .topnav .login-container button {\n" + " float: none;\n" + " display: block;\n" + " text-align: left;\n" + " width: 100%;\n" + " margin: 0;\n" + " padding: 14px;\n" + " }\n" + " .topnav input[type=text] {\n" + " border: 1px solid #ccc; \n" + " }\n" + "}\n" + "</style>\n" + "</head>\n" + "<body style=\"background:url(1.gif); background-position: center;background-size: cover;\">\n" + " <form action=\"studentbiodata.html\" method=\"post\">\n" + "<div class=\"topnav\">\n" + " <a class=\"active\" href=\"index.html\">Home</a>\n" + " <a href=\"http://www.cit.edu.in/about-us/\">About</a>\n" + " <a href=\"http://www.cit.edu.in/contact-us/\">Contact</a>\n" + " <div class=\"login-container\">\n" + " <button type=\"submit\">Logout</button>\n" + " </form>\n" + " </div>\n" + "</div>\n" + "\n" + "<div style=\"padding-left:16px\">\n" + " <h2></h2>\n" + " <p></p>\n" + " <p></p>\n" + " <div class=\"banner-head\">\n" + " <h1 style=\"color:#FFC;\">Welcome to</h1>\n" + " <h2 style=\"color:#FFC;\">Coimbatore Institute of Technology</h2>\n" + " <div class=\"seperator\">\n" + " <img src=\"D:\\College\\College\\src\\java\\cit123.JPG\">\n" + " </div>\n" + " <h3 style=\"color:#FFC;\">Maintaining Global Standards and Excellence</h3>\n" + " <!-- <p>\" Nulla consequat massa quis enim.Donec pede justo, fringilla vel, aliquet nec, vulputate eget \"</p>-->\n" + " <div class=\"clearfix\"></div>\n" + " <p></p>\n" + " </div>\n" + " </div>\n" + "</div>\n" + "</form>\n" + "</body>\n" + "</html>\n" + ""); out.println(""); out.println(""); out.println(""); out.println(""); out.println(""); out.println(""); out.println(""); out.println(""); out.println(""); out.println(""); out.println(""); out.print("<br>"); out.print("<a href='SecondServlet?username=" + n + "' style=\"color:red\">Save your Details</a>" + "<br>"); // out.print("<a href='ChecYourDetailServlet?username=" + n + "'>Check your Details</a>"); out.print("<a href='CheckMineServlet?username=" + n + " ' style=\"color:red\">Check your own Details</a>"); out.close(); } catch (Exception e) { System.out.println(e); } } } <file_sep>/CheckMineServlet.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. */ import java.io.IOException; import java.io.PrintWriter; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * * @author deepe */ public class CheckMineServlet extends HttpServlet { protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //processRequest(request, response); PrintWriter out = response.getWriter(); String n = request.getParameter("username"); //int m = Integer.parseInt(request.getParameter("roll")); try { response.setContentType("text/html"); out.print("<form action=\"studentbiodata.html\" method=\"post\">\n" + "<div class=\"topnav\">\n" + " <div class=\"login-container\">\n" + " <a class=\"active\" href=\"index.html\">Home</a>\n" + " <a href=\"http://www.cit.edu.in/about-us/\">About</a>\n" + " <a href=\"http://www.cit.edu.in/contact-us/\">Contact</a>\n" + " <button type=\"submit\">Logout</button>\n" + " </form>\n" + " </div>\n" + "</div>\n" + "\n"); //PrintWriter out = response.getWriter(); //String n = request.getParameter("username"); out.print("Hello " + n ); }catch(Exception e){ out.println(e); } try { Class.forName("org.apache.derby.jdbc.ClientDriver"); //creating connection with the database Connection con = DriverManager.getConnection("jdbc:derby://localhost:1527/cit","root","root"); Statement stmt = con.createStatement(); String sql,sql2; sql = ("select name,father,mother,bloodgroup,aadhar,gender from personal where username='"+n+"'"); ResultSet rs = stmt.executeQuery(sql); while(rs.next()){ //Retrieve by column name String name = rs.getString("name"); String father = rs.getString("father"); String mother = rs.getString("mother"); String bloodgroup = rs.getString("bloodgroup"); String aadhar = rs.getString("aadhar"); String gender = rs.getString("gender"); //Display values out.println("<br><br>"); out.println("Name: " + name + "<br>"); out.println("Fathers Name: " + father + "<br>"); out.println("Mother: " + mother + "<br>"); out.println("Bloodgroup: " + bloodgroup + "<br>"); out.println("Aadhar: " + aadhar + "<br>"); out.println("Gender: " + gender + "<br>"); out.println("<br><br>"); } out.println("</body></html>"); // Clean-up environment rs.close(); stmt.close(); con.close(); } catch(Exception se) { //Handle errors for JDBC se.printStackTrace(); } out.println("<!DOCTYPE html>\n" + "<html>\n" + "<head>\n" + "<link rel=\"stylesheet\" href=\"https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css\">\n" + "<style>\n" + "* {box-sizing: border-box;}\n" + "\n" + "body {\n" + " margin: 0;\n" + " font-family: Arial, Helvetica, sans-serif;\n" + "}\n" + "\n" + ".topnav {\n" + " overflow: hidden;\n" + " background-color: #e9e9e9;\n" + "}\n" + "\n" + ".topnav a {\n" + " float: left;\n" + " display: block;\n" + " color: black;\n" + " text-align: center;\n" + " padding: 14px 16px;\n" + " text-decoration: none;\n" + " font-size: 17px;\n" + "}\n" + "\n" + ".topnav a:hover {\n" + " background-color: #ddd;\n" + " color: black;\n" + "}\n" + "\n" + ".topnav a.active {\n" + " background-color: #2196F3;\n" + " color: white;\n" + "}\n" + "\n" + ".topnav .login-container {\n" + " float: right;\n" + "}\n" + "\n" + ".topnav input[type=text] {\n" + " padding: 6px;\n" + " margin-top: 8px;\n" + " font-size: 17px;\n" + " border: none;\n" + " width:120px;\n" + "}\n" + "\n" + ".topnav .login-container button {\n" + " float: right;\n" + " padding: 6px 10px;\n" + " margin-top: 8px;\n" + " margin-right: 16px;\n" + " background-color: #555;\n" + " color: white;\n" + " font-size: 17px;\n" + " border: none;\n" + " cursor: pointer;\n" + "}\n" + "\n" + ".topnav .login-container button:hover {\n" + " background-color: green;\n" + "}\n" + "\n" + "@media screen and (max-width: 600px) {\n" + " .topnav .login-container {\n" + " float: none;\n" + " }\n" + " .topnav a, .topnav input[type=text], .topnav .login-container button {\n" + " float: none;\n" + " display: block;\n" + " text-align: left;\n" + " width: 100%;\n" + " margin: 0;\n" + " padding: 14px;\n" + " }\n" + " .topnav input[type=text] {\n" + " border: 1px solid #ccc; \n" + " }\n" + "}\n" + "</style>\n" + "</head>\n" + "<body style=\"background:url(1.gif); background-position: center;background-size: cover;\">\n" + " <form action=\"studentbiodata.html\" method=\"post\">\n" + "\n" + "<div style=\"padding-left:16px\">\n" + " <h2></h2>\n" + " <p></p>\n" + " <p></p>\n" + " <div class=\"banner-head\">\n" + " <h1 style=\"color:#FFC;\"></h1>\n" + " <h2 style=\"color:#FFC;\"></h2>\n" + " <div class=\"seperator\">\n" + " <img src=\"D:\\College\\College\\src\\java\\cit123.JPG\">\n" + " </div>\n" + " <h3 style=\"color:#FFC;\"></h3>\n" + " <!-- <p>\" Nulla consequat massa quis enim.Donec pede justo, fringilla vel, aliquet nec, vulputate eget \"</p>-->\n" + " <div class=\"clearfix\"></div>\n" + " <p></p>\n" + " </div>\n" + " </div>\n" + "</div>\n" + "</form>\n" + "</body>\n" + "</html>\n" + ""); } @Override public String getServletInfo() { return "Short description"; }// </editor-fold> } <file_sep>/SecondServlet.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. */ import java.io.IOException; import java.io.PrintWriter; import javax.servlet.ServletContext; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * * @author deepe */ public class SecondServlet extends HttpServlet { @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { PrintWriter out = response.getWriter(); try { response.setContentType("text/html"); //PrintWriter out = response.getWriter(); String n = request.getParameter("username"); //String m = request.getParameter("roll"); // ServletContext context=getServletContext(); // String o =(String)context.getAttribute("m"); //int newm = Integer.parseInt(m); out.print("<form action='studentbiodata.html' method='post'>"+"<div class='topnav'>"+"<div class='login-container'>"+"<button type='submit'>Logout</button>"+"</form>"+"</div>"+"</div>"); out.print("Hello " + n ); out.print("<br>"); out.print("<body>\n" + " <marquee>Edit and Save Your Details</marquee>\n" + " </body>"); /* out.println is used to print on the client web browser */ out.println("<link rel='stylesheet' type='text/css' href='biodatas.css' />"); out.println("<form action=\"Biodata\" method=\"post\">"); //out.println("<form action='SecondServlet?username=" + n + "' >); out.println("<body>"); out.println("<h3>STUDENT BIODATA FORM</h3>"); out.println("<table align=\"center\" cellpadding = \"5\">"); out.println("<tr>\n" + "<td>NAME</td>\n" + "<td><input type=\"text\" name=\"name\" maxlength=\"30\"/>\n" + "</td>\n" + "</tr>"); out.println("<tr>\n" + "<td>ROLL NUMBER</td>\n" + "<td><input type=\"text\" name=\"roll\" maxlength=\"30\"/>\n" + "</td>\n" + "</tr>"); out.println("<tr>\n" + "<td>FATHER'S NAME</td>\n" + "<td><input type=\"text\" name=\"father\" maxlength=\"30\"/>\n" + "</td>\n" + "</tr>\n" + "<tr>\n" + "<td>MOTHER'S NAME</td>\n" + "<td><input type=\"text\" name=\"mother\" maxlength=\"30\"/>\n" + "\n" + "</td>\n" + "</tr>"); out.println("<tr>\n" + "<td>BLOOD GROUP</td>\n" + " \n" + "<td>\n" + "<select name=\"bloodgroup\" id=\"bloodgroup\">\n" + "<option value=\"-1\">Select</option>\n" + "<option value=\"A+\">A+</option>\n" + "<option value=\"A-\">A-</option>\n" + "<option value=\"B+\">B+</option>\n" + " \n" + "<option value=\"B-\">B-</option>\n" + "<option value=\"O+\">O+</option>\n" + "<option value=\"O-\">O-</option>\n" + "<option value=\"AB+\">AB+</option>\n" + "<option value=\"AB-\">AB-</option>\n" + "</select>\n" + " \n" + "</td>\n" + "</tr>"); out.println("<tr>\n" + "<td>EMAIL ID</td>\n" + "<td><input type=\"text\" name=\"email\" maxlength=\"100\" /></td>\n" + "</tr>"); out.println("<tr>\n" + "<td>AADHAR NUMBER</td>\n" + "<td>\n" + "<input type=\"text\" name=\"aadhar\"/>\n" + "</td>\n" + "</tr>"); out.println("<tr>\n" + "<td>GENDER</td>\n" + "<td>\n" + "Male <input type=\"radio\" name=\"gender\" value=\"Male\" />\n" + "Female <input type=\"radio\" name=\"gender\" value=\"Female\" />\n" + "</td>\n" + "</tr>"); out.println("<tr>\n" + "<td>ADDRESS <br /><br /><br /></td>\n" + "<td><textarea name=\"Address\" rows=\"4\" cols=\"30\"></textarea></td>\n" + "</tr>"); out.println("<tr>\n" + "<td>CITY</td>\n" + "<td><input type=\"text\" name=\"city\" maxlength=\"30\" />\n" + "(max 30 characters a-z and A-Z)\n" + "</td>\n" + "</tr>"); out.println("<tr>\n" + "<td>PIN CODE</td>\n" + "<td><input type=\"text\" name=\"pin\" maxlength=\"6\" />\n" + "(6 digit number)\n" + "</td>\n" + "</tr>"); out.println("<tr>\n" + "<td>STATE</td>\n" + "<td><input type=\"text\" name=\"state\" maxlength=\"30\" />\n" + "(max 30 characters a-z and A-Z)\n" + "</td>\n" + "</tr>"); out.println("<tr>\n" + "<td>COUNTRY</td>\n" + "<td><input type=\"text\" name=\"country\" /></td>\n" + "</tr>"); out.println("<tr>\n" + "<td>MOBILE NUMBER</td>\n" + "<td><input type=\"text\" name=\"mobile\" maxlength=\"30\"/>\n" + "</td>\n" + "</tr>"); out.println("<tr>\n" + "<td>Userame</td>\n" + "<td><input type=\"text\" name=\"username\" maxlength=\"30\"/>\n" + "</td>\n" + "</tr>"); out.println("<tr>\n" + "<td>QUALIFICATION <br /><br /><br /><br /><br /><br /><br /></td>\n" + " \n" + "<td>\n" + "<table>\n" + " \n" + "<tr>\n" + "<td align=\"center\"><b>Sl.No.</b></td>\n" + "<td align=\"center\"><b>Examination</b></td>\n" + "<td align=\"center\"><b>Board</b></td>\n" + "<td align=\"center\"><b>Percentage</b></td>\n" + "<td align=\"center\"><b>Year of Passing</b></td>\n" + "</tr>"); out.println("<tr>\n" + "<td>1</td>\n" + "<td>Class X</td>\n" + "<td><input type=\"text\" name=\"ClassX_Board\" maxlength=\"30\" /></td>\n" + "<td><input type=\"text\" name=\"ClassX_Percentage\" maxlength=\"30\" /></td>\n" + "<td><input type=\"text\" name=\"ClassX_YrOfPassing\" maxlength=\"30\" /></td>\n" + "</tr>"); out.println("<tr>\n" + "<td>2</td>\n" + "<td>Class XII</td>\n" + "<td><input type=\"text\" name=\"ClassXII_Board\" maxlength=\"30\" /></td>\n" + "<td><input type=\"text\" name=\"ClassXII_Percentage\" maxlength=\"30\" /></td>\n" + "<td><input type=\"text\" name=\"ClassXII_YrOfPassing\" maxlength=\"30\" /></td>\n" + "</tr>"); out.println("<tr>\n" + "<td>3</td>\n" + "<td>Graduation</td>\n" + "<td><input type=\"text\" name=\"Graduation_Board\" maxlength=\"30\" /></td>\n" + "<td><input type=\"text\" name=\"Graduation_Percentage\" maxlength=\"30\" /></td>\n" + "<td><input type=\"text\" name=\"Graduation_YrOfPassing\" maxlength=\"30\" /></td>\n" + "</tr>"); out.println("<tr>\n" + "<td>4</td>\n" + "<td>Masters</td>\n" + "<td><input type=\"text\" name=\"Masters_Board\" maxlength=\"30\" /></td>\n" + "<td><input type=\"text\" name=\"Masters_Percentage\" maxlength=\"30\" /></td>\n" + "<td><input type=\"text\" name=\"Masters_YrOfPassing\" maxlength=\"30\" /></td>\n" + "</tr>"); out.println("<tr>\n" + "<td></td>\n" + "<td></td>\n" + "<td align=\"center\">(10 char max)</td>\n" + "<td align=\"center\">(upto 2 decimal)</td>\n" + "</tr>\n" + "</table>\n" + " \n" + "</td>\n" + "</tr>"); out.println("<tr>\n" + "<td colspan=\"2\" align=\"center\">\n" + "<input type=\"submit\" value=\"Save\">\n" + "<input type=\"reset\" value=\"Reset\">\n" + "</td>\n" + "</tr>"); out.println("</table>\n" + " \n" + "</form>\n" + " \n" + "</body>\n" + "</html>"); out.println(""); out.println(""); out.println(""); out.println(""); out.println(""); out.println(""); out.println(""); out.println(""); out.println(""); out.println(""); out.println(""); out.println(""); out.close(); } catch (Exception e) { System.out.println(e); } /* out.print("<table width=100% border=1>"); String roll = request.getParameter("roll"); String name = request.getParameter("name"); String father = request.getParameter("father"); String mother = request.getParameter("mother"); String bloodgroup = request.getParameter("bloodgroup"); String aadhar = request.getParameter("aadhar"); String gender = request.getParameter("gender"); String email = request.getParameter("email"); String address = request.getParameter("address"); String city = request.getParameter("city"); String pin = request.getParameter("pin"); String state = request.getParameter("state"); String country = request.getParameter("country"); String mobile = request.getParameter("mobile"); String ClassX_Board = request.getParameter("ClassX_Board"); String ClassX_Percentage = request.getParameter("ClassX_Percentage"); String ClassX_YrOfPassing = request.getParameter("ClassX_YrOfPassing"); String ClassXII_Board = request.getParameter("ClassXII_Board"); String ClassXII_Percentage = request.getParameter("ClassXII_Percentage"); String ClassXII_YrOfPassing = request.getParameter("ClassXII_YrOfPassing"); String Graduation_Board = request.getParameter("Graduation_Board"); String Graduation_Percentage = request.getParameter("Graduation_Percentage"); String Graduation_YrOfPassing = request.getParameter("Graduation_YrOfPassing"); String Masters_Board = request.getParameter("Masters_Board"); String Masters_Percentage = request.getParameter("Masters_Percentage"); String Masters_YrOfPassing = request.getParameter("Masters_YrOfPassing"); PrintWriter writer = response.getWriter(); String htmlresponse = "<html>"; htmlresponse +="<table align='center' cellpadding = '10'>"; htmlresponse += "<tr><td>NAME</td><td>"+name+"</td></tr>"; htmlresponse += "<tr><td>ROLL NUMBER</td><td>"+roll +"</td></tr>"; htmlresponse += "<tr><td>Father's Name</td><td>"+father+"</td></tr>"; htmlresponse += "<tr><td>Mother's Name</td><td>"+mother+"</td></tr>"; htmlresponse += "<tr><td>Blood Group</td><td>"+bloodgroup+"</td></tr>"; htmlresponse += "<tr><td>EmailId</td><td>"+email+"</td></tr>"; htmlresponse += "<tr><td>AadharNo</td><td>"+aadhar+"</td></tr>"; htmlresponse += "<tr><td>Gender</td><td>"+gender+"</td></tr>"; htmlresponse += "<tr>" +"<td>ADDRESS <br /><br /><br /></td></tr>"; htmlresponse += "<tr><td>City</td><td>"+city+"</td></tr>"; htmlresponse += "<tr><td>State</td><td>"+state+"</td></tr>"; htmlresponse += "<tr><td>Country</td><td>"+country+"</td></tr>"; htmlresponse += "<tr><td>PinCode</td><td>"+pin+"</td></tr>"; htmlresponse += "<tr><td>Mobile NO</td><td>"+mobile+"</td></tr>"; htmlresponse += "<tr><td>Qualification<br /><br /><br /><br /><br /><br /></td></tr>"; htmlresponse += "<tr><td>EmailId</td><td>"+email+"</td></tr>"; htmlresponse += "<tr><td>Mobile</td><td>"+mobile+"</td></tr>"; htmlresponse += "<tr>" +"<td>QUALIFICATION <br /><br /><br /><br /><br /><br /><br /></td>" +"<td>" +"<table>"; /* htmlresponse += "<h2>Name: " + name + "<br>"; htmlresponse += "<h2>Name: " + name + "<br>"; htmlresponse += "<h2>Name: " + name + "<br>"; htmlresponse += "<h2>Name: " + name + "<br>"; htmlresponse += "<h2>Name: " + name + "<br>"; htmlresponse += "<h2>Name: " + name + "<br>"; htmlresponse += "<h2>Name: " + name + "<br>"; htmlresponse += "<h2>Name: " + name + "<br>"; htmlresponse += "<h2>Name: " + name + "<br>"; htmlresponse += "<h2>Name: " + name + "<br>"; htmlresponse += "<h2>Name: " + name + "<br>";*/ //htmlresponse +="</html>"; //writer.println(htmlresponse); } @Override public String getServletInfo() { return "Short description"; }// </editor-fold> } <file_sep>/Register.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. */ import java.io.IOException; import java.io.PrintWriter; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import javax.servlet.RequestDispatcher; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * * @author deepe */ public class Register extends HttpServlet { protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { PrintWriter out = response.getWriter(); String firstname=request.getParameter("fname"); String surname=request.getParameter("lname"); String father=request.getParameter("father"); int roll=Integer.parseInt(request.getParameter("roll")); String mobile=request.getParameter("mobile"); String course=request.getParameter("course"); String username=request.getParameter("username"); String password=request.getParameter("password"); String day=request.getParameter("day"); String month=request.getParameter("month"); String year=request.getParameter("year"); String gender=request.getParameter("gender"); try{ Class.forName("org.apache.derby.jdbc.ClientDriver"); Connection con=DriverManager.getConnection("jdbc:derby://localhost:1527/cit","root","root"); PreparedStatement ps=con.prepareStatement( "insert into register values(?,?,?,?,?,?,?,?,?,?,?,?)"); ps.setString(1,firstname); ps.setString(2,surname); ps.setString(3,father); ps.setInt(4,roll); ps.setString(5,mobile); ps.setString(6,course); ps.setString(7,username); ps.setString(8,password); ps.setString(9,day); ps.setString(10,month); ps.setString(11,year); ps.setString(12,gender); int i=ps.executeUpdate(); if(i>0) out.println("You are successfully registered..."); RequestDispatcher rs = request.getRequestDispatcher("studentbiodata.html"); rs.forward(request, response); out.println("You are successfully registered..."); }catch (Exception e2) {out.println(e2);} } @Override public String getServletInfo() { return "Short description"; }// </editor-fold> }
c8417ac775c33278c9432001a91d1e31e689e8bc
[ "Markdown", "Java" ]
5
Markdown
deepek23/Student-Biodata
8d18554fa54f09ec2eeb5d61258a7d85b0d157a7
41a7391cab6804f3718083ad0b8d5f8273fa9668
refs/heads/master
<repo_name>leitian123/update-location-settings<file_sep>/requirements.txt certifi==2019.9.11 chardet==3.0.4 idna==2.8 pyaml==19.4.1 PyYAML==5.1.2 requests==2.22.0 urllib3==1.25.7 <file_sep>/update-location-settings.py import requests import sys import json import os import time import logging from logging.handlers import TimedRotatingFileHandler import yaml requests.packages.urllib3.disable_warnings() from requests.packages.urllib3.exceptions import InsecureRequestWarning def get_logger(logfile, level): ''' Create a logger ''' if logfile is not None: ''' Create the log directory if it doesn't exist ''' fldr = os.path.dirname(logfile) if not os.path.exists(fldr): os.makedirs(fldr) logger = logging.getLogger() logger.setLevel(level) log_format = '%(asctime)s | %(levelname)-8s | %(funcName)-20s | %(lineno)-3d | %(message)s' formatter = logging.Formatter(log_format) file_handler = TimedRotatingFileHandler(logfile, when='midnight', backupCount=7) file_handler.setFormatter(formatter) file_handler.setLevel(level) logger.addHandler(file_handler) return logger return None class Authentication: @staticmethod def get_jsessionid(vmanage_host, vmanage_port, username, password): api = "/j_security_check" base_url = "https://%s:%s"%(vmanage_host, vmanage_port) url = base_url + api payload = {'j_username' : username, 'j_password' : <PASSWORD>} response = requests.post(url=url, data=payload, verify=False) try: cookies = response.headers["Set-Cookie"] jsessionid = cookies.split(";") return(jsessionid[0]) except: if logger is not None: logger.error("No valid JSESSION ID returned\n") exit() @staticmethod def get_token(vmanage_host, vmanage_port, jsessionid): headers = {'Cookie': jsessionid} base_url = "https://%s:%s"%(vmanage_host, vmanage_port) api = "/dataservice/client/token" url = base_url + api response = requests.get(url=url, headers=headers, verify=False) if response.status_code == 200: return(response.text) else: return None class update_location: def __init__(self, vmanage_host, vmanage_port, jsessionid, token): base_url = "https://%s:%s/dataservice/"%(vmanage_host, vmanage_port) self.base_url = base_url self.jsessionid = jsessionid self.token = token def get_device_templateid(self,device_template_name): if self.token is not None: headers = {'Cookie': self.jsessionid, 'X-XSRF-TOKEN': self.token} else: headers = {'Cookie': self.jsessionid} api = "template/device" url = self.base_url + api template_id_response = requests.get(url=url, headers=headers, verify=False) device_info = dict() if template_id_response.status_code == 200: items = template_id_response.json()['data'] template_found=0 if logger is not None: logger.info("\nFetching Template uuid of %s"%device_template_name) print("\nFetching Template uuid of %s"%device_template_name) for item in items: if item['templateName'] == device_template_name: device_info["device_template_id"] = item['templateId'] device_info["device_type"] = item["deviceType"] template_found=1 return(device_info) if template_found==0: if logger is not None: logger.error("\nDevice Template is not found") print("\nDevice Template is not found") exit() else: if logger is not None: logger.error("\nDevice Template is not found " + str(template_id_response.text)) print("\nError fetching list of templates") exit() def get_attached_devices(self,device_template_id): if self.token is not None: headers = {'Content-Type': "application/json",'Cookie': self.jsessionid, 'X-XSRF-TOKEN': self.token} else: headers = {'Content-Type': "application/json",'Cookie': self.jsessionid} api = "template/device/config/attached/%s"%device_template_id url = self.base_url + api device_ids = requests.get(url=url,headers=headers,verify=False) if device_ids.status_code == 200: items = device_ids.json()['data'] device_uuid = list() for i in range(len(items)): device_uuid.append(items[i]['uuid']) return device_uuid else: print("\nError retrieving attached devices") if logger is None: print("\nError retrieving attached devices " + str(device_template_edit_res.text)) exit() def push_device_template(self,device_info,device_uuids,loc_parameters): if self.token is not None: headers = {'Content-Type': "application/json",'Cookie': self.jsessionid, 'X-XSRF-TOKEN': self.token} else: headers = {'Content-Type': "application/json",'Cookie': self.jsessionid} device_template_id = device_info["device_template_id"] # Fetching Device csv values if logger is not None: logger.info("\nFetching device csv values") print("\nFetching device csv values") payload = { "templateId":device_template_id, "deviceIds":device_uuids, "isEdited":False, "isMasterEdited":False } payload = json.dumps(payload) api = "template/device/config/input/" url = self.base_url + api device_csv_res = requests.post(url=url, data=payload,headers=headers, verify=False) if device_csv_res.status_code == 200: device_csv_values = device_csv_res.json()['data'] else: if logger is not None: logger.error("\nError getting device csv values" + str(device_csv_res.text)) print("\nError getting device csv values") exit() # Adding the values to device specific variables temp = device_csv_values for item1 in temp: sys_ip = item1["csv-deviceIP"] for item2 in loc_parameters: if sys_ip == item2["device_sys_ip"]: item1["//system/location"] = item2["loc_name"] item1["//system/gps-location/latitude"] = item2["latitude"] item1["//system/gps-location/longitude"] = item2["longitude"] break else: continue if logger is not None: logger.info("\nUpdated device csv values are" + str(temp)) device_csv_values = temp # Updating Device CSV values print("\nUpdating Device CSV values") if logger is not None: logger.info("\nUpdating Device CSV values") payload = { "deviceTemplateList":[ { "templateId":device_template_id, "device":device_csv_values, "isEdited":False, "isMasterEdited":False }] } payload = json.dumps(payload) api = "template/device/config/attachfeature" url = self.base_url + api attach_template_res = requests.post(url=url, data=payload,headers=headers, verify=False) if attach_template_res.status_code == 200: attach_template_pushid = attach_template_res.json()['id'] else: if logger is not None: logger.error("\nUpdating Device CSV values failed, "+str(attach_template_res.text)) print("\nUpdating Device CSV values failed") exit() # Fetch the status of template push api = "device/action/status/%s"%attach_template_pushid url = self.base_url + api while(1): template_status_res = requests.get(url,headers=headers,verify=False) if template_status_res.status_code == 200: if template_status_res.json()['summary']['status'] == "done": print("\nUpdated Location parameters") if logger is not None: logger.info("\nUpdated Location parameters") return else: if logger is not None: logger.error("\nUpdating Location parameters failed " + str(template_status_res.text)) print("\nUpdating Location parameters failed") exit() if __name__ == "__main__": try: log_level = logging.DEBUG logger = get_logger("log/location_logs.txt", log_level) if logger is not None: logger.info("Loading configuration details from YAML\n") print("Loading configuration details from YAML\n") with open("config_details.yaml") as f: config = yaml.safe_load(f.read()) vmanage_host = config["vmanage_host"] vmanage_port = config["vmanage_port"] vmanage_username = config["vmanage_username"] vmanage_password = config["<PASSWORD>"] device_template_name = config["device_template_name"] Auth = Authentication() jsessionid = Auth.get_jsessionid(vmanage_host,vmanage_port,vmanage_username,vmanage_password) token = Auth.get_token(vmanage_host,vmanage_port,jsessionid) location_settings = update_location(vmanage_host,vmanage_port,jsessionid, token) loc_parameters = list() # Loop over edge routers to update location parameters for device in config["devices"]: print("Device: {}".format(device["system_ip"])) loc_name = device["location_name"] latitude = device["latitude"] longitude = device["longitude"] temp_parameters = { "device_sys_ip": device["system_ip"], "loc_name": device["location_name"], "latitude": device['latitude'], "longitude": device['longitude'] } loc_parameters.append(temp_parameters) if logger is not None: logger.info("\location parameters are " + str(loc_parameters)) device_info = location_settings.get_device_templateid(device_template_name) device_uuids = location_settings.get_attached_devices(device_info["device_template_id"]) location_settings.push_device_template(device_info,device_uuids,loc_parameters) except Exception as e: print(e) <file_sep>/README.md # Update Location Settings # Objective * How to use vManage REST APIs to update location name and GPS settings of vEdge or cEdge router. # Requirements To use this code you will need: * Python 3.7+ * vManage user login details. (User should have privilege level to edit device template) * vEdge or cEdge routers with device template attached. # Install and Setup - Clone the code to local machine. ``` git clone https://github.com/suchandanreddy/update-location-settings.git cd update-location-settings ``` - Setup Python Virtual Environment (requires Python 3.7+) ``` python3.7 -m venv venv source venv/bin/activate pip3 install -r requirements.txt ``` - Create config_details.yaml using below sample format to update the environment variables for vManage login details and Location parameters ## Example: ``` # vManage Connectivity Info vmanage_host: vmanage_port: vmanage_username: vmanage_password: # Device template Info device_template_name: # Network Routers devices: - system_ip: location_name: latitude: longitude: - system_ip: location_name: latitude: longitude: ``` After setting the env variables, run the python script `update-location-settings.py` `update-location-settings.py` script does the below steps in sequence. ## Workflow - Fetch the device template-id associated with the device template name. - Retrieve device uuids of the attached devices to the device template. - Update the location parameters using the values from config_details.yaml file ## Restrictions - vEdge or cEdge should be in vManage mode with device template attached which contains System feature template with device specific variables for location name, latitude and longitude ## Sample output ``` $python3 update-location-settings.py Loading configuration details from YAML Device: 1.1.1.5 Fetching Template uuid of BR1-CSR-1000v-AMP Fetching device csv values Updating Device CSV values Updated Location parameters ```
719288b02ac43fdcba9648ebffb44495c5e14ea7
[ "Markdown", "Python", "Text" ]
3
Text
leitian123/update-location-settings
5eea7c4ac11d4ad78ff78f0b4fb079e45f55fb4b
9aca8512a664bfce1b6c0c136fbe9c7643300e06
refs/heads/master
<file_sep>(function() { var $imgs = $('ul#trip li a img'); var $search = $('#box'); var cache = []; $imgs.each(function() { cache.push({ element: this, text: this.title.trim().toLowerCase() }); }); function filter() { var query = this.value.trim().toLowerCase() cache.forEach(function(cacheItem) { var index = 0; if (query) { index = cacheItem.text.indexOf(query); } $(cacheItem.element).parent().parent().toggle(index != -1); }); } if ('oninput' in $search[0]) { $search.on('input', filter); } else { $search.on('keyup', filter); } }());<file_sep># Project_Four Interactive Photo Gallery
9eee9b1a9516f01eca3dc3786d80af08bbc0b90c
[ "JavaScript", "Markdown" ]
2
JavaScript
tech-mills/Project_Four
d4eab42e367e9621a17e102d3bbf4cb05c3aaea6
8033b5690f110cab2b6ce54be03f59f3a17f3d26
refs/heads/master
<file_sep><?php namespace GestionFraisBundle\Controller; use Symfony\Component\HttpFoundation\Request; use Symfony\Bundle\FrameworkBundle\Controller\Controller; use GestionFraisBundle\Entity\EtatFicheFrais; use GestionFraisBundle\Form\EtatFicheFraisType; /** * EtatFicheFrais controller. * */ class EtatFicheFraisController extends Controller { /** * Lists all EtatFicheFrais entities. * */ public function indexAction() { $em = $this->getDoctrine()->getManager(); $entities = $em->getRepository('GestionFraisBundle:EtatFicheFrais')->findAll(); return $this->render('GestionFraisBundle:EtatFicheFrais:index.html.twig', array( 'entities' => $entities, )); } /** * Creates a new EtatFicheFrais entity. * */ public function createAction(Request $request) { $entity = new EtatFicheFrais(); $form = $this->createCreateForm($entity); $form->handleRequest($request); if ($form->isValid()) { $em = $this->getDoctrine()->getManager(); $em->persist($entity); $em->flush(); return $this->redirect($this->generateUrl('etatfichefrais_show', array('id' => $entity->getId()))); } return $this->render('GestionFraisBundle:EtatFicheFrais:new.html.twig', array( 'entity' => $entity, 'form' => $form->createView(), )); } /** * Creates a form to create a EtatFicheFrais entity. * * @param EtatFicheFrais $entity The entity * * @return \Symfony\Component\Form\Form The form */ private function createCreateForm(EtatFicheFrais $entity) { $form = $this->createForm(new EtatFicheFraisType(), $entity, array( 'action' => $this->generateUrl('etatfichefrais_create'), 'method' => 'POST', )); $form->add('submit', 'submit', array('label' => 'Create')); return $form; } /** * Displays a form to create a new EtatFicheFrais entity. * */ public function newAction() { $entity = new EtatFicheFrais(); $form = $this->createCreateForm($entity); return $this->render('GestionFraisBundle:EtatFicheFrais:new.html.twig', array( 'entity' => $entity, 'form' => $form->createView(), )); } /** * Finds and displays a EtatFicheFrais entity. * */ public function showAction($id) { $em = $this->getDoctrine()->getManager(); $entity = $em->getRepository('GestionFraisBundle:EtatFicheFrais')->find($id); if (!$entity) { throw $this->createNotFoundException('Unable to find EtatFicheFrais entity.'); } $deleteForm = $this->createDeleteForm($id); return $this->render('GestionFraisBundle:EtatFicheFrais:show.html.twig', array( 'entity' => $entity, 'delete_form' => $deleteForm->createView(), )); } /** * Displays a form to edit an existing EtatFicheFrais entity. * */ public function editAction($id) { $em = $this->getDoctrine()->getManager(); $entity = $em->getRepository('GestionFraisBundle:EtatFicheFrais')->find($id); if (!$entity) { throw $this->createNotFoundException('Unable to find EtatFicheFrais entity.'); } $editForm = $this->createEditForm($entity); $deleteForm = $this->createDeleteForm($id); return $this->render('GestionFraisBundle:EtatFicheFrais:edit.html.twig', array( 'entity' => $entity, 'edit_form' => $editForm->createView(), 'delete_form' => $deleteForm->createView(), )); } /** * Creates a form to edit a EtatFicheFrais entity. * * @param EtatFicheFrais $entity The entity * * @return \Symfony\Component\Form\Form The form */ private function createEditForm(EtatFicheFrais $entity) { $form = $this->createForm(new EtatFicheFraisType(), $entity, array( 'action' => $this->generateUrl('etatfichefrais_update', array('id' => $entity->getId())), 'method' => 'PUT', )); $form->add('submit', 'submit', array('label' => 'Update')); return $form; } /** * Edits an existing EtatFicheFrais entity. * */ public function updateAction(Request $request, $id) { $em = $this->getDoctrine()->getManager(); $entity = $em->getRepository('GestionFraisBundle:EtatFicheFrais')->find($id); if (!$entity) { throw $this->createNotFoundException('Unable to find EtatFicheFrais entity.'); } $deleteForm = $this->createDeleteForm($id); $editForm = $this->createEditForm($entity); $editForm->handleRequest($request); if ($editForm->isValid()) { $em->flush(); return $this->redirect($this->generateUrl('etatfichefrais_edit', array('id' => $id))); } return $this->render('GestionFraisBundle:EtatFicheFrais:edit.html.twig', array( 'entity' => $entity, 'edit_form' => $editForm->createView(), 'delete_form' => $deleteForm->createView(), )); } /** * Deletes a EtatFicheFrais entity. * */ public function deleteAction(Request $request, $id) { $form = $this->createDeleteForm($id); $form->handleRequest($request); if ($form->isValid()) { $em = $this->getDoctrine()->getManager(); $entity = $em->getRepository('GestionFraisBundle:EtatFicheFrais')->find($id); if (!$entity) { throw $this->createNotFoundException('Unable to find EtatFicheFrais entity.'); } $em->remove($entity); $em->flush(); } return $this->redirect($this->generateUrl('etatfichefrais')); } /** * Creates a form to delete a EtatFicheFrais entity by id. * * @param mixed $id The entity id * * @return \Symfony\Component\Form\Form The form */ private function createDeleteForm($id) { return $this->createFormBuilder() ->setAction($this->generateUrl('etatfichefrais_delete', array('id' => $id))) ->setMethod('DELETE') ->add('submit', 'submit', array('label' => 'Delete')) ->getForm() ; } } <file_sep><?php namespace GestionFraisBundle\Entity; use Doctrine\ORM\Mapping as ORM; /** * LigneFraisForfait * * @ORM\Table() * @ORM\Entity(repositoryClass="GestionFraisBundle\Entity\LigneFraisForfaitRepository") */ class LigneFraisForfait { /** * @var integer * * @ORM\Id * * @ORM\Column(name="idVisiteur", type="integer") * * @ORM\OneToOne(targetEntity="Fichefrais") * @ORM\JoinColumn(name="$idVisiteur", referencedColumnName="idVisiteur") */ private $idVisiteur; /** * @var \string * * @ORM\Id * * @ORM\Column(name="mois", type="string", length=6) * * @ORM\OneToOne(targetEntity="Fichefrais") * @ORM\JoinColumn(name="$mois", referencedColumnName="mois") */ private $mois; /** * @var integer * * @ORM\Id * * @ORM\Column(name="idFraisForfait", type="integer") * * @ORM\ManyToOne(targetEntity="FraisForfait") * @ORM\JoinColumn(name="$id", referencedColumnName="id") */ private $idFraisForfait; /** * @var float * * @ORM\Column(name="quantite", type="float") */ private $quantite; /** * @var integer * * @ORM\Column(name="idEtatLigneFrais", type="integer") * * @ORM\ManyToOne(targetEntity="EtatLigneFrais") * @ORM\JoinColumn(name="$id", referencedColumnName="id") */ private $idEtatLigneFrais; /** * Set idVisiteur * * @param integer $idVisiteur * * @return LigneFraisForfait */ public function setIdVisiteur($idVisiteur) { $this->idVisiteur = $idVisiteur; return $this; } /** * Get idVisiteur * * @return integer */ public function getIdVisiteur() { return $this->idVisiteur; } /** * Set mois * * @param \string $mois * * @return LigneFraisForfait */ public function setMois($mois) { $this->mois = $mois; return $this; } /** * Get mois * * @return \string */ public function getMois() { return $this->mois; } /** * Set idFraisForfait * * @param integer $idFraisForfait * * @return LigneFraisForfait */ public function setIdFraisForfait($idFraisForfait) { $this->idFraisForfait = $idFraisForfait; return $this; } /** * Get idFraisForfait * * @return integer */ public function getIdFraisForfait() { return $this->idFraisForfait; } /** * Set quantite * * @param float $quantite * * @return LigneFraisForfait */ public function setQuantite($quantite) { $this->quantite = $quantite; return $this; } /** * Get quantite * * @return float */ public function getQuantite() { return $this->quantite; } /** * Set idEtatLigneFrais * * @param integer $idEtatLigneFrais * * @return LigneFraisForfait */ public function setIdEtatLigneFrais($idEtatLigneFrais) { $this->idEtatLigneFrais = $idEtatLigneFrais; return $this; } /** * Get idEtatLigneFrais * * @return integer */ public function getIdEtatLigneFrais() { return $this->idEtatLigneFrais; } } <file_sep><?php namespace GestionFraisBundle\Controller; use Symfony\Component\HttpFoundation\Request; use Symfony\Bundle\FrameworkBundle\Controller\Controller; use GestionFraisBundle\Entity\Visiteur; use GestionFraisBundle\Form\VisiteurType; /** * Visiteur controller. * */ class VisiteurController extends Controller { /** * Lists all Visiteur entities. * */ public function indexAction() { $em = $this->getDoctrine()->getManager(); $entities = $em->getRepository('GestionFraisBundle:Visiteur')->findAll(); return $this->render('GestionFraisBundle:Visiteur:index.html.twig', array( 'entities' => $entities, )); } /** * Creates a new Visiteur entity. * */ public function createAction(Request $request) { $entity = new Visiteur(); $form = $this->createCreateForm($entity); $form->handleRequest($request); if ($form->isValid()) { $em = $this->getDoctrine()->getManager(); $em->persist($entity); $em->flush(); return $this->redirect($this->generateUrl('visiteur_show', array('id' => $entity->getId()))); } return $this->render('GestionFraisBundle:Visiteur:new.html.twig', array( 'entity' => $entity, 'form' => $form->createView(), )); } /** * Creates a form to create a Visiteur entity. * * @param Visiteur $entity The entity * * @return \Symfony\Component\Form\Form The form */ private function createCreateForm(Visiteur $entity) { $form = $this->createForm(new VisiteurType(), $entity, array( 'action' => $this->generateUrl('visiteur_create'), 'method' => 'POST', )); $form->add('submit', 'submit', array('label' => 'Create')); return $form; } /** * Displays a form to create a new Visiteur entity. * */ public function newAction() { $entity = new Visiteur(); $form = $this->createCreateForm($entity); return $this->render('GestionFraisBundle:Visiteur:new.html.twig', array( 'entity' => $entity, 'form' => $form->createView(), )); } /** * Finds and displays a Visiteur entity. * */ public function showAction($id) { $em = $this->getDoctrine()->getManager(); $entity = $em->getRepository('GestionFraisBundle:Visiteur')->find($id); if (!$entity) { throw $this->createNotFoundException('Unable to find Visiteur entity.'); } $deleteForm = $this->createDeleteForm($id); return $this->render('GestionFraisBundle:Visiteur:show.html.twig', array( 'entity' => $entity, 'delete_form' => $deleteForm->createView(), )); } /** * Displays a form to edit an existing Visiteur entity. * */ public function editAction($id) { $em = $this->getDoctrine()->getManager(); $entity = $em->getRepository('GestionFraisBundle:Visiteur')->find($id); if (!$entity) { throw $this->createNotFoundException('Unable to find Visiteur entity.'); } $editForm = $this->createEditForm($entity); $deleteForm = $this->createDeleteForm($id); return $this->render('GestionFraisBundle:Visiteur:edit.html.twig', array( 'entity' => $entity, 'edit_form' => $editForm->createView(), 'delete_form' => $deleteForm->createView(), )); } /** * Creates a form to edit a Visiteur entity. * * @param Visiteur $entity The entity * * @return \Symfony\Component\Form\Form The form */ private function createEditForm(Visiteur $entity) { $form = $this->createForm(new VisiteurType(), $entity, array( 'action' => $this->generateUrl('visiteur_update', array('id' => $entity->getId())), 'method' => 'PUT', )); $form->add('submit', 'submit', array('label' => 'Update')); return $form; } /** * Edits an existing Visiteur entity. * */ public function updateAction(Request $request, $id) { $em = $this->getDoctrine()->getManager(); $entity = $em->getRepository('GestionFraisBundle:Visiteur')->find($id); if (!$entity) { throw $this->createNotFoundException('Unable to find Visiteur entity.'); } $deleteForm = $this->createDeleteForm($id); $editForm = $this->createEditForm($entity); $editForm->handleRequest($request); if ($editForm->isValid()) { $em->flush(); return $this->redirect($this->generateUrl('visiteur_edit', array('id' => $id))); } return $this->render('GestionFraisBundle:Visiteur:edit.html.twig', array( 'entity' => $entity, 'edit_form' => $editForm->createView(), 'delete_form' => $deleteForm->createView(), )); } /** * Deletes a Visiteur entity. * */ public function deleteAction(Request $request, $id) { $form = $this->createDeleteForm($id); $form->handleRequest($request); if ($form->isValid()) { $em = $this->getDoctrine()->getManager(); $entity = $em->getRepository('GestionFraisBundle:Visiteur')->find($id); if (!$entity) { throw $this->createNotFoundException('Unable to find Visiteur entity.'); } $em->remove($entity); $em->flush(); } return $this->redirect($this->generateUrl('visiteur')); } /** * Creates a form to delete a Visiteur entity by id. * * @param mixed $id The entity id * * @return \Symfony\Component\Form\Form The form */ private function createDeleteForm($id) { return $this->createFormBuilder() ->setAction($this->generateUrl('visiteur_delete', array('id' => $id))) ->setMethod('DELETE') ->add('submit', 'submit', array('label' => 'Delete')) ->getForm() ; } } <file_sep><?php /** * Created by PhpStorm. * User: Eddy * Date: 28/11/2015 * Time: 13:06 */ namespace GestionFraisBundle\Controller; use Symfony\Bundle\FrameworkBundle\Controller\Controller; class FicheFraisController extends Controller { /** * Affiche le contenue d'une fiche de frais pour le visiteur * */ public function consulterFicheAction($mois) { return $this->render('GestionFraisBundle:FicheFrais:consulterFiche.html.twig', array( 'mois' => $mois)); } /** * Affiche le contenue d'une fiche de frais et offre la possibilité de la modifier au visiteur * */ public function renseignerFicheAction($mois) { } /** * Affiche le contenue d'une fiche de frais et permet la modification de l'etat au comptable * */ public function validerFicheAction($visteur, $mois) { } }<file_sep><?php namespace GestionFraisBundle\Entity; use Doctrine\ORM\Mapping as ORM; /** * FraisForfait * * @ORM\Table() * @ORM\Entity(repositoryClass="GestionFraisBundle\Entity\FraisForfaitRepository") */ class FraisForfait { /** * @var integer * * @ORM\Column(name="id", type="integer") * @ORM\Id * @ORM\GeneratedValue(strategy="AUTO") */ private $id; /** * @var string * * @ORM\Column(name="libelleFraisForfait", type="string", length=255) */ private $libelleFraisForfait; /** * @var float * * @ORM\Column(name="montant", type="float") */ private $montant; /** * Get id * * @return integer */ public function getId() { return $this->id; } /** * Set libelleFraisForfait * * @param string $libelleFraisForfait * * @return FraisForfait */ public function setLibelleFraisForfait($libelleFraisForfait) { $this->libelleFraisForfait = $libelleFraisForfait; return $this; } /** * Get libelleFraisForfait * * @return string */ public function getLibelleFraisForfait() { return $this->libelleFraisForfait; } /** * Set montant * * @param float $montant * * @return FraisForfait */ public function setMontant($montant) { $this->montant = $montant; return $this; } /** * Get montant * * @return float */ public function getMontant() { return $this->montant; } } <file_sep><?php namespace GestionFraisBundle\Entity; use Doctrine\ORM\Mapping as ORM; /** * FicheFrais * * @ORM\Table() * @ORM\Entity(repositoryClass="GestionFraisBundle\Entity\FicheFraisRepository") */ class FicheFrais { /** * @var integer * * @ORM\Id * * @ORM\Column(name="idVisiteur", type="integer") * @ORM\ManyToOne(targetEntity="Visiteur") * @ORM\JoinColumn(name="$id", referencedColumnName="id") */ private $idVisiteur; /** * @var \string * * @ORM\Id * * @ORM\Column(name="mois", type="string", length=6) * */ private $mois; /** * @var integer * * @ORM\Column(name="idEtatFicheFrais", type="integer") * @ORM\ManyToOne(targetEntity="EtatFicheFrais") * @ORM\JoinColumn(name="$id", referencedColumnName="id") * * */ private $idEtatFicheFrais; /** * @var string * * @ORM\Column(name="montantValide", type="string", length=255) */ private $montantValide; /** * @var \DateTime * * @ORM\Column(name="dateModif", type="datetime") */ private $dateModif; /** * Set idVisiteur * * @param integer $idVisiteur * * @return FicheFrais */ public function setIdVisiteur($idVisiteur) { $this->idVisiteur = $idVisiteur; return $this; } /** * Get idVisiteur * * @return integer */ public function getIdVisiteur() { return $this->idVisiteur; } /** * Set mois * * @param \string $mois * * @return FicheFrais */ public function setMois($mois) { $this->mois = $mois; return $this; } /** * Get mois * * @return \string */ public function getMois() { return $this->mois; } /** * Set idEtatFicheFrais * * @param integer $idEtatFicheFrais * * @return FicheFrais */ public function setIdEtatFicheFrais($idEtatFicheFrais) { $this->idEtatFicheFrais = $idEtatFicheFrais; return $this; } /** * Get idEtatFicheFrais * * @return integer */ public function getIdEtatFicheFrais() { return $this->idEtatFicheFrais; } /** * Set montantValide * * @param string $montantValide * * @return FicheFrais */ public function setMontantValide($montantValide) { $this->montantValide = $montantValide; return $this; } /** * Get montantValide * * @return string */ public function getMontantValide() { return $this->montantValide; } /** * Set dateModif * * @param \DateTime $dateModif * * @return FicheFrais */ public function setDateModif($dateModif) { $this->dateModif = $dateModif; return $this; } /** * Get dateModif * * @return \DateTime */ public function getDateModif() { return $this->dateModif; } /** * Set nbJustificatif * * @param integer $nbJustificatif * * @return FicheFrais */ public function setNbJustificatif($nbJustificatif) { $this->nbJustificatif = $nbJustificatif; return $this; } /** * Get nbJustificatif * * @return integer */ public function getNbJustificatif() { return $this->nbJustificatif; } } <file_sep><?php /** * Created by PhpStorm. * User: Eddy * Date: 28/11/2015 * Time: 13:08 */ namespace GestionFraisBundle\Controller; use Symfony\Bundle\FrameworkBundle\Controller\Controller; class LigneFraisHorsForfaitController extends Controller { }<file_sep><?php /** * Created by PhpStorm. * User: Eddy * Date: 28/11/2015 * Time: 13:07 */ namespace GestionFraisBundle\Controller; use Symfony\Component\HttpKernel\Tests\Controller; class LigneFraisForfaitController extends Controller { }<file_sep>CastorJunior ============ A Symfony project created on November 27, 2015, 2:39 pm. <file_sep><?php namespace GestionFraisBundle; use Symfony\Component\HttpKernel\Bundle\Bundle; class GestionFraisBundle extends Bundle { }
f3cfeaa94555132213f3ecb4540e93602c2ca7ce
[ "Markdown", "PHP" ]
10
PHP
Marquand/ProjetCastor
be2a4bea802bb2948c1078ba9001e0b09a60a554
dca628119533230a98b95dd47578f8fba5588ac6
refs/heads/master
<file_sep>import sanitizeHtml = require('sanitize-html') export const excerptResolvers = { rendered: async ({ rendered }: { rendered: string }, _: any, __: any) => { return sanitizeHtml(rendered, { allowedTags: [] }) }, }
9ccd7ab666288019935b10d3edcdb32fce68f4ab
[ "TypeScript" ]
1
TypeScript
giovanapereira/wordpress-integration
00bd2c29ca82b9cf837919ed0e4263cd033703ba
9f1ee9417080228e578dde680960fff6343db01f
refs/heads/master
<file_sep>package castledesigner; import java.awt.Point; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.nio.ByteBuffer; import java.nio.ByteOrder; import java.nio.ShortBuffer; import java.nio.channels.FileChannel; import java.util.HashMap; import java.util.TreeSet; public class CasFileWriter { private TileBuilding[][] gridData; private File[] casFiles; private HashMap<CastlePoint, BuildingType> castleLayoutMap; private HashMap<Point, BuildingType> preWriteMap; public void writeToCasFiles(){ castleLayoutMap = convertGridData(gridData); preWriteMap = addCasFileOffset(castleLayoutMap); short[] payload = constructPayload(preWriteMap); System.out.println(preWriteMap); //short[] payload = new short[] {0x0300, 0x0000, 0x2323, 0x0e00, 0x2329, 0x0e00, 0x232f, 0x0e00}; FileOutputStream fos; for (File f : casFiles){ try { fos = new FileOutputStream(f); ByteBuffer myByteBuffer = ByteBuffer.allocate(payload.length*2); myByteBuffer.order(ByteOrder.LITTLE_ENDIAN); ShortBuffer myShortBuffer = myByteBuffer.asShortBuffer(); myShortBuffer.put(payload); FileChannel out = fos.getChannel(); out.write(myByteBuffer); out.close(); fos.close(); } catch (FileNotFoundException e2) { // TODO Auto-generated catch block e2.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } private short[] constructPayload(HashMap<Point, BuildingType> pwm) { short[] shortBuildArray = new short[2 + pwm.size()*2]; shortBuildArray[0] = (short) pwm.size(); shortBuildArray[1] = 0x0000; int count = 2; for (Point p : pwm.keySet()){ short[] pair = getStructureShortPair(p, pwm.get(p)); shortBuildArray[count] = pair[0]; shortBuildArray[count + 1] = pair[1]; count+=2; } return shortBuildArray; } /*File f = new File("HERO.cas"); FileOutputStream fos; try { fos = new FileOutputStream(f); ByteBuffer myByteBuffer = ByteBuffer.allocate(2); myByteBuffer.order(ByteOrder.LITTLE_ENDIAN); ShortBuffer myShortBuffer = myByteBuffer.asShortBuffer(); myShortBuffer.put((short)(0x0000 + 15)); FileChannel out = fos.getChannel(); out.write(myByteBuffer); out.close(); } catch (FileNotFoundException e2) { // TODO Auto-generated catch block e2.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); }*/ private short[] getStructureShortPair(Point p, BuildingType bt) { short coord, buildingCode; buildingCode = bt.getCaseFileCode(); byte[] coordPair = new byte[] {(byte)(p.x + 0x21), (byte)(p.y + 0x21)}; coord = coordPair[1]; coord = (short) ((coord << 8) | coordPair[0]); return new short[] {coord, buildingCode}; } private short pointToCasFileShortConverter(Point p){ File f = new File("HERO.cas"); FileOutputStream fos; try { fos = new FileOutputStream(f); short[] payload = {0x2122, 0x2324, 0x2122, 0x2324}; ByteBuffer myByteBuffer = ByteBuffer.allocate(8); myByteBuffer.order(ByteOrder.LITTLE_ENDIAN); ShortBuffer myShortBuffer = myByteBuffer.asShortBuffer(); myShortBuffer.put(payload); FileChannel out = fos.getChannel(); out.write(myByteBuffer); out.close(); } catch (FileNotFoundException e2) { // TODO Auto-generated catch block e2.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } return 0x0000; } private HashMap<Point, BuildingType> addCasFileOffset(HashMap<CastlePoint, BuildingType> clm) { HashMap<Point, BuildingType> output = new HashMap<Point, BuildingType>(); for(CastlePoint cp : clm.keySet()){ BuildingType bt = clm.get(cp); Point offset = bt.getCasFilePointOffset(); Point p = new Point(cp.x + offset.x, cp.y + offset.y); output.put(p, bt); } return output; } /** * Converting the gridData into something that can be put into an actual .cas file. * * @param TileBuilding[][] gd * @return TreeMap<CastlePoint, BuildingType> clm */ private HashMap<CastlePoint, BuildingType> convertGridData(TileBuilding[][] gd) { //HashMap<BuildingId, TreeSet<CastlePoint>> to filter same building IDs HashMap<Integer, TreeSet<CastlePoint>> structureMap = new HashMap<Integer, TreeSet<CastlePoint>>(); for (int i = 0; i < gridData.length; i++) for (int j = 0; j < gridData[i].length; j++){ //System.out.println("("+ i + "," + j + ")" + (gridData[i][j] != null ? gridData[i][j].getBuildingType().name() + " ID:" + gridData[i][j].getBuildingId() : "Empty spot")); if (gridData[i][j] != null) if (gridData[i][j].getBuildingType() != BuildingType.KEEP){ if (!structureMap.containsKey(gridData[i][j].getBuildingId())){ structureMap.put(gridData[i][j].getBuildingId(), new TreeSet<CastlePoint>()); //System.out.println("("+ i + "," + j + ")" + (gridData[i][j] != null ? gridData[i][j].getBuildingType().name() + " ID:" + gridData[i][j].getBuildingId() : "Empty spot")); } structureMap.get(gridData[i][j].getBuildingId()).add(new CastlePoint(i, j)); } } //take the top of each list so that we can get the bottom-right corner of each structure. HashMap<CastlePoint, BuildingType> clm = new HashMap<CastlePoint, BuildingType>(); for (Integer i : structureMap.keySet()){ //simply take the first value in each entry clm.put(structureMap.get(i).first(), getBuildingId(structureMap.get(i).first())); } return clm; } private BuildingType getBuildingId(CastlePoint point) { return gridData[point.x][point.y].getBuildingType(); } public TileBuilding[][] getGridData() { return gridData; } public void setGridData(TileBuilding[][] gridData) { this.gridData = gridData; } public File[] getCasFiles() { return casFiles; } public void setCasFiles(File[] casFiles) { this.casFiles = casFiles; } //for the sake of getting the correct point in the TreeSet. Not good programming but it gets it done. class CastlePoint extends Point implements Comparable<CastlePoint>{ public CastlePoint(int x, int y){ super (x, y); } public int compareTo(CastlePoint other) { if (other.x + other.y < this.x + this.y){ return 1; } else if (other.x + other.y > this.x + this.y){ return -1; } return 0; } } }
4ec38914660d9b8716b3f6d789b1a5e577479dcd
[ "Java" ]
1
Java
Velaseriat/stronghold-kingdoms-castle-designer
ef565407f093dd559099a6d030ab9ed55e67308c
9766c9475dcebdf4235c270c0c13c827d08fb156
refs/heads/master
<repo_name>IceCruelStuff/seesaw<file_sep>/common/ipc/ipc.go // Copyright 2014 Google Inc. All Rights Reserved. // // 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. // Author: <EMAIL> (<NAME>) // Package ipc contains types and functions used for interprocess communication // between Seesaw components. package ipc import ( "fmt" "os" "os/user" "strings" "github.com/google/seesaw/common/seesaw" spb "github.com/google/seesaw/pb/seesaw" ) // AuthType specifies the type of authentication established. type AuthType int const ( ATNone AuthType = iota ATSSO ATTrusted ATUntrusted ) var authTypeNames = map[AuthType]string{ ATNone: "none", ATSSO: "SSO", ATTrusted: "trusted", ATUntrusted: "untrusted", } // String returns the string representation of an AuthType. func (at AuthType) String() string { if name, ok := authTypeNames[at]; ok { return name } return "(unknown)" } // Peer contains information identifying a peer process. type Peer struct { Component seesaw.Component Identity string } // Context contains information relating to interprocess communication. type Context struct { AuthToken string AuthType AuthType Groups []string Peer Peer // Untrusted - client provided Proxy Peer User string } // NewContext returns a new context for the given component. func NewContext(component seesaw.Component) *Context { return &Context{ AuthType: ATNone, Peer: Peer{ Component: component, Identity: fmt.Sprintf("%s [pid %d]", component, os.Getpid()), }, } } // NewAuthContext returns a new authenticated context for the given component. func NewAuthContext(component seesaw.Component, token string) *Context { ctx := NewContext(component) ctx.AuthToken = token ctx.AuthType = ATUntrusted return ctx } // NewTrustedContext returns a new trusted context for the given component. func NewTrustedContext(component seesaw.Component) *Context { ctx := NewContext(component) ctx.AuthType = ATTrusted if u, err := user.Current(); err == nil { ctx.User = fmt.Sprintf("%s [uid %s]", u.Username, u.Uid) } else { ctx.User = fmt.Sprintf("(unknown) [uid %d]", os.Getuid()) } return ctx } // String returns the string representation of a context. func (ctx *Context) String() string { if ctx == nil { return "(nil context)" } var s []string if ctx.Peer.Component != seesaw.SCNone { s = append(s, fmt.Sprintf("peer %s", ctx.Peer.Identity)) } if ctx.Proxy.Component != seesaw.SCNone { s = append(s, fmt.Sprintf("via %s", ctx.Proxy.Identity)) } s = append(s, fmt.Sprintf("as %s (%v auth)", ctx.User, ctx.AuthType)) return strings.Join(s, " ") } // IsTrusted returns whether a context came from a trusted source. func (ctx *Context) IsTrusted() bool { return ctx.AuthType == ATTrusted } // ConfigSource contains data for a config source IPC. type ConfigSource struct { Ctx *Context Source string } // HAStatus contains data for a HA status IPC. type HAStatus struct { Ctx *Context Status seesaw.HAStatus } // HAState contains data for a HA state IPC. type HAState struct { Ctx *Context State spb.HaState } // Override contains data for an override IPC. type Override struct { Ctx *Context Vserver *seesaw.VserverOverride Destination *seesaw.DestinationOverride Backend *seesaw.BackendOverride }
039c2d51065c352712e7cad5ebe3f2c48fd7fb69
[ "Go" ]
1
Go
IceCruelStuff/seesaw
cb3d46175cb13ee09f23914edbbcf43aa0c3cfc2
d4a752d808f8a849dbdd9763ad397f75a43e4847
refs/heads/master
<repo_name>darshanasalvi/form2fit<file_sep>/docs/setup.md # Setup We're going to install `form2fit` as a local python package. The only requirement is to have python3 which you can install through [Anaconda](https://docs.continuum.io/anaconda/install/). ## Creating a Conda Environment First, create a new conda environment: ``` conda create -n form2fit python=3.6 conda activate form2fit ``` ## Installing Walle Install `walle` with pip: ``` pip install walle ``` If it fails to import `python -c "import walle"`, you can install it locally with: ``` git clone https://github.com/kevinzakka/walle.git cd walle pip install -e . ``` ## Installing Form2Fit Finally, clone this repository and install locally with pip. ``` git clone https://github.com/kevinzakka/form2fit.git cd form2fit pip install -e . ```<file_sep>/docs/evaluate_benchmark.md # Benchmark Evaluation **Disclaimer.** Evaluation can currently only be done on the train partition. It will be updated to support the entire benchmark when the generalization partition is added to the dataset in the coming weeks. The model-agnostic code for evaluating benchmark performance resides in the `benchmark` folder. It reads a pickle file of estimated poses and outputs a pickle file containing computed metrics. ## Input Format The input must be saved as a pickle file. The expected content of the pickle file is a dictionary. The keys of the dictionary are each of the kits in that specific partition of the benchmark. For example, on the train partition, you should have 5 keys, one for each of the 5 kits. The value of each key is a list containing the estimated pose of each data sample in that particular kit. In the case of the train partition, we have 25 test points per kit. For the generalization benchmark, there are 20 test points per configuration. ``` estimated_poses = { 'deodorants': [pose_0, pose_1, ..., pose_24], 'black-floss': [pose_0, pose_1, ..., pose_24], ... } ``` ## Evaluate To evaluate the performance of your model, run the following command, replacing `{ALGORITHM}_poses.pkl` with the name of your saved estimated poses pickle file. Make sure it ends with `_poses.pkl`. ``` python eval.py {ALGORITHM}_poses.pkl --debug=False ``` This will output a pickle file of computed accuracies named `{ALGORITHM}_acc.pkl`. The computed metrics are: * translational error * rotational error * reprojection error * average distance (ADD) ## Visualize You can now plot accuracy vs threshold curves with: ``` python auc.py ALGORITHM_acc.pkl ```<file_sep>/docs/model_weights.md # Model Weights You can download model weights by running the `download_weights.sh` script in the `form2fit` directory: ``` bash download_weights.sh ``` This will create a directory called `weights` in `form2fit/code/ml/models/` containing model weights for the matching module of `Form2Fit`. You should find one for each kit in the training partition of the benchmark. We'll be releasing more matching network weights in the coming weeks, as well as weights for the place and suction networks.<file_sep>/setup.py from setuptools import setup setup( name="form2fit", version="0.0.1", description="Form2Fit Code and Benchmark", author="<NAME>", python_requires=">=3.6", install_requires=[ "numpy>=1.0.0", "scikit-image>=0.15.0", "open3d-python==0.4.0.0", "PyQt5==5.9.2", "torch", "torchvision", "ipdb", "opencv-python", "tqdm", ], ) <file_sep>/docs/about_benchmark.md # The Form2Fit Benchmark **Disclaimer.** The generalization kits are currently only available in raw format. The processed format will be made available in the coming weeks. We present the **Form2Fit Benchmark**, a dataset for evaluating the generalization capabilities of kit assembly algorithms. It currently consists of: * 5 training kits * 6 kit configurations that test for generalization: * combinations and mixtures of training kits (x2) * novel single and multi object kits (x4) For all 11 kits, we provide the raw data collected by the robot, as well as the processed format used by `Form2Fit`. Each training kit contains over 500 data points which we split into train, validation and testing splits for model training. For the generalization kits, we provide 20 data points where: we have 5 sets of 4 kit pose samples where in each set, the pose of the kit is fixed but the pose of the objects is randomized. This aligns with the real-world experiments reported in section V.B of the [paper](""). <p align="center"> <img src="../assets/black-floss.png" width=18% alt="Drawing"> <img src="../assets/tape-runner.png" width=18% alt="Drawing"> <img src="../assets/deodorants.png" width=18% alt="Drawing"> <img src="../assets/zoo-animals.png" width=18% alt="Drawing"> <img src="../assets/fruits.png" width=18% alt="Drawing"> </p> <p align="center"> <img src="../assets/combo.png" width=18% alt="Drawing"> <img src="../assets/mixture.png" width=18% alt="Drawing"> </p> <p align="center"> <img src="../assets/green-gray.png" width=18% alt="Drawing"> <img src="../assets/white-tape.png" width=18% alt="Drawing"> <img src="../assets/circles.png" width=18% alt="Drawing"> <img src="../assets/green-green.png" width=18% alt="Drawing"> </p> ## Download We provide a script for downloading and unpacking the dataset under the `form2fit/benchmark/` directory. Execute it as follows: ``` cd form2fit/form2fit/ bash download_data.sh ``` ## Data Organization ``` . ├── raw ├── test └── train ``` The `raw` folder contains the raw (unsurprisingly) data gathered during the self-supervised disassembly pipeline. The `test` folder contains the 6 generalization kits and the `train` folder the 5 training kits. The train folder contains 5 directories, one for each kit: `black-floss`, `deodorants`, `tape-runner`, `zoo-animals` and `fruits`. Let's dive into the contents of the `deodorants` folder. **Note.** Files or folders that do not have an associated comment are specific to the Form2Fit architecture and can be ignored for the purposes of the benchmark. ``` . ├── data_indices.npy ├── extr.txt # the pose of the 3D sensor with respect to the robot base ├── intr.txt # the intrinsics of the 3D sensor ├── mean_std.p # the train dataset mean and standard deviation for the grayscale and depth heightmaps. ├── test # test split ├── train # train split └── valid # validation split ``` In the `train` folder, you will find a folder for each data point. Each folder consists of: ``` . ├── corrs.npy ├── curr_hole_mask.npy # the pixel mask of the kit hole at the current timestep ├── curr_kit_minus_hole_mask.npy ├── curr_kit_plus_hole_mask.npy ├── curr_object_mask.npy # the pixel mask of the object at the current timestep ├── final_color_height.png # the grayscale heightmap ├── final_depth_height.png # the depth heightmap ├── final_pose.txt # the object pose when it is outside the kit hole ├── init_color_height.png ├── init_depth_height.png ├── init_pose.txt # the object pose when it is inside the kit hole ├── placement_points.txt ├── suction_points_final.txt ├── suction_points_init.txt └── transforms.npy ```<file_sep>/form2fit/code/utils/viz.py import os import matplotlib.pyplot as plt import numpy as np # import open3d as o3d from skimage.draw import circle from form2fit.code.utils.misc import rotate_img def plot_rgbd(rgb, depth, gray=False, name=None): fig, axes = plt.subplots(1, 2, figsize=(10, 10)) axes[0].imshow(rgb, cmap="gray" if gray else None) axes[1].imshow(depth) for ax in axes: ax.axis("off") if name is not None: if not os.path.exists("./plots/"): os.makedirs("./plots/") plt.savefig("./plots/{}.png".format(name), format="png", dpi=150) plt.show() def plot_img(img, figsize=(30, 30), uv=None, gray=False): fig = plt.figure(figsize=figsize) plt.imshow(img, cmap="gray" if gray else None) if uv is not None: plt.scatter(uv[:, 1], uv[:, 0], c="b") plt.axis("off") plt.show() def view_pc(xyzrgbs, frame=True, gray=False): """Displays a list of colored pointclouds. """ pcs = [] for xyzrgb in xyzrgbs: pts = xyzrgb[:, :3].copy().astype(np.float64) if gray: clrs = np.repeat((xyzrgb[:, 3:].copy()).astype(np.float64), 3, axis=1) else: clrs = xyzrgb[:, 3:].copy().astype(np.float64) pc = o3d.PointCloud() pc.points = o3d.Vector3dVector(pts) pc.colors = o3d.Vector3dVector(clrs) pcs.append(pc) if frame: pcs.append(o3d.create_mesh_coordinate_frame(size=0.1, origin=[0, 0, 0])) o3d.draw_geometries(pcs) def plot_correspondences( height_s, height_t, label, matches=5, non_matches=5, num_rotations=20, name=None, gray=False, ): # store image size for later use H, W = height_s.shape[:2] source_uv = label[:, :2].numpy() target_uv = label[:, 2:].numpy() rot_indices = label[:, 4].numpy() is_match = label[:, 5].numpy() rot_step_size = 360 / num_rotations rotations = np.array([rot_step_size * i for i in range(num_rotations)]) fig, axes = plt.subplots( 5, 4, figsize=(40, 20), gridspec_kw={"wspace": 0, "hspace": 0} ) for rot_idx, (rot, ax) in enumerate(zip(rotations, axes.flatten())): height_s_r = rotate_img(height_s, -rot) height_combined = np.hstack([height_s_r, height_t]) ax.imshow(height_combined, cmap="gray" if gray else None) # plot matches mask = np.logical_and(is_match == 1.0, rot_indices == rot_idx) if mask.sum() > 0: f_s = source_uv[mask] f_t = target_uv[mask] rand_idxs = np.random.choice(len(f_s), replace=False, size=matches) vs = [f_s[rand_idxs, 1], f_t[rand_idxs, 1] + W] us = [f_s[rand_idxs, 0], f_t[rand_idxs, 0]] ax.plot(vs, us, "wo--", linewidth=3.0, alpha=0.4) # sample and plot non-matches non_match_idxs = np.random.choice( np.where(np.logical_and(rot_indices == rot_idx, is_match == 0.0))[0], replace=False, size=non_matches, ) f_s = source_uv[non_match_idxs] f_t = target_uv[non_match_idxs] vs = [f_s[:, 1], f_t[:, 1] + W] us = [f_s[:, 0], f_t[:, 0]] ax.plot(vs, us, "ro--", linewidth=3.0, alpha=0.4) ax.axis("off") if name is not None: if not os.path.exists("./plots/"): os.makedirs("./plots/") plt.savefig("./plots/{}.png".format(name), format="png", dpi=150) plt.show() def plot_suction(height_c, height_d, suction, name=None, gray=True): suction = suction.detach().cpu().numpy() pos_suction = suction[suction[:, 2] == 1] neg_suction = suction[suction[:, 2] != 1] fig, axes = plt.subplots(1, 2, figsize=(20, 40)) for ax, im in zip(axes, [height_c, height_d]): ax.imshow(im) ax.scatter(pos_suction[:, 1], pos_suction[:, 0], color="b") ax.scatter(neg_suction[:, 1], neg_suction[:, 0], color="r") ax.axis("off") if name is not None: if not os.path.exists("./plots/"): os.makedirs("./plots/") plt.savefig("./plots/{}.png".format(name), format="png", dpi=150) plt.show() def plot_placement(height_c, height_d, placement, name=None, gray=True): placement = placement.detach().cpu().numpy() pos_placement = placement[placement[:, 2] == 1] neg_placement = placement[placement[:, 2] != 1] fig, axes = plt.subplots(1, 2, figsize=(20, 40)) for ax, im in zip(axes, [height_c, height_d]): ax.imshow(im) ax.scatter(pos_placement[:, 1], pos_placement[:, 0], color="b") ax.scatter(neg_placement[:, 1], neg_placement[:, 0], color="r") ax.axis("off") if name is not None: if not os.path.exists("./plots/"): os.makedirs("./plots/") plt.savefig("./plots/{}.png".format(name), format="png", dpi=150) plt.show() def plot_loss(arr, window=50, figsize=(20, 10), name=None): def _rolling_window(a, window): shape = a.shape[:-1] + (a.shape[-1] - window + 1, window) strides = a.strides + (a.strides[-1],) return np.lib.stride_tricks.as_strided(a, shape=shape, strides=strides) arr = np.asarray(arr) fig, ax = plt.subplots(figsize=figsize) rolling_mean = np.mean(_rolling_window(arr, 50), 1) rolling_std = np.std(_rolling_window(arr, 50), 1) plt.plot(range(len(rolling_mean)), rolling_mean, alpha=0.98, linewidth=0.9) plt.fill_between( range(len(rolling_std)), rolling_mean - rolling_std, rolling_mean + rolling_std, alpha=0.5, ) plt.grid() plt.xlabel("Iteration #") plt.ylabel("Loss") if name is not None: if not os.path.exists("./plots/"): os.makedirs("./plots/") plt.savefig("./plots/{}.png".format(name), format="png", dpi=150) plt.show() def plot_losses(arr1, arr2, figsize=(20, 10), name=None): fig, ax = plt.subplots(figsize=figsize) for arr, lbl in zip([arr1, arr2], ["train", "test"]): ax.plot(arr, linewidth=0.9, label=lbl) plt.grid() plt.xlabel("Iteration #") plt.ylabel("Loss") plt.legend(loc="upper right") if name is not None: if not os.path.exists("./plots/"): os.makedirs("./plots/") plt.savefig("./plots/{}.png".format(name), format="png", dpi=150) else: u_min, v_min = misc.make2d(min_val, w) plt.show()<file_sep>/form2fit/code/planner/planner.py import cv2 import matplotlib.pyplot as plt import numpy as np import torch from itertools import product from skimage.feature import peak_local_max from form2fit.code.utils import misc class Planner: def __init__(self, center): self.center = center def plan(self, suction_scores, place_scores, kit_descriptor_map, object_descriptor_map, suction_mask=None, place_mask=None, img1=None, img2=None): if suction_mask is not None: suction_scores[suction_mask[:, 0], suction_mask[:, 1]] = 0 suction_coordinates = peak_local_max(suction_scores, min_distance=0, threshold_rel=0.1) if place_mask is not None: place_scores[place_mask[:, 0], place_mask[:, 1]] = 0 place_coordinates = peak_local_max(place_scores, min_distance=0, threshold_rel=0.1) combinations = list(product(place_coordinates, suction_coordinates)) num_rotations = len(kit_descriptor_map) B, D, H, W = object_descriptor_map.shape object_descriptor_map_flat = object_descriptor_map.view(B, D, H*W) distances = [] rotation_idxs = [] for place_uv, suction_uv in combinations: # index object descriptor map suction_uv_flat = torch.from_numpy(np.array((suction_uv[0]*W+suction_uv[1]))).long().cuda() object_descriptor = torch.index_select(object_descriptor_map_flat[0], 1, suction_uv_flat).unsqueeze(0) kit_descriptors = [] for r in range(num_rotations): place_uv_rot = misc.rotate_uv(np.array([place_uv]), -(360/num_rotations)*r, H, W, cxcy=self.center)[0] place_uv_rot_flat = torch.from_numpy(np.array((place_uv_rot[0]*W+place_uv_rot[1]))).long().cuda() kit_descriptor_map_flat = kit_descriptor_map[r].view(kit_descriptor_map.shape[1], -1) kit_descriptors.append(torch.index_select(kit_descriptor_map_flat, 1, place_uv_rot_flat)) kit_descriptors = torch.stack(kit_descriptors) # compute L2 distances diffs = object_descriptor - kit_descriptors l2_dists = diffs.pow(2).sum(1).sqrt() # store best across rotation best_rot_idx = l2_dists.argmin().item() l2_dist = l2_dists[best_rot_idx].item() distances.append(l2_dist) rotation_idxs.append(best_rot_idx) # compute best across candidates best_distance_idx = np.argmin(distances) best_place_uv, best_suction_uv = combinations[best_distance_idx] ret = { "best_distance_idx": best_distance_idx, "best_distance": distances[best_distance_idx], "best_rotation_idx": rotation_idxs[best_distance_idx], "best_place_uv": best_place_uv, "best_suction_uv": best_suction_uv, } return ret<file_sep>/form2fit/download_weights.sh echo "Downloading model weights..." cd code/ml/models fileid="1nAAs7Wbfe9wywi8LtYSg1jLaIe3zxVJJ" filename="weights.zip" curl -c ./cookie -s -L "https://drive.google.com/uc?export=download&id=${fileid}" > /dev/null curl -Lb ./cookie "https://drive.google.com/uc?export=download&confirm=`awk '/download/ {print $NF}' ./cookie`&id=${fileid}" -o ${filename} rm cookie unzip -q weights.zip rm -rf __MACOSX rm weights.zip echo "Done."<file_sep>/form2fit/benchmark/eval.py import argparse import glob import os import pickle import cv2 import matplotlib.pyplot as plt import numpy as np import open3d as o3d from tqdm import tqdm from ipdb import set_trace from form2fit import config from form2fit.benchmark.metrics import * from form2fit.code.utils import common, misc from form2fit.code.utils.pointcloud import transform_xyz if __name__ == "__main__": parser = argparse.ArgumentParser(description="Evaluate Algorithm on Train Partition") parser.add_argument("pose_pkl", type=str) parser.add_argument("--debug", type=lambda s: s.lower() in ["1", "true"], default=False) args, unparsed = parser.parse_known_args() kit_dirs = glob.glob("./data/train" + "/*") dump_dir = "../code/dump/" all_poses = pickle.load(open(os.path.join(dump_dir, args.pose_pkl), "rb")) accuracies = {} for kit_idx, data_dir in enumerate(kit_dirs): if data_dir.split("/")[-1] == "deodorants": continue print("{}/{}".format(kit_idx+1, len(kit_dirs))) estimated_poses = all_poses[data_dir.split("/")[-1]] test_dir = os.path.join(data_dir, "test") test_foldernames = glob.glob(test_dir + "/*") test_foldernames.sort(key=lambda x: int(x.split("/")[-1])) add_errors = [] reproj_errors = [] translational_errors = [] rotational_errors = [] for folder_idx, folder in enumerate(test_foldernames): # load ground truth pose intr = np.loadtxt(os.path.join(data_dir, "intr.txt")) extr = np.loadtxt(os.path.join(data_dir, "extr.txt")) depth_f = common.depthload(os.path.join(folder, "final_depth_height.png")) color_f = common.depthload(os.path.join(folder, "final_color_height.png")) H, W = depth_f.shape obj_mask = np.load(os.path.join(folder, "curr_object_mask.npy")).astype("int") init_pose = np.loadtxt(os.path.join(folder, "init_pose.txt")) final_pose = np.loadtxt(os.path.join(folder, "final_pose.txt")) true_pose = np.linalg.inv(final_pose @ np.linalg.inv(init_pose)) # load estimated pose estimated_pose = estimated_poses[folder_idx] if np.isnan(np.min(estimated_pose)): add_errors.append(np.nan) reproj_errors.append(np.nan) rotational_errors.append(np.nan) translational_errors.append(np.nan) continue # trim object mask depth_vals = depth_f[obj_mask[:, 0], obj_mask[:, 1]] valid_ds = depth_vals >= depth_vals.mean() mask = np.zeros_like(depth_f) mask[obj_mask[valid_ds][:, 0], obj_mask[valid_ds][:, 1]] = 1 mask = misc.largest_cc(mask) valid_mask = np.vstack(np.where(mask == 1)).T tset = set([tuple(x) for x in valid_mask]) for i in range(len(valid_ds)): is_valid = valid_ds[i] if is_valid: tidx = obj_mask[i] if tuple(tidx) not in tset: valid_ds[i] = False obj_mask = obj_mask[valid_ds] zs = depth_f[obj_mask[:, 0], obj_mask[:, 1]].reshape(-1, 1) obj_xyz = np.hstack([obj_mask, zs]) obj_xyz[:, [0, 1]] = obj_xyz[:, [1, 0]] obj_xyz[:, 0] = (obj_xyz[:, 0] * config.HEIGHTMAP_RES) + config.VIEW_BOUNDS[0, 0] obj_xyz[:, 1] = (obj_xyz[:, 1] * config.HEIGHTMAP_RES) + config.VIEW_BOUNDS[1, 0] if args.debug: zs = depth_f[obj_mask[:, 0], obj_mask[:, 1]].reshape(-1, 1) mask_xyz = np.hstack([obj_mask, zs]) mask_xyz[:, [0, 1]] = mask_xyz[:, [1, 0]] mask_xyz[:, 0] = (mask_xyz[:, 0] * config.HEIGHTMAP_RES) + config.VIEW_BOUNDS[0, 0] mask_xyz[:, 1] = (mask_xyz[:, 1] * config.HEIGHTMAP_RES) + config.VIEW_BOUNDS[1, 0] mask_xyz = transform_xyz(mask_xyz, estimated_pose) mask_xyz[:, 0] = (mask_xyz[:, 0] - config.VIEW_BOUNDS[0, 0]) / config.HEIGHTMAP_RES mask_xyz[:, 1] = (mask_xyz[:, 1] - config.VIEW_BOUNDS[1, 0]) / config.HEIGHTMAP_RES hole_idxs = mask_xyz[:, [1, 0]] mask_xyz = np.hstack([obj_mask, zs]) mask_xyz[:, [0, 1]] = mask_xyz[:, [1, 0]] mask_xyz[:, 0] = (mask_xyz[:, 0] * config.HEIGHTMAP_RES) + config.VIEW_BOUNDS[0, 0] mask_xyz[:, 1] = (mask_xyz[:, 1] * config.HEIGHTMAP_RES) + config.VIEW_BOUNDS[1, 0] true_xyz = transform_xyz(mask_xyz, true_pose) true_xyz[:, 0] = (true_xyz[:, 0] - config.VIEW_BOUNDS[0, 0]) / config.HEIGHTMAP_RES true_xyz[:, 1] = (true_xyz[:, 1] - config.VIEW_BOUNDS[1, 0]) / config.HEIGHTMAP_RES true_idxs = true_xyz[:, [1, 0]] fig, axes = plt.subplots(1, 2) axes[0].imshow(color_f) axes[0].scatter(hole_idxs[:, 1], hole_idxs[:, 0]) axes[1].imshow(color_f) axes[1].scatter(true_idxs[:, 1], true_idxs[:, 0]) for ax in axes: ax.axis('off') plt.show() obj_xyz_pred = transform_xyz(obj_xyz, estimated_pose) obj_xyz_true = transform_xyz(obj_xyz, true_pose) pcs = [] pts = obj_xyz_pred[:, :3].copy().astype(np.float64) pc = o3d.PointCloud() pc.points = o3d.Vector3dVector(pts) pcs.append(pc) pts = obj_xyz_true[:, :3].copy().astype(np.float64) pc = o3d.PointCloud() pc.points = o3d.Vector3dVector(pts) pcs.append(pc) o3d.draw_geometries(pcs) # compute metric add_err = compute_ADD(true_pose, estimated_pose, obj_xyz) reproj_err = reprojection_error(true_pose, estimated_pose, obj_xyz, config.VIEW_BOUNDS, config.HEIGHTMAP_RES) gt_final_pose = init_pose.copy() est_final_pose = estimated_pose @ final_pose rot_err = rotational_error(gt_final_pose[:3, :3], est_final_pose[:3, :3]) trans_err = translational_error(gt_final_pose[:3, 3], est_final_pose[:3, 3]) if data_dir.split("/")[-1] == "fruits" and folder_idx in config.FRUIT_IDXS: rot_err = 0 add_errors.append(add_err) reproj_errors.append(reproj_err) rotational_errors.append(rot_err) translational_errors.append(trans_err) acc = {} acc["err_add"] = add_errors acc["err_reproj"] = reproj_errors acc["err_rot"] = rotational_errors acc["err_trans"] = translational_errors accuracies[data_dir.split("/")[-1]] = acc with open(os.path.join(dump_dir, "{}_acc.pkl".format(args.pose_pkl.split("_")[0])), "wb") as fp: pickle.dump(accuracies, fp)<file_sep>/form2fit/benchmark/auc.py import argparse import json import os import pickle import matplotlib.pyplot as plt import numpy as np from form2fit import config if __name__ == "__main__": parser = argparse.ArgumentParser(description="Plot Curves") parser.add_argument("pkl_files", nargs='+', type=str) args, unparsed = parser.parse_known_args() dump_dir = "../code/dump/" plot_dir = "./plots/" if not os.path.exists(plot_dir): os.makedirs(plot_dir) accs = [pickle.load(open(os.path.join(dump_dir, fp), "rb")) for fp in args.pkl_files] names = [pkl_file.split("_")[0] for pkl_file in args.pkl_files] all_res = {name: {} for name in names} aucs = {} for method_name, method_dict in zip(names, accs): aucs[method_name] = {} res = { "err_tr": [], "err_rot": [], "err_add": [], "err_reproj": [], } for k, v in method_dict.items(): aucs[method_name][k] = {} # load metrics for current item err_tr = np.array(v['err_trans']) err_rot = np.array(v['err_rot']) err_add = np.array(v['err_add']) err_reproj = np.array(v['err_reproj']) acc_lists = [err_tr, err_rot, err_add, err_reproj] acc_names = ["err_tr", "err_rot", "err_add", "err_reproj"] x_names = [ "Translation Threshold [m]", "Rotation Angle Threshold [deg]", "Average Distance Threshold [m]", "Reprojection Threshold [heightmap pix]", ] for acc_list, acc_name, x_name in zip(acc_lists, acc_names, x_names): # if NaN encountered, make it bigger than the threshold idxs = np.argwhere(np.isnan(acc_list)) acc_list[idxs] = 10000000 accuracies = [] if acc_name == "err_rot": thresholds = np.linspace(0, config.MAX_DEG_THRESH, 30) elif acc_name == "err_reproj": thresholds = np.linspace(0, config.MAX_PIX_THRESH, 20) elif acc_name == "err_tr": thresholds = np.linspace(0, config.MAX_TR_THRESH, 20) else: thresholds = np.linspace(0, config.MAX_LENGTH_THRESH, 20) for thresh in thresholds: accuracies.append(np.mean(acc_list < thresh)) aucs[method_name][k][acc_name] = np.trapz(accuracies, thresholds) res[acc_name].append(accuracies) all_res[method_name] = res with open("per_auc.json", "w") as fp: json.dump(aucs, fp, indent=4) aucs = {} fig, axes = plt.subplots(1, 4, sharey=True, figsize=(25, 6)) for i, (metric_name, metric_xlabel) in enumerate(zip(acc_names, x_names)): aucs[metric_name[4:]] = {} for method_name, method_dict in all_res.items(): accs = np.mean(np.array(method_dict[metric_name]), axis=0) if metric_name == "err_rot": thresholds = np.linspace(0, config.MAX_DEG_THRESH, 30) elif metric_name == "err_reproj": thresholds = np.linspace(0, config.MAX_PIX_THRESH, 20) elif metric_name == "err_tr": thresholds = np.linspace(0, config.MAX_TR_THRESH, 20) else: thresholds = np.linspace(0, config.MAX_LENGTH_THRESH, 20) aucs[metric_name[4:]][method_name] = np.trapz(accs, thresholds) axes.flatten()[i].plot(thresholds, accs, label=method_name) axes.flatten()[i].set_xlabel(metric_xlabel) if i == 0: axes.flatten()[i].set_ylabel("Accuracy") axes.flatten()[i].legend(loc='lower right') axes.flatten()[i].grid() fig.tight_layout() plt.savefig(os.path.join(plot_dir, "4x4.pdf"), format="pdf", dpi=200) plt.show() with open("avg_auc.json", "w") as fp: json.dump(aucs, fp, indent=4)<file_sep>/form2fit/code/ml/models/correspondence.py import cv2 import numpy as np import torch from torch import nn from torch.nn import functional as F from form2fit.code.ml.models.base import BaseModel from form2fit.code.ml.models.fcn import FCNet from form2fit.code.utils.misc import anglepie from walle.core import RotationMatrix from torchvision import transforms trans = transforms.ToTensor() class CorrespondenceNet(BaseModel): """The correspondence prediction network. Attributes: num_channels: (int) The number of channels in the input tensor. num_descriptor: (int) The dimension of the descriptor space. num_rotations: (int) The number of rotations to perform on the source heightmap. """ def __init__(self, num_channels, num_descriptor, num_rotations): super().__init__() self.num_channels = num_channels self.num_descriptor = num_descriptor self.num_rotations = num_rotations self._rotations = anglepie(num_rotations, False) self._fcn = FCNet(num_channels, num_descriptor) def forward(self, x, uc, vc): """Forwards the target and rotated sources through the network. """ batch_size = len(x) device = torch.device("cuda" if x.is_cuda else "cpu") # split input tensor into source and target tensors xs, xt = x[:, :self.num_channels, :, :], x[:, self.num_channels:, :, :] xs = xs.detach().cpu().numpy().squeeze() # apply `num_rotations` to source tensors ins_c = [] ins_d = [] for angle in self._rotations: aff_1 = np.eye(3) aff_1[:2, 2] = [-vc, -uc] aff_2 = RotationMatrix.rotz(np.radians(angle)) aff_3 = np.eye(3, 3) aff_3[:2, 2] = [vc, uc] affine = aff_3 @ aff_2 @ aff_1 affine = affine[:2, :] ins_c.append(cv2.warpAffine(xs[0], affine, (xs.shape[2], xs.shape[1]), flags=cv2.INTER_NEAREST, borderMode=cv2.BORDER_REPLICATE)) ins_d.append(cv2.warpAffine(xs[1], affine, (xs.shape[2], xs.shape[1]), flags=cv2.INTER_NEAREST, borderMode=cv2.BORDER_REPLICATE)) # concatenate all rotated sources and target into single tensor along batch dim ins = [np.stack([ins_c[i], ins_d[i]]) for i in range(len(ins_c))] if x.is_cuda: ins = [torch.FloatTensor(i).cuda().unsqueeze(0) for i in ins] else: ins = [torch.FloatTensor(i).unsqueeze(0) for i in ins] ins.append(xt) ins = torch.cat(ins, dim=0) # forward pass out = self._fcn(ins) # separate into source and target outputs per batch out_s = [] for b in range(batch_size): sources = [out[i * batch_size + b] for i in range(self.num_rotations)] out_s.append(torch.stack(sources, dim=0)) out_s = torch.stack(out_s, dim=0) out_t = out[ batch_size * self.num_rotations : batch_size * self.num_rotations + batch_size ] return out_s, out_t @property def rotations(self): return self._rotations <file_sep>/form2fit/code/baseline/eval_baseline.py """Run the ORB-PE baseline referenced in Section V, A. """ import argparse import glob import os import pickle import cv2 import matplotlib.pyplot as plt import numpy as np from tqdm import tqdm from form2fit import config from form2fit.code.utils.pointcloud import transform_xyz from form2fit.code.utils import common from walle.utils.geometry import estimate_rigid_transform if __name__ == "__main__": parser = argparse.ArgumentParser(description="Evaluate ORB-PE Baseline on Benchmark") parser.add_argument("--debug", type=lambda s: s.lower() in ["1", "true"], default=False) args, unparsed = parser.parse_known_args() # instantiate ORB detector detector = cv2.ORB_create() bf = cv2.BFMatcher(cv2.NORM_HAMMING, crossCheck=True) save_dir = os.path.join("../dump/") if not os.path.exists(save_dir): os.makedirs(save_dir) kit_poses = {} kit_dirs = glob.glob("../../benchmark/data/train" + "/*") for kit_idx, data_dir in enumerate(kit_dirs): print(data_dir.split("/")[-1]) train_dir = os.path.join(data_dir, "train") test_dir = os.path.join(data_dir, "test") train_foldernames = glob.glob(train_dir + "/*") test_foldernames = glob.glob(test_dir + "/*") test_foldernames.sort(key=lambda x: int(x.split("/")[-1])) pred_poses = [] for test_folder in tqdm(test_foldernames, leave=False): # load camera params intr = np.loadtxt(os.path.join(data_dir, "intr.txt")) extr = np.loadtxt(os.path.join(data_dir, "extr.txt")) # load test color and depth heightmaps color_test = common.colorload(os.path.join(test_folder, "final_color_height.png")) depth_test = common.depthload(os.path.join(test_folder, "final_depth_height.png")) # load object mask obj_idxs_test = np.load(os.path.join(test_folder, "curr_object_mask.npy")).astype("int") obj_mask_test = np.zeros_like(color_test) obj_mask_test[obj_idxs_test[:, 0], obj_idxs_test[:, 1]] = 1 # load initial and final object pose init_pose_test = np.loadtxt(os.path.join(test_folder, "init_pose.txt")) final_pose_test = np.loadtxt(os.path.join(test_folder, "final_pose.txt")) # compute end-effector transform true_transform = np.linalg.inv(final_pose_test @ np.linalg.inv(init_pose_test)) # find keypoints and descriptors for current image kps_test, des_test = detector.detectAndCompute(color_test, obj_mask_test) # loop through train and detect keypoint matches matches_train = [] for i, train_folder in enumerate(train_foldernames): # load train data color_train = common.colorload(os.path.join(train_folder, "final_color_height.png")) obj_idxs_train = np.load(os.path.join(train_folder, "curr_object_mask.npy")).astype("int") obj_mask_train = np.zeros_like(color_train) obj_mask_train[obj_idxs_train[:, 0], obj_idxs_train[:, 1]] = 1 # find keypoints in train image kps_train, des_train = detector.detectAndCompute(color_train, obj_mask_train) if des_train is None: continue # brute force match matches = bf.match(des_test, des_train) if len(matches) < config.MIN_NUM_MATCH: continue matches_train.append([i, matches]) # in case we don't find any matches if len(matches_train) == 0: pred_poses.append(np.nan) continue # sort matches by lowest average match distance matches_train = sorted(matches_train, key=lambda x: np.mean([y.distance for y in x[1]])) # retrieve top match image from database idx = matches_train[0][0] matches = matches_train[0][1] color_train = common.colorload(os.path.join(train_foldernames[idx], "final_color_height.png")) depth_train = common.depthload(os.path.join(train_foldernames[idx], "final_depth_height.png")) obj_idxs_train = np.load(os.path.join(train_foldernames[idx], "curr_object_mask.npy")).astype("int") obj_mask_train = np.zeros_like(color_train) obj_mask_train[obj_idxs_train[:, 0], obj_idxs_train[:, 1]] = 1 init_pose_train = np.loadtxt(os.path.join(train_foldernames[idx], "init_pose.txt")) final_pose_train = np.loadtxt(os.path.join(train_foldernames[idx], "final_pose.txt")) transform_train = np.linalg.inv(final_pose_train @ np.linalg.inv(init_pose_train)) kps_train, des_train = detector.detectAndCompute(color_train, obj_mask_train) # plots descriptor matches between query and train if args.debug: img_debug = cv2.drawMatches(color_test, kps_test, color_train, kps_train, matches, None, flags=2) plt.imshow(img_debug) plt.show() src_pts = np.float32([kps_test[m.queryIdx].pt for m in matches]).reshape(-1, 2).astype("int") dst_pts = np.float32([kps_train[m.trainIdx].pt for m in matches]).reshape(-1, 2).astype("int") # estimate rigid transform from matches projected in 3D zs = depth_test[src_pts[:, 1], src_pts[:, 0]].reshape(-1, 1) src_xyz = np.hstack([src_pts, zs]) src_xyz[:, 0] = (src_xyz[:, 0] * config.HEIGHTMAP_RES) + config.VIEW_BOUNDS[0, 0] src_xyz[:, 1] = (src_xyz[:, 1] * config.HEIGHTMAP_RES) + config.VIEW_BOUNDS[1, 0] zs = depth_train[dst_pts[:, 1], dst_pts[:, 0]].reshape(-1, 1) dst_xyz = np.hstack([dst_pts, zs]) dst_xyz[:, 0] = (dst_xyz[:, 0] * config.HEIGHTMAP_RES) + config.VIEW_BOUNDS[0, 0] dst_xyz[:, 1] = (dst_xyz[:, 1] * config.HEIGHTMAP_RES) + config.VIEW_BOUNDS[1, 0] R, t = estimate_rigid_transform(src_xyz, dst_xyz) tr = np.eye(4) tr[:4, :4] = R tr[:3, 3] = t # compute estimated transform estimated_trans = transform_train @ tr pred_poses.append(estimated_trans) if args.debug: zs = depth_test[obj_idxs_test[:, 0], obj_idxs_test[:, 1]].reshape(-1, 1) mask_xyz = np.hstack([obj_idxs_test, zs]) mask_xyz[:, [0, 1]] = mask_xyz[:, [1, 0]] mask_xyz[:, 0] = (mask_xyz[:, 0] * config.HEIGHTMAP_RES) + config.VIEW_BOUNDS[0, 0] mask_xyz[:, 1] = (mask_xyz[:, 1] * config.HEIGHTMAP_RES) + config.VIEW_BOUNDS[1, 0] mask_xyz = transform_xyz(mask_xyz, estimated_trans) mask_xyz[:, 0] = (mask_xyz[:, 0] - config.VIEW_BOUNDS[0, 0]) / config.HEIGHTMAP_RES mask_xyz[:, 1] = (mask_xyz[:, 1] - config.VIEW_BOUNDS[1, 0]) / config.HEIGHTMAP_RES hole_idxs_est = mask_xyz[:, [1, 0]] mask_xyz = np.hstack([obj_idxs_test, zs]) mask_xyz[:, [0, 1]] = mask_xyz[:, [1, 0]] mask_xyz[:, 0] = (mask_xyz[:, 0] * config.HEIGHTMAP_RES) + config.VIEW_BOUNDS[0, 0] mask_xyz[:, 1] = (mask_xyz[:, 1] * config.HEIGHTMAP_RES) + config.VIEW_BOUNDS[1, 0] true_xyz = transform_xyz(mask_xyz, true_transform) true_xyz[:, 0] = (true_xyz[:, 0] - config.VIEW_BOUNDS[0, 0]) / config.HEIGHTMAP_RES true_xyz[:, 1] = (true_xyz[:, 1] - config.VIEW_BOUNDS[1, 0]) / config.HEIGHTMAP_RES hole_idxs_true = true_xyz[:, [1, 0]] fig, axes = plt.subplots(1, 2) axes[0].imshow(color_test) axes[0].scatter(hole_idxs_true[:, 1], hole_idxs_true[:, 0]) axes[0].title.set_text('Ground Truth') axes[1].imshow(color_test) axes[1].scatter(hole_idxs_est[:, 1], hole_idxs_est[:, 0]) axes[1].title.set_text('Predicted') plt.show() kit_poses[data_dir.split("/")[-1]] = pred_poses with open(os.path.join(save_dir, "ORB-PE_poses.pkl"), "wb") as fp: pickle.dump(kit_poses, fp)<file_sep>/docs/paper_code.md ## Paper Code The different architectural components of Form2Fit reside in various subfolders inside the `code` directory. This does not include code for controlling the UR5e robot or the self-supervised data collection process. <p align="center"> <img src="../assets/method.png" width=100% alt="Drawing"> </p> ## Baseline To evaluate and compare the baseline performance on the benchmark, cd to the `baseline` folder. ``` python eval_baseline.py ``` This will produce a pickle file of estimated poses called `ORB-PE_poses.pkl`. You can then evaluate its performance by running the [evaluation instructions](./evaluate_benchmark.md) on this pickle file. You can optionally run the above in debug mode `--debug=True` to plot the ORB descriptors, matches and predicted poses. ## Dataloaders We provide pytorch dataloaders for the place, suction and matching networks. They can be found in `code/ml/dataloader/`. The matching module dataloader performs sampling of matches and non-matches for feeding to the contrastive loss function. ## Losses We provide an implementation of the contrastive loss function with hard negative mining. We also provide a binary cross entropy loss implementation with a dice loss component. You can find the loss functions in `code/ml/losses.py`. ## Planner The planner module class resides in `code/planner/`. Here's a code snippet for how to use it: ``` planner = Planner((uc, vc)) # instantiate planner with kit center ret = planner.plan(suction_scores, placement_scores, outs_s, outs_t) # feed it suction and place heatmaps and descriptor maps best_place_uv = ret['best_place_uv'] best_suction_uv = ret['best_suction_uv'] best_rotation_idx = ret['best_rotation_idx'] ``` ## GUI We provide an interactive GUI for visualizing trained matching network outputs. This can be crucial for debugging and iterating over hyperparameters and designs. The GUI code resides in `code/gui`. <p align="center"> <img src="../assets/gui1.png" width=48% alt="Drawing"> <img src="../assets/gui2.png" width=48% alt="Drawing"> </p> For a video of the GUI in action, click [here](https://youtu.be/bkUKCOdVSOQ).<file_sep>/form2fit/code/planner/__init__.py from form2fit.code.planner.planner import Planner<file_sep>/form2fit/code/ml/dataloader/meta.py """A meta-dataloader for iterating over combinations of datasets. """ import random from form2fit.code.ml.dataloader.suction import * from form2fit.code.ml.dataloader.placement import * from form2fit.code.ml.dataloader.correspondence import * class MetaLoader: def __init__(self, names, dtype, stype, kwargs): self.names = names self.dtype = dtype self.kwargs = kwargs if stype == "corr": func = get_corr_loader elif stype == "suction": func = get_suction_loader elif stype == "place": func = get_placement_loader else: raise ValueError("{} not supported.".format(stype)) self.dsets = [] for name, kwarg in zip(self.names, self.kwargs): self.dsets.append(func(name, dtype=self.dtype, **kwarg)) self.loaders = [iter(d) for d in self.dsets] self.num_loaders = len(self.loaders) self.iter = 0 def __iter__(self): return self def __next__(self): """Samples from each dataset consecutively. """ dset_idx = self.iter % self.num_loaders try: imgs, labels = next(self.loaders[dset_idx]) except StopIteration: self.loaders[dset_idx] = iter(self.dsets[dset_idx]) imgs, labels = next(self.loaders[dset_idx]) self.iter += 1 return imgs, labels<file_sep>/form2fit/code/gui/main.py """A GUI for interacting with a trained descriptor network. """ import argparse import os import sys import glob import pickle import torch import torch.nn as nn import numpy as np import matplotlib.cm as cm from form2fit import config from form2fit.code.ml.models import * from form2fit.code.ml.dataloader import get_corr_loader from form2fit.code.utils import ml, misc from PyQt5.QtGui import * from PyQt5.QtWidgets import * from PyQt5.QtCore import * class Debugger(QDialog): """A PyQt5 GUI for debugging a descriptor network. """ USE_CUDA = True WINDOW_WIDTH = 1500 WINDOW_HEIGHT = 1000 WINDOW_TITLE = "Debug Descriptor Network" def __init__(self, args): super().__init__() self._foldername = args.foldername self._dtype = args.dtype self._num_desc = args.num_desc self._background_subtract = args.background_subtract self._augment = args.augment self._num_channels = args.num_channels self._init_loader_and_network() self._reset() self._init_UI() self.show() def _init_loader_and_network(self): """Initializes the data loader and network. """ self._dev = torch.device("cuda" if Debugger.USE_CUDA and torch.cuda.is_available() else "cpu") self._data = get_corr_loader( self._foldername, batch_size=1, sample_ratio=1, dtype=self._dtype, shuffle=False, num_workers=0, augment=self._augment, num_rotations=20, background_subtract=config.BACKGROUND_SUBTRACT[self._foldername], num_channels=self._num_channels, ) self._net = CorrespondenceNet(self._num_channels, self._num_desc, 20).to(self._dev) self._net.eval() stats = self._data.dataset.stats self._color_mean = stats[0][0] self._color_std = stats[0][1] self._resolve_data_dims() def _resolve_data_dims(self): """Reads the image dimensions from the data loader. """ x, _, _ = next(iter(self._data)) self._h, self._w = x.shape[2:] self._c = 3 self._zeros = np.zeros((self._h, self._w, self._c), dtype="uint8") self.xs = None self.xt = None def _reset(self): """Resets the GUI. """ def _he_init(m): if isinstance(m, (nn.Conv2d, nn.Linear)): nn.init.kaiming_normal_(m.weight, mode="fan_in") self._is_switch = False self._pair_idx = 0 self._dloader = iter(self._data) self._get_network_names() self._net.apply(_he_init) def _get_network_names(self): """Reads all saved model weights. """ self.weights_dir = os.path.join(config.weights_dir, "matching") filenames = glob.glob(os.path.join(self.weights_dir, "*.tar")) self._model_names = [os.path.basename(x).split(".")[0] for x in filenames] def _load_selected_network(self, name): """Loads a trained network. """ if name: self._model_name = name state_dict = torch.load(os.path.join(self.weights_dir, name + ".tar"), map_location=self._dev) self._net.load_state_dict(state_dict['model_state']) self._set_prediction_text("{} was loaded...".format(name)) def _init_UI(self): """Initializes the UI. """ self.setWindowTitle(Debugger.WINDOW_TITLE) # self.setFixedSize(Debugger.WINDOW_WIDTH, Debugger.WINDOW_HEIGHT) self._create_menu() self._create_main() self._create_progress() self._all_layout = QVBoxLayout(self) self._all_layout.addLayout(self._menu_layout) self._all_layout.addLayout(self._main_layout) self._all_layout.addLayout(self._progress_layout) def _create_menu(self): """Creates the top horizontal menu bar. """ # buttons next_button = QPushButton("Next Pair", self) next_button.clicked.connect(self._next_click) reset_button = QPushButton("Reset", self) reset_button.clicked.connect(self._reset_click) sample_button = QPushButton("Sample", self) sample_button.clicked.connect(self._sample_click) colorize_button = QPushButton("Rotation Error", self) colorize_button.clicked.connect(self._colorize_click) self._switch_button = QPushButton("View RGB", self) self._switch_button.clicked.connect(self._switch_click) # boxes self._is_correct_box = QLabel(self) self._networks_box = QComboBox(self) self._networks_box.addItems([""] + self._model_names) self._networks_box.activated[str].connect(self._load_selected_network) self._networks_box_label = QLabel("Network Name", self) self._networks_box_label.setBuddy(self._networks_box) # add to layout self._menu_layout = QHBoxLayout() self._menu_layout.addWidget(self._networks_box_label) self._menu_layout.addWidget(self._networks_box) self._menu_layout.addWidget(next_button) self._menu_layout.addWidget(sample_button) self._menu_layout.addWidget(colorize_button) self._menu_layout.addWidget(self._is_correct_box) self._menu_layout.addStretch(1) self._menu_layout.addWidget(self._switch_button) self._menu_layout.addWidget(reset_button) def _create_main(self): """Creates the main layout. """ vbox_left = QVBoxLayout() grid_right = QGridLayout() self._target_widget = QLabel(self) self._source_widget = QLabel(self) self._grid_widgets = [QLabel(self) for _ in range(20)] self._draw_target(init=True) self._draw_source(init=True) vbox_left.addWidget(self._target_widget) vbox_left.addWidget(self._source_widget) self._target_widget.mousePressEvent = self._get_mouse_pos self._draw_rotations(init=True) for col in range(5): for row in range(4): grid_right.addWidget(self._grid_widgets[col * 4 + row], col, row) self._main_layout = QHBoxLayout() self._main_layout.addLayout(vbox_left) self._main_layout.addLayout(grid_right) def _create_progress(self): """A progress bar for the data loader. """ self._progress_bar = QProgressBar(self) self._progress_bar.setRange(0, len(self._dloader)) self._progress_bar.setValue(0) self._progress_layout = QHBoxLayout() self._progress_layout.addWidget(self._progress_bar) self._advance_progress_bar() def _draw_target(self, uv=None, init=False): img_target = self._zeros.copy() if init else self._xt_np.copy() if uv is not None: img_target[uv[0] - 1 : uv[0] + 1, uv[1] - 1 : uv[1] + 1] = [255, 0, 0] self._target_img = QImage( img_target.data, self._w, self._h, self._c * self._w, QImage.Format_RGB888 ) self._target_pixmap = QPixmap.fromImage(self._target_img) self._target_widget.setPixmap(self._target_pixmap) self._target_widget.setScaledContents(True) def _draw_source(self, uvs=None, init=False): if uvs is None: img_source = self._zeros.copy() if init else self._xs_np.copy() else: img_source = self._xt_np.copy() colors = [[0, 255, 0], [0, 0, 255], [255, 0, 0]] color_names = ["green", "blue", "red"] for i in range(3): mask = np.where(uvs[:, 2] == i)[0] idxs = uvs[mask] img_source[idxs[:, 0], idxs[:, 1]] = colors[i] self._source_img = QImage( img_source.data, self._w, self._h, self._c * self._w, QImage.Format_RGB888 ) self._source_pixmap = QPixmap.fromImage(self._source_img) self._source_widget.setPixmap(self._source_pixmap) self._source_widget.setScaledContents(True) def _draw_rotations(self, init=False, heatmap=True): def _hist_eq(img): from skimage import exposure img_cdf, bin_centers = exposure.cumulative_distribution(img) return np.interp(img, bin_centers, img_cdf) for col in range(5): for row in range(4): offset = col * 4 + row if init: img = self._zeros.copy() else: if heatmap: img = self.heatmaps[offset].copy() img = img / img.max() img = _hist_eq(img) img = np.uint8(cm.viridis(img) * 255)[..., :3] img = img.copy() else: img = misc.rotate_img(self._xs_np, -(360 / 20) * offset, center=(self.center[1], self.center[0])) img = img.copy() if offset == self._uv[-1]: img[ self._uv[0] - 1 : self._uv[0] + 1, self._uv[1] - 1 : self._uv[1] + 1, ] = [255, 0, 0] self._add_border_clr(img, [255, 0, 0]) if offset == self.best_rot_idx: self._add_border_clr(img, [0, 255, 0]) self._img = QImage( img.data, self._w, self._h, self._c * self._w, QImage.Format_RGB888 ) pixmap = QPixmap.fromImage(self._img) self._grid_widgets[offset].setPixmap(pixmap) self._grid_widgets[offset].setScaledContents(True) def _switch_click(self): if not self._is_switch: self._switch_button.setText("Heatmap View") self._is_switch = True self._draw_rotations(heatmap=False) else: self._switch_button.setText("RGB View") self._is_switch = False self._draw_rotations(heatmap=True) def _next_click(self): if self._pair_idx == len(self._dloader): self.close() else: self._get_next_data() self._draw_target() self._draw_source() self._draw_rotations(init=True) self._advance_progress_bar() def _reset_click(self): self._reset() self._networks_box.setCurrentIndex(0) self._draw_target(init=True) self._draw_source(init=True) self._draw_rotations(init=True) self._advance_progress_bar() def _colorize_click(self): filename = os.path.join( config.rot_stats_dir, self._model_name, self._dtype, str(self._pair_idx - 1), "rot_color.npy", ) pixel_colors = np.load(filename) self._draw_source(pixel_colors) def _set_prediction_text(self, msg): self._is_correct_box.setText(msg) def _sample_click(self): if self._pair_idx > 0: self._forward_network() rand_idx = np.random.choice(np.arange(len(self.target_pixel_idxs))) u_rand, v_rand = self.target_pixel_idxs[rand_idx] self._draw_target([u_rand, v_rand]) u_s, v_s = self.source_pixel_idxs[rand_idx] target_vector = self.out_t[:, :, u_rand, v_rand] outs_flat = self.outs.view(self.outs.shape[0], self.outs.shape[1], -1) target_vector_flat = target_vector.unsqueeze_(2).repeat( (outs_flat.shape[0], 1, outs_flat.shape[2]) ) diff = outs_flat - target_vector_flat dist = diff.pow(2).sum(1).sqrt() self.heatmaps = dist.view(dist.shape[0], self._h, self._w).cpu().numpy() predicted_best_idx = dist.min(dim=1)[0].argmin() is_correct = predicted_best_idx == self.best_rot_idx msg = "Correct!" if is_correct else "Wrong!" self._set_prediction_text(msg) min_val = self.heatmaps[predicted_best_idx].argmin() u_min, v_min = misc.make2d(min_val, self._w) self._uv = [u_min, v_min, predicted_best_idx] self._draw_rotations(heatmap=not self._is_switch) else: print("[!] You must first click next to load a data sample.") def _get_mouse_pos(self, event): v = event.pos().x() u = event.pos().y() u = int(u * (self._h / self._target_widget.height())) v = int(v * (self._w / self._target_widget.width())) uv = [u, v] if self.xs is not None and self.xt is not None: self._forward_network() row_idx = np.where((self.target_pixel_idxs == uv).all(axis=1))[0] if row_idx.size != 0: row_idx = row_idx[0] self._draw_target(uv) u_s, v_s = self.source_pixel_idxs[row_idx] target_vector = self.out_t[:, :, uv[0], uv[1]] outs_flat = self.outs.view(self.outs.shape[0], self.outs.shape[1], -1) target_vector_flat = target_vector.unsqueeze_(2).repeat( (outs_flat.shape[0], 1, outs_flat.shape[2]) ) diff = outs_flat - target_vector_flat dist = diff.pow(2).sum(1).sqrt() self.heatmaps = dist.view(dist.shape[0], self._h, self._w).cpu().numpy() predicted_best_idx = dist.min(dim=1)[0].argmin() is_correct = predicted_best_idx == self.best_rot_idx msg = "Correct!" if is_correct else "Wrong!" self._set_prediction_text(msg) min_val = self.heatmaps[predicted_best_idx].argmin() u_min, v_min = misc.make2d(min_val, self._w) self._uv = [u_min, v_min, predicted_best_idx] self._draw_rotations(heatmap=not self._is_switch) def _get_next_data(self): """Grabs a fresh pair of source and target data points. """ self._pair_idx += 1 self.imgs, labels, center = next(self._dloader) self.center = center[0] label = labels[0] self.xs, self.xt = self.imgs[:, :self._num_channels, :, :], self.imgs[:, self._num_channels:, :, :] if self._num_channels == 4: self._xs_np = ml.tensor2ndarray(self.xs[:, :3], [self._color_mean * 3, self._color_std * 3]) self._xt_np = ml.tensor2ndarray(self.xt[:, :3], [self._color_mean * 3, self._color_std * 3]) else: self._xs_np = ml.tensor2ndarray(self.xs[:, :1], [self._color_mean, self._color_std], False) self._xt_np = ml.tensor2ndarray(self.xt[:, :1], [self._color_mean, self._color_std], False) self._xs_np = np.uint8(cm.viridis(self._xs_np) * 255)[..., :3] self._xt_np = np.uint8(cm.viridis(self._xt_np) * 255)[..., :3] source_idxs = label[:, 0:2] target_idxs = label[:, 2:4] rot_idx = label[:, 4] is_match = label[:, 5] self.best_rot_idx = rot_idx[0].item() mask = (is_match == 1) & (rot_idx == self.best_rot_idx) self.source_pixel_idxs = source_idxs[mask].numpy() self.target_pixel_idxs = target_idxs[mask].numpy() def _forward_network(self): """Forwards the current source-target pair through the network. """ self.imgs = self.imgs.to(self._dev) with torch.no_grad(): self.outs, self.out_t = self._net(self.imgs, *self.center) self.outs = self.outs[0] def _advance_progress_bar(self): """Advances the progress bar. """ curr_val = self._pair_idx max_val = self._progress_bar.maximum() self._progress_bar.setValue(curr_val + (max_val - curr_val) / 100) def _add_border_clr(self, img, color): """Adds a border color to an image. """ img[0 : self._h - 1, 0:10] = color # left img[0:10, 0 : self._w - 1] = color # top img[self._h - 11 : self._h - 1, 0 : self._w - 1] = color img[0 : self._h - 1, self._w - 11 : self._w - 1] = color return img if __name__ == "__main__": def str2bool(s): return s.lower() in ["1", "true"] parser = argparse.ArgumentParser(description="Descriptor Network Visualizer") parser.add_argument("foldername", type=str) parser.add_argument("--dtype", type=str, default="valid") parser.add_argument("--num_desc", type=int, default=64) parser.add_argument("--num_channels", type=int, default=2) parser.add_argument("--background_subtract", type=tuple, default=None) parser.add_argument("--augment", type=str2bool, default=False) args, unparsed = parser.parse_known_args() app = QApplication(sys.argv) window = Debugger(args) window.show() sys.exit(app.exec_()) <file_sep>/form2fit/code/ml/losses.py """Various loss function definitions. """ from abc import ABC, abstractmethod import numpy as np import torch import torch.nn.functional as F def zero_loss(device): return torch.FloatTensor([0]).to(device) def nanmean(x): """Computes the arithmetic mean, ignoring any NaNs. """ return torch.mean(x[x == x]) def pixel2spatial(xs, H, W): """Converts a tensor of coordinates to a boolean spatial map. """ xs_spatial = [] for x in xs: pos = x[x[:, 2] == 1][:, :2] pos_label = torch.zeros(1, 1, H, W) pos_label[:, :, pos[:, 0], pos[:, 1]] = 1 xs_spatial.append(pos_label) xs_spatial = torch.cat(xs_spatial, dim=0).long() return xs_spatial class BaseLoss(ABC): def __call__(self, *args, **kwargs): return self.forward(*args, **kwargs) @abstractmethod def forward(self, *args, **kwargs): pass class SuctionLoss(BaseLoss): """The loss for training a suction prediction network. """ def __init__(self, sample_ratio, device, mean=True): self.sample_ratio = torch.FloatTensor([sample_ratio]).to(device) self._device = device self._mean = mean def forward(self, out, label, add_dice_loss=False): batch_size = len(label) if self._mean: loss = zero_loss(self._device) for i, l in enumerate(label): logits = out[i, :, l[:, 0], l[:, 1]] target = l[:, 2].unsqueeze(0).float() loss += F.binary_cross_entropy_with_logits(logits, target, self.sample_ratio) loss /= batch_size else: loss = [] for i, l in enumerate(label): logits = out[i, :, l[:, 0], l[:, 1]] target = l[:, 2].unsqueeze(0).float() loss.append(F.binary_cross_entropy_with_logits(logits, target, self.sample_ratio, reduction="none")) if add_dice_loss: label_spatial = pixel2spatial(label, out.shape[2], out.shape[3]) dice_loss = compute_dice_loss(label_spatial, out) loss = loss + (5 * dice_loss) return loss PlacementLoss = SuctionLoss class CorrespondenceLoss(BaseLoss): """The loss for training a correspondence prediction network. """ def __init__(self, margin, num_rotations, hard_negative, device, sample_ratio=None): self.margin = margin self.num_rotations = num_rotations self.sample_ratio = sample_ratio self._device = device self._hard_neg = hard_negative def _sq_hinge_loss(self, source, target, reduction=True): diff = source - target l2_dist = diff.pow(2).sum(1).sqrt() margin_diff = self.margin - l2_dist loss = torch.clamp(margin_diff, min=0).pow(2) if reduction: return loss.mean() return loss def _sq_l2(self, source, target, reduction=True): diff = source - target l2_dist_sq = diff.pow(2).sum(1) if reduction: return l2_dist_sq.mean() return l2_dist_sq def _positive_corrs(self, outs_s, outs_t, labels): """Computes match loss. """ batch_size = len(labels) match_loss = zero_loss(self._device) for b_idx, label in enumerate(labels): mask = torch.all(label == torch.LongTensor([999]).repeat(6).to(self._device), dim=1) label = label[~mask] source_idxs = label[:, 0:2] target_idxs = label[:, 2:4] rot_idx = label[:, 4] is_match = label[:, 5] correct_rot_idx = rot_idx[0] out_s = outs_s[b_idx] D, H, W = outs_t.shape[1:] out_t = outs_t[b_idx : b_idx + 1] out_t_flat = out_t.view(1, D, H*W).permute(0, 2, 1) mask = (is_match == 1) & (rot_idx == correct_rot_idx) s_idxs = source_idxs[mask] t_idxs = target_idxs[mask] s_idxs_f = s_idxs[:, 0] * W + s_idxs[:, 1] t_idxs_f = t_idxs[:, 0] * W + t_idxs[:, 1] out_s_flat = out_s[correct_rot_idx:correct_rot_idx+1].view(1, D, H*W).permute(0, 2, 1) match_s_descriptors = torch.index_select(out_s_flat, 1, s_idxs_f).squeeze(0) match_t_descriptors = torch.index_select(out_t_flat, 1, t_idxs_f).squeeze(0) match_loss += self._sq_l2(match_s_descriptors, match_t_descriptors) match_loss /= batch_size return match_loss def _negative_corrs(self, outs_s, outs_t, labels): """Computes non-match loss. """ batch_size = len(labels) non_match_loss = zero_loss(self._device) for b_idx, label in enumerate(labels): mask = torch.all(label == torch.LongTensor([999]).repeat(6).to(self._device), dim=1) label = label[~mask] source_idxs = label[:, 0:2] target_idxs = label[:, 2:4] rot_idx = label[:, 4] is_match = label[:, 5] out_s = outs_s[b_idx] D, H, W = outs_t.shape[1:] out_t = outs_t[b_idx : b_idx + 1] out_t_flat = out_t.view(1, D, H*W).permute(0, 2, 1) non_match_s_descriptors = [] non_match_t_descriptors = [] for r_idx in range(self.num_rotations): mask = (is_match != 1) & (rot_idx == r_idx) s_idxs = source_idxs[mask] t_idxs = target_idxs[mask] s_idxs_f = s_idxs[:, 0] * W + s_idxs[:, 1] t_idxs_f = t_idxs[:, 0] * W + t_idxs[:, 1] out_s_flat = out_s[r_idx : r_idx + 1].view(1, D, H*W).permute(0, 2, 1) non_match_s_descriptors.append(torch.index_select(out_s_flat, 1, s_idxs_f).squeeze(0)) non_match_t_descriptors.append(torch.index_select(out_t_flat, 1, t_idxs_f).squeeze(0)) if self._hard_neg: for des_s, des_t in zip(non_match_s_descriptors, non_match_t_descriptors): with torch.no_grad(): loss = self._sq_hinge_loss(des_s, des_t, False) hard_negative_idxs = torch.nonzero(loss) if hard_negative_idxs.size(0) != 0: des_s = des_s[hard_negative_idxs.squeeze()] des_t = des_t[hard_negative_idxs.squeeze()] if des_s.ndimension() < 2: des_s.unsqueeze_(0) des_t.unsqueeze_(0) non_match_loss += self._sq_hinge_loss(des_s, des_t) else: non_match_s_descriptors = torch.cat(non_match_s_descriptors, dim=0) non_match_t_descriptors = torch.cat(non_match_t_descriptors, dim=0) non_match_loss += self._sq_hinge_loss(non_match_s_descriptors, non_match_t_descriptors) non_match_loss /= batch_size return non_match_loss def forward(self, outs_s, outs_t, labels): """Computes contrastive loss. Args: outs_s: list of len B, rotations x D x H x W. outs_t: B x D x H x W labels: N x 6 """ match_loss = self._positive_corrs(outs_s, outs_t, labels) non_match_loss = self._negative_corrs(outs_s, outs_t, labels) if self.sample_ratio is not None: assert not np.isclose(self.sample_ratio, 0.0), "[!] Sample ratio cannot be zero." loss = (self.sample_ratio * match_loss) + non_match_loss return match_loss, non_match_loss class TripletLoss(BaseLoss): """The triplet loss for training a correspondence prediction network. """ def __init__(self, alpha, num_rotations, device): self.alpha = alpha self.num_rotations = num_rotations self._device = device def _triplet_loss(self, anchors, positives, negatives): diff_pos = (anchors - positives).pow(2).sum(1) diff_neg = (anchors - negatives).pow(2).sum(1) return torch.clamp(diff_pos - diff_neg + self.alpha, min=0).mean() def forward(self, outs_s, outs_t, labels): B, D, H, W = outs_t.shape batch_size = len(labels) loss = zero_loss(self._device) for b_idx, label in enumerate(labels): mask = torch.all( label == torch.LongTensor([999]).repeat(6).to(self._device), dim=1 ) label = label[~mask] source_idxs = label[:, 0:2] target_idxs = label[:, 2:4] rot_idx = label[:, 4] is_match = label[:, 5] r_idx = rot_idx[0] out_s = outs_s[b_idx] out_t = outs_t[b_idx : b_idx + 1] mask = (is_match == 1) & (rot_idx == r_idx) match_s_idxs = source_idxs[mask] match_t_idxs = target_idxs[mask] mask = is_match != 1 non_match_s_idxs = source_idxs[mask] non_match_rot_idxs = rot_idx[mask] match_s_idxs_f = match_s_idxs[:, 0] * W + match_s_idxs[:, 1] out_s_flat = out_s[r_idx : r_idx + 1].view(1, D, H * W).permute(0, 2, 1) positives = torch.index_select(out_s_flat, 1, match_s_idxs_f).squeeze(0) match_t_idxs_f = match_t_idxs[:, 0] * W + match_t_idxs[:, 1] out_t_flat = out_t.view(1, D, H * W).permute(0, 2, 1) anchors = torch.index_select(out_t_flat, 1, match_t_idxs_f).squeeze(0) rand_idxs = np.random.choice( np.arange(len(non_match_rot_idxs)), replace=False, size=len(match_s_idxs_f), ) negatives = [] for idx in rand_idxs: nm_rot_idx = non_match_rot_idxs[idx] non_match_s_idx = non_match_s_idxs[idx] non_match_s_idx_f = non_match_s_idx[0] * W + non_match_s_idx[1] out_s_flat = ( out_s[nm_rot_idx : nm_rot_idx + 1] .view(1, D, H * W) .permute(0, 2, 1) ) negatives.append( torch.index_select(out_s_flat, 1, non_match_s_idx_f).squeeze(0) ) negatives = torch.cat(negatives, dim=0) loss += self._triplet_loss(anchors, positives, negatives) loss /= batch_size return loss def compute_bce_loss(true, logits, pos_weight=None): """Computes the weighted binary cross-entropy loss. Args: true: a tensor of shape [B, 1, H, W]. logits: a tensor of shape [B, 1, H, W]. Corresponds to the raw output or logits of the model. pos_weight: a scalar representing the weight attributed to the positive class. This is especially useful for an imbalanced dataset. Returns: bce_loss: the weighted binary cross-entropy loss. """ bce_loss = F.binary_cross_entropy_with_logits( logits.float(), true.float(), pos_weight=pos_weight, ) return bce_loss def compute_ce_loss(true, logits, weights, ignore=255): """Computes the weighted multi-class cross-entropy loss. Args: true: a tensor of shape [B, 1, H, W]. logits: a tensor of shape [B, C, H, W]. Corresponds to the raw output or logits of the model. weight: a tensor of shape [C,]. The weights attributed to each class. ignore: the class index to ignore. Returns: ce_loss: the weighted multi-class cross-entropy loss. """ ce_loss = F.cross_entropy( logits.float(), true.long(), ignore_index=ignore, weight=weights, ) return ce_loss def compute_dice_loss(true, logits, eps=1e-7): """Computes the Sørensen–Dice loss. Note that PyTorch optimizers minimize a loss. In this case, we would like to maximize the dice loss so we return the negated dice loss. Args: true: a tensor of shape [B, 1, H, W]. logits: a tensor of shape [B, C, H, W]. Corresponds to the raw output or logits of the model. eps: added to the denominator for numerical stability. Returns: dice_loss: the Sørensen–Dice loss. """ num_classes = logits.shape[1] if num_classes == 1: true_1_hot = torch.eye(num_classes + 1)[true.squeeze(1)] true_1_hot = true_1_hot.permute(0, 3, 1, 2).float() true_1_hot_f = true_1_hot[:, 0:1, :, :] true_1_hot_s = true_1_hot[:, 1:2, :, :] true_1_hot = torch.cat([true_1_hot_s, true_1_hot_f], dim=1) pos_prob = torch.sigmoid(logits) neg_prob = 1 - pos_prob probas = torch.cat([pos_prob, neg_prob], dim=1) else: true_1_hot = torch.eye(num_classes)[true.squeeze(1)] true_1_hot = true_1_hot.permute(0, 3, 1, 2).float() probas = F.softmax(logits, dim=1) true_1_hot = true_1_hot.type(logits.type()) dims = (0,) + tuple(range(2, true.ndimension())) intersection = torch.sum(probas * true_1_hot, dims) cardinality = torch.sum(probas + true_1_hot, dims) dice_loss = (2. * intersection / (cardinality + eps)).mean() return (1 - dice_loss) def compute_jaccard_loss(true, logits, eps=1e-7): """Computes the Jaccard loss, a.k.a the IoU loss. Note that PyTorch optimizers minimize a loss. In this case, we would like to maximize the jaccard loss so we return the negated jaccard loss. Args: true: a tensor of shape [B, H, W] or [B, 1, H, W]. logits: a tensor of shape [B, C, H, W]. Corresponds to the raw output or logits of the model. eps: added to the denominator for numerical stability. Returns: jacc_loss: the Jaccard loss. """ num_classes = logits.shape[1] if num_classes == 1: true_1_hot = torch.eye(num_classes + 1)[true.squeeze(1)] true_1_hot = true_1_hot.permute(0, 3, 1, 2).float() true_1_hot_f = true_1_hot[:, 0:1, :, :] true_1_hot_s = true_1_hot[:, 1:2, :, :] true_1_hot = torch.cat([true_1_hot_s, true_1_hot_f], dim=1) pos_prob = torch.sigmoid(logits) neg_prob = 1 - pos_prob probas = torch.cat([pos_prob, neg_prob], dim=1) else: true_1_hot = torch.eye(num_classes)[true.squeeze(1)] true_1_hot = true_1_hot.permute(0, 3, 1, 2).float() probas = F.softmax(probas, dim=1) true_1_hot = true_1_hot.type(logits.type()) dims = (0,) + tuple(range(2, true.ndimension())) intersection = torch.sum(probas * true_1_hot, dims) cardinality = torch.sum(probas + true_1_hot, dims) union = cardinality - intersection jacc_loss = (intersection / (union + eps)).mean() return (1 - jacc_loss) def compute_tversky_loss(true, logits, alpha, beta, eps=1e-7): """Computes the Tversky loss [1]. Args: true: a tensor of shape [B, H, W] or [B, 1, H, W]. logits: a tensor of shape [B, C, H, W]. Corresponds to the raw output or logits of the model. alpha: controls the penalty for false positives. beta: controls the penalty for false negatives. eps: added to the denominator for numerical stability. Returns: tversky_loss: the Tversky loss. Notes: alpha = beta = 0.5 => dice coeff alpha = beta = 1 => tanimoto coeff alpha + beta = 1 => F beta coeff References: [1]: https://arxiv.org/abs/1706.05721 """ num_classes = logits.shape[1] if num_classes == 1: true_1_hot = torch.eye(num_classes + 1)[true.squeeze(1)] true_1_hot = true_1_hot.permute(0, 3, 1, 2).float() true_1_hot_f = true_1_hot[:, 0:1, :, :] true_1_hot_s = true_1_hot[:, 1:2, :, :] true_1_hot = torch.cat([true_1_hot_s, true_1_hot_f], dim=1) pos_prob = torch.sigmoid(logits) neg_prob = 1 - pos_prob probas = torch.cat([pos_prob, neg_prob], dim=1) else: true_1_hot = torch.eye(num_classes)[true.squeeze(1)] true_1_hot = true_1_hot.permute(0, 3, 1, 2).float() probas = F.softmax(probas, dim=1) true_1_hot = true_1_hot.type(logits.type()) dims = (0,) + tuple(range(2, true.ndimension())) intersection = torch.sum(probas * true_1_hot, dims) fps = torch.sum(probas * (1 - true_1_hot), dims) fns = torch.sum((1 - probas) * true_1_hot, dims) num = intersection denom = intersection + (alpha * fps) + (beta * fns) tversky_loss = (num / (denom + eps)).mean() return (1 - tversky_loss)<file_sep>/form2fit/__init__.py """Form2Fit Code and Benchmark. """<file_sep>/form2fit/code/eval_form2fit.py """Run the Form2Fit models on the benchmark. """ import argparse import os import pickle import cv2 import matplotlib.pyplot as plt import numpy as np import torch from tqdm import tqdm from scipy.stats import mode from form2fit import config from form2fit.code.ml.models import CorrespondenceNet from form2fit.code.ml.dataloader import get_corr_loader from form2fit.code.utils import misc, ml from form2fit.code.utils.pointcloud import transform_xyz from walle.core import Pose, RotationMatrix def main(args): device = torch.device("cuda") if torch.cuda.is_available() else torch.device("cpu") save_dir = os.path.join("./dump/") if not os.path.exists(save_dir): os.makedirs(save_dir) dloader = get_corr_loader( args.foldername, batch_size=1, sample_ratio=1, shuffle=False, dtype=args.dtype, num_rotations=20, num_workers=1, markovian=True, augment=False, background_subtract=config.BACKGROUND_SUBTRACT[args.foldername], ) stats = dloader.dataset.stats color_mean = stats[0][0] color_std = stats[0][1] depth_mean = stats[1][0] depth_std = stats[1][1] # load model model = CorrespondenceNet(2, 64, 20).to(device) state_dict = torch.load(os.path.join(config.weights_dir, "matching", args.foldername + ".tar"), map_location=device) model.load_state_dict(state_dict['model_state']) model.eval() estimated_poses = [] for idx, (imgs, labels, center) in enumerate(dloader): print("{}/{}".format(idx+1, len(dloader))) imgs, labels = imgs.to(device), labels.to(device) # remove padding from labels label = labels[0] mask = torch.all(label == torch.LongTensor([999]).repeat(6).to(device), dim=1) label = label[~mask] # extract correspondences from label source_idxs = label[:, 0:2] target_idxs = label[:, 2:4] rot_idx = label[:, 4] is_match = label[:, 5] correct_rot = rot_idx[0] mask = (is_match == 1) & (rot_idx == correct_rot) kit_idxs = source_idxs[mask] obj_idxs = target_idxs[mask] kit_idxs_all = kit_idxs.clone() obj_idxs_all = obj_idxs.clone() if args.subsample is not None: kit_idxs = kit_idxs[::int(args.subsample)] obj_idxs = obj_idxs[::int(args.subsample)] H, W = imgs.shape[2:] # compute kit and object descriptor maps with torch.no_grad(): outs_s, outs_t = model(imgs, *center[0]) out_s = outs_s[0] D, H, W = outs_t.shape[1:] out_t = outs_t[0:1] out_t_flat = out_t.view(1, D, H * W).permute(0, 2, 1) color_kit = ml.tensor2ndarray(imgs[:, 0, :], [color_mean, color_std], True).squeeze() color_obj = ml.tensor2ndarray(imgs[:, 2, :], [color_mean, color_std], True).squeeze() depth_kit = ml.tensor2ndarray(imgs[:, 1, :], [depth_mean, depth_std], False).squeeze() depth_obj = ml.tensor2ndarray(imgs[:, 3, :], [depth_mean, depth_std], False).squeeze() if args.debug: kit_idxs_np = kit_idxs_all.detach().cpu().numpy().squeeze() obj_idxs_np = obj_idxs_all.detach().cpu().numpy().squeeze() fig, axes = plt.subplots(1, 2) color_kit_r = misc.rotate_img(color_kit, -(360/20)*correct_rot, center=(center[0][1], center[0][0])) axes[0].imshow(color_kit_r) axes[0].scatter(kit_idxs_np[:, 1], kit_idxs_np[:, 0], c='r') axes[1].imshow(color_obj) axes[1].scatter(obj_idxs_np[:, 1], obj_idxs_np[:, 0], c='b') for ax in axes: ax.axis('off') plt.show() # loop through ground truth correspondences obj_uvs = [] predicted_kit_uvs = [] rotations = [] correct = 0 for corr_idx, (u, v) in enumerate(tqdm(obj_idxs, leave=False)): idx_flat = u*W + v target_descriptor = torch.index_select(out_t_flat, 1, idx_flat).squeeze(0) outs_s_flat = out_s.view(20, out_s.shape[1], H*W) target_descriptor = target_descriptor.unsqueeze(0).repeat(20, H*W, 1).permute(0, 2, 1) diff = outs_s_flat - target_descriptor l2_dist = diff.pow(2).sum(1).sqrt() heatmaps = l2_dist.view(l2_dist.shape[0], H, W).cpu().numpy() predicted_best_idx = l2_dist.min(dim=1)[0].argmin() rotations.append(predicted_best_idx.item()) if predicted_best_idx == correct_rot: correct += 1 min_val = heatmaps[predicted_best_idx].argmin() u_min, v_min = np.unravel_index(min_val, (H, W)) predicted_kit_uvs.append([u_min.item(), v_min.item()]) obj_uvs.append([u.item(), v.item()]) # print("acc: {}".format(correct / len(obj_idxs))) # compute rotation majority best_rot = mode(rotations)[0][0] # eliminate correspondences with rotation different than mode select_idxs = np.array(rotations) == best_rot predicted_kit_uvs = np.array(predicted_kit_uvs)[select_idxs] obj_uvs = np.array(obj_uvs)[select_idxs] # use predicted correspondences to estimate affine transformation src_pts = np.array(obj_uvs)[:, [1, 0]] dst_pts = np.array(predicted_kit_uvs) dst_pts = misc.rotate_uv(dst_pts, (360/20)*best_rot, H, W, cxcy=center[0])[:, [1, 0]] # compose transform zs = depth_obj[src_pts[:, 1], src_pts[:, 0]].reshape(-1, 1) src_xyz = np.hstack([src_pts, zs]) src_xyz[:, 0] = (src_xyz[:, 0] * config.HEIGHTMAP_RES) + config.VIEW_BOUNDS[0, 0] src_xyz[:, 1] = (src_xyz[:, 1] * config.HEIGHTMAP_RES) + config.VIEW_BOUNDS[1, 0] zs = depth_kit[dst_pts[:, 1], dst_pts[:, 0]].reshape(-1, 1) dst_pts[:, 0] += W dst_xyz = np.hstack([dst_pts, zs]) dst_xyz[:, 0] = (dst_xyz[:, 0] * config.HEIGHTMAP_RES) + config.VIEW_BOUNDS[0, 0] dst_xyz[:, 1] = (dst_xyz[:, 1] * config.HEIGHTMAP_RES) + config.VIEW_BOUNDS[1, 0] m1 = np.eye(4) dst_xyz[:, 2] = src_xyz[:, 2] m1[:3, 3] = np.mean(dst_xyz, axis=0) - np.mean(src_xyz, axis=0) m2 = np.eye(4) m2[:3, 3] = -np.mean(dst_xyz, axis=0) m3 = np.eye(4) m3[:3, :3] = RotationMatrix.rotz(np.radians(-(360/20)*best_rot)) m4 = np.eye(4) m4[:3, 3] = np.mean(dst_xyz, axis=0) estimated_pose = m4 @ m3 @ m2 @ m1 estimated_poses.append(estimated_pose) # plot if args.debug: img = np.zeros((H, W*2)) img[:, :W] = color_obj img[:, W:] = color_kit zs = depth_obj[obj_idxs_np[:, 0], obj_idxs_np[:, 1]].reshape(-1, 1) mask_xyz = np.hstack([obj_idxs_np, zs]) mask_xyz[:, [0, 1]] = mask_xyz[:, [1, 0]] mask_xyz[:, 0] = (mask_xyz[:, 0] * config.HEIGHTMAP_RES) + config.VIEW_BOUNDS[0, 0] mask_xyz[:, 1] = (mask_xyz[:, 1] * config.HEIGHTMAP_RES) + config.VIEW_BOUNDS[1, 0] mask_xyz = transform_xyz(mask_xyz, estimated_pose) mask_xyz[:, 0] = (mask_xyz[:, 0] - config.VIEW_BOUNDS[0, 0]) / config.HEIGHTMAP_RES mask_xyz[:, 1] = (mask_xyz[:, 1] - config.VIEW_BOUNDS[1, 0]) / config.HEIGHTMAP_RES hole_idxs = mask_xyz[:, [1, 0]] plt.imshow(img) plt.scatter(hole_idxs[:, 1], hole_idxs[:, 0]) plt.show() with open(os.path.join(save_dir, "{}_poses.pkl".format(args.foldername)), "wb") as fp: pickle.dump(estimated_poses, fp) if __name__ == "__main__": parser = argparse.ArgumentParser(description="Evaluate Form2Fit Matching Module on Benchmark") parser.add_argument("foldername", type=str, help="The name of the dataset.") parser.add_argument("dtype", type=str, default="valid") parser.add_argument("--subsample", type=int, default=1) parser.add_argument("--debug", type=lambda s: s.lower() in ["1", "true"], default=False) args, unparsed = parser.parse_known_args() main(args)<file_sep>/docs/conventions.md # Notation and Conventions * We use `u` to denote row coordinates and `v` to denote column coordinates. This means we index images using the `img[u, v]` format. * When de-projecting an image to 3D space, we convert `u` values to `y` values and `v` values to `x` values. This means our frame of reference is the top left corner of the image with x pointing right and y pointing down. * When scattering in matplotlib, we use `plt.scatter(vs, us)` to respect the above conventions.<file_sep>/README.md # Form2Fit Code for the paper **[Form2Fit: Learning Shape Priors for Generalizable Assembly from Disassembly][1]**<br/> *<NAME>, <NAME>, <NAME>, <NAME>*<br/> [arxiv.org/abs/1910.13675][2]<br/> ICRA 2020 <p align="center"> <img src="./assets/teaser.gif" width=100% alt="Drawing"> </p> This repository contains: - The [Form2Fit Benchmark](docs/about_benchmark.md) - Code to [download and process](#data) the benchmark datasets. - Code to [evaluate](docs/evaluate_benchmark.md) any model's performance on the benchmark test set. - Code to [reproduce](docs/paper_code.md) the paper results: - Architectures, dataloaders and losses for suction, place and matching networks. - Planner module for intergrating all the outputs. - Baseline implementation. If you find this code useful, consider citing our work: ``` @inproceedings{zakka2020form2fit, title={Form2Fit: Learning Shape Priors for Generalizable Assembly from Disassembly}, author={<NAME> and Zeng, Andy and <NAME> and <NAME>}, booktitle={Proceedings of the IEEE International Conference on Robotics and Automation}, year={2020} } ``` ### Documentation - [setup](docs/setup.md) - [about the Form2Fit benchmark](docs/about_benchmark.md) - [reproducing paper results](docs/paper_code.md) - [evaluating a trained model](docs/evaluate_benchmark.md) - [model weights](docs/model_weights.md) - [conventions](docs/conventions.md) ### Todos - [ ] Add processed generalization partition (combinations, mixtures and unseen) to benchmark. - [ ] Add code for training the different networks. ### Note This is not an officially supported Google product. [1]: https://form2fit.github.io/ [2]: https://arxiv.org/abs/1910.13675 <file_sep>/form2fit/benchmark/metrics.py """Compute various pose estimation metrics. Ref: https://github.com/yuxng/PoseCNN/blob/master/lib/utils/pose_error.py """ import cv2 import numpy as np from form2fit.code.utils.pointcloud import transform_xyz def rotational_error(R1, R2): r, _ = cv2.Rodrigues(R1.dot(R2.T)) return np.degrees(np.linalg.norm(r)) def translational_error(t1, t2): return np.linalg.norm(t1 - t2) def compute_ADD(pose_true, pred_pose, obj_xyz): """Computes the Average Distance Metric (ADD) [1]. [1]: https://arxiv.org/pdf/1711.00199.pdf """ obj_xyz_pred = transform_xyz(obj_xyz, pred_pose) obj_xyz_true = transform_xyz(obj_xyz, pose_true) return np.linalg.norm(obj_xyz_pred - obj_xyz_true, axis=1).mean() def reprojection_error(pose_true, pred_pose, obj_xyz, view_bounds, pixel_size): obj_xyz_pred = transform_xyz(obj_xyz, pred_pose) obj_xyz_true = transform_xyz(obj_xyz, pose_true) obj_xyz_pred[:, 0] = (obj_xyz_pred[:, 0] - view_bounds[0, 0]) / pixel_size obj_xyz_pred[:, 1] = (obj_xyz_pred[:, 1] - view_bounds[1, 0]) / pixel_size obj_idx_pred = obj_xyz_pred[:, [1, 0]] obj_xyz_true[:, 0] = (obj_xyz_true[:, 0] - view_bounds[0, 0]) / pixel_size obj_xyz_true[:, 1] = (obj_xyz_true[:, 1] - view_bounds[1, 0]) / pixel_size obj_idx_true = obj_xyz_true[:, [1, 0]] return np.linalg.norm(obj_idx_true - obj_idx_pred, axis=1).mean()<file_sep>/form2fit/code/utils/sampling.py """Sampling functions for non-matches. """ import numpy as np from form2fit.code.utils.misc import rotate_uv def make1d(uv, num_cols): uv = np.round(uv).astype("int") linear = uv[:, 0] * num_cols + uv[:, 1] return linear.astype("int") def make2d(linear, num_cols): v = linear % num_cols u = linear // num_cols return np.vstack([u, v]).T def remove_outliers(uv_1d, inside_2d, num_cols): u_min, u_max = np.min(inside_2d[:, 0]), np.max(inside_2d[:, 0]) v_min, v_max = np.min(inside_2d[:, 1]), np.max(inside_2d[:, 1]) uv_2d = make2d(uv_1d, num_cols) u_cond = np.logical_or(uv_2d[:, 0] <= u_min, uv_2d[:, 0] > u_max) v_cond = np.logical_or(uv_2d[:, 1] >= v_max, uv_2d[:, 1] < v_min) valid_ind = np.logical_or(u_cond, v_cond) uv_2d = uv_2d[valid_ind] return make1d(uv_2d, num_cols) def sample_non_matches( num_nm, shape, angle, mask_source=None, mask_target=None, rotate=True, cxcy=None, ): """Randomly generate negative correspondences between a source and target image. An optional mask can be provided for both the source and target to restrict the sampling space. Args: num_nm: (int) The number of negative correspondences to sample. shape: (tuple) The height and width of the source and target images. source_mask: (ndarray) ... target_mask: (ndarray) ... Returns: source_non_matches: (ndarray) The (u, v) coordinates of the negative correspondences in the source image. target_non_matches: (ndarray) The (u, v) coordinates of the positive correspondences in the target image. """ # define sampling spaces boundaries source_ss = (np.arange(0, shape[0] * shape[1]) if mask_source is None else mask_source) target_ss = (np.arange(0, shape[0] * shape[1]) if mask_target is None else mask_target) # rotate source indices if rotate: source_ss = rotate_uv(make2d(source_ss, shape[1]), angle, *shape, cxcy=cxcy) source_ss[:, 0] = np.clip(source_ss[:, 0], 0, shape[0] - 1) source_ss[:, 1] = np.clip(source_ss[:, 1], 0, shape[1] - 1) source_ss = make1d(source_ss, shape[1]) # subset sampling with replacement source_nm = np.random.choice(source_ss, size=num_nm, replace=True) target_nm = np.random.choice(target_ss, size=num_nm, replace=True) # convert to 2D coordinates source_nm = make2d(source_nm, shape[1]) target_nm = make2d(target_nm, shape[1]) return np.hstack([source_nm, target_nm]) def non_matches_from_matches( num_nm, shape, angle, mask_source, matches_source, matches_target, cxcy=None, ): """Create negative correspondences from positive ones. This ensures that we do not create negative correspondences that are actually positive. """ matches_source_1d = make1d(matches_source, shape[1]) matches_target_1d = make1d(matches_target, shape[1]) source_ss = rotate_uv(make2d(mask_source, shape[1]), angle, *shape, cxcy=cxcy) source_ss[:, 0] = np.clip(source_ss[:, 0], 0, shape[0] - 1) source_ss[:, 1] = np.clip(source_ss[:, 1], 0, shape[1] - 1) mask_source = make1d(source_ss, shape[1]) source_nm = [] target_nm = [] while len(source_nm) < num_nm: source_idx = np.random.choice(mask_source) source_loc = np.where(matches_source_1d == source_idx)[0] if source_loc.size != 0: actual_target = matches_target_1d[source_loc[0]] target_idx = np.random.choice(matches_target_1d) while target_idx == actual_target: target_idx = np.random.choice(matches_target_1d) else: target_idx = np.random.choice(matches_target_1d) source_nm.append(source_idx) target_nm.append(target_idx) source_nm = np.array(source_nm) target_nm = np.array(target_nm) # convert to 2D coordinates source_nm = make2d(source_nm, shape[1]) target_nm = make2d(target_nm, shape[1]) return np.hstack([source_nm, target_nm]) <file_sep>/form2fit/code/utils/common.py """A set of commonly used utilities. """ import datetime import os import numpy as np import skimage.io as io from PIL import Image def makedir(dirname): """Safely creates a new directory. """ if not os.path.exists(dirname): os.makedirs(dirname) def gen_timestamp(): """Generates a timestamp in YYYY-MM-DD-hh-mm-ss format. """ date = str(datetime.datetime.now()).split(".")[0] return date.split(" ")[0] + "-" + "-".join(date.split(" ")[1].split(":")) def colorsave(filename, x): """Saves an rgb image as a 24 bit PNG. """ io.imsave(filename, x, check_contrast=False) def depthsave(filename, x): """Saves a depth image as a 16 bit PNG. """ io.imsave(filename, (x * 1000).astype("uint16"), check_contrast=False) def colorload(filename): """Loads an rgb image as a numpy array. """ return np.asarray(Image.open(filename)) def depthload(filename): """Loads a depth image as a numpy array. """ x = np.asarray(Image.open(filename)) x = (x * 1e-3).astype("float32") return x <file_sep>/form2fit/code/ml/models/fcn.py from collections import OrderedDict import torch from torch import nn from torch.nn import functional as F from form2fit.code.ml.models import resnet from form2fit.code.ml.models.base import BaseModel class FCNet(BaseModel): """A fully-convolutional network with an encoder-decoder architecture. """ def __init__(self, in_channels, out_channels): super().__init__() self._in_channels = in_channels self._out_channels = out_channels self._encoder = nn.Sequential( OrderedDict( [ ( "enc-conv0", nn.Conv2d( in_channels, 64, kernel_size=3, stride=1, padding=1, bias=False, ), ), ("enc-norm0", nn.BatchNorm2d(64)), ("enc-relu0", nn.ReLU(inplace=True)), ("enc-pool1", nn.MaxPool2d(kernel_size=3, stride=2, padding=1)), ( "enc-resn2", resnet.BasicBlock( 64, 128, downsample=nn.Sequential( nn.Conv2d(64, 128, kernel_size=1, bias=False), nn.BatchNorm2d(128), ), dilation=1, ), ), ("enc-pool3", nn.MaxPool2d(kernel_size=3, stride=2, padding=1)), ( "enc-resn4", resnet.BasicBlock( 128, 256, downsample=nn.Sequential( nn.Conv2d(128, 256, kernel_size=1, bias=False), nn.BatchNorm2d(256), ), dilation=1, ), ), ( "enc-resn5", resnet.BasicBlock( 256, 512, downsample=nn.Sequential( nn.Conv2d(256, 512, kernel_size=1, bias=False), nn.BatchNorm2d(512), ), dilation=1, ), ), ] ) ) self._decoder = nn.Sequential( OrderedDict( [ ( "dec-resn0", resnet.BasicBlock( 512, 256, downsample=nn.Sequential( nn.Conv2d(512, 256, kernel_size=1, bias=False), nn.BatchNorm2d(256), ), dilation=1, ), ), ( "dec-resn1", resnet.BasicBlock( 256, 128, downsample=nn.Sequential( nn.Conv2d(256, 128, kernel_size=1, bias=False), nn.BatchNorm2d(128), ), dilation=1, ), ), ( "dec-upsm2", Interpolate( scale_factor=2, mode="bilinear", align_corners=True ), ), ( "dec-resn3", resnet.BasicBlock( 128, 64, downsample=nn.Sequential( nn.Conv2d(128, 64, kernel_size=1, bias=False), nn.BatchNorm2d(64), ), dilation=1, ), ), ( "dec-upsm4", Interpolate( scale_factor=2, mode="bilinear", align_corners=True ), ), ( "dec-conv5", nn.Conv2d(64, out_channels, kernel_size=1, stride=1, bias=True), ), ] ) ) self._init_weights() def _init_weights(self): for m in self.modules(): if isinstance(m, nn.Conv2d): nn.init.kaiming_normal_(m.weight, mode='fan_out', nonlinearity='relu') elif isinstance(m, (nn.BatchNorm2d, nn.GroupNorm)): nn.init.constant_(m.weight, 1) nn.init.constant_(m.bias, 0) def forward(self, x): out_enc = self._encoder(x) out_dec = self._decoder(out_enc) return out_dec class Interpolate(nn.Module): def __init__( self, size=None, scale_factor=None, mode="nearest", align_corners=None, ): super().__init__() self.size = size self.scale_factor = scale_factor self.mode = mode self.align_corners = align_corners def forward(self, input): return F.interpolate( input, self.size, self.scale_factor, self.mode, self.align_corners )<file_sep>/form2fit/code/utils/misc.py import cv2 import numpy as np from PIL import Image from skimage.measure import label from walle.core import RotationMatrix def adjust_gamma(image, gamma=1.0): """https://stackoverflow.com/questions/33322488/how-to-change-image-illumination-in-opencv-python """ invGamma = 1.0 / gamma table = np.array([((i / 255.0) ** invGamma) * 255 for i in np.arange(0, 256)]).astype("uint8") return cv2.LUT(image, table) def anglepie(num_rotations, use_rad): """Computes the rotation increments in a full rotation. Args: num_rotations: (int) The number of rotation increments. use_rad: (bool) Whether to return the angles in radians or not (degrees). Returns: A list containing the angle increments. """ angles = [i * (360.0 / num_rotations) for i in range(num_rotations)] if use_rad: angles = np.deg2rad(angles).tolist() return angles def rotz2angle(rotz): """Extracts z-rotation angle from rotation matrix. Args: rotz: (ndarray) The (3, 3) rotation about z. """ return np.arctan2(rotz[1, 0], rotz[0, 0]) def clip_uv(uv, rows, cols): """Ensures pixel coordinates are within image bounds. """ uv[:, 0] = np.clip(uv[:, 0], 0, rows - 1) uv[:, 1] = np.clip(uv[:, 1], 0, cols - 1) return uv def scale_uv(uv, rows, cols): us = uv[:, 0] vs = uv[:, 1] us_s = ((2 * us) / rows) - 1 vs_s = ((2 * vs) / cols) - 1 return np.vstack([us_s, vs_s]).T def descale_uv(uv, rows, cols): us = uv[:, 0] vs = uv[:, 1] us_s = 0.5 * ((us + 1.0) * rows) vs_s = 0.5 * ((vs + 1.0) * cols) return np.vstack([us_s, vs_s]).T def rotate_uv(uv, angle, rows, cols, cxcy=None): """Finds the value of a pixel in an image after a rotation. Args: uv: (ndarray) The [u, v] image coordinates. angle: (float) The rotation angle in degrees. """ txty = [cxcy[0], cxcy[1]] if cxcy is not None else [(rows // 2), (cols // 2)] txty = np.asarray(txty) uv = np.array(uv) aff_1 = np.eye(3) aff_3 = np.eye(3) aff_1[:2, 2] = -txty aff_2 = RotationMatrix.rotz(np.radians(angle)) aff_3[:2, 2] = txty affine = aff_3 @ aff_2 @ aff_1 affine = affine[:2, :] uv_rot = (affine @ np.hstack((uv, np.ones((len(uv), 1)))).T).T uv_rot = np.round(uv_rot).astype("int") uv_rot = clip_uv(uv_rot, rows, cols) return uv_rot def xyz2uv(xyz, intrinsics): """Converts 3D points into 2D pixels. """ cx, cy = intrinsics[0, 2], intrinsics[1, 2] fx, fy = intrinsics[0, 0], intrinsics[1, 1] x = xyz[:, 0] y = xyz[:, 1] z = xyz[:, 2] v = np.round((x * fx / z) + cx).astype("int") u = np.round((y * fy / z) + cy).astype("int") return np.vstack([u, v]).T def make2d(idx, num_cols=224): """Make a linear image index 2D. """ v = idx % num_cols u = idx // num_cols return u, v def make1d(u, v, num_cols=224): """Make a 2D image index linear. """ return (u * num_cols + v).astype("int") def rotate_img(img, angle, center=None, txty=None): """Rotates an image represented by an ndarray. """ img = Image.fromarray(img) img_r = img.rotate(angle, center=center, translate=txty) return np.array(img_r) def process_mask(mask, erode=True, kernel_size=3): """Cleans up a binary mask. """ mask = mask.astype("float32") kernel = np.ones((kernel_size, kernel_size), "uint8") if erode: mask = cv2.erode(mask, np.ones((3, 3), "uint8"), iterations=2) mask = cv2.dilate(mask, kernel, iterations=2).astype("float32") return mask def largest_cc(mask): labels = label(mask) largest = labels == np.argmax(np.bincount(labels.flat)[1:]) + 1 return largest def mask2bbox(mask): rows = np.any(mask, axis=1) cols = np.any(mask, axis=0) rmin, rmax = np.where(rows)[0][[0, -1]] cmin, cmax = np.where(cols)[0][[0, -1]] return rmin, rmax, cmin, cmax class AverageMeter(object): """Computes and stores the average and current value. """ def __init__(self): self.reset() def reset(self): self.val = 0 self.avg = 0 self.sum = 0 self.count = 0 self.arr = [] def update(self, val, n=1): self.val = val self.sum += val * n self.count += n self.avg = self.sum / self.count self.arr.append(val) <file_sep>/form2fit/code/ml/dataloader/__init__.py from form2fit.code.ml.dataloader.suction import * from form2fit.code.ml.dataloader.placement import * from form2fit.code.ml.dataloader.correspondence import *<file_sep>/form2fit/code/ml/dataloader/correspondence.py """The correspondence network dataloader. """ import glob import multiprocessing import os import pickle import cv2 import matplotlib.pyplot as plt import numpy as np import torch from functools import reduce from pathlib import Path from PIL import Image from torch.utils.data import DataLoader, Dataset from torchvision import transforms from form2fit.code.utils import misc, viz from form2fit.code.utils import sampling from form2fit import config from walle.core import RotationMatrix, Orientation class CorrespondenceDataset(Dataset): """The correspondence network dataset. """ def __init__( self, root, sample_ratio, num_rotations, markovian, augment, background_subtract, num_channels, ): """Initializes the dataset. Args: root: (str) Root directory path. sample_ratio: (float) The ratio of negative to positive labels. num_rotations: (int) The number of discrete rotation levels to consider. markovian: (bool) If `True`, only consider correspondences from the current timestep. Else, use correspondences from all previous and current timestep. augment: (bool) Whether to apply data augmentation. background_subtract: (bool) Whether to apply background subtraction. num_channels: (int) 4 clones the grayscale image to produce an RGB image. """ self._root = root self._num_rotations = num_rotations self._markovian = markovian self._sample_ratio = sample_ratio self._augment = augment self._background_subtract = background_subtract self._num_channels = num_channels # figure out how many data samples we have self._get_filenames() # generate rotation increments self._rot_step_size = 360 / num_rotations self._rotations = np.array([self._rot_step_size * i for i in range(num_rotations)]) # load per-channel mean and std stats = pickle.load(open(os.path.join(Path(self._root).parent, "mean_std.p"), "rb")) self.stats = stats if num_channels == 2: self._c_norm = transforms.Normalize(mean=stats[0][0], std=stats[0][1]) else: self._c_norm = transforms.Normalize(mean=stats[0][0]*3, std=stats[0][1]*3) self._d_norm = transforms.Normalize(mean=stats[1][0], std=stats[1][1]) self._transform = transforms.ToTensor() def __len__(self): return len(self._filenames) def _get_filenames(self): """Returns a list of filenames to process. """ self._filenames = glob.glob(os.path.join(self._root, "*/")) self._filenames.sort(key=lambda x: int(x.split("/")[-2])) def _load_state(self, name): # load poses pose_i = np.loadtxt(os.path.join(name, "init_pose.txt")) pose_f = np.loadtxt(os.path.join(name, "final_pose.txt")) # load visual c_height_i = np.asarray(Image.open(os.path.join(name, "init_color_height.png"))) d_height_i = np.asarray(Image.open(os.path.join(name, "init_depth_height.png"))) c_height_f = np.asarray(Image.open(os.path.join(name, "final_color_height.png"))) d_height_f = np.asarray(Image.open(os.path.join(name, "final_depth_height.png"))) # convert depth to meters d_height_i = (d_height_i * 1e-3).astype("float32") d_height_f = (d_height_f * 1e-3).astype("float32") # load masks if self._markovian: object_mask = np.load(os.path.join(name, "curr_object_mask.npy"), allow_pickle=True) hole_mask = np.load(os.path.join(name, "curr_hole_mask.npy"), allow_pickle=True) kit_minus_hole_mask = np.load( os.path.join(name, "curr_kit_minus_hole_mask.npy"), allow_pickle=True ) kit_plus_hole_mask = np.load( os.path.join(name, "curr_kit_plus_hole_mask.npy"), allow_pickle=True ) else: object_mask = np.load(os.path.join(name, "object_mask.npy"), allow_pickle=True) hole_mask = np.load(os.path.join(name, "hole_mask.npy"), allow_pickle=True) kit_minus_hole_mask = np.load(os.path.join(name, "kit_minus_hole_mask.npy"), allow_pickle=True) kit_plus_hole_mask = np.load(os.path.join(name, "kit_plus_hole_mask.npy"), allow_pickle=True) # load correspondences corrs = np.load(os.path.join(name, "corrs.npy"), allow_pickle=True) # fix weird npy behavior if corrs.ndim > 2: corrs = [corrs[0]] else: corrs = corrs.tolist() # compute all previous rotation quantizations indices transforms = np.load(os.path.join(name, "transforms.npy"), allow_pickle=True) rotations = [np.rad2deg(misc.rotz2angle(t)) for t in transforms] rot_quant_indices = [self._quantize_rotation(r) for r in rotations] # sort by increasing rotation index if rot_quant_indices: temp_argsort = np.argsort(rot_quant_indices) rot_quant_indices.sort() curr_corrs = corrs[-1:] prev_corrs = corrs[:-1] if prev_corrs: prev_corrs = [prev_corrs[i] for i in temp_argsort] corrs = prev_corrs + curr_corrs return ( pose_i, pose_f, c_height_i, d_height_i, c_height_f, d_height_f, object_mask, hole_mask, kit_minus_hole_mask, kit_plus_hole_mask, corrs, rot_quant_indices, ) def _split_heightmap(self, height): """Splits a heightmap into a source and target. """ half = height.shape[1] // 2 self._half = half height_s = height[:, half:].copy() height_t = height[:, :half].copy() return height_s, height_t def _compute_relative_rotation(self, pose_i, pose_f): """Computes the relative z-axis rotation between two poses. Returns: (float) The angle in degrees. """ transform = pose_f @ np.linalg.inv(pose_i) rotation = np.rad2deg(misc.rotz2angle(transform)) return rotation def _quantize_rotation(self, true_rot): """Bins the true rotation into one of `num_rotations`. Returns: (int) An index from 0 to `num_rotations` - 1. """ angle = true_rot - (360 * np.floor(true_rot * (1 / 360))) # angle = (true_rot % 360 + 360) % 360 # since 0 = 360 degrees, we need to remap # any indices in the last quantization # bracket to 0 degrees. if angle > (360 - (0.5 * self._rot_step_size)) and angle <= 360: return 0 return np.argmin(np.abs(self._rotations - angle)) def _process_correspondences(self, corrs, rot_idx, depth=None, append=True): """Processes correspondences for a given rotation. """ # split correspondences into source and target source_corrs = corrs[:, 0:2] target_corrs = corrs[:, 2:4] # rotate source indices source_idxs = misc.rotate_uv(source_corrs, -self._rot_step_size * rot_idx, self._H, self._W, (self._uc, self._vc)) target_idxs = np.round(target_corrs) # remove any repetitions _, unique_idxs = np.unique(source_idxs, return_index=True, axis=0) source_idxs_unique = source_idxs[unique_idxs] target_idxs_unique = target_idxs[unique_idxs] _, unique_idxs = np.unique(target_idxs_unique, return_index=True, axis=0) source_idxs_unique = source_idxs_unique[unique_idxs] target_idxs_unique = target_idxs_unique[unique_idxs] # remove indices that exceed image bounds valid_idxs = np.logical_and( target_idxs_unique[:, 0] < self._H, np.logical_and( target_idxs_unique[:, 1] < self._W, np.logical_and( target_idxs_unique[:, 0] >= 0, target_idxs_unique[:, 1] >= 0 ), ), ) target_idxs = target_idxs_unique[valid_idxs] source_idxs = source_idxs_unique[valid_idxs] valid_idxs = np.logical_and( source_idxs[:, 0] < self._H, np.logical_and( source_idxs[:, 1] < self._W, np.logical_and(source_idxs[:, 0] >= 0, source_idxs[:, 1] >= 0), ), ) target_idxs = target_idxs[valid_idxs].astype("int") source_idxs = source_idxs[valid_idxs].astype("int") # if depth is not None: # depth_vals = depth[target_idxs[:, 0], target_idxs[:, 1]] # valid_ds = depth_vals >= depth_vals.mean() # mask = np.zeros_like(depth) # mask[target_idxs[valid_ds][:, 0], target_idxs[valid_ds][:, 1]] = 1 # mask = misc.largest_cc(mask) # valid_mask = np.vstack(np.where(mask == 1)).T # tset = set([tuple(x) for x in valid_mask]) # for i in range(len(valid_ds)): # is_valid = valid_ds[i] # if is_valid: # tidx = target_idxs[i] # if tuple(tidx) not in tset: # valid_ds[i] = False # target_idxs = target_idxs[valid_ds] # source_idxs = source_idxs[valid_ds] if append: self._features_source.append(source_idxs) self._features_target.append(target_idxs) self._rot_idxs.append(np.repeat([rot_idx], len(source_idxs))) self._is_match.append(np.ones(len(source_idxs))) else: return np.hstack([source_idxs, target_idxs]) def _get_valid_idxs(self, corr, rows, cols): positive_cond = np.logical_and(corr[:, 0] >= 0, corr[:, 1] >= 0) within_cond = np.logical_and(corr[:, 0] < rows, corr[:, 1] < cols) valid_idxs = reduce(np.logical_and, [positive_cond, within_cond]) return valid_idxs def _sample_translation(self, corrz, angle): aff_1 = np.eye(3) aff_1[:2, 2] = [-self._uc, -self._vc] aff_2 = RotationMatrix.rotz(-angle) aff_3 = np.eye(3, 3) aff_3[:2, 2] = [self._uc, self._vc] affine = aff_3 @ aff_2 @ aff_1 affine = affine[:2, :] corrs = [] for corr in corrz: ones = np.ones((len(corr), 1)) corrs.append((affine @ np.hstack((corr, ones)).T).T) max_vv = corrs[0][:, 1].max() max_vu = corrs[0][corrs[0][:, 1].argmax()][0] min_vv = corrs[0][:, 1].min() min_vu = corrs[0][corrs[0][:, 1].argmin()][0] max_uu = corrs[0][:, 0].max() max_uv = corrs[0][corrs[0][:, 0].argmax()][1] min_uu = corrs[0][:, 0].min() min_uv = corrs[0][corrs[0][:, 0].argmin()][1] for t in corrs[1:]: if t[:, 1].max() > max_vv: max_vv = t[:, 1].max() max_vu = t[t[:, 1].argmax()][0] if t[:, 1].min() < min_vv: min_vv = t[:, 1].min() min_vu = t[t[:, 1].argmin()][0] if t[:, 0].max() > max_uu: max_uu = t[:, 0].max() max_uv = t[t[:, 0].argmax()][1] if t[:, 0].min() < min_uu: min_uu = t[:, 0].min() min_uv = t[t[:, 0].argmin()][1] tu = np.random.uniform(-min_vv + 10, self._W - max_vv - 10) tv = np.random.uniform(-min_uu + 10, self._H - max_uu - 10) return tu, tv def __getitem__(self, idx): name = self._filenames[idx] # load states pose_i, pose_f, c_height_i, d_height_i, c_height_f, \ d_height_f, object_mask, hole_mask, kit_minus_hole_mask, \ kit_plus_hole_mask, all_corrs, rot_quant_indices = self._load_state(self._filenames[idx]) # split heightmap into source and target c_height_s, c_height_t = self._split_heightmap(c_height_f) d_height_s, d_height_t = self._split_heightmap(d_height_f) self._H, self._W = c_height_t.shape[:2] hole_mask[:, 1] = hole_mask[:, 1] - self._half kit_minus_hole_mask[:, 1] = kit_minus_hole_mask[:, 1] - self._half kit_plus_hole_mask[:, 1] = kit_plus_hole_mask[:, 1] - self._half for corr in all_corrs: corr[:, 1] = corr[:, 1] - self._half if self._background_subtract is not None: # idxs = np.vstack(np.where(d_height_s > self._background_subtract[0])).T # mask = np.zeros_like(d_height_s) # mask[idxs[:, 0], idxs[:, 1]] = 1 # mask = misc.largest_cc(np.logical_not(mask)) # idxs = np.vstack(np.where(mask == 1)).T mask = np.zeros_like(d_height_s) mask[kit_plus_hole_mask[:, 0], kit_plus_hole_mask[:, 1]] = 1 idxs = np.vstack(np.where(mask == 1)).T mask[int(idxs[:, 0].min()):int(idxs[:, 0].max()), int(idxs[:, 1].min()):int(idxs[:, 1].max())] = 1 mask = np.logical_not(mask) idxs = np.vstack(np.where(mask == 1)).T c_height_s[idxs[:, 0], idxs[:, 1]] = 0 d_height_s[idxs[:, 0], idxs[:, 1]] = 0 idxs = np.vstack(np.where(d_height_t > self._background_subtract[1])).T mask = np.zeros_like(d_height_s) mask[idxs[:, 0], idxs[:, 1]] = 1 mask = misc.largest_cc(np.logical_not(mask)) idxs = np.vstack(np.where(mask == 1)).T c_height_t[idxs[:, 0], idxs[:, 1]] = 0 d_height_t[idxs[:, 0], idxs[:, 1]] = 0 # partition correspondences into current and previous curr_corrs = all_corrs[-1] prev_corrs = all_corrs[:-1] # compute rotation about z-axis using inital and final pose gd_truth_rot = self._compute_relative_rotation(pose_i, pose_f) # center of rotation is the center of the kit self._uc = int((kit_plus_hole_mask[:, 0].max() + kit_plus_hole_mask[:, 0].min()) // 2) self._vc = int((kit_plus_hole_mask[:, 1].max() + kit_plus_hole_mask[:, 1].min()) // 2) if self._augment: shape = (self._W, self._H) source_corrs = curr_corrs[:, 0:2].astype("float64") target_corrs = curr_corrs[:, 2:4].astype("float64") # determine bounds on translation for source and target all_corrz = [] for i, corr in enumerate(all_corrs): all_corrz.append(corr) sources = [kit_plus_hole_mask] targets = [p[:, 2:4] for p in all_corrz] angle_s = np.radians(np.random.uniform(0, 360)) tu_s, tv_s = self._sample_translation(sources, angle_s) aff_1 = np.eye(3) aff_1[:2, 2] = [-self._vc, -self._uc] aff_2 = RotationMatrix.rotz(angle_s) aff_2[:2, 2] = [tu_s, tv_s] aff_3 = np.eye(3, 3) aff_3[:2, 2] = [self._vc, self._uc] affine_s = aff_3 @ aff_2 @ aff_1 affine_s = affine_s[:2, :] c_height_s = cv2.warpAffine(c_height_s, affine_s, shape, flags=cv2.INTER_NEAREST) d_height_s = cv2.warpAffine(d_height_s, affine_s, shape, flags=cv2.INTER_NEAREST) aff_1[:2, 2] = [-self._uc, -self._vc] aff_2 = RotationMatrix.rotz(-angle_s) aff_2[:2, 2] = [tv_s, tu_s] aff_3[:2, 2] = [self._uc, self._vc] affine_s = aff_3 @ aff_2 @ aff_1 affine_s = affine_s[:2, :] source_corrs = (affine_s @ np.hstack((source_corrs, np.ones((len(source_corrs), 1)))).T).T # target affine transformation angle_t = 0 tu_t, tv_t = 0, 0 # self._sample_translation(targets, angle_t) aff_1 = np.eye(3) aff_1[:2, 2] = [-self._vc, -self._uc] aff_2 = RotationMatrix.rotz(angle_t) aff_2[:2, 2] = [tu_t, tv_t] aff_3 = np.eye(3, 3) aff_3[:2, 2] = [self._vc, self._uc] affine_t = aff_3 @ aff_2 @ aff_1 affine_t = affine_t[:2, :] c_height_t = cv2.warpAffine(c_height_t, affine_t, shape, flags=cv2.INTER_NEAREST) d_height_t = cv2.warpAffine(d_height_t, affine_t, shape, flags=cv2.INTER_NEAREST) aff_1[:2, 2] = [-self._uc, -self._vc] aff_2 = RotationMatrix.rotz(-angle_t) aff_2[:2, 2] = [tv_t, tu_t] aff_3[:2, 2] = [self._uc, self._vc] affine_t = aff_3 @ aff_2 @ aff_1 affine_t = affine_t[:2, :] target_corrs = (affine_t @ np.hstack((target_corrs, np.ones((len(target_corrs), 1)))).T).T # remove invalid indices valid_target_idxs = self._get_valid_idxs(target_corrs, self._H, self._W) target_corrs = target_corrs[valid_target_idxs].astype("int64") source_corrs = source_corrs[valid_target_idxs].astype("int64") curr_corrs = np.hstack((source_corrs, target_corrs)) # apply affine transformation to masks in source masks = [hole_mask, kit_plus_hole_mask, kit_minus_hole_mask] for i in range(len(masks)): ones = np.ones((len(masks[i]), 1)) masks[i] = (affine_s @ np.hstack((masks[i], ones)).T).T hole_mask, kit_plus_hole_mask, kit_minus_hole_mask = masks # apply affine transformation to masks in target ones = np.ones((len(object_mask), 1)) object_mask = (affine_t @ np.hstack((object_mask, ones)).T).T object_mask[:, 0] = np.clip(object_mask[:, 0], 0, self._H - 1) object_mask[:, 1] = np.clip(object_mask[:, 1], 0, self._W - 1) # reupdate kit mask center self._uc = int((kit_plus_hole_mask[:, 0].max() + kit_plus_hole_mask[:, 0].min()) // 2) self._vc = int((kit_plus_hole_mask[:, 1].max() + kit_plus_hole_mask[:, 1].min()) // 2) if self._augment: gd_truth_rot = gd_truth_rot + np.degrees(angle_t) - np.degrees(angle_s) # quantize rotation curr_rot_idx = self._quantize_rotation(gd_truth_rot) curr_rot = self._rotations[curr_rot_idx] self._features_source = [] self._features_target = [] self._rot_idxs = [] self._is_match = [] # sample matches from all previous timesteps if not markovian if not self._markovian: for rot_idx, corrs in zip(rot_quant_indices, prev_corrs): self._process_correspondences(corrs, rot_idx) # sample matches from the current timestep self._process_correspondences(curr_corrs, curr_rot_idx, depth=d_height_t) # determine the number of non-matches to sample per rotation num_matches = 0 for m in self._is_match: num_matches += len(m) num_non_matches = int(self._sample_ratio * num_matches / self._num_rotations) # convert masks to linear indices for sampling all_idxs_1d = np.arange(0, self._H * self._W) object_target_1d = sampling.make1d(object_mask, self._W) background_target_1d = np.array(list((set(all_idxs_1d) - set(object_target_1d)))) hole_source_1d = sampling.make1d(hole_mask, self._W) kit_minus_hole_source_1d = sampling.make1d(kit_minus_hole_mask, self._W) kit_plus_hole_source_1d = sampling.make1d(kit_plus_hole_mask, self._W) background_source_1d = np.array(list(set(all_idxs_1d) - set(kit_plus_hole_source_1d))) background_source_1d = sampling.remove_outliers(background_source_1d, kit_plus_hole_mask, self._W) # sample non-matches temp_idx = 0 div_factor = 2 for rot_idx in range(self._num_rotations): non_matches = [] # # source: anywhere # # target: anywhere but the object # non_matches.append(sampling.sample_non_matches( # 1 * num_non_matches // div_factor, # (self._H, self._W), # -self._rotations[rot_idx], # mask_target=background_target_1d, # rotate=False) # ) # # source: anywhere but the kit # # target: on the object # nm_idxs = sampling.sample_non_matches( # 1 * num_non_matches // div_factor, # (self._H, self._W), # -self._rotations[rot_idx], # background_source_1d, # object_target_1d, # rotate=False, # ) # non_matches.append(nm_idxs) # source: on the kit but not in the hole # target: on the object nm_idxs = sampling.sample_non_matches( 1 * num_non_matches // div_factor, (self._H, self._W), -self._rotations[rot_idx], kit_minus_hole_source_1d, object_target_1d, cxcy=(self._uc, self._vc), ) non_matches.append(nm_idxs) # # here, I want to explicity samples matches # # for the incorrect rotations to teach # # the network that in fact, this is # # the incorrect rotation. # # This is especially useful for the # # 180 degree rotated version of the # # correct rotation. # if rot_idx != curr_rot_idx: # nm_idxs = self._process_correspondences(curr_corrs, rot_idx, False) # subset_mask = np.random.choice(np.arange(len(nm_idxs)), replace=False, size=(1 * num_non_matches // div_factor)) # nm_idxs = nm_idxs[subset_mask] # non_matches.append(nm_idxs) # source: in the hole # target: on the object if self._markovian: if rot_idx == curr_rot_idx: nm_idxs = sampling.non_matches_from_matches( 1 * num_non_matches // div_factor, (self._H, self._W), -self._rotations[rot_idx], hole_source_1d, self._features_source[0], self._features_target[0], cxcy=(self._uc, self._vc), ) non_matches.append(nm_idxs) else: nm_idxs = sampling.sample_non_matches( 1 * num_non_matches // div_factor, (self._H, self._W), -self._rotations[rot_idx], hole_source_1d, object_target_1d, cxcy=(self._uc, self._vc), ) non_matches.append(nm_idxs) else: if rot_idx in rot_quant_indices: non_matches.append( sampling.non_matches_from_matches( num_non_matches // div_factor, (self._H, self._W), -self._rotations[rot_idx], hole_source_1d, self._features_source[temp_idx], self._features_target[temp_idx], ) ) temp_idx += 1 else: non_matches.append( sampling.sample_non_matches( num_non_matches // div_factor, (self._H, self._W), -self._rotations[rot_idx], hole_source_1d, object_target_1d, ) ) non_matches = np.vstack(non_matches) self._features_source.append(non_matches[:, :2]) self._features_target.append(non_matches[:, 2:]) self._rot_idxs.append(np.repeat([rot_idx], len(non_matches))) self._is_match.append(np.repeat([0], len(non_matches))) # convert lists to numpy arrays self._features_source = np.concatenate(self._features_source) self._features_target = np.concatenate(self._features_target) self._rot_idxs = np.concatenate(self._rot_idxs)[..., np.newaxis] self._is_match = np.concatenate(self._is_match)[..., np.newaxis] # concatenate into 1 big array label = np.hstack( ( self._features_source, self._features_target, self._rot_idxs, self._is_match, ) ) if self._num_channels == 2: c_height_s = c_height_s[..., np.newaxis] c_height_t = c_height_t[..., np.newaxis] else: # clone the gray channel 3 times c_height_s = np.repeat(c_height_s[..., np.newaxis], 3, axis=-1) c_height_t = np.repeat(c_height_t[..., np.newaxis], 3, axis=-1) # ndarray -> tensor label_tensor = torch.LongTensor(label) # heightmaps -> tensor c_height_s = self._c_norm(self._transform(c_height_s)) c_height_t = self._c_norm(self._transform(c_height_t)) d_height_s = self._d_norm(self._transform(d_height_s[..., np.newaxis])) d_height_t = self._d_norm(self._transform(d_height_t[..., np.newaxis])) # concatenate height and depth into a 4-channel tensor source_img_tensor = torch.cat([c_height_s, d_height_s], dim=0) target_img_tensor = torch.cat([c_height_t, d_height_t], dim=0) # concatenate source and target into a 8-channel tensor img_tensor = torch.cat([source_img_tensor, target_img_tensor], dim=0) return img_tensor, label_tensor, (self._uc, self._vc) def get_corr_loader( foldername, dtype="train", batch_size=1, shuffle=True, sample_ratio=1.0, num_rotations=20, markovian=True, augment=False, background_subtract=None, num_channels=2, num_workers=1, ): """Returns a dataloader over the correspondence dataset. Args: foldername: (str) The name of the folder containing the data. dtype: (str) Whether to use the train, validation or test partition. shuffle: (bool) Whether to shuffle the dataset at the end of every epoch. sample_ratio: (float) The ratio of negative to positive labels. num_rotations: (int) The number of discrete rotation levels to consider. markovian: (bool) If `True`, only consider correspondences from the current timestep. Else, use correspondences from all previous and current timestep. background_subtract: (bool) Whether to apply background subtraction. num_channels: (int) 4 clones the grayscale image to produce an RGB image. num_workers: (int) How many processes to use. Each workers is responsible for loading a batch. """ def _collate_fn(batch): """A custom collate function. This is to support variable length correspondence labels. """ imgs = [b[0] for b in batch] labels = [b[1] for b in batch] centers = [b[2] for b in batch] # mask = [b[2] for b in batch] # kit_mask = [b[3] for b in batch] imgs = torch.stack(imgs, dim=0) max_num_label = labels[0].shape[0] for l in labels[1:]: if l.shape[0] > max_num_label: max_num_label = l.shape[0] new_labels = [] for l in labels: if l.shape[0] < max_num_label: l_pad = torch.cat([l, torch.LongTensor([999]).repeat(max_num_label - l.shape[0], 6)], dim=0) new_labels.append(l_pad) else: new_labels.append(l) labels = torch.stack(new_labels, dim=0) return [imgs, labels, centers] num_workers = min(num_workers, multiprocessing.cpu_count()) root = os.path.join(config.benchmark_dir, "train", foldername, dtype) dataset = CorrespondenceDataset( root, sample_ratio, num_rotations, markovian, augment, background_subtract, num_channels, ) loader = DataLoader( dataset, batch_size=batch_size, shuffle=shuffle, collate_fn=_collate_fn, pin_memory=True, num_workers=num_workers, ) return loader <file_sep>/form2fit/config.py """Config file. """ import os import numpy as np # directories root_dir = os.path.dirname(os.path.realpath(__file__)) benchmark_dir = os.path.join(root_dir, "benchmark/data/") root_dir = os.path.join(root_dir, "code") ml_data_dir = os.path.join(root_dir, "ml/dataset/") weights_dir = os.path.join(root_dir, "ml/models/weights") results_dir = os.path.join(root_dir, "results") train_dir = os.path.join(root_dir, "train") logs_dir = os.path.join(root_dir, "logs") # heightmap params VIEW_BOUNDS = np.asarray([[-0.2, .728], [0.38, 1.1], [-1, 1]]) HEIGHTMAP_RES = 0.002 # baseline parameters MIN_NUM_MATCH = 4 # background subtraction BACKGROUND_SUBTRACT = { "black-floss": (0.04, 0.047), "tape-runner": (0.04, 0.047), "zoo-animals": None, "fruits": (0.04, 0.047), "deodorants": (0.04, 0.047), } # the watermelon fruit is 360-degree symmetrical # thus we don't want to penalize rotational errors FRUIT_IDXS = [0, 4, 8, 12, 16, 20] # plotting params MAX_LENGTH_THRESH = 0.1 MAX_DEG_THRESH = 200 MAX_PIX_THRESH = 30 MAX_TR_THRESH = 0.15<file_sep>/form2fit/code/ml/dataloader/placement.py """The placement network dataset and dataloader. """ import glob import logging import multiprocessing import os import pickle import cv2 import matplotlib.pyplot as plt import numpy as np import torch from pathlib import Path from PIL import Image from skimage.draw import circle from torch.utils.data import DataLoader, Dataset from torchvision import transforms from walle.core import RotationMatrix from form2fit import config from form2fit.code.utils import misc class PlacementDataset(Dataset): """The placement network dataset. """ def __init__(self, root, sample_ratio, stateless, augment, background_subtract, num_channels, radius): """Initializes the dataset. Args: root: (str) Root directory path. sample_ratio: (float) The ratio of negative to positive labels. stateless: (bool) Whether to use just the current placement point and ignore all the ones from the previous objects in the sequence. augment: (bool) Whether to apply data augmentation. background_subtract: (bool) Whether to apply background subtraction. num_channels: (int) 4 clones the grayscale image to produce an RGB image. """ self._root = root self._sample_ratio = sample_ratio self._augment = augment self._stateless = stateless self._background_subtract = background_subtract self._num_channels = num_channels self.radius = radius # figure out how many data samples we have self._get_filenames() stats = pickle.load(open(os.path.join(Path(self._root).parent, "mean_std.p"), "rb")) if self._num_channels == 4: self._c_norm = transforms.Normalize(mean=stats[0][0] * 3, std=stats[0][1] * 3) else: self._c_norm = transforms.Normalize(mean=stats[0][0], std=stats[0][1]) self._d_norm = transforms.Normalize(mean=stats[1][0], std=stats[1][1]) self._transform = transforms.ToTensor() def __len__(self): return len(self._filenames) def _get_filenames(self): self._filenames = glob.glob(os.path.join(self._root, "*/")) self._filenames.sort(key=lambda x: int(x.split("/")[-2])) def _load_state(self, name): """Loads the raw state variables. """ # load the list of suction points placement_points = np.loadtxt(os.path.join(name, "placement_points.txt"), ndmin=2) # we just want the current timestep place point placement_points = np.round(placement_points) if self._stateless: placement_points = placement_points[-1:] # load heightmaps c_height = np.asarray(Image.open(os.path.join(name, "final_color_height.png"))) d_height = np.asarray(Image.open(os.path.join(name, "final_depth_height.png"))) c_height_i = np.asarray(Image.open(os.path.join(name, "init_color_height.png"))) d_height_i = np.asarray(Image.open(os.path.join(name, "init_depth_height.png"))) # convert depth to meters d_height_i = (d_height_i * 1e-3).astype("float32") d_height = (d_height * 1e-3).astype("float32") # load kit mask kit_mask = np.load(os.path.join(name, "curr_kit_plus_hole_mask.npy")) return c_height, d_height, placement_points, kit_mask, c_height_i, d_height_i def _split_heightmap(self, height): """Splits a heightmap into a source and target. For placement, we just need the source heightmap. """ half = height.shape[1] // 2 self._half = half height_s = height[:, half:].copy() return height_s def _sample_negative(self, positives): """Randomly samples negative pixel indices. """ max_val = self._H * self._W num_pos = len(positives) num_neg = int(num_pos * self._sample_ratio) positives = np.round(positives).astype("int") positives = positives[:, :2] positives = np.ravel_multi_index((positives[:, 0], positives[:, 1]), (self._H, self._W)) if self._sample_ratio < 70: negative_indices = [] while len(negative_indices) < num_neg: negative = np.random.randint(0, max_val) if negative not in positives: negative_indices.append(negative) else: allowed = list(set(np.arange(0, max_val)) - set(positives.ravel())) np.random.shuffle(allowed) negative_indices = allowed[:num_neg] negative_indices = np.unravel_index(negative_indices, (self._H, self._W)) return negative_indices def _sample_free_negative(self, kit_mask): """Randomly samples negative pixel indices. """ max_val = self._H * self._W num_neg = int(100 * self._sample_ratio) negative_indices = [] while len(negative_indices) < num_neg: negative_indices.append(np.random.randint(0, max_val)) negative_indices = np.vstack(np.unravel_index(negative_indices, (self._H, self._W))).T idxs = np.random.choice(np.arange(len(kit_mask)), size=30, replace=False) inside = kit_mask[idxs] negative_indices = np.vstack([negative_indices, inside]) return negative_indices def _sample_translation(self, corrz, angle): aff_1 = np.eye(3) aff_1[:2, 2] = [-self._uc, -self._vc] aff_2 = RotationMatrix.rotz(-angle) aff_3 = np.eye(3, 3) aff_3[:2, 2] = [self._uc, self._vc] affine = aff_3 @ aff_2 @ aff_1 affine = affine[:2, :] corrs = [] for corr in corrz: ones = np.ones((len(corr), 1)) corrs.append((affine @ np.hstack((corr, ones)).T).T) max_vv = corrs[0][:, 1].max() max_vu = corrs[0][corrs[0][:, 1].argmax()][0] min_vv = corrs[0][:, 1].min() min_vu = corrs[0][corrs[0][:, 1].argmin()][0] max_uu = corrs[0][:, 0].max() max_uv = corrs[0][corrs[0][:, 0].argmax()][1] min_uu = corrs[0][:, 0].min() min_uv = corrs[0][corrs[0][:, 0].argmin()][1] for t in corrs[1:]: if t[:, 1].max() > max_vv: max_vv = t[:, 1].max() max_vu = t[t[:, 1].argmax()][0] if t[:, 1].min() < min_vv: min_vv = t[:, 1].min() min_vu = t[t[:, 1].argmin()][0] if t[:, 0].max() > max_uu: max_uu = t[:, 0].max() max_uv = t[t[:, 0].argmax()][1] if t[:, 0].min() < min_uu: min_uu = t[:, 0].min() min_uv = t[t[:, 0].argmin()][1] tu = np.random.uniform(-min_vv + 10, self._W - max_vv - 10) tv = np.random.uniform(-min_uu + 10, self._H - max_uu - 10) return tu, tv def __getitem__(self, idx): name = self._filenames[idx] # load state c_height, d_height, positives, kit_mask, c_height_i, d_height_i = self._load_state(name) # split heightmap into source and target c_height = self._split_heightmap(c_height) d_height = self._split_heightmap(d_height) c_height_i = self._split_heightmap(c_height_i) d_height_i = self._split_heightmap(d_height_i) self._H, self._W = c_height.shape[:2] pos_placement = [] for pos in positives: rr, cc = circle(pos[0], pos[1], self.radius) pos_placement.append(np.vstack([rr, cc]).T) pos_placement = np.concatenate(pos_placement) # offset placement point to adjust for splitting pos_placement[:, 1] = pos_placement[:, 1] - self._half kit_mask[:, 1] = kit_mask[:, 1] - self._half # center of rotation is the center of the kit self._uc = int((kit_mask[:, 0].max() + kit_mask[:, 0].min()) // 2) self._vc = int((kit_mask[:, 1].max() + kit_mask[:, 1].min()) // 2) if self._augment: shape = (self._W, self._H) angle = np.radians(np.random.uniform(0, 360)) tu, tv = self._sample_translation([kit_mask], angle) aff_1 = np.eye(3) aff_1[:2, 2] = [-self._vc, -self._uc] aff_2 = RotationMatrix.rotz(angle) aff_2[:2, 2] = [tu, tv] aff_3 = np.eye(3, 3) aff_3[:2, 2] = [self._vc, self._uc] affine = aff_3 @ aff_2 @ aff_1 affine = affine[:2, :] c_height = cv2.warpAffine(c_height, affine, shape, flags=cv2.INTER_NEAREST) d_height = cv2.warpAffine(d_height, affine, shape, flags=cv2.INTER_NEAREST) aff_1[:2, 2] = [-self._uc, -self._vc] aff_2 = RotationMatrix.rotz(-angle) aff_2[:2, 2] = [tv, tu] aff_3[:2, 2] = [self._uc, self._vc] affine = aff_3 @ aff_2 @ aff_1 affine = affine[:2, :] pos_placement = (affine @ np.hstack((pos_placement, np.ones((len(pos_placement), 1)))).T).T kit_mask = (affine @ np.hstack((kit_mask, np.ones((len(kit_mask), 1)))).T).T # update center of rotation self._uc = int((kit_mask[:, 0].max() + kit_mask[:, 0].min()) // 2) self._vc = int((kit_mask[:, 1].max() + kit_mask[:, 1].min()) // 2) if self._background_subtract is not None: idxs = np.vstack(np.where(d_height > self._background_subtract[0])).T mask = np.zeros_like(d_height) mask[idxs[:, 0], idxs[:, 1]] = 1 mask = misc.largest_cc(np.logical_not(mask)) idxs = np.vstack(np.where(mask == 1)).T c_height[idxs[:, 0], idxs[:, 1]] = 0 d_height[idxs[:, 0], idxs[:, 1]] = 0 idxs = np.vstack(np.where(d_height_i > self._background_subtract[0])).T mask = np.zeros_like(d_height) mask[idxs[:, 0], idxs[:, 1]] = 1 mask = misc.largest_cc(np.logical_not(mask)) idxs = np.vstack(np.where(mask == 1)).T c_height_i[idxs[:, 0], idxs[:, 1]] = 0 d_height_i[idxs[:, 0], idxs[:, 1]] = 0 if self._num_channels == 2: c_height = c_height[..., np.newaxis] c_height_i = c_height_i[..., np.newaxis] else: # clone the gray channel 3 times c_height = np.repeat(c_height[..., np.newaxis], 3, axis=-1) c_height_i = np.repeat(c_height_i[..., np.newaxis], 3, axis=-1) # convert heightmaps tensors c_height = self._c_norm(self._transform(c_height)) d_height = self._d_norm(self._transform(d_height[..., np.newaxis])) c_height_i = self._c_norm(self._transform(c_height_i)) d_height_i = self._d_norm(self._transform(d_height_i[..., np.newaxis])) # concatenate height and depth into a 4-channel tensor # img_tensor = torch.cat([c_height, d_height], dim=0) img_tensor_i = torch.cat([c_height_i, d_height_i], dim=0) img_tensor = torch.cat([c_height, d_height], dim=0) img_tensor = torch.stack([img_tensor_i, img_tensor], dim=0) # add columns of 1 (positive labels) pos_label = np.hstack((pos_placement, np.ones((len(pos_placement), 1)))) # generate negative labels neg_placement = np.vstack(self._sample_negative(pos_label)).T neg_label = np.hstack((neg_placement, np.zeros((len(neg_placement), 1)))) # stack positive and negative into a single array label = np.vstack((pos_label, neg_label)) neg_placement_i = self._sample_free_negative(kit_mask) neg_label_i = np.hstack((neg_placement_i, np.zeros((len(neg_placement_i), 1)))) label_tensor_i = torch.LongTensor(neg_label_i) label_tensor_f = torch.LongTensor(label) label_tensor = [label_tensor_i, label_tensor_f] # convert suction points to tensors # label_tensor = torch.LongTensor(label) return img_tensor, label_tensor def get_placement_loader( foldername, dtype="train", batch_size=1, sample_ratio=1.0, shuffle=True, stateless=True, augment=False, background_subtract=None, num_channels=2, radius=2, num_workers=4, use_cuda=True, ): """Returns a dataloader over the `Placement` dataset. Args: foldername: (str) The name of the folder containing the data. dtype: (str) Whether to use the train, validation or test partition. batch_size: (int) The number of data samples in a batch. sample_ratio: (float) The ratio of negative to positive labels. shuffle: (bool) Whether to shuffle the dataset at the end of every epoch. stateless: (bool) Whether to use just the current placement point and ignore all the ones from the previous objects in the sequence. augment: (bool) Whether to apply data augmentation. background_subtract: (bool) Whether to apply background subtraction. num_workers: (int) How many processes to use. Each workers is responsible for loading a batch. use_cuda: (bool) Whether to use the GPU. """ def _collate_fn(batch): """A custom collate function. This is to support variable length suction labels. """ # imgs = [b[0] for b in batch] # labels = [b[1] for b in batch] # imgs = torch.stack(imgs, dim=0) # return [imgs, labels] imgs = [b[0] for b in batch] labels = [b[1] for b in batch] imgs = torch.cat(imgs, dim=0) labels = [l for sublist in labels for l in sublist] return [imgs, labels] num_workers = min(num_workers, multiprocessing.cpu_count()) root = os.path.join(config.ml_data_dir, foldername, dtype) dataset = PlacementDataset( root, sample_ratio, stateless, augment, background_subtract, num_channels, radius, ) loader = DataLoader( dataset, batch_size=batch_size, shuffle=shuffle, collate_fn=_collate_fn, pin_memory=True, num_workers=num_workers, ) return loader<file_sep>/form2fit/code/ml/models/suction.py import torch from form2fit.code.ml.models.base import BaseModel from form2fit.code.ml.models.fcn import FCNet class SuctionNet(BaseModel): """The suction prediction network. Attributes: num_channels: (int) The number of channels in the input tensor. """ def __init__(self, num_channels): super().__init__() self.num_channels = num_channels self._fcn = FCNet(num_channels, 1) def forward(self, x): return self._fcn(x)<file_sep>/form2fit/code/ml/dataloader/suction.py """The suction dataset. """ import glob import logging import multiprocessing import os import pickle import cv2 import matplotlib.pyplot as plt import numpy as np import torch from pathlib import Path from PIL import Image from skimage.draw import circle from torch.utils.data import DataLoader, Dataset from torchvision import transforms from walle.core import RotationMatrix from form2fit import config from form2fit.code.utils import misc class SuctionDataset(Dataset): """The suction network dataset. """ def __init__(self, root, sample_ratio, augment, background_subtract, num_channels, radius): """Initializes the dataset. Args: root: (str) Root directory path. sample_ratio: (float) The ratio of negative to positive labels. normalize: (bool) Whether to normalize the images by subtracting the mean and dividing by the std deviation. augment: (bool) Whether to apply data augmentation. """ self._root = root self._sample_ratio = sample_ratio self._augment = augment self._background_subtract = background_subtract self._num_channels = num_channels self._radius = radius # figure out how many data samples we have self._get_filenames() stats = pickle.load(open(os.path.join(Path(self._root).parent, "mean_std.p"), "rb")) if self._num_channels == 4: self._c_norm = transforms.Normalize(mean=stats[0][0] * 3, std=stats[0][1] * 3) else: self._c_norm = transforms.Normalize(mean=stats[0][0], std=stats[0][1]) self._d_norm = transforms.Normalize(mean=stats[1][0], std=stats[1][1]) self._transform = transforms.ToTensor() def __len__(self): return len(self._filenames) def _get_filenames(self): self._filenames = glob.glob(os.path.join(self._root, "*/")) self._filenames.sort(key=lambda x: int(x.split("/")[-2])) def _load_state(self, name): """Loads the raw state variables. """ # load the list of suction points suction_points_init = np.loadtxt(os.path.join(name, "suction_points_init.txt"), ndmin=2) suction_points_final = np.loadtxt(os.path.join(name, "suction_points_final.txt"), ndmin=2) # round num_init = suction_points_init.shape[0] suction_points_init = np.round(suction_points_init)[num_init - 1 : num_init] suction_points_final = np.round(suction_points_final) # load heightmaps c_height_f = np.asarray(Image.open(os.path.join(name, "final_color_height.png"))) d_height_f = np.asarray(Image.open(os.path.join(name, "final_depth_height.png"))) c_height_i = np.asarray(Image.open(os.path.join(name, "init_color_height.png"))) d_height_i = np.asarray(Image.open(os.path.join(name, "init_depth_height.png"))) # convert depth to meters d_height_f = (d_height_f * 1e-3).astype("float32") d_height_i = (d_height_i * 1e-3).astype("float32") # load correspondences corrs = np.load(os.path.join(name, "corrs.npy")) # fix weird npy behavior if corrs.ndim > 2: corrs = [corrs[0]] else: corrs = corrs.tolist() # load kit mask kit_mask = np.load(os.path.join(name, "curr_kit_plus_hole_mask.npy")) return ( c_height_i, d_height_i, c_height_f, d_height_f, suction_points_init, suction_points_final, corrs, kit_mask, ) def _split_heightmap(self, height, source): """Splits a heightmap into a source and target. For suction, we just need the target heightmap. """ half = height.shape[1] // 2 self._half = half height_t = height[:, :half].copy() height_s = height[:, half:].copy() if source: return height_s return height_t def _sample_negative(self, positives): """Randomly samples negative pixel indices. """ max_val = self._H * self._W num_pos = len(positives) num_neg = int(num_pos * self._sample_ratio) if self._sample_ratio < 70: negative_indices = [] while len(negative_indices) < num_neg: negative = np.random.randint(0, max_val) if negative not in positives: negative_indices.append(negative) else: allowed = list(set(np.arange(0, max_val)) - set(list(positives))) np.random.shuffle(allowed) negative_indices = allowed[:num_neg] negative_indices = np.unravel_index(negative_indices, (self._H, self._W)) return negative_indices def _sample_translation(self, corrz, angle, center=True): aff_1 = np.eye(3) if center: aff_1[:2, 2] = [-self._uc, -self._vc] else: aff_1[:2, 2] = [-self._H//2, -self._W//2] aff_2 = RotationMatrix.rotz(-angle) aff_3 = np.eye(3, 3) if center: aff_3[:2, 2] = [self._uc, self._vc] else: aff_3[:2, 2] = [self._H//2, self._W//2] affine = aff_3 @ aff_2 @ aff_1 affine = affine[:2, :] corrs = [] for corr in corrz: ones = np.ones((len(corr), 1)) corrs.append((affine @ np.hstack((corr, ones)).T).T) max_vv = corrs[0][:, 1].max() max_vu = corrs[0][corrs[0][:, 1].argmax()][0] min_vv = corrs[0][:, 1].min() min_vu = corrs[0][corrs[0][:, 1].argmin()][0] max_uu = corrs[0][:, 0].max() max_uv = corrs[0][corrs[0][:, 0].argmax()][1] min_uu = corrs[0][:, 0].min() min_uv = corrs[0][corrs[0][:, 0].argmin()][1] for t in corrs[1:]: if t[:, 1].max() > max_vv: max_vv = t[:, 1].max() max_vu = t[t[:, 1].argmax()][0] if t[:, 1].min() < min_vv: min_vv = t[:, 1].min() min_vu = t[t[:, 1].argmin()][0] if t[:, 0].max() > max_uu: max_uu = t[:, 0].max() max_uv = t[t[:, 0].argmax()][1] if t[:, 0].min() < min_uu: min_uu = t[:, 0].min() min_uv = t[t[:, 0].argmin()][1] tu = np.random.uniform(-min_vv + 10, self._W - max_vv - 10) tv = np.random.uniform(-min_uu + 10, self._H - max_uu - 10) return tu, tv def __getitem__(self, idx): name = self._filenames[idx] # load state c_height_i, d_height_i, c_height_f, d_height_f, \ pos_suction_i, pos_suction_f, all_corrs, kit_mask = self._load_state(name) # split heightmap into source and target c_height_f = self._split_heightmap(c_height_f, False) d_height_f = self._split_heightmap(d_height_f, False) c_height_i = self._split_heightmap(c_height_i, True) d_height_i = self._split_heightmap(d_height_i, True) self._H, self._W = c_height_f.shape[:2] # offset indices to adjust for splitting pos_suction_i[:, 1] = pos_suction_i[:, 1] - self._half kit_mask[:, 1] = kit_mask[:, 1] - self._half pos_f = [] for pos in pos_suction_f: rr, cc = circle(pos[0], pos[1], self._radius) pos_f.append(np.vstack([rr, cc]).T) pos_suction_f = np.concatenate(pos_f) pos_i = [] for pos in pos_suction_i: rr, cc = circle(pos[0], pos[1], self._radius) pos_i.append(np.vstack([rr, cc]).T) pos_suction_i = np.concatenate(pos_i) for corr in all_corrs: corr[:, 1] = corr[:, 1] - self._half self._uc = int((kit_mask[:, 0].max() + kit_mask[:, 0].min()) // 2) self._vc = int((kit_mask[:, 1].max() + kit_mask[:, 1].min()) // 2) shape = (self._W, self._H) if self._augment: angle = np.radians(np.random.uniform(0, 360)) tu, tv = 0, 0 # self._sample_translation([kit_mask], angle) aff_1 = np.eye(3) aff_1[:2, 2] = [-self._vc, -self._uc] aff_2 = RotationMatrix.rotz(angle) aff_2[:2, 2] = [tu, tv] aff_3 = np.eye(3, 3) aff_3[:2, 2] = [self._vc, self._uc] affine = aff_3 @ aff_2 @ aff_1 affine = affine[:2, :] c_height_i = cv2.warpAffine(c_height_i, affine, shape, flags=cv2.INTER_NEAREST) d_height_i = cv2.warpAffine(d_height_i, affine, shape, flags=cv2.INTER_NEAREST) aff_1[:2, 2] = [-self._uc, -self._vc] aff_2 = RotationMatrix.rotz(-angle) aff_2[:2, 2] = [tv, tu] aff_3[:2, 2] = [self._uc, self._vc] affine = aff_3 @ aff_2 @ aff_1 affine = affine[:2, :] pos_suction_i = (affine @ np.hstack((pos_suction_i, np.ones((len(pos_suction_i), 1)))).T).T kit_mask = (affine @ np.hstack((kit_mask, np.ones((len(kit_mask), 1)))).T).T # augment obj heightmap angle = np.radians(np.random.uniform(0, 360)) tu, tv = self._sample_translation([p[:, 2:4].copy() for p in all_corrs], angle, False) aff_1 = np.eye(3) aff_1[:2, 2] = [-self._W//2, -self._H//2] aff_2 = RotationMatrix.rotz(angle) aff_2[:2, 2] = [tu, tv] aff_3 = np.eye(3, 3) aff_3[:2, 2] = [self._W//2, self._H//2] affine = aff_3 @ aff_2 @ aff_1 affine = affine[:2, :] c_height_f = cv2.warpAffine(c_height_f, affine, shape, flags=cv2.INTER_NEAREST) d_height_f = cv2.warpAffine(d_height_f, affine, shape, flags=cv2.INTER_NEAREST) aff_1[:2, 2] = [-self._H//2, -self._W//2] aff_2 = RotationMatrix.rotz(-angle) aff_2[:2, 2] = [tv, tu] aff_3[:2, 2] = [self._H//2, self._W//2] affine = aff_3 @ aff_2 @ aff_1 affine = affine[:2, :] pos_suction_f = (affine @ np.hstack((pos_suction_f, np.ones((len(pos_suction_f), 1)))).T).T if self._background_subtract is not None: idxs = np.vstack(np.where(d_height_i > self._background_subtract[0])).T mask = np.zeros_like(d_height_i) mask[idxs[:, 0], idxs[:, 1]] = 1 mask = misc.largest_cc(mask) idxs = np.vstack(np.where(mask == 1)).T mask = np.zeros_like(d_height_i) mask[idxs[:, 0].min():idxs[:, 0].max(), idxs[:, 1].min():idxs[:, 1].max()] = 1 # mask = np.zeros_like(d_height_i) # mask[idxs[:, 0], idxs[:, 1]] = 1 # mask = misc.largest_cc(np.logical_not(mask)) idxs = np.vstack(np.where(mask == 0)).T c_height_i[idxs[:, 0], idxs[:, 1]] = 0 d_height_i[idxs[:, 0], idxs[:, 1]] = 0 idxs = np.vstack(np.where(d_height_f > self._background_subtract[1])).T mask = np.zeros_like(d_height_f) mask[idxs[:, 0], idxs[:, 1]] = 1 mask = misc.largest_cc(np.logical_not(mask)) idxs = np.vstack(np.where(mask == 1)).T c_height_f[idxs[:, 0], idxs[:, 1]] = 0 d_height_f[idxs[:, 0], idxs[:, 1]] = 0 if self._num_channels == 2: c_height_i = c_height_i[..., np.newaxis] c_height_f = c_height_f[..., np.newaxis] else: # clone the gray channel 3 times c_height_i = np.repeat(c_height_i[..., np.newaxis], 3, axis=-1) c_height_f = np.repeat(c_height_f[..., np.newaxis], 3, axis=-1) # convert heightmaps tensors c_height_i = self._c_norm(self._transform(c_height_i)) c_height_f = self._c_norm(self._transform(c_height_f)) d_height_i = self._d_norm(self._transform(d_height_i[..., np.newaxis])) d_height_f = self._d_norm(self._transform(d_height_f[..., np.newaxis])) # concatenate height and depth into a 4-channel tensor img_tensor_i = torch.cat([c_height_i, d_height_i], dim=0) img_tensor_f = torch.cat([c_height_f, d_height_f], dim=0) img_tensor = torch.stack([img_tensor_i, img_tensor_f], dim=0) # add columns of 1 (positive labels) pos_label_i = np.hstack((pos_suction_i, np.ones((len(pos_suction_i), 1)))) pos_label_f = np.hstack((pos_suction_f, np.ones((len(pos_suction_f), 1)))) # generate negative labels neg_suction_i = np.vstack(self._sample_negative(pos_label_i)).T neg_label_i = np.hstack((neg_suction_i, np.zeros((len(neg_suction_i), 1)))) neg_suction_f = np.vstack(self._sample_negative(pos_label_f)).T neg_label_f = np.hstack((neg_suction_f, np.zeros((len(neg_suction_f), 1)))) # stack positive and negative into a single array label_i = np.vstack((pos_label_i, neg_label_i)) label_f = np.vstack((pos_label_f, neg_label_f)) # convert suction points to tensors label_tensor_i = torch.LongTensor(label_i) label_tensor_f = torch.LongTensor(label_f) label_tensor = [label_tensor_i, label_tensor_f] return img_tensor, label_tensor def get_suction_loader( foldername, dtype="train", batch_size=1, sample_ratio=1, shuffle=True, augment=False, num_channels=2, background_subtract=None, radius=1, num_workers=4, use_cuda=True, ): """Returns a dataloader over the `Suction` dataset. Args: foldername: (str) The name of the folder containing the data. dtype: (str) Whether to use the train, validation or test partition. batch_size: (int) The number of data samples in a batch. sample_ratio: (float) The ratio of negative to positive labels. shuffle: (bool) Whether to shuffle the dataset at the end of every epoch. augment: (bool) Whether to apply data augmentation. num_workers: (int) How many processes to use. Each workers is responsible for loading a batch. use_cuda: (bool) Whether to use the GPU. """ def _collate_fn(batch): """A custom collate function. This is to support variable length suction labels. """ imgs = [b[0] for b in batch] labels = [b[1] for b in batch] imgs = torch.cat(imgs, dim=0) labels = [l for sublist in labels for l in sublist] return [imgs, labels] num_workers = min(num_workers, multiprocessing.cpu_count()) root = os.path.join(config.ml_data_dir, foldername, dtype) dataset = SuctionDataset( root, sample_ratio, augment, background_subtract, num_channels, radius, ) loader = DataLoader( dataset, batch_size=batch_size, shuffle=shuffle, collate_fn=_collate_fn, pin_memory=True, num_workers=num_workers, ) return loader <file_sep>/form2fit/code/ml/models/__init__.py from form2fit.code.ml.models.correspondence import CorrespondenceNet from form2fit.code.ml.models.placement import PlacementNet from form2fit.code.ml.models.suction import SuctionNet
7c1c95886161b24336eae5a76a0589f6b16ba9dc
[ "Markdown", "Python", "Shell" ]
33
Markdown
darshanasalvi/form2fit
099a4ceac0ec60f5fbbad4af591c24f3fff8fa9e
adbb9cfd2f3d3a32884fb88f0a89828903a99a58
refs/heads/master
<repo_name>msparks/docker-prosody<file_sep>/README.md # docker-prosody This is a Docker image for [Prosody](http://prosody.im), a light-weight XMPP server. This Docker image is intended to be used a base for other Docker images that include their own virtual hosts and SSL keys; see the section below on deriving from this image. You should not use this image by itself. This image is automatically published on the [Docker Hub](https://hub.docker.com/) at [msparks/prosody](https://registry.hub.docker.com/u/msparks/prosody/). ## Usage The default configuration creates a single VirtualHost for `example.com`. SSL/TLS is enabled, but note that the private key for the self-signed certificate is in the published image, so you obviously should not use this image in a production environment. To test out the image: # Create the data volume container. # Data is stored in /var/lib/prosody in the container. docker run --name=prosody-data msparks/prosody:data # Run prosody image. # DO NOT USE THIS IN PRODUCTION. docker run --rm -ti --name=prosody \ -p 5222:5222 \ --volumes-from prosody-data \ msparks/prosody # Create a user. This is necessary because registration is disabled. docker exec -ti prosody prosodyctl adduser <EMAIL> Then connect on port 5222 as `<EMAIL>` with the password you entered in the last step. ## Paths Prosody cares about these paths: * `/etc/prosody` for configuration files. * `/var/lib/prosody` for data. Exported as a volume by `msparks/prosody:data`. * `/var/log/prosody` for logs ## Deriving from this image If you want to build your own image from this one, you just need to create a new Dockerfile that contains FROM msparks/prosody COPY conf /etc/prosody and create a `conf` directory with your own `prosody.cfg.lua` file. <file_sep>/data/Makefile all: data .PHONY: all data: docker build -t msparks/prosody:data . .PHONY: data <file_sep>/entrypoint.sh #!/bin/bash set -e chown -R prosody: /var/lib/prosody chmod 700 /var/lib/prosody sudo -u prosody "$@" <file_sep>/data/Dockerfile FROM busybox MAINTAINER <NAME> <<EMAIL>> VOLUME ["/var/lib/prosody"] <file_sep>/Makefile all: prosody .PHONY: all prosody: docker build -t msparks/prosody . .PHONY: prosody
4e348eecca85a36b964719fd168a279420ef639e
[ "Markdown", "Makefile", "Dockerfile", "Shell" ]
5
Markdown
msparks/docker-prosody
442b92e0aa311f937c3040a3c20beb7624e02cb4
ad424ed29aab80607d13dc0a75c1c2cccd9526be
refs/heads/master
<file_sep>import json import os import urllib from google.appengine.ext import ndb from google.appengine.api import users import jinja2 import webapp2 import json JINJA_ENVIRONMENT = jinja2.Environment( loader=jinja2.FileSystemLoader(os.path.dirname(__file__)), extensions=['jinja2.ext.autoescape'], autoescape=True) class Thesis(ndb.Model): year= ndb.StringProperty() title = ndb.StringProperty(indexed=True) abstract = ndb.StringProperty(indexed=True) adviser = ndb.StringProperty(indexed=True) section= ndb.StringProperty() date = ndb.DateTimeProperty(auto_now_add=True) class ThesisHandler(webapp2.RequestHandler): def get(self): template = JINJA_ENVIRONMENT.get_template('main.html') self.response.write(template.render()) def post(self): thesis =Thesis() thesis.year = self.request.get('year') thesis.title = self.request.get('title') thesis.abstract = self.request.get('abstract') thesis.adviser = self.request.get('adviser') thesis.section = self.request.get('section') thesis.put() self.redirect('/') class APINewHandler(webapp2.RequestHandler): def get(self): CpE_Thesis= Thesis.query().order(-Thesis.date).fetch() thesis_list=[] for thesis in CpE_Thesis: thesis_list.append ({ 'id': thesis.key.id(), 'year' : thesis.year, 'title': thesis.title, 'abstract': thesis.abstract, 'adviser': thesis.adviser, 'section': thesis.section }) response = { 'result' :'OK' , 'data' : thesis_list } self.response.headers['Content-type'] = 'app/json' self.response.out.write(json.dumps(response)) def post(self): thesis = Thesis() thesis.year = self.request.get('year') thesis.title = self.request.get('title') thesis.abstract = self.request.get('abstract') thesis.adviser = self.request.get('adviser') thesis.section = self.request.get('section') thesis.put() response = { 'result': 'OK', 'data':{ 'id': thesis.key.id(), 'year' : thesis.year, 'title': thesis.title, 'abstract': thesis.abstract, 'adviser': thesis.adviser, 'section': thesis.section } } self.response.out.write(json.dumps(response)) class ThesisDelete(webapp2.RequestHandler): def get(self,id): thesis_key = Thesis.get_by_id(int(id)) thesis_key.key.delete() self.redirect('/') class ThesisEdit(webapp2.RequestHandler): def get(self,id): template = JINJA_ENVIRONMENT.get_template('edit.html') self.response.write(template.render()) CpE_Thesis = Thesis.query().order(-Thesis.date).fetch() thesis_id = int(id) response = { 'CpE_Thesis': CpE_Thesis, 'id':thesis_id } self.response.write(template.render(response)) def post(self,id): thesis_id = int(id) thesis = Thesis.get_by_id(thesis_id) thesis.year = self.request.get('year') thesis.title = self.request.get('title') thesis.abstract = self.request.get('abstract') thesis.adviser = self.request.get('adviser') thesis.section = self.request.get('section') thesis.put() self.redirect('/home') app = webapp2.WSGIApplication([ ('/api/thesis', APINewHandler), ('/thesis/delete/(\d+)', ThesisDelete), ('/thesis/edit/(\d+)',ThesisEdit), ('/home', ThesisHandler), ('/', ThesisHandler) ], debug=True)
1d6b3b7c307d42dfd36d705c4d99a098e94cffc8
[ "Python" ]
1
Python
JMichaelNolasco/Module-3---Basic-Thesis-Database-System--CRUD-
967cecc74a74e67d39940e5862a4d6b708cbcd1a
3fa006ea28e294b854179f82fd3db0dd70e7ccdc
refs/heads/main
<repo_name>staff-634/study-step.CA<file_sep>/10-canvas/js/cofee.js let cnvOne = document.getElementById("cnv1"); let ctx = cnvOne.getContext("2d"); ctx.fillStyle = "green"; ctx.fillRect(5,5,181,10); ctx.fillText("JavaScript 18.1%", 210,15); ctx.fillRect(5,20,147,10); ctx.fillText("Java 14.7%", 210,30); ctx.fillRect(5,35,143,10); ctx.fillText("C# 14.3%", 210,45); ctx.fillRect(5,50,121,10); ctx.fillText("Python 12.1%", 210,60); ctx.fillRect(5,65,101,10); ctx.fillText("PHP 10.1%", 210,75); ctx.fillRect(5,80,69,10); ctx.fillText("TypeScript 6.9%", 210,90); ctx.fillRect(5,95,46,10); ctx.fillText("C++ 4.6%", 210,105); ctx.fillRect(5,110,192,10); ctx.fillText("Інші 19.2%", 210,120); ctx.beginPath(); ctx.moveTo(299,0); ctx.lineTo(299,300); ctx.fillStyle = "#000"; ctx.fillText("Динаміка використання", 310,15); ctx.fillText("JavaScript та TypeScript", 360,30); ctx.fillText("2012 - 2021", 410,45); ctx.moveTo(350,270); ctx.fillText("2012", 340,280); ctx.lineTo(530,270); ctx.fillText("2021", 520,280); ctx.moveTo(370,270); ctx.lineTo(370,265); //2013 ctx.moveTo(390,270); ctx.lineTo(390,265); //2014 ctx.moveTo(410,270); ctx.lineTo(410,265); //2015 ctx.moveTo(430,270); ctx.lineTo(430,265); //2016 ctx.moveTo(450,270); ctx.lineTo(450,265); //2017 ctx.moveTo(470,270); ctx.lineTo(470,265); //2018 ctx.moveTo(490,270); ctx.lineTo(490,265); //2019 ctx.moveTo(510,270); ctx.lineTo(510,265); //2020 ctx.stroke(); ctx.beginPath(); ctx.strokeStyle = "yellow"; //JS ctx.moveTo(350,233); ctx.lineTo(370,215); //2013 ctx.moveTo(370,215); ctx.lineTo(390,195); //2014 ctx.moveTo(370,215); ctx.lineTo(390,195); //2015 ctx.moveTo(390,195); ctx.lineTo(410,159); //2015 ctx.moveTo(410,159); ctx.lineTo(430,131); //2016 ctx.moveTo(430,131); ctx.lineTo(450,108); //2017 ctx.moveTo(450,108); ctx.lineTo(470,105); //2018 ctx.moveTo(470,105); ctx.lineTo(490,93); //2019 ctx.moveTo(490,93); ctx.lineTo(510,86); //2020 ctx.moveTo(510,86); ctx.lineTo(530,89); //2021 ctx.stroke(); ctx.fillStyle = "yellow"; ctx.fillText("JavaScript", 535,90); ctx.fillText("18.1%", 535,100); ctx.beginPath(); ctx.strokeStyle = "blue"; //TS ctx.moveTo(430,270); ctx.lineTo(450,268); //2017 ctx.moveTo(450,268); ctx.lineTo(470,250); //2018 ctx.moveTo(470,250); ctx.lineTo(490,241); //2019 ctx.moveTo(490,241); ctx.lineTo(510,223); //2020 ctx.moveTo(510,223); ctx.lineTo(530,201); //2021 ctx.stroke(); ctx.fillStyle = "blue"; ctx.fillText("TypeScript", 535,202); ctx.fillText("6.9%", 535,212); ctx.beginPath(); ctx.strokeStyle = "#000"; ctx.moveTo(599,0); ctx.lineTo(599,300); ctx.stroke(); ctx.fillStyle = "#000"; ctx.fillText("Використання у Front-end розробці", 610,15); ctx.fillText("JavaScript - 68.2%", 610,55); ctx.fillText("TypeScript - 26%", 610,65); ctx.fillText("Java - 1.4%", 610,75); ctx.fillText("C# - 1.2%", 610,85); ctx.fillText("PHP - 1.1%", 610,95); ctx.fillText("Інші - 2.1%", 610,105); ctx.moveTo(650,150); ctx.lineTo(750,150); ctx.moveTo(750,150); ctx.lineTo(818,250); //JS ctx.moveTo(750,150); ctx.lineTo(814,250); //Java ctx.moveTo(750,150); ctx.lineTo(802,250); //C# ctx.moveTo(750,150); ctx.lineTo(791,250); //PHP ctx.moveTo(750,150); ctx.lineTo(771,250); //Other ctx.stroke(); <file_sep>/05-bootstrap/bs.html <!DOCTYPE html> <head> <meta charset="utf-8"> <title>Seven</title> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <link rel="stylesheet" href="libs/bootstrap/css/bootstrap-grid.min.css"> <link rel="stylesheet" href="libs/bootstrap/css/bootstrap.min.css"> <link rel="stylesheet" href="css/fonts.css"> <link rel="stylesheet" href="css/style.css"> </head> <body> <div class="container-fluid header"> <div class="container"> <div class="row "> <div class="col"><a href="#" class="logo"><img src="icon/logo.png"></a></div> <div class="col offset-1"></div> <div class="col"><a href="#">Solutions</a></div> <div class="col"><a href="#">Products</a></div> <div class="col"><a href="#">Portfolio</a></div> <div class="col"><a href="#">Contact</a></div> <div class="w-100"></div> <div class="col-12"> <div id="carouselExampleCaptions" class="carousel slide" data-ride="carousel"> <div class="carousel-inner"> <div class="carousel-item active"><img src="icon/cofee2.png" class="d-block w-100" alt="..."> <div class="carousel-caption d-none d-md-block"> <h2>Introdusing</h2> <p>Something hot......</p> <div class="try"><a href="#">Try Demo</a></div> </div> </div> <div class="carousel-item"><img src="icon/cofee2.png" class="d-block w-100" alt="..."> <div class="carousel-caption d-none d-md-block"> <h2>Якийсь текст</h2> <p>Місце для розміщення текстової інформації</p> <div class="try"><a href="#">Тиць сюди</a></div> </div> </div> </div> <a class="carousel-control-prev" href="#carouselExampleIndicators" role="button" data-slide="prev"><img src="icon/arrowL.png"></a> <a class="carousel-control-next" href="#carouselExampleIndicators" role="button" data-slide="next"><img src="icon/arrowR.png"></a> </div> </div> </div> </div> </div> <div class="container-fluid body"> <div class="container"> <div class="row"> <div class="col-3 tabs"><img src="icon/11.png"></br>Responsive</br><span>Websites</span></div> <div class="col-3 tabs"><img src="icon/22.png"></br>e Commerce</br><span>Websites</span></div> <div class="col-3 tabs"><img src="icon/32.png"></br>Daily blog</br><span>Websites</span></div> <div class="col-3 tabs"><img src="icon/42.png"></br>Searh based</br><span>Websites</span></div> <div class="col-12 mix"></div> <div class="w-100"></div> <div class="col-12 text"> <h3>Lorem Ipsum is simply dummy text</h3> <p>Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged.</p> <p>It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.</p> </div> <div class="w-100"></div> <div class="col-6 f1"><img src="icon/screen.png"></div> <div class="col-6 f1"> <ul><h4>Why choose us?</h4> <li>Lorem Ipsum is simply dummy text of the printing and typesetting</li> <li>Lorem Ipsum has been the industry's standard dummy text ever</li> <li>When an unknown printer took a galley of type and scrambled</li> <li>It has survived not only five centuries, but also the leap into electronic</li> <li>It was popularised in the 1960s with the release of Letraset sheets containing</li> <li>More recently with desktop publishing software like Aldus PageMaker</li> </ul> </div> </div> </div> </div> <div class="container-fluid form"> <form action="#" method="post" name="ms" autocomplete="off"></form> <div class="container"> <div class="row"> <div class="col ml"><span>Member login</span></br> <input type="text" maxlength="16" placeholder="User name" required pattern="[A-Z][a-z]{3-16}"></input> <input type="password" maxlength="50" placeholder="<PASSWORD>" required pattern="^(?=.*[0-9])(?=.*[a-z])(?=.*[A-Z])(?=\S+$).{12,}$"></input> <button class="submit">Log me in.</button> </div> <div class="col sb"><span>Subscribe to our weekly newsletter</span> <input type="email" maxlength="50" placeholder="email address" required></input> <button class="submit">Subscribe</button> </div> </div> </div> </div> <div class="container-fluid footer"> <div class="container"> <div class="row"> <div class="col"> <ul>About Us <li><a href="">About us</a></li> <li><a href="">Why us</a></li> <li><a href="">Customer stories</a></li> <li><a href="">Press resourses</a></li> <li><a href="">Press Releases</a></li> <li><a href="">Contact us</a></li> </ul> </div> <div class="col"> <ul>About Us <li><a href="">About us</a></li> <li><a href="">Why us</a></li> <li><a href="">Customer stories</a></li> <li><a href="">Press resourses</a></li> <li><a href="">Press Releases</a></li> <li><a href="">Contact us</a></li> </ul> </div> <div class="col-4">Testimoanials <div id="carouselExampleCaptions" class="carousel ptt" data-ride="carousel"> <div class="carousel-inner"> <div class="carousel-item active"><p>Lorem Ipsum is simply dummy text of the printing and.Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a. It was popularised in the 1960s with the release of Letraset sheets containing.</p> </div> <div class="carousel-item"><p>Місце для розміщення текстової інформації</p> </div> </div> <a class="carousel-control-prev" href="#carouselExampleIndicators" role="button" data-slide="prev"><img src="icon/arrowLl.png"></a> <a class="carousel-control-next" href="#carouselExampleIndicators" role="button" data-slide="next"><img src="icon/arrowRr.png"></a> <div><b>Lorem Ipsum is simply</b></div> <div><b>Owner, Lorem Ipsum</b></div> </div> </div> <div class="col"><a href="#"><img src="icon/logo.png"></a></br><a href="https://cssauthor.com/" class="copy">&copy; cssauthor.com</a></div> </div> </div> </div> </div> <script src="libs/jquery/jquery.js"></script> <script src="libs/bootstrap/js/bootstrap.min.js"></script> </body> </html><file_sep>/README.md # study-step.CA My work while studying in CA "STEP-Mykolaiv". - 01-07 HTML & CSS 02-05.2021 - 08- JS 05- .2021 - - .2021 - - .2021
1a62f1f1e3152a4ffdc41089343c239347060fb1
[ "JavaScript", "HTML", "Markdown" ]
3
JavaScript
staff-634/study-step.CA
e3eba8b6506d78a96b255bf2be6845db7e1bb5ea
9b5555cb3763031cd37f64f44944b9f30de2f69b
refs/heads/master
<file_sep>#include "su3.h" using namespace NS_SU3; using namespace std; #include <stdio.h> //Purpose of this program is to investigate if //a truly random walk through p-q space and see if the //same weights appear as specified in the more guided //random walk done in traj.cc void get_good_list (int p_given, int q_given, int p_new, int q_new, int delta_p[7], int delta_q[7], int maxval, int num_multiplet, Tpqlist * good_list); int main (int argc, char **argv) { int Amax, n0, p1, q1, n1, pmax, pprime, qprime, a, ipq, count, nprime; double r, wsum, wtot, w[7]; CRandy *randy = new CRandy (-time (NULL)); char filename[150]; vector < vector < vector < double >>>pqcount; Amax = atoi (argv[1]); //Grab Amax and the starting point from arguments pmax = GetPmax(Amax); //let the walker move around a little bit. long Ntraj, itraj; Ntraj = 1000; CalcPQCount(Amax,pqcount); sprintf (filename, "gluon_walks/gluon_traj_%d.txt", Amax); //open a file for our trajectories that come back to zero FILE *fptr = fopen (filename, "w"); fprintf (fptr, "t p q n\n"); int dp[7] = { 2, 1, 0, -1, -2, 1, -1 }, dq[7] = { -1, 1, 0, 2, 1, -2, -1 }; //initalize tableaux "machinery" Tpqlist *goodlist = new Tpqlist (pmax); Tpq *pq; vector < int >traj_vectors[Amax + 1]; //storing our trajectory with vectors vector < int >curr_traj {0, 0, 0, 0}; for (itraj = 0; itraj < Ntraj; itraj++) //generate Ntraj total random walks { curr_traj[0] = 0; p1 = curr_traj[1] = 0; q1 = curr_traj[2] = 0; n1 = curr_traj[3] = 1; traj_vectors[0] = curr_traj; for (a = 1; a <= Amax; a++) // adding 'A' total gluons to our trajectory { wtot = 0.0; goodlist->clear (); get_good_list (p1, q1, pprime, qprime, dp, dq, pmax, count, goodlist); //grabs the allowed states we can jump too and stores them in goodlist ipq = 0; wtot = 0.; for (pq = goodlist->first; pq != NULL; pq = pq->next) { pprime = pq->p; qprime = pq->q; w[ipq] = pqcount[Amax - a][pprime][qprime] * pq->n / degen (pprime, qprime); wtot += w[ipq]; ipq += 1; } r = randy->ran (); //grab a number on the interval [0,1] pq = goodlist->first; wsum = 0.0; ipq = 0; do //add the weights, and the first one to pass 'r' is the multiplet we select { pprime = pq->p; qprime = pq->q; nprime = pq->n; wsum += w[ipq] / wtot; if (wsum > 1.000001) { printf ("wsum=%g\n", wsum); exit (1); } pq = pq->next; ipq += 1; } while (r > wsum); curr_traj[0] = a; p1 = curr_traj[1] = pprime; q1 = curr_traj[2] = qprime; n1 = curr_traj[3] = nprime; traj_vectors[a] = curr_traj; //add this value of (p,q) to our array goodlist->clear (); } int len = sizeof(traj_vectors)/sizeof(traj_vectors[0]); int p_iter, q_iter, n_iter; char output_string[100]; for (int i = 0; i < len; i++) //output the step, and p and q to a file { p_iter = traj_vectors[i][1]; q_iter = traj_vectors[i][2]; n_iter = traj_vectors[i][3]; sprintf (output_string, "%i %i %i %i\n", i, p_iter, q_iter, n_iter); fprintf (fptr, "%s", output_string); } } fclose (fptr); return 0; } void get_good_list (int p_given, int q_given, int p_new, int q_new, int delta_p[7], int delta_q[7], int maxval, int num_multiplet, Tpqlist * good_list) { for (int iter_pq = 0; iter_pq < 7; iter_pq++) { //using the rules of young tableaux diagrams, get the possible multiplets we may jump too if ((p_given == 0) && (q_given == 0)) { good_list->add (1, 1, 1); break; } p_new = p_given - delta_p[iter_pq]; q_new = q_given - delta_q[iter_pq]; if (p_new >= 0 && q_new >= 0 && p_new <= maxval && q_new <= maxval) { num_multiplet = 1; if (iter_pq == 2) num_multiplet = 2; good_list->add (p_new, q_new, num_multiplet); } } } <file_sep>#include "randy.h" using namespace std; CRandy::CRandy(int iseed){ seed=iseed; mt.seed(seed); } void CRandy::reset(int iseed){ seed=iseed; mt.seed(seed); } double CRandy::ran(){ return ranu(mt); } double CRandy::ran_exp(){ return -log(ran()); } double CRandy::ran_gauss(void){ return rang(mt); } void CRandy::ran_gauss2(double &ra,double &rb){ double x,y,r2,r,c,s; TRY_AGAIN: x=1.0-2.0*ran(); y=1.0-2.0*ran(); r2=x*x+y*y; if(r2>1.0) goto TRY_AGAIN; r=sqrt(r2); c=x/r; s=y/r; ra=c*sqrt(-2.0*log(r2)); rb=(s/c)*ra; } void CRandy::generate_boltzmann_alt(double mass,double T,FourVector &p){ const double PI=4.0*atan(1.0); double r1,r2,r3,r0,I1,I2,I3,Itot; double pmag,E,ctheta,stheta,phi,pgauss,K; array<double,4> pp; pp[0]=pp[1]=pp[2]=pp[3]=1.2345; GB_TRYAGAIN: r0=ran(); I1=mass*mass; I2=2.0*mass*T; I3=2.0*T*T; Itot=I1+I2+I3; if(r0<I1/Itot){ r1=ran(); K=-T*log(r1); } else if(r0<(I1+I2)/Itot){ r1=ran(); r2=ran(); K=-T*log(r1*r2); } else{ r1=ran(); r2=ran(); r3=ran(); K=-T*log(r1*r2*r3); } E=K+mass; pmag=sqrt(E*E-mass*mass); r0=ran(); if(r0>pmag/E) goto GB_TRYAGAIN; phi=2.0*PI*ran(); ctheta=1.0-2.0*ran(); stheta=sqrt(1.0-ctheta*ctheta); p[3]=pmag*ctheta; p[1]=pmag*stheta*cos(phi); p[2]=pmag*stheta*sin(phi); p[0]=E; } void CRandy::generate_boltzmann(double mass,double T,FourVector &p){ const double PI=4.0*atan(1.0); double r1,r2,r3,a,b,c; double pmag,ctheta,stheta,phi,pgauss; if(T/mass>0.6){ GB_TRYAGAIN: r1=ran(); r2=ran(); r3=ran(); a=-log(r1); b=-log(r2); c=-log(r3); pmag=T*(a+b+c); p[0]=sqrt(pmag*pmag+mass*mass); if(ran()>exp((pmag-p[0])/T)) goto GB_TRYAGAIN; ctheta=(a-b)/(a+b); stheta=sqrt(1.0-ctheta*ctheta); phi=T*T*pow(a+b,2)/(pmag*pmag); phi=2.0*PI*phi; p[3]=pmag*ctheta; p[1]=pmag*stheta*cos(phi); p[2]=pmag*stheta*sin(phi); } else generate_boltzmann_alt(mass,T,p); } int CRandy::poisson(){ return ranp(mt); } void CRandy::set_mean(double mu){ using param_t = std::poisson_distribution<int>::param_type; ranp.param(param_t{mu}); } <file_sep>#ifndef __ADDMULTS_CC__ #define __ADDMULTS_CC__ #include "su3.h" using namespace std; using namespace NS_SU3; void NS_SU3::ReadNpq(vector<vector<vector<double>>> &Npq,int Amax,vector<vector<double>> &biggestweight){ int pmax,a,p,q,a1,a2,d; double weight; char filename[150]; FILE *fptr; biggestweight.resize(Amax+1); for(a=0;a<=Amax;a++){ biggestweight[a].resize(Amax+1); } pmax=GetPmax(Amax); Npq.resize(Amax+1); for(a=0;a<=Amax;a++){ Npq[a].resize(pmax+1); for(p=0;p<=pmax;p++){ Npq[a][p].resize(p+1); for(q=0;q<=p;q++){ Npq[a][p][q]=0; } } if(a>0){ sprintf(filename,"opentrajectories/Npq_A%d.dat",a); fptr=fopen(filename,"r"); fscanf(fptr,"%d %d",&p,&q); while(!feof(fptr)){ fscanf(fptr,"%lf",&Npq[a][p][q]); fscanf(fptr,"%d %d",&p,&q); } fclose(fptr); } } for(a1=0;a1<=Amax;a1++){ for(a2=0;a2<=a1;a2++){ biggestweight[a1][a2]=0.0; if(a1!=a2) biggestweight[a2][a1]=0.0; if(a1<a2) pmax=GetPmax(a1); else pmax=GetPmax(a2); for(p=0;p<=pmax;p++){ for(q=0;q<=p;q++){ d=degen(p,q); if(a1==a2){ //weight=0.5*Npq[a1][p][q]*(Npq[a2][p][q]-1)/(d*d); weight=0.5*Npq[a1][p][q]*(Npq[a2][p][q]-1.0)/(d*d); if(p==q) weight*=4.0; } else{ weight=0.5*Npq[a1][p][q]*Npq[a2][p][q]/(d*d); if(p==q) weight*=4.0; } if(weight>biggestweight[a1][a2]){ biggestweight[a1][a2]=weight; if(a1!=a2) biggestweight[a2][a1]=biggestweight[a1][a2]; } } } } } } void NS_SU3::WriteOpenTrajectories(int A,long long int ntraj,CRandy *randy){ long long int itraj; int pmax=GetPmax(A),p,q,a; double w; char filename[150]; vector<int> ptraj; vector<int> qtraj; ptraj.resize(A+1); qtraj.resize(A+1); // Npq counts the number of trajectories for given pq vector<vector<double>> Npq; Npq.resize(pmax+1); for(p=0;p<=pmax;p++){ Npq[p].resize(p+1); for(q=0;q<=p;q++) Npq[p][q]=0; } // Open Files to write trajectoies vector<vector<FILE *>> opentraj; opentraj.resize(pmax+1); for(p=0;p<=pmax;p++){ opentraj[p].resize(p+1); for(q=0;q<=p;q++){ sprintf(filename,"opentrajectories/A%d/p%d_q%d.dat",A,p,q); opentraj[p][q]=fopen(filename,"w"); } } // NOW LET'S MAKE TRAJECTORIES for(itraj=0;itraj<ntraj;itraj++){ ptraj[0]=qtraj[0]=0; p=q=0; for(a=1;a<=A;a++){ RanStep(p,q,randy->ran(),w); if(p>GetPmax(a) || q>GetPmax(a)){ printf("pq is too big=%d,%d, a=%d",p,q,a); } ptraj[a]=p; qtraj[a]=q; } if(p>pmax || q>pmax){ printf("%d:%d, pmax=%d\n",p,q,pmax); exit(1); } for(a=0;a<=A;a++){ //printf("A=%d, p=%d, q=%d, ptraj=%d,qtraj=%d\n",A,p,q,ptraj[A],qtraj[A]); if(p>=q){ fprintf(opentraj[p][q],"%d %d ",ptraj[a],qtraj[a]); } else{ fprintf(opentraj[q][p],"%d %d ",ptraj[a],qtraj[a]); } //printf("--------\n"); } if(p>=q){ fprintf(opentraj[p][q],"\n"); Npq[p][q]+=1; } else{ fprintf(opentraj[q][p],"\n"); Npq[q][p]+=1; } if(((itraj+1)*10)%ntraj==0) printf("finished %g percent of trajectories\n",double(itraj+1)*100.0/double(ntraj)); } for(p=0;p<=pmax;p++){ for(q=0;q<=p;q++){ fclose(opentraj[p][q]); } } sprintf(filename,"opentrajectories/Npq_A%d.dat",A); FILE *fptr=fopen(filename,"w"); for(p=0;p<=pmax;p++){ for(q=0;q<=p;q++){ fprintf(fptr,"%d %d %g\n",p,q,Npq[p][q]); } } fclose(fptr); } void NS_SU3::CalcPQCount(int Amax,vector<vector<vector<double>>> &pqcount){ int A,pmax,p,q; int nquarks=0,nanti=0,ngluons,casimir; double dtot,Mtot,nsinglets=0; double dtrue; Tpq *pq; Tpqlist **pqlist; CRandy *randy=new CRandy(-1234); ngluons=Amax; //Amax=ngluons+nquarks+nanti; pqlist=new Tpqlist *[Amax+1]; pmax=GetPmax(ngluons)+nquarks+nanti; for(A=0;A<=Amax;A++) pqlist[A]=new Tpqlist(GetPmax(ngluons)+nquarks+nanti); pqlist[0]->add(0,0,1); for(A=1;A<=Amax;A++){ pqlist[A]->clear(); for(pq=pqlist[A-1]->first;pq!=NULL;pq=pq->next){ if(A<=ngluons) addmults_list(pq->p,pq->q,pq->n,1,1,1,pqlist[A]); if(A>ngluons && A<=ngluons+nquarks) addmults_list(pq->p,pq->q,pq->n,1,0,1,pqlist[A]); if(A>ngluons+nquarks) addmults_list(pq->p,pq->q,pq->n,0,1,1,pqlist[A]); } //pqlist[A-1]->clear(); //pqlist[A]->compress(); } pqcount.resize(Amax+1); for(A=0;A<=Amax;A++){ pqcount[A].resize(pmax+1); for(p=0;p<=pmax;p++){ pqcount[A][p].resize(pmax+1,0); } } for(A=0;A<=Amax;A++){ dtot=Mtot=0.0; for(pq=pqlist[A]->first;pq!=NULL;pq=pq->next){ p=pq->p; q=pq->q; //printf("pqcount=%f A=%d p=%d q=%d\n",pqcount[A][p][q],A,p,q); pqcount[A][p][q]+=degen(p,q)*pq->n; if(A==Amax){ dtot+=degen(p,q)*pq->n; Mtot+=pq->n; if(A==Amax && pq->p==0 && pq->q==0) nsinglets+=pq->n; } } if(A==Amax){ dtrue=pow(double(3),nquarks+nanti)*pow(8.0,ngluons); printf("---- A=%d, dtot=%g =? %g ----\n",A,dtot,dtrue); printf("Nsinglets=%g = %g fraction of multiplets and %g fraction of states\n",nsinglets,nsinglets/Mtot,nsinglets/dtot); } } for(A=0;A<=Amax;A++){ pqlist[A]->remove(); delete pqlist[A]; } delete randy; delete pqlist; } void NS_SU3::ClearPQCount(int Amax,vector<vector<vector<double>>> &pqcount){ int pmax=GetPmax(Amax); for(int A=0;A<=Amax;A++){ for(int p=0;p<=pmax;p++){ for(int q=0;q<=pmax;q++){ pqcount[A][p][q]=0; } } } } double NS_SU3::omega_massless(double T,double V){ const double prefactor=(1.0/(2.0*PI*PI*HBARC*HBARC*HBARC)); return 4.0*V*prefactor*T*T*T; } double NS_SU3::omegae_massless(double T,double V){ const double prefactor=(1.0/(2.0*PI*PI*HBARC*HBARC*HBARC)); return 12.0*V*prefactor*T*T*T*T; } double NS_SU3::omega_bessel(double mass,double T,double V){ const double prefactor=(1.0/(PI*PI*HBARC*HBARC*HBARC)); double z,answer; z=mass/T; answer=V*pow(mass,3)*prefactor*(z*cyl_bessel_k(0,z)+2.0*cyl_bessel_k(1,z))/(z*z); return answer; } double NS_SU3::omegae_bessel(double mass,double T,double V){ const double prefactor=(1.0/(PI*PI*HBARC*HBARC*HBARC)); double z,answer; z=mass/T; answer=V*pow(mass,4)*prefactor*(3.0*z*cyl_bessel_k(0,z)+(z*z+6.0)*cyl_bessel_k(1,z))/(z*z*z); return answer; } double NS_SU3::omegap_bessel(double mass,double T,double V){ const double prefactor=(1.0/(PI*PI*HBARC*HBARC*HBARC)); double z,answer; z=mass/T; answer=V*mass*mass*T*T*prefactor*(cyl_bessel_k(0,z)+2*cyl_bessel_k(1,z)/z); return answer; } int NS_SU3::GetPmax(int A){ return lrint(0.1+1.5*A); } int NS_SU3::degen(int p,int q){ int answer; answer=(p+1)*(q+1)*(p+q+2); return answer/2; } int NS_SU3::Casimir(int p,int q){ return (p*p+q*q+3*p+3*q+p*q)/3; } #endif <file_sep>import matplotlib.pyplot as plt from matplotlib.lines import Line2D import numpy as np import os from pylab import * from matplotlib import ticker from matplotlib.ticker import ScalarFormatter sformatter=ScalarFormatter(useOffset=True,useMathText=True) sformatter.set_scientific(True) sformatter.set_powerlimits((-2,3)) #plt.ticklabel_format(style='sci', axis='y', scilimits=(0,0)) font = {'family' : 'serif', 'weight' : 'normal', 'size' : 14} plt.rc('font', **font) plt.rc('text', usetex=False) plt.figure(figsize=(6,5)) fig = plt.figure(1) ax = fig.add_axes([0.15,0.12,0.8,0.8]) a10=np.arange(0,11) a20=np.arange(0,21) a30=np.arange(0,31) a40=np.arange(0,41) mydata=np.loadtxt('../trajectories/A20.dat',skiprows=0,unpack=False) for i in arange(0,20): plt.plot(a20,mydata[i],color='r',linestyle='-',linewidth=2,marker='None') #amax=5 #z10=1.5*(amax-(a10-amax)*(a10-amax)/amax) #plt.plot(a10,z10,color='k',linestyle='-',linewidth='6',marker='None') amax=10 z20=1.5*(amax-(a20-amax)*(a20-amax)/amax) plt.plot(a20,z20,color='k',linestyle='-',linewidth=5) #amax=15 #z30=1.5*(amax-(a30-amax)*(a30-amax)/amax) #plt.plot(a30,z30,color='k',linestyle='-',linewidth='6',marker='None') #amax=20 #z40=1.5*(amax-(a40-amax)*(a40-amax)/amax) #plt.plot(a40,z40,color='k',linestyle='-',linewidth='6',marker='None') #plt.semilogy(x,y) ax.tick_params(axis='both', which='major', labelsize=14) ax.set_xticks(np.arange(0,81,5), minor=False) ax.set_xticklabels(np.arange(0,81,5), minor=False, family='serif') ax.set_xticks(np.arange(0,81,1), minor=True) #ax.xaxis.set_major_formatter(ticker.FormatStrFormatter('%0.1f')) ax.xaxis.set_major_formatter(sformatter) plt.xlim(0.0,20) ax.set_yticks(np.arange(0,200,20), minor=False) ax.set_yticklabels(np.arange(0,200,20), minor=False, family='serif') ax.set_yticks(np.arange(0,200,5), minor=True) plt.ylim(0.0,50.0) #ax.set_yticks(0.1:1.0:10.0:100.0, minor=True) #ax.yaxis.set_major_formatter(ticker.FormatStrFormatter('%.1e')) ax.yaxis.set_major_formatter(sformatter) text(15,13,'$A_{\\rm max}=20$') text(30,24,'$A_{\\rm max}=40$') #text(45,35,'$A_{\\rm max}=60$') #text(60,46,'$A_{\\rm max}=80$') plt.xlabel('$A$', fontsize=18, weight='normal') plt.ylabel('$\langle C_1\\rangle$',fontsize=18) #plt.title('MathText Number $\sum_{n=1}^\infty({-e^{i\pi}}/{2^n})$!', #fontsize=12, color='gray') #plt.subplots_adjust(top=0.85) plt.savefig('traj.pdf',format='pdf') os.system('open -a Preview traj.pdf') #plt.show() quit() <file_sep>EIGEN_INCLUDE_PATH = /usr/local/include/eigen3 CC = clang++ -std=c++11 -O2 all : make -C ../software make edens make edens_vsA make edist edens : edens.cc ../software/lib/libsu3.a ${CC} -o edens edens.cc -I ../software/include -L ../software/lib -I${EIGEN_INCLUDE_PATH} -I/usr/local/include -L/usr/local/lib -lsu3 edens_vsA : edens_vsA.cc ../software/lib/libsu3.a ${CC} -o edens_vsA edens_vsA.cc -I ../software/include -L ../software/lib -I${EIGEN_INCLUDE_PATH} -I/usr/local/include -L/usr/local/lib -lsu3 edist : edist.cc ../software/lib/libsu3.a ${CC} -o edist edist.cc -I ../software/include -L ../software/lib -I${EIGEN_INCLUDE_PATH} -I/usr/local/include -L/usr/local/lib -lsu3 traj : traj.cc ../software/lib/libsu3.a ${CC} -o traj traj.cc -I ../software/include -L ../software/lib -I${EIGEN_INCLUDE_PATH} -I/usr/local/include -L/usr/local/lib -lsu3 corr : corr.cc ../software/lib/libsu3.a ${CC} -o corr corr.cc -I ../software/include -L ../software/lib -I/usr/local/include -L/usr/local/lib -lsu3 slope_smeared : slope_smeared.cc ../software/lib/libsu3.a ${CC} -o slope_smeared slope_smeared.cc -I ../software/include -L ../software/lib -I/usr/local/include -L/usr/local/lib -lsu3 slope : slope.cc ../software/lib/libsu3.a ${CC} -o slope slope.cc -I ../software/include -L ../software/lib -I/usr/local/include -L/usr/local/lib -lsu3 exact : exact.cc ../software/lib/libsu3.a ${CC} -o exact exact.cc -I ../software/include -L ../software/lib -I/usr/local/include -L/usr/local/lib -lsu3 findmults_list : findmults_list.cc ../software/lib/libsu3.a ${CC} -o findmults_list findmults_list.cc -I ../software/include -L ../software/lib -I${EIGEN_INCLUDE_PATH} -I/usr/local/include -L/usr/local/lib -lsu3 <file_sep>#include "su3.h" using namespace NS_SU3; using namespace std; int main () { int A, Amax; int nquarks, nanti, ngluons; double dtrue, dtot, nsinglets; Tpq *pq; Tpqlist **pqlist; printf ("Enter Ngluons, Nquarks and Nantiquarks : "); scanf ("%d %d %d", &ngluons, &nquarks, &nanti); Amax = ngluons + nquarks + nanti; pqlist = new Tpqlist *[Amax + 1]; for (A = 0; A <= Amax; A++) pqlist[A] = new Tpqlist (GetPmax (ngluons) + nquarks + nanti); pqlist[0]->add (0, 0, 1); for (A = 1; A <= Amax; A++) { pqlist[A]->clear (); for (pq = pqlist[A - 1]->first; pq != NULL; pq = pq->next) { /* if(A<=ngluons) addmults_list(pq->p,pq->q,pq->n,1,1,1,pqlist[A]); if(A>ngluons && A<=ngluons+nquarks) addmults_list(pq->p,pq->q,pq->n,1,0,1,pqlist[A]); if(A>ngluons+nquarks) addmults_list(pq->p,pq->q,pq->n,0,1,1,pqlist[A]); */ if (A <= nquarks) addquark_list (pq->p, pq->q, pq->n, pqlist[A]); if (A > nquarks && A <= nquarks + nanti) addantiquark_list (pq->p, pq->q, pq->n, pqlist[A]); if (A > nanti + nquarks) addgluon_list (pq->p, pq->q, pq->n, pqlist[A]); } //pqlist[A]->compress(); } dtot = 0; nsinglets = 0; for (pq = pqlist[Amax]->first; pq != NULL; pq = pq->next) { //printf("(%d,%d), n=%d\n",pq->p,pq->q,pq->n); dtot += degen (pq->p, pq->q) * pq->n; if (pq->p == 0 && pq->q == 0) nsinglets += pq->n; } dtrue = pow (double (3), nquarks + nanti) * pow (8.0, ngluons); printf ("dtot=%g =? %g\n", dtot, dtrue); printf ("Nsinglets=%g\n", nsinglets); //for(A=0;A<=Amax;A++) pqlist[A]->print(); pqlist[Amax]->print (); return 0; } <file_sep>#include "su3.h" using namespace NS_SU3; using namespace std; int main(){ int Amax,p,q,pmax,a,Ntraj,itraj,Nsample=10; double YB=7.0, WG=0.8; // beam rapidity and gaussian thermal smearing width vector<double> eta; CRandy *randy=new CRandy(-time(NULL)); vector<vector<vector<double>>> pqcount; double edens=0,y,eta_temp; double Ebar=0,E2bar=0,E3bar=0,E4bar=0,kappa1_avg=0,kappa2_avg=0,kappa3_avg=0,kappa4_avg=0,Ssigma_avg=0,Ksigma2_avg=0,c3c1_avg=0,c4c3_avg=0; double k1error,k2error,k3error,k4error,omega_avg=0,Serror,Kerror,werror,c3c1error,c4c3error; vector<double> kappa1,kappa2,kappa3,kappa4,Ssigma,Ksigma2,omega,c3c1,c4c3; printf("Enter Ntraj: "); scanf("%d",&Ntraj); printf("Enter Amax: "); scanf("%d",&Amax); CalcPQCount(Amax,pqcount); pmax=GetPmax(Amax+2); eta.resize(Amax+2); Ctraj traj(Amax+1); multimap<double,int> etamap; multimap<double,int> amap; multimap<double,int>::iterator iter; string filename="moments.dat"; FILE *fptr=fopen(filename.c_str(),"w"); fprintf(fptr,"y\tkappa1\tk1error\tkappa2\tk2error\tkappa3\tk3error\tkappa4\tk4error\tSsigma_avg\tSerror\tKsigma2_avg\tKerror\tomega_avg\twerror\n"); for(y=-6.5;y<=6.5;y+=1){ Ssigma.clear(); Ksigma2.clear(); omega.clear(); kappa1.clear(); kappa2.clear(); kappa3.clear(); kappa4.clear(); c3c1.clear(); c4c3.clear(); Ssigma_avg=Ksigma2_avg=omega_avg=0; kappa1_avg=kappa2_avg=kappa3_avg=kappa4_avg=0; c3c1_avg=c4c3_avg=0; Serror=Kerror=werror=0; k1error=k2error=k3error=k4error=0; c3c1error=c4c3error=0; printf("------------------------------------------------------\n"); for(int isample=0;isample<Nsample;isample++){ Ebar=E2bar=E3bar=E4bar=0; printf("y=%lf, beginning sample %d\n",y,isample); for(int itraj=0;itraj<Ntraj;itraj++){ etamap.clear(); etamap.insert(pair<double,int>(-YB,0)); etamap.insert(pair<double,int>(YB,Amax+1)); for(a=1;a<=Amax;a++){ eta_temp=YB*(1.0-2.0*randy->ran()); etamap.insert(pair<double,int>(eta_temp,a)); } a=0; for(iter=etamap.begin();iter!=etamap.end();++iter){ eta[a]=iter->first; a=a+1; } traj.FindTrajectory(Amax+1,pqcount,randy); traj.CalcCasimirs(); //traj.PrintCasimirs(); for(a=0;a<=Amax;a++){ edens+=.5*traj.casimir[a]*(erf((eta[a+1]-y)/(sqrt(2)*WG))-erf((eta[a]-y)/(sqrt(2)*WG))); } Ebar+=edens; E2bar+=edens*edens; E3bar+=pow(edens,3); E4bar+=pow(edens,4); edens=0; } Ebar/=double(Ntraj); E2bar/=double(Ntraj); E3bar/=double(Ntraj); E4bar/=double(Ntraj); kappa1.push_back(Ebar); kappa2.push_back(E2bar-Ebar*Ebar); kappa3.push_back(E3bar-3*kappa2.back()*Ebar-Ebar*Ebar*Ebar); kappa4.push_back(E4bar-4*kappa3.back()*Ebar-3*kappa2.back()*kappa2.back()-6*kappa2.back()*Ebar*Ebar-Ebar*Ebar*Ebar*Ebar); Ssigma.push_back(kappa3.back()/kappa2.back()); Ksigma2.push_back(kappa4.back()/kappa2.back()); omega.push_back(kappa2.back()/kappa1.back()); c3c1.push_back(kappa3.back()/kappa1.back()); c4c3.push_back(kappa4.back()/kappa3.back()); Ssigma_avg+=Ssigma.back(); Ksigma2_avg+=Ksigma2.back(); omega_avg+=omega.back(); kappa1_avg+=kappa1.back(); kappa2_avg+=kappa2.back(); kappa3_avg+=kappa3.back(); kappa4_avg+=kappa4.back(); c3c1_avg+=c3c1.back(); c4c3_avg+=c4c3.back(); } //printf("kappa1_avg=%lf kappa2_avg=%lf kappa3_avg=%lf kappa4_avg=%lf\n",kappa1_avg,kappa2_avg,kappa3_avg,kappa4_avg); Ssigma_avg/=double(Nsample); Ksigma2_avg/=double(Nsample); omega_avg/=double(Nsample); kappa1_avg/=double(Nsample); kappa2_avg/=double(Nsample); kappa3_avg/=double(Nsample); kappa4_avg/=double(Nsample); c3c1_avg/=double(Nsample); c4c3_avg/=double(Nsample); for(int isample=0;isample<Nsample;isample++){ Serror+=(Ssigma[isample]-Ssigma_avg)*(Ssigma[isample]-Ssigma_avg); Kerror+=(Ksigma2[isample]-Ksigma2_avg)*(Ksigma2[isample]-Ksigma2_avg); werror+=(omega[isample]-omega_avg)*(omega[isample]-omega_avg); k1error+=(kappa1[isample]-kappa1_avg)*(kappa1[isample]-kappa1_avg); k2error+=(kappa2[isample]-kappa2_avg)*(kappa2[isample]-kappa2_avg); k3error+=(kappa3[isample]-kappa3_avg)*(kappa3[isample]-kappa3_avg); k4error+=(kappa4[isample]-kappa4_avg)*(kappa4[isample]-kappa4_avg); c3c1error+=(c3c1[isample]-c3c1_avg)*(c3c1[isample]-c3c1_avg); c4c3error+=(c4c3[isample]-c4c3_avg)*(c4c3[isample]-c4c3_avg); } Serror=sqrt(Serror)/double(Nsample); Kerror=sqrt(Kerror)/double(Nsample); werror=sqrt(werror)/double(Nsample); k1error=sqrt(k1error)/double(Nsample); k2error=sqrt(k2error)/double(Nsample); k3error=sqrt(k3error)/double(Nsample); k4error=sqrt(k4error)/double(Nsample); c3c1error=sqrt(c3c1error)/double(Nsample); c4c3error=sqrt(c4c3error)/double(Nsample); fprintf(fptr,"%lf\t%lf\t%lf\t%lf\t%lf\t%lf\t%lf\t%lf\t%lf\t%lf\t%lf\t%lf\t%lf\t%lf\t%lf\t%lf\t%lf\t%lf\t%lf\n", y,kappa1_avg,k1error,kappa2_avg,k2error,kappa3_avg,k3error,kappa4_avg,k4error, omega_avg,werror,Ssigma_avg,Serror,Ksigma2_avg,Kerror,c3c1_avg,c3c1error,c4c3_avg,c4c3error); } delete randy; ClearPQCount(Amax,pqcount); fclose(fptr); return 0; } <file_sep>#include "su3.h" using namespace NS_SU3; using namespace std; int main(){ int Amax,p,q,a1,a2,pmax; char filename[150]; double CZbar,Cbar,w; CRandy *randy=new CRandy(-time(NULL)); vector<vector<vector<double>>> pqcount; printf("Enter Amax: "); scanf("%d",&Amax); pmax=GetPmax(Amax); CalcPQCount(Amax,pqcount); Ctraj traj(Amax); int Ntraj,itraj,a; vector<double> C(Amax+1); printf("Enter Ntraj: "); scanf("%d",&Ntraj); sprintf(filename,"trajectories/A%d.dat",Amax); FILE *fptr=fopen(filename,"w"); for(int itraj=0;itraj<Ntraj;itraj++){ traj.FindTrajectory(Amax,pqcount,randy); traj.CalcCasimirs(); traj.Write(fptr); for(a1=0;a1<=Amax;a1++){ C[a1]+=traj.casimir[a1]; } traj.Print(); } fclose(fptr); for(a1=0;a1<=Amax;a1++){ printf("Cbar[%d]=%g\n",a1,C[a1]/double(Ntraj)); } return 0; } <file_sep>import matplotlib.pyplot as plt import numpy as np from scipy.optimize import curve_fit import os file="moments_vsA.dat"; mydata = np.loadtxt(file,skiprows=1,unpack=True) A=mydata[0] kappa1_avg=mydata[1] k1error=mydata[2] kappa2_avg=mydata[3] k2error=mydata[4] kappa3_avg=mydata[5] k3error=mydata[6] kappa4_avg=mydata[7] k4error=mydata[8] omega=mydata[9] werror=mydata[10] Ssigma=mydata[11] Serror=mydata[12] Ksigma=mydata[13] Kerror=mydata[14] fig=plt.figure(figsize=(8,16)) ax1 = fig.add_subplot(411) plt.ylabel('$C_1$', fontsize=22, weight='normal') ax2 = fig.add_subplot(412) plt.ylabel('$C_2$', fontsize=22, weight='normal') #ax3 = fig.add_subplot(313) #plt.ylabel('$C_2/C_1$', fontsize=22, weight='normal') ax3 = fig.add_subplot(413) plt.ylabel('$C_3$', fontsize=22, weight='normal') plt.ticklabel_format(axis="y", style="sci", scilimits=(0,0)) ax4 = fig.add_subplot(414) plt.ylabel('$C_4$', fontsize=22, weight='normal') plt.ticklabel_format(axis="y", style="sci", scilimits=(0,0)) plt.xlabel('A',fontsize=18 , weight='normal') def linear(A, m): return m*A def parabola(A, m): return m*A**2 def cubic(A, m): return m*A**3 def quartic(A, m): return m*A**4 param, param_cov = curve_fit(linear, A, kappa1_avg) line = param[0]*A ax1.errorbar(A,kappa1_avg,k1error,linestyle='',linewidth=2,markersize=8,color='r', marker='o', markerfacecolor=None, markeredgecolor=None) ax1.plot(A,line,linestyle='-',color='r') param, param_cov = curve_fit(parabola, A, kappa2_avg) parab = param[0]*A**2 ax2.errorbar(A,kappa2_avg,k2error,linestyle='',linewidth=2,markersize=8,color='g', marker='d', markerfacecolor=None, markeredgecolor=None) ax2.plot(A,parab,linestyle='--',color='g') """ param, param_cov = curve_fit(linear, A, omega) line = param[0]*A ax3.errorbar(A,omega,werror,linestyle='',linewidth=2,markersize=10,color='b', marker='^', markerfacecolor=None, markeredgecolor=None) ax3.plot(A,line,linestyle='-',color='b') """ param, param_cov = curve_fit(parabola, A, kappa3_avg) parab = param[0]*A**2 param, param_cov = curve_fit(cubic, A, kappa3_avg) cub = param[0]*A**3 ax3.errorbar(A,kappa3_avg,k3error,linestyle='',linewidth=2,markersize=10,color='b', marker='^', markerfacecolor=None, markeredgecolor=None) ax3.plot(A,parab,linestyle='--',color='b') ax3.plot(A,cub,linestyle=':',color='b') param, param_cov = curve_fit(parabola, A, kappa4_avg) parab = param[0]*A**2 param, param_cov = curve_fit(cubic, A, kappa4_avg) cub = param[0]*A**3 param, param_cov = curve_fit(quartic, A, kappa4_avg) quart = param[0]*A**4 ax4.errorbar(A,kappa4_avg,k4error,linestyle='',linewidth=2,markersize=10,color='k', marker='s', markerfacecolor=None, markeredgecolor=None) ax4.plot(A,parab,linestyle='--',color='k') ax4.plot(A,cub,linestyle=':',color='k') ax4.plot(A,quart,linestyle='-',color='k') plt.savefig('figs/moments_vsA.pdf',format='pdf') os.system('xdg-open figs/moments_vsA.pdf') quit() <file_sep>import numpy as np import matplotlib matplotlib.use('Agg') import matplotlib.pyplot as plt import sys whichA = sys.argv[1] A = int(whichA) filename = "A" +whichA+ ".txt" traj_total = np.loadtxt("/home/thomas/fluxtubes/thomasrun/trajectories/" + filename) average = np.average(traj_total, axis=0) A_vals = np.arange(0,A+1,1) x_vals = np.arange(0,A+2,2) fig = plt.figure() plt.bar(A_vals, average, align = "edge", width = 1,color="red",edgecolor="black") plt.xlabel("A") plt.xticks(x_vals) plt.ylabel("Average Value of Casimir Operator") plt.title("Amax="+str(A)+", Ntraj ="+str(A**2)) plt.savefig("/home/thomas/fluxtubes/figs/A"+whichA+".png") <file_sep>#include "su3.h" using namespace NS_SU3; using namespace std; int main(){ int Amax,p,q; int Ntraj,itraj,a,ahalf,dela,a1,a2; double alpha,alpha2=0.0; CRandy *randy=new CRandy(-time(NULL)); vector<vector<vector<double>>> pqcount; printf("Enter Amax: "); scanf("%d",&Amax); CalcPQCount(Amax,pqcount); dela=Amax/5; ahalf=floorl((Amax+1.0)/2.0); a1=ahalf-dela; a2=ahalf+dela; Ctraj traj(Amax); vector<double> corr(ahalf,0.0); vector<double> Cbar(Amax+1); printf("Enter Ntraj: "); scanf("%d",&Ntraj); for(int itraj=0;itraj<Ntraj;itraj++){ do{ traj.FindTrajectory(Amax,pqcount,randy); traj.CalcCasimirs(); }while(traj.casimir[ahalf]==0); for(a=0;a<=Amax;a++){ Cbar[a]+=traj.casimir[a]; } alpha=(traj.casimir[a2]-traj.casimir[a1])/(2.0*dela); if(traj.casimir[ahalf]!=0) alpha2+=alpha*alpha; } for(a=0;a<=Amax;a++){ Cbar[a]=Cbar[a]/double(Ntraj); printf("Cbar[%d]=%g\n",a,Cbar[a]); } alpha2=alpha2/(double(Ntraj)*pow(Cbar[ahalf],0.0)); printf("<alpha^2=%g>\n",alpha2); return 0; } <file_sep>import matplotlib.pyplot as plt from matplotlib.lines import Line2D import numpy as np import os from pylab import * from matplotlib import ticker from matplotlib.ticker import ScalarFormatter sformatter=ScalarFormatter(useOffset=True,useMathText=True) sformatter.set_scientific(True) sformatter.set_powerlimits((-2,3)) #plt.ticklabel_format(style='sci', axis='y', scilimits=(0,0)) font = {'family' : 'serif', 'weight' : 'normal', 'size' : 14} plt.rc('font', **font) plt.rc('text', usetex=False) plt.figure(figsize=(6,5)) fig = plt.figure(1) ax = fig.add_axes([0.15,0.12,0.8,0.8]) mydata10 = np.loadtxt('Cbar_A10.dat',skiprows=0,unpack=True) a10=mydata10[0] cbar10=mydata10[1] mydata20 = np.loadtxt('Cbar_A20.dat',skiprows=0,unpack=True) a20=mydata20[0] cbar20=mydata20[1] mydata30 = np.loadtxt('Cbar_A30.dat',skiprows=0,unpack=True) a30=mydata30[0] cbar30=mydata30[1] mydata40 = np.loadtxt('Cbar_A40.dat',skiprows=0,unpack=True) a40=mydata40[0] cbar40=mydata40[1] plt.plot(a10,cbar10,color='r',linestyle='None',markersize=4, marker='o', markerfacecolor='r', markeredgecolor='r') plt.plot(a20,cbar20,color='r',linestyle='None',markersize=4, marker='o', markerfacecolor='r', markeredgecolor='r') plt.plot(a30,cbar30,color='r',linestyle='None',markersize=4, marker='o', markerfacecolor='r', markeredgecolor='r') plt.plot(a40,cbar40,color='r',linestyle='None',markersize=4, marker='o', markerfacecolor='r', markeredgecolor='r') amax=10 z10=1.5*(amax-(a10-amax)*(a10-amax)/amax) plt.plot(a10,z10,color='k',linestyle='-',linewidth='6',marker='None') amax=20 z20=1.5*(amax-(a20-amax)*(a20-amax)/amax) plt.plot(a20,z20,color='k',linestyle='-',linewidth='6',marker='None') amax=30 z30=1.5*(amax-(a30-amax)*(a30-amax)/amax) plt.plot(a30,z30,color='k',linestyle='-',linewidth='6',marker='None') amax=40 z40=1.5*(amax-(a40-amax)*(a40-amax)/amax) plt.plot(a40,z40,color='k',linestyle='-',linewidth='6',marker='None') #plt.semilogy(x,y) ax.tick_params(axis='both', which='major', labelsize=14) ax.set_xticks(np.arange(0,81,20), minor=False) ax.set_xticklabels(np.arange(0,81,10), minor=False, family='serif') ax.set_xticks(np.arange(0,81,1), minor=True) ax.xaxis.set_major_formatter(ticker.FormatStrFormatter('%0.1f')) plt.xlim(0.0,80) ax.set_yticks(np.arange(0,200,20), minor=False) ax.set_yticklabels(np.arange(0,200,20), minor=False, family='serif') ax.set_yticks(np.arange(0,200,5), minor=True) plt.ylim(0.0,64.0) #ax.set_yticks(0.1:1.0:10.0:100.0, minor=True) #ax.yaxis.set_major_formatter(ticker.FormatStrFormatter('%.1e')) ax.yaxis.set_major_formatter(sformatter) text(15,13,'$A_{\\rm max}=20$') text(30,24,'$A_{\\rm max}=40$') text(45,35,'$A_{\\rm max}=60$') text(60,46,'$A_{\\rm max}=80$') plt.xlabel('$A$', fontsize=18, weight='normal') plt.ylabel('$\langle C_1\\rangle$',fontsize=18) #plt.title('MathText Number $\sum_{n=1}^\infty({-e^{i\pi}}/{2^n})$!', #fontsize=12, color='gray') #plt.subplots_adjust(top=0.85) plt.savefig('cbar.pdf',format='pdf') os.system('open -a Preview cbar.pdf') #plt.show() quit() <file_sep>import numpy as np import matplotlib matplotlib.use('Agg') import matplotlib.pyplot as plt import sys from scipy.optimize import curve_fit def linear_fit(x,m,b): return (x*m+b) A = np.arange(10,101,1) max_cas = [] for a in A: traj_total = np.loadtxt("/home/thomas/fluxtubes/thomasrun/trajectories/A" + str(a)+".txt") max_cas.append(np.amax(traj_total)) max_cas_array = np.array(max_cas) params, error = curve_fit(linear_fit,A,max_cas_array) fit = params[0]*A + params[1] fig = plt.figure() plt.xlabel("Amax") plt.ylabel("Maximum value of Casimir") plt.scatter(A,max_cas,color="red",label="Max Casimir") plt.plot(A,fit,color="black",label="C = "+str(np.round(params[0],2))+"*A + "+ str(np.round(params[1],2))) plt.title("Maximum Casimir Value vs. Amax") plt.legend() plt.savefig("/home/thomas/fluxtubes/figs/max_casimir.png") <file_sep>#ifndef __RANDY_H__ #define __RANDY_H__ #include <cstdlib> #include <cmath> #include <array> #include <random> #include "defs.h" using namespace std; class CRandy{ public: CRandy(int iseed); int seed; double ran(); double ran_gauss(); void ran_gauss2(double &g1,double &g2); double ran_exp(); void reset(int iseed); void generate_boltzmann(double mass,double T,FourVector &p); void generate_boltzmann_alt(double mass,double T,FourVector &p); int poisson(); void set_mean(double mu); // For Poisson Dist private: std::mt19937 mt; std::uniform_real_distribution<double> ranu; std::normal_distribution<double> rang; std::poisson_distribution<int> ranp; }; #endif<file_sep>import matplotlib.pyplot as plt import numpy as np from scipy.optimize import curve_fit import os file="moments.dat"; mydata = np.loadtxt(file,skiprows=1,unpack=True) y=mydata[0] kappa1_avg=mydata[1] k1error=mydata[2] kappa2_avg=mydata[3] k2error=mydata[4] kappa3_avg=mydata[5] k3error=mydata[6] kappa4_avg=mydata[7] k4error=mydata[8] omega=mydata[9] werror=mydata[10] Ssigma=mydata[11] Serror=mydata[12] Ksigma2=mydata[13] Kerror=mydata[14] def parabola(y, a, b): return a*y**2 + b def gaussian(y, A, sigma): return A*np.exp(-y**2/(2*sigma**2))/(np.sqrt(2*np.pi*abs(sigma))) def quartic(y, A, B, C): return A*y**4+B*y**2+C fig=plt.figure(figsize=(8,12)) ax1 = fig.add_subplot(311) plt.ylabel('$C_2/C_1$', fontsize=22, weight='normal') ax2 = fig.add_subplot(312) plt.ylabel('$C_3/C_2$', fontsize=22, weight='normal') ax3 = fig.add_subplot(313) plt.ylabel('$C_4/C_2$', fontsize=22, weight='normal') param, param_cov = curve_fit(parabola, y, omega) parab = param[0]*(y)**2+param[1] ax1.errorbar(y,omega,werror,linestyle='',linewidth=2,markersize=8,color='g', marker='d', markerfacecolor=None, markeredgecolor=None) ax1.plot(y,parab,linestyle='-',color='g') param, param_cov = curve_fit(parabola, y, Ssigma) parab = (param[0]*(y)**2+param[1]) ax2.errorbar(y,Ssigma,Serror,linestyle='',linewidth=2,markersize=8,color='b', marker='^', markerfacecolor=None, markeredgecolor=None) ax2.plot(y,parab,linestyle='-',color='b') param, param_cov = curve_fit(parabola, y, Ksigma2) parab = (param[0]*(y)**2+param[1]) param, param_cov = curve_fit(quartic, y, Ksigma2) quart = param[0]*y**4+param[1]*y**2+param[2] ax3.errorbar(y,Ksigma2,Kerror,linestyle='',linewidth=2,markersize=10,color='k', marker='s', markerfacecolor=None, markeredgecolor=None) ax3.plot(y,parab,linestyle='-',color='k') ax3.plot(y,quart,linestyle=':',color='k') plt.xlabel('y',fontsize=18 , weight='normal') plt.savefig('figs/ratios.pdf',format='pdf') os.system('xdg-open figs/ratios.pdf') quit() <file_sep>#include "su3.h" using namespace NS_SU3; using namespace std; int main(){ int Amax,p,q,A1,A2,pmax; double N12=0.0; double CZbar,Cbar,w; CRandy *randy=new CRandy(-time(NULL)); char filename[150]; vector<vector<vector<double>>> pqcount; printf("Enter Amax: "); scanf("%d",&Amax); pmax=GetPmax(Amax); CalcPQCount(Amax,pqcount); sprintf(filename,"Cbar_Amax%d.dat",Amax); FILE *fptr=fopen(filename,"w"); for(A1=0;A1<=Amax;A1++){ A2=Amax-A1; N12=0.0; Cbar=CZbar=0.0; for(p=0;p<=pmax;p++){ for(q=0;q<=pmax;q++){ w=(pqcount[A1][p][q]/degen(p,q))*(pqcount[A2][p][q]/degen(p,q)); N12+=w; CZbar+=w; Cbar+=w*Casimir(p,q); } } fprintf(fptr,"%3d %g\n",A1,Cbar/CZbar); printf("A1=%3d Cbar=%g\n",A1,Cbar/CZbar); } fclose(fptr); return 0; } <file_sep>#ifndef __PQ_CC__ #define __PQ_CC__ #include "su3.h" using namespace NS_SU3; using namespace std; Tpq::Tpq(int pset,int qset,double nset){ p=pset; q=qset; n=nset; next=NULL; } Tpqlist::Tpqlist(int pqmax_set){ int p,q; pqmax=pqmax_set; first=NULL; last=NULL; pqptr_array=new Tpq **[pqmax+1]; for(p=0;p<=pqmax;p++){ pqptr_array[p]=new Tpq *[pqmax+1]; for(q=0;q<=pqmax;q++) pqptr_array[p][q]=NULL; } } void Tpqlist::print(){ Tpq *pqptr; pqptr=first; do{ printf("(%d,%d), degen=%d, number=%g\n",pqptr->p,pqptr->q, degen(pqptr->p,pqptr->q),pqptr->n); pqptr=pqptr->next; } while(pqptr!=NULL); } void Tpqlist::compress(){ Tpq *pq1,*pq2,*oldpq1,*pqtemp,*nextpq1; for(pq2=first->next;pq2!=NULL;pq2=pq2->next){ oldpq1=NULL; for(pq1=first;pq1!=pq2;pq1=nextpq1){ nextpq1=pq1->next; if(pq1->p==pq2->p && pq1->q==pq2->q){ pqptr_array[pq2->p][pq2->q]=pq2; if(pq1==first){ pqtemp=first; first=first->next; pq1=first; } else{ pqtemp=pq1; if(oldpq1==NULL){ printf("oldpq1=NULL?? error!\n"); exit(1); } oldpq1->next=pq1->next; pq1=oldpq1; } pq2->n+=pqtemp->n; delete pqtemp; } else{ oldpq1=pq1; } } } } void Tpqlist::add(int p,int q,double n){ Tpq *pq; if(p>pqmax || q>pqmax){ printf("Tpqlist::add -- Trying to add to list something that is out of bounds!\n"); printf("p=%d, q=%d, pqmax=%d\n",p,q,pqmax); exit(1); } if(pqptr_array[p][q]==NULL){ pq=new Tpq(p,q,n); if(first==NULL){ first=pq; last=pq; } else{ last->next=pq; last=pq; } pqptr_array[p][q]=pq; } else{ pq=pqptr_array[p][q]; pq->n+=n; } if(p>pqmax||q>pqmax){ printf("Tpqlist::add p,q too large=%d,%d\n",p,q); exit(1); } } void Tpqlist::clear(){ Tpq *next; next=first; while(first!=NULL){ next=first->next; delete first; first=next; } first=NULL; last=NULL; int p,q; for(p=0;p<=pqmax;p++){ for(q=0;q<=pqmax;q++){ pqptr_array[p][q]=NULL; } } } void Tpqlist::remove(){ Tpq *next; next=first; while(first!=NULL){ next=first->next; delete first; first=next; } first=NULL; last=NULL; int p,q; for(p=0;p<=pqmax;p++){ for(q=0;q<=pqmax;q++){ pqptr_array[p][q]=NULL; } delete pqptr_array[p]; } delete pqptr_array; } void Tpqlist::cgluon(int ell){ clear(); if(ell==1) add(1,1,1.0); if(ell==2){ add(2,2,1.0); add(0,3,-1.0); add(3,0,-1.0); add(0,0,1.0); } if(ell>=3){ add(ell,ell,1.0); add(ell-2,ell+1,-1.0); add(ell+1,ell-2,-1.0); add(ell-2,ell-2,-1.0); add(ell,ell-3,1.0); add(ell-3,ell,1.0); add(0,0,2.0); } } void Tpqlist::cquark(int ell){ clear(); if(ell==1) add(1,0,1.0); if(ell==2){ add(2,0,1.0); add(0,1,-1.0); } if(ell>=3){ add(ell,0,1.0); add(ell-2,1,-1.0); add(ell-3,0,1.0); } } #endif <file_sep>#ifndef __TABLEAUX_CC__ #define __TABLEAUX_CC__ //#define PRINT_TABLEAUS #define EPSILON 1.0E-60 #include "su3.h" using namespace NS_SU3; using namespace std; void Ttableaux::getpq(int &p,int &q){ p=length[0]-length[1]; q=length[1]-length[2]; } bool Ttableaux::testequal(Ttableaux *other){ bool test; int i; test=1; for(i=0;i<3;i++){ if(na[i]!=other->na[i] || nb[i]!=other->nb[i] || nx[i]!=other->nb[i]){ test=0; goto TestFailure; } } TestFailure: return test; } void Ttableaux::copy(Ttableaux *tableaux_ptr){ int i,j; //next=tableaux_ptr->next; next=NULL; for(i=0;i<3;i++){ length[i]=tableaux_ptr->length[i]; na[i]=tableaux_ptr->na[i]; nb[i]=tableaux_ptr->nb[i]; nx[i]=tableaux_ptr->nx[i]; } } Ttableaux::Ttableaux(int *naset,int *nbset,int *nxset){ int i; next=NULL; for(i=0;i<3;i++){ na[i]=naset[i]; nb[i]=nbset[i]; nx[i]=nxset[i]; length[i]=na[i]+nb[i]+nx[i]; } } void Ttableaux::print(){ int i,j,p,q; q=length[1]-length[2]; p=length[0]-length[1]; printf("___ P=%d ___ Q=%d ___ degen=%d\n",p,q,degen(p,q)); for(i=0;i<3;i++){ for(j=0;j<nx[i];j++) printf("x "); for(j=0;j<na[i];j++) printf("a "); for(j=0;j<nb[i];j++) printf("b "); printf("\n"); } } Ttableauxlist::Ttableauxlist(){ first=NULL; last=NULL; void clear(); } void Ttableauxlist::clear(){ Ttableaux *tptr; while(first!=NULL){ tptr=first->next; delete first; first=tptr; } first=NULL; last=NULL; } void Ttableauxlist::add(Ttableaux *tableaux){ if(last==NULL){ first=tableaux; last=tableaux; } else{ last->next=tableaux; last=tableaux; } } #endif <file_sep>#ifndef __TRAJECTORY_CC__ #define __TRAJECTORY_CC__ #include "su3.h" using namespace NS_SU3; using namespace std; void Ctraj::FindTrajectory(int A,vector<vector<vector<double>>> pqcount,CRandy* &randy){ Resize(A); int pmax=GetPmax(A); Tpqlist *goodlist=new Tpqlist(pmax+2); Tpq *pq; int p,q,pprime,qprime,a,ipq,count; int dp[7]={2,1,0,-1,-2,1,-1},dq[7]={-1,1,0,2,1,-2,-1}; double r,wsum,wtot,w[7]; p=q=0; for(a=1;a<=A;a++){ wtot=0.0; //goodlist=new Tpqlist(pmax+2); goodlist->clear(); //for(pprime=ppmin;pprime<=ppmax;pprime++){ //for(qprime=qpmin;qprime<=qpmax;qprime++){ for(ipq=0;ipq<7;ipq++){ pprime=p-dp[ipq]; qprime=q-dq[ipq]; if(pprime>=0 && qprime>=0 && pprime<=pmax && qprime<=pmax){ if(pprime!=0 || qprime!=0 || p!=0 || q!=0){ count=1; if(ipq==2) count=2; goodlist->add(pprime,qprime,count); } } } wtot=0.0; ipq=0; for(pq=goodlist->first;pq!=NULL;pq=pq->next){ pprime=pq->p; qprime=pq->q; w[ipq]=pqcount[A-a][pprime][qprime]*pq->n/degen(pprime,qprime); wtot+=w[ipq]; ipq+=1; } //printf("a=%d, wtot=%g\n",a,wtot); r=randy->ran(); pq=goodlist->first; wsum=0.0; ipq=0; do{ pprime=pq->p; qprime=pq->q; wsum+=w[ipq]/wtot; if(wsum>1.000001){ printf("wsum=%g\n",wsum); exit(1); } pq=pq->next; ipq+=1; }while(r>wsum); ptraj[a]=pprime; qtraj[a]=qprime; p=pprime; q=qprime; goodlist->clear(); //delete goodlist; } goodlist->remove(); delete goodlist; //Print(); } void Ctraj::PrintCasimirs(){ for(int a=0;a<=A;a++){ printf("%6d ",casimir[a]); } printf("\n"); } void Ctraj::CalcCasimirs(){ for(int a=0;a<=A;a++){ casimir[a]=Casimir(ptraj[a],qtraj[a]); } } void Ctraj::Print(){ int a; for(a=0;a<=A;a++){ printf("(%2d,%2d)",ptraj[a],qtraj[a]); } printf("\n -----------------------------------------------------------\n"); } void Ctraj::Write(FILE *fptr){ int a; for(a=0;a<=A;a++){ fprintf(fptr,"%d ",casimir[a]); } fprintf(fptr,"\n"); } #endif <file_sep>import matplotlib.pyplot as plt import numpy as np from scipy.optimize import curve_fit import os file="test.dat"; mydata = np.loadtxt(file,skiprows=1,unpack=True) y=mydata[0] kappa1_avg=mydata[1] k1error=mydata[2] kappa2_avg=mydata[3] k2error=mydata[4] kappa3_avg=mydata[5] k3error=mydata[6] kappa4_avg=mydata[7] k4error=mydata[8] omega=mydata[9] werror=mydata[10] Ssigma=mydata[11] Serror=mydata[12] Ksigma=mydata[13] Kerror=mydata[14] def parabola(y, a): return a*y**2 - 49*a def altparabola(y, a, b): return a*y**2 + b def gaussian(y, A, sigma): return A*np.exp(-y**2/(2*sigma**2))/(np.sqrt(2*np.pi*abs(sigma))) def quartic(y, k): return k*(y**2-49)**2 def hexic(y, k): return k*(y**2-49)**3 def octic(y, k): return k*(y**2-49)**4 fig=plt.figure(figsize=(8,16)) ax1 = fig.add_subplot(411) plt.ylabel('$C_1$', fontsize=22, weight='normal') ax2 = fig.add_subplot(412) plt.ylabel('$C_2$', fontsize=22, weight='normal') ax3 = fig.add_subplot(413) plt.ylabel('$C_2/C_1$', fontsize=22, weight='normal') #plt.ylim(bottom=0,top=.06) """ plt.ylabel('$C_3$', fontsize=22, weight='normal') ax4 = fig.add_subplot(414) plt.ylabel('$C_4$', fontsize=22, weight='normal') """ param, param_cov = curve_fit(parabola, y, kappa1_avg) parab = param[0]*(y**2-49) print("kappa 1 parabolic fit: A=", param[0]) ax1.errorbar(y,kappa1_avg,k1error,linestyle='',linewidth=2,markersize=8,color='r', marker='o', markerfacecolor=None, markeredgecolor=None) ax1.plot(y,parab,linestyle='-',color='r') param, param_cov = curve_fit(quartic, y, kappa2_avg) quart = param[0]*(y**2-49)**2 print("kappa 2 quartic fit: A=", param[0]) param, param_cov = curve_fit(parabola, y, kappa2_avg) parab = param[0]*(y**2-49) ax2.errorbar(y,kappa2_avg,k2error,linestyle='',linewidth=2,markersize=8,color='g', marker='d', markerfacecolor=None, markeredgecolor=None) ax2.plot(y,quart,linestyle=':',color='g') ax2.plot(y,parab,linestyle='-',color='g') param, param_cov = curve_fit(altparabola, y, omega) altparab = param[0]*y**2+param[1] ax3.errorbar(y,omega,werror,linestyle='',linewidth=2,markersize=10,color='b', marker='^', markerfacecolor=None, markeredgecolor=None) ax3.plot(y,altparab,linestyle='-',color='b') """ param, param_cov = curve_fit(hexic, y, kappa3_avg) hex = param[0]*(y**2-49)**3 param, param_cov = curve_fit(quartic, y, kappa3_avg) quart = param[0]*(y**2-49)**2 param, param_cov = curve_fit(parabola, y, kappa3_avg) parab = param[0]*(y**2-49) ax3.errorbar(y,kappa3_avg,k3error,linestyle='',linewidth=2,markersize=10,color='b', marker='^', markerfacecolor=None, markeredgecolor=None) ax3.plot(y,parab,linestyle='-',color='b') ax3.plot(y,quart,linestyle=':',color='b') ax3.plot(y,hex,linestyle='--',color='b') param, param_cov = curve_fit(quartic, y, kappa4_avg) quart = param[0]*(y**2-49)**2 param, param_cov = curve_fit(hexic, y, kappa4_avg) hex = param[0]*(y**2-49)**3 param, param_cov = curve_fit(octic, y, kappa4_avg) oct = param[0]*(y**2-49)**4 ax4.errorbar(y,kappa4_avg,k4error,linestyle='',linewidth=2,markersize=10,color='k', marker='s', markerfacecolor=None, markeredgecolor=None) ax4.plot(y,quart,linestyle=':',color='k') ax4.plot(y,hex,linestyle='--',color='k') ax4.plot(y,oct,linestyle='-',color='k') """ plt.xlabel('y',fontsize=18 , weight='normal') plt.savefig('figs/test.pdf',format='pdf') os.system('xdg-open figs/test.pdf') quit() <file_sep>#include <cstdlib> #include <cmath> #include <cstdio> #include <complex> #include <string> #include <cstring> #include <boost/math/special_functions.hpp> const double PI=4.0*atan(1.0); const double HBARC=197.3269602; using namespace std; //using namespace boost::math; long long int degen(int p,int q){ return (p+1)*(q+1)*(p+q+2)/2; } long long int Casimir(int p,int q){ return (p*p+q*q+3*p+3*q+p*q)/3; } double nmults(int p,int q,double sigma){ double a,b,g,theta,x,y,r,sigma2=sigma*sigma,M=1.5; a=sigma*sqrt(3.0); b=sigma; x=(p+q+1.0)/a; y=(p-q)/b; r=sqrt(x*x+y*y); if(r<40.0*sigma){ //printf("x=%g, y=%g\n",x,y); g=(1.0/sigma)*pow(r/sigma2,M)*exp(-0.5*r*r); theta=atan2(y,x); return g; //return g*cos(M*theta); } else return 0.0; } int main(int argc,char *argv[]){ const int AMAX=4000; int p,q; double x,y,r,theta; double nm,sigma,norm,Ebar; for(sigma=0.001*AMAX;sigma<=0.0200001*AMAX;sigma+=0.001*AMAX){ norm=0.0; Ebar=0.0; for(p=0;p<=AMAX;p++){ for(q=0;q<=AMAX;q++){ nm=nmults(p,q,sigma); norm+=nm*degen(p,q); Ebar+=nm*degen(p,q)*Casimir(p,q); } } Ebar=Ebar/norm; printf("AMAX=%3d, sigma=%g, Ebar=%g, Ebar/sigma^4=%g\n",AMAX,sigma,Ebar,Ebar/pow(sigma,2)); } return 0; } <file_sep>#include "su3.h" using namespace NS_SU3; using namespace std; int main(){ int Amax,p,q,pmax,a,a1,a2,Ntraj,itraj,dela,abar,ahalf; char filename[150]; double w,eta_temp,alpha,alpha2,etabar; double YB=7.0, WG=0.8; // beam rapidity and gaussian thermal smearing width vector<double> eta; CRandy *randy=new CRandy(-time(NULL)); vector<vector<vector<double>>> pqcount; double deleta=2.0; FILE *fptr=fopen(filename,"w"); double eta1=-deleta,eta2=deleta,rho1,rho2,E,Etot,Etotbar; printf("Enter Amax: "); scanf("%d",&Amax); ahalf=lrint(0.5*Amax); pmax=GetPmax(Amax+2); eta.resize(Amax+2); CalcPQCount(Amax,pqcount); multimap<double,int> etamap; multimap<double,int> amap; multimap<double,int>::iterator iter; Ctraj traj(Amax+1); vector<double> C(Amax); printf("Enter Ntraj: "); scanf("%d",&Ntraj); for(int isample=0;isample<10;isample++){ alpha2=Etotbar=0.0; for(int itraj=0;itraj<Ntraj;itraj++){ etamap.clear(); etamap.insert(pair<double,int>(-YB,0)); etamap.insert(pair<double,int>(YB,Amax+1)); //make sure on charge is either at +Amax or -Amax if(randy->ran()<0.5){ etamap.insert(pair<double,int>(-YB+0.0001,Amax)); } else{ etamap.insert(pair<double,int>(YB-0.0001,Amax)); } for(a=1;a<Amax;a++){ eta_temp=YB*(1.0-2.0*randy->ran()); etamap.insert(pair<double,int>(eta_temp,a)); } a=0; for(iter=etamap.begin();iter!=etamap.end();++iter){ eta[a]=iter->first; //printf("%2d: %g\n",a,eta[a]); a=a+1; } traj.FindTrajectory(Amax+1,pqcount,randy); traj.CalcCasimirs(); //traj.PrintCasimirs(); rho1=rho2=Etot=0.0; for(a=1;a<Amax;a++){ E=traj.casimir[a]*(eta[a+1]-eta[a]); etabar=0.5*(eta[a+1]+eta[1]); rho1+=E*exp(-0.5*pow(etabar-eta1,2)/(WG*WG)); rho2+=E*exp(-0.5*pow(etabar-eta2,2)/(WG*WG)); Etot+=E; } Etotbar+=Etot; //printf("itraj=%d, eta1=%g, eta2=%g, rho1=%g, rho2=%g\n",itraj,eta1,eta2,rho1,rho2); alpha=(rho1-rho2)/(Etot); alpha2+=alpha*alpha; } alpha2=alpha2/double(Ntraj); Etotbar=Etotbar/double(Ntraj); printf("<alpha^2>=%g, <Etot>=%g, <alpha^2*Etot>=%g\n",alpha2,Etotbar,alpha2*Etotbar); } return 0; } <file_sep>#ifndef __SU3_MISC_CC__ #define __SU3_MISC_CC__ #include "su3.h" using namespace std; using namespace NS_SU3; //#define PRINT_TABLEAUS void NS_SU3::RanStepWeighted(int &p,int &q,double randy,double &weight){ int p1,q1,p2,q2; p1=p; q1=q; p2=q2=1; // gluons int degen1=degen(p1,q1); double ransum=0.0,maxsum=0.0; int ip2,iq2,i,na0min,na1min,na1max,nb1min,nb1max,iw; int na[3],nb[3],nx[3]; Ttableauxlist alist; Ttableaux *atableaux; Ttableaux *abtableaux; Ttableaux *testtableaux; for(i=0;i<3;i++) nb[i]=0; nx[0]=p1+q1; nx[1]=q1; nx[2]=0; na0min=p2+q2-(p1+q1); if(na0min<0) na0min=0; for(na[0]=na0min;na[0]<=p2+q2;na[0]++){ na1min=(p2+q2-na[0])-q1; if(na1min<0) na1min=0; na1max=p1; if(na1max>p2+q2-na[0]) na1max=p2+q2-na[0]; for(na[1]=na1min;na[1]<=na1max;na[1]++){ na[2]=(p2+q2-na[0]-na[1]); atableaux=new Ttableaux(na,nb,nx); alist.add(atableaux); } } for(atableaux=alist.first;atableaux!=NULL; atableaux=atableaux->next){ nb1min=q2-atableaux->length[1]+atableaux->length[2]; if(nb1min<0) nb1min=0; nb1max=q2; if(nb1max>atableaux->length[0]-atableaux->length[1]) nb1max=atableaux->length[0]-atableaux->length[1]; if(nb1max>atableaux->na[0]) nb1max=atableaux->na[0]; for(nb[1]=nb1min;nb[1]<=nb1max;nb[1]++){ nb[2]=q2-nb[1]; if(nb[2]<=atableaux->na[0]+atableaux->na[1]-nb[1]){ p=atableaux->na[0]+nx[0]-atableaux->na[1]-nb[1]-nx[1]; q=atableaux->na[1]+nb[1]+nx[1]-atableaux->na[2]-nb[2]; maxsum+=1.0; } } } weight=maxsum/8.0; //printf("maxsum=%g, weight=%g\n",maxsum,weight); randy*=maxsum; for(atableaux=alist.first;atableaux!=NULL; atableaux=atableaux->next){ nb1min=q2-atableaux->length[1]+atableaux->length[2]; if(nb1min<0) nb1min=0; nb1max=q2; if(nb1max>atableaux->length[0]-atableaux->length[1]) nb1max=atableaux->length[0]-atableaux->length[1]; if(nb1max>atableaux->na[0]) nb1max=atableaux->na[0]; for(nb[1]=nb1min;nb[1]<=nb1max;nb[1]++){ nb[2]=q2-nb[1]; if(nb[2]<=atableaux->na[0]+atableaux->na[1]-nb[1]){ p=atableaux->na[0]+nx[0]-atableaux->na[1]-nb[1]-nx[1]; q=atableaux->na[1]+nb[1]+nx[1]-atableaux->na[2]-nb[2]; ransum+=1.0; if(ransum>maxsum+0.5){ printf("ransum=%g, maxsum=%g\n",ransum,maxsum); } if(ransum>randy){ alist.clear(); return; } } } } alist.clear(); printf("DIDN'T FIND RANSTEP!!!!\n"); exit(1); } void NS_SU3::RanStep(int &p,int &q,double randy,double &weight){ weight=1.0; int p1,q1,p2,q2; p1=p; q1=q; p2=q2=1; // gluons int degen1=degen(p1,q1); double ransum=0.0; int ip2,iq2,i,na0min,na1min,na1max,nb1min,nb1max,iw; int na[3],nb[3],nx[3]; Ttableauxlist alist; Ttableaux *atableaux; Ttableaux *abtableaux; Ttableaux *testtableaux; for(i=0;i<3;i++) nb[i]=0; nx[0]=p1+q1; nx[1]=q1; nx[2]=0; na0min=p2+q2-(p1+q1); if(na0min<0) na0min=0; for(na[0]=na0min;na[0]<=p2+q2;na[0]++){ na1min=(p2+q2-na[0])-q1; if(na1min<0) na1min=0; na1max=p1; if(na1max>p2+q2-na[0]) na1max=p2+q2-na[0]; for(na[1]=na1min;na[1]<=na1max;na[1]++){ na[2]=(p2+q2-na[0]-na[1]); atableaux=new Ttableaux(na,nb,nx); alist.add(atableaux); } } for(atableaux=alist.first;atableaux!=NULL; atableaux=atableaux->next){ nb1min=q2-atableaux->length[1]+atableaux->length[2]; if(nb1min<0) nb1min=0; nb1max=q2; if(nb1max>atableaux->length[0]-atableaux->length[1]) nb1max=atableaux->length[0]-atableaux->length[1]; if(nb1max>atableaux->na[0]) nb1max=atableaux->na[0]; for(nb[1]=nb1min;nb[1]<=nb1max;nb[1]++){ nb[2]=q2-nb[1]; if(nb[2]<=atableaux->na[0]+atableaux->na[1]-nb[1]){ p=atableaux->na[0]+nx[0]-atableaux->na[1]-nb[1]-nx[1]; q=atableaux->na[1]+nb[1]+nx[1]-atableaux->na[2]-nb[2]; ransum+=degen(p,q)/(8.0*degen1); if(ransum>randy){ alist.clear(); return; } } } } alist.clear(); printf("DIDN'T FIND RANSTEP!!!!\n"); exit(1); } void NS_SU3::addmults(int p1,int q1,int p2,int q2,Tweightlist *weightlist){ if(fabs(weightlist->inweight[0])>1.0E-10){ int p,q,ip2,iq2,i,na0min,na1min,na1max,nb1min,nb1max,iw; int na[3],nb[3],nx[3]; Ttableauxlist *alist; Ttableaux *atableaux; Ttableaux *abtableaux; Ttableaux *testtableaux; alist=new Ttableauxlist; for(i=0;i<3;i++) nb[i]=0; nx[0]=p1+q1; nx[1]=q1; nx[2]=0; na0min=p2+q2-(p1+q1); if(na0min<0) na0min=0; for(na[0]=na0min;na[0]<=p2+q2;na[0]++){ na1min=(p2+q2-na[0])-q1; if(na1min<0) na1min=0; na1max=p1; if(na1max>p2+q2-na[0]) na1max=p2+q2-na[0]; for(na[1]=na1min;na[1]<=na1max;na[1]++){ na[2]=(p2+q2-na[0]-na[1]); atableaux=new Ttableaux(na,nb,nx); alist->add(atableaux); } } for(atableaux=alist->first;atableaux!=NULL; atableaux=atableaux->next){ nb1min=q2-atableaux->length[1]+atableaux->length[2]; if(nb1min<0) nb1min=0; nb1max=q2; if(nb1max>atableaux->length[0]-atableaux->length[1]) nb1max=atableaux->length[0]-atableaux->length[1]; if(nb1max>atableaux->na[0]) nb1max=atableaux->na[0]; for(nb[1]=nb1min;nb[1]<=nb1max;nb[1]++){ nb[2]=q2-nb[1]; if(nb[2]<=atableaux->na[0]+atableaux->na[1]-nb[1]){ p=atableaux->na[0]+nx[0]-atableaux->na[1]-nb[1]-nx[1]; q=atableaux->na[1]+nb[1]+nx[1]-atableaux->na[2]-nb[2]; for(iw=0;iw<weightlist->length;iw++){ weightlist->outweight[iw][p][q]+=weightlist->inweight[iw]; } } } } alist->clear(); delete alist; } } void NS_SU3::addgluon_list(int p,int q,int n0,Tpqlist *pqlist){ int dp[7]={2,1,0,-1,-2,1,-1},dq[7]={-1,1,0,2,1,-2,-1}; int pprime,qprime,ipq,count,ncheck=0; if(p==0 && q==0){ pqlist->add(1,1,n0); ncheck+=8; } else{ for(ipq=0;ipq<7;ipq++){ pprime=p+dp[ipq]; qprime=q+dq[ipq]; if(pprime>pqlist->pqmax || qprime>pqlist->pqmax){ printf("NS_SU3::addgluon_list -- pprime, qprime too big, =%d,%d\n",pprime,qprime); exit(1); } if(pprime>=0 && qprime>=0){ count=1; if(ipq==2 && p!=0 && q!=0) count=2; pqlist->add(pprime,qprime,n0*count); ncheck+=count*degen(pprime,qprime); } } } if(ncheck!=8*degen(p,q)){ printf("ncheck=%d =? %d\n",ncheck,8*degen(p,q)); exit(1); } } void NS_SU3::addquark_list(int p,int q,int n0,Tpqlist *pqlist){ int dp[3]={1,-1,0},dq[3]={0,1,-1}; int pprime,qprime,ipq,count,ncheck=0; if(p==0 && q==0){ pqlist->add(1,0,n0); ncheck=3; } else{ for(ipq=0;ipq<3;ipq++){ pprime=p+dp[ipq]; qprime=q+dq[ipq]; if(pprime>pqlist->pqmax || qprime>pqlist->pqmax){ printf("NS_SU3::addgluon_list -- pprime, qprime too big, =%d,%d\n",pprime,qprime); exit(1); } if(pprime>=0 && qprime>=0){ count=1; //if(ipq==2 && pprime!=0 && qprime!=0) //count=2; pqlist->add(pprime,qprime,n0*count); ncheck+=count*degen(pprime,qprime); } } } if(ncheck!=3*degen(p,q)){ printf("ncheck=%d =? %d\n",ncheck,3*degen(p,q)); printf("pq=(%d,%d), p'q'=(%d,%d)\n",p,q,pprime,qprime); exit(1); } } void NS_SU3::addantiquark_list(int p,int q,int n0,Tpqlist *pqlist){ int dp[3]={0,1,-1},dq[3]={1,-1,0}; int pprime,qprime,ipq,count,ncheck=0; if(p==0 && q==0){ pqlist->add(1,0,n0); ncheck=3; } else{ for(ipq=0;ipq<3;ipq++){ pprime=p+dp[ipq]; qprime=q+dq[ipq]; if(pprime>pqlist->pqmax || qprime>pqlist->pqmax){ printf("NS_SU3::addgluon_list -- pprime, qprime too big, =%d,%d\n",pprime,qprime); exit(1); } if(pprime>=0 && qprime>=0){ count=1; //if(ipq==2 && pprime!=0 && qprime!=0) //count=2; pqlist->add(pprime,qprime,n0*count); ncheck+=count*degen(pprime,qprime); } } } if(ncheck!=3*degen(p,q)){ printf("ncheck=%d =? %d\n",ncheck,3*degen(p,q)); printf("pq=(%d,%d), p'q'=(%d,%d)\n",p,q,pprime,qprime); exit(1); } } void NS_SU3::addmults_list(int p1,int q1,double n1, int p2,int q2,long long n2,Tpqlist *pqlist){ int p,q,ip2,iq2,i,na0min,na1min,na1max,nb1min,nb1max; int delp,delpq; int na[3],nb[3],nx[3]; Ttableauxlist *alist; Ttableauxlist *ablist; Ttableaux *atableaux; Ttableaux *abtableaux; alist=new Ttableauxlist; for(i=0;i<3;i++) nb[i]=0; nx[0]=p1+q1; nx[1]=q1; nx[2]=0; na0min=p2+q2-(p1+q1); if(na0min<0) na0min=0; for(na[0]=na0min;na[0]<=p2+q2;na[0]++){ na1min=(p2+q2-na[0])-q1; if(na1min<0) na1min=0; na1max=p1; if(na1max>p2+q2-na[0]) na1max=p2+q2-na[0]; for(na[1]=na1min;na[1]<=na1max;na[1]++){ na[2]=(p2+q2-na[0]-na[1]); atableaux=new Ttableaux(na,nb,nx); alist->add(atableaux); } } ablist=new Ttableauxlist; for(atableaux=alist->first;atableaux!=NULL; atableaux=atableaux->next){ #ifdef PRINT_TABLEAUS printf("___________________________________________\n"); #endif nb1min=q2-atableaux->length[1]+atableaux->length[2]; if(nb1min<0) nb1min=0; nb1max=q2; if(nb1max>atableaux->length[0]-atableaux->length[1]) nb1max=atableaux->length[0]-atableaux->length[1]; if(nb1max>atableaux->na[0]) nb1max=atableaux->na[0]; for(nb[1]=nb1min;nb[1]<=nb1max;nb[1]++){ nb[2]=q2-nb[1]; if(nb[2]<=atableaux->na[0]+atableaux->na[1]-nb[1]){ abtableaux=new Ttableaux(atableaux->na,nb,nx); ablist->add(abtableaux); #ifdef PRINT_TABLEAUS abtableaux->print(); #endif q=abtableaux->length[1]-abtableaux->length[2]; p=abtableaux->length[0]-abtableaux->length[1]; if(p>pqlist->pqmax || q>pqlist->pqmax){ printf("addmults_list, p,q too big, %d,%d, pqmax=%d\n",p,q,pqlist->pqmax); } pqlist->add(p,q,n1*n2); delp=p-p1; delpq=p+q-p1-q1; if(abs(delpq)>2) printf("delp=%d, p1,q1=%d,%d, p2,q2=%d,%d, N=%g, p,q=%d,%d\n",delp,p1,q1,p2,q2,n1*n2,p,q); } } } alist->clear(); ablist->clear(); delete alist; delete ablist; } #endif <file_sep>#include "su3.h" #define NBINS 50 using namespace NS_SU3; using namespace std; int main(){ int Amax,p,q,pmax,a,Ntraj,itraj,Nsample=10,n; double YB=7.0, WG=0.8; // beam rapidity and gaussian thermal smearing width vector<double> eta; CRandy *randy=new CRandy(-time(NULL)); vector<vector<vector<double>>> pqcount; double edens=0,y=0,eta_temp; printf("Enter Ntraj: "); scanf("%d",&Ntraj); printf("Enter n: "); scanf("%d",&n); printf("Enter Amax: "); scanf("%d",&Amax); CalcPQCount(Amax,pqcount); pmax=GetPmax(Amax+2); eta.resize(Amax+2); Ctraj traj(Amax+1); multimap<double,int> etamap; multimap<double,int> amap; multimap<double,int>::iterator iter; string filename="edist.dat"; FILE *fptr=fopen(filename.c_str(),"w"); fprintf(fptr,"edens\tfrequency\n"); int ibin; double Emax=100; double dE=Emax/double(NBINS); int edist[NBINS]={}; printf("------------------------------------------------------\n"); for(int isample=0;isample<Nsample;isample++){ printf("y=%lf, beginning sample %d\n",y,isample); for(int i=0; i<Ntraj/n; i++) { for(int itraj=0;itraj<n;itraj++){ etamap.clear(); etamap.insert(pair<double,int>(-YB,0)); etamap.insert(pair<double,int>(YB,Amax+1)); for(a=1;a<=Amax;a++){ eta_temp=YB*(1.0-2.0*randy->ran()); etamap.insert(pair<double,int>(eta_temp,a)); } a=0; for(iter=etamap.begin();iter!=etamap.end();++iter){ eta[a]=iter->first; a=a+1; } traj.FindTrajectory(Amax+1,pqcount,randy); traj.CalcCasimirs(); //traj.PrintCasimirs(); for(a=0;a<=Amax;a++){ edens+=.5*traj.casimir[a]*(erf((eta[a+1]-y)/(sqrt(2)*WG))-erf((eta[a]-y)/(sqrt(2)*WG))); } } ibin=floorl((edens/double(n))/dE); edist[ibin]+=1; //printf("edens=%lf\n",edens/double(n)); edens=0; } } for(ibin=0;ibin<NBINS;ibin++){ fprintf(fptr,"%lf\t%lf\n",ibin*dE+dE/2.,edist[ibin]/double(Nsample*Ntraj/double(n))); printf("%lf\t%lf\n",ibin*dE+dE/2.,edist[ibin]/double(Nsample*Ntraj/double(n))); } delete randy; ClearPQCount(Amax,pqcount); fclose(fptr); return 0; } <file_sep>#ifndef __SU3_H__ #define __SU3_H__ #include <cmath> #include <cstdio> #include <cstdlib> #include <map> #include "constants.h" #include "defs.h" #include "randy.h" #include <boost/math/special_functions/bessel.hpp> using namespace std; using namespace boost::math; class Tpq{ public: int p,q; double n; Tpq *next; Tpq(int pset,int qset,double nset); }; class Tpqlist{ public: int pqmax; Tpq ***pqptr_array; Tpq *first; Tpq *last; Tpqlist(int Amax); void add(int p,int q,double n); void clear(); void remove(); void cgluon(int ell); void cquark(int ell); void compress(); void print(); }; class Ttableaux{ public: Ttableaux *next; int length[3],na[3],nb[3],nx[3]; Ttableaux(int *naset,int *nbset,int *nxset); void copy(Ttableaux *tableaux_ptr); void print(); bool testequal(Ttableaux *other); void getpq(int &p,int &q); }; class Tweightlist{ public: int length; double inweight[5]; double **outweight[5]; }; class Ttableauxlist{ public: Ttableaux *first; Ttableaux *last; Ttableauxlist(); void add(Ttableaux *tableaux); void clear(); }; class Ctraj{ public: vector<int> ptraj,qtraj,casimir; int A; void Resize(int Aset){ A=Aset; ptraj.resize(A+1); qtraj.resize(A+1); casimir.resize(A+1); } void CalcCasimirs(); void PrintCasimirs(); Ctraj(int Aset){ Resize(Aset); } void JoinTrajectories(vector<vector<vector<int>>> &Npq,CRandy* &randy,int A,vector<vector<double>> &biggestweight); void FindTrajectory(int A,vector<vector<vector<double>>> pqcount,CRandy* &randy); void Print(); void Write(FILE *fptr); }; namespace NS_SU3{ void RanStepWeighted(int &p,int &q,double randy,double &weight); void RanStep(int &p,int &q,double randy,double &weight); void addmults(int p1,int q1,int p2,int q2,Tweightlist *weightlist); void addmults_list(int p1,int q1,double n1,int p2,int q2,int long long n2,Tpqlist *pqlist); void addgluon_list(int p,int q,int n0,Tpqlist *pqlist); void addquark_list(int p,int q,int n0,Tpqlist *pqlist); void addantiquark_list(int p,int q,int n0,Tpqlist *pqlist); void ReadNpq(vector<vector<vector<double>>> &Npq,int Amax,vector<vector<double>> &biggestweight); void WriteOpenTrajectories(int Amax,long long int ntraj,CRandy *randy); void CalcPQCount(int Amax,vector<vector<vector<double>>> &pqcount); void ClearPQCount(int Amax,vector<vector<vector<double>>> &pqcount); int GetPmax(int A); int degen(int p,int q); int Casimir(int p,int q); double omega_massless(double T,double V); double omegae_massless(double T,double V); double omega_bessel(double mass,double T,double V); double omegae_bessel(double mass,double T,double V); double omegap_bessel(double mass,double T,double V); } #endif <file_sep>#ifndef __CORAL_CONSTANTS_H__ #define __CORAL_CONSTANTS_H__ #include <cmath> #include <complex> const double ZERO = 0.0; const double HBARC = 197.3269718; // hbar times c const double ALPHA = 1.0/137.03599976; // fine structure constant const double PI = 3.141592653589793238462643383279; const double SQRTPI = 1.772453850905516; const double SQRTFOURPI = 3.544907702; const double DEGRAD = 57.29577951308232; const double AMU = 931.494; // atomic mass unit const double ProtonMass = 938.272; const double KaonMass = 493.677; const double PionMass = 139.57018; const double Pion0Mass = 134.9766; const double LambdaMass = 1115.7; const double NeutronMass = 939.565; const double RhoMass = 771.1; const double XiMass = 1321.3; const double XiStarMass = 1530.0; const std::complex< double > ci = std::complex< double >(0.0,1.0); #endif <file_sep># fluxtubes fluxtubes project here we go.. <file_sep>#ifndef __BALANCE_DEFS_H__ #define __BALANCE_DEFS_H__ #include <cstdio> #include <cstdlib> #include <cmath> #include <iostream> #include <cstring> #include <complex> #include <sys/stat.h> #include <ctime> #include <vector> #include <array> #include <unordered_map> #include <map> #include <cmath> #include <vector> #include <map> #include <unordered_map> #include <Eigen/Dense> #include "constants.h" using namespace std; class CHydroBalance; class CHydroMesh; class CHyperMesh; class CEoS; class CCharge; class CPart; class CResList; class CResInfo; class CBranchInfo; class CHyperElement; class CBalance; class CAcceptance; class CAction; class CB3D; class CB3DCell; class CRandom; class CParameterMap; class CBalanceArrays; class CSampler; class CLocalInfo; class CAction; class CRegenerate; class CSEInfo; class CHYDROtoB3D; typedef unordered_map<long int,CResInfo *> CResInfoMap; typedef pair<long int, CResInfo*> CResInfoPair; typedef vector<CBranchInfo *> CBranchList; //gives branchlist name typedef multimap<int,CCharge* > CChargeMap; typedef pair<int,CCharge* > CChargePair; typedef multimap<int,CPart* > CPartMap; typedef pair<int,CPart* > CPartPair; //typedef array<double,4> FourVector; typedef double FourVector[4]; typedef multimap<double,CAction *> CActionMap; typedef pair<double,CAction*> CActionPair; #endif <file_sep>import matplotlib.pyplot as plt import numpy as np from scipy.optimize import curve_fit import os file="moments.dat"; mydata = np.loadtxt(file,skiprows=1,unpack=True) y=mydata[0] kappa1_avg=mydata[1] k1error=mydata[2] kappa2_avg=mydata[3] k2error=mydata[4] kappa3_avg=mydata[5] k3error=mydata[6] kappa4_avg=mydata[7] k4error=mydata[8] omega=mydata[9] werror=mydata[10] Ssigma=mydata[11] Serror=mydata[12] Ksigma2=mydata[13] Kerror=mydata[14] c3c1=mydata[15] c3c1error=mydata[16] c4c3=mydata[17] c4c3error=mydata[18] def parabola(y, a, b): return a*y**2 + b def gaussian(y, A, sigma): return A*np.exp(-y**2/(2*sigma**2))/(np.sqrt(2*np.pi*abs(sigma))) def quartic(y, A, B, C): return A*y**4+B*y**2+C def hexic(y, A, B, C, D): return A*y**6+B*y**4+C*y**2+D fig=plt.figure(figsize=(8,12)) ax1 = fig.add_subplot(211) plt.ylabel('$C_3/C_1$', fontsize=22, weight='normal') ax2 = fig.add_subplot(212) plt.ylabel('$C_4/C_3$', fontsize=22, weight='normal') param, param_cov = curve_fit(parabola, y, c3c1) parab = param[0]*(y)**2+param[1] param, param_cov = curve_fit(quartic, y, c3c1) quart = param[0]*y**4+param[1]*y**2+param[2] #param, param_cov = curve_fit(hexic, y, c3c1) #hex = param[0]*y**6+param[1]*y**4+param[2]*y**2+param[3] ax1.errorbar(y,c3c1,c3c1error,linestyle='',linewidth=2,markersize=8,color='b', marker='d', markerfacecolor=None, markeredgecolor=None) ax1.plot(y,parab,linestyle='-',color='b') ax1.plot(y,quart,linestyle=':',color='b') #ax1.plot(y,hex,linestyle='--',color='b') param, param_cov = curve_fit(parabola, y, c4c3) parab = (param[0]*(y)**2+param[1]) param, param_cov = curve_fit(quartic, y, c4c3) quart = param[0]*y**4+param[1]*y**2+param[2] ax2.errorbar(y,c4c3,c4c3error,linestyle='',linewidth=2,markersize=8,color='k', marker='^', markerfacecolor=None, markeredgecolor=None) ax2.plot(y,parab,linestyle='-',color='k') ax2.plot(y,quart,linestyle=':',color='k') plt.xlabel('y',fontsize=18 , weight='normal') plt.savefig('figs/altratios.pdf',format='pdf') os.system('xdg-open figs/altratios.pdf') quit() <file_sep>import matplotlib.pyplot as plt from matplotlib.lines import Line2D import numpy as np import os from pylab import * #import scipy.special as sp from matplotlib import ticker from matplotlib.ticker import ScalarFormatter sformatter=ScalarFormatter(useOffset=True,useMathText=True) sformatter.set_scientific(True) sformatter.set_powerlimits((-2,3)) #plt.ticklabel_format(style='sci', axis='y', scilimits=(0,0)) font = {'family' : 'serif', 'weight' : 'normal', 'size' : 14} plt.rc('font', **font) plt.rc('text', usetex=False) plt.figure(figsize=(6,5)) fig = plt.figure(1) ax = fig.add_axes([0.18,0.12,0.75,0.8]) mydata10 = np.loadtxt('corr_A10.dat',skiprows=0,unpack=True) a10=mydata10[0] corr10=mydata10[1] mydata20 = np.loadtxt('corr_A20.dat',skiprows=0,unpack=True) a20=mydata20[0] corr20=mydata20[1] mydata30 = np.loadtxt('corr_A30.dat',skiprows=0,unpack=True) a30=mydata30[0] corr30=mydata30[1] mydata40 = np.loadtxt('corr_A40.dat',skiprows=0,unpack=True) a40=mydata40[0] corr40=mydata40[1] amax=20 plt.plot(a10/amax,corr10,color='r',linestyle='None',markersize=4, marker='o', markerfacecolor='r', markeredgecolor='r') amax=40 plt.plot(a20/amax,corr20,color='g',linestyle='None',markersize=4, marker='o', markerfacecolor='g', markeredgecolor='g') amax=60 plt.plot(a30/amax,corr30,color='b',linestyle='None',markersize=4, marker='o', markerfacecolor='b', markeredgecolor='b') amax=80 plt.plot(a40/amax,corr40,color='cyan',linestyle='None',markersize=4, marker='o', markerfacecolor='cyan', markeredgecolor='cyan') amax=80 z40=1.0+0.26*exp(-4.5*a40/amax) plt.plot(a40/amax,z40,color='k',linestyle='-',linewidth='6',marker='None') #plt.semilogy(x,y) ax.tick_params(axis='both', which='major', labelsize=14) ax.set_xticks(np.arange(0,1.2,0.2), minor=False) ax.set_xticklabels(np.arange(0,1.2,0.2), minor=False, family='serif') ax.set_xticks(np.arange(0,1.2,0.05), minor=True) ax.xaxis.set_major_formatter(ticker.FormatStrFormatter('%0.1f')) plt.xlim(0.0,1.0) ax.set_yticks(np.arange(0,2.0,0.1), minor=False) ax.set_yticklabels(np.arange(0,2.0,0.1), minor=False, family='serif') ax.set_yticks(np.arange(0,2.0,0.02), minor=True) plt.ylim(0.95,1.3) #ax.set_yticks(0.1:1.0:10.0:100.0, minor=True) #ax.yaxis.set_major_formatter(ticker.FormatStrFormatter('%.1e')) ax.yaxis.set_major_formatter(sformatter) plt.xlabel('$\delta A/A_{\\rm max}$', fontsize=18, weight='normal') plt.ylabel('$\\frac{\langle C_1(A_{\\rm max}/2-\delta A/2)C_1(A_{\\rm max}/2+\delta A/2)\\rangle}{\langle C_1(A_{\\rm max}/2-\delta A/2)\\rangle\langle C_1(A_{\\rm max}/2+\delta A/2)\\rangle}$',fontsize=18) #plt.title('MathText Number $\sum_{n=1}^\infty({-e^{i\pi}}/{2^n})$!', #fontsize=12, color='gray') #plt.subplots_adjust(top=0.85) plt.savefig('corr.pdf',format='pdf') os.system('open -a Preview corr.pdf') #plt.show() quit() <file_sep>import matplotlib.pyplot as plt import numpy as np from scipy.optimize import curve_fit import os file="edist.dat"; mydata = np.loadtxt(file,skiprows=1,unpack=True) edens=mydata[0] n=mydata[1] def gaussian(y, A, B, sigma): return A*np.exp(-(y-B)**2/(2*sigma**2))/(np.sqrt(2*np.pi*abs(sigma))) def fit1(y, A, sigma): return A*y**2*np.exp(-y**2/(2*sigma**2))/(np.sqrt(2*np.pi*abs(sigma))) def fit2(y, A, r): return A*y**4*np.exp(-y/r) fig=plt.figure(figsize=(8,12)) param, param_cov = curve_fit(gaussian, edens, n, p0=[1.,25.,10.]) gauss=param[0]*np.exp(-(edens-param[1])**2/(2*param[2]**2))/(np.sqrt(2*np.pi*abs(param[2]))) print(param) param, param_cov = curve_fit(fit1, edens, n, p0=[1.,30.]) eq1=param[0]*edens**2*np.exp(-edens**2/(2*param[1]**2))/(np.sqrt(2*np.pi*abs(param[1]))) print(param) param, param_cov = curve_fit(fit2, edens, n, p0=[10.,20.]) eq2=param[0]*edens**4*np.exp(-edens/param[1]) print(param) plt.plot(edens,n,linestyle='',linewidth=2,markersize=8,color='k', marker='d', markerfacecolor=None, markeredgecolor=None) plt.plot(edens,eq1,linestyle='-',color='r',label='$x^2$*gaussian') plt.plot(edens,eq2,linestyle='-',color='g',label='$x^4 e^{-x}$') plt.plot(edens,gauss,linestyle='-',color='b',label='gaussian') plt.xlabel('dE/dy',fontsize=18 , weight='normal') plt.ylabel('% of paths',fontsize=18 , weight='normal') plt.legend(fontsize=18) plt.savefig('figs/dist.pdf',format='pdf') os.system('xdg-open figs/dist.pdf') quit() <file_sep>MADAI_GSLPATH = /usr/local MADAI_CPP = /usr/bin/clang++ #MADAI_CPP = /usr/local/bin/clang-omp++ #MADAI_CPP = /usr/bin/g++ #compiler MADAI_CFLAGS = -Oz -std=c++14 -Wall INCLUDE = -I include -I /usr/local/include LIBRARY = -L lib -L /usr/local/lib OBJFILES = build/addmults.o build/pq.o build/randy.o build/su3_misc.o build/tableaux.o build/trajectory.o lib/libsu3.a : ${OBJFILES} ar -ru lib/libsu3.a ${OBJFILES} build/addmults.o : include/su3.h src/addmults.cc ${MADAI_CPP} -c ${MADAI_CFLAGS} ${INCLUDE} src/addmults.cc -o build/addmults.o build/pq.o : include/su3.h src/pq.cc ${MADAI_CPP} -c ${MADAI_CFLAGS} ${INCLUDE} src/pq.cc -o build/pq.o build/randy.o : include/randy.h src/randy.cc ${MADAI_CPP} -c ${MADAI_CFLAGS} ${INCLUDE} src/randy.cc -o build/randy.o build/su3_misc.o : include/su3.h src/su3_misc.cc ${MADAI_CPP} -c ${MADAI_CFLAGS} ${INCLUDE} src/su3_misc.cc -o build/su3_misc.o build/tableaux.o : include/su3.h src/tableaux.cc ${MADAI_CPP} -c ${MADAI_CFLAGS} ${INCLUDE} src/tableaux.cc -o build/tableaux.o build/trajectory.o : include/su3.h src/trajectory.cc ${MADAI_CPP} -c ${MADAI_CFLAGS} ${INCLUDE} src/trajectory.cc -o build/trajectory.o clean: rm lib/*.a build/*.o
098ad48ce298e2383a9efe2e4bc93e5aa77636a4
[ "Markdown", "Python", "Makefile", "C++" ]
32
C++
scottedwardpratt/fluxtubes
ff46624277a7c0f404a870ac99c9cae75eee3c33
e48ff1796f3bea27667e68c0739dd885bebb20a1
refs/heads/master
<repo_name>zulu15/springmvc-training<file_sep>/src/test/java/com/fincasmendoza/repository/ProductDAOImplTests.java package com.fincasmendoza.repository; import static org.junit.Assert.assertEquals; import java.util.List; import org.junit.Before; import org.junit.Test; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; import com.fincasmendoza.domain.Product; import com.fincasmendoza.repository.ProductDAO; public class ProductDAOImplTests { private ApplicationContext appContext; private ProductDAO productDAO; @Before public void setUp() { appContext = new ClassPathXmlApplicationContext("classpath:test-context.xml"); productDAO = (ProductDAO) appContext.getBean("productDAO"); } @Test public void testGetProductList() { List<Product> products = productDAO.getProductList(); assertEquals(products.size(), 4, 0); } @Test public void testSaveProduct() { List<Product> products = productDAO.getProductList(); Product p = products.get(0); Double price = p.getPrice(); p.setPrice(200.12); productDAO.saveProduct(p); List<Product> updatedProducts = productDAO.getProductList(); Product p2 = updatedProducts.get(0); assertEquals(p2.getPrice(), 200.12, 0); p2.setPrice(price); productDAO.saveProduct(p2); } } <file_sep>/pom.xml <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.zulu</groupId> <artifactId>fincasmendoza</artifactId> <packaging>war</packaging> <version>0.0.1-SNAPSHOT</version> <name>fincasmendoza Maven Webapp</name> <url>http://maven.apache.org</url> <properties> <hibernate.version>5.0.1.Final</hibernate.version> <!-- wanted Hibernate version --> </properties> <dependencies> <!-- https://mvnrepository.com/artifact/org.springframework/spring-core --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-core</artifactId> <version>4.3.8.RELEASE</version> </dependency> <!-- https://mvnrepository.com/artifact/org.springframework/spring-webmvc --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>4.3.8.RELEASE</version> </dependency> <!-- https://mvnrepository.com/artifact/javax.servlet/javax.servlet-api --> <dependency> <groupId>javax.servlet</groupId> <artifactId>javax.servlet-api</artifactId> <version>4.0.0-b05</version> </dependency> <!-- https://mvnrepository.com/artifact/junit/junit --> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.8.2</version> </dependency> <!-- https://mvnrepository.com/artifact/javax.servlet/jstl --> <dependency> <groupId>javax.servlet</groupId> <artifactId>jstl</artifactId> <version>1.2</version> </dependency> <!-- https://mvnrepository.com/artifact/taglibs/standard --> <dependency> <groupId>taglibs</groupId> <artifactId>standard</artifactId> <version>1.1.2</version> </dependency> <!-- https://mvnrepository.com/artifact/javax.validation/validation-api --> <dependency> <groupId>javax.validation</groupId> <artifactId>validation-api</artifactId> <version>1.1.0.Final</version> </dependency> <!-- persistence --> <!-- https://mvnrepository.com/artifact/org.hibernate/hibernate-validator --> <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-validator</artifactId> <version>${hibernate.version}</version> </dependency> <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-core</artifactId> <version>${hibernate.version}</version> </dependency> <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-entitymanager</artifactId> <version>${hibernate.version}</version> </dependency> <dependency> <groupId>org.jboss.logging</groupId> <artifactId>jboss-logging</artifactId> <version>3.3.0.Final</version> </dependency> <!-- https://mvnrepository.com/artifact/org.slf4j/slf4j-api --> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-api</artifactId> <version>1.7.21</version> </dependency> <!-- https://mvnrepository.com/artifact/org.slf4j/slf4j-log4j12 --> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-log4j12</artifactId> <version>1.7.21</version> </dependency> <!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java --> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.38</version> </dependency> <!-- https://mvnrepository.com/artifact/org.springframework/spring-orm --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-orm</artifactId> <version>4.3.8.RELEASE</version> </dependency> </dependencies> <build> <finalName>fincasmendoza</finalName> </build> </project> <file_sep>/src/main/webapp/WEB-INF/classes/jdbc.properties jdbc.driverClassName=com.mysql.jdbc.Driver jdbc.url=jdbc:mysql://localhost:3306/gestion_inventario jdbc.username=root jdbc.password= hibernate.dialect=org.hibernate.dialect.MySQLDialect jpa.database = MYSQL hibernate.generate_statistics = true hibernate.show_sql = true jpa.showSql = true jpa.generateDdl = true<file_sep>/src/main/java/com/fincasmendoza/web/PriceIncreaseFormController.java package com.fincasmendoza.web; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.validation.Valid; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.validation.BindingResult; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import com.fincasmendoza.domain.PriceIncrease; import com.fincasmendoza.service.ProductManager; import com.fincasmendoza.service.ProductManagerImpl; @Controller @RequestMapping(value="/priceincrease.htm") public class PriceIncreaseFormController { /** Logger for this class and subclasses */ protected final Log logger = LogFactory.getLog(getClass()); @Autowired private ProductManagerImpl productManagerImpl; //@Valid permitirá validar el incremento introducido y volverá a mostrar //el formulario en caso de que éste no sea válido. @RequestMapping(method = RequestMethod.POST) public String onSubmit(@Valid PriceIncrease priceIncrease, BindingResult result) { if (result.hasErrors()) { return "priceincrease"; } int increase = priceIncrease.getPercentage(); logger.info("Increasing prices by " + increase + "%."); productManagerImpl.incrementarPrecios(increase); return "redirect:/hello.htm"; } @RequestMapping(method = RequestMethod.GET) protected PriceIncrease formBackingObject(HttpServletRequest request) throws ServletException { PriceIncrease priceIncrease = new PriceIncrease(); priceIncrease.setPercentage(15); return priceIncrease; } } <file_sep>/src/main/java/com/fincasmendoza/service/ProductManagerImpl.java package com.fincasmendoza.service; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import com.fincasmendoza.domain.Product; import com.fincasmendoza.repository.ProductDAO; @Component public class ProductManagerImpl implements ProductManager { @Autowired private ProductDAO productDAO; public void setProductDAO(ProductDAO productDAO) { this.productDAO = productDAO; } public ProductDAO getProductDAO() { return productDAO; } public void incrementarPrecios(int porcentaje) { for (Product product : productDAO.getProductList()) { double newPrice = product.getPrice() * (100 + porcentaje) / 100; product.setPrice(newPrice); productDAO.saveProduct(product); } } public List<Product> obtenerProductos() { return productDAO.getProductList(); } } <file_sep>/src/main/java/com/fincasmendoza/domain/Product.java package com.fincasmendoza.domain; import java.io.Serializable; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.Table; @Entity @Table(name="productos") public class Product implements Serializable { private static final long serialVersionUID = 1L; public Product(String description, double price) { this.description = description; this.price = price; } @Id @Column(name = "id") @GeneratedValue(strategy = GenerationType.AUTO) private int id; private String description; private double price; public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public double getPrice() { return price; } public void setPrice(double price) { this.price = price; } public void setId(int id) { this.id = id; } public int getId() { return id; } public Product() { // TODO Auto-generated constructor stub } @Override public String toString() { return "Product [description=" + description + ", price=" + price + "]"; } } <file_sep>/src/test/java/com/fincasmendoza/service/ProductManagerImplTests.java package com.fincasmendoza.service; import static org.junit.Assert.*; import java.util.ArrayList; import java.util.List; import org.junit.Before; import org.junit.Test; import com.fincasmendoza.domain.Product; //keep the bar green to keep the code clean public class ProductManagerImplTests { private ProductManagerImpl productManager; private List<Product> productos; private static final String MONITOR_DESCRIPTION = "Monitor de 4 pulgadas led smart TV"; private static final double MONITOR_PRICE = 6500; private static final String MOUSE_DESCRIPTION = "Mouse Verbatim gamer"; private static final double MOUSE_PRICE = 850; /* // será invocado previamente a cada llamada a un método de test. @Before public void setUp() throws Exception { productManager = new ProductManagerImpl(); productos = new ArrayList<Product>(); productos.add(new Product(MONITOR_DESCRIPTION, MONITOR_PRICE)); productos.add(new Product(MOUSE_DESCRIPTION, MOUSE_PRICE)); productManager.setProductList(productos); } @Test public void testGetProductsWithNoProducts() { productManager = new ProductManagerImpl(); assertNull(productManager.obtenerProductos()); } @Test public void testGetProductsWithProducts() { assertNotNull(productManager.obtenerProductos()); assertEquals(MONITOR_DESCRIPTION, productManager.obtenerProductos().get(0).getDescription()); assertEquals(MONITOR_PRICE, productManager.obtenerProductos().get(0).getPrice(),0); assertEquals(MOUSE_DESCRIPTION, productManager.obtenerProductos().get(1).getDescription()); assertEquals(MOUSE_PRICE, productManager.obtenerProductos().get(1).getPrice(),0); } */ } <file_sep>/src/main/java/com/fincasmendoza/repository/ProductDAO.java package com.fincasmendoza.repository; import java.util.List; import com.fincasmendoza.domain.Product; public interface ProductDAO { List<Product> getProductList(); int saveProduct(Product product); }
2f44292580404f3bbfb055a8fff6e0b1ef0bfafe
[ "Java", "Maven POM", "INI" ]
8
Java
zulu15/springmvc-training
e75ec1b2573645d601dd4a67588ffec3a191236a
b47f43edc9b0bad6f40d421416299f5b34f5490a
refs/heads/master
<repo_name>wolzethan/destiny-api<file_sep>/server/router/index.js module.exports = function(app) { app.use('/player', require('./routes/search')); } <file_sep>/server/modules/destiny/defaults.js module.exports = { "baseUrl" : "http://www.bungie.net/Platform/Destiny" } <file_sep>/server.js // Requiring node Modules var express = require('express'); var bodyParser = require('body-parser'); var app = express(); var request = require('request'); var router = require('./server/router')(app); var port = process.env.PORT || 4000; app.use(bodyParser.urlencoded({extended : true})); app.use(bodyParser.json()); app.listen(port); console.log("Getting stats for your Guardian on PORT: ", port); <file_sep>/server/about.md # [DESTINY-API]() ### CLASS TYPES * ClassType of 2 is Warlock * ClassType of 1 is Hunter * ClassType of 0 is Titan [FULL LIST OF API CALLS HERE]("https://www.bungie.net/platform/destiny/help/") ### IMPORTANT API CALLS HERE * /Stats/ActivityHistory/{membershipType}/{destinyMembershipId}/{characterId}/ * This returns activity history for selected characterId ### BASE url * http://www.bungie.net/Platform/Destiny/{api_info} ### INFO You need to attach a X-API-Key to the header when you make a request or you will get an error. #### WHAT WE WANT TO DO - Character Stats - KD - Previous Games - Currents Weapons - PVE KD - Weapon Stats - ELO - PVP KD and PVE KD - Different Game modes - Slack Integration - Web hooks Stats Hp Golfer - Bot that will walk you through the flow (getting activity history) - Infuse calculator - Clan Website - Aggregate Stats for the Clan (raid, trials) - Individual Stats - Clan Settings #### Functions we need - Get Character activity history - Get Character Weapon Stats #### Weapon Portion / Item Portion of API - To search for a specific InventoryItem you need to go to the endpoint - /Manifest/InventoryItem/{hash} <file_sep>/server/modules/destiny/config.js module.exports = { "apiKey" : process.env.APIKEY, "baseUrl": "http://www.bungie.net/Platform/Destiny" } <file_sep>/server/modules/destiny/index.js var request = require('request'); var EventEmitter = require('events').EventEmitter; var util = require('util'); // Config.js this is ignored in .gitignore // youll need to create one of these and include your ApiKey and // bungies base url for the api var config = require('./config'); var defaults = require('./defaults'); var DestinyApi = function() { // DESTINYAPI Inherits EventEmitter properties EventEmitter.call(this); this.weapons = require('./libs/weapons'); } // DESTINYAPI Inherits EventEmitter properties util.inherits(DestinyApi, EventEmitter); // This gets basic info from a users gamertag. // Right now this is for XBOX only. Playstation would have to be changed // to a 0. Right now this is static DestinyApi.prototype.searchPlayer = function(name) { var self = this; var options = { url : defaults.baseUrl + "/SearchDestinyPlayer/1/" + name, headers : { 'X-API-Key' : config.apiKey } } // The request module makes a GET request to bungies API using The // Options that we specified. request(options, function(err, response, body) { if(err) { throw err; } // Since DestinyApi has EventEmitter properties we can // Emit events to handle Asyncrhonous flow in NodeJS self.emit('player:found', JSON.parse(response.body)); }); } // This handles getting the players stats once we have their membershipId // You have to make the call above to get the id first. DestinyApi.prototype.getPlayerStats = function(id) { var self = this; var options = { url : defaults.baseUrl + "/1/Account/" + id, headers : { 'X-API-Key' : config.apiKey } } // The request module makes a GET request to bungies API using The // Options that we specified. request(options, function(err, response, body) { if(err) { throw err; } // Since DestinyApi has EventEmitter properties we can // Emit events to handle Asyncrhonous flow in NodeJS self.emit('player stats', JSON.parse(response.body)); }); } DestinyApi.prototype.returnCharacterFromId = function(charNum, data) { var self = this; var validVals = ['1', '2', '3']; if(validVals.indexOf(charNum) < 0) { charNum = validVals[0]; } var Chars = data.Response.data.characters; var character; for(var i = 0; i < Chars.length; i++) { if(Chars[i].characterBase.classType === parseInt(charNum)) { character = Chars[i]; } } if(character === undefined) { return false; } return character; } module.exports = new DestinyApi(); <file_sep>/server/router/routes/search.js var express = require('express'); var router = express.Router(); var Destiny = require('../../modules/destiny'); // TODO: Create route that returns basic player character data // THIS RETURNS THE PLAYER AND ACCOUNT DATA router.get('/:gamertag', function(req, res) { var gamertag = req.params.gamertag; gamertag = gamertag.replace("+", "%20"); Destiny.searchPlayer(gamertag); // Using EventEmitter to handle Asynchronous Flow Destiny.on('player:found', function(data) { Destiny.getPlayerStats(data.Response[0].membershipId); }); var count = 0; Destiny.on('player stats', function(data) { if(count === 0) { res.send(data); count++ } }); }); //TODO: return player and character history... 1, 2, 3 router.get('/:gamertag/history/:characterNum', function(req, res) { var gamertag = req.params.gamertag; gamertag = gamertag.replace("+", "%20"); var characterNum = req.params.characterNum; Destiny.searchPlayer(gamertag); var counter = 0; Destiny.on('player:found', function(data) { if(counter === 0) { var membershipId = data.Response[0].membershipId; Destiny.getPlayerStats(membershipId); counter++; } }); var count = 0; Destiny.on('player stats', function(data) { if(count === 0) { var character = Destiny.returnCharacterFromId(characterNum, data); res.send(character); count++ } }); }); module.exports = router;
0a39b53599abe4619489135845ccd6aeb4b86e1e
[ "JavaScript", "Markdown" ]
7
JavaScript
wolzethan/destiny-api
db8e788b2519a389b60b6c5891fa687dd8ec90c9
0bfdc3037ed29a97522908719e26bd1d236bcdbb
refs/heads/master
<repo_name>BidiptoRoy/Lyrics-Finder<file_sep>/app/src/main/java/com/bidiptoroy/lyricsfinderapp/MainActivity.java package com.bidiptoroy.lyricsfinderapp; import androidx.appcompat.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.TextView; import com.android.volley.Request; import com.android.volley.RequestQueue; import com.android.volley.Response; import com.android.volley.VolleyError; import com.android.volley.toolbox.JsonObjectRequest; import com.android.volley.toolbox.Volley; import org.json.JSONException; import org.json.JSONObject; public class MainActivity extends AppCompatActivity { EditText artistName , songName; Button searchbtn; TextView lyrics; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); artistName = findViewById(R.id.artistName); songName = findViewById(R.id.songName); searchbtn = findViewById(R.id.searchLyrics); lyrics = findViewById(R.id.lyrics); searchbtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { String url ="https://api.lyrics.ovh/v1/" + artistName.getText().toString() + "/" + songName.getText().toString(); url.replace(" ","%20"); RequestQueue requestQueue = Volley.newRequestQueue(MainActivity.this); JsonObjectRequest jasonObjectRequest = new JsonObjectRequest(Request.Method.GET, url, null, new Response.Listener<JSONObject>() { @Override public void onResponse(JSONObject response) { try{ lyrics.setText(response.getString("lyrics")); }catch (JSONException e){ e.getMessage(); } } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { } }); requestQueue.add(jasonObjectRequest); } }); } }
78ffa667bdff29896f1e3ad1c5702f07321b8b0f
[ "Java" ]
1
Java
BidiptoRoy/Lyrics-Finder
1f42ecbd6ac0dbc8e9d7f1a8327c68690a896d78
6d0ab22de227f7592bb74a2d7059750c9942a7c7
refs/heads/master
<file_sep>#!/usr/bin/env python3 from timeit import default_timer as timer import random import pprint def insertion_sort(a_list): t_start = timer() for index in range(1, len(a_list)): current_value = a_list[index] position = index while position > 0 and a_list[position - 1] > current_value: a_list[position] = a_list[position - 1] position = position - 1 a_list[position] = current_value t_end = timer() return t_end - t_start def shell_sort(a_list): t_start = timer() n = len(a_list) gap = n // 2 while gap > 0: for i in range(gap, n): temp = a_list[i] j = i while j >= gap and a_list[j - gap] > temp: a_list[j] = a_list[j - gap] j -= gap a_list[j] = temp gap //= 2 t_end = timer() return t_end - t_start def python_sort(a_list): t_start = timer() a_list.sort() t_end = timer() return t_end - t_start def generate_list(size): rand_list = [random.randrange(0, size + 1, 1) for i in range(size)] return rand_list def calc_average(a_list): return sum(a_list) / len(a_list) def main(): rand_lists = {"list_500": generate_list(3), "list_1000": generate_list(5), "list_10000": generate_list(10)} time_res = [] final_res = [] ########################### # Run insertion sort algo # ########################### for value in rand_lists.values(): t = insertion_sort(value) time_res.append(t) ave = calc_average(time_res) print_msg = "Insertion sort took {} seconds to run on average.".format(ave) final_res.append(print_msg) ########################### # Run shell sort algo # ########################### rand_lists = {"list_500": generate_list(3), "list_1000": generate_list(5), "list_10000": generate_list(10)} time_res.clear() for value in rand_lists.values(): t = shell_sort(value) time_res.append(t) ave = calc_average(time_res) print_msg = "Shell sort took {} seconds to run on average.".format(ave) final_res.append(print_msg) ########################### # Run python sort algo # ########################### rand_lists = {"list_500": generate_list(3), "list_1000": generate_list(5), "list_10000": generate_list(10)} time_res.clear() for value in rand_lists.values(): t = python_sort(value) time_res.append(t) ave = calc_average(time_res) print_msg = "Python sort took {} seconds to run on average.".format(ave) final_res.append(print_msg) pprint.pprint(final_res) if __name__ == '__main__': main() <file_sep>#!/usr/bin/env python3 from timeit import default_timer as timer import random import pprint def sequential_search(a_list, item): pos = 0 found = False t_start = timer() while pos < len(a_list) and not found: if a_list[pos] == item: found = True else: pos = pos + 1 t_end = timer() t_elapsed = t_end - t_start result = (found, t_elapsed) return result def ordered_sequential_search(ordered_list, item): pos = 0 found = False t_start = timer() while pos < len(ordered_list) and not found: if ordered_list[pos] == item: found = True else: pos = pos + 1 t_end = timer() t_elapsed = t_end - t_start result = (found, t_elapsed) return result def binary_search_iterative(ordered_list, item): first = 0 last = len(ordered_list) - 1 found = False t_start = timer() while first <= last and not found: midpoint = (first + last) // 2 if ordered_list[midpoint] == item: found = True else: if item < ordered_list[midpoint]: last = midpoint - 1 else: first = midpoint + 1 t_end = timer() t_elapsed = t_end - t_start result = (found, t_elapsed) return result def binary_search_recursive(ordered_list, item): t_start = timer() if len(ordered_list) == 0: t_end = timer() t_elapsed = t_end - t_start result = (False, t_elapsed) return result else: midpoint = len(ordered_list) // 2 if ordered_list[midpoint] == item: t_end = timer() t_elapsed = t_end - t_start result = (True, t_elapsed) return result else: if item < ordered_list[midpoint]: return binary_search_recursive(ordered_list[:midpoint], item) else: return binary_search_recursive(ordered_list[midpoint + 1:], item) def list_generator(size): main_list = [] for i in range(100): inner_list = [random.randrange(0, size + 1, 1) for i in range(size)] main_list.append(inner_list) return main_list def calc_average(times): total = sum(times) return total / len(times) def order_list(a_dict): for value in a_dict.values(): for lst in value: lst.sort() return a_dict def main(): rand_lists = {"list_500": list_generator(500), "list_1000": list_generator(1000), "list_10000": list_generator(10000)} ############################## # Run sequential search algo # ############################## num_to_find = -1 ss_result = [] final_results = [] for value in rand_lists.values(): # Value contain a list of lists size x for lst in value: # Run algo res = sequential_search(lst, num_to_find) # add duration to result_list ss_result.append(res[1]) ave = calc_average(ss_result) print_msg = "Sequential Search took {} seconds to run on average.".format(ave) final_results.append(print_msg) # Order lists rand_lists = order_list(rand_lists) ###################################### # Run ordered sequential search algo # ###################################### ss_result.clear() for value in rand_lists.values(): # Value contain a list of lists size x for lst in value: # Run algo res = ordered_sequential_search(lst, num_to_find) # add duration to result_list ss_result.append(res[1]) ave = calc_average(ss_result) print_msg = "Ordered Sequential Search took {} seconds to run on average.".format(ave) final_results.append(print_msg) #################################### # Run binary_search_iterative algo # #################################### ss_result.clear() for value in rand_lists.values(): # Value contain a list of lists size x for lst in value: # Run algo res = binary_search_iterative(lst, num_to_find) # add duration to result_list ss_result.append(res[1]) ave = calc_average(ss_result) print_msg = "Binary Search Iterative took {} seconds to run on average.".format(ave) final_results.append(print_msg) #################################### # Run binary_search_recursive algo # #################################### ss_result.clear() for value in rand_lists.values(): # Value contain a list of lists size x for lst in value: # Run algo res = binary_search_recursive(lst, num_to_find) # add duration to result_list ss_result.append(res[1]) ave = calc_average(ss_result) print_msg = "Binary Search Recursive took {} seconds to run on average.".format(ave) final_results.append(print_msg) pprint.pprint(final_results) if __name__ == '__main__': main()
4df665caeab9ef06af8b562d324a0e404dbcf434
[ "Python" ]
2
Python
CalicheCas/IS211_Assignment4
616699654bd35df51fa373147c9074d42bc5b801
647223edca9ffd79dedcbdf02e9c43410416d86d
refs/heads/master
<repo_name>6Sinnet/PyjamaRun<file_sep>/PyjamaRun/app/src/main/java/sjttesinnet/pyjamarun/ReadTagActivity.java package sjttesinnet.pyjamarun; import android.app.Activity; import android.app.ActivityManager; import android.app.AlertDialog; import android.app.PendingIntent; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.content.IntentFilter; import android.content.IntentFilter.MalformedMimeTypeException; import android.content.SharedPreferences; import android.graphics.Color; import android.nfc.NdefMessage; import android.nfc.NdefRecord; import android.nfc.NfcAdapter; import android.os.Bundle; import android.os.Parcelable; import android.util.Log; import android.view.View; import android.widget.ArrayAdapter; import android.widget.ListView; import android.widget.TextView; import android.widget.Toast; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Stack; import android.content.SharedPreferences; public class ReadTagActivity extends Activity { private static final String TAG = ReadTagActivity.class.getSimpleName(); private static final String ALARM_SETTINGS = "AlarmSettings"; // NFC-related variables private NfcAdapter _nfcAdapter; private InverseAdapter<String> adapter; private PendingIntent _nfcPendingIntent; IntentFilter[] _readTagFilters; private SharedPreferences settings; private ListView listView; String[] colors = {"E88080","9AE880", "80C4E8", "D180E8", "EBE86C"}; int[] colorIndex = {0,1,2,3,4}; private TextView _textViewData; private Stack<String> tagOrder; private List<String> availableTags; private boolean alarmSounding; private List<String> listOrder; SharedPreferences prefs; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_readtag); settings = getSharedPreferences(ALARM_SETTINGS, 0); // Get ListView object from xml listView = (ListView) findViewById(R.id.tagOrder); //Set up available tags, should be done in settings activity availableTags = new ArrayList<>(); prefs = getSharedPreferences("MyPrefs", MODE_PRIVATE); String csvList = prefs.getString("myList", ""); if(csvList!=null) { String[] items = csvList.split(","); for (int i = 0; i < items.length; i++) { if (!items[i].equals("")) availableTags.add(items[i]); } } String csv2List = prefs.getString("myList", ""); listOrder = new ArrayList<>(); if(csv2List!=null) { String[] items2 = csv2List.split(","); for (int i = 0; i < items2.length; i++) { if (!items2[i].equals("")) listOrder.add(items2[i]); } } _textViewData = (TextView) findViewById(R.id.textData); _nfcAdapter = NfcAdapter.getDefaultAdapter(this); loadSettings(); // Defined Array values to show in ListView String[] values = new String[] { "List is empty" }; if(tagOrder != null){ adapter = new InverseAdapter<String>(this, R.layout.simple_list_item, android.R.id.text1, tagOrder); listView.setAdapter(adapter); // ask the system to wait before setting the background color of the favorite item so that // the ListView has time to load the items. //really bad code, but acceptable for presentation final int DELAY_IN_MILLISECONDS = 20; listView.postDelayed(new Runnable() { @Override public void run() { updateColor(); } }, DELAY_IN_MILLISECONDS); } if (_nfcAdapter == null) { Toast.makeText(this, "Your device does not support NFC. Cannot run this demo.", Toast.LENGTH_LONG).show(); finish(); return; } checkNfcEnabled(); //Toast.makeText(this, "Scant the following tag:" + randomTag, Toast.LENGTH_LONG).show(); _nfcPendingIntent = PendingIntent.getActivity(this, 0, new Intent(this, getClass()).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP), 0); IntentFilter ndefDetected = new IntentFilter(NfcAdapter.ACTION_NDEF_DISCOVERED); try { ndefDetected.addDataType("application/com.elsinga.sample.nfc"); } catch (MalformedMimeTypeException e) { throw new RuntimeException("Could not add MIME type.", e); } _readTagFilters = new IntentFilter[]{ndefDetected}; } @Override protected void onResume() { super.onResume(); checkNfcEnabled(); if (getIntent().getAction() != null) { onNewIntent(getIntent()); } _nfcAdapter.enableForegroundDispatch(this, _nfcPendingIntent, _readTagFilters, null); } @Override protected void onPause() { super.onPause(); //saveTagOrderSettings(); _nfcAdapter.disableForegroundDispatch(this); } @Override protected void onDestroy() { super.onDestroy(); saveTagOrderSettings(); } private TextView getViewByPosition(int pos, ListView listView) { final int firstListItemPosition = listView.getFirstVisiblePosition(); final int lastListItemPosition = firstListItemPosition + listView.getChildCount() - 1; if (pos < firstListItemPosition || pos > lastListItemPosition ) { return (TextView) listView.getAdapter().getView(pos, null, listView); } else { final int childIndex = pos - firstListItemPosition; return (TextView) listView.getChildAt(childIndex); } } @Override protected void onNewIntent(Intent intent) { if (intent.getAction().equals(NfcAdapter.ACTION_NDEF_DISCOVERED)) { if (alarmSounding) { NdefMessage[] msgs = getNdefMessagesFromIntent(intent); String payload = new String(msgs[0].getRecords()[0].getPayload()); if (tagOrder.peek().equals(payload)) { tagOrder.pop(); adapter.notifyDataSetChanged(); updateColor(); Toast.makeText(this, "Good!", Toast.LENGTH_SHORT).show(); if (tagOrder.empty()) { _textViewData.setText("All tags scanned. Good job!"); stopService(new Intent(this, MusicService.class)); saveAlarmFinishedSettings(); } else { _textViewData.setText("Scan tag: " + tagOrder.peek()); } } else { Toast.makeText(this, "Wrong tag!", Toast.LENGTH_SHORT).show(); } } else { _textViewData.setText("Oops! No alarm currently sounding."); /* Toast.makeText(this, "Oops! No alarm currently sounding.", Toast.LENGTH_SHORT).show(); Intent myIntent = new Intent(this, ConfigureActivity.class); startActivity(myIntent); */ } // confirmDisplayedContentOverwrite(msgs[0]); } else if (intent.getAction().equals(NfcAdapter.ACTION_TAG_DISCOVERED)) { Toast.makeText(this, "This NFC tag has no NDEF data.", Toast.LENGTH_LONG).show(); } } NdefMessage[] getNdefMessagesFromIntent(Intent intent) { // Parse the intent NdefMessage[] msgs = null; String action = intent.getAction(); if (action.equals(NfcAdapter.ACTION_TAG_DISCOVERED) || action.equals(NfcAdapter.ACTION_NDEF_DISCOVERED)) { Parcelable[] rawMsgs = intent.getParcelableArrayExtra(NfcAdapter.EXTRA_NDEF_MESSAGES); if (rawMsgs != null) { msgs = new NdefMessage[rawMsgs.length]; for (int i = 0; i < rawMsgs.length; i++) { msgs[i] = (NdefMessage) rawMsgs[i]; } } else { // Unknown tag type byte[] empty = new byte[]{}; NdefRecord record = new NdefRecord(NdefRecord.TNF_UNKNOWN, empty, empty, empty); NdefMessage msg = new NdefMessage(new NdefRecord[]{record}); msgs = new NdefMessage[]{msg}; } } else { Log.e(TAG, "Unknown intent."); finish(); } return msgs; } private void generateRandomOrderOfTags() { tagOrder = new Stack<String>(); Collections.shuffle(availableTags); tagOrder.addAll(availableTags); } private void saveAlarmFinishedSettings() { alarmSounding = false; SharedPreferences.Editor editor = settings.edit(); editor.putBoolean("alarmActive", false); editor.putBoolean("alarmSounding", alarmSounding); editor.putString("tagOrder", ""); editor.commit(); } private void saveTagOrderSettings() { if (alarmSounding) { SharedPreferences.Editor editor = settings.edit(); StringBuilder sb = new StringBuilder(); while (!tagOrder.isEmpty()) { sb.append(tagOrder.pop()); sb.append("#"); } editor.putString("tagOrder", sb.toString()); editor.commit(); } } private boolean restoreTagOrder() { String[] tags = settings.getString("tagOrder", "").split("#"); tagOrder = new Stack<String>(); for (String s : tags) { if (!s.equals("")) { tagOrder.push(s); } } return !tagOrder.isEmpty(); } private void loadSettings() { alarmSounding = settings.getBoolean("alarmSounding", false); if (alarmSounding) { if (!restoreTagOrder()) { //alarm starts for the first time generateRandomOrderOfTags(); } _textViewData.setText("Scan tag: " + tagOrder.peek()); } } private void updateColor(){ String colList = prefs.getString("colourList", ""); ArrayList<String> colourList = new ArrayList<>(); if(colList!=null) { String[] items = colList.split(","); colourList = new ArrayList<>(); for (int i = 0; i < items.length; i++) { if(!items[i].equals("")){ colourList.add(items[i]); } } } for (int i = 0; i < tagOrder.size(); i++){ StringBuilder sb = new StringBuilder(); double opacity = (double)((tagOrder.size() - i))/(double)tagOrder.size(); sb.append("#"); sb.append(Integer.toHexString((int) (opacity * 255))); if (opacity == 0) sb.append(0); String actualColor = colourList.get(listOrder.indexOf(adapter.getItem(i))); sb.append(actualColor); getViewByPosition(i, listView).setBackgroundColor(Color.parseColor(sb.toString())); } } private void checkNfcEnabled() { Boolean nfcEnabled = _nfcAdapter.isEnabled(); if (!nfcEnabled) { // new AlertDialog.Builder(ReadTagActivity.this).setTitle(getString(R.string.text_warning_nfc_is_off)) // .setMessage(getString(R.string.text_turn_on_nfc)).setCancelable(false) // .setPositiveButton(getString(R.string.text_update_settings), new DialogInterface.OnClickListener() // { // @Override // public void onClick(DialogInterface dialog, int id) // { // startActivity(new Intent(android.provider.Settings.ACTION_WIRELESS_SETTINGS)); // } // }).create().show(); } } } <file_sep>/log.md # Initial commit 2015-04-08 Vi har valt tre vyer varav en är en konfigurationsvy som inte ska användas dagligen för att hålla applikationen simpel och användarvänlig. # 2015-04-07 Vi har kommit igång med både designen och programeringen. Vi har valt att hålla designen så enkel som möjligt med endast tre vyer (varav en är en settings-vy som man inte ser så ofta). I alarm-vyn så har vi valt att identiera taggarna både med siffror, färger och mönster. Allt för att det ska passa så många som möjligt, färgblinda m.m. Vi försöker skapa en igenkänning mellan alla vyer. De ska gå i samma designspråk så man känner igen sig inom appen. Inställningsvyn ska vara så absolut enkel som möjligt för att man snabbt ska komma igång med appen. Vi kommer använda oss av välkända gester och designmönster (ex. svep åt höger för att ta bort, plustecken längst ner till höger för att lägga till). <file_sep>/PyjamaRun/app/src/main/java/sjttesinnet/pyjamarun/AlarmActivity.java package sjttesinnet.pyjamarun; import android.app.ActivityManager; import android.app.AlarmManager; import android.app.PendingIntent; import android.content.ComponentName; import android.content.Context; import android.content.Intent; import android.content.ServiceConnection; import android.content.SharedPreferences; import android.nfc.NfcAdapter; import android.os.Bundle; import android.os.IBinder; import android.support.v7.app.ActionBarActivity; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.Button; import android.widget.TimePicker; import android.widget.Toast; import android.view.View.OnClickListener; import java.util.ArrayList; import java.util.Calendar; public class AlarmActivity extends ActionBarActivity { private NfcAdapter mNfcAdapter; private static final String ALARM_SETTINGS = "AlarmSettings"; AlarmManager am; private Intent musicIntent; PendingIntent sender; private long delay; TimePicker tp; Button onoff; SharedPreferences prefs; ArrayList<String> availableTags; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_alarm); am = (AlarmManager) getSystemService(ALARM_SERVICE); musicIntent = new Intent(this, MusicService.class); sender = PendingIntent.getService(this, 0, musicIntent, 0); mNfcAdapter = NfcAdapter.getDefaultAdapter(this); if (!mNfcAdapter.isEnabled()) { Toast.makeText(this, "NCF is not enabled, please enable NFC.", Toast.LENGTH_LONG).show(); } else { Toast.makeText(this, "NFC is enabled.", Toast.LENGTH_LONG).show(); } onoff = (Button) findViewById(R.id.onoff); availableTags = new ArrayList<>(); prefs = getSharedPreferences("MyPrefs", MODE_PRIVATE); String csvList = prefs.getString("myList", ""); if(csvList!=null) { String[] items = csvList.split(","); for (int i = 0; i < items.length; i++) { if (!items[i].equals("")) availableTags.add(items[i]); } } tp = (TimePicker) findViewById(R.id.timePicker); tp.setIs24HourView(true); restoreAlarmSettings(); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.menu_alarm, menu); //final Calendar c = Calendar.getInstance(); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); //noinspection SimplifiableIfStatement if (id == R.id.action_settings) { Intent myIntent = new Intent(AlarmActivity.this, ConfigureActivity.class); startActivity(myIntent); } return super.onOptionsItemSelected(item); } public void Onoff(View view) { boolean alarmActive = tp.isEnabled(); if (availableTags.size() == 0) { Toast.makeText(this, "You need to register tags before setting the alarm!", Toast.LENGTH_SHORT).show(); } else { onoff.setSelected(!onoff.isSelected()); tp.setEnabled(!alarmActive); if (tp.isEnabled()) tp.setAlpha((float)1); else tp.setAlpha((float)0.3); if (alarmActive) onoff.setText(R.string.on); else onoff.setText(R.string.off); if (alarmActive) { Toast.makeText(this, "Alarm created", Toast.LENGTH_SHORT).show(); setTimer(); am.setExact(AlarmManager.RTC_WAKEUP, delay, sender); } else { am.cancel(sender); Toast.makeText(this, "Alarm killed", Toast.LENGTH_SHORT).show(); } saveAlarmSettings(); } } /* If the alarm is set greater than the current time, it will trigger during the current day, if however it is set to a time less than the current one, it will trigger the next day. */ private void setTimer() { Calendar c = Calendar.getInstance(); int currH = c.get(Calendar.HOUR_OF_DAY); int currM = c.get(Calendar.MINUTE); int setH = tp.getCurrentHour(); int setM = tp.getCurrentMinute(); long diff = 60000 * ((setH * 60 + setM) - (currH * 60 + currM)); if (diff >= 0) { delay = diff + System.currentTimeMillis(); //set delay to actual difference between set and current time } else { delay = 24 * 3600000 + diff + System.currentTimeMillis(); //set delay to (24 hours - difference) } } private void saveAlarmSettings() { // We need an Editor object to make preference changes. // Save settings from alarm SharedPreferences settings = getSharedPreferences(ALARM_SETTINGS, 0); SharedPreferences.Editor editor = settings.edit(); editor.putBoolean("alarmActive", !tp.isEnabled()); editor.putInt("H", tp.getCurrentHour()); editor.putInt("M", tp.getCurrentMinute()); // Commit the edits! editor.commit(); } private void restoreAlarmSettings() { // Restore alarm SharedPreferences settings = getSharedPreferences(ALARM_SETTINGS, 0); boolean active = settings.getBoolean("alarmActive", false); int hour = settings.getInt("H", 7); int min = settings.getInt("M", 0); tp.setEnabled(!active); onoff.setSelected(active); if (active) onoff.setText(R.string.on); else onoff.setText(R.string.off); tp.setCurrentHour(hour); tp.setCurrentMinute(min); } @Override protected void onResume() { availableTags = new ArrayList<>(); String csvList = prefs.getString("myList", ""); if(csvList!=null) { String[] items = csvList.split(","); for (int i = 0; i < items.length; i++) { if (!items[i].equals("")) availableTags.add(items[i]); } } super.onResume(); restoreAlarmSettings(); } } <file_sep>/PyjamaRun/app/src/main/java/Handlers/Alarm.java package Handlers; import android.text.format.Time; /** * Created by Johannes on 2015-04-13. * * http://developer.android.com/reference/android/app/AlarmManager.html * http://developer.android.com/training/scheduling/alarms.html Guide till hur man anvander klassen ovanfor */ public class Alarm { //Set alarm public void set(Time time){ } //Fires when alarm goes off public void ring(){ } } <file_sep>/PyjamaRun/app/src/main/java/Handlers/NFCHandler.java package Handlers; /** * Created by Johannes on 2015-04-13. */ public class NFCHandler { public void read(){ } //Fires when an NFC tag is scanned public void scan(){ } //Register a new NFC tag public void register(){ } } <file_sep>/README.md # Pyjama Run Authors: <NAME>, <NAME>, <NAME>, <NAME> - Vi revolutionerar alarmbranschen med vårt unika sätt att få folk ur sängen. - Utan en enda snooze går du från zombie till klarvaken på nolltid. - Ger dig en morgonpromenad innan första koppen kaffe.
7e0f8440eae9a4ed6dacd98918161ab1041dd1a3
[ "Markdown", "Java" ]
6
Java
6Sinnet/PyjamaRun
a94286b97821d39388eee0e4a169a41878b93a8b
459a44dd9e23a15674bb7a95eb5a399da318af2a
refs/heads/master
<file_sep>#!/bin/bash host=`basename $0` logonuser=root function help { echo -e "\nUsage: $0 [-u|-h] \n\t -u : Connect as User ($USER) insted as root\n" } for i in $* ; do case "$1" in -u) if [ -n "$2" -a "${2:0:1}" != "-" ] ; then logonuser=$2 else logonuser=$USER fi ;; -h|--help) help; exit ;; -*) param="$param $1" ;; *) true ;; esac shift done if [ $(ssh-add -L | grep $USER | wc -l) == 0 ] then ssh-add fi echo "ssh -ACX $param $logonuser@$host" ssh -ACX $param $logonuser@$host
79ae53bf284059972dca499be6dd12874d74d4c8
[ "Shell" ]
1
Shell
firemind/dotfiles
acda9dad32d6a97888d5e85dbe80fc27fcc28a64
9369ae2e149dbce03898032839a43c795c3660bf
refs/heads/main
<repo_name>fernandodealcantara/trabalhosSC<file_sep>/cifra-aes-modos-ecb-ctr/main.py from random import randint # usado apenas para gerar chave de 16 bytes com valores aleatorios entre 0x0 e 0xFF from hashlib import sha1 # usado apenas para gerar o hash from PIL import Image # usado para tratar imagem .bmp from os import system, name # limpar terminal ################################################################################################ # TABELAS S_BOX, SBOX_INVERSA E RCON # tabela de subtituicao com todas as combinacoes de 0 a 255 util para geracao de subchaves e aes s_box = ( 0x63, 0x7C, 0x77, 0x7B, 0xF2, 0x6B, 0x6F, 0xC5, 0x30, 0x01, 0x67, 0x2B, 0xFE, 0xD7, 0xAB, 0x76, 0xCA, 0x82, 0xC9, 0x7D, 0xFA, 0x59, 0x47, 0xF0, 0xAD, 0xD4, 0xA2, 0xAF, 0x9C, 0xA4, 0x72, 0xC0, 0xB7, 0xFD, 0x93, 0x26, 0x36, 0x3F, 0xF7, 0xCC, 0x34, 0xA5, 0xE5, 0xF1, 0x71, 0xD8, 0x31, 0x15, 0x04, 0xC7, 0x23, 0xC3, 0x18, 0x96, 0x05, 0x9A, 0x07, 0x12, 0x80, 0xE2, 0xEB, 0x27, 0xB2, 0x75, 0x09, 0x83, 0x2C, 0x1A, 0x1B, 0x6E, 0x5A, 0xA0, 0x52, 0x3B, 0xD6, 0xB3, 0x29, 0xE3, 0x2F, 0x84, 0x53, 0xD1, 0x00, 0xED, 0x20, 0xFC, 0xB1, 0x5B, 0x6A, 0xCB, 0xBE, 0x39, 0x4A, 0x4C, 0x58, 0xCF, 0xD0, 0xEF, 0xAA, 0xFB, 0x43, 0x4D, 0x33, 0x85, 0x45, 0xF9, 0x02, 0x7F, 0x50, 0x3C, 0x9F, 0xA8, 0x51, 0xA3, 0x40, 0x8F, 0x92, 0x9D, 0x38, 0xF5, 0xBC, 0xB6, 0xDA, 0x21, 0x10, 0xFF, 0xF3, 0xD2, 0xCD, 0x0C, 0x13, 0xEC, 0x5F, 0x97, 0x44, 0x17, 0xC4, 0xA7, 0x7E, 0x3D, 0x64, 0x5D, 0x19, 0x73, 0x60, 0x81, 0x4F, 0xDC, 0x22, 0x2A, 0x90, 0x88, 0x46, 0xEE, 0xB8, 0x14, 0xDE, 0x5E, 0x0B, 0xDB, 0xE0, 0x32, 0x3A, 0x0A, 0x49, 0x06, 0x24, 0x5C, 0xC2, 0xD3, 0xAC, 0x62, 0x91, 0x95, 0xE4, 0x79, 0xE7, 0xC8, 0x37, 0x6D, 0x8D, 0xD5, 0x4E, 0xA9, 0x6C, 0x56, 0xF4, 0xEA, 0x65, 0x7A, 0xAE, 0x08, 0xBA, 0x78, 0x25, 0x2E, 0x1C, 0xA6, 0xB4, 0xC6, 0xE8, 0xDD, 0x74, 0x1F, 0x4B, 0xBD, 0x8B, 0x8A, 0x70, 0x3E, 0xB5, 0x66, 0x48, 0x03, 0xF6, 0x0E, 0x61, 0x35, 0x57, 0xB9, 0x86, 0xC1, 0x1D, 0x9E, 0xE1, 0xF8, 0x98, 0x11, 0x69, 0xD9, 0x8E, 0x94, 0x9B, 0x1E, 0x87, 0xE9, 0xCE, 0x55, 0x28, 0xDF, 0x8C, 0xA1, 0x89, 0x0D, 0xBF, 0xE6, 0x42, 0x68, 0x41, 0x99, 0x2D, 0x0F, 0xB0, 0x54, 0xBB, 0x16, ) # tabela inversa de subtituicao com todas as combinacoes de 0 a 255 util para aes s_box_inversa = ( 0x52, 0x09, 0x6A, 0xD5, 0x30, 0x36, 0xA5, 0x38, 0xBF, 0x40, 0xA3, 0x9E, 0x81, 0xF3, 0xD7, 0xFB, 0x7C, 0xE3, 0x39, 0x82, 0x9B, 0x2F, 0xFF, 0x87, 0x34, 0x8E, 0x43, 0x44, 0xC4, 0xDE, 0xE9, 0xCB, 0x54, 0x7B, 0x94, 0x32, 0xA6, 0xC2, 0x23, 0x3D, 0xEE, 0x4C, 0x95, 0x0B, 0x42, 0xFA, 0xC3, 0x4E, 0x08, 0x2E, 0xA1, 0x66, 0x28, 0xD9, 0x24, 0xB2, 0x76, 0x5B, 0xA2, 0x49, 0x6D, 0x8B, 0xD1, 0x25, 0x72, 0xF8, 0xF6, 0x64, 0x86, 0x68, 0x98, 0x16, 0xD4, 0xA4, 0x5C, 0xCC, 0x5D, 0x65, 0xB6, 0x92, 0x6C, 0x70, 0x48, 0x50, 0xFD, 0xED, 0xB9, 0xDA, 0x5E, 0x15, 0x46, 0x57, 0xA7, 0x8D, 0x9D, 0x84, 0x90, 0xD8, 0xAB, 0x00, 0x8C, 0xBC, 0xD3, 0x0A, 0xF7, 0xE4, 0x58, 0x05, 0xB8, 0xB3, 0x45, 0x06, 0xD0, 0x2C, 0x1E, 0x8F, 0xCA, 0x3F, 0x0F, 0x02, 0xC1, 0xAF, 0xBD, 0x03, 0x01, 0x13, 0x8A, 0x6B, 0x3A, 0x91, 0x11, 0x41, 0x4F, 0x67, 0xDC, 0xEA, 0x97, 0xF2, 0xCF, 0xCE, 0xF0, 0xB4, 0xE6, 0x73, 0x96, 0xAC, 0x74, 0x22, 0xE7, 0xAD, 0x35, 0x85, 0xE2, 0xF9, 0x37, 0xE8, 0x1C, 0x75, 0xDF, 0x6E, 0x47, 0xF1, 0x1A, 0x71, 0x1D, 0x29, 0xC5, 0x89, 0x6F, 0xB7, 0x62, 0x0E, 0xAA, 0x18, 0xBE, 0x1B, 0xFC, 0x56, 0x3E, 0x4B, 0xC6, 0xD2, 0x79, 0x20, 0x9A, 0xDB, 0xC0, 0xFE, 0x78, 0xCD, 0x5A, 0xF4, 0x1F, 0xDD, 0xA8, 0x33, 0x88, 0x07, 0xC7, 0x31, 0xB1, 0x12, 0x10, 0x59, 0x27, 0x80, 0xEC, 0x5F, 0x60, 0x51, 0x7F, 0xA9, 0x19, 0xB5, 0x4A, 0x0D, 0x2D, 0xE5, 0x7A, 0x9F, 0x93, 0xC9, 0x9C, 0xEF, 0xA0, 0xE0, 0x3B, 0x4D, 0xAE, 0x2A, 0xF5, 0xB0, 0xC8, 0xEB, 0xBB, 0x3C, 0x83, 0x53, 0x99, 0x61, 0x17, 0x2B, 0x04, 0x7E, 0xBA, 0x77, 0xD6, 0x26, 0xE1, 0x69, 0x14, 0x63, 0x55, 0x21, 0x0C, 0x7D, ) # tabela rcon util para gerar subchaves r_con = ( 0x00, 0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80, 0x1b, 0x36, 0x6c, 0xd8, 0xab, 0x4d, 0x9a, 0x2f, 0x5e, 0xbc, 0x63, 0xc6, 0x97, 0x35, 0x6a, 0xd4, 0xb3, 0x7d, 0xfa, 0xef, 0xc5, 0x91, 0x39, 0x72, 0xe4, 0xd3, 0xbd, 0x61, 0xc2, 0x9f, 0x25, 0x4a, 0x94, 0x33, 0x66, 0xcc, 0x83, 0x1d, 0x3a, 0x74, 0xe8, 0xcb, 0x8d, 0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80, 0x1b, 0x36, 0x6c, 0xd8, 0xab, 0x4d, 0x9a, 0x2f, 0x5e, 0xbc, 0x63, 0xc6, 0x97, 0x35, 0x6a, 0xd4, 0xb3, 0x7d, 0xfa, 0xef, 0xc5, 0x91, 0x39, 0x72, 0xe4, 0xd3, 0xbd, 0x61, 0xc2, 0x9f, 0x25, 0x4a, 0x94, 0x33, 0x66, 0xcc, 0x83, 0x1d, 0x3a, 0x74, 0xe8, 0xcb, 0x8d, 0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80, 0x1b, 0x36, 0x6c, 0xd8, 0xab, 0x4d, 0x9a, 0x2f, 0x5e, 0xbc, 0x63, 0xc6, 0x97, 0x35, 0x6a, 0xd4, 0xb3, 0x7d, 0xfa, 0xef, 0xc5, 0x91, 0x39, 0x72, 0xe4, 0xd3, 0xbd, 0x61, 0xc2, 0x9f, 0x25, 0x4a, 0x94, 0x33, 0x66, 0xcc, 0x83, 0x1d, 0x3a, 0x74, 0xe8, 0xcb, 0x8d, 0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80, 0x1b, 0x36, 0x6c, 0xd8, 0xab, 0x4d, 0x9a, 0x2f, 0x5e, 0xbc, 0x63, 0xc6, 0x97, 0x35, 0x6a, 0xd4, 0xb3, 0x7d, 0xfa, 0xef, 0xc5, 0x91, 0x39, 0x72, 0xe4, 0xd3, 0xbd, 0x61, 0xc2, 0x9f, 0x25, 0x4a, 0x94, 0x33, 0x66, 0xcc, 0x83, 0x1d, 0x3a, 0x74, 0xe8, 0xcb, 0x8d, 0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80, 0x1b, 0x36, 0x6c, 0xd8, 0xab, 0x4d, 0x9a, 0x2f, 0x5e, 0xbc, 0x63, 0xc6, 0x97, 0x35, 0x6a, 0xd4, 0xb3, 0x7d, 0xfa, 0xef, 0xc5, 0x91, 0x39, 0x72, 0xe4, 0xd3, 0xbd, 0x61, 0xc2, 0x9f, 0x25, 0x4a, 0x94, 0x33, 0x66, 0xcc, 0x83, 0x1d, 0x3a, 0x74, 0xe8, 0xcb, 0x8d ) ################################################################################################ ################################################################################################ # FUNCOES UTEIS TANTO PARA GERAR CHAVES, AES E MODOS DE OPERACAO # funcao para imprimir valores no formato hexadecimal -> usada para debug hexValues = lambda mensagem: [hex(m) for m in mensagem] # funcao que rotaciona a palavra n vezes rotacionar = lambda palavra, n: palavra[n:] + palavra[0:n] # funcao que efetua um xor entre cada byte da palavra com a tabela de round constants aka r_con palavra_xor_rcon = lambda palavra, pos: [palavra[0] ^ r_con[pos%len(r_con)]] + palavra[1:] # funcao que efetua xor entre duas palavras palavra_xor_outra_palavra = lambda palavra, outra_palavra: [i^j for i, j in zip(palavra, outra_palavra)] # funcao que nivela uma lista que tem sublista exemplo uma lista [[1], [2]] vira [1, 2] flatten = lambda lista: [item for sublista in lista for item in sublista] # transpõe a matriz (é uma lista só que referenciada aqui como matriz) pegar_matriz_transposta = lambda matriz: flatten([[matriz[(4*j)+i] for j in range(4)] for i in range(4)]) ################################################################################################ # FUNCOES AES E DE MODOS DE OPERACAO # seleciona as 4 subchaves da rodada (pega 4 subchaves de 4 bytes e concatena em uma de 16 bytes) pegar_chave_da_rodada = lambda subchaves, rodada: pegar_matriz_transposta(flatten(subchaves[rodada*4:(rodada*4)+4])) # funcao que adiciona a chave para o estado (em aes, adicao eh sempre a operacao xor) add_round_key = lambda estado, chave_da_rodada: [estado[i] ^ chave_da_rodada[i] for i in range(16)] # funcao que substitui os valores do estado utilizando a tabela de substituicao s_box sub_bytes = lambda palavra: [s_box[pos] for pos in palavra] # funcao que substitui os valores do estado utilizando a tabela de substituicao inversa sub_bytes_inversa = lambda estado: [s_box_inversa[pos] for pos in estado] # funcao que rotaciona as linhas da matriz de estado shift_rows = lambda estado: flatten([rotacionar(estado[i*4:(i*4)+4], i) for i in range(4)]) # funcao que rotaciona as linhas da matriz de estado inversamente a funcao shift_rows shift_rows_inverso = lambda estado: flatten([rotacionar(estado[i*4:(i*4)+4], -i) for i in range(4)]) # funcao que realiza a operacao de multiplicacao -> galois multiplication def gm(a, b): p = 0 hiBitSet = 0 for _ in range(8): if b & 1 == 1: p ^= a hiBitSet = a & 0x80 a <<= 1 if hiBitSet == 0x80: a ^= 0x1b b >>= 1 return p % 256 # funcao que incrementa um array de bytes -> utilizada no modo ctr def incrementar(contador): for i in reversed(range(len(contador))): if contador[i] == 0xFF: contador[i] = 0 else: contador[i] += 1 break return contador # funcao responsavel por gerar as subchaves que serao utilizadas pelo aes passo -> add_round_key(). def gerar_subchaves(chave128bits, rodadas=10): palavras_geradas_por_passo = 4 subchaves = [chave128bits[i:i+4] for i in range(0, 16, 4)] for i in range(4, (4*rodadas)+4): if i % 4 == 0: nova_palavra = rotacionar(subchaves[i-1], 1) nova_palavra = sub_bytes(nova_palavra) # aka sub_bytes nova_palavra = palavra_xor_rcon(nova_palavra, i//4) nova_palavra = palavra_xor_outra_palavra(nova_palavra, subchaves[i-palavras_geradas_por_passo]) subchaves.append(nova_palavra) return subchaves # funcao que cria uma nova coluna dependendo do valor de vm 'valores da matriz' # se vm = [1, 1, 2, 3] (gera matriz normal) realiza a operacao mix column normal # se vm = [0x09, 0x0d, 0x0e, 0x0b] (gera matriz inversa) realiza a operacao mix column inversa def mix_column(coluna, vm): nova_coluna = [0] * 4 nova_coluna[0] = gm(coluna[0], vm[2]) ^ gm(coluna[1], vm[3]) ^ gm(coluna[2], vm[1]) ^ gm(coluna[3], vm[0]) nova_coluna[1] = gm(coluna[0], vm[0]) ^ gm(coluna[1], vm[2]) ^ gm(coluna[2], vm[3]) ^ gm(coluna[3], vm[1]) nova_coluna[2] = gm(coluna[0], vm[1]) ^ gm(coluna[1], vm[0]) ^ gm(coluna[2], vm[2]) ^ gm(coluna[3], vm[3]) nova_coluna[3] = gm(coluna[0], vm[3]) ^ gm(coluna[1], vm[1]) ^ gm(coluna[2], vm[0]) ^ gm(coluna[3], vm[2]) return nova_coluna # funcao que embaralha a matriz de estado def mix_columns(estado, valores_matriz): novo_estado = pegar_matriz_transposta(estado) # transpor facilita as outras operacoes for i in range(4): novo_estado[i*4:(i*4)+4] = mix_column(novo_estado[i*4:(i*4)+4], valores_matriz) return pegar_matriz_transposta(novo_estado) # transpõe novamente para voltar ao normal # funcao aes que executa o processo cifrar def aes_cifrar(mensagem, subchaves, rodadas): valores_para_gerar_matriz_para_mix_columns = [1, 1, 2, 3] estado = mensagem chave_da_rodada = pegar_chave_da_rodada(subchaves, 0) estado = add_round_key(estado, chave_da_rodada) for rodada in range(1, rodadas): estado = sub_bytes(estado) estado = shift_rows(estado) estado = mix_columns(estado, valores_para_gerar_matriz_para_mix_columns) chave_da_rodada = pegar_chave_da_rodada(subchaves, rodada) estado = add_round_key(estado, chave_da_rodada) estado = sub_bytes(estado) estado = shift_rows(estado) chave_da_rodada = pegar_chave_da_rodada(subchaves, rodadas) estado = add_round_key(estado, chave_da_rodada) return estado # funcao aes que executa o processo decifrar def aes_decifrar(mensagem, subchaves, rodadas): valores_para_gerar_matriz_para_mix_columns_inversa = [0x09, 0x0d, 0x0e, 0x0b] estado = mensagem chave_da_rodada = pegar_chave_da_rodada(subchaves, rodadas) estado = add_round_key(estado, chave_da_rodada) estado = shift_rows_inverso(estado) estado = sub_bytes_inversa(estado) for rodada in range(rodadas-1, 0, -1): chave_da_rodada = pegar_chave_da_rodada(subchaves, rodada) estado = add_round_key(estado, chave_da_rodada) estado = mix_columns(estado, valores_para_gerar_matriz_para_mix_columns_inversa) estado = shift_rows_inverso(estado) estado = sub_bytes_inversa(estado) chave_da_rodada = pegar_chave_da_rodada(subchaves, 0) estado = add_round_key(estado, chave_da_rodada) return estado # funcao que realiza o modo ecb - electronic codebook def ecb(chave, blocos, rodadas, modo): subchaves = gerar_subchaves(chave, rodadas) blocos_gerados = [] for bloco in blocos: bloco = pegar_matriz_transposta(bloco) if modo == 'cifrar': novo_bloco = pegar_matriz_transposta(aes_cifrar(bloco, subchaves, rodadas)) elif modo == 'decifrar': novo_bloco = pegar_matriz_transposta(aes_decifrar(bloco, subchaves, rodadas)) blocos_gerados.append(novo_bloco) return blocos_gerados # retorna os blocos cifrados ou decifrados, depende do valor de modo = cifrar | decifrar # funcao que realiza o modo ctr - counter def ctr(chave, blocos, rodadas): subchaves = gerar_subchaves(chave, rodadas) contador = [0x0] * 16 blocos_gerados = [] for bloco in blocos: res = pegar_matriz_transposta(aes_cifrar(pegar_matriz_transposta(contador.copy()), subchaves, rodadas)) novo_bloco = palavra_xor_outra_palavra(res, bloco) blocos_gerados.append(novo_bloco) contador = incrementar(contador.copy()) return blocos_gerados # # funcao pega os bytes de image data entre os marcadores de start of scan 0xffda e o de final do arquivo 0xffd9 # e transforma em blocos de 16 bytes (que serao usados no aes) # retorna um dict com os blocos e informacoes do marcador start of scan def criar_blocos_jpg(lista_de_bytes): sos_marker = {} for i in range(len(lista_de_bytes)-1): if lista_de_bytes[i] == 0xff and lista_de_bytes[i+1] == 0xda: sos_marker['começo'] = i+1 sos_marker['tamanho'] = (lista_de_bytes[i+2]*256) + lista_de_bytes[i+3] break # consideramos apenas o primeiro marcador sos encontrado inicio_dados_bloco = sos_marker['começo'] + sos_marker['tamanho'] + 1 fim_dados_bloco = -2 # em um arquivo jpg normal, os 2 ultimos bytes são ff d9 que indicam o fim do jpg image_data = lista_de_bytes[inicio_dados_bloco:fim_dados_bloco] for i in range(0, len(image_data)-1): if image_data[i] == 0xff and image_data[i+1] == 0x00: image_data[i+1] = None image_data = [value for value in image_data if value != None] # retira o valor 0x0 que acompanha o ff -> 0xff 0x0 == 0xff em jpg blocos = [] for i in range(0, len(image_data), 16): novo_bloco = image_data[i:i+16] if len(novo_bloco) < 16: preencher_restante = [0x0] * (16-len(novo_bloco)) # padding novo_bloco += preencher_restante blocos.append(novo_bloco.copy()) sos_marker['blocos'] = blocos.copy() return sos_marker # adiciona o valor 0x0 para os bytes com valor 0xff novamente 0xff -> 0xff 0x0 def substituir_bytes_jpg(parte_modificada): copia_parte_modificada = parte_modificada.copy() i = 0 while (True): if copia_parte_modificada[i] == 0xff: copia_parte_modificada.insert(i+1, 0x0) i += 1 if i >= len(copia_parte_modificada): break return copia_parte_modificada def criar_blocos_bmp(imgname): img = Image.open(imgname) imgInBytes = list(img.tobytes()) blocos = [] resto = [] for i in range(0, len(imgInBytes), 16): novo_bloco = imgInBytes[i:i+16] if len(novo_bloco) < 16: resto = novo_bloco break blocos.append(novo_bloco.copy()) return (blocos, resto, img.size) def montar_imagem(img, resto, tam, name): d = img + resto d = bytes(d) im = Image.frombytes(mode = "RGB", size = tam, data= d) im.show() im.save(name + '.bmp') return d def main(): try: while (True): opcao = input('Modo de execucao\n1 - para cifrar\n2 - para decifrar\nOpcao: ') modo = input('Modo de operacao\n1 - ecb\n2 - ctr\nOpcao: ') if opcao not in ['1', '2'] or modo not in ['1', '2']: print('Opcao ou modo invalido.') continue nome_imagem_entrada = str(input('Insira o nome da imagem com extensao[.bmp ou .jpg] em que sera aplicado o algoritmo: ')) rodadas = int(input('Quantidade de rodadas: ')) chave = input('Informe a chave (16 bytes separados por espaço) ou gere automaticamente (pressione enter): ').split() if not rodadas > 0 and not rodadas < 250: print('Excedeu o valor de rodada maximo (250)') continue if '.jpg' in nome_imagem_entrada: with open(nome_imagem_entrada, mode='rb') as original_file: original_image = list(original_file.read()) # dict sos marker que contem blocos a ser cifrados, inicio do marcador e tamanho do marcador -> jpg sos_marker_info = criar_blocos_jpg(original_image.copy()) # cabecalho da nova imagem nova_imagem = original_image.copy()[0:sos_marker_info['começo'] + sos_marker_info['tamanho'] + 1] blocos = sos_marker_info['blocos'].copy() # blocos de 16 bytes jpg elif '.bmp' in nome_imagem_entrada: blocos, resto, size = criar_blocos_bmp(nome_imagem_entrada) else: print('Extensão da imagem não identificada.') continue if len(chave) == 16: chave = [int(value, 16) for value in chave] else: chave = [randint(0, 255) for _ in range(16)] print('Chave:', *hexValues(chave)) print('Realizando operações. Aguarde.') nome_imagem_saida = nome_imagem_entrada[0:-4] + '-' if opcao == '1': nome_imagem_saida += 'cifrar-' else: nome_imagem_saida += 'decifrar-' if modo == '1': nome_imagem_saida += 'ecb-' else: nome_imagem_saida += 'ctr-' nome_imagem_saida += str(rodadas) blocos_gerados = [] # blocos modificados if opcao == '1': # cifrar if modo == '1': blocos_gerados = ecb(chave, blocos, rodadas, 'cifrar') elif modo == '2': blocos_gerados = ctr(chave, blocos, rodadas) elif opcao == '2': # decifrar if modo == '1': blocos_gerados = ecb(chave, blocos, rodadas, 'decifrar') elif modo == '2': blocos_gerados = ctr(chave, blocos, rodadas) bloco_unico = flatten(blocos_gerados) # junta todos os blocos de 16 bytes modificados em apenas uma if '.jpg' in nome_imagem_entrada: nova_imagem += substituir_bytes_jpg(bloco_unico) # montando jpg nova_imagem += [0xff, 0xd9] # adiciona o marcador do final da imagem out_file_image = open(f'{nome_imagem_saida}.jpg', mode='wb') # salvando jpg out_file_image.write(bytes(nova_imagem)) out_file_image.close() else: nova_imagem = montar_imagem(bloco_unico, resto, size, nome_imagem_saida) result_hash = sha1(bytes(nova_imagem)).hexdigest() out_file_infos_execution = open(f'chave e hash.txt', mode='w') # salvando hash em txt out_file_infos_execution.write('Chave:' + ' '.join(hexValues(chave)) + '\n') # chave out_file_infos_execution.write('Hash:' + result_hash) # hash out_file_infos_execution.close() print('Chave e hash salvos em: chave e hash.txt ') print(f'Imagem resultante salva em: {nome_imagem_saida}') print("O hash hexadecimal gerado:", result_hash) print('Finalizado!') break except: print('Algo deu errado!') if __name__ == '__main__': while (True): main() continuar = input('Continuar execução [s/n]?') if continuar not in 'sim': break system('cls' if name == 'nt' else 'clear')<file_sep>/cifra-vigenere/readme.txt Trabalho de Segurança Computacional Feito por <NAME> - 190125586 <NAME> – 190084197 Como usar: Primeira forma: De dois cliques no executável main.exe dentro da pasta vigenere ou no atalho do executavel na pasta raiz vigenere.lnk dessa forma a interação é feita por meio de inputs que o programa pedirá atraves do cmd/powershell. Inputs: Selecione o que fazer: 1 - Encriptar mensagem 2 - Decriptar mensagem 3 - Atacar Any key - Cancelar 1 e 2 encriptar e decriptar: Mensagem: Chave: 3 atacar: Utilizar frequencias em português [s/n]? s Tamanhos de chaves encontradas (em ordem de possivel melhor tamanho): Escolha uma começando do índice 0 ou aperte enter: Mostrar resultado [s/n]? ===================================================================================================================== <file_sep>/cifra-aes-modos-ecb-ctr/README.md TRABALHO 2 - AES - MODOS DE OPERAÇÃO ECB E CTR - CIFRAR E DECIFRAR IMAGEM 190125586 e 190084197 Considerações: O formato de imagem que deve ser utilizado é .bmp A disponibilidade do formato .jpg nesse trabalho está apenas como resultado de uma implementação para .jpg que não resultou no esperado. COMO USAR: Execute o main.exe no diretorio aes-executavel ou o main.py - caso utilize o codigo fonte instale a biblioteca pillow necessaria: Pillow==8.3.2 Passo 1: Escolha o modo de execução 1 - para cifrar 2 - para decifrar Passo 2: Escolha o modo de operação 1 - ecb 2 - ctr Passo 3: Insira o nome da imagem com extensao[.bmp ou .jpg] em que sera aplicado o algoritmo: (Como citado acima, utilize .bmp para obter os resultados de interesse) Passo 4: Quantidade de rodadas: (0 < rodadas < 250) Passo 5: Informe a chave (16 bytes separados por espaço) ou gere automaticamente (pressione enter): Passo 6: Após passar pelas entradas acima aguarde a execução do algoritmo.<file_sep>/cifra-vigenere/main.py alfabeto = 'abcdefghijklmnopqrstuvwxyz' frequencias_ingles = [0.08167, 0.01492, 0.02782, 0.04253, 0.12702, 0.02228, 0.02015, 0.06094, 0.06966, 0.00153, 0.00772, 0.04025, 0.02406, 0.06749, 0.07507, 0.01929, 0.00095, 0.05987, 0.06327, 0.09056, 0.02758, 0.00978, 0.02360, 0.00150, 0.01974, 0.00074] frequencias_portugues = [0.1463, 0.0104, 0.0388, 0.0499, 0.1257, 0.0102, 0.0130, 0.0128, 0.0618, 0.040, 0.002, 0.0278, 0.0474, 0.0505, 0.1073, 0.0252, 0.0120, 0.0653, 0.0781, 0.0434, 0.0463, 0.0167, 0.001, 0.0021, 0.001, 0.0047] utilizar_frequencias_portugues = False # função decoradora responsavel por lidar com caracteres que não podem ser cifrados def considerar_apenas_alfabeto(func): def inner(mensagem_para_tratar, chave=None): mensagem_final = [None] * len(mensagem_para_tratar) mensagem = '' for indice in range(len(mensagem_para_tratar)): if mensagem_para_tratar[indice] in alfabeto + alfabeto.upper(): mensagem += mensagem_para_tratar[indice] else: mensagem_final[indice] = mensagem_para_tratar[indice] if chave: nova_mensagem = func(mensagem, chave) for caractere in nova_mensagem: mensagem_final[mensagem_final.index(None)] = caractere return ''.join(mensagem_final) else: return func(mensagem.lower()) return inner # funcao responsavel por encriptar a mensagem @considerar_apenas_alfabeto def encriptar(mensagem, chave): mensagem_em_lista = [mensagem[i: i + len(chave)] for i in range(0, len(mensagem), len(chave))] encriptado = '' for pedaço in mensagem_em_lista: i = 0 for letra in pedaço: indice = (alfabeto.index(letra.lower()) + alfabeto.index(chave[i].lower())) % len(alfabeto) encriptado += alfabeto[indice] if letra.islower() else alfabeto[indice].upper() i += 1 return encriptado # funcao responsavel por decriptar a mensagem @considerar_apenas_alfabeto def decriptar(mensagem, chave): mensagem_em_lista = [mensagem[i: i + len(chave)] for i in range(0, len(mensagem), len(chave))] decriptado = '' for pedaço in mensagem_em_lista: i = 0 for letra in pedaço: indice = (alfabeto.index(letra.lower()) - alfabeto.index(chave[i].lower())) % len(alfabeto) decriptado += alfabeto[indice] if letra.islower() else alfabeto[indice].upper() i += 1 return decriptado # funcao responsavel de realizar o calculo de indice de coincidencia def pegar_indice_coincidencia(sequencia): N = float(len(sequencia)) soma_frequencia = 0.0 for letra in alfabeto: soma_frequencia += sequencia.count(letra) * (sequencia.count(letra) - 1) indice_coincidencia = soma_frequencia/ (N*(N-1)) return indice_coincidencia # funcao responsavel de escolher o tamanho mais provavel da chave def pegar_tamanho_chave(mensagem, tamanho: int = 20): tabela_ic = [] tamanho_maximo_chave = tamanho for tamanho_suposto in range(tamanho_maximo_chave): soma_ic = 0.0 for i in range(tamanho_suposto): sequencia = '' for j in range(0, len(mensagem[i:]), tamanho_suposto): sequencia += mensagem[i+j] if (len(sequencia) > 1): soma_ic += pegar_indice_coincidencia(sequencia) ic_medio = soma_ic / tamanho_suposto if not tamanho_suposto == 0 else 0.0 tabela_ic.append(ic_medio) tabela_ic_ordenada = sorted(tabela_ic, reverse=True) melhores_suposições = list(map(lambda valor: tabela_ic.index(valor), tabela_ic_ordenada)) melhores_suposições = [suposição for suposição in list(dict.fromkeys(melhores_suposições)) if suposição != 0] return melhores_suposições[:5] # funcao responsavel de escolher a melhor letra baseado em analise de frequencia def analise_frequencia(sequencia): todos_qui_quadrados = [0] * 26 for i in range(26): sequencia_deslocada = [alfabeto[(alfabeto.index(letra.lower())-i)%26] for letra in sequencia] frequencias_ocorrencias_letras = [float(sequencia_deslocada.count(letra))/float(len(sequencia)) for letra in alfabeto] soma_qui_quadrado = 0.0 frequencia = frequencias_portugues if utilizar_frequencias_portugues else frequencias_ingles for j in range(26): soma_qui_quadrado+=((frequencias_ocorrencias_letras[j] - float(frequencia[j]))**2)/float(frequencia[j]) todos_qui_quadrados[i] = soma_qui_quadrado letra_com_menor_qui_quadrado = todos_qui_quadrados.index(min(todos_qui_quadrados)) for qui_quadrado in sorted(todos_qui_quadrados)[:5]: print(f'({alfabeto[todos_qui_quadrados.index(qui_quadrado)]}:{qui_quadrado:.2f})', end = ' ') letra = input('Escolha uma letra ou aperte enter: ') return letra if len(letra) == 1 and letra in alfabeto else alfabeto[letra_com_menor_qui_quadrado] # funcao responsavel por 'montar' a chave final def pegar_chave(mensagem, tamanho_chave): chave = '' for i in range(tamanho_chave): sequencia = '' for j in range(0, len(mensagem[i:]), tamanho_chave): sequencia += mensagem[i+j] chave += analise_frequencia(sequencia) return chave # funcao que executa os passos de ataque para achar uma chave @considerar_apenas_alfabeto def atacar(mensagem): tamanho_chave = pegar_tamanho_chave(mensagem) if tamanho_chave == 0: return None else: print('Tamanhos de chaves encontradas (em ordem de possivel melhor tamanho): ', *[{i: tamanho_chave[i]} for i in range(len(tamanho_chave))]) tamanho_escolhido = input('Escolha uma começando do índice 0 ou aperte enter: ', ) tamanho_escolhido = int(tamanho_escolhido)%len(tamanho_chave) if tamanho_escolhido.isnumeric() else 0 chave = pegar_chave(mensagem, tamanho_chave[tamanho_escolhido]) return chave # DAQUI PARA BAIXO É APENAS INPUT DE DADOS DO USUARIO, # NADA RELACIONADO COM AS FUNÇÕES DA CIFRA def formatar_chave(chave): return ''.join([char for char in chave if char.lower() in alfabeto]) def selecionar_modo(): print('Selecione o que fazer:') print('1 - Encriptar mensagem') print('2 - Decriptar mensagem') print('3 - Atacar') print('Any key - Cancelar') modo = input('Opção: ') if modo == '1': return 'cifrar' elif modo == '2': return 'decifrar' elif modo == '3': return 'atacar' return None def main(): global utilizar_frequencias_portugues try: resultado = '' modo = selecionar_modo() if modo == 'cifrar': mensagem = input('Mensagem: ') chave = formatar_chave(input('Chave: ')) resultado = encriptar(mensagem, chave) elif modo == 'decifrar': mensagem = input('Mensagem: ') chave = formatar_chave(input('Chave: ')) resultado = decriptar(mensagem, chave) elif modo == 'atacar': mensagem = input('Mensagem: ') utilizar_opcao = input('Utilizar frequencias em português [s/n]? ') if utilizar_opcao.lower() in 'simyes' and len(utilizar_opcao) > 0: utilizar_frequencias_portugues = True chave = atacar(mensagem) if chave: resultado = decriptar(mensagem, chave) filename = 'saida.txt' if len(resultado): f = open(filename, "w") f.write(resultado) f.close() print(f'Resultado salvo em {filename}') mostrar = input('Mostrar resultado [s/n]? ') if mostrar.lower() in 'simyes' and len(mostrar) > 0: print(resultado) input('Pressione para encerrar.') except: pass if __name__ == '__main__': main()
b17d833c083aaab3b9aba38088c18c96ad592ab8
[ "Markdown", "Python", "Text" ]
4
Python
fernandodealcantara/trabalhosSC
850c58bc53facb2fd6b26a97843f10360f25a64a
511a66a1c0b7c4a26f1be1dfeb9707d0749921d0
refs/heads/master
<repo_name>yuzhiliu/learning<file_sep>/jupyter-tips-and-tricks/README.md # Jupyter Notebok Tips and Tricks A few (hopefully) useful tips and tricks to using the Jupyter Notebook to its full potential. This is not, in any way, an exhaustive demostration of the Jupyter notebook. Quite a bit of the information is given verbally as I generally give a demonstration of these notebooks. If you have any suggestions, edits, or corrections, please open an issue or let me know some other way. Best of luck! <file_sep>/data_challenges/mbrdna_data_challenge/MBRDNA_VIDA_InterviewChallenge/scatter_matrix.py import pandas as pd import numpy as np from pandas.tools.plotting import scatter_matrix df = pd.read_csv(r'features.csv', header = None) scatter_matrix(df, alpha=0.5, figsize=(12, 12), diagonal='kde') <file_sep>/computer_science/cs_fundamentals/simple_problems/is_power_three.py #! /usr/bin/env python def isPowerOfThree(n): """ :type n: int :rtype: bool """ is_pow_three = False for i in range(1,n): if 3**i == n: is_pow_three = True break return is_pow_three print isPowerOfThree(9) <file_sep>/data_challenges/mbrdna_data_challenge/MB_DataChallenge/MBRDNA_MLPUX_InterviewChallenge/README.md # main.py contains the solution with a description, however please check out the ipython notebook for more details. <file_sep>/data_challenges/mbrdna_data_challenge/MBRDNA_MLPUX_InterviewChallenge/make_data_set.py #!/usr/bin/env python import random as rand def make_gaus_data(): lines = [] for i in range(0,500): x_0 = rand.gauss(1,0.1) y_0 = rand.gauss(0,0.1) x_1 = rand.gauss(-1,0.1) y_1 = rand.gauss(0,0.1) data = str(x_0)+','+str(y_0)+':0' lines.append(data) data = str(x_1)+','+str(y_1)+':1' lines.append(data) return lines # Assume that data is in four clusters, and that we give the algorithm the # centroid of the cluster the data belongs to def make_clustered_data(): lines = [] for i in range(0,500): d_0 = '.256,.632:0' d_1 = '-0.1,-.2622:1' lines.append(d_0) lines.append(d_1) return lines gaus_data = make_gaus_data() centroid_data = make_clustered_data() rand.shuffle(centroid_data) with open('clustered_data.txt','w') as out_file: for line in centroid_data: out_file.write(line+'\n') <file_sep>/statistics/resources/bayesian_inference_statistical_programming/ExamplesFromChapters/Chapter2/ABtesting.py """ This is an example of using Bayesian A/B testing """ import pymc as pm # these two quantities are unknown to us. true_p_A = 0.05 true_p_B = 0.04 # notice the unequal sample sizes -- no problem in Bayesian analysis. N_A = 1500 N_B = 1000 # generate data observations_A = pm.rbernoulli(true_p_A, N_A) observations_B = pm.rbernoulli(true_p_B, N_B) # set up the pymc model. Again assume Uniform priors for p_A and p_B p_A = pm.Uniform("p_A", 0, 1) p_B = pm.Uniform("p_B", 0, 1) # define the deterministic delta function. This is our unknown of interest. @pm.deterministic def delta(p_A=p_A, p_B=p_B): return p_A - p_B # set of observations, in this case we have two observation datasets. obs_A = pm.Bernoulli("obs_A", p_A, value=observations_A, observed=True) obs_B = pm.Bernoulli("obs_B", p_B, value=observations_B, observed=True) # to be explained in chapter 3. mcmc = pm.MCMC([p_A, p_B, delta, obs_A, obs_B]) mcmc.sample(20000, 1000) <file_sep>/data_challenges/mbrdna_data_challenge/MBRDNA_MLPUX_InterviewChallenge/main.py import matplotlib.pyplot as plt import mnbayes as classifier import numpy as np import random as rand # Notes # Naive Bayes will overfit if the data is collinear (nerd-speak for linearly # related). For multicollinear data, we may be able to use linear regression and # obtain the varience from the data to compare things that are not correllated. DEBUG_VISUALIZATION = False classifier.reset() def predict(input): # #Debug the debug visualization # return 0 if input[0] < .25 else 1 return classifier.predict(input) def train(input, output): classifier.train(input, output) # Data Exploration def get_feature_arrays(filename): val1 = [] val2 = [] with open(filename,'r') as in_file: for line in in_file.readlines(): values = line.split(',') (data,label) = values[1].split(':') val1.append(values[0]) val2.append(data) data_1 = np.array(val1) data_2 = np.array(val2) return (data_1,data_2) print "loading training data:" (data_1,data_2) = get_feature_arrays('SQUASHED') if DEBUG_VISUALIZATION: plt.scatter(data_1,data_2) plt.show() # # # Edit everything above here ####################################### # # Plumbing below here PROBLEM = "SQUASHED" print "Reading input" file_stream = open(PROBLEM, 'r') full_text = file_stream.read(); train_set = [] test_set = [] lines = full_text.split("\n") for line in lines: if line: input_output = line.split(":") input = input_output[0].split(",") input = map(lambda x : float(x), input) output = float(input_output[1]) example_dest = test_set if rand.randint(0, 1) == 1 else train_set example_dest.append((input, output)) print "Training..." for x, y in train_set: train(x, y) # train([x for x, y in train_set], [y for x, y in train_set]) print "Predicting..." correct = 0 for i in xrange(len(train_set)): if int(predict(train_set[i][0]) + .5) == train_set[i][1]: correct += 1 print "Train:", str(100 - 100.0 * correct / len(train_set)) + "% error" correct = 0 for i in xrange(len(test_set)): if int(predict(test_set[i][0]) + .5) == test_set[i][1]: correct += 1 print "Test:", str(100 - 100.0 * correct / len(test_set)) + "% error" if DEBUG_VISUALIZATION: print "Drawing...\n\n" # Draw the color background grid GRID_MAX = 1.2 GRID_MIN = -.2 GRID_DELTA = .02 GRID_MAX += GRID_DELTA grid_x, grid_y = np.meshgrid(np.arange(GRID_MIN, GRID_MAX, GRID_DELTA), np.arange(GRID_MIN, GRID_MAX, GRID_DELTA)) colors = np.zeros((len(grid_x), len(grid_y))) for x in xrange(len(grid_x)): for y in xrange(len(grid_y)): colors[x][y] = predict([grid_x[x][y], grid_y[x][y]]) cdict = {'red': ((0.0, 1.0, 1.0), (1.0, 0.5, 0.5)), 'green': ((0.0, 0.5, 0.5), (1.0, 0.5, 0.5)), 'blue': ((0.0, 0.5, 0.5), (1.0, 1.0, 1.0))} plt.register_cmap(name='muted_rdbl', data=cdict) plt.pcolormesh(grid_x, grid_y, colors, cmap='muted_rdbl') # Scatter plot of examples input = [u for u, v in test_set] output = np.array([v for u, v, in test_set]) x = np.array([u[0] for u in input]) y = np.array([u[1] for u in input]) colors = ['r', 'b'] color_values = [colors[int(c) % len(colors)] for c in output] plt.scatter(x, y, color=color_values) plt.show() <file_sep>/statistics/resources/bayesian_inference_statistical_programming/requirements.txt ipython>=2.0 matplotlib>=1.2.1 numpy>=1.7.1 pymc==2.3.4 pyzmq>=13.1.0 scipy>=0.12.0 tornado>=3.0.2 wsgiref>=0.1.2 praw>=2.0.0 jinja2 <file_sep>/statistics/resources/bayesian_inference_statistical_programming/ExamplesFromChapters/Chapter3/ClusteringWithGaussians.py import numpy as np import pymc as pm data = np.loadtxt("../../Chapter3_MCMC/data/mixture_data.csv", delimiter=",") p = pm.Uniform("p", 0, 1) assignment = pm.Categorical("assignment", [p, 1 - p], size=data.shape[0]) taus = 1.0 / pm.Uniform("stds", 0, 100, size=2) ** 2 # notice the size! centers = pm.Normal("centers", [150, 150], [0.001, 0.001], size=2) """ The below deterministic functions map a assingment, in this case 0 or 1, to a set of parameters, located in the (1,2) arrays `taus` and `centers.` """ @pm.deterministic def center_i(assignment=assignment, centers=centers): return centers[assignment] @pm.deterministic def tau_i(assignment=assignment, taus=taus): return taus[assignment] # and to combine it with the observations: observations = pm.Normal("obs", center_i, tau_i, value=data, observed=True) # below we create a model class model = pm.Model([p, assignment, taus, centers]) map_ = pm.MAP(model) map_.fit() mcmc = pm.MCMC(model) mcmc.sample(100000, 50000) <file_sep>/computer_science/cs_fundamentals/simple_problems/nim_game.py #!/usr/bin/env python # NIM # You are playing the following Nim Game with your friend: There is a heap of # stones on the table, each time one of you take turns to remove 1 to 3 stones. # The one who removes the last stone will be the winner. You will take the first # turn to remove the stones. # # Both of you are very clever and have optimal strategies for the game. Write a # function to determine whether you can win the game given the number of stones in # the heap. # # For example, if there are 4 stones in the heap, then you will never win the # game: no matter 1, 2, or 3 stones you remove, the last stone will always be # removed by your friend. # # Hint: # # If there are 5 stones in the heap, could you figure out a way to remove the # stones such that you will always be the winner? Credits: Special thanks to # @jianchao.li.fighter for adding this problem and creating all test cases. # # Subscribe to see which companies asked this question class Solution(object): def canWinNim(self, n): """ :type n: int :rtype: bool, False = lose, True = win """ if n % == 4: return False else: return True ## Testing s = Solution() s.canWinNim(10) <file_sep>/analytics/numpy_tutorial_notes/README.md # Numpy and Plotting Tutorial This notebook follows along with the course here: http://www.scipy-lectures.org/ And eventually the course here: http://www.scipy-lectures.org/intro/matplotlib/matplotlib.html#introduction <file_sep>/computer_science/cs_fundamentals/simple_problems/count_1.py #!/usr/bin/env python def count_ones(n): """ :type n: int :rtype: int """ if n < 0: return if n % 1 > 0: return # Brute Force import re number_of_ones = 0 for i in range(1,n+1): my_str = str(i) for char in my_str: if char == '1': number_of_ones += 1 return number_of_ones print count_ones(3184191) <file_sep>/computer_science/cs_fundamentals/simple_problems/find_unduplicated.py #!/usr/bin/env python class Solution(object): def singleNumber(self, nums): """ :type nums: List[int] :rtype: int """ final_map = {} missing_number = 0 for num in nums: if num not in final_map: final_map[num] = 1 else: final_map[num] += 1 return sorted(final_map,key=final_map.get)[0] s = Solution() test_set = [17,12,5,-6,12,4,17,-5,2,-3,2,4,5,16,-3,-4,15,15,-4,-5,-6] print s.singleNumber(test_set) <file_sep>/statistics/simple_problems/simulate_bobo.py #!/usr/bin/env python import random n_amoeba = 1 def reproduce(n): ''' Given a population of n ameobas, returns the number of offspring, with each amoeba having the following chances to produce offspring: 0: 0.25 1: 0.25 2: 0.5 ''' new_population = 0 for i in range(0,n): rand_int = random.randint(1,4) if rand_int == 2: new_population += 1 if rand_int > 2: new_population += 2 return new_population def simulate_bobo(population): ''' Given an initial population of amoebas (all named bobo), count the number of generations it takes for bobo's lineage to die off. ''' n_amoeba = population number_of_generations = 0 while n_amoeba > 0: n_amoeba = reproduce(n_amoeba) number_of_generations+=1 if number_of_generations == 30: break; return number_of_generations print "simulating bobo" number_of_generations = simulate_bobo(1) lives_forever = 0 dies_tragically = 0 number_of_trials = 0 tenth_trial = False prev_frac = 0 while(True): if simulate_bobo(1) == 30: lives_forever += 1 else: dies_tragically +=1 fraction_lives = float(dies_tragically)/(lives_forever+dies_tragically) number_of_trials += 1 if number_of_trials == 10: prev_frac = fraction_lives elif number_of_trials > 10: if abs(fraction_lives-prev_frac) < 0.001: print "the fraction which lives:",fraction_lives,"found after",number_of_trials break else: prev_frac = fraction_lives <file_sep>/statistics/resources/bayesian_inference_statistical_programming/ExamplesFromChapters/Chapter2/FreqOfCheaters.py import pymc as pm p = pm.Uniform("freq_cheating", 0, 1) @pm.deterministic def p_skewed(p=p): return 0.5 * p + 0.25 yes_responses = pm.Binomial( "number_cheaters", 100, p_skewed, value=35, observed=True) model = pm.Model([yes_responses, p_skewed, p]) # To Be Explained in Chapter 3! mcmc = pm.MCMC(model) mcmc.sample(50000, 25000) <file_sep>/data_challenges/mbrdna_data_challenge/MB_DataChallenge/README.md # This repository contains the solutions to the two data challenges for the MBRDNA interview <file_sep>/data_challenges/mbrdna_data_challenge/MB_DataChallenge/MBRDNA_MLPUX_InterviewChallenge/mnbayes.py ugooki1 = {} fuscat1 = {} Chri1 = 1 Chri2 = 1.0 def predict(ii2): ii2 = {'spo': ((int((ii2[0] * 100.0)) * 1000000.0) + int((ii2[1] * 100.0)))} ugooki2 = [] fuscat2 = sum(ugooki1.itervalues()) for jjdi1 in ugooki1: Chri4 = (ugooki1[jjdi1] / fuscat2) for fuscat3 in ii2: if ((fuscat3 in fuscat1) and (ii2[fuscat3] in fuscat1[fuscat3]) and (jjdi1 in fuscat1[fuscat3][ii2[fuscat3]])): Chri4 *= (fuscat1[fuscat3][ii2[fuscat3]][jjdi1] / ugooki1[jjdi1]) else: Chri4 *= (0.01 / fuscat2) ugooki2.append((jjdi1, Chri4)) ugooki2 = sorted(ugooki2, key=(lambda ormow1: (1 - ormow1[1]))) jjdi3 = sum(map((lambda Chri3: Chri3[1]), ugooki2)) ugooki2 = map((lambda fuscat5: ((fuscat5[0] * fuscat5[1]) / jjdi3)), ugooki2) ugooki2 = sum(ugooki2) return ugooki2 def train(ii2, jjdi4): global Chri1 ii2 = {'spo': ((int((ii2[0] * 100.0)) * 1000000.0) + int((ii2[1] * 100.0)))} for jjdi5 in ii2: if (not (jjdi5 in fuscat1)): fuscat1[jjdi5] = {} if (not (ii2[jjdi5] in fuscat1[jjdi5])): fuscat1[jjdi5][ii2[jjdi5]] = {} if (not (jjdi4 in fuscat1[jjdi5][ii2[jjdi5]])): fuscat1[jjdi5][ii2[jjdi5]][jjdi4] = 0.0 fuscat1[jjdi5][ii2[jjdi5]][jjdi4] += Chri1 if (not (jjdi4 in ugooki1)): ugooki1[jjdi4] = 0.0 ugooki1[jjdi4] += Chri1 Chri1 = (Chri1 * Chri2) def reset(ormow2=1.0): global Chri1 global Chri2 global ugooki1 global fuscat1 ugooki1 = {} fuscat1 = {} Chri1 = 1 Chri2 = ormow2 if (__name__ == '__main__'): train([1, 1], 1) train([0, 0], 2) print predict([1, 1]) <file_sep>/machine_learning/gradient_descent/data_generator/README.md # General Idea - Use the data generator module to create data sets which can be fit with linear models. # Data Generator Spec 1. API - generate.py - --relation f(x1,x2) = g(x3,x4): creates a set of data conforming exactly to this distribution - --fuzz (x1,numpy.dist(x1,vals)) (x2,numpy.dist...) ...: fuzz the data randomly according to the given distribution - --n number: number of rows to generate 2. Generates a file which conforms to the given parameters from left to right, x1...xN <file_sep>/statistics/resources/bayesian_inference_statistical_programming/ExamplesFromChapters/Chapter1/SMS_behaviour.py import pymc as pm import numpy as np count_data = np.loadtxt("../../Chapter1_Introduction/data/txtdata.csv") n_count_data = len(count_data) alpha = 1.0 / count_data.mean() # recall count_data is # the variable that holds our txt counts lambda_1 = pm.Exponential("lambda_1", alpha) lambda_2 = pm.Exponential("lambda_2", alpha) tau = pm.DiscreteUniform("tau", lower=0, upper=n_count_data) @pm.deterministic def lambda_(tau=tau, lambda_1=lambda_1, lambda_2=lambda_2): out = np.zeros(n_count_data) out[:tau] = lambda_1 # lambda before tau is lambda1 out[tau:] = lambda_2 # lambda after tau is lambda2 return out observation = pm.Poisson("obs", lambda_, value=count_data, observed=True) model = pm.Model([observation, lambda_1, lambda_2, tau]) mcmc = pm.MCMC(model) mcmc.sample(100000, 50000, 1) <file_sep>/visualization/notebooks/dstone_matplot_lib_demo/README.md # This area contains work done by <NAME>, not myself. <file_sep>/visualization/notebooks/dstone_matplot_lib_demo/roma-traffic-incidents/README.md # roma-traffic-incidents An iPython notebook that analyses Rome traffic data with the pandas library <file_sep>/data_challenges/mbrdna_data_challenge/MBRDNA_MLPUX_InterviewChallenge/mnbayes.py num_entries_per_category = {} fuscat1 = {} # {'spo':} int_one = 1 float_one = 1.0 def predict(features): features = {'spo': ((int((features[0] * 100.0)) * 1000000.0) + int((features[1] * 100.0)))} ugooki2 = [] fuscat2 = sum(num_entries_per_category.itervalues()) for jjdi1 in num_entries_per_category: Chri4 = (num_entries_per_category[jjdi1] / fuscat2) for fuscat3 in features: if ((fuscat3 in fuscat1) and (features[fuscat3] in fuscat1[fuscat3]) and (jjdi1 in fuscat1[fuscat3][features[fuscat3]])): Chri4 *= (fuscat1[fuscat3][features[fuscat3]][jjdi1] / num_entries_per_category[jjdi1]) else: Chri4 *= (0.01 / fuscat2) ugooki2.append((jjdi1, Chri4)) ugooki2 = sorted(ugooki2, key=(lambda ormow1: (1 - ormow1[1]))) jjdi3 = sum(map((lambda Chri3: Chri3[1]), ugooki2)) ugooki2 = map((lambda fuscat5: ((fuscat5[0] * fuscat5[1]) / jjdi3)), ugooki2) ugooki2 = sum(ugooki2) # This seems to be a number that is either 0, very small, 0.5 or very nearly # 1 #print ugooki2 return ugooki2 def train(features, label): global int_one features = {'spo': ((int((features[0] * 100.0)) * 1000000.0) + int((features[1] * 100.0)))} for feature_key in features: # fuscat1 is a global variable if feature_key not in fuscat1: fuscat1[feature_key] = {} if features[feature_key] not in fuscat1[feature_key]: fuscat1[feature_key][features[feature_key]] = {} if label not in fuscat1[feature_key][features[feature_key]]: fuscat1[feature_key][features[feature_key]][label] = 0.0 fuscat1[feature_key][features[feature_key]][label] += int_one if label not in num_entries_per_category: num_entries_per_category[label] = 0.0 num_entries_per_category[label] += int_one int_one = (int_one * float_one) def reset(set_float_one=1.0): global int_one global float_one global num_entries_per_category global fuscat1 num_entries_per_category = {} fuscat1 = {} int_one = 1 float_one = set_float_one if (__name__ == '__main__'): train([1, 1], 1) train([0, 0], 2) #print predict([1, 1]) <file_sep>/computer_science/cs_fundamentals/notebooks/bubble_sort.py #!/usr/bin/env python import random def bubble_sort(my_list): number_of_iterations = 0 unsorted = True while(unsorted == True): unsorted = False for index in range(len(unsorted_list)-1): current_entry = my_list[index] next_entry = my_list[index+1] if next_entry < current_entry: my_list[index] = next_entry my_list[index+1] = current_entry unsorted = True print my_list number_of_iterations += 1 return my_list unsorted_list = [] for x in range(100): unsorted_list.append(random.randint(1,100)) number_of_iterations = bubble_sort(unsorted_list) <file_sep>/README.md # Introduction This repository contains much of my work learning to program, learning about machine learning and data science. It is reserved exclusively for small demos, little tutorials, and the like. Some of the work is very old, and was just put here for me to chuckle at and see how far I've come (check out the cpp area...cobwebs...). Any little thing that I do, which might be useful as a reference, or a toy implementation which I might benefit from actually saving will go here. Proper projects will get their own repositories. The goal of this repository is to reign in my learning into one place, to facilitate working on various machines without worring about synching things up. This repository will also serve as a complete record/prep area for all job related activities that I undertake over my career in Data Scienece / Machine learning. In the Introduction.ipynb, the goal will be to link any relevant notebooks to concepts, notes, etc, elsewhere in this repo. The introduction ranks my comfort level in these topics, but the ranking was carried out some time ago and is not really relevant anymore. Topics (overall) will be rated with a score (1, 2, or 3), where 3 is "very prepared", 2 is "familiar, needs study" and 3 is "not at all prepared".
a463cbed858fc50c58d7138548fc43c3973416e6
[ "Markdown", "Python", "Text" ]
24
Markdown
yuzhiliu/learning
05828ed2bae134bf380370d189eb9bdae675397f
5603df79e2f152b9240c0bc671bd15d49975e170
refs/heads/master
<file_sep>#include "Adafruit_BluefruitLE_SPI.h" #include <SPI.h> #define Vcc 5 #define UPDATE_COMMAND_CHARSIZE 30 #define FACTORYRESET_ENABLE 0 #define AVERAGE_OF_TRIES 5 #define BUFSIZE 160 // Size of the read buffer for incoming data #define VERBOSE_MODE true // If set to 'true' enables debug output #define BLUEFRUIT_SPI_CS 10 #define BLUEFRUIT_SPI_IRQ 7 #define BLUEFRUIT_SPI_RST 8 // Optional but recommended, set to -1 if unused // All possible states enum state_name { idle_state = 0, connect_state, adc_state, update_state }; // Hold value for distance reading from radar static volatile float distance; // State machine static volatile unsigned char state; // Reserved place for service ID and characteristic ID static uint32_t s_ID; static uint32_t c_ID; // Adafruit provided library to interact with lower level SPI and messging between Bluefruit. // 3 parameters: CS, IRQ, RST(optional) Adafruit_BluefruitLE_SPI ble(BLUEFRUIT_SPI_CS, BLUEFRUIT_SPI_IRQ, BLUEFRUIT_SPI_RST); // Print to serial and stop program void error(const __FlashStringHelper*err) { Serial.println(err); while (1); } // Interrupt for ADC conversion completion ISR(ADC_vect){ // Increment sum counter static volatile char sum_counter = 0; static volatile int distance_sum_before_processing = 0; static volatile float Aread_V = 0; sum_counter++; // Read low register first and then 2 bits from high register distance_sum_before_processing += ADCL | (ADCH << 8); // Calculate average if (sum_counter == AVERAGE_OF_TRIES){ // Find the average Aread_V = (float(distance_sum_before_processing/(float)AVERAGE_OF_TRIES) * Vcc) / 1024; // Calculate real voltage level distance = 26.927 * pow(Aread_V, -1.197); // Calculate distance from voltage, formula extracted from data points using excel treadline // Remove unstable values if (distance <= 10 || distance > 90){ distance = 0; } // Reset counter distance_sum_before_processing = 0; Aread_V = 0; sum_counter = 0; } // Move to update state state = update_state; } void setup() { cli(); // Disable global interrupt Serial.begin(115200); Serial.println(F("Beginnging distance sensor project")); // Setup BLE ble_setup(); // configure ADC register adc_setup(); // Initialize distance = 0; state = connect_state; sei(); // Enable global interrupt; } void loop() { switch (state){ case idle_state: // Do nothing break; case connect_state: // Change state only when ble is connected if (ble.isConnected()){ Serial.println(F("Bluetooth device connected.")); // Turn off verbose mode ble.verbose(false); Serial.println(F("Verbose mode - OFF")); state = adc_state; } // Check for connection after a small delay delay(2000); break; case adc_state: //Serial.println(F("Start sampling ADC value... and go back to idle")); // After enablig adc, swithc to idle state to wait for ADC interrupt adc_start(); state = idle_state; break; case update_state: // If device is no longer connected, go back to connect_state without updating BLE if (!ble.isConnected()){ state = connect_state; return; } // Send update to BLE device and go back to sampling ADC setCharacteristicToValue(c_ID, distance); // Pause briefly delay(100); state = adc_state; break; default: break; } } // Setup bluetooth device and // Add service and characteristics to transmit distance sensor over BLE // Service: void ble_setup(){ // Begin setting up bluefruit if (!ble.begin(VERBOSE_MODE)){ error(F("Can't initialized bluefruit...")); } /* Disable command echo from Bluefruit */ ble.echo(false); Serial.println("Requesting Bluefruit info:"); /* Print Bluefruit information */ ble.info(); // Set device name to BLE-DistanceSensor if (!ble.atcommand(F("AT+GAPDEVNAME=BLE-DistanceSensor"))) { error(F("Failed to set device name")); } Serial.println(F("Set BLE device name to 'BLE-DistanceSensor'")); // Clear all existing services and characteristics if (!ble.atcommand(F("AT+GATTCLEAR"))) { error(F("Failed to clear GATT services")); } Serial.println(F("Cleared GATT services")); // Register a service with a unique 128-bit UUID generated by online generator if (!ble.atcommandIntReply(F("AT+GATTADDSERVICE=UUID128=c7-81-14-b0-51-cd-4f-2d-8e-1b-5b-64-28-18-1c-66"), &s_ID)){ error(F("Failed to register service 1")); } Serial.println(F("GATT service added")); // Register a characteristic with a 16-bit UUID (String: 0x2A3D) // Property is notify if (!ble.atcommandIntReply(F("AT+GATTADDCHAR=UUID=0x2A3D,PROPERTIES=0x10,MIN_LEN=1,MAX_LEN=2,VALUE=0,DESCRIPTION=DISTANCE MEASUREMENT"), &c_ID)){ error(F("Failed to register characteristic 1")); } Serial.println(F("GATT characteristic added")); // Reset system after changing GATT profile ble.atcommand(F("ATZ")); delay(3000); // Start advertising if it isn't already ble.atcommand(F("AT+GAPSTARTADV")); Serial.println(F("BLE advertising...")); } // Send a new distance value to BLE and return 1 for OK or 0 for ERROR void setCharacteristicToValue(uint32_t ID, float val){ // Serial.println("======== Update Sensor Value ========="); uint32_t dnum; // Hold distance value char d[5]; // string to store update command char updateCommand[UPDATE_COMMAND_CHARSIZE]; // Remove decimal points dnum = int(val); // Clear update command string memset(updateCommand, 0, UPDATE_COMMAND_CHARSIZE); // Fill update command with characteristic ID and distance value sprintf(updateCommand, "AT+GATTCHAR=%u,", ID); sprintf(d, "%u", dnum); // Form update char string strcat(updateCommand, d); if (!ble.atcommand(updateCommand)){ //error(F("Failed to send new distance data")); Serial.println(F("Failed to send new distance data")); } } // Configure ADC to target ADC0 and enable ADC interrupt. Auto-trigger is disabled void adc_setup(){ PRR &= ~(1 << PRADC); // Disable power reduction for adc ADMUX = (0 << REFS1) | (1 << REFS0); // Set ADC voltage reference to AVcc with external capacitor at AREF pin ADMUX &= B11110000; // ADMUX: select ADC0 as input by setting MUX[0:3] = 0 ADMUX &= ~(1 << ADLAR); // Right-adjusted bit ADCSRA |= (1 << ADEN); //ADC enable bit delay(10); ADCSRA |= (1 << ADIF); // Clear interrupt flag by writing a 1 ADCSRA &= ~(1 << ADATE); // Disable ADC auto trigger bit ADCSRA |= (1 << ADIE); // Enable ADC interrupt ADCSRA |= B00000111; // Set pre-scaler to 128 for most accurate setting } // Start ADC conversion. When conversion is completed, ADC_vect interrupt will be triggered void adc_start(){ ADCSRA |= 1 << ADSC; // start conversion, ADCS will stay high while processing and clear by hardware }
ca0e0bc77301a707b4314a19174d2d114834c75d
[ "C++" ]
1
C++
Chanrich/Garage-Park-Safe
2bbb385e1187f4a193f2a96e8f3f9eb514f5a331
b484be04e0b02bc2767335a6b56ca9228e19eeb5
refs/heads/master
<file_sep>#![feature(step_by)] #[macro_use] extern crate lazy_static; use std::io; use std::io::prelude::*; use std::collections::HashMap; use std::hash::{Hash, Hasher}; use std::cmp::Ordering; use std::fmt; use std::sync::{Arc, Mutex}; use std::thread; use std::mem; lazy_static! { static ref TONUM: [u8; 256] = { let mut m: [u8; 256] = [0; 256]; m['A' as usize] = 0; m['C' as usize] = 1; m['T' as usize] = 2; m['G' as usize] = 3; m }; } static TOCHAR: [char; 4] = ['A', 'C', 'T', 'G']; #[derive(Copy, Clone, Eq)] struct T { data: u64, size: usize, } impl T { fn blank() -> T { T::new("") } fn new(s: &str) -> T { let mut t = T { data: 0, size: s.len(), }; t.reset(s); t } fn reset(&mut self, s: &str) -> &T { self.data = 0; self.size = s.len(); for c in s.chars() { self.data <<= 2; self.data |= TONUM[c as usize] as u64; } self } } impl PartialEq for T { fn eq(&self, other: &Self) -> bool { self.data.eq(&other.data) } } impl PartialOrd for T { fn partial_cmp(&self, other: &Self) -> Option<Ordering> { self.data.partial_cmp(&other.data) } } impl Ord for T { fn cmp(&self, other: &Self) -> Ordering { self.data.cmp(&other.data) } } impl Hash for T { fn hash<H: Hasher>(&self, state: &mut H) { self.data.hash(state); } } impl fmt::Display for T { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { let mut out = String::from(""); let mut tmp = self.data; for _ in 0..self.size { out.push(TOCHAR[(tmp & 3) as usize]); tmp >>= 2; } out = out.chars().rev().collect(); write!(f, "{}", out) } } fn calculate(input: &str, tsize: usize, begin: usize, incr: usize) -> HashMap<T, u32> { let mut counts = HashMap::new(); let mut tmp = T::blank(); for i in (begin..(input.len() + 1 - tsize)).step_by(incr) { tmp.reset(&input[i..(i + tsize)]); let counter = counts.entry(tmp).or_insert(0); *counter += 1; } counts } fn parallel_calculate(input: &str, tsize: usize) -> HashMap<T, u32> { let num_cpus = 4; let mut children = vec![]; let combined_counts = Arc::new(Mutex::new(HashMap::new())); let input: &'static str = unsafe { mem::transmute(input) }; for n in 0..num_cpus { let combined_counts = combined_counts.clone(); children.push(thread::spawn(move || { let counts = calculate(&input, tsize, n, num_cpus); let mut combined_counts = combined_counts.lock().unwrap(); for (t, count) in &counts { let counter = combined_counts.entry(*t).or_insert(0); *counter += *count; } })); } for child in children { child.join().unwrap(); } Arc::try_unwrap(combined_counts).ok().expect("foobar").into_inner().unwrap() } fn write_frequencies(input: &str, tsize: usize) { let sum: usize = input.len() + 1 - tsize; let counts = parallel_calculate(input, tsize); let mut counts_descending: Vec<(&T, &u32)> = counts.iter().collect(); counts_descending.sort_by(|a, b| a.1.cmp(b.1).reverse()); for (ch, count) in counts_descending { let frequency: f64 = if sum != 0 { (100 * count) as f64 / sum as f64 } else { 0.0 }; println!("{}\t{:.3}", ch, frequency); } println!(""); } fn write_count(input: &str, tstr: &str) { let size = tstr.len(); let counts = parallel_calculate(input, size); let count = counts.get(&T::new(tstr)).cloned().unwrap_or(0); println!("{}\t{}", count, tstr); } fn main() { let stdin = io::stdin(); let input: String = stdin.lock().lines() .map(|line| line.unwrap()) .skip_while(|line| !line.starts_with(">THREE")) .skip(1) .take_while(|line| !line.starts_with('>')) .collect::<Vec<_>>() .concat() .to_uppercase(); for i in 1..3 { write_frequencies(&input, i); } for t in ["GGT", "GGTA", "GGTATT", "GGTATTTTAATT", "GGTATTTTAATTTATAGT"].into_iter() { write_count(&input, t); } } <file_sep>[package] name = "k-nucleotide" version = "0.1.0" authors = ["<NAME> <<EMAIL>>"] [dependencies] lazy_static = "0.1.*" [[bin]] name = "k-nucleotide" path = "k-nucleotide.rs"
ae922d9b5ddf289979b7afb828ba825f4c0c4ce9
[ "TOML", "Rust" ]
2
Rust
aschampion/rust-clbg
0b43ce3a88c1d42fa1d3d2e799606bd2c01c517b
3587ff690ab01dd080a62538554c9805deddb0ab
refs/heads/master
<file_sep>package se.kth.csc.iprog.dinnerplanner.swing.view; import se.kth.csc.iprog.dinnerplanner.model.Dish; import java.awt.*; import javax.swing.*; /** * Created by Jiansun on 16/2/10. */ public class PreparationPanel extends JPanel{ private static final long serialVersionUID = 1L; // String dishStarter; // String dishMain; // String dishDesert; JLabel title=new JLabel(); Font font = new Font("Courier", Font.BOLD,30); JLabel starter = new JLabel(); JLabel main = new JLabel(); JLabel desert = new JLabel(); JTextArea starterContent = new JTextArea(); JTextArea mainContent = new JTextArea(); JTextArea desertContent = new JTextArea(); public PreparationPanel(Dish dishStarter,Dish dishMain, Dish dishDesert ){ super(new BorderLayout()); // The top layout title.setText("Dinner menu preparation"); title.setHorizontalAlignment(JLabel.CENTER); //title.setPreferredSize(new Dimension(Constants.dishNameDisplayWindowWidth, //Constants.dishNameInformationPanelHeight)); JPanel topP = new JPanel(); topP.setLayout(new BorderLayout()); //topP.setPreferredSize(new Dimension(Constants.dishNameDisplayWindowWidth, //Constants.dishNameInformationPanelHeight)); topP.add(title,BorderLayout.NORTH); starter.setText("Starter:"+dishStarter.getName()); starter.setHorizontalAlignment(JLabel.CENTER); //starter.setPreferredSize(new Dimension(Constants.dishNameDisplayWindowWidth, //Constants.dishNameInformationPanelHeight)); topP.add(starter,BorderLayout.CENTER); starterContent.setText(dishStarter.getDescription()); starterContent.setPreferredSize(new Dimension(Constants.dishNameDisplayWindowWidth, Constants.dishNameInformationPanelHeight)); //title.setPreferredSize(new Dimension(20,20)); topP.add(starterContent,BorderLayout.SOUTH); //topP.setPreferredSize(new Dimension(100,100)); // The middle layout JPanel midP = new JPanel(); midP.setLayout(new BorderLayout()); main.setText("Main:"+dishMain.getName()); main.setHorizontalAlignment(JLabel.CENTER); mainContent.setText(dishMain.getDescription()); midP.add(main,BorderLayout.NORTH); midP.add(mainContent,BorderLayout.SOUTH); mainContent.setPreferredSize(new Dimension(Constants.dishNameDisplayWindowWidth, Constants.dishNameInformationPanelHeight)); midP.setPreferredSize(new Dimension(Constants.dishNameDisplayWindowWidth, Constants.dishNameInformationPanelHeight)); // The bottom layout JPanel bottP = new JPanel(); bottP.setLayout(new BorderLayout()); desert.setText("Desert:"+dishDesert.getName()); desert.setHorizontalAlignment(JLabel.CENTER); bottP.add(desert,BorderLayout.NORTH); desertContent.setText(dishDesert.getDescription()); bottP.add(desertContent,BorderLayout.SOUTH); //bottP.setPreferredSize(new Dimension(Constants.dishNameDisplayWindowWidth, // Constants.dishNameInformationPanelHeight)); desertContent.setPreferredSize(new Dimension(Constants.dishNameDisplayWindowWidth, Constants.dishNameInformationPanelHeight)); title.setFont(font); starter.setFont(font); main.setFont(font); desert.setFont(font); //setPreferredSize(new Dimension(800,600)); //this.setLayout(new BoxLayout(this,BoxLayout.Y_AXIS)); //add(Box.createRigidArea(new Dimension(20,20))); add(topP,BorderLayout.NORTH); //add(Box.createRigidArea(new Dimension(20,20))); add(midP,BorderLayout.CENTER); //add(Box.createRigidArea(new Dimension(20,20))); add(bottP,BorderLayout.SOUTH); this.setPreferredSize(new Dimension(Constants.dishNameDisplayWindowWidth, Constants.dishNameInformationPanelHeight)); } // public PreparationPanel() { // // } public void creatAndShowGUI(){ //creat and setup the window JFrame frame = new JFrame("Dinner planner-Preparation"); frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); this.setOpaque(true); //this.setLayout(new BoxLayout(this,BoxLayout.Y_AXIS)); frame.setContentPane(this); // this.setPreferredSize(new Dimension(Constants.dishNameDisplayWindowWidth, // Constants.dishNameInformationPanelHeight)); frame.setSize(800,750); //frame.pack(); frame.setVisible(true); } public static void main(String[] args) { Dish temp1 = new Dish("Apple",1,"xxx","Stockholm"); Dish temp2 = new Dish("Banana",2,"@@@","Madrid"); Dish temp3 = new Dish("Orange",3,"$$$","Tokyo"); PreparationPanel newPrepPane = new PreparationPanel(temp1,temp2,temp3); //PreparationPanel pp = new PreparationPanel(); newPrepPane.creatAndShowGUI(); } } <file_sep>package se.kth.csc.iprog.dinnerplanner.model.dynamicData; import okhttp3.ResponseBody; import retrofit2.Call; import retrofit2.http.GET; import retrofit2.http.Headers; import retrofit2.http.Path; import retrofit2.http.Query; import retrofit2.http.Url; public interface ApiService { @Headers("Accept:application/json") @GET("/recipes?") Call<ResultInformation> getDishListByPaging( @Query("api_Key") String apiKey, @Query("pg") int pgValue, @Query("rpp") int rppValue); @Headers("Accept:application/json") @GET("/recipe/{rid}") Call<RecipeInformation> getDishInformationById( @Path("rid") int rid, @Query("api_Key") String apiKey); @Headers("Accept:application/json") @GET("/recipes?") Call<ResultInformation> getDishListByType( @Query("api_Key") String apiKey, @Query("any_kw") String keyWord, @Query("pg") int pgValue, @Query("rpp") int rppValue); @Headers("Accept:application/json") @GET("/recipes?") Call<ResultInformation> getDishListByTitleKeyWord( @Query("api_Key") String apiKey, @Query("title_kw") String keyWord, @Query("pg") int pgValue, @Query("rpp") int rppValue); @GET Call<ResponseBody> getImageByURL( @Url String url); } <file_sep>package se.kth.csc.iprog.dinnerplanner.swing.view; import java.awt.Cursor; import java.awt.dnd.DnDConstants; import java.awt.dnd.DragGestureEvent; import java.awt.dnd.DragGestureListener; import java.awt.dnd.DragSource; import javax.swing.BorderFactory; import se.kth.csc.iprog.dinnerplanner.model.Dish; import se.kth.csc.iprog.dinnerplanner.swing.view.ListAllPanel.DishDisplayPanel; public class DishDragGestureListener implements DragGestureListener{ @Override public void dragGestureRecognized(DragGestureEvent e) { Cursor cursor=null; DishDisplayPanel p=(DishDisplayPanel)e.getComponent(); p.setBorder(BorderFactory.createEtchedBorder()); Dish dish=p.getDish(); if(dish.getName().equals("NO RESULT")) return; if(e.getDragAction()==DnDConstants.ACTION_COPY) { cursor=DragSource.DefaultCopyDrop; } e.startDrag(cursor, new DishTransferable(dish)); } } <file_sep>package se.kth.csc.iprog.dinnerplanner.swing.view; import java.awt.BorderLayout; import java.awt.Color; import java.awt.Dimension; import java.awt.Font; import java.awt.Image; import java.awt.dnd.DnDConstants; import java.awt.dnd.DragSource; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import javax.swing.BorderFactory; import javax.swing.ImageIcon; import javax.swing.JLabel; import javax.swing.JPanel; import se.kth.csc.iprog.dinnerplanner.model.DinnerModel; import se.kth.csc.iprog.dinnerplanner.model.Dish; public class DishDisplayPanel extends JPanel{ private static final long serialVersionUID = 1L; Dish dish=new Dish(); ImageIcon dishIcon; JLabel dishImageLabel; JLabel dishNameLabel=new JLabel(); int ID; DinnerModel model; boolean isSearch; String kw=null; public DishDisplayPanel(Dish d,int id,DinnerModel m,boolean search,String kw) { this.kw=kw; this.isSearch=search; this.setPreferredSize(new Dimension(Constants.dishDisplayWidth+Constants.interDishDisplayMargin, Constants.dishDisplayHeight+Constants.interDishDisplayMargin)); //if(d==null) return; this.ID=id; this.dish=d; this.model=m; this.dishIcon=new ImageIcon(Constants.homeDir+Constants.pictureDir+dish.getImage()); this.dishImageLabel=new JLabel(); this.dishNameLabel.setText(dish.getName()); this.setBorder(BorderFactory.createLoweredBevelBorder()); this.dishImageLabel.setPreferredSize(new Dimension(Constants.dishDisplayWidth, Constants.dishDisplayWidth)); this.dishImageLabel.setBorder(BorderFactory.createRaisedBevelBorder()); this.dishNameLabel.setPreferredSize(new Dimension(Constants.dishDisplayWidth, Constants.dishNameDisplayLabelHeight)); this.dishNameLabel.setHorizontalAlignment(JLabel.CENTER); this.dishNameLabel.setVerticalAlignment(JLabel.CENTER); Font nameFont=new Font("Segoe Print", Font.BOLD,16); this.dishNameLabel.setFont(nameFont); Image img=this.dishIcon.getImage(); Image newImg=img.getScaledInstance (Constants.dishDisplayWidth,Constants.dishDisplayWidth,Image.SCALE_SMOOTH); ImageIcon newIcon=new ImageIcon(newImg); this.dishImageLabel.setIcon(newIcon); //this.dishImageLabel.setIcon(this.dishIcon); this.setLayout(new BorderLayout()); this.add(this.dishImageLabel,BorderLayout.NORTH); this.add(this.dishNameLabel,BorderLayout.CENTER); this.setFocusable(true); this.addMouseListener(new MouseAdapter(){ @Override public void mouseEntered(MouseEvent e) { DishDisplayPanel.this.setBorder(BorderFactory.createLineBorder(Color.LIGHT_GRAY,5)); } @Override public void mouseExited(MouseEvent e) { DishDisplayPanel.this.setBorder(BorderFactory.createLoweredBevelBorder()); } @Override public void mouseClicked(MouseEvent e) { if(DishDisplayPanel.this.dish.getName().equals(Constants.addMoreName)) { System.out.println(" is serach "+isSearch+" kw "+kw); if(!isSearch) model.loadMoreDish(dish.getType()); else model.loadMoreSearchResult(dish.getType(),kw); } model.setLoadingState(true); } }); DragSource dragSource=DragSource.getDefaultDragSource(); dragSource.createDefaultDragGestureRecognizer(this, DnDConstants.ACTION_COPY, new DishDragGestureListener()); } public Dish getDish() { return this.dish; } public void loadNewImage(String pic) { this.dish.setImage(pic); this.dishIcon=new ImageIcon(Constants.homeDir+Constants.pictureDir+pic); Image img=this.dishIcon.getImage(); Image newImg=img.getScaledInstance (Constants.dishDisplayWidth,Constants.dishDisplayWidth,Image.SCALE_SMOOTH); ImageIcon newIcon=new ImageIcon(newImg); this.dishImageLabel.setIcon(newIcon); this.validate(); this.repaint(); } } <file_sep>package se.kth.csc.iprog.dinnerplanner.model.dynamicData; public class DishImage { String name; String picName; int type; public DishImage(String n,String pic,int t) { this.name=n; this.picName=pic; this.type=t; } public int getType() { return type; } public String getName() { return name; } public String getPicName() { return picName; } } <file_sep>package se.kth.csc.iprog.dinnerplanner.swing; import java.awt.Image; import javax.swing.JFrame; import se.kth.csc.iprog.dinnerplanner.controller.DinnerPlannerController; import se.kth.csc.iprog.dinnerplanner.model.*; import se.kth.csc.iprog.dinnerplanner.swing.view.*; public class DinnerPlanner extends JFrame { private static final long serialVersionUID = 1L; public DinnerPlanner() { this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); this.setBounds((Constants.widthDf-Constants.width)/2, (Constants.heightDf-Constants.height)/2, Constants.width, Constants.height); Image img = this.getToolkit().getImage(Constants.windowIconDir); this.setIconImage(img); } private static DinnerModel model = new DinnerModel(); public DinnerModel getModel() { return model; } public void setModel(DinnerModel model) { DinnerPlanner.model = model; } public static void main(String[] args) { //Initiating the main JFrame DinnerPlanner dinnerPlanner = new DinnerPlanner(); dinnerPlanner.setTitle("Dinner Planner"); //Creating the first view MainView mainView = new MainView(model); //Create main controller DinnerPlannerController controller=new DinnerPlannerController(model,mainView); controller.registerAllListener(); //Create drag and drop controller new DishDropTargetListener(mainView.informationPanel,model); //Adding the view to the main JFrame dinnerPlanner.setContentPane(mainView); //Resize it so content fits dinnerPlanner.pack(); //and starting the JFrame dinnerPlanner.setVisible(true); } } <file_sep>package se.kth.csc.iprog.dinnerplanner.swing.view; import java.awt.BorderLayout; import java.awt.Dimension; import java.awt.Font; import java.awt.Image; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.Observable; import java.util.Observer; import javax.swing.BorderFactory; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JTable; import javax.swing.table.DefaultTableModel; import javax.swing.table.JTableHeader; import se.kth.csc.iprog.dinnerplanner.model.ChangeMessage; import se.kth.csc.iprog.dinnerplanner.model.Dish; import se.kth.csc.iprog.dinnerplanner.model.Ingredient; public class IngredientPanel extends JPanel implements Observer { private static final long serialVersionUID = 1L; Font tableFont = new Font("Gill Sans MT", Font.PLAIN, 16); Font tableFontSmall = new Font("Gill Sans MT", Font.PLAIN, 14); Dish tempStarter; Dish tempMain; Dish temphDesert; String temp1; Ingredient tempS; ArrayList<Ingredient> list=new ArrayList<Ingredient>(); JTable table = new JTable(); JTableHeader theader; public void creatAndShowGUI(ArrayList<Ingredient> list) { JFrame frame = new JFrame("Dinner Planner - Ingredients"); frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); frame.setBounds((Constants.widthDf-Constants.ingredientPanelWidth)/2, (Constants.heightDf-Constants.ingredientPanelHeight)/2, Constants.ingredientPanelWidth, Constants.ingredientPanelHeight); Image img = this.getToolkit().getImage(Constants.windowIconDir); frame.setIconImage(img); this.setPreferredSize(new Dimension(Constants.ingredientPanelWidth, Constants.ingredientPanelHeight)); this.setBorder(BorderFactory.createEmptyBorder(10,10,10,10)); //Create and set up the content pane. //IngredientPanel newContentPane = new IngredientPanel(); this.setOpaque(false); //content panes must be opaque frame.setContentPane(this); //Display the window. this.list=list; IngredientTableCellRender renderer = new IngredientTableCellRender(); String headers[] = {"Ingredient", "Quantity", "Cost"}; DefaultTableModel dtm=(DefaultTableModel) table.getModel(); dtm.setColumnIdentifiers(headers); this.refreshIngredientsTable(list); Font tableFont=new Font("Gill Sans MT",Font.PLAIN,20); table.setFont(tableFont); table.getTableHeader().setFont(tableFont); table.setDefaultRenderer(Object.class, renderer); //table.setFillsViewportHeight(true); //table.setAutoCreateRowSorter(true); table.setRowHeight(Constants.dishNameTableRowHeight); this.table.getColumn("Ingredient").setPreferredWidth(Constants.ingredientPanelTableWidth1); this.table.getColumn("Quantity").setPreferredWidth(Constants.ingredientPanelTableWidth2); this.table.getColumn("Cost").setPreferredWidth(Constants.ingredientPanelTableWidth2); int height=Constants.dishNameTableRowHeight; int [] width={Constants.ingredientPanelTableWidth1,Constants.ingredientPanelTableWidth2, Constants.ingredientPanelTableWidth2}; TableHeaderRender hrender=new TableHeaderRender(width,height); this.theader=this.table.getTableHeader(); this.theader.setDefaultRenderer(hrender); this.theader.addMouseListener(new MouseAdapter(){ @Override public void mouseClicked(MouseEvent e) { int columnNo=IngredientPanel.this.table.columnAtPoint(e.getPoint()); IngredientPanel.this.sortTbaleByKey(columnNo); } }); JScrollPane scrollPane = new JScrollPane(table); scrollPane.setPreferredSize(new Dimension(Constants.ingredientPanelWidth, Constants.ingredientPanelHeight)); frame.getContentPane().setLayout(new BorderLayout()); frame.getContentPane().add(scrollPane, BorderLayout.CENTER); frame.setFont(tableFont); frame.pack(); frame.setVisible(true); } private class ListComparator implements Comparator<Ingredient> { int sortType=0; public ListComparator(int t) { this.sortType=t; } @Override public int compare(Ingredient ing1, Ingredient ing2) { if(this.sortType==0) return ing1.getName().compareTo(ing2.getName()); else if(this.sortType==1) return Double.compare(ing1.getQuantity(), ing2.getQuantity()); else return Double.compare(ing1.getPrice(), ing2.getPrice()); } } public void sortTbaleByKey(int key) { ListComparator comp=new ListComparator(key); Collections.sort(list, comp); int num=this.table.getRowCount(); DefaultTableModel dtm=(DefaultTableModel)this.table.getModel(); for(int i=0;i<num;i++) dtm.removeRow(0); num=list.size(); String[] tableContent=new String[3]; for(int i=0;i<num;i++) { Ingredient ing=list.get(i); tableContent[0]=ing.getName(); tableContent[1]=""+ing.getQuantity()+" "+ing.getUnit(); tableContent[2]="$ "+ing.getPrice(); dtm.addRow(tableContent); } this.validate(); this.repaint(); } // set the background color public void refreshIngredientsTable(ArrayList<Ingredient> list) { int num=this.table.getRowCount(); DefaultTableModel dtm=(DefaultTableModel) table.getModel(); for(int i=0;i<num;i++) dtm.removeRow(0); String[] data=new String [3]; num=list.size(); for(int i=0;i<num;i++) { Ingredient tmp=list.get(i); data[0]=tmp.getName(); data[1]=tmp.getQuantity()+" "+tmp.getUnit(); data[2]="$ "+tmp.getPrice(); dtm.addRow(data); } this.validate(); this.repaint(); } @SuppressWarnings("unchecked") @Override public void update(Observable obs, Object obj) { ChangeMessage cm=(ChangeMessage) obj; if(cm.getType()==ChangeMessage.ingredientsCahnged) { this.refreshIngredientsTable((ArrayList<Ingredient>)cm.getData()); } } } <file_sep>package se.kth.csc.iprog.dinnerplanner.swing.view; import java.awt.BorderLayout; import java.awt.Dimension; import java.awt.Font; import java.awt.Image; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.Iterator; import java.util.Observable; import java.util.Observer; import javax.swing.BorderFactory; import javax.swing.ImageIcon; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JSplitPane; import javax.swing.JTable; import javax.swing.JTextArea; import javax.swing.table.DefaultTableModel; import javax.swing.table.JTableHeader; import javax.swing.table.TableCellRenderer; import se.kth.csc.iprog.dinnerplanner.model.ChangeMessage; import se.kth.csc.iprog.dinnerplanner.model.DinnerModel; import se.kth.csc.iprog.dinnerplanner.model.Dish; import se.kth.csc.iprog.dinnerplanner.model.Ingredient; public class DishNameDisplayWindow extends JFrame implements Observer { private static final long serialVersionUID = 1L; Dish dish; int guestNum=0; String[] header={"Ingredient","Quantity","Cost"}; JPanel content=new JPanel(); JPanel nameInformationPanel=new JPanel(); JLabel image=new JLabel(); JPanel imagePanel=new JPanel(); JPanel namePanel=new JPanel(); JLabel name=new JLabel(); JLabel cost=new JLabel(); JSplitPane split=new JSplitPane(); JScrollPane descriptionScroll; JScrollPane ingredientScroll; JTextArea description=new JTextArea(); JTable table; IngredientTableCellRender render=new IngredientTableCellRender(); JTableHeader theader; public DishNameDisplayWindow(Dish d,int num,DinnerModel m) { m.addObserver(this); Image imgic = this.getToolkit().getImage(Constants.windowIconDir); this.setIconImage(imgic); this.dish=d; this.guestNum=num; // release the resources when closing the window this.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); this.setTitle("Dinner Planner-Dish Name"); // create some different fonts Font nameFont=new Font("Informal Roman",Font.BOLD,38); Font costFont=new Font("Segoe Print",Font.BOLD,20); Font tableFont=new Font("Gill Sans MT",Font.PLAIN,18); Font headerFont=new Font("Segoe Print",Font.BOLD,20); // set window location and size this.setBounds((Constants.widthDf-Constants.dishNameDisplayWindowWidth)/2, (Constants.heightDf-Constants.dishNameDisplayWindowHeight)/2, Constants.dishNameDisplayWindowWidth, Constants.dishNameDisplayWindowHeight); // set size layout add component to the content pane this.setContentPane(this.content); this.content.setPreferredSize(new Dimension(Constants.dishNameDisplayWindowWidth, Constants.dishNameDisplayWindowHeight)); this.content.setLayout(new BorderLayout()); this.content.add(nameInformationPanel, BorderLayout.NORTH); this.content.add(split,BorderLayout.CENTER); // resize the image to fit the size Image img=new ImageIcon(Constants.homeDir+Constants.pictureDir+this.dish.getImage()).getImage(); Image newImg=img.getScaledInstance(Constants.dishNameImageWidth, Constants.dishNameImageWidth, Image.SCALE_SMOOTH); this.image.setIcon(new ImageIcon(newImg)); this.image.setBorder(BorderFactory.createRaisedBevelBorder()); // set image panel parameters this.imagePanel.setPreferredSize(new Dimension(Constants.dishNameInformationPanelHeight, Constants.dishNameInformationPanelHeight)); this.imagePanel.setLayout(new BorderLayout()); this.imagePanel.add(image,BorderLayout.CENTER); this.imagePanel.setBorder(BorderFactory.createEmptyBorder(Constants.dishNameBorder, Constants.dishNameBorder, Constants.dishNameBorder, Constants.dishNameBorder)); // set name label parameters this.name.setText(dish.getName()); this.name.setFont(nameFont); this.name.setPreferredSize(new Dimension(Constants.dishNameNamePanelWidth, Constants.dishNameNameHeight)); // set cost label parameters this.cost.setPreferredSize(new Dimension(Constants.dishNameNamePanelWidth, Constants.dishNameNameHeight)); this.cost.setText("$ "+(dish.getCost()*guestNum)+" for "+this.guestNum+" persons"); this.cost.setFont(costFont); // set name panel parameters this.namePanel.setPreferredSize(new Dimension(Constants.dishNameNamePanelWidth, Constants.dishNameInformationPanelHeight)); this.namePanel.setLayout(new BorderLayout()); this.namePanel.add(name, BorderLayout.NORTH); this.namePanel.add(cost,BorderLayout.SOUTH); this.namePanel.setBorder(BorderFactory.createEmptyBorder (Constants.dishNameNamePanelBorderWidth, Constants.dishNameNamePanelBorderWidth, Constants.dishNameNamePanelBorderWidth, Constants.dishNameNamePanelBorderWidth)); // set name information panel parameters this.nameInformationPanel.setPreferredSize(new Dimension(Constants.dishNameDisplayWindowWidth, Constants.dishNameInformationPanelHeight)); this.nameInformationPanel.setLayout(new BorderLayout()); this.nameInformationPanel.add(this.imagePanel, BorderLayout.WEST); this.nameInformationPanel.add(this.namePanel, BorderLayout.CENTER); // set description not editable this.description.setEditable(false); // set description automatic line wrap this.description.setLineWrap(true); this.description.setText(dish.getDescription()); this.description.setFont(costFont); // set translucent background, same color as window background this.description.setOpaque(false); // crate a scroll pane containing the text area this.descriptionScroll=new JScrollPane(this.description,JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED, JScrollPane.HORIZONTAL_SCROLLBAR_NEVER); this.descriptionScroll.setPreferredSize(new Dimension(Constants.dishNameDescriptionWidth, Constants.dishNameSplitHeight)); // set cursor at the start this.description.setSelectionStart(0); this.description.setSelectionEnd(0); // set scroll bar at the start this.descriptionScroll.getVerticalScrollBar().setValue(0); // crate a new table using specified cell renderer this.table=new JTable(){ private static final long serialVersionUID = 1L; public TableCellRenderer getCellRenderer(int row, int column) { return render; } }; DefaultTableModel dtm=(DefaultTableModel)this.table.getModel(); dtm.setColumnIdentifiers(header); int height=Constants.dishNameTableRowHeight; int [] width={Constants.dishNameTableColumnWidth1,Constants.dishNameTableColumnWidth2, Constants.dishNameTableColumnWidth2}; TableHeaderRender hrender=new TableHeaderRender(width,height); this.theader=this.table.getTableHeader(); this.theader.setDefaultRenderer(hrender); this.theader.setFont(headerFont); this.theader.addMouseListener(new MouseAdapter(){ @Override public void mouseClicked(MouseEvent e) { int columnNo=DishNameDisplayWindow.this.table.columnAtPoint(e.getPoint()); DishNameDisplayWindow.this.sortTbaleByKey(columnNo); } }); // set different column width this.table.getColumn("Ingredient").setPreferredWidth(Constants.dishNameTableColumnWidth1); this.table.getColumn("Quantity").setPreferredWidth(Constants.dishNameTableColumnWidth2); this.table.getColumn("Cost").setPreferredWidth(Constants.dishNameTableColumnWidth2); this.table.setOpaque(false); this.table.setRowHeight(Constants.dishNameTableRowHeight); this.table.setFont(tableFont); Iterator <Ingredient> itr=dish.getIngredients().iterator(); String[] tableContent=new String[3]; while(itr.hasNext()) { Ingredient ing=itr.next(); tableContent[0]=ing.getName(); tableContent[1]=""+ing.getQuantity()+" "+ing.getUnit(); tableContent[2]="$ "+ing.getPrice(); dtm.addRow(tableContent); } this.ingredientScroll=new JScrollPane(table,JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED, JScrollPane.HORIZONTAL_SCROLLBAR_NEVER); this.ingredientScroll.setPreferredSize(new Dimension(Constants.dishNameTableWidth, Constants.dishNameSplitHeight)); this.split.setPreferredSize(new Dimension(Constants.dishNameDisplayWindowWidth, Constants.dishNameInformationPanelHeight)); this.split.setDividerLocation(Constants.dishNameDividerLocation); this.split.setLeftComponent(descriptionScroll); this.split.setRightComponent(ingredientScroll); this.split.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5)); } private class ListComparator implements Comparator<Ingredient> { int sortType=0; public ListComparator(int t) { this.sortType=t; } @Override public int compare(Ingredient ing1, Ingredient ing2) { if(this.sortType==0) return ing1.getName().compareTo(ing2.getName()); else if(this.sortType==1) return Double.compare(ing1.getQuantity(), ing2.getQuantity()); else return Double.compare(ing1.getPrice(), ing2.getPrice()); } } public void sortTbaleByKey(int key) { Iterator <Ingredient> itr=dish.getIngredients().iterator(); ArrayList<Ingredient> list=new ArrayList<Ingredient>(); while(itr.hasNext()) list.add(itr.next()); ListComparator comp=new ListComparator(key); Collections.sort(list, comp); int num=this.table.getRowCount(); DefaultTableModel dtm=(DefaultTableModel)this.table.getModel(); for(int i=0;i<num;i++) dtm.removeRow(0); num=list.size(); String[] tableContent=new String[3]; for(int i=0;i<num;i++) { Ingredient ing=list.get(i); tableContent[0]=ing.getName(); tableContent[1]=""+ing.getQuantity()+" "+ing.getUnit(); tableContent[2]="$ "+ing.getPrice(); dtm.addRow(tableContent); } this.validate(); this.repaint(); } @Override public void update(Observable obs, Object obj) { ChangeMessage cm=(ChangeMessage) obj; if(cm.getType()==ChangeMessage.GuestNumChanged) { this.guestNum=(Integer) cm.getData(); this.cost.setText("$ "+(dish.getCost()*guestNum)+" for "+this.guestNum+" persons"); } } } <file_sep>package se.kth.csc.iprog.dinnerplanner.model; public class IngredientsInformation { } <file_sep>package se.kth.csc.iprog.dinnerplanner.swing.view; import java.awt.Toolkit; public class Constants { public final static String homeDir="./"; public final static String pictureDir="images/"; public final static String pictureSuffix=".jpg"; public final static String dataDir="./initData/data.txt"; public final static String notSelctName="NOT select"; public final static String notSelctDescription="You have NOT selet a dish in specified type"; public final static String notSelctPic="noResult.jpg"; public final static String windowIconDir="./images/icon.png"; public final static String nullImageName="icon.png"; public final static String addMoreImageName="add.png"; public final static String addMoreName="Load More"; public final static int noImageId=-1; public final static int borderMargin=10; public final static int interDishDisplayMargin=10; public final static int widthDf=Toolkit.getDefaultToolkit().getScreenSize().width; public final static int heightDf=Toolkit.getDefaultToolkit().getScreenSize().height; public final static int width=900; public final static int height=700; public final static int dividerLocation=(width/3)*2; public final static int tabWidth=dividerLocation; public final static int progressBarPanelHeight=90; public final static int tabHeight=height-progressBarPanelHeight; public final static int progressBarPanelWidth=tabWidth; public final static int progressBarWidth=progressBarPanelWidth; public final static int progressBarHeight=(progressBarPanelHeight-2*borderMargin)/2; public final static int progressIndicatingTextWidth=progressBarWidth; public final static int progressIndicatingTextHeight=progressBarHeight; public final static int progressBarMin=0; public final static int progressBarMax=100; public final static int searchFieldHeight=50; public final static int searchButtonWidth=100; public final static int searchTextWidth=tabWidth-searchButtonWidth; public final static int scrollHeight=height-searchFieldHeight; public final static int dishNumInARow=3; public final static int dishDisplayWidth=(tabWidth-interDishDisplayMargin*(dishNumInARow+1)) /(dishNumInARow); public final static int dishNameDisplayLabelHeight=50; public final static int dishDisplayHeight=dishDisplayWidth+dishNameDisplayLabelHeight; public final static int dishTypeNum=3; public final static int verticalScrollbarUnit=20; public final static int informationPanelWidth=width-dividerLocation; public final static int guestNumLabelHeight=35; public final static int guestNumLabelWidth=150; public final static int costLabelHeight=35; public final static int guestNumSpinnerWidth=informationPanelWidth-guestNumLabelWidth-2*borderMargin; public final static int guestNumSpinnerHeight=30; public final static int informationPanelHeight=guestNumLabelHeight+costLabelHeight+2*borderMargin; public final static int dinnerMenuHeight=70; public final static int preparationButtonHeight=40; public final static int dinnerMenuPanelHaight=height-preparationButtonHeight- informationPanelHeight-2*borderMargin; public final static int preparationButtonWidth=(informationPanelWidth-6*borderMargin)/2; public final static int menuEntryWidth=informationPanelWidth-borderMargin*5-5; public final static int menuEntryHeight=50; public final static int menuListHeight=dinnerMenuPanelHaight-dinnerMenuHeight-70; public final static int menuEntryPicWidth=menuEntryHeight; public final static int menuEntryLabelHeight=menuEntryHeight/2; public final static int menuEntryLabelWidth=menuEntryWidth-2*menuEntryPicWidth; public final static int largeBorderMargin=20; public final static int menuEntryRealHeight=menuEntryHeight+5; public final static int dishNameDisplayWindowWidth=750; public final static int dishNameDisplayWindowHeight=600; public final static int dishNameBorder=20; public final static int dishNameInformationPanelHeight=dishNameDisplayWindowHeight/3; public final static int dishNameImageWidth=dishNameInformationPanelHeight-2*dishNameBorder; public final static int dishNameNamePanelWidth=dishNameDisplayWindowWidth-dishNameInformationPanelHeight; public final static int dishNameNameHeight=dishNameInformationPanelHeight/2; public final static int dishNameSplitHeight=dishNameDisplayWindowHeight-dishNameInformationPanelHeight; public final static int dishNameDividerLocation=300; public final static int dishNameDescriptionWidth=dishNameDividerLocation; public final static int dishNameTableWidth=dishNameDisplayWindowWidth-dishNameDescriptionWidth; public final static int dishNameNamePanelBorderWidth=20; public final static int dishNameTableColumnWidth2=(dishNameDividerLocation/8)*3; public final static int dishNameTableColumnWidth1=dishNameTableWidth-2*dishNameTableColumnWidth2; public final static int dishNameTableRowHeight=40; public final static int preparationPanelWidth=700; public final static int preparationPanelHeight=600; public final static int preparationPanelTitleHeight=preparationPanelHeight/10; public final static int preparationPanelNameHeight=(preparationPanelTitleHeight*2)/3; public final static int preparationPanelDescriptionHeight=(preparationPanelHeight-preparationPanelTitleHeight- 3*preparationPanelNameHeight)/3; public final static int preparationPanelTopHeight=preparationPanelTitleHeight+preparationPanelNameHeight+ preparationPanelDescriptionHeight; public final static int preparationPanelCenterHeight=preparationPanelNameHeight+preparationPanelDescriptionHeight; public final static int preparetionPanelBottomHeight=preparationPanelCenterHeight; public final static int ingredientPanelWidth=600; public final static int ingredientPanelHeight=600; public final static int ingredientPanelTableWidth1=(ingredientPanelWidth*3)/6; public final static int ingredientPanelTableWidth2=(ingredientPanelWidth-ingredientPanelTableWidth1)/2; } <file_sep>package se.kth.csc.iprog.dinnerplanner.swing.view; import java.awt.Cursor; import java.awt.Image; import java.awt.Point; import java.awt.Toolkit; import java.awt.dnd.DnDConstants; import java.awt.dnd.DragGestureEvent; import java.awt.dnd.DragGestureListener; import javax.swing.BorderFactory; import se.kth.csc.iprog.dinnerplanner.model.Dish; public class DishDragGestureListener implements DragGestureListener{ @Override public void dragGestureRecognized(DragGestureEvent e) { DishDisplayPanel p=(DishDisplayPanel)e.getComponent(); p.setBorder(BorderFactory.createEtchedBorder()); Dish dish=p.getDish(); if(dish.getName().equals("NO RESULT")||dish.getName().equals(Constants.addMoreName)) return; Cursor cursor=null; if(e.getDragAction()==DnDConstants.ACTION_COPY) { //cursor=DragSource.DefaultCopyDrop; Toolkit toolkit = Toolkit.getDefaultToolkit(); Image img=toolkit.getImage(Constants.homeDir+Constants.pictureDir+dish.getImage()); cursor=toolkit.createCustomCursor(img, new Point(30,30)," a cursor"); } e.startDrag(cursor, new DishTransferable(dish)); } } <file_sep>package se.kth.csc.iprog.dinnerplanner.model; public class ChangeMessage { public static int GuestNumChanged=0; public static int MenuChanged=1; int type; Object value; public ChangeMessage (int t,Object v) throws Exception { if(t!=GuestNumChanged&&t!=MenuChanged) throw new Exception(); this.type=t; this.value=v; } } <file_sep>package se.kth.csc.iprog.dinnerplanner.swing.view; import java.awt.Color; import java.awt.Component; import javax.swing.JTable; import javax.swing.table.DefaultTableCellRenderer; public class IngredientTableCellRender extends DefaultTableCellRenderer{ private static final long serialVersionUID = 1L; public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) { Component cell = super.getTableCellRendererComponent ( table, value,isSelected, hasFocus, row, column); if (row % 2 == 0) cell.setBackground(Color.gray); else cell.setBackground(Color.LIGHT_GRAY); return cell; } } <file_sep>package se.kth.csc.iprog.dinnerplanner.swing.view; import java.awt.BorderLayout; import java.awt.Dimension; import java.awt.Font; import java.awt.GridLayout; import java.util.ArrayList; import javax.swing.JButton; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JTextField; import se.kth.csc.iprog.dinnerplanner.model.DinnerModel; import se.kth.csc.iprog.dinnerplanner.model.Dish; public class ListAllPanel extends JPanel{ private static final long serialVersionUID = 1L; public JTextField searchText=new JTextField(); JScrollPane scroll; public JButton searchButton=new JButton("Search"); JPanel searchPanel=new JPanel(); public JPanel scrollContentPanel=new JPanel(); JPanel scrollBackgroundPanel=new JPanel(); Dish selectedItem=new Dish(); public int type; ArrayList<Dish> list; ArrayList<Dish> searchList=new ArrayList<Dish>(); DinnerModel model; boolean isSearch=false; String kw=null; public ListAllPanel(ArrayList<Dish> list,int type,DinnerModel m) { this.type=type; this.list=list; this.model=m; Font font=new Font("Britannic", Font.BOLD,20); this.setLayout(new BorderLayout()); this.searchPanel.setLayout(new BorderLayout()); this.setPreferredSize(new Dimension(Constants.tabWidth,Constants.height)); this.searchPanel.setPreferredSize(new Dimension(Constants.tabWidth, Constants.searchFieldHeight)); this.searchButton.setPreferredSize(new Dimension(Constants.searchButtonWidth, Constants.searchFieldHeight)); //this.searchButton.setFont(font); this.searchText.setPreferredSize( new Dimension(Constants.searchTextWidth, Constants.searchFieldHeight)); this.searchText.setFont(font); this.searchPanel.add(this.searchText,BorderLayout.WEST); this.searchPanel.add(this.searchButton,BorderLayout.CENTER); this.add(this.searchPanel, BorderLayout.NORTH); this.scrollContentPanel=new JPanel(); this.scrollBackgroundPanel.setPreferredSize(new Dimension(Constants.tabWidth, Constants.height)); ////////////////////////// this.scroll=new JScrollPane(this.scrollContentPanel,JScrollPane.VERTICAL_SCROLLBAR_ALWAYS, JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED); this.scroll.setBounds(0,0,Constants.tabWidth, Constants.scrollHeight); this.scroll.getVerticalScrollBar().setUnitIncrement(Constants.verticalScrollbarUnit); //this.scroll.setLayout(null); this.add(this.scrollBackgroundPanel,BorderLayout.CENTER); this.scrollBackgroundPanel.setLayout(new BorderLayout()); this.scrollBackgroundPanel.add(this.scroll, BorderLayout.CENTER); //////////////////////////////////////////////////// this.searchList.add(model.getAddMore(type));// add addMore icon } public void showThisDishOnly(Dish d,boolean search) { int itemNum=this.scrollContentPanel.getComponentCount(); for(int i=0;i<itemNum;i++) this.scrollContentPanel.remove(0); this.scrollContentPanel.setPreferredSize(new Dimension(Constants.dishDisplayWidth, Constants.dishDisplayHeight)); this.scrollContentPanel.setLayout(new GridLayout(2,Constants.dishNumInARow)); DishDisplayPanel r=new DishDisplayPanel(d,0,model,search,kw); this.scrollContentPanel.add(r); this.scrollContentPanel.setLayout(null); int width= Constants.dishDisplayWidth+10; int height=Constants.dishDisplayHeight+10; r.setBounds(0, 0,width,height);// French toast this.revalidate(); this.repaint(); } public void listAllDishes(ArrayList <Dish> dishList) { this.list=dishList; int itemNum=this.scrollContentPanel.getComponentCount(); for(int i=0;i<itemNum;i++) this.scrollContentPanel.remove(0); int num=dishList.size(); int remainder=num%Constants.dishNumInARow; int rowNum=num/Constants.dishNumInARow; if(remainder!=0) rowNum++; int contentPanelWidth=Constants.tabWidth-50; int contentPanelHeight=Constants.dishDisplayHeight*rowNum+ Constants.interDishDisplayMargin*(rowNum+1); this.scrollContentPanel.setLayout(new GridLayout(rowNum,Constants.dishNumInARow)); //this.scrollContentPnael.setLayout(new FlowLayout()); this.scrollContentPanel.setPreferredSize(new Dimension(contentPanelWidth, contentPanelHeight)); for(int i=0;i<num;i++) { DishDisplayPanel ddp=new DishDisplayPanel(dishList.get(i),i,model,false,kw); this.scrollContentPanel.add(ddp); } this.revalidate(); this.repaint(); } public void addNewDishToList(Dish dish) { if(!isSearch) { synchronized (list) { //list.add(list.size()-1,dish); int num=list.size(); int remainder=num%Constants.dishNumInARow; int rowNum=num/Constants.dishNumInARow; if(remainder!=0) rowNum++; int contentPanelWidth=Constants.tabWidth-50; int contentPanelHeight=Constants.dishDisplayHeight*rowNum+ Constants.interDishDisplayMargin*(rowNum+1); this.scrollContentPanel.setLayout(new GridLayout(rowNum,Constants.dishNumInARow)); //this.scrollContentPnael.setLayout(new FlowLayout()); this.scrollContentPanel.setPreferredSize(new Dimension(contentPanelWidth, contentPanelHeight)); this.scrollContentPanel.remove(num-2); DishDisplayPanel ddp=new DishDisplayPanel(dish,num-2,model,isSearch,kw); this.scrollContentPanel.add(ddp); this.scrollContentPanel.add(new DishDisplayPanel(list.get(num-1),num-1,model,isSearch,kw)); this.revalidate(); this.repaint(); } } else { // only add more icon in the list, show it if(searchList.size()==1) this.showThisDishOnly(model.getAddMore(type),isSearch); synchronized (searchList) { searchList.add(searchList.size()-1,dish); int num=searchList.size(); int remainder=num%Constants.dishNumInARow; int rowNum=num/Constants.dishNumInARow; if(remainder!=0) rowNum++; int contentPanelWidth=Constants.tabWidth-50; int contentPanelHeight=Constants.dishDisplayHeight*rowNum+ Constants.interDishDisplayMargin*(rowNum+1); this.scrollContentPanel.setLayout(new GridLayout(rowNum,Constants.dishNumInARow)); //this.scrollContentPnael.setLayout(new FlowLayout()); this.scrollContentPanel.setPreferredSize(new Dimension(contentPanelWidth, contentPanelHeight)); this.scrollContentPanel.remove(num-2); DishDisplayPanel ddp=new DishDisplayPanel(dish,num-2,model,isSearch,kw); this.scrollContentPanel.add(ddp); this.scrollContentPanel.add(new DishDisplayPanel(searchList.get(num-1),num-1,model,isSearch,kw)); this.revalidate(); this.repaint(); } } } public void loadNemImage(String name,String img) { if(!isSearch) { synchronized (list) { int num=list.size(); DishDisplayPanel dsp; for(int i=0;i<num;i++) { dsp=(DishDisplayPanel) this.scrollContentPanel.getComponent(i); if(dsp.getDish().getName().equals(name)) dsp.loadNewImage(img); } } } else { synchronized (searchList) { int num=searchList.size(); DishDisplayPanel dsp; for(int i=0;i<num;i++) { dsp=(DishDisplayPanel) this.scrollContentPanel.getComponent(i); if(dsp.getDish().getName().equals(name)) dsp.loadNewImage(img); } } } } public void clearList() { searchList=new ArrayList<Dish>(); searchList.add(model.getAddMore(type)); this.scrollContentPanel.setPreferredSize(new Dimension(0,0)); int itemNum=this.scrollContentPanel.getComponentCount(); for(int i=0;i<itemNum;i++) this.scrollContentPanel.remove(0); } public void setSearch(boolean b,String kw) { System.out.println(" lisat all panel "+kw); this.isSearch=b; this.kw=kw; } } <file_sep>package se.kth.csc.iprog.dinnerplanner.model; public class ChangeMessage { public final static int GuestNumChanged=0; public final static int MenuChanged=1; public final static int ToatalMenuCostCahnged=2; public final static int MenuCahngedForPreparation=3; public final static int ingredientsCahnged=4; public final static int listLoaded=5; public final static int dishLoaded=6; public final static int imageLoaded=7; public final static int currentLoadedNumChanged=8; public final static int loadingStateChanged=9; public final static int internetConnectionFailure=10; int type; Object value; public ChangeMessage (int t,Object v) throws Exception { if(t!=GuestNumChanged&&t!=MenuChanged&&t!=ToatalMenuCostCahnged&&t!=MenuCahngedForPreparation &&t!=ingredientsCahnged&&t!=listLoaded&&t!=dishLoaded&&t!=imageLoaded &&t!=currentLoadedNumChanged&&t!=loadingStateChanged&&t!=internetConnectionFailure) throw new Exception(); this.type=t; this.value=v; } public int getType() { return this.type; } public Object getData() { return value; } } <file_sep>package se.kth.csc.iprog.dinnerplanner.swing.view; import java.awt.BorderLayout; import java.awt.Dimension; import java.awt.Font; import java.awt.Image; import java.util.ArrayList; import java.util.Observable; import java.util.Observer; import javax.swing.BorderFactory; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JTextArea; import se.kth.csc.iprog.dinnerplanner.model.ChangeMessage; import se.kth.csc.iprog.dinnerplanner.model.Dish; /** * Created by Jiansun on 16/2/10. */ public class PreparationPanel extends JPanel implements Observer { private static final long serialVersionUID = 1L; JLabel title=new JLabel(); JLabel starter = new JLabel(); JLabel main = new JLabel(); JLabel desert = new JLabel(); JTextArea starterContent = new JTextArea(); JTextArea mainContent = new JTextArea(); JTextArea desertContent = new JTextArea(); JPanel topP = new JPanel(); JPanel midP = new JPanel(); JPanel bottP = new JPanel(); JScrollPane starterScroll; JScrollPane mainScroll; JScrollPane desertScroll; Dish dishStarter; Dish dishMain; Dish dishDesert; public PreparationPanel(Dish dishStarter,Dish dishMain,Dish dishDesert) { super(new BorderLayout()); this.setPreferredSize(new Dimension(Constants.preparationPanelWidth, Constants.preparationPanelHeight)); this.dishStarter=dishStarter; this.dishMain=dishMain; this.dishDesert=dishDesert; Font titleFont=new Font("Forte",Font.BOLD,32); Font nameFont=new Font("Segoe Print",Font.BOLD,22); Font descriptionFont=new Font("Segoe Print",Font.PLAIN,18); // The top layout title.setText("Dinner menu preparation"); title.setHorizontalAlignment(JLabel.CENTER); title.setPreferredSize(new Dimension(Constants.preparationPanelWidth, Constants.preparationPanelTitleHeight)); title.setFont(titleFont); starter.setText("Starter: "+dishStarter.getName()); starter.setHorizontalAlignment(JLabel.CENTER); starter.setVerticalAlignment(JLabel.CENTER); starter.setFont(nameFont); starter.setPreferredSize(new Dimension(Constants.preparationPanelWidth, Constants.preparationPanelNameHeight)); starterContent.setText(dishStarter.getDescription()); starterContent.setLineWrap(true); starterContent.setEditable(false); starterContent.setOpaque(false); starterContent.setFont(descriptionFont); starterContent.setSelectionStart(0); starterContent.setSelectionEnd(0); starterScroll=new JScrollPane(starterContent,JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED, JScrollPane.HORIZONTAL_SCROLLBAR_NEVER); starterScroll.setPreferredSize(new Dimension(Constants.preparationPanelWidth, Constants.preparationPanelDescriptionHeight)); starterScroll.setBorder(BorderFactory.createEmptyBorder(0, Constants.borderMargin, 0, Constants.borderMargin)); topP.setPreferredSize(new Dimension(Constants.preparationPanelWidth, Constants.preparationPanelTopHeight)); topP.setLayout(new BorderLayout()); topP.add(title,BorderLayout.NORTH); topP.add(starter,BorderLayout.CENTER); topP.add(starterScroll,BorderLayout.SOUTH); // The middle layout main.setPreferredSize(new Dimension(Constants.preparationPanelWidth, Constants.preparationPanelNameHeight)); main.setText("Main: "+dishMain.getName()); main.setHorizontalAlignment(JLabel.CENTER); main.setVerticalAlignment(JLabel.CENTER); main.setFont(nameFont); mainContent.setText(dishMain.getDescription()); mainContent.setLineWrap(true); mainContent.setEditable(false); mainContent.setOpaque(false); mainContent.setFont(descriptionFont); mainContent.setSelectionStart(0); mainContent.setSelectionEnd(0); mainScroll=new JScrollPane(mainContent,JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED, JScrollPane.HORIZONTAL_SCROLLBAR_NEVER); mainScroll.setPreferredSize(new Dimension(Constants.preparationPanelWidth, Constants.preparationPanelDescriptionHeight)); mainScroll.setBorder(BorderFactory.createEmptyBorder(0, Constants.borderMargin, 0, Constants.borderMargin)); midP.setPreferredSize(new Dimension(Constants.preparationPanelWidth, Constants.preparationPanelCenterHeight)); midP.setLayout(new BorderLayout()); midP.add(main,BorderLayout.NORTH); midP.add(mainScroll,BorderLayout.CENTER); desert.setText("Desert: "+dishDesert.getName()); desert.setHorizontalAlignment(JLabel.CENTER); desert.setVerticalAlignment(JLabel.CENTER); desert.setFont(nameFont); desertContent.setPreferredSize(new Dimension(Constants.preparationPanelWidth, Constants.preparationPanelDescriptionHeight)); desertContent.setText(dishDesert.getDescription()); desertContent.setLineWrap(true); desertContent.setEditable(false); desertContent.setOpaque(false); desertContent.setFont(descriptionFont); desertContent.setSelectionStart(0); desertContent.setSelectionEnd(0); desertScroll=new JScrollPane(desertContent,JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED, JScrollPane.HORIZONTAL_SCROLLBAR_NEVER); desertScroll.setPreferredSize(new Dimension(Constants.preparationPanelWidth, Constants.preparationPanelDescriptionHeight)); desertScroll.setBorder(BorderFactory.createEmptyBorder(0, Constants.borderMargin, 0, Constants.borderMargin)); bottP.setPreferredSize(new Dimension(Constants.preparationPanelWidth, Constants.preparetionPanelBottomHeight)); bottP.setLayout(new BorderLayout()); bottP.add(desert,BorderLayout.NORTH); bottP.add(desertScroll,BorderLayout.SOUTH); starterContent.setEditable(false); mainContent.setEditable(false); desertContent.setEditable(false); add(topP,BorderLayout.NORTH); add(midP,BorderLayout.CENTER); add(bottP,BorderLayout.SOUTH); } public void creatAndShowGUI(){ //creat and setup the window JFrame frame = new JFrame("Dinner Planner-Preparation"); frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); frame.setContentPane(this); frame.setBounds((Constants.widthDf-Constants.preparationPanelWidth)/2, (Constants.heightDf-Constants.preparationPanelHeight)/2,Constants.preparationPanelWidth, Constants.preparationPanelHeight); frame.pack(); frame.setVisible(true); Image img = this.getToolkit().getImage(Constants.windowIconDir); frame.setIconImage(img); } public void setDishes(ArrayList<Dish> list) { int num=list.size(); for(int i=0;i<num;i++) { if(list.get(i).getType()==Dish.STARTER) { this.dishStarter=list.get(i); } else if(list.get(i).getType()==Dish.MAIN) { this.dishMain=list.get(i); } else { this.dishDesert=list.get(i); } } starter.setText("Starter: "+dishStarter.getName()); main.setText("Main: "+dishMain.getName()); desert.setText("Desert: "+dishDesert.getName()); starterContent.setText(dishStarter.getDescription()); starterContent.setSelectionStart(0); starterContent.setSelectionEnd(0); mainContent.setText(dishMain.getDescription()); mainContent.setSelectionStart(0); mainContent.setSelectionEnd(0); desertContent.setText(dishDesert.getDescription()); desertContent.setSelectionStart(0); desertContent.setSelectionEnd(0); //System.out.println(starterContent); } @SuppressWarnings("unchecked") @Override public void update(Observable obs, Object obj) { ChangeMessage cm=(ChangeMessage) obj; if(cm.getType()==ChangeMessage.MenuCahngedForPreparation) { this.setDishes((ArrayList<Dish>)cm.getData()); } } } <file_sep>package se.kth.csc.iprog.dinnerplanner.swing.view; import java.awt.datatransfer.DataFlavor; import java.awt.datatransfer.Transferable; import java.awt.datatransfer.UnsupportedFlavorException; import java.io.IOException; import se.kth.csc.iprog.dinnerplanner.model.Dish; public class DishTransferable implements Transferable{ protected static DataFlavor dishFlavor=new DataFlavor(Dish.class,"A dish object"); protected static DataFlavor [] supportedFlavors= {dishFlavor,DataFlavor.stringFlavor}; Dish dish=new Dish(); public DishTransferable(Dish d) { this.dish=d; } @Override public Object getTransferData(DataFlavor df) throws UnsupportedFlavorException, IOException { if (df.equals(dishFlavor)) return dish; else if (df.equals(DataFlavor.stringFlavor)) return dish.toString(); else throw new UnsupportedFlavorException(df); } @Override public DataFlavor[] getTransferDataFlavors() { return supportedFlavors; } @Override public boolean isDataFlavorSupported(DataFlavor df) { int num=supportedFlavors.length; boolean support=false; for(int i=0;i<num;i++) { if(df.equals(supportedFlavors[i])) { support=true; break; } } return support; } }
1df211c8ad5ed688c0ac7fee6834587199722dbe
[ "Java" ]
17
Java
patrickwh/IPLAB2
dd06011d2927a33d7940751f08419227fb72c178
673307cbb0a30798af933aa112d01922ca967e76
refs/heads/main
<file_sep> import anndata as ad from pycdr.pycdr import run_CDR_analysis from pycdr.perm import calculate_enrichment from enrichment_utils.ontology_analysis import analyse_adata INPUT = snakemake.input[0] INPUT_FILE_GENE2GO = snakemake.input[1] INPUT_FILE_ONTOLOGY = snakemake.input[2] OUTPUT_enrichment = snakemake.output[0] OUTPUT_enrichment_proportions = snakemake.output[1] mono = ad.read(INPUT) #run_CDR_analysis(mono, "stim") analyse_adata(mono, INPUT_FILE_ONTOLOGY, INPUT_FILE_GENE2GO, "human", threshold_pvalue = 0.05, ontology_subset = "BP", prop = False) mono.write(OUTPUT_enrichment) factor_list = [i for i in mono.uns["factor_loadings"].keys()] calculate_enrichment(mono, "stim", factor_list, 100, "features", 0.05) mono.write(OUTPUT_enrichment_proportions) <file_sep>#!/usr/bin/env python # coding: utf-8 import anndata as ad import pandas as pd import glob import os # get list of CD8 T cells CD8Tcells = pd.read_csv(snakemake.input[0])["Cell Name"] # parse raw file to get colnames rawfile = pd.read_csv(snakemake.input[2], nrows = 0, skiprows=0, engine = "python", sep = "\t", index_col=False) colnames_of_raw_datafile = rawfile.columns.to_list() colnames_of_raw_datafile.pop(0) chunksize = 1000 with pd.read_csv(snakemake.input[1], chunksize=chunksize, sep = '\t', header = None, index_col=0) as reader: for i, chunk in enumerate(reader): a = chunk.drop(16292, axis = 1) a.index.name = "genes" a.astype('float64') a.columns = colnames_of_raw_datafile select_relevant_cells = a.columns[a.columns.isin(CD8Tcells)] processed_chunked = a[select_relevant_cells] chunk_filename = "chunk" + str(i) + ".csv" processed_chunked.to_csv(chunk_filename) csv_chunks = glob.glob("*.csv") new = pd.concat([pd.read_csv(i) for i in csv_chunks]) new = new.set_index("genes") [os.remove(i) for i in csv_chunks] new.to_pickle(snakemake.output[0]) <file_sep> import anndata as ad from pycdr.pycdr import run_CDR_analysis INPUT = snakemake.input[0] OUTPUT = snakemake.output[0] mono = ad.read(INPUT) run_CDR_analysis(mono, "stim") mono.write(OUTPUT) <file_sep>#!/usr/bin/env python # coding: utf-8 import anndata as ad import scanpy as sc from pycdr.utils import filter_genecounts_percent import numpy as np tirosh = ad.read(snakemake.input[0]) sade_felman = ad.read(snakemake.input[1]) sc.pp.log1p(sade_felman) sc.pp.log1p(tirosh) sc.pp.highly_variable_genes(sade_felman) sc.pp.highly_variable_genes(tirosh) sade_felman = sade_felman[:, sade_felman.var.highly_variable] tirosh = tirosh[:, tirosh.var.highly_variable] sc.pp.scale(sade_felman, zero_center = False) sc.pp.scale(tirosh, zero_center = False) combined_dataset = sade_felman.concatenate(tirosh) combined_dataset.obs.dropna(axis = 1, inplace=True) combined_dataset.var["features"] = combined_dataset.var["features-1"] combined_dataset_filtered = filter_genecounts_percent(combined_dataset, 0.01, 1) combined_dataset_filtered = combined_dataset_filtered.copy() print("dimensions: ", str(combined_dataset_filtered.shape)) combined_dataset_filtered.write(snakemake.output[0]) <file_sep> # Spectral detection of condition-specific biological pathways in single-cell gene expression data. This repository contains the snakemake workflows required to generate the results in the CDR-g manuscript. These workflows contain steps that are containerised. Therefore, involve the --run-singularity flag when runnin snakemake. # Recommended dependencies: Scanpy, bbknn and enrichment_utils are required for data proprocessing and visualisation of results. Please refer to the [CDR-g page](https://github.com/wlchin/pycdr) for additional installation information. # Functional annotation - required file versions Enrichment analysis in these workflows depends on the PANTHER GO-ontology (version 16.0) and the NCBI gene2go (dated 2022-01-03). These files are provided in this repository. <file_sep> import anndata as ad from pycdr.pycdr import run_CDR_analysis from pycdr.perm import calculate_enrichment from enrichment_utils.ontology_analysis import analyse_adata INPUT = snakemake.input[0] INPUT_FILE_GENE2GO = snakemake.input[1] INPUT_FILE_ONTOLOGY = snakemake.input[2] OUTPUT = snakemake.output[0] x = ad.read(INPUT) run_CDR_analysis(x, "Hours") analyse_adata(x, INPUT_FILE_ONTOLOGY, INPUT_FILE_GENE2GO, "human", threshold_pvalue = 0.05, ontology_subset = "BP", prop = False) factor_list = [i for i in x.uns["factor_loadings"].keys()] calculate_enrichment(x, "Hours", factor_list, 100, "gene_short_name", 0.05) x.write(OUTPUT) <file_sep>import anndata as ad import pandas as pd INPUT_CDR = snakemake.input[0] INPUT_DE_LIST = snakemake.input[1] OUTPUT_CDR_ONLY = snakemake.output[1] OUTPUT_DE_ONLY = snakemake.output[2] OUTPUT_INTERSECTION_ONLY = snakemake.output[0] def retrieve_terms_for_selected_factors(x, factorlist): # earmarked removal move to other package en = x.uns["enrichment_results"] terms = [] for i in factorlist: termie = en[i] terms.append(termie) flat_list = set([item for sublist in terms for item in sublist]) len(set(flat_list)) return set(flat_list) CDR_obj = ad.read(INPUT_CDR) factor_list = [i for i in CDR_obj.uns["factor_loadings"].keys()] CDR_set = retrieve_terms_for_selected_factors(CDR_obj, factor_list) other = pd.read_csv(INPUT_DE_LIST) DEset = set(other.Terms) len(CDR_set), len(DEset - CDR_set), len(CDR_set - DEset) pd.DataFrame(CDR_set - DEset).to_csv(OUTPUT_CDR_ONLY) pd.DataFrame(DEset - CDR_set).to_csv(OUTPUT_DE_ONLY) pd.DataFrame(DEset.intersection(CDR_set)).to_csv(OUTPUT_INTERSECTION_ONLY) <file_sep>#!/usr/bin/env python # coding: utf-8 import anndata as ad import seaborn as sns import pandas as pd import numpy as np from pycdr.utils import get_top_genes import matplotlib.pyplot as plt import matplotlib.patheffects as path_effects import scanpy as sc # specific details for scatterplot #['factor.1002', 'factor.1553', 'factor.976'] coords_1002 = [(0,20), (0,20), (0,20), (0,20), (0,20)] coords_1553 = [(0,20), (40,0), (25,25), (-25,20), (0,-30)] coords_976 = [(0,20), (40,0), (40,0), (-25,20), (0,-30)] def process_data_for_barplots(x, factor_of_interest, degenes, geneindex): genesofinterest = get_top_genes(x, factor_of_interest).sort_values("z_score", ascending = False) genes = genesofinterest.head(20).index.to_list() loadingscores = get_top_genes(x, factor_of_interest).sort_values("z_score", ascending = False) scores = loadingscores.head(20).z_score.to_list() color_list = [] genes_plotting = pd.DataFrame(zip(genes, scores), index = genes).reindex(geneindex) Product = genes_plotting[0] for i in Product: if i in degenes.to_list(): color_list.append("black") else: color_list.append("white") Quantity = genes_plotting[1] return Product, Quantity, color_list def plot_barplots(Product, Quantity, color_list, filename): fig, ax = plt.subplots(figsize=(2,5)) # Horizontal Bar Plot ax.barh(Product, Quantity, color = color_list, edgecolor = "black") ax.invert_yaxis() ax.spines['top'].set_visible(False) ax.spines['right'].set_visible(False) ax.spines['bottom'].set_visible(True) ax.spines['left'].set_visible(False) import matplotlib.ticker as ticker ax.xaxis.set_major_locator(ticker.MultipleLocator(10)) ax.grid(axis='x') #plt.ylabel('Gene') plt.xlabel('Z-scores', fontsize = "x-large") plt.tight_layout() plt.savefig(filename, dpi = 300) def process_data_for_scatterplot(x, factor, genelist, pheno1, pheno2): #factor_ = "factor." + str(factor) ctrl = x[x.obs[factor] == pheno1].copy() stim = x[x.obs[factor] == pheno2].copy() genesstim = sc.pp.calculate_qc_metrics(stim)[1] genesctrl = sc.pp.calculate_qc_metrics(ctrl)[1] factor0 = genelist stimcounts = genesstim[genesstim.index.isin(factor0)].log1p_mean_counts nonstimcounts = genesctrl[genesctrl.index.isin(factor0)].log1p_mean_counts x1 = stimcounts y1 = nonstimcounts return stimcounts, nonstimcounts def process_data_for_heatmaps(x, factor_of_interest): genes = get_top_genes(x, factor_of_interest).sort_values("z_score", ascending = False) genesofinterest = genes.head(20).index.to_list() inder = x.var.features.isin(genesofinterest) responder_adata = x[x.obs.stim == "STIM",inder] nonresponder_adata = x[x.obs.stim == "CTRL",inder] responder_adata_mat = responder_adata.X.toarray() nonresponder_adata_mat = nonresponder_adata.X.toarray() corr = np.corrcoef(responder_adata_mat.T) corr2 = np.corrcoef(nonresponder_adata_mat.T) resp = pd.DataFrame(corr) resp.columns = responder_adata.var.index resp.index = responder_adata.var.index nonresp = pd.DataFrame(corr2) nonresp.columns = nonresponder_adata.var.index nonresp.index = nonresponder_adata.var.index p = sns.clustermap(resp) order = p.dendrogram_row.reordered_ind geneindex = resp.columns[order] nonresp = nonresp.reindex(geneindex, axis=1) nonresp = nonresp.reindex(geneindex, axis=0) resp = resp.reindex(geneindex, axis=1) resp = resp.reindex(geneindex, axis=0) return resp, nonresp, genesofinterest def plot_heatmaps(resp, nonresp, filename, thres = 0.10): fig, (ax1, ax2) = plt.subplots(1,2, figsize = (10,5), gridspec_kw={'width_ratios': [1, 1]}) sns.heatmap( resp, square=True, cmap = 'RdBu_r', vmax = thres, ax = ax1, cbar = None, ) sns.heatmap( nonresp, square= True, cmap = 'RdBu_r', vmax = thres, ax = ax2, cbar = None, yticklabels=False ) ax1.set_title("IFN-stimulated", fontsize = "x-large") ax2.set_title("Control", fontsize = "x-large") plt.tight_layout() plt.savefig(filename, dpi = 300) def plot_scatterplot(X, Y, genes, filename): fig, ax = plt.subplots(figsize = (5,5)) #ax.plot(x, y, ls='--', color = 'red') #X = a #Y = b X = X.reindex(genes) Y = Y.reindex(genes) toplevel = np.max([X,Y]) #toplevel = np.round(np.max([X,Y]), 1) plt.ylim(-0.05, toplevel + 0.05) plt.xlim(-0.05, toplevel + 0.05) plt.xticks(np.arange(0, toplevel + 0.05, 0.1)) plt.yticks(np.arange(0, toplevel + 0.05, 0.1)) ax.grid() I = 5 Px = X[0:I] Py = Y[0:I] ax.scatter(X, Y, edgecolor="None", facecolor="gray", alpha=0.5) ax.scatter(Px, Py, edgecolor="black", facecolor="white", zorder=20) ax.scatter(Px, Py, edgecolor="black", facecolor="C1", alpha=0.5, zorder=30) plt.plot([0, toplevel], [0, toplevel], ls='--', color = 'red') # plots line y = x y, dy = 1.0, 0.125 style = "arc,angleA=-0,angleB=0,armA=-100,armB=0,rad=0" GENENAMES = X.index.to_list() for i in range(I): text = ax.annotate( GENENAMES[i], xy=(Px[i], Py[i]), xycoords="data", xytext=(0, 20), textcoords="offset points", ha="center", size="large", arrowprops=dict( arrowstyle="->", shrinkA=0, shrinkB=5, color="black", linewidth=0.75 ), ) text.set_path_effects( [path_effects.Stroke(linewidth=2, foreground="white"), path_effects.Normal()] ) text.arrow_patch.set_path_effects( [path_effects.Stroke(linewidth=2, foreground="white"), path_effects.Normal()] ) plt.xlabel("log1p expression: CTRL monocytes", fontsize = "large") plt.ylabel("log1p expression: STIM monocytes", fontsize = "large") plt.title("Key genes in factor loading", fontsize = "x-large") #ax.spines['top'].set_linestyle((0, (10, 10))) #ax.spines['right'].set_linestyle((0, (10, 10, 1, 10))) plt.savefig(filename, dpi = 300) x = ad.read(snakemake.input[0]) degenes = pd.read_csv(snakemake.input[1])["0"] a,b,c = process_data_for_heatmaps(x, 976) plot_heatmaps(a,b, "results/heatmaps_976.png", 0.15) e,f,g = process_data_for_barplots(x, 976, degenes, a.index) plot_barplots(e,f,g, "results/barplot_976.png") h, i = process_data_for_scatterplot(x, "stim", c, "CTRL", "STIM") plot_scatterplot(i, h, c, "results/scaterplot_976.png") a,b,c = process_data_for_heatmaps(x, 1002) plot_heatmaps(a,b, "results/heatmaps_1002.png", 0.15) e,f,g = process_data_for_barplots(x, 1002, degenes, a.index) plot_barplots(e,f,g, "results/barplot_1002.png") h, i = process_data_for_scatterplot(x, "stim", c, "CTRL", "STIM") plot_scatterplot(i, h, c, "results/scaterplot_1002.png") a,b,c = process_data_for_heatmaps(x, 1553) plot_heatmaps(a,b, "results/heatmaps_1553.png", 0.15) e,f,g = process_data_for_barplots(x, 1553, degenes, a.index) plot_barplots(e,f,g, "results/barplot_1553.png") h, i = process_data_for_scatterplot(x, "stim", c, "CTRL", "STIM") plot_scatterplot(i, h, c, "results/scaterplot_1553.png") <file_sep>#!/usr/bin/env python # coding: utf-8 # In[2]: import anndata as ad import pandas as pd # In[3]: tpm = ad.read_csv(snakemake.input[0]) # In[4]: onlyyou = tpm.T # In[5]: #onlyyou.write("cleantirosh.h5ad") # In[6]: hum = pd.read_csv(snakemake.input[1]) # In[7]: hum.index = hum.cells # In[8]: onlyyou.obs = hum # In[9]: onlyyou.obs.index.name = "features" # In[10]: onlyyou.var["features"] = onlyyou.var.index # In[11]: onlyyou.obs["cell.types"].unique() # In[12]: CD8only = onlyyou[onlyyou.obs["cell.types"] == "T.CD8"] # In[14]: CD8only.obs["response_pheno"] = CD8only.obs["treatment.group"] # In[16]: CD8only.write(snakemake.output[0]) # In[17]: CD8only <file_sep>#!/usr/bin/env python # coding: utf-8 import pandas as pd import anndata as ad import scanpy as sc from pycdr.utils import get_top_genes from pycdr.perm import calculate_enrichment import matplotlib.ticker as ticker import numpy as np import matplotlib.pyplot as plt muscle = ad.read(snakemake.input[0]) calculate_enrichment(muscle, "Hours", ["factor.1", "factor.0", "factor.8", "factor.5", "factor.7", "factor.54", "factor.8"], 100, "features", 0.1, 19) sc.pp.scale(muscle, max_value=10) sc.tl.pca(muscle, svd_solver='arpack') sc.pp.neighbors(muscle, n_neighbors = 20, n_pcs=40) sc.tl.umap(muscle) sc.pl.umap(muscle, color = ["factor.8", "factor.7", "Hours"], add_outline = True, size = 200) muscle.obs["Hours"] = muscle.obs["Hours"].astype("category") muscle.write(snakemake.output[0]) <file_sep> import anndata as ad from pycdr.utils import filter_genecounts_numcells, filter_genecounts_percent import scanpy as sc mono = ad.read(snakemake.input[0]) mono = filter_genecounts_percent(mono, 0.01, 1) mono = filter_genecounts_numcells(mono, 0, 100) mono.raw = mono.raw.to_adata() sc.pp.log1p(mono) sc.pp.scale(mono, zero_center = False) mono.write(snakemake.output[0]) <file_sep>#!/usr/bin/env python # coding: utf-8 import pandas as pd import anndata as ad import scanpy as sc from pycdr.perm import calculate_enrichment muscle = ad.read(snakemake.input[0]) calculate_enrichment(muscle, "Hours", ["factor.1", "factor.0", "factor.8", "factor.5", "factor.7", "factor.54", "factor.8"], 100, "features", 0.1, 42) #sc.pp.scale(muscle, max_value=10) sc.tl.pca(muscle, svd_solver='arpack') sc.pp.neighbors(muscle, n_neighbors = 20, n_pcs=50) sc.tl.umap(muscle, random_state = 7) muscle.obs["Hours"] = muscle.obs["Hours"].astype("category") sc.set_figure_params(scanpy=True, dpi=80, dpi_save=600, format='png') sc.pl.umap(muscle, color = ["factor.8", "factor.7", "Hours"], add_outline = True, size = 200, save="muscle") muscle.write(snakemake.output[0]) <file_sep>import scanpy as sc import anndata as ad from pycdr.utils import filter_genecounts_numcells, filter_genecounts_percent muscle = ad.read(snakemake.input[0]) muscle.var_names_make_unique() muscle.var["features"] = muscle.var["gene_short_name"] filtered_by_numcells = filter_genecounts_numcells(muscle, 1, 50) sc.pp.log1p(filtered_by_numcells) sc.pp.scale(filtered_by_numcells, zero_center = False) filtered_by_numcells.write(snakemake.output[0]) <file_sep>#!/usr/bin/env python # coding: utf-8 import anndata as ad from pycdr.pycdr import run_CDR_analysis from enrichment_utils.ontology_analysis import analyse_adata x = ad.read(snakemake.input[0]) run_CDR_analysis(x, "response_pheno") analyse_adata(x, snakemake.input[1], snakemake.input[2], "human", threshold_pvalue = 0.05, ontology_subset = "BP", prop = False) x.write(snakemake.output[0]) <file_sep>#!/usr/bin/env python # coding: utf-8 import scanpy as sc import pandas as pd phenodata = pd.read_csv(snakemake.input[0], sep = "\t", header = 0, index_col=0) clean = phenodata[phenodata.columns[0:6]] clean.index = clean.title otheraddtional = clean["characteristics: patinet ID (Pre=baseline; Post= on treatment)"].str.split("_", expand = True) clean["stage"] = otheraddtional[0] clean["res"] = clean["characteristics: response"] + "_" + clean["stage"] # create anndata from pickled df genedf = pd.read_pickle(snakemake.input[1]) sade_felman = sc.AnnData(genedf) sade_felman = sade_felman.T sade_felman.obs["title"] = sade_felman.obs.index pheno_reduced = clean[clean.title.isin(sade_felman.obs.index)] pheno_reduced.index.name = "cell" sade_felman.obs = sade_felman.obs.merge(pheno_reduced) sade_felman.obs.index = sade_felman.obs.title sade_felman.obs.index.name = "cellnames" df = clean[clean.index.isin(sade_felman.obs.index)] sade_felman.obs["response_pheno"] = df["res"] sade_felman.write(snakemake.output[0]) sade_felman.obs.to_csv(snakemake.output[1]) <file_sep>#!/usr/bin/env python # coding: utf-8 import anndata as ad import scanpy as sc import numpy as np import bbknn from pycdr.perm import calculate_enrichment sc.set_figure_params(dpi_save = 300) adata_all = ad.read(snakemake.input[0]) calculate_enrichment(adata_all, "response_pheno", ["factor.169", "factor.1192", "factor.10", "factor.13"], 100, "features", 0.10, 19) sc.tl.pca(adata_all) bbknn.bbknn(adata_all, batch_key = "batch") sc.tl.leiden(adata_all) bbknn.ridge_regression(adata_all, batch_key=['batch'], confounder_key=['leiden']) sc.tl.pca(adata_all) sc.pp.neighbors(adata_all, n_neighbors=30, n_pcs=25) sc.tl.leiden(adata_all, resolution = 1.0) sc.tl.tsne(adata_all) sc.pl.tsne(adata_all, color=["leiden", "factor.1192", "MT1E"], legend_loc='on data', save = "_MT1E.png") cl1 = adata_all[adata_all.obs['leiden'].isin(["5"]),:] sc.tl.rank_genes_groups(cl1, "factor.1192", method="wilcoxon") sc.pl.rank_genes_groups(cl1, n_genes=25, sharey=False, save="_DEresult.png") adata_all.obs["Exhaustion"] = adata_all.obs["factor.13"] adata_all.obs["Cell division"] = adata_all.obs["factor.10"] adata_all.obs["IFN response"] = adata_all.obs["factor.169"] adata_all.obs["Hypoxia"] = adata_all.obs["factor.1192"] sc.pl.tsne(adata_all, color = ["Exhaustion", "TIGIT", "PDCD1", "Cell division", "CDK1", "CDCA8", "IFN response", "MX1", "IFI44L", "Hypoxia", "BAD", "CCNB1"], ncols=3, wspace = 0.3, save = "_genesets.png", legend_loc = None) sc.tl.leiden(adata_all, resolution = 5.0) # 3 and 15 for this. sc.pl.tsne(adata_all, color=["leiden"], save="leidenbignonum.png") cl1 = adata_all[adata_all.obs['leiden'].isin(["1", "6", "19"]),:] sc.tl.rank_genes_groups(cl1, "leiden", method="wilcoxon") sc.pl.rank_genes_groups(cl1, n_genes=25, sharey=False, save="_DEresult_multicluster.png")<file_sep>import pandas as pd import anndata as ad import scanpy as sc from pycdr.utils import get_top_genes from pycdr.perm import calculate_enrichment import matplotlib.ticker as ticker import numpy as np import matplotlib.pyplot as plt adata = ad.read(snakemake.input[0]) factors = ["factor.1", "factor.5", "factor.54","factor.0"] factor_nums = [1,5,54,0] fig, ax = plt.subplots(1,4, figsize = (9,3)) for i in range(4): factor_loading = factors[i] info = adata.uns["dict_res_prop"][factor_loading] timepoints = np.array(info[2]).astype("str") vals = (np.array(info[0]).astype("int"))/(np.array(info[1]).astype("int")) * 100 ax[i].bar(timepoints,vals, color = "black") ax[i].set_xlabel("Hours", fontsize = "x-large") ax[i].set_title(factor_loading, fontsize = "x-large", pad=10) ax[i].set_ylim((0,35)) ax[i].spines['top'].set_visible(False) ax[i].spines['right'].set_visible(False) ax[i].spines['bottom'].set_visible(True) fig.supylabel("% activated cells", fontsize = "xx-large") plt.savefig("results/muscle_factors.png", dpi = 600) fig, ax = plt.subplots(1,4, figsize = (9,6)) for i in range(4): factor_id = factor_nums[i] top20 = get_top_genes(adata, factor_id).sort_values("z_score", ascending = False).head(20) genesofinterest = top20.index.to_list() loadingscores = top20.z_score.to_list() ax[i].barh(genesofinterest, loadingscores, edgecolor = "black") ax[i].invert_yaxis() ax[i].spines['top'].set_visible(False) ax[i].spines['right'].set_visible(False) ax[i].spines['bottom'].set_visible(True) ax[i].spines['left'].set_visible(False) ax[i].xaxis.set_major_locator(ticker.MultipleLocator(2)) ax[i].grid(axis='x') ax[i].set_xlabel('Z-scores') fig.supylabel("Top genes in factor loading", fontsize = "xx-large") fig.tight_layout(pad = 4.0) plt.savefig("results/muscle_genes.png", dpi = 300) factors = ["factor.7", "factor.8"] fig, ax = plt.subplots(1,2, figsize = (9,3)) for i in range(2): factor_loading = factors[i] info = adata.uns["dict_res_prop"][factor_loading] timepoints = np.array(info[2]).astype("str") vals = (np.array(info[0]).astype("int"))/(np.array(info[1]).astype("int")) * 100 ax[i].bar(timepoints,vals, color = "black") ax[i].set_xlabel("Hours", fontsize = "x-large") ax[i].set_title(factor_loading, fontsize = "x-large", pad=10) ax[i].set_ylim((0,35)) ax[i].spines['top'].set_visible(False) ax[i].spines['right'].set_visible(False) ax[i].spines['bottom'].set_visible(True) fig.supylabel("% activated cells", fontsize = "xx-large") fig.savefig("results/bar_chart_subpopulations.png", dpi = 500) <file_sep>import anndata as ad import scanpy as sc import pandas as pd from enrichment_utils.ontology_analysis import analyse_list INPUT_FILE = snakemake.input[0] INPUT_FILE_GENE2GO = snakemake.input[1] INPUT_FILE_ONTOLOGY = snakemake.input[2] OUTPUT_DE_ENRICHMENT_LOW = snakemake.output[0] OUTPUT_DE_ENRICHMENT_HIGH = snakemake.output[1] OUTPUT_DE_LIST_LOW = snakemake.output[2] OUTPUT_DE_LIST_HIGH = snakemake.output[3] def get_DE_genes(adata, factor, pheno1, pheno2, lfc, fdr): adata.var_names_make_unique() adata_filtered = adata[(adata.obs[factor] == pheno1) | (adata.obs[factor] == pheno2)] adata_filtered.obs[factor] = adata_filtered.obs[factor].astype("string") sc.tl.rank_genes_groups(adata_filtered, factor, method='wilcoxon', key_added = "wilcoxon") wcup = sc.get.rank_genes_groups_df(adata_filtered, group=pheno1, key='wilcoxon', pval_cutoff=fdr, log2fc_min=lfc)['names'] wcdown = sc.get.rank_genes_groups_df(adata_filtered, group=pheno1, key='wilcoxon', pval_cutoff=fdr, log2fc_max = -lfc)['names'] upgenes = wcup.to_list() downgenes = wcdown.to_list() comb = upgenes + downgenes return comb, upgenes, downgenes def combine_output_of_lists(set1, set2, outputfile): import pandas as pd set1 = set(set1) set2 = set(set2) listo = set1.union(set2) x = pd.DataFrame(listo) x.columns = ["Terms"] x.to_csv(outputfile) x = ad.read(INPUT_FILE) adata = x.raw.to_adata() # remember that sc.pp.normalize_total(adata, target_sum=1e4) sc.pp.log1p(adata) x.raw = adata a,b,c = get_DE_genes(x, "stim", "CTRL", "STIM", 0.5, 0.1) # low log e,f,g = get_DE_genes(x, "stim", "CTRL", "STIM", 1.0, 0.05) # strict gos, enrichment1_low = analyse_list(a, INPUT_FILE_ONTOLOGY, INPUT_FILE_GENE2GO, "human") gos, enrichment2_low = analyse_list(b, INPUT_FILE_ONTOLOGY, INPUT_FILE_GENE2GO, "human") gos, enrichment3_high = analyse_list(e, INPUT_FILE_ONTOLOGY, INPUT_FILE_GENE2GO, "human") gos, enrichment4_high = analyse_list(f, INPUT_FILE_ONTOLOGY, INPUT_FILE_GENE2GO, "human") combine_output_of_lists(enrichment1_low, enrichment2_low, OUTPUT_DE_ENRICHMENT_LOW) combine_output_of_lists(enrichment3_high, enrichment4_high, OUTPUT_DE_ENRICHMENT_HIGH) high_thres = pd.DataFrame(g) high_thres.to_csv(OUTPUT_DE_LIST_HIGH) low_thres = pd.DataFrame(c) low_thres.to_csv(OUTPUT_DE_LIST_LOW)
69a231a4737e3fdfcceab0a577b7d02260c3d74f
[ "Markdown", "Python" ]
18
Python
wlchin/CDR_workflows
cc0492da06f5cb1974fb801547de06d17e60fc18
6acb51163aded32e8b13f9096e755045190df0f5
refs/heads/main
<repo_name>Macflash/woodwork<file_sep>/README.md ## WoodWork Work with wood. 3D CAD modeling optimized for working with lumber! Supports dimensional lumber and sheet lumber. Give it a go at [https://macflash.github.io/woodwork](https://macflash.github.io/woodwork).<file_sep>/src/actions/operation.ts import { Vector3 } from "three"; import { Board } from "../lumber/board"; // Each board can have a series of operations performed once it is created. export type OperationType = "MOVE" | "ADD"; // UX Operation also has some Menus or other things associated with it. export interface Operation { type: OperationType; } export interface Step { // Needs some MENU // and probably some rendering logic } export interface Move extends Operation { getMove(): Vector3; } export class Translate implements Move { readonly type = "MOVE"; constructor(private vector: Vector3) { } getMove() { return this.vector; } } export class Attach implements Move { readonly type = "MOVE"; constructor(private board: Board, private vertex: number) { } getMove() { return this.board.vertices[this.vertex]; } }<file_sep>/src/lumber/board.ts import { addLine, getScene, getScale, addPoints } from "../3d/threetest"; import * as THREE from 'three'; import { Vector3 } from "three"; const Origin = new Vector3(); const boards: Board[] = []; var pendingBoard: Board | null = null; export function getPendingBoard() { return pendingBoard; } export function setPendingBoard(board: Board|null) { pendingBoard = board; pendingBoard?.drawToScene(); } function getNewBoardName() { return `Board-${boards.length}`; } export function getSelectionLength() { return getBoards().filter(b => b.selected).length; } export function clearSelection() { getBoards().forEach(b => b.unselect()); } export function getBoards() { return boards; } export function getBoardByName(name: string) { return boards.find(b => b.name === name); } export class Board { readonly name = getNewBoardName(); private line: THREE.Line | null = null; public hovered = false; public selected = false; public vertices: Vector3[] = this.createVerts(); constructor(public width: number, public height: number, public length: number, public origin: Vector3 = Origin, private pending = false) { boards.push(this); } setOrigin(origin: Vector3) { this.vertices.forEach(v => v.subVectors(v, this.origin)); this.origin = origin; this.vertices.forEach(v => v.addVectors(v, this.origin)); this.updateGeometry(); } private createVerts() { const verts: Vector3[] = []; // front face verts.push(new Vector3(0, 0, 0)); verts.push(new Vector3(this.width, 0, 0)); verts.push(new Vector3(this.width, this.height, 0)); verts.push(new Vector3(0, this.height, 0)); verts.push(new Vector3(0, 0, this.length)); verts.push(new Vector3(0, this.height, this.length)); verts.push(new Vector3(this.width, this.height, this.length)); verts.push(new Vector3(this.width, 0, this.length)); return verts.map(v => v.add(this.origin)); } updateGeometry(){ var points = this.getLinePoints(); this.line!.geometry = new THREE.BufferGeometry().setFromPoints(points); } updateColor() { if (this.pending) { if(this.line! instanceof THREE.LineDashedMaterial){return;} this.line!.material = new THREE.LineDashedMaterial({ color: 0xFFFF00 }); this.line?.computeLineDistances(); } else if (this.selected) { this.line!.material = new THREE.LineBasicMaterial({ color: 0xFF0066 }); } else if (this.hovered) { this.line!.material = new THREE.LineBasicMaterial({ color: 0x00FFFF }); } else { this.line!.material = new THREE.LineBasicMaterial({ color: 0x00FF66 }); } } select() { this.selected = true; this.updateColor(); } unselect() { this.selected = false; this.updateColor(); } hover() { this.hovered = true; this.updateColor(); } unhover() { this.hovered = false; this.updateColor(); } fix(){ this.pending = false; addLine(this.line!); // how can we remove these later?? Just remove all and re-add from boards?? return this; } hide(){ this.line!.visible = false; } show(){ this.line!.visible = true; } drawToScene() { const scene = getScene(); const points = this.getPoints(); //scene.add(points); //addPoints(points); const line = this.getLines(); line.computeLineDistances(); scene.add(line); if(!this.pending){ addLine(line); } //addLine(line); function animate() { requestAnimationFrame(animate); //line.rotateZ(.005); //line.rotateY(.001); } //animate(); this.updateColor(); return this; } getPoints() { var dotGeometry = new THREE.Geometry(); dotGeometry.vertices.push(this.vertices[0]); dotGeometry.vertices.push(this.vertices[1]); dotGeometry.vertices.push(this.vertices[2]); dotGeometry.vertices.push(this.vertices[3]); dotGeometry.vertices.push(this.vertices[4]); dotGeometry.vertices.push(this.vertices[5]); dotGeometry.vertices.push(this.vertices[6]); dotGeometry.vertices.push(this.vertices[7]); var dotMaterial = new THREE.PointsMaterial({ size: 2, sizeAttenuation: false }); var dots = new THREE.Points(dotGeometry, dotMaterial); return dots; } getLinePoints() { var points = []; points.push(this.vertices[0]); points.push(this.vertices[4]); points.push(this.vertices[5]); points.push(this.vertices[3]); points.push(this.vertices[0]); points.push(this.vertices[1]); points.push(this.vertices[7]); points.push(this.vertices[4]); points.push(this.vertices[7]); points.push(this.vertices[6]); points.push(this.vertices[5]); points.push(this.vertices[6]); points.push(this.vertices[2]); points.push(this.vertices[1]); points.push(this.vertices[2]); points.push(this.vertices[3]); return points; } getLines() { var points = this.getLinePoints(); var geometry = new THREE.BufferGeometry().setFromPoints(points); var material = new THREE.LineBasicMaterial({ color: 0x00FF66 }); var line = new THREE.Line(geometry, material); line.name = this.name; this.line = line; return line; } rotateX(angle?: number) { console.log("angle", angle); angle = angle === undefined ? (Math.PI / 2) : angle; console.log("used angle", angle); this.vertices.forEach(v => v.subVectors(v, this.origin).applyAxisAngle(new Vector3(1, 0, 0), angle === undefined ? (Math.PI / 2) : angle).addVectors(v, this.origin)); return this; } rotateY(angle?: number) { this.vertices.forEach(v => v.subVectors(v, this.origin).applyAxisAngle(new Vector3(0, 1, 0), angle === undefined ? (Math.PI / 2) : angle).addVectors(v, this.origin)); return this; } rotateZ(angle?: number) { this.vertices.forEach(v => v.subVectors(v, this.origin).applyAxisAngle(new Vector3(0, 0, 1), angle === undefined ? (Math.PI / 2) : angle).addVectors(v, this.origin)); return this; } }<file_sep>/src/actions/add_lumber/dimensional.ts import { Operation } from "../operation"; export class AddDimensionalLumber implements Operation { readonly type = "ADD"; constructor(private height: number, private width: number){} // needs a starting point step1_SetOriginPoint(){} // needs another point to set the orientation of the small face. step2_SetSecondPoint(){} // could possibly MOVE the board a fixed distance from here. // Sets the length of the board step3_SetLength(){} // Pick which scrap piece it comes from }<file_sep>/src/app/styles.ts import * as React from 'react'; export const color = "#00FF88"; export const border = `1px solid ${color}`; export const rowStyle: React.CSSProperties = { display: "flex", flexDirection: 'row' };<file_sep>/src/renderHelper.ts var renderer: ()=>void = ()=>{}; export function registerAppRender(render: ()=>void){ renderer = render; } export function renderApp(){ renderer(); }<file_sep>/src/3d/threetest.ts import * as THREE from 'three'; import { Vector2, Vector3 } from 'three'; import { OrbitControls } from "three/examples/jsm/controls/OrbitControls"; import { getBoardByName, getBoards, getPendingBoard, setPendingBoard } from '../lumber/board'; import { renderApp } from '../renderHelper'; export type ActionMode = "MOVE" | "SELECT" | "ADD"; var actionMode: ActionMode = "MOVE"; export function GetMode() { return actionMode; } export function SetMode(mode: ActionMode) { if (actionMode === mode) { return; } actionMode = mode; if (actionMode === "MOVE") { controls.enabled = true; } else { controls.enabled = false; } renderApp(); } var scene = new THREE.Scene(); var lines: THREE.Line[] = []; var points: THREE.Points[] = []; var scale = 10; export function getScale() { return scale; } export function getScene() { return scene; } export function addLine(line: THREE.Line) { lines.push(line); } export function addPoints(pt: THREE.Points) { points.push(pt); } var camera: THREE.PerspectiveCamera; var orthoCamera: THREE.OrthographicCamera; var controls: OrbitControls; export function getControlsState() { return controls.enabled; } export function setControls(enabled: boolean) { controls.enabled = enabled; } export function setupThreeScene() { camera = new THREE.PerspectiveCamera(45, window.innerWidth / window.innerHeight, 1, 500); orthoCamera = new THREE.OrthographicCamera( window.innerWidth / -2 / scale, window.innerWidth / 2 / scale, window.innerHeight / 2 / scale, window.innerHeight / - 2 / scale, 1, 1000); camera.position.set(25, 50, 100); camera.lookAt(25, 25, 25); var renderer = new THREE.WebGLRenderer({ antialias: true }); renderer.setSize(window.innerWidth, window.innerHeight); document.body.appendChild(renderer.domElement); controls = new OrbitControls(camera, renderer.domElement); controls.enableDamping = true; const origin = new Vector3(0, 0, 0); const axisScale = 10; const xAxis = new Vector3(axisScale, 0, 0); const yAxis = new Vector3(0, axisScale, 0); const zAxis = new Vector3(0, 0, axisScale); function addLineToScene(points: Vector3[], color = 0xFFFFFF) { var geometry = new THREE.BufferGeometry().setFromPoints(points); var material = new THREE.LineBasicMaterial({ color }); var line = new THREE.Line(geometry, material); scene.add(line); } function initOrigin() { addLineToScene([origin, xAxis], 0xFF0000); addLineToScene([origin, yAxis], 0x00FF00); addLineToScene([origin, zAxis], 0x0000FF); } initOrigin(); //var geometry = new THREE.BoxGeometry(); //var material = new THREE.MeshBasicMaterial( { color: 0x00ff00 } ); //var cube = new THREE.Mesh( geometry, material ); //scene.add( cube ); // camera.position.z = 5; // Interaction stuff for lines var hovergeometry = new THREE.SphereBufferGeometry(.5); var hovermaterial = new THREE.MeshBasicMaterial({ color: 0xFFFFFF }); const sphereInter = new THREE.Mesh(hovergeometry, hovermaterial); sphereInter.visible = false; scene.add(sphereInter); var hovergeometry = new THREE.SphereBufferGeometry(1); var hovermaterial = new THREE.MeshBasicMaterial({ color: 0xff0000 }); const ptInter = new THREE.Mesh(hovergeometry, hovermaterial); ptInter.visible = false; scene.add(ptInter); const mouse = new THREE.Vector2(); const lastMouse = new THREE.Vector2(); let mouseDown = false; document.oncontextmenu = e => { if (actionMode === "ADD") { e.preventDefault?.(); e.stopPropagation?.(); return false; } }; document.addEventListener('mousedown', e => { console.log("click!", e); if (!mouseDown && actionMode === "SELECT") { if (e.button === 2) { return; } var intersects = raycaster.intersectObjects(lines, true); if (intersects.length > 0) { const board = getBoardByName(intersects[0].object.name); if (board) { console.log("Selected! ", board); if (board.selected) { board.unselect(); } else { board.select(); } renderApp(); } } } if (!mouseDown && actionMode === "ADD" && getPendingBoard()) { if (e.button === 2) { // rotate the item somehow... getPendingBoard()!.rotateX().setOrigin(getPendingBoard()!.origin); return; } else { // PLACE THE BOARD IN THE SCENE! var intersects = raycaster.intersectObjects(lines, true); if (intersects.length > 0) { getPendingBoard()?.setOrigin(intersects[0].point); const newBoard = getPendingBoard()!; newBoard.fix(); setPendingBoard(null); newBoard.select(); renderApp(); } } } mouseDown = true; }); document.addEventListener('keydown', e => { if (actionMode === "ADD") { const pendingBoard = getPendingBoard(); if (pendingBoard) { switch (e.key) { case "a": pendingBoard.rotateY(); break; case "d": pendingBoard.rotateY(Math.PI / -2); break; case "s": pendingBoard.rotateX(); break; case "w": pendingBoard.rotateX(Math.PI / -2); break; case "q": pendingBoard.rotateZ(); break; case "e": pendingBoard.rotateZ(Math.PI / -2); break; } } } if (e.key === "m" || e.key === "Escape") { SetMode("MOVE"); } if (e.key === "s") { // SetMode("SELECT"); } if (e.key === "a") { // SetMode("ADD"); } }); document.addEventListener('mouseup', e => { mouseDown = false; }); document.addEventListener('mousemove', (event) => { lastMouse.x = mouse.x; lastMouse.y = mouse.y; // track mouse location event.preventDefault(); mouse.x = (event.clientX / window.innerWidth) * 2 - 1; mouse.y = - (event.clientY / window.innerHeight) * 2 + 1; }, false); window.addEventListener('resize', () => { camera.aspect = window.innerWidth / window.innerHeight; camera.updateProjectionMatrix(); renderer.setSize(window.innerWidth, window.innerHeight); }, false); const raycaster = new THREE.Raycaster()!; raycaster.params.Line!.threshold = 2; raycaster.params.Points!.threshold = .5; function renderLinePoint() { if (actionMode !== "ADD") { return; } getBoards().forEach(b => b.unhover()); raycaster.setFromCamera(mouse, camera); var intersects = raycaster.intersectObjects(lines, true); if (intersects.length > 0) { sphereInter.visible = true; sphereInter.position.copy(intersects[0].point); const board = getBoardByName(intersects[0].object.name); if (board) { board.hover(); } const pendingBoard = getPendingBoard(); if (pendingBoard) { getPendingBoard()?.show(); pendingBoard.setOrigin(intersects[0].point); } } else { sphereInter.visible = false; getPendingBoard()?.hide(); } } function renderLineHover() { if (actionMode !== "SELECT") { return; } getBoards().forEach(b => b.unhover()); // find intersections raycaster.setFromCamera(mouse, camera); var intersects = raycaster.intersectObjects(lines, true); if (intersects.length > 0) { const board = getBoardByName(intersects[0].object.name); if (board) { board.hover(); } } } function labelAxes(axis: Vector3, id: string, label: string, color: string) { const vector = new Vector3().copy(axis).project(camera); vector.x = (vector.x + 1) * window.innerWidth / 2; vector.y = - (vector.y - 1) * window.innerHeight / 2; vector.z = 0; let el = document.getElementById(id); if (!el) { el = document.createElement("div"); el.id = id; el.style.position = "absolute"; document.body.appendChild(el); el.style.color = color; el.style.cursor = "pointer"; el.onclick = () => { camera.position.copy(new Vector3(10, 10, 10).multiply(axis)); }; } el.innerText = label; el.style.top = vector.y + "px"; el.style.left = vector.x + "px"; } function basicallyEqual(a: number, b: number, margin: number = .1) { if (a - margin <= b && a + margin >= b) { return true; } return false; } // Finally render the scene! function animate() { requestAnimationFrame(animate); controls.update(); renderLineHover(); renderLinePoint(); labelAxes(xAxis, "xaxis", "X", "red"); labelAxes(yAxis, "yaxis", "Y", "green"); labelAxes(zAxis, "zaxis", "Z", "blue"); orthoCamera.position.copy(camera.position); orthoCamera.lookAt(0,0,0); let useOrth = false; if (basicallyEqual(camera.position.x, 0) && basicallyEqual(camera.position.y, 0)) { useOrth = true; } if (basicallyEqual(camera.position.z, 0) && basicallyEqual(camera.position.y, 0)) { useOrth = true; } if (basicallyEqual(camera.position.x, 0) && basicallyEqual(camera.position.z, 0)) { useOrth = true; } renderer.render(scene, useOrth ? orthoCamera : camera); } animate(); }
320ffcc23957c319e027669a47542c2e813d35e6
[ "Markdown", "TypeScript" ]
7
Markdown
Macflash/woodwork
8cae18df18f4b1ab060489c4ff061329aefe589a
bf12a4f7d08f23683655b134911c2421db24b8ae
refs/heads/master
<file_sep>import { CUSTOM_TAG_FOR } from '@ember/-internals/metal'; import { HAS_NATIVE_PROXY } from '@ember/-internals/utils'; import { assert } from '@ember/debug'; import { DEBUG } from '@glimmer/env'; import { Arguments, CapturedArguments, CapturedNamedArguments, CapturedPositionalArguments, } from '@glimmer/interfaces'; import { Reference, valueForRef } from '@glimmer/reference'; import { Tag, track } from '@glimmer/validator'; function convertToInt(prop: number | string | symbol): number | null { if (typeof prop === 'symbol') return null; const num = Number(prop); if (isNaN(num)) return null; return num % 1 === 0 ? num : null; } function tagForNamedArg(namedArgs: CapturedNamedArguments, key: string): Tag { return track(() => { if (key in namedArgs) { valueForRef(namedArgs[key]); } }); } function tagForPositionalArg(positionalArgs: CapturedPositionalArguments, key: string): Tag { return track(() => { if (key === '[]') { // consume all of the tags in the positional array positionalArgs.forEach(valueForRef); } const parsed = convertToInt(key); if (parsed !== null && parsed < positionalArgs.length) { // consume the tag of the referenced index valueForRef(positionalArgs[parsed]); } }); } export let argsProxyFor: ( capturedArgs: CapturedArguments, type: 'component' | 'helper' | 'modifier' ) => Arguments; if (HAS_NATIVE_PROXY) { argsProxyFor = (capturedArgs, type) => { const { named, positional } = capturedArgs; let getNamedTag = (key: string) => tagForNamedArg(named, key); let getPositionalTag = (key: string) => tagForPositionalArg(positional, key); const namedHandler: ProxyHandler<{}> = { get(_target, prop) { const ref = named[prop as string]; if (ref !== undefined) { return valueForRef(ref); } else if (prop === CUSTOM_TAG_FOR) { return getNamedTag; } }, has(_target, prop) { return prop in named; }, ownKeys(_target) { return Object.keys(named); }, isExtensible() { return false; }, getOwnPropertyDescriptor(_target, prop) { assert( 'args proxies do not have real property descriptors, so you should never need to call getOwnPropertyDescriptor yourself. This code exists for enumerability, such as in for-in loops and Object.keys()', prop in named ); return { enumerable: true, configurable: true, }; }, }; const positionalHandler: ProxyHandler<[]> = { get(target, prop) { if (prop === 'length') { return positional.length; } const parsed = convertToInt(prop); if (parsed !== null && parsed < positional.length) { return valueForRef(positional[parsed]); } if (prop === CUSTOM_TAG_FOR) { return getPositionalTag; } return (target as any)[prop]; }, isExtensible() { return false; }, has(_target, prop) { const parsed = convertToInt(prop); return parsed !== null && parsed < positional.length; }, }; const namedTarget = Object.create(null); const positionalTarget: unknown[] = []; if (DEBUG) { const setHandler = function (_target: unknown, prop: symbol | string | number): never { throw new Error( `You attempted to set ${String( prop )} on the arguments of a component, helper, or modifier. Arguments are immutable and cannot be updated directly, they always represent the values that is passed down. If you want to set default values, you should use a getter and local tracked state instead.` ); }; const forInDebugHandler = (): never => { throw new Error( `Object.keys() was called on the positional arguments array for a ${type}, which is not supported. This function is a low-level function that should not need to be called for positional argument arrays. You may be attempting to iterate over the array using for...in instead of for...of.` ); }; namedHandler.set = setHandler; positionalHandler.set = setHandler; positionalHandler.ownKeys = forInDebugHandler; } return { named: new Proxy(namedTarget, namedHandler), positional: new Proxy(positionalTarget, positionalHandler), }; }; } else { argsProxyFor = (capturedArgs, _type) => { const { named, positional } = capturedArgs; let getNamedTag = (key: string) => tagForNamedArg(named, key); let getPositionalTag = (key: string) => tagForPositionalArg(positional, key); let namedProxy = {}; Object.defineProperty(namedProxy, CUSTOM_TAG_FOR, { configurable: false, enumerable: false, value: getNamedTag, }); Object.keys(named).forEach((name) => { Object.defineProperty(namedProxy, name, { enumerable: true, configurable: true, get() { return valueForRef(named[name]); }, }); }); let positionalProxy: unknown[] = []; Object.defineProperty(positionalProxy, CUSTOM_TAG_FOR, { configurable: false, enumerable: false, value: getPositionalTag, }); positional.forEach((ref: Reference, index: number) => { Object.defineProperty(positionalProxy, index, { enumerable: true, configurable: true, get() { return valueForRef(ref); }, }); }); if (DEBUG) { // Prevent mutations in development mode. This will not prevent the // proxy from updating, but will prevent assigning new values or pushing // for instance. Object.freeze(namedProxy); Object.freeze(positionalProxy); } return { named: namedProxy, positional: positionalProxy, }; }; } <file_sep>import { ENV } from '@ember/-internals/environment'; import { Factory } from '@ember/-internals/owner'; import { assert } from '@ember/debug'; import { Arguments, Bounds, ComponentCapabilities, ComponentDefinition, Destroyable, Dict, Option, VMArguments, WithStaticLayout, } from '@glimmer/interfaces'; import { createConstRef, Reference } from '@glimmer/reference'; import { registerDestructor } from '@glimmer/runtime'; import { unwrapTemplate } from '@glimmer/util'; import { EmberVMEnvironment } from '../environment'; import RuntimeResolver from '../resolver'; import { OwnedTemplate } from '../template'; import { argsProxyFor } from '../utils/args-proxy'; import { buildCapabilities, InternalCapabilities } from '../utils/managers'; import AbstractComponentManager from './abstract'; const CAPABILITIES = { dynamicLayout: false, dynamicTag: false, prepareArgs: false, createArgs: true, attributeHook: false, elementHook: false, createCaller: false, dynamicScope: true, updateHook: true, createInstance: true, wrapped: false, willDestroy: false, }; export interface OptionalCapabilities { '3.4': { asyncLifecycleCallbacks?: boolean; destructor?: boolean; }; '3.13': { asyncLifecycleCallbacks?: boolean; destructor?: boolean; updateHook?: boolean; }; } export interface Capabilities extends InternalCapabilities { asyncLifeCycleCallbacks: boolean; destructor: boolean; updateHook: boolean; } export function capabilities<Version extends keyof OptionalCapabilities>( managerAPI: Version, options: OptionalCapabilities[Version] = {} ): Capabilities { assert( 'Invalid component manager compatibility specified', managerAPI === '3.4' || managerAPI === '3.13' ); let updateHook = true; if (managerAPI === '3.13') { updateHook = Boolean((options as OptionalCapabilities['3.13']).updateHook); } return buildCapabilities({ asyncLifeCycleCallbacks: Boolean(options.asyncLifecycleCallbacks), destructor: Boolean(options.destructor), updateHook, }) as Capabilities; } export interface DefinitionState<ComponentInstance> { name: string; ComponentClass: Factory<ComponentInstance>; template: OwnedTemplate; } export interface ManagerDelegate<ComponentInstance> { capabilities: Capabilities; createComponent(factory: unknown, args: Arguments): ComponentInstance; getContext(instance: ComponentInstance): unknown; } export function hasAsyncLifeCycleCallbacks<ComponentInstance>( delegate: ManagerDelegate<ComponentInstance> ): delegate is ManagerDelegateWithAsyncLifeCycleCallbacks<ComponentInstance> { return delegate.capabilities.asyncLifeCycleCallbacks; } export interface ManagerDelegateWithAsyncLifeCycleCallbacks<ComponentInstance> extends ManagerDelegate<ComponentInstance> { didCreateComponent(instance: ComponentInstance): void; } export function hasUpdateHook<ComponentInstance>( delegate: ManagerDelegate<ComponentInstance> ): delegate is ManagerDelegateWithUpdateHook<ComponentInstance> { return delegate.capabilities.updateHook; } export interface ManagerDelegateWithUpdateHook<ComponentInstance> extends ManagerDelegate<ComponentInstance> { updateComponent(instance: ComponentInstance, args: Arguments): void; } export function hasAsyncUpdateHook<ComponentInstance>( delegate: ManagerDelegate<ComponentInstance> ): delegate is ManagerDelegateWithAsyncUpdateHook<ComponentInstance> { return hasAsyncLifeCycleCallbacks(delegate) && hasUpdateHook(delegate); } export interface ManagerDelegateWithAsyncUpdateHook<ComponentInstance> extends ManagerDelegateWithAsyncLifeCycleCallbacks<ComponentInstance>, ManagerDelegateWithUpdateHook<ComponentInstance> { didUpdateComponent(instance: ComponentInstance): void; } export function hasDestructors<ComponentInstance>( delegate: ManagerDelegate<ComponentInstance> ): delegate is ManagerDelegateWithDestructors<ComponentInstance> { return delegate.capabilities.destructor; } export interface ManagerDelegateWithDestructors<ComponentInstance> extends ManagerDelegate<ComponentInstance> { destroyComponent(instance: ComponentInstance): void; } export interface ComponentArguments { positional: unknown[]; named: Dict<unknown>; } /** The CustomComponentManager allows addons to provide custom component implementations that integrate seamlessly into Ember. This is accomplished through a delegate, registered with the custom component manager, which implements a set of hooks that determine component behavior. To create a custom component manager, instantiate a new CustomComponentManager class and pass the delegate as the first argument: ```js let manager = new CustomComponentManager({ // ...delegate implementation... }); ``` ## Delegate Hooks Throughout the lifecycle of a component, the component manager will invoke delegate hooks that are responsible for surfacing those lifecycle changes to the end developer. * `create()` - invoked when a new instance of a component should be created * `update()` - invoked when the arguments passed to a component change * `getContext()` - returns the object that should be */ export default class CustomComponentManager<ComponentInstance> extends AbstractComponentManager< CustomComponentState<ComponentInstance>, CustomComponentDefinitionState<ComponentInstance> > implements WithStaticLayout< CustomComponentState<ComponentInstance>, CustomComponentDefinitionState<ComponentInstance>, RuntimeResolver > { create( env: EmberVMEnvironment, definition: CustomComponentDefinitionState<ComponentInstance>, vmArgs: VMArguments ): CustomComponentState<ComponentInstance> { let { delegate } = definition; let args = argsProxyFor(vmArgs.capture(), 'component'); let component = delegate.createComponent(definition.ComponentClass.class, args); let bucket = new CustomComponentState(delegate, component, args, env); if (ENV._DEBUG_RENDER_TREE) { env.extra.debugRenderTree.create(bucket, { type: 'component', name: definition.name, args: vmArgs.capture(), instance: component, template: definition.template, }); registerDestructor(bucket, () => { env.extra.debugRenderTree.willDestroy(bucket); }); } return bucket; } getDebugName({ name }: CustomComponentDefinitionState<ComponentInstance>) { return name; } update(bucket: CustomComponentState<ComponentInstance>) { if (ENV._DEBUG_RENDER_TREE) { bucket.env.extra.debugRenderTree.update(bucket); } if (hasUpdateHook(bucket.delegate)) { let { delegate, component, args } = bucket; delegate.updateComponent(component, args); } } didCreate({ delegate, component }: CustomComponentState<ComponentInstance>) { if (hasAsyncLifeCycleCallbacks(delegate)) { delegate.didCreateComponent(component); } } didUpdate({ delegate, component }: CustomComponentState<ComponentInstance>) { if (hasAsyncUpdateHook(delegate)) { delegate.didUpdateComponent(component); } } getContext({ delegate, component }: CustomComponentState<ComponentInstance>) { delegate.getContext(component); } getSelf({ delegate, component }: CustomComponentState<ComponentInstance>): Reference { return createConstRef(delegate.getContext(component), 'this'); } getDestroyable(bucket: CustomComponentState<ComponentInstance>): Option<Destroyable> { return bucket; } getCapabilities({ delegate, }: CustomComponentDefinitionState<ComponentInstance>): ComponentCapabilities { return Object.assign({}, CAPABILITIES, { updateHook: ENV._DEBUG_RENDER_TREE || delegate.capabilities.updateHook, }); } didRenderLayout(bucket: CustomComponentState<ComponentInstance>, bounds: Bounds) { if (ENV._DEBUG_RENDER_TREE) { bucket.env.extra.debugRenderTree.didRender(bucket, bounds); } } didUpdateLayout(bucket: CustomComponentState<ComponentInstance>, bounds: Bounds) { if (ENV._DEBUG_RENDER_TREE) { bucket.env.extra.debugRenderTree.didRender(bucket, bounds); } } getStaticLayout(state: DefinitionState<ComponentInstance>) { return unwrapTemplate(state.template).asLayout(); } } const CUSTOM_COMPONENT_MANAGER = new CustomComponentManager(); /** * Stores internal state about a component instance after it's been created. */ export class CustomComponentState<ComponentInstance> { constructor( public delegate: ManagerDelegate<ComponentInstance>, public component: ComponentInstance, public args: Arguments, public env: EmberVMEnvironment ) { if (hasDestructors(delegate)) { registerDestructor(this, () => delegate.destroyComponent(component)); } } } export interface CustomComponentDefinitionState<ComponentInstance> extends DefinitionState<ComponentInstance> { delegate: ManagerDelegate<ComponentInstance>; } export class CustomManagerDefinition<ComponentInstance> implements ComponentDefinition { public state: CustomComponentDefinitionState<ComponentInstance>; public manager: CustomComponentManager< ComponentInstance > = CUSTOM_COMPONENT_MANAGER as CustomComponentManager<ComponentInstance>; constructor( public name: string, public ComponentClass: Factory<ComponentInstance>, public delegate: ManagerDelegate<ComponentInstance>, public template: OwnedTemplate ) { this.state = { name, ComponentClass, template, delegate, }; } }
0e437a1fd5678162d0fec7da06891f1e2050a22a
[ "TypeScript" ]
2
TypeScript
pgengler/ember.js
fb295a9e6a5800b070b62d26c980ea709fd7069c
b3ce7d8de5b807ccf3095b65a0d3aef708d4c10e
refs/heads/master
<repo_name>malrial/NodeServer_mk1<file_sep>/README.md # NodeServer_mk1 Node server test <file_sep>/index.js var server = require("./server"); var router = require("./router"); var handler = require("./handlers"); var handle = {} handle["/"] = handler.iniciar; handle["/iniciar"] = handler.iniciar; handle["/subir"] = handler.subir; server.iniciarServidor(router.route,handle);
fb4c567f16ce64ce3da75b4fca88cc16d0dac934
[ "Markdown", "JavaScript" ]
2
Markdown
malrial/NodeServer_mk1
6b3e4ee60207d50e0aac40259a440dc4bc31fd5e
e60e4f4bf15bc851e4986fa6020518bb1ab8d013
refs/heads/master
<file_sep>using NLog; using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace NLogExample.Model { public abstract class ClassBase : IPerson { public virtual Logger Log { get { return _logger; } } private static Logger _logger = LogManager.GetCurrentClassLogger(); public string Name { get; set; } public ClassBase(String name) { this.Name = name; Log.Info("From ClassBase constructor: {0} - logger.Name: {1}", this.GetType().ToString(), Log.Name); } public void LogFromClassBase() { Log.Info("LogFromClassBase(): {0}", Log.Name); } public virtual string GetClassName() { string className = this.GetType().ToString(); Log.Debug("In class : {0}", className); return className; } public abstract void ExecuteRequest(); } }<file_sep>using NLog; using NLog.Targets; using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Optimization; using System.Web.Routing; using System.Web.Security; using System.Web.SessionState; namespace NLogExample { public class Global : HttpApplication { void Application_Start(object sender, EventArgs e) { // Code that runs on application startup RouteConfig.RegisterRoutes(RouteTable.Routes); BundleConfig.RegisterBundles(BundleTable.Bundles); //NLog configuration alternative to NLog.config >>>> var config = new NLog.Config.LoggingConfiguration(); FileTarget logfileTarget1 = new NLog.Targets.FileTarget("NLogExample.Model.ClassSon") { FileName = "NLogExample.Model.ClassSon.log" }; FileTarget logfileTarget2 = new NLog.Targets.FileTarget("NLogExample.Model.ClassDaughter") { FileName = "NLogExample.Model.ClassDaughter.log" }; //Format the output lines logfileTarget1.Layout = new NLog.Layouts.SimpleLayout("${longdate}|${uppercase:${level}}|" + "${ callsite:className=true:methodName=true} | ${message} "); logfileTarget2.Layout = new NLog.Layouts.SimpleLayout("${longdate}|${uppercase:${level}}|" + "${ callsite:className=true:methodName=true} | ${message} "); //!!LoggerNamePattern parameter is important to split the log strema into the files depending on the class instance!! config.AddRule(LogLevel.Debug, LogLevel.Fatal, logfileTarget1, "NLogExample.Model.ClassSon"); config.AddRule(LogLevel.Debug, LogLevel.Fatal, logfileTarget2, "NLogExample.Model.ClassDaughter"); NLog.LogManager.Configuration = config; //<<<< NLog configuration } } }<file_sep>using NLog; using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace NLogExample.Model { public class ClassSon : ClassBase { //private static Logger logger = LogManager.GetCurrentClassLogger(); //.GetLogger("NLogExample.Model.ClassSonX"); public override Logger Log { get { return _logger; } } private static Logger _logger = LogManager.GetCurrentClassLogger(); public string Ball { get; set; } public ClassSon(String name, string ball) : base(name) { this.Ball = ball; Log.Info("From ClassSon constructor: {0} - logger.Name: {1}", this.GetType().ToString(), Log.Name); } public override string GetClassName() { string className = this.GetType().ToString(); Log.Debug("In class : {0} , {1}", className, this.Ball); return className + "_" + this.Ball; } public override void ExecuteRequest() { //throw new NotImplementedException(); this.Log.Info("Execute() in class: " + this.GetType().ToString()); } } }<file_sep>using NLog; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace NLogExample.Model { public interface IPerson { Logger Log { get; } void ExecuteRequest(); } } <file_sep>using NLog; using NLogExample.Model; using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; namespace NLogExample { public partial class _Default : Page { private static Logger logger = LogManager.GetCurrentClassLogger(); protected void Page_Load(object sender, EventArgs e) { logger.Info("START MAIN PROGRAM"); Request rd = new Request(new ClassDaughter("Girl", "Daughter in Request")); rd.Execute(); Request rs = new Request(new ClassSon("Boy", "Son in Request")); rs.Execute(); //CallSon(); //CallDaughter(); logger.Info("END MAIN PROGRAM"); } public void CallDaughter() { ClassDaughter daughter = new ClassDaughter("Girl", "Ring"); logger = daughter.Log; logger.Info("In CallDaughter"); daughter.GetClassName(); daughter.LogFromClassBase(); daughter.ExecuteRequest(); logger.Info("From the main procedure in the context of ClassDaughter - logger.Name: {0}", logger.Name); } public void CallSon() { ClassSon son = new ClassSon("Boy", "Ball"); logger = son.Log; logger.Info("In CallSon"); son.GetClassName(); son.LogFromClassBase(); son.ExecuteRequest(); logger.Info("From the main procedure in the context of ClassSon - logger.Name: {0}", logger.Name); } } }<file_sep>using NLog; using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace NLogExample.Model { public class Request { private static Logger logger = LogManager.GetCurrentClassLogger(); public IPerson Person { get; private set; } public Request(IPerson person) { this.Person = person; } public void Execute() { logger = this.Person.Log; logger.Info("Starting Request.Execute - class: {0}", this.GetType().ToString()); this.Person.ExecuteRequest(); logger.Info("Ending Request.Execute - class: {0}", this.GetType().ToString()); } } }
a7a339682a12e6ef4e4c3a8180d641c3647ff293
[ "C#" ]
6
C#
sv-georgiev/NLogExample
fadc69557e0d3d02c810296ec3750810cc4358ec
a1b5d1b0744a4a9229a28900c56bdfa8fc5e5448
refs/heads/master
<file_sep>var debounce = function(func, wait) { var timeout, context, args var later = function() { timeout = null func.apply(context, args) } var debounced = function() { if (timeout) clearTimeout(timeout) context = this args = arguments timeout = setTimeout(later, wait) } } <file_sep>var chineseNum = { '零': 0, '一': 1, '二': 2, '三': 3, '四': 4, '五': 5, '六': 6, '七': 7, '八': 8, '九': 9 } var chineseUnit = { '十': {value:10, sec:false}, '百': {value:100, sec:false}, '千': {value:1000, sec:false}, '万': {value:10000, sec:true}, '亿': {value:100000000, sec:true}, } function chinese2num(chinese) { var spilitChinese = chinese.split(''), length = spilitChinese.length; var num = 0, unitSum = 0, sum = 0; for (var i=0; i<length; i++) { var singleChar = spilitChinese[i]; if (singleChar in chineseNum) { num = chineseNum[singleChar]; if (i === length - 1) { sum += num; } } else { var unit = chineseUnit[singleChar] if (unit.sec) { sum = (sum + num) * unit.value } else { sum += num * unit.value } num = 0; } } console.log(sum); } var t1 = '四' var t2 = '一十四' var t3 = '一百一十四' var t4 = '一千一百一十四' var t5 = '一万一百一十四' var t6 = '五百七十八万六千四百九十一' chinese2num(t6)<file_sep>// 获取URL上的参数 var getUrlParams = function(url) { var result = {} var params = url.split('?')[1].split('&') params.forEach(item => { var tmp = item.split('=') result[tmp[0]] = tmp[1] || '' }) return result } var getUrlParamsWithRegExp = function(url) { var result = {} url = url.split('?')[1] url.replace(/(\w+)=(\w*)/g, function(match, a, b) { result[a] = b }) return result } <file_sep>function matrixMultiplication(a,b){ var len=a.length, arr=[]; for (var i=0; i<len; i++) { arr[i]=[]; for(var j=0; j<len; j++) { arr[i][j]=0;//每次都重新置为0 for(var k=0; k<len; k++) { arr[i][j]+=a[i][k]*b[k][j]; } } } return arr; } function matrixMultiplication(a,b){ return a.map(function(row){ return row.map(function(_,i){ return row.reduce(function(sum,cell,j){ return sum+cell*b[j][i]; },0); }); }); } function matrixMultiply(a, b) { if (!Array.isArray(a) || !Array.isArray(b)) { throw new Error('params must be array') } var isValid = a.every(item => item.length === b.length) if (!isValid) { throw new Error('传入的数组数据有误,无法进行矩阵乘') } var result = [] var rowLen = a.length, colLen = b[0].length; var addTimes = a[0].length; for(var i=0; i<rowLen; i++) { result[i] = []; for(var j=0; j<colLen; j++) { result[i][j] = 0 for(var k=0; k<addTimes; k++) { result[i][j] += a[i][k] * b[k][j] } } } console.log(result) return result } var a = [[1,2,3],[4,5,6]] var b = [[1,4],[2,5],[3,6]] matrixMultiply(a,b)<file_sep>var throttle = function(func, wait) { let previous var throttled = function() { var now = Date.now() previous = previous || now var remaining = wait - (now - previous) if (remaining <= 0) { func.call(this, arguments) previous = now } } return throttled }<file_sep>// 数组去重 var unique = function(arr) { var obj = {} var result = [] var len = arr.length for (var i = 0; i < len; i++) { if (!obj[arr[i]]) { result.push(obj) obj[arr[i]] = true } } return result } var uniqueWithIndex = function(arr) { var result = [] var len = arr.length for (var i = 0; i < len; i++) { if (arr.indexOf(arr[i]) === i) { // or result.indexOf(arr[i]) === -1 result.push(obj) } } return result } var uniqueWithES6 = function(arr) { return [...new Set(arr)] } <file_sep># interview-problem Some interview problem
839340edd911afef72c1ba4a0ecb71824db8f036
[ "JavaScript", "Markdown" ]
7
JavaScript
LeeJim/interview-problem
2b57d79c473fd2b782165b8eeb930ba82407d678
f3f031eb9dbfe0539315cd89c41c4f1004b01be4
refs/heads/master
<file_sep># VecMat La aguja del pajar <file_sep>#include <iostream> #include <conio.h> using namespace std; int filas,columnas,valor; //extern int mat[filas][columnas]; float matriz (int& mat); void orden(){system("cls"); } multiplicacion(){system("cls"); } transpuesta(){system("cls"); } frecuencia(){system("cls"); } matriz(){ int mat[filas][columnas]; for(int i=1;i<=filas;i++){ for(int j=0;j<columnas;j++){ cout<<"\n ingresa el valor de tu vector "<<i<<" en la posicion "<<j<<endl; cin>>valor; mat[i][j]=valor; } } } imprimirv(){ } main(){ system("cls"); cout<<" Elije que programa quieres correr"<<endl; cout<<"\n 1)Ordenar vector de menor a mayor"<<endl; cout<<"\n 2)Multiplicar dos matrices"<<endl; cout<<"\n 3)Transpuesta de matriz"<<endl; cout<<"\n 4)Frecuencia Matriz de 5x5,llenado, impresion, busqueda de un numero a buscar sacando su frecuencia "<<endl; cout<<"\n 5)salir"<<endl; int opcion; cin>>opcion; switch(opcion){ break; case 1: system("cls"); filas=1; cout<<"Ordenar vector de menor a mayor\n"<<endl; cout<<"Cuanto valores quieres en tu vector?"<<endl; cin>>columnas; matriz(); void orden(); break; case 2: system("cls"); matriz(); void multiplicacion(); break; case 3: system("cls"); matriz(); void transpuesta(); case 4: system("cls"); matriz(); void frecuencia(); break; case 5: system("cls"); exit(0); break; } }
ed3b61909c6c8970ec6d638b85845717c67aa085
[ "Markdown", "C++" ]
2
Markdown
Adiazsu/VecMat
9f9d007eb9f935c80f09767b10494942685a945e
8342b0c1b6f7e5f9a8b31efca05e9916aa248593
refs/heads/master
<repo_name>bcourbon/TraditionalRegression<file_sep>/Makefile #makefile CC = g++ #UCFLAGS = -O0 -g3 -Wall -gstabs+ UCFLAGS = -O3 -fopenmp -Wall -gstabs+ #UCFLAGS = -O0 -g3 -fopenmp -Wall -gstabs+ #RUCFLAGS = -pthread -m64 -I/afs/cern.ch/sw/lcg/external/root/head/slc4_amd64_gcc34/root/include #LIBS = -L/afs/cern.ch/sw/lcg/external/root/head/slc4_amd64_gcc34/root/lib -lCore -lCint -lHist -lGraf -lGraf3d -lGpad -lTree -lRint -lPostscript -lMatrix -lPhysics -pthread -lm -ldl -rdynamic #GLIBS = -L/afs/cern.ch/sw/lcg/external/root/head/slc4_amd64_gcc34/root/lib -lCore -lCint -lHist -lGraf -lGraf3d -lGpad -lTree -lRint -lPostscript -lMatrix -lPhysics -lGui -pthread -lm -ldl -rdynamic RUCFLAGS := $(shell root-config --cflags) -I./include/ LIBS := -lgomp $(shell root-config --libs) -lTreePlayer -lTMVA -lRooFit -lRooFitCore GLIBS := $(shell root-config --glibs) vpath %.cpp ./src SRCPP = main.cpp\ Utilities.cpp\ GBRApply.cpp\ GBREvent.cpp\ GBRForest.cpp\ GBRTrainer.cpp\ GBRTree.cpp\ TMVAMaker.cpp\ RegressionTest.cpp\ RooDoubleCB.cpp\ GBRMaker.cpp\ ParReader.cpp\ RegressionManager.cpp\ SmearingCorrection.cpp\ ErrorCorrection.cpp\ TrackMomentumCorrection.cpp\ VariableCorrectionApply.cpp #OBJCPP = $(SRCPP:.cpp=.o) OBJCPP = $(patsubst %.cpp,obj/%.o,$(SRCPP)) all : regression.exe obj/libDictionary_C.so obj/%.o : %.cpp @echo "> compiling $*" @mkdir -p obj/ @$(CC) -c $< $(UCFLAGS) $(RUCFLAGS) -o $@ regression.exe : $(OBJCPP) @echo "> linking" @$(CC) $^ $(ACLIBS) $(LIBS) $(GLIBS) -o $@ clean: @echo "> Cleaning object files" @rm -f obj/*.o cleanall: clean @echo "> Cleaning dictionary" @rm -f obj/libDictionary_C.so @echo "> Cleaning executable" @rm -f regression.exe obj/libDictionary_C.so: ./include/libDictionary.C @echo "> Generating dictionary" @cd include && root -b -q libDictionary.C++ @mv ./include/libDictionary_C.so ./obj/ <file_sep>/include/RegressionTest.h #ifndef REGRESSIONTEST_H #define REGRESSIONTEST_H #include <string> #include <vector> #include "GBRForest.h" #include "TTree.h" class RegressionTest { public: RegressionTest(); ~RegressionTest(); void init(std::string RegFileName,std::string DataFileName,std::string DirName,std::string TreeName); void PlotResponse(); private: const std::vector<std::string> *varlistEB; const std::vector<std::string> *varlistEE; const GBRForest* forestEB; const GBRForest* forestEE; int numvarsEB; int numvarsEE; TTree *tree; }; #endif <file_sep>/README.md TraditionalRegression ===================== <file_sep>/src/Utilities.cpp /** * @file Utilities.cxx * @brief * * * @author <NAME> <<EMAIL>> * * @date 03/27/2010 * * @internal * Created : 03/27/2010 * Last update : 03/27/2010 01:00:52 PM * by : <NAME> * * ===================================================================================== */ #include "Utilities.h" #include "TH1.h" #include "TF1.h" #include "TMath.h" //--- STL using namespace std; ///*****************************************************************/ //void tokenize(const string& str, // vector<string>& tokens, // const string& delimiters) ///*****************************************************************/ //{ // // Skip delimiters at beginning. // string::size_type lastPos = str.find_first_not_of(delimiters, 0); // // Find first "non-delimiter". // string::size_type pos = str.find_first_of(delimiters, lastPos); // // while (string::npos != pos || string::npos != lastPos) // { // // Found a token, add it to the vector. // tokens.push_back(str.substr(lastPos, pos - lastPos)); // // Skip delimiters. Note the "not_of" // lastPos = str.find_first_not_of(delimiters, pos); // // Find next "non-delimiter" // pos = str.find_first_of(delimiters, lastPos); // } //} /*****************************************************************/ void tokenize(const string& str, vector<string>& tokens, const string& delimiter) /*****************************************************************/ { string::size_type length = delimiter.size(); string::size_type lastPos = 0; string::size_type pos = str.find(delimiter, 0); while (string::npos != pos) { // Found a token, add it to the vector. if(str.substr(lastPos, pos - lastPos).size()>0) tokens.push_back(str.substr(lastPos, pos - lastPos)); lastPos = pos + length; // Find next "non-delimiter" pos = str.find(delimiter, lastPos); } if(str.substr(lastPos).size()>0) tokens.push_back(str.substr(lastPos)); } /*****************************************************************/ string intToString(int n) /*****************************************************************/ { ostringstream oss; oss << n; return oss.str(); } /*****************************************************************/ void findAndReplace(string& sInput, string sFind, string sReplace ) /*****************************************************************/ { size_t itPos = 0; size_t itFindLen = sFind.length(); size_t itReplaceLen = sReplace.length(); if( itFindLen == 0 ) return; while( (itPos = sInput.find( sFind, itPos )) != std::string::npos ) { sInput.replace( itPos, itFindLen, sReplace ); itPos += itReplaceLen; } } /*****************************************************************/ void strip(std::string& sInput) /*****************************************************************/ { //-- removing blanks at the beginning and at the end while(*sInput.begin()==' ' || *sInput.begin()=='\t') sInput.erase(sInput.begin()); while(*(sInput.end()-1)==' ' || *(sInput.end()-1)=='\t') sInput.erase(sInput.end()-1); } /*****************************************************************/ //effsigma function from Chris double effSigma(TH1 * hist) /*****************************************************************/ { TAxis *xaxis = hist->GetXaxis(); Int_t nb = xaxis->GetNbins(); if(nb < 10) { cout << "effsigma: Not a valid histo. nbins = " << nb << endl; return 0.; } Double_t bwid = xaxis->GetBinWidth(1); if(bwid == 0) { cout << "effsigma: Not a valid histo. bwid = " << bwid << endl; return 0.; } //Double_t xmax = xaxis->GetXmax(); Double_t xmin = xaxis->GetXmin(); Double_t ave = hist->GetMean(); Double_t rms = hist->GetRMS(); Double_t total=0.; for(Int_t i=0; i<nb+2; i++) { total+=hist->GetBinContent(i); } // if(total < 100.) { // cout << "effsigma: Too few entries " << total << endl; // return 0.; // } Int_t ierr=0; Int_t ismin=999; Double_t rlim=0.683*total; Int_t nrms=rms/(bwid); // Set scan size to +/- rms if(nrms > nb/10) nrms=nb/10; // Could be tuned... Double_t widmin=9999999.; for(Int_t iscan=-nrms;iscan<nrms+1;iscan++) { // Scan window centre Int_t ibm=(ave-xmin)/bwid+1+iscan; Double_t x=(ibm-0.5)*bwid+xmin; Double_t xj=x; Double_t xk=x; Int_t jbm=ibm; Int_t kbm=ibm; Double_t bin=hist->GetBinContent(ibm); total=bin; for(Int_t j=1;j<nb;j++){ if(jbm < nb) { jbm++; xj+=bwid; bin=hist->GetBinContent(jbm); total+=bin; if(total > rlim) break; } else ierr=1; if(kbm > 0) { kbm--; xk-=bwid; bin=hist->GetBinContent(kbm); total+=bin; if(total > rlim) break; } else ierr=1; } Double_t dxf=(total-rlim)*bwid/bin; Double_t wid=(xj-xk+bwid-dxf)*0.5; if(wid < widmin) { widmin=wid; ismin=iscan; } } if(ismin == nrms || ismin == -nrms) ierr=3; if(ierr != 0) cout << "effsigma: Error of type " << ierr << endl; return widmin; } /*****************************************************************/ double DoubleCrystalBall(double *x, double *par) /*****************************************************************/ { double mean=par[0]; double sigma=par[1]; double alpha1=par[2]; double n1=par[3]; double alpha2=par[4]; double n2=par[5]; double t = (x[0]-mean)/sigma; double val = -99.; if(t>-alpha1 && t<alpha2){ val = exp(-0.5*t*t); }else if(t<=-alpha1){ double alpha1invn1 = alpha1/n1; val = exp(-0.5*alpha1*alpha1)*pow(1. - alpha1invn1*(alpha1+t), -n1); }else if(t>=alpha2){ double alpha2invn2 = alpha2/n2; val = exp(-0.5*alpha2*alpha2)*pow(1. - alpha2invn2*(alpha2-t), -n2); } return val; } /*****************************************************************/ double GetMeanAfterFit(TH1 *histo) /*****************************************************************/ { TF1 *FitFunction = new TF1("FitFunction",DoubleCrystalBall,0,3,6); FitFunction->SetParameter(0,1); FitFunction->SetParLimits(0,0.5,1.5); FitFunction->SetParameter(1,0.1); FitFunction->SetParLimits(1,0.01,1); FitFunction->SetParameter(2,2); FitFunction->SetParLimits(2,2,2); FitFunction->SetParameter(3,3); FitFunction->SetParLimits(3,1.01,10); FitFunction->SetParameter(4,1); FitFunction->SetParLimits(4,1,1); FitFunction->SetParameter(5,3); FitFunction->SetParLimits(5,1.01,10); histo->Fit("FitFunction"); return FitFunction->GetParameter(0); } <file_sep>/src/RegressionTest.cpp #include "RegressionTest.h" #include "GBRMaker.h" #include "GBRForest.h" #include "GBRTree.h" #include "Utilities.h" #include "TTree.h" #include "TTreeFormula.h" #include "TH1D.h" #include "TGraph.h" #include "TH2D.h" #include "TCanvas.h" #include "TLegend.h" #include "TFile.h" #include "TDirectory.h" #include "TProfile.h" #include "TMath.h" #include "TPaveLabel.h" #include "TStyle.h" #include "RooGaussian.h" #include "RooRealVar.h" #include "RooArgSet.h" #include "RooDataHist.h" #include "RooPlot.h" #include "RooBreitWigner.h" #include "RooArgList.h" #include "RooCBShape.h" #include "RooAddPdf.h" #include "RooDoubleCB.h" #include "RooClassFactory.h" #ifndef __CINT__ #include "RooGlobalFunc.h" #endif #include "TROOT.h" #include <TSystem.h> #include <TFile.h> #include <iostream> #include <sstream> #include <algorithm> #include <vector> using namespace std; using namespace RooFit; /*****************************************************************/ RegressionTest::RegressionTest() /*****************************************************************/ { } /*****************************************************************/ RegressionTest::~RegressionTest() /*****************************************************************/ { } /*****************************************************************/ void RegressionTest::init(string RegFileName, std::string DataFileName, std::string DirName, std::string TreeName) /*****************************************************************/ { TFile *file = new TFile(RegFileName.c_str(),"READ"); varlistEB = (std::vector<std::string>*)file->Get("varlistEB"); forestEB = (GBRForest*)file->Get("EBCorrection"); numvarsEB = varlistEB->size(); varlistEE = (std::vector<std::string>*)file->Get("varlistEE"); forestEE = (GBRForest*)file->Get("EECorrection"); numvarsEE = varlistEE->size(); printf("liste des variables Barrel \n"); for (int ivar = 0; ivar<numvarsEB; ++ivar) { printf("%i: %s\n",ivar, varlistEB->at(ivar).c_str()); } printf("liste des variables Endcaps \n"); for (int ivar = 0; ivar<numvarsEE; ++ivar) { printf("%i: %s\n",ivar, varlistEE->at(ivar).c_str()); } TFile *datafile = TFile::Open(DataFileName.c_str()); TDirectory *dir = (TDirectory*)datafile->FindObjectAny(DirName.c_str()); tree = (TTree*)dir->Get(TreeName.c_str()); } /*****************************************************************/ void RegressionTest::PlotResponse() /*****************************************************************/ { double Eta,Phi,EtaWidth,PhiWidth,R9,Nvtx,Eraw,Etrue,Pt; double Correction; // Ecor/Eraw double RawBias; // Eraw/Etrue double CorBias; // Ecor/Etrue //vector of variables of interest std::vector<std::string> InputVarsEB; for (int ivar = 0; ivar<numvarsEB; ++ivar) { InputVarsEB.push_back(varlistEB->at(ivar)); } InputVarsEB.push_back("genEnergy"); InputVarsEB.push_back("genPt"); unsigned int numvars2EB=InputVarsEB.size(); std::vector<std::string> InputVarsEE; for (int ivar = 0; ivar<numvarsEE; ++ivar) { InputVarsEE.push_back(varlistEE->at(ivar)); } InputVarsEE.push_back("genEnergy"); InputVarsEE.push_back("genPt"); unsigned int numvars2EE=InputVarsEE.size(); //to read the variables in the ttree std::vector<TTreeFormula*> inputformsEB; for (std::vector<std::string>::const_iterator it = InputVarsEB.begin(); it != InputVarsEB.end(); ++it) { inputformsEB.push_back(new TTreeFormula(it->c_str(),it->c_str(),tree)); } std::vector<TTreeFormula*> inputformsEE; for (std::vector<std::string>::const_iterator it = InputVarsEE.begin(); it != InputVarsEE.end(); ++it) { inputformsEE.push_back(new TTreeFormula(it->c_str(),it->c_str(),tree)); } //contains ttree events float* EventEB; EventEB = new float[numvars2EB]; float* EventEE; EventEE = new float[numvars2EE]; //Declare all histograms TH1D *hCor=new TH1D("Ecor/Eraw","Ecor/Eraw",100,0.8,1.2); TH1D *hBiasCor=new TH1D("Ecor/Etrue","Ecor/Etrue",100,0.8,1.2); TH1D *hBiasRaw=new TH1D("Eraw/Etrue","Eraw/Etrue",100,0.8,1.2); TH2D *hCor_Eta=new TH2D("Ecor/Eraw vs Eta","Ecor/Eraw vs Eta",100,-3,3,500,0,2); TH2D *hCor_Phi=new TH2D("Ecor/Eraw vs Phi","Ecor/Eraw vs Phi",100,-3.14,3.14,500,0,2); TH2D *hCor_EtaWidth=new TH2D("Ecor/Eraw vs Eta Width","Ecor/Eraw vs Eta Width",100,0,0.03,500,0,2); TH2D *hCor_PhiWidth=new TH2D("Ecor/Eraw vs Phi Width","Ecor/Eraw vs Phi Width",100,0,0.1,500,0,2); TH2D *hCor_R9=new TH2D("Ecor/Eraw vs R9","Ecor/Eraw vs R9",100,0,1.2,500,0,2); TH2D *hCor_Nvtx=new TH2D("Ecor/Eraw vs nVtx","Ecor/Eraw vs nVtx",100,0,50,500,0,2); std::vector<TH1*> HistPt1;//for 0<|eta|<1 std::vector<TH1*> HistPt2;//for 1<|eta|<1.479 std::vector<TH1*> HistPt3;//for 1.479<|eta|<2 std::vector<TH1*> HistPt4;//for 2<|eta|<2.5 for (int i=0;i<10;i++){ HistPt1.push_back(new TH1D(Form("Ecor/Etrue for %i < Pt <%i and 0<|eta|<1",i*10,(i+1)*10),Form("Ecor/Etrue for %i < Pt <%i ",i*10,(i+1)*10),99,0.8,1.2)); HistPt2.push_back(new TH1D(Form("Ecor/Etrue for %i < Pt <%i and 1<|eta|<1.48",i*10,(i+1)*10),Form("Ecor/Etrue for %i < Pt <%i ",i*10,(i+1)*10),99,0.8,1.2)); HistPt3.push_back(new TH1D(Form("Ecor/Etrue for %i < Pt <%i and 1.48<|eta|<2",i*10,(i+1)*10),Form("Ecor/Etrue for %i < Pt <%i ",i*10,(i+1)*10),49,0.8,1.2)); HistPt4.push_back(new TH1D(Form("Ecor/Etrue for %i < Pt <%i and 2<|eta|<2.5",i*10,(i+1)*10),Form("Ecor/Etrue for %i < Pt <%i ",i*10,(i+1)*10),49,0.8,1.2)); } //Loop on tree events for (Long64_t ievt=0; ievt<tree->GetEntries();ievt++){ if(ievt%10000==0) printf("%lld / %lld \n",ievt,tree->GetEntries()); tree->LoadTree(ievt); Eta=inputformsEB[1]->EvalInstance(); if (fabs(Eta)<1.479){ for (unsigned int ivar=0; ivar<numvars2EB; ++ivar) EventEB[ivar] = inputformsEB[ivar]->EvalInstance(); Correction=forestEB->GetResponse(EventEB); Phi=EventEB[2]; EtaWidth=EventEB[3]; PhiWidth=EventEB[4]; R9=EventEB[5]; Nvtx=EventEB[0]; Eraw=EventEB[32]; Etrue=EventEB[33]; Pt=EventEB[34]; } else{ for (unsigned int ivar=0; ivar<numvars2EE; ++ivar) EventEE[ivar] = inputformsEE[ivar]->EvalInstance(); Correction=forestEE->GetResponse(EventEE); Phi=EventEE[2]; EtaWidth=EventEE[3]; PhiWidth=EventEE[4]; R9=EventEE[5]; Nvtx=EventEE[0]; Eraw=EventEE[29]; Etrue=EventEE[30]; Pt=EventEE[31]; } RawBias=Eraw/Etrue; CorBias=RawBias*Correction; hCor->Fill(Correction); hBiasRaw->Fill(RawBias); hBiasCor->Fill(CorBias); hCor_Eta->Fill(Eta,Correction); hCor_Phi->Fill(Phi,Correction); hCor_EtaWidth->Fill(EtaWidth,Correction); hCor_PhiWidth->Fill(PhiWidth,Correction); hCor_R9->Fill(R9,Correction); hCor_Nvtx->Fill(Nvtx,Correction); for(int i=0;i<10;i++){ if (Pt>i*10 && Pt<(i+1)*10 && fabs(Eta)<1.) HistPt1[i]->Fill(CorBias); if (Pt>i*10 && Pt<(i+1)*10 && fabs(Eta)>=1. && fabs(Eta)<1.479) HistPt2[i]->Fill(CorBias); if (Pt>i*10 && Pt<(i+1)*10 && fabs(Eta)>=1.479 && fabs(Eta)<2.) HistPt3[i]->Fill(CorBias); if (Pt>i*10 && Pt<(i+1)*10 && fabs(Eta)>=2. && fabs(Eta)<2.5) HistPt4[i]->Fill(CorBias); } } //Plot ECor/Eraw TCanvas *can = new TCanvas; hCor->Draw(); hCor->GetXaxis()->SetTitle("Ecor/Eraw"); hCor->SetLineWidth(2); can->SaveAs("plots/Correction.png"); //Plot Ecor/Etrue compared to Eraw/Etrue TCanvas *can2 = new TCanvas; hBiasCor->Draw(); hBiasRaw->Draw("same"); hBiasCor->SetLineColor(kRed); hBiasRaw->SetLineColor(kBlue); hBiasCor->SetLineWidth(2); hBiasRaw->SetLineWidth(2); TLegend *leg = new TLegend(0.12,0.78,0.32,0.88); leg->AddEntry(hBiasRaw,"Eraw/Etrue","l"); leg->AddEntry(hBiasCor,"Ecor/Etrue","l"); leg->Draw(); hBiasCor->SetTitle("E/Etrue"); hBiasCor->GetXaxis()->SetTitle("E/Etrue"); gStyle->SetOptStat(0); TPaveLabel *OldPerf = new TPaveLabel(0.63,0.88,0.88,0.78, Form("Peak = %.3f , RMS = %.3f ",hBiasRaw->GetXaxis()->GetBinCenter(hBiasRaw->GetMaximumBin()),hBiasRaw->GetRMS()),"NDC"); TPaveLabel *NewPerf = new TPaveLabel(0.63,0.76,0.88,0.66, Form("Peak = %.3f , RMS = %.3f ",hBiasCor->GetXaxis()->GetBinCenter(hBiasCor->GetMaximumBin()),hBiasCor->GetRMS()),"NDC"); OldPerf->SetBorderSize(1); OldPerf->SetTextSize(0.25); OldPerf->SetTextColor(kBlue); NewPerf->SetBorderSize(1); NewPerf->SetTextSize(0.25); NewPerf->SetTextColor(kRed); OldPerf->Draw(); NewPerf->Draw(); can2->SaveAs("plots/Performance.png"); //Plot profiles of Ecor/Eraw in function of input variables TCanvas *can3 = new TCanvas("","",1200,700); can3->Divide(3,2); can3->cd(1); TProfile *pCor_Eta= new TProfile(); pCor_Eta=hCor_Eta->ProfileX("",1,-1,"s"); pCor_Eta->SetMinimum(0.9); pCor_Eta->SetMaximum(1.1); pCor_Eta->Draw(); pCor_Eta->GetXaxis()->SetTitle("Eta"); pCor_Eta->GetYaxis()->SetTitle("Ecor/Eraw"); pCor_Eta->SetTitle("Profile of Ecor/Eraw vs Eta"); pCor_Eta->SetMarkerStyle(3); can3->cd(2); TProfile *pCor_Phi= new TProfile(); pCor_Phi=hCor_Phi->ProfileX("",1,-1,"s"); pCor_Phi->SetMinimum(0.9); pCor_Phi->SetMaximum(1.1); pCor_Phi->Draw(); pCor_Phi->GetXaxis()->SetTitle("Phi"); pCor_Phi->GetYaxis()->SetTitle("Ecor/Eraw"); pCor_Phi->SetTitle("Profile of Ecor/Eraw vs Phi"); pCor_Phi->SetMarkerStyle(3); can3->cd(3); TProfile *pCor_EtaWidth= new TProfile(); pCor_EtaWidth=hCor_EtaWidth->ProfileX("",1,-1,"s"); pCor_EtaWidth->SetMinimum(0.9); pCor_EtaWidth->SetMaximum(1.2); pCor_EtaWidth->Draw(); pCor_EtaWidth->GetXaxis()->SetTitle("EtaWidth"); pCor_EtaWidth->GetYaxis()->SetTitle("Ecor/Eraw"); pCor_EtaWidth->SetTitle("Profile of Ecor/Eraw vs EtaWidth"); pCor_EtaWidth->SetMarkerStyle(3); can3->cd(4); TProfile *pCor_PhiWidth= new TProfile(); pCor_PhiWidth=hCor_PhiWidth->ProfileX("",1,-1,"s"); pCor_PhiWidth->SetMinimum(0.9); pCor_PhiWidth->SetMaximum(1.2); pCor_PhiWidth->Draw(); pCor_PhiWidth->GetXaxis()->SetTitle("PhiWidth"); pCor_PhiWidth->GetYaxis()->SetTitle("Ecor/Eraw"); pCor_PhiWidth->SetTitle("Profile of Ecor/Eraw vs PhiWidth"); pCor_PhiWidth->SetMarkerStyle(3); can3->cd(5); TProfile *pCor_R9= new TProfile(); pCor_R9=hCor_R9->ProfileX("",1,-1,"s"); pCor_R9->SetMinimum(0.9); pCor_R9->SetMaximum(1.2); pCor_R9->Draw(); pCor_R9->GetXaxis()->SetTitle("R9"); pCor_R9->GetYaxis()->SetTitle("Ecor/Eraw"); pCor_R9->SetTitle("Profile of Ecor/Eraw vs R9"); pCor_R9->SetMarkerStyle(3); can3->cd(6); TProfile *pCor_Nvtx= new TProfile(); pCor_Nvtx=hCor_Nvtx->ProfileX("",1,-1,"s"); pCor_Nvtx->SetMinimum(0.9); pCor_Nvtx->SetMaximum(1.1); pCor_Nvtx->Draw(); pCor_Nvtx->GetXaxis()->SetTitle("Nvtx"); pCor_Nvtx->GetYaxis()->SetTitle("Ecor/Eraw"); pCor_Nvtx->SetTitle("Profile of Ecor/Eraw vs Nvtx"); pCor_Nvtx->SetMarkerStyle(3); can3->SaveAs("plots/Correction_Variables.png"); //Compute and Plot Bias and Resolution in function of Pt by fitting the distributions by a double Crystal Ball, in for eta bins double pt1[10]; double mean1[10]; double sigeff1[10]; double pt2[10]; double mean2[10]; double sigeff2[10]; double pt3[10]; double mean3[10]; double sigeff3[10]; double pt4[10]; double mean4[10]; double sigeff4[10]; //create fit function RooRealVar *bias=new RooRealVar("Ecor/Etrue","Ecor/Etrue",0.8,1.2); const RooArgList *var=new RooArgList(*bias,""); RooRealVar *mu=new RooRealVar("mu","mu",1,0.5,1.5); RooRealVar *sig=new RooRealVar("sig","sig",0.05,0.001,1); RooRealVar *alpha1=new RooRealVar("alpha1","alpha1",2.,0,10); RooRealVar *alpha2=new RooRealVar("alpha2","alpha2",1.,0,10); RooRealVar *n1=new RooRealVar("n1","n2",2,0,5); RooRealVar *n2=new RooRealVar("n2","n2",2,0,5); RooDoubleCB *DoubleCB=new RooDoubleCB("doubleCB","doubleCB",*bias,*mu,*sig,*alpha1,*n1,*alpha2,*n2); RooArgSet *paramSet=new RooArgSet; TCanvas *can7 = new TCanvas("can7","can7",1200,600); can7->Divide(5,2); TCanvas *can8 = new TCanvas("can8","can8",1200,600); can8->Divide(5,2); TCanvas *can9 = new TCanvas("can9","can9",1200,600); can9->Divide(5,2); TCanvas *can10 = new TCanvas("can10","can10",1200,600); can10->Divide(5,2); for (int i=0;i<10;i++){ pt1[i]=5.+i*10.; RooDataHist *HistPtclone1=new RooDataHist("","",*var,HistPt1[i]); DoubleCB->fitTo(*HistPtclone1); paramSet=DoubleCB->getParameters(HistPtclone1) ; mean1[i]=paramSet->getRealValue("mu"); sigeff1[i]=effSigma(HistPt1[i]); can7->cd(i+1); RooPlot *plot1=bias->frame(Title(Form("%i<Pt<%i and 0<|eta|<1",i*10,(i+1)*10))); HistPtclone1->plotOn(plot1); DoubleCB->plotOn(plot1); plot1->Draw(); pt2[i]=5.+i*10.; RooDataHist *HistPtclone2=new RooDataHist("","",*var,HistPt2[i]); DoubleCB->fitTo(*HistPtclone2); paramSet=DoubleCB->getParameters(HistPtclone2) ; mean2[i]=paramSet->getRealValue("mu"); sigeff2[i]=effSigma(HistPt2[i]); can8->cd(i+1); RooPlot *plot2=bias->frame(Title(Form("%i<Pt<%i and 1<|eta|<1.48",i*10,(i+1)*10))); HistPtclone2->plotOn(plot2); DoubleCB->plotOn(plot2); plot2->Draw(); pt3[i]=5.+i*10.; RooDataHist *HistPtclone3=new RooDataHist("","",*var,HistPt3[i]); DoubleCB->fitTo(*HistPtclone3); paramSet=DoubleCB->getParameters(HistPtclone3) ; mean3[i]=paramSet->getRealValue("mu"); sigeff3[i]=effSigma(HistPt3[i]); can9->cd(i+1); RooPlot *plot3=bias->frame(Title(Form("%i<Pt<%i and 1.48<|eta|<2",i*10,(i+1)*10))); HistPtclone3->plotOn(plot3); DoubleCB->plotOn(plot3); plot3->Draw(); pt4[i]=5.+i*10.; RooDataHist *HistPtclone4=new RooDataHist("","",*var,HistPt4[i]); DoubleCB->fitTo(*HistPtclone4); paramSet=DoubleCB->getParameters(HistPtclone4) ; mean4[i]=paramSet->getRealValue("mu"); sigeff4[i]=effSigma(HistPt4[i]); can10->cd(i+1); RooPlot *plot4=bias->frame(Title(Form("%i<Pt<%i and 2<|eta|<2.5",i*10,(i+1)*10))); HistPtclone4->plotOn(plot4); DoubleCB->plotOn(plot4); plot4->Draw(); } can7->SaveAs("plots/PtDistributions1.png"); can8->SaveAs("plots/PtDistributions2.png"); can9->SaveAs("plots/PtDistributions3.png"); can10->SaveAs("plots/PtDistributions4.png"); TCanvas *can4=new TCanvas; can4->Divide(2,2); can4->cd(1); TGraph *graphRes_Pt1 = new TGraph(10,pt1,sigeff1); graphRes_Pt1->Draw("AL*"); graphRes_Pt1->SetMarkerStyle(8); graphRes_Pt1->GetXaxis()->SetTitle("pt"); graphRes_Pt1->GetYaxis()->SetTitle("Ecor/Etrue effective width"); graphRes_Pt1->SetTitle("Ecor/Etrue effective width vs Pt for 0<|eta|<1"); can4->cd(2); TGraph *graphRes_Pt2 = new TGraph(10,pt2,sigeff2); graphRes_Pt2->Draw("AL*"); graphRes_Pt2->SetMarkerStyle(8); graphRes_Pt2->GetXaxis()->SetTitle("pt"); graphRes_Pt2->GetYaxis()->SetTitle("Ecor/Etrue effective width"); graphRes_Pt2->SetTitle("Ecor/Etrue effective width vs Pt for 1<|eta|<1.48"); can4->cd(3); TGraph *graphRes_Pt3 = new TGraph(10,pt3,sigeff3); graphRes_Pt3->Draw("AL*"); graphRes_Pt3->SetMarkerStyle(8); graphRes_Pt3->GetXaxis()->SetTitle("pt"); graphRes_Pt3->GetYaxis()->SetTitle("Ecor/Etrue effective width"); graphRes_Pt3->SetTitle("Ecor/Etrue effective width vs Pt for 1.48<|eta|<2"); can4->cd(4); TGraph *graphRes_Pt4 = new TGraph(10,pt4,sigeff4); graphRes_Pt4->Draw("AL*"); graphRes_Pt4->SetMarkerStyle(8); graphRes_Pt4->GetXaxis()->SetTitle("pt"); graphRes_Pt4->GetYaxis()->SetTitle("Ecor/Etrue effective width"); graphRes_Pt4->SetTitle("Ecor/Etrue effective width vs Pt for 2<|eta|<2.5"); can4->SaveAs("plots/Resolution_Pt.png"); TCanvas *can5=new TCanvas; can5->Divide(2,2); can5->cd(1); TGraph *graphCor_Pt1 = new TGraph(10,pt1,mean1); graphCor_Pt1->Draw("AL*"); graphCor_Pt1->SetMarkerStyle(8); graphCor_Pt1->GetXaxis()->SetTitle("pt"); graphCor_Pt1->GetYaxis()->SetTitle("Ecor/Etrue mean"); graphCor_Pt1->SetTitle("Ecor/Etrue peak value vs Pt for 0<|eta|<1"); can5->cd(2); TGraph *graphCor_Pt2 = new TGraph(10,pt2,mean2); graphCor_Pt2->Draw("AL*"); graphCor_Pt2->SetMarkerStyle(8); graphCor_Pt2->GetXaxis()->SetTitle("pt"); graphCor_Pt2->GetYaxis()->SetTitle("Ecor/Etrue mean"); graphCor_Pt2->SetTitle("Ecor/Etrue peak value vs Pt for 1<|eta|<1.48"); can5->cd(3); TGraph *graphCor_Pt3 = new TGraph(10,pt3,mean3); graphCor_Pt3->Draw("AL*"); graphCor_Pt3->SetMarkerStyle(8); graphCor_Pt3->GetXaxis()->SetTitle("pt"); graphCor_Pt3->GetYaxis()->SetTitle("Ecor/Etrue mean"); graphCor_Pt3->SetTitle("Ecor/Etrue peak value vs Pt for 1.48<|eta|<2"); can5->cd(4); TGraph *graphCor_Pt4 = new TGraph(10,pt4,mean4); graphCor_Pt4->Draw("AL*"); graphCor_Pt4->SetMarkerStyle(8); graphCor_Pt4->GetXaxis()->SetTitle("pt"); graphCor_Pt4->GetYaxis()->SetTitle("Ecor/Etrue mean"); graphCor_Pt4->SetTitle("Ecor/Etrue peak value vs Pt for 2<|eta|<2.5"); can5->SaveAs("plots/Bias_Pt.png"); }
2f62eeacc1cbd6a9f695c73243e3709a7558c84e
[ "Markdown", "Makefile", "C++" ]
5
Makefile
bcourbon/TraditionalRegression
c71874be02f82dfa385f9520a5c3b966b067ad53
9ffa69396f55c516f71acc4162b597574b60ee02
refs/heads/master
<repo_name>tonmayonweb/HOW-TO-PLAY-MUSIC-IN-PYTHON<file_sep>/music.py from pygame import mixer mixer.init() mixer.music.load("song.mp3") mixer.music.play(10) print("\t\t\t\t\t\t\t Tonmay Music Production") while True: print("\t\t\t\t Press p for pause and r for resume and q for ") option = input() if option == "p" : mixer.music.pause() elif option == "r" : mixer.music.unpause() elif option == "q" : mixer.music.stop() break
1bf48b4e327bdee236e538274f8a60a1f80cb0d9
[ "Python" ]
1
Python
tonmayonweb/HOW-TO-PLAY-MUSIC-IN-PYTHON
4c94570afe16f10a8f938fdb7a8096af8adc8ba1
b15348018d5bf99d9aeb5d8521eabe075deee84e
refs/heads/master
<repo_name>vikky12343/Character_count-sender-<file_sep>/char_count_send.3.py f=open("character.txt","w+") s=raw_input('Enter the character:') i=0 s1='' s2='' j=0 while i<len(s): if s[i]==' ': s1=s1+str(j)+s2 s2='' j=0 else: s2=s2+s[i] j=j+1 i=i+1 s1=s1+str(j)+s2 print s1 f=open("character.txt","w") f.write(s2)
def2d23cb3763cbfe0b2e9104757c2fc0eea44d8
[ "Python" ]
1
Python
vikky12343/Character_count-sender-
577eb98b6d32d0e2db42ebcfedc8fade04285b20
6b956be97bd3a7e483f5ce70a7939ea786fc8417
refs/heads/master
<file_sep>#### App trắc nghiệm kiến thức THPT theo bộ môn <div style="display: flex;"> <img src="screenshot/sc1.jpg" width=300> <img src="screenshot/sc2.jpg" width=300> <img src="screenshot/sc3.jpg" width=300> </div> <file_sep>package huukhuong.multiplechoice.util; import java.util.ArrayList; import huukhuong.multiplechoice.model.Question; public class Constant { public static String URL_ROOT = "http://quiz.huukhuongit.tk/"; public static String URL_IMAGE = URL_ROOT + "img/"; public static String URL_SUBJECT = URL_ROOT + "subject.php"; public static String URL_QUESTION = URL_ROOT + "question.php"; public static ArrayList<Question> listQuestion; } <file_sep>package huukhuong.multiplechoice; import android.app.ProgressDialog; import android.os.Bundle; import android.util.Log; import android.view.View; import androidx.appcompat.app.AppCompatActivity; import androidx.recyclerview.widget.RecyclerView; import com.android.volley.AuthFailureError; import com.android.volley.Request; import com.android.volley.RequestQueue; import com.android.volley.Response; import com.android.volley.VolleyError; import com.android.volley.toolbox.JsonArrayRequest; import com.android.volley.toolbox.Volley; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.util.ArrayList; import java.util.Map; import huukhuong.multiplechoice.adapters.AdapterSubject; import huukhuong.multiplechoice.model.Question; import huukhuong.multiplechoice.model.Subject; import huukhuong.multiplechoice.util.Constant; import huukhuong.multiplechoice.util.PlayGame; import me.everything.android.ui.overscroll.OverScrollDecoratorHelper; public class MainActivity extends AppCompatActivity { private RecyclerView rcvSubjects; private AdapterSubject adapterSubject; private ArrayList<Subject> listSubject; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); addControls(); } private void addControls() { listSubject = new ArrayList<>(); rcvSubjects = findViewById(R.id.rcvSubjects); adapterSubject = new AdapterSubject(this, listSubject); rcvSubjects.setAdapter(adapterSubject); OverScrollDecoratorHelper.setUpOverScroll(rcvSubjects, OverScrollDecoratorHelper.ORIENTATION_VERTICAL); getAllSubjects(); } private void getAllSubjects() { ProgressDialog progress = new ProgressDialog(this); progress.setTitle("Đang tải"); progress.setMessage("Vui lòng đợi..."); progress.setCanceledOnTouchOutside(false); progress.show(); RequestQueue requestQueue = Volley.newRequestQueue(getApplicationContext()); JsonArrayRequest subjectRequest = new JsonArrayRequest(Request.Method.GET, Constant.URL_SUBJECT, null, response -> { try { for (int i = 0; i < response.length(); i++) { JSONObject jsonObject = response.getJSONObject(i); Subject subject = new Subject(); subject.setId(jsonObject.getInt("id")); subject.setName(jsonObject.getString("name")); subject.setImage(Constant.URL_IMAGE + jsonObject.getString("image")); listSubject.add(subject); } } catch (JSONException e) { e.printStackTrace(); } adapterSubject.notifyDataSetChanged(); progress.dismiss(); }, error -> findViewById(R.id.err).setVisibility(View.VISIBLE)) { @Override protected Map<String, String> getParams() throws AuthFailureError { return null; } }; Constant.listQuestion = new ArrayList<>(); JsonArrayRequest questionRequest = new JsonArrayRequest( Request.Method.GET, Constant.URL_QUESTION, null, response -> { try { for (int i = 0; i < response.length(); i++) { JSONObject jsonObject = response.getJSONObject(i); Question question = new Question(); question.setId(jsonObject.getInt("id")); question.setQuestion(jsonObject.getString("question")); question.setAnsA(jsonObject.getString("ans_a")); question.setAnsB(jsonObject.getString("ans_b")); question.setAnsC(jsonObject.getString("ans_c")); question.setAnsD(jsonObject.getString("ans_d")); question.setCorrect(jsonObject.getString("result")); question.setSubjectId(jsonObject.getInt("subject")); Constant.listQuestion.add(question); } } catch (Exception e) { } progress.dismiss(); }, error -> findViewById(R.id.err).setVisibility(View.VISIBLE) ); requestQueue.add(subjectRequest); requestQueue.add(questionRequest); } }<file_sep>package huukhuong.multiplechoice; import androidx.appcompat.app.AppCompatActivity; import android.content.Intent; import android.os.Bundle; import android.util.Log; import android.widget.ImageButton; import android.widget.TextView; import android.widget.Toast; import java.util.ArrayList; import huukhuong.multiplechoice.util.PlayGame; public class ResultActivity extends AppCompatActivity { private TextView txvScore; private TextView txvCorrectQty; private TextView txvPercent; private TextView txvTotalQty; private TextView txvWrongQty; private ImageButton btnHome; private ImageButton btnShowResult; private ImageButton btnRanking; private Intent intent; private int correctQty; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_result); addControls(); addEvents(); } private void addControls() { intent = getIntent(); txvScore = findViewById(R.id.txvScore); txvCorrectQty = findViewById(R.id.txvCorrectQty); txvPercent = findViewById(R.id.txvPercent); txvTotalQty = findViewById(R.id.txvTotalQty); txvWrongQty = findViewById(R.id.txvWrongQty); btnHome = findViewById(R.id.btnHome); btnShowResult = findViewById(R.id.btnShowResult); btnRanking = findViewById(R.id.btnRanking); correctQty = intent.getIntExtra("correct", 0); int total = PlayGame.questionPlay.size(); float score = (float) 10 / total * correctQty; float percent = (float) (correctQty * 1.0 / total * 100); int wrong = total - correctQty; txvScore.setText(score + ""); txvPercent.setText((int) percent + "%"); txvTotalQty.setText(total + ""); txvCorrectQty.setText(correctQty + ""); txvWrongQty.setText(wrong + ""); } private void addEvents() { btnHome.setOnClickListener(v -> startActivity(new Intent(ResultActivity.this, MainActivity.class))); btnRanking.setOnClickListener(v -> Toast.makeText(ResultActivity.this, "Chức năng này đang được phát triển", Toast.LENGTH_SHORT).show()); btnShowResult.setOnClickListener(v -> Toast.makeText(ResultActivity.this, "Chức năng này tạm khóa", Toast.LENGTH_SHORT).show()); } }
405dde963150ce49a45290badc1f47fbe127bfb3
[ "Markdown", "Java" ]
4
Markdown
huukhuong/MultipleChoice
bf23602592c22f7b9229b9a5cd3690f89e74d2cf
a313ab3e2834225ee43b7507453081e0bb56b707
refs/heads/master
<file_sep>mail.smtp.host=smtp.gmail.com mail.smtp.port=587 mail.smtp.username=<EMAIL> mail.smtp.password=<PASSWORD> <file_sep>## Script Java para envio de email com Gmail com uso de servidor [SMTP](https://en.wikipedia.org/wiki/SMTP_Authentication) ### Envio de email com gmail + java + spring Fonte: http://blog.algaworks.com/spring-gmail/ <file_sep>package com.bruno.email; import org.springframework.context.annotation.AnnotationConfigApplicationContext; import com.bruno.email.envio.Mailer; import com.bruno.email.envio.Mensagem; import com.bruno.random.RandomCode;; public class SpringEmailMain { public static void main(String[] args) { AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext( SpringEmailMain.class.getPackage().getName()); try { RandomCode rcode = new RandomCode(); Integer code = rcode.randomic(); String usuario = "Nome Sobrenome"; //getUser() String email = " <<EMAIL>>"; //getUsermail() String remetente = "Remetente <<EMAIL>>"; String destinatario = usuario + email; String assunto = "Email de teste"; String mensagem = "Mensagem"; Mailer mailer = applicationContext.getBean(Mailer.class); mailer.enviar(new Mensagem(remetente, destinatario, assunto, mensagem)); applicationContext.close(); //enviado para... System.out.println("Email enviado para: " + destinatario); } catch (Exception e) { System.err.println("Erro: " + e); } } }
811680815222f87ca340192906e7636a096e2ed3
[ "Markdown", "Java", "INI" ]
3
INI
isk4ndar/mailjava
975d0bd5cc8c224036ad4195637d74c0a11e450a
7282d1d5c673000b13330ef9b3e3a45fcf9df045
refs/heads/master
<file_sep><?php class EsticadeTest extends PHPUnit_Framework_TestCase { public function testEsticadeCreation() { $serviceName = "TestService"; $esticade = new \Esticade\Esticade($serviceName); $this->assertInstanceOf('\Esticade\Esticade', $esticade, "Expecting Esticade class"); $this->assertEquals($serviceName, $esticade->getServiceName(), "Expecting correct service name"); $callback = function ($message) {}; $this->assertEquals($esticade, $esticade->on("TestEvent", $callback), "Expecting on to return Esticade object"); $this->assertEquals($esticade, $esticade->alwaysOn("TestEvent", $callback), "Expecting on to return Esticade object"); $this->assertNull($esticade->emit("TestEvent", null), "Expecting to have emit function"); $this->assertEquals($esticade, $esticade->emitChain("TestEvent", null), "Expecting to have emitChain function"); $this->assertNull($esticade->execute(), "Expecting to have execute function"); $this->assertNull($esticade->shutdown(), "Expecting to have shutdown function"); } }<file_sep><?php namespace Esticade; class Esticade { /** * @var string */ private $serviceName; public function __construct($serviceName) { $this->serviceName = $serviceName; } /** * @return string */ public function getServiceName() { return $this->serviceName; } /** * @param string $event * @param callable $callback * @return Esticade */ public function on($event, $callback) { return $this; } /** * @param string $event * @param callable $callback * @return Esticade */ public function alwaysOn($event, $callback) { return $this; } /** * @param string $event * @param mixed $payload */ public function emit($event, $payload) { } /** * @param string $event * @param mixed $payload * * @return Esticade */ public function emitChain($event, $payload) { return $this; } public function execute() { } public function shutdown() { } }<file_sep># esticade.php Esticade PHP library
ac02a0183d07430ada15f7d1ff38fbba6d533482
[ "Markdown", "PHP" ]
3
PHP
abitwise/esticade.php
8d1834df645aff59f020bb34dd528d211fde8034
4372cf0b674809c42366450f21cdb72622f1160f
refs/heads/master
<file_sep>//Rock, Paper, Scissors, Lizard, Spock using es6 and served by a simple node server (http module), no peaking at your past R,P,S code and push to Github. //Set Up event listeners for each of the images let scoreHuman = 1; let scoreComputer = 1; let scoreDraw = 1; const getValue = (e) => { let userChoice = e.target.getAttribute('value'); //rock, p, s, l, s makeRequest(userChoice); } document.querySelectorAll('.imgChoices').forEach(e => e.addEventListener('click', getValue)) document.querySelector('.buttonReset').addEventListener('click', resetGame) let imageArrays = [ ['rock', 'pic/rock.png'], ['paper', 'pic/paper.png'], ['scissors','pic/scissors.png'], ['lizard', 'pic/lizard.png'], ['spock', 'pic/spock.jpeg'] ] const getImage = (choice) => { for(imgArr of imageArrays) { if(imgArr[0] === choice) { return imgArr[1] } } } const displayUserChoiceImage = (userInput) => { document.querySelector('#summaryChoice').innerText = "" document.querySelector('#reportWinner').innerText = "" document.querySelector('#playerChoiceImage').setAttribute('src', getImage(userInput)) } const makeRequest = (userInput) => { setTimeout(() => {displayUserChoiceImage(userInput)}, 500) fetch(`/api?choice=${userInput}`) .then(response => response.json()) .then(data => { console.log(data); const displayComputerChoiceImage = () => { document.querySelector('#computerChoiceImage').setAttribute('src', getImage(data['choiceComputer'])) } setTimeout(() => {displayComputerChoiceImage()}, 500) const humanBeatsComputer = () => { document.querySelector('#summaryChoice').innerText = data['choiceHuman'].toUpperCase() + ' beats ' + data['choiceComputer'].toUpperCase() + '.' } const computerBeatsHuman = () => { document.querySelector('#summaryChoice').innerText = data['choiceComputer'].toUpperCase() + ' beats ' + data['choiceHuman'].toUpperCase() + '.' } if(data['winner'] === 'playerHuman') { setTimeout(() => { humanBeatsComputer(userInput) increaseScore('human') document.querySelector('#reportWinner').innerText = "You Win!" }, 500) } else if (data['winner'] === 'draw') { setTimeout(() => { increaseScore('draw') document.querySelector('#reportWinner').innerText = "Draw!" }, 500) } else { setTimeout(() => { computerBeatsHuman() increaseScore('computer') document.querySelector('#reportWinner').innerText = "Computer Wins!" }, 500) } }) } function increaseScore(winner) { if(winner === 'human') { document.querySelector('#humanScore').innerText = scoreHuman++ } else if (winner === 'computer') { document.querySelector('#computerScore').innerText = scoreComputer++ } else if (winner === 'draw') { document.querySelector('#drawScore').innerText = scoreDraw++ } } function resetGame() { scoreHuman = 1; scoreComputer = 1; scoreDraw = 1; document.querySelector('#humanScore').innerText = "0" document.querySelector('#computerScore').innerText = "0" document.querySelector('#drawScore').innerText = "0" document.querySelector('#summaryChoice').innerText = "" document.querySelector('#reportWinner').innerText = "" document.querySelector('#computerChoiceImage').setAttribute('src', "") document.querySelector('#playerChoiceImage').setAttribute('src', "") } <file_sep># rock-paper-scissors-lizard-spock A spin on the original rock-paper-scissors game, 'rock-paper-scissors-lizard-spock' adds on two more items. Each item can beat 2 items. -Rock beats scissors & lizard. -Paper beats rock & spock. -Scissors beats paper & lizard. -Lizard beats paper & spock. -Spock beats rock & scissors. Link to Project: ![Project Image](/pic/game.png) ### How It's Made: This projects is build using HTML, CSS, and JavaScript on the front-end and Node.js on the back-end. After the player indicates their choice, their choice is sent as a request to the server. Their request is processed on the back-end where the computer's randomized choice is generated and the computer's choice is compared to the player's choice. Next, a winner is declared. The server packages the player's choice, the computer's choice, and who the winner is, into an object. The object is sent as a response back to the front-end where the data is used to render content to the DOM. ### Lesson Learned I learned how to use Node.js to create a server on the back-end. ###<file_sep>//Rock, Paper, Scissors, Lizard, Spock using es6 and served by a simple node server (http module), no peaking at your past R,P,S code and push to Github. //These variables store the modules that we need to use. const http = require('http'); const fs = require('fs'); const url = require('url'); const querystring = require('querystring'); const figlet = require('figlet'); var PORT = process.env.PORT || 8000; class Game { constructor(playerPerson, playerComputer) { this.playerPerson = playerPerson this.playerComputer = playerComputer this.playerComputerChoice = null this.currentState = 'continue' this.winner = null this.score = 0 } getCurrentState() { return this.currentState; } setCurrentState() { return this.currentState; } increaseScore() { this.score++ } getRandomizedComputerChoice() { let randomNumber = Math.random() if(randomNumber <= 0.2) { return this.playerComputerChoice = 'rock' } else if (randomNumber <= 0.4) { return this.playerComputerChoice = 'paper' } else if (randomNumber <= 0.6) { return this.playerComputerChoice = 'scissors' } else if (randomNumber <= 0.7) { return this.playerComputerChoice = 'lizard' } else if (randomNumber <= 1) { return this.playerComputerChoice = 'spock' } } } class Player{ constructor(name) { this.name = name this.score = 0 } } let playerHuman = new Player('player1') let playerCPU = new Player('playerCPU') let rpsls = new Game(playerHuman, playerCPU); let winningArrays = [ ['rock', 'scissors', 'lizard'], ['paper','rock', 'spock'], ['scissors', 'paper', 'lizard'], ['lizard', 'paper', 'spock'], ['spock', 'rock', 'scissors'] ] function checkWinner(userChoice) { let computerChoice = rpsls.getRandomizedComputerChoice() console.log(computerChoice) for(winArr of winningArrays) { if(userChoice === winArr[0] && (computerChoice === winArr[1] || computerChoice === winArr[2])) { return [userChoice, computerChoice, 'playerHuman'] //return {player: userChoice, computer: computerChoice, winner: 'playerHuman'} } else if (userChoice === computerChoice) { return [userChoice, computerChoice, 'draw'] } else if (userChoice === winArr[0] && (computerChoice != winArr[1] || computerChoice != winArr[2])) { return [userChoice, computerChoice, 'playerComputer'] } } } //The function expression creates the server. const server = http.createServer(function(req, res) { //The 'page' variable contains the path of the url--the string after the host name and before the query. const page = url.parse(req.url).pathname; //https:localhost8000/ --> page === "/" const params = querystring.parse(url.parse(req.url).query); //https:localhost8000/api?word=cat -> {word:cat} if(page === "/") { fs.readFile('index.html', function(err, data) { res.writeHead(200, {'Content-Type': 'text/html'}); res.write(data); res.end(); }); } else if (page === '/api') { const array = checkWinner(params['choice']) const resultToJson = { choiceHuman: array[0], //rock choiceComputer : array[1], //scissors winner: array[2] //human } console.log(resultToJson) res.writeHead(200, {'Content-Type' : 'application/json'}); res.write(JSON.stringify(resultToJson)); res.end() } else if (page === '/css/style.css') { fs.readFile('css/style.css', function(err, data) { res.write(data); res.end(); }); } else if (page === '/pic/bg.jpeg') { fs.readFile('pic/bg.jpeg', function(err, data) { res.write(data); res.end(); }); } else if (page === '/pic/lizard.png') { fs.readFile('pic/lizard.png', function(err, data) { res.write(data); res.end(); }); } else if (page === '/pic/paper.png') { fs.readFile('pic/paper.png', function(err, data) { res.write(data); res.end(); }); } else if (page === '/pic/rock.png') { fs.readFile('pic/rock.png', function(err, data) { res.write(data); res.end(); }); } else if (page === '/pic/scissors.png') { fs.readFile('pic/scissors.png', function(err, data) { res.write(data); res.end(); }); } else if (page === '/pic/spock.jpeg') { fs.readFile('pic/spock.jpeg', function(err, data) { res.write(data); res.end(); }); } else if (page === '/css/normalize.css') { fs.readFile('css/normalize.css', function(err, data) { res.write(data); res.end(); }); } else if (page === '/pic/bg.png') { fs.readFile('pic/bg.png', function(err, data) { res.write(data); res.end(); }); } else if (page === '/js/main.js') { fs.readFile('js/main.js', function(err, data) { res.writeHead(200, {'Content-Type': 'text/javascript'}); res.write(data); res.end(); }); } else { figlet('404!!', function(err, data) { if (err) { console.log('Something went wrong...'); console.dir(err); return; } res.write(data); res.end(); }); } }); server.listen(PORT);
22e1d59a29b9aecd9e830f1e636dae65f7746ae7
[ "JavaScript", "Markdown" ]
3
JavaScript
anvytran-dev/spock-lizard
b912a6280b2213bf3f10792a859fc14786388805
96f8257c9705b315e0124693b58d66cf4bea6b21
refs/heads/master
<file_sep>package Calculadora; public class Program { public static void main(String[] args) { //Ejercicio 3 // System.out.println(ManejoString.cantidadCaracteres(cadena)); // System.out.println(ManejoString.primeraMitad(cadena)); // System.out.println(ManejoString.ultimoCaracter(cadena)); // System.out.println(ManejoString.formaInversa(cadena)); // System.out.println(ManejoString.caracterSeparado(cadena)); // System.out.println(ManejoString.poseeHola(cadena)); // //Ejercicio 5 Calculadora calculadora = new Calculadora(); System.out.println(calculadora.sumar(1, 1)); System.out.println(calculadora.restar(1, 1)); System.out.println(calculadora.multiplicar(2, 2)); try { System.out.println(calculadora.dividir(4, 0)); } catch (DivisionPorCeroException e) { System.out.println(e.getMessage()); } } } <file_sep>package ejercicio18; public class Program { public static void main(String[] args) { // TODO Auto-generated method stub Thread hilo = new Thread(new MiHilo()); hilo.start(); } } <file_sep>package Program; import java.util.List; public class AgregarPalabra implements Runnable { List<String> palabras; int contador= 0; public List<String> getPalabras() { return palabras; } public void setPalabras(List<String> palabras) { this.palabras = palabras; } @Override public void run() { while(true) { //Parte crítica uso lista compartida synchronized (this.palabras) { contador++; this.palabras.add("palabra" + contador); System.out.println(Thread.currentThread().getName() + " agregó palabra" ); this.palabras.notify(); } try { Thread.sleep(5000); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } } <file_sep>package program; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; public class Program { public static void main(String[] args) { // TODO Auto-generated method stub //Conexión a base de datos try { //se levantan los objetos dentro de la memoria RAM Class.forName("com.mysql.jdbc.Driver"); String pathConexion = "jdbc:mysql://localhost:3306/test"; Connection connection = DriverManager.getConnection(pathConexion, "root", ""); //Ejecutar cualquier consulta PreparedStatement st = connection.prepareStatement( "insert into persona (id, nombre, apellido)" + " values (1, 'Lionel', 'Herrero')"); st.execute(); //Ejecutar consultas que requieren respuesta .executeQuery PreparedStatement stConsulta = connection.prepareStatement( "Select * from persona"); ResultSet rs = stConsulta.executeQuery(); //enlace a la respuesta //Cargar lista de personas //List<Persona> personas = new ArrayList<>() ; //Recorrer mientras haya respuesta while(rs.next()) { String nombre = rs.getString("nombre"); Integer id = rs.getInt(1); //Agregar persona a la lista } //ejecutar consultas connection.close(); //Se cierra la instancia. //retornar lista de personas } catch (ClassNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } <file_sep>package program; import java.util.Date; public class MiUnchecked extends RuntimeException{ private Date hora; public MiUnchecked(String s) { super(s); //El mensaje va sobre el constructor } } <file_sep>package ejercicio18.test; import org.junit.Assert; import org.junit.Test; import ejercicio18.MiHilo; public class MiHiloTest { @Test public void runOk() { //Crear 3 hilos Thread hiloUno = new Thread(new MiHilo(), "hiloUno"); Thread hiloDos = new Thread(new MiHilo(), "hiloDos"); Thread hiloTres = new Thread(new MiHilo(), "hiloTres"); hiloUno.start(); hiloDos.start(); hiloTres.start(); while(hiloUno.isAlive() && hiloDos.isAlive() && hiloTres.isAlive()) { } System.out.println("Terminaron los hilos"); Assert.assertTrue(true); //Mostrar mensaje cuando finalicen } } <file_sep>package punto4; public class MiHilo implements Runnable { ClasePrincipal c; public MiHilo(ClasePrincipal c ) { this.c = c; } @Override public void run() { synchronized (c.lista) { while(c.lista.size()> 0) { String proceso = c.procesar(); c.mostrarInfo(Thread.currentThread().getName(), proceso); } } } } <file_sep>package ejercicio1; public enum EMarca { ford, renault, volkswagen, fiat, } <file_sep>package program; public class Auto { private String marca; private String patente; public Auto() { super(); } public Auto(String marca, String patente) { super(); this.marca = marca; this.patente = patente; } public String getMarca() { return marca; } public void setMarca(String marca) { this.marca = marca; } public String getPatente() { return patente; } public void setPatente(String patente) { this.patente = patente; } @Override public String toString() { return "Auto [marca=" + marca + ", patente=" + patente + "]"; } } <file_sep>package ejercicio1; public class Program { public static void main(String[] args) { Auto a1 = new Auto("AU123321", EMarca.ford, "KA", 1230450); Auto a2 = new Auto("BA456321", EMarca.renault, "Clio", 830450); Auto a3 = new Auto("EE123345", EMarca.volkswagen, "Cross", 2230450); System.out.println(a1); System.out.println(a2); System.out.println(a3); } } <file_sep>package program; import java.lang.reflect.Constructor; import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.List; public class Program { public static void main(String[] args) throws IllegalAccessException, IllegalArgumentException, InvocationTargetException, ClassNotFoundException { // TODO Auto-generated method stub //Persona p = new Persona(); Object p = null; //Importar los atributos //Class c = p.getClass(); Class c = Class.forName("program.Persona"); //levanta en memoria ram Constructor[] constructores = c.getConstructors(); for(Constructor cons: constructores) { if(cons.getParameterCount()==0) { try { p = cons.newInstance(null); } catch (InstantiationException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IllegalAccessException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IllegalArgumentException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (InvocationTargetException e) { // TODO Auto-generated catch block e.printStackTrace(); } break; } } Field [] attrs = c.getDeclaredFields(); //Ejecutar los set for(Field f:attrs) { f.setAccessible(true); String nombreAt = f.getName(); String nombreSetter = "set" + nombreAt; Method[] metodos = c.getDeclaredMethods(); //tambien se puede encontrar el get method específico (+ performante) //Buscar los set for(Method m:metodos) { m.setAccessible(true); //Buscar el nombre if(m.getName().equalsIgnoreCase(nombreSetter)) { Object[] params = new Object[1];//Para guardar el parametro //Setear los valores segun el tipo if(f.getType().equals(String.class)) { params[0] = "String"; } else if(f.getType().equals(Integer.class)) { params[0] = 33320102; } else { params[0] = null; } //Invocar el método con el parámetro m.invoke(p, params); } } } //Ejecutar los get for(Field f:attrs) { f.setAccessible(true); System.out.println(f.get(p)); String nombreAt = f.getName(); String nombreGetter = "get" + nombreAt; Method[] metodos = c.getDeclaredMethods(); //Buscar los get for(Method m:metodos) { m.setAccessible(true); if(m.getName().equalsIgnoreCase(nombreGetter)) { //Invocar los get Object o = m.invoke(p, null); System.out.println("El parametro " + nombreAt + " valor " + o ); } } } /*p.setDni(123456); Class c = p.getClass(); //Importar los atributos //Field [] attrs = c.getFields(); Field [] attrs = c.getDeclaredFields(); for(Field f:attrs) { //Saber el nombre System.out.println(f.getName()); System.out.println(f.getType()); System.out.println(f.getModifiers()); } Method[] metodos = c.getDeclaredMethods(); for(Method m: metodos) { //llamar a un método if(m.getName().equals("getDni")) { //Debo pasarle la instancia donde //se va a ejecutar el método Object o = m.invoke(p, null); System.out.println(o); } else if("setDni".equals(m.getName())) { //Preparo los parametros del objeto Object[] params = new Object[1]; params[0] = 33320102; System.out.println(m.invoke(p, params)); } }*/ } } <file_sep>package program; public class ManejoPalabra{ public String segundaPalabra(String palabra) throws ArrayIndexOutOfBoundsException{ String[] palabras =palabra.split(" "); return palabras[1]; } } <file_sep>package Calculadora; public class DivisionPorCeroException extends Exception { DivisionPorCeroException() { super("Intenta dividir por cero"); } } <file_sep>package Program; public class Program { public static void main(String[] args) { // TODO Auto-generated method stub Ejecucion hilo = new Ejecucion(); hilo.start(); hilo.frenar(); hilo.reanudar(); hilo.detener(); } } <file_sep>package clase.test; import org.junit.Assert; import org.junit.Test; import clase.ManejoString; public class ManejoStringTest { @Test public void cantidadCaracteresOk() { try { int cantidadCaracteres = ManejoString.cantidadCaracteres("hola"); Assert.assertEquals(4, cantidadCaracteres); } catch (NullPointerException e){ Assert.fail(); } } @Test public void cantidadCaracteresPalabraNull() { try { int cantidadCaracteres = ManejoString.cantidadCaracteres(null); Assert.fail("No lanzo NullPointerException"); } catch (NullPointerException e){ Assert.assertTrue(true); } } @Test public void primeraMitadOk() { try { String primeraMitad = ManejoString.primeraMitad("hola"); Assert.assertEquals("ho", primeraMitad); } catch (NullPointerException e) { Assert.fail(); } } @Test public void primeraMitadLenghtUno() { try { String primeraMitad = ManejoString.primeraMitad("h"); Assert.assertEquals("h", primeraMitad); } catch (NullPointerException e) { Assert.fail(); } } @Test public void primeraMitadPalabraNull() { try { String primeraMitad = ManejoString.primeraMitad(null); Assert.fail(); } catch (NullPointerException e) { Assert.assertTrue(true); } } @Test public void ultimoCaracterOk() { try { char ultimoCaracter = ManejoString.ultimoCaracter("hola"); Assert.assertTrue(ultimoCaracter == 'a'); } catch (NullPointerException e) { Assert.fail(); } } @Test public void ultimoCaracterStringUnCaracter() { try { char ultimoCaracter = ManejoString.ultimoCaracter("a"); Assert.assertTrue(ultimoCaracter == 'a'); } catch (NullPointerException e) { Assert.fail(); } } @Test public void ultimoCaracterNullPointer() { try { char ultimoCaracter = ManejoString.ultimoCaracter(null); Assert.fail(); } catch (NullPointerException e) { Assert.assertTrue(true); } } } <file_sep>package program; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; public class Program { public static void main(String[] args) { // TODO Auto-generated method stub Program.ejecutarPrueba(); } public static void ejecutarPrueba() { ManejoStringTest m = new ManejoStringTest(); Method[] metodos = ManejoStringTest.class.getDeclaredMethods(); for(Method metodo: metodos) { Test t = metodo.getAnnotation(Test.class); System.out.println("Nombre prueba: " + t.nombre()); try { for(int i = 0; i < t.intentos(); i++) { metodo.invoke(m, null); } } catch (IllegalAccessException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IllegalArgumentException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (InvocationTargetException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } } <file_sep># Programacion-Avanzada-I<file_sep>package Calculadora; public interface ICalcular { public Double sumar(Number a, Number b); public Double restar(Number a, Number b); public Double multiplicar(Number a, Number b); public Double dividir(Number a, Number b) throws DivisionPorCeroException; } <file_sep>package program; import java.sql.SQLException; import java.util.List; public interface IConexion { void abrirConexion() throws ClassNotFoundException, SQLException; void cerrarConexion() throws SQLException; } <file_sep>package ejercicio18; public class MiHilo implements Runnable{ @Override public void run() { for(int i = 0; i < 2000; i++) { System.out.println("Iteración n°" + i + " Hilo: " + MiHilo.class.getSimpleName()); } } }
b068ac4f54d2492430cd6ad2b2e41ad0795255ea
[ "Markdown", "Java" ]
20
Java
lionelherrerobattista/Programacion_Avanzada_I
4e4c461f829b0b2dbf5486106b36c0015639d8f4
6844bc90b862a17c3b7c3401606bb67228216dbf
refs/heads/master
<repo_name>MeetDevin/AminoAcidNet<file_sep>/utils/log_output.py # encoding: utf-8 """ @author: <NAME> @contact: <EMAIL> @file: log_output.py @time: 12/9/20 10:08 AM @desc: """ from datetime import datetime import sys class Logger(object): """Writes both to file and terminal""" def __init__(self, log_path, is_print=False, mode='a'): self.terminal = sys.stdout self.log = open(log_path, mode) self.is_print = is_print def write(self, *message, end='\n', join_time=False): if join_time: string = datetime.now().strftime('%Y-%m-%d %H:%M:%S') \ + ": " + str.join(" ", [str(a) for a in message]) + end else: string = " " + str.join(" ", [str(a) for a in message]) + end if self.is_print: self.terminal.write(string) self.log.write(string) def flush(self): self.log.flush() # this flush method is needed for python 3 compatibility. # this handles the flush command by doing nothing. # you might want to specify some extra behavior here. pass <file_sep>/data_engineer/pdb_cleansing/select_residues.py # encoding: utf-8 """ @author: <NAME> @contact: <EMAIL> @file: pdb_parser.py @time: 6/6/21 4:08 PM @desc: fork from https://github.com/manasa711/Protein-Binding-Site-Visualization addition features to save new pdb """ import platform import os import numpy as np from collections import defaultdict as ddict from utils.exception_message import ExceptionPassing from utils.log_output import Logger logger = Logger(log_path='//output/logs/select_residue.log', is_print=False) def _continuity_check(res_list): """ :param res_list: like ['2', '3', '3A', '4', '7', ...] :return: fix missing but remains special elements like 3A -> ['2', '3', '3A', '4', '5', '6', '7'] """ start = res_list[0] end = res_list[-1] if not start.isdigit(): # start = re.findall(r'\d+', start) # op 1 start = ''.join(e for e in start if e.isdigit()) # op 2 more pythonic if not end.isdigit(): # end = re.findall(r'\d+', end) end = ''.join(e for e in end if e.isdigit()) idx_list = range(int(start), int(end) + 1) # [2, 3, 4, 5, 6, 7] point_res = 0 point_idx = 0 final_res = [] while True: try: idx = str(idx_list[point_idx]) res = res_list[point_res] except IndexError: break if res == idx: final_res.append(res) point_idx += 1 point_res += 1 elif not res.isdigit(): # or res not in idx_list final_res.append(res) point_res += 1 else: final_res.append(idx) point_idx += 1 return final_res def _search_bind_sites(pdb_file, bind_radius, chain1, chain2): file = open(pdb_file, 'r') # creating lists with the coordinates of CA atoms from both the chains CA_atoms_ch1 = [] CA_atoms_ch2 = [] for line in file.readlines(): if line.startswith('ATOM'): # elem = line.split() # # if elem[2] == 'CA': # is_ch_id = elem[4] # if is_ch_id.isalpha(): # chain_id = is_ch_id # aa_idx = elem[5] # x = elem[6] # y = elem[7] # z = elem[8] # else: # A1099A -> A 1099A # chain_id = is_ch_id[0] # aa_idx = is_ch_id[1:] # x = elem[5] # y = elem[6] # z = elem[7] chain_id = line[21].strip() res_seq = line[22:26].strip() x = line[30:38].strip() y = line[38:46].strip() z = line[46:54].strip() if chain_id == chain1: CA_atoms_ch1.append([res_seq, x, y, z]) elif chain_id == chain2: CA_atoms_ch2.append([res_seq, x, y, z]) file.close() # calculating Euclidean Distance between CA atoms of chain 1 and CA atoms of chain2 bind_sites_1 = [] # list with interface atoms from chain 1 bind_sites_2 = [] # list with interface atoms from chain 2 for CA_i in CA_atoms_ch1: for CA_j in CA_atoms_ch2: x1 = float(CA_i[1]) y1 = float(CA_i[2]) z1 = float(CA_i[3]) x2 = float(CA_j[1]) y2 = float(CA_j[2]) z2 = float(CA_j[3]) e = ((x1 - x2) ** 2) + ((y1 - y2) ** 2) + ((z1 - z2) ** 2) euc = e ** 0.5 if euc <= bind_radius: if CA_i[0] not in bind_sites_1: bind_sites_1.append(CA_i[0]) # We have to do this loop twice, to maintain the original order of amino acid for CA_j in CA_atoms_ch2: for CA_i in CA_atoms_ch1: x1 = float(CA_i[1]) y1 = float(CA_i[2]) z1 = float(CA_i[3]) x2 = float(CA_j[1]) y2 = float(CA_j[2]) z2 = float(CA_j[3]) e = ((x1 - x2) ** 2) + ((y1 - y2) ** 2) + ((z1 - z2) ** 2) euc = e ** 0.5 if euc <= bind_radius: if CA_j[0] not in bind_sites_2: bind_sites_2.append(CA_j[0]) if len(bind_sites_1) == 0 or len(bind_sites_2) == 0: raise ExceptionPassing(' can not find binding sites, maybe due to error chain selection: \n', ' - bind_sites: ', bind_sites_1, bind_sites_2, pdb_file) bind_sites_1 = _continuity_check(bind_sites_1) bind_sites_2 = _continuity_check(bind_sites_2) return bind_sites_1, bind_sites_2 def save_bind_sites(pdb_file, save_dir, rec_chains, lig_chains, bind_radius): if platform.system() == 'Windows': pdb_id = pdb_file.split('\\')[-1].replace('.pdb', '') else: pdb_id = pdb_file.split('/')[-1].replace('.pdb', '') # get residues index of binding site final_res = ddict(set) for cr in rec_chains: for cl in lig_chains: try: bs1, bs2 = _search_bind_sites(pdb_file, bind_radius, cr, cl) except ExceptionPassing as e: logger.write(e.message, join_time=False) # logger.flush() break for res_seq in bs1: final_res[cr].add(res_seq) for res_seq in bs2: final_res[cl].add(res_seq) # save pdb chain_ids = np.concatenate([rec_chains, lig_chains], axis=0) if not os.path.exists(save_dir): os.makedirs(save_dir) new_file = open(save_dir + pdb_id + '_bind_site.pdb', 'a') for line in open(pdb_file, 'r'): if line.startswith('ATOM'): chain_id = line[21].strip() res_seq = line[22:26].strip() if chain_id in chain_ids and res_seq in list(final_res[chain_id]): new_file.write(line) if line.startswith('HETATM') and line[17:20].strip() == 'HOH': new_file.write(line) new_file.close() logger.write(pdb_id, '_bind_sites: ', final_res.values(), join_time=False) logger.flush() if __name__ == "__main__": save_bind_sites(pdb_file='/media/zhangxin/Raid0/dataset/PP/single_complex/2/1a4y.pdb', save_dir='/media/zhangxin/Raid0/dataset/PP/single_complex/bind_sites/test/', bind_radius=10, rec_chains=['A'], lig_chains=['B']) <file_sep>/data_engineer/affinity_parser.py # encoding: utf-8 """ @author: <NAME> @contact: <EMAIL> @file: affinity_parser.py @time: 1/19/21 5:21 PM @desc: """ import re def get_affinity(file_path): key_value_pairs = [] with open(file_path, "r") as f: lines = f.readlines()[6:] # start by line 7 # line can be like those: # 3sgb 1.80 1983 Kd=17.9pM // 3sgb.pdf (56-mer) TURKEY OVOMUCOID INHIBITOR (OMTKY3), 1.79 x 10-11M # 2tgp 1.90 1983 Kd~2.4uM // 2tgp.pdf (58-mer) TRYPSIN INHIBITOR, 2.4 x 10-6M # 1ihs 2.00 1994 Ki=0.3nM // 1ihs.pdf (21-mer) hirutonin-2 with human a-thrombin, led to Ki=0.3nM for line in lines: line = line.split() id = str(line[0]) affinity_str = str(line[3]) v = re.findall(r"\d+\.?\d*", affinity_str)[0] unit = affinity_str[-2:] if unit == 'uM': affinity = float(str(v)) if unit == 'nM': affinity = float(str(v))/1000 if unit == 'pM': affinity = float(str(v))/1000000 if unit == 'fM': affinity = float(str(v))/1000000000 key_value_pairs.append([id, affinity]) return dict(key_value_pairs) <file_sep>/utils/loader_from_h5.py # encoding: utf-8 """ @author: <NAME> @contact: <EMAIL> @file: loader_from_h5.py @time: 5/26/21 11:40 AM @desc: """ import h5py import torch from torch.utils.data import DataLoader def get_loader(filename, batch_size): dataset = H5PytorchDataset(filename) print('construct dataloader... total: ', dataset.__len__(), ', ', batch_size, ' per batch.') return torch.utils.data.DataLoader(dataset, batch_size=batch_size, sampler=None, collate_fn=None, shuffle=True, num_workers=4) def collation(): pass def get_train_test_validation_sampler(ratio_test, ratio_val): pass class H5PytorchDataset(torch.utils.data.Dataset): def __init__(self, filename): super(H5PytorchDataset, self).__init__() self.h5py_file = h5py.File(filename, 'r') self.num_samples, self.num_atoms = self.h5py_file['res_idx'].shape def __getitem__(self, index): atom_fea = torch.Tensor(self.h5py_file['atom_fea'][index]) atom_3d = torch.Tensor(self.h5py_file['atom_3d'][index]) edge = torch.Tensor(self.h5py_file['edge'][index]) res_idx = torch.Tensor(self.h5py_file['res_idx'][index]) affinity = torch.Tensor(self.h5py_file['affinity'][index]) return atom_fea, atom_3d, edge, res_idx, affinity def __len__(self): return self.num_samples <file_sep>/data_engineer/elem_periodic_map.py # encoding: utf-8 """ @author: <NAME> @contact: <EMAIL> @file: build_h5.py @time: 5/25/21 11:34 AM @desc: """ # serial mol row_in_periodic n_ele atoms_periodic_dic = { 'H': [1, 1.008, 1, 1], 'C': [6, 12.011, 2, 4], 'N': [7, 14.007, 2, 5], 'O': [8, 15.999, 2, 6], 'S': [16, 32.06, 3, 6] } # where groups20.txt is located, 167 heavy atoms in 20 amino acids groups20_path = '/preprocess/data_engineer/groups20.txt' # Create a one-hot encoded feature map for each protein atom heavy_atom_idx_dic = {} # dic with open(groups20_path, 'r') as f: data = f.readlines() for idx, line in enumerate(data): name, _ = line.split(" ") heavy_atom_idx_dic[name] = idx <file_sep>/data_engineer/pdb_cleansing/select_chain.py # encoding: utf-8 """ @author: <NAME> @contact: <EMAIL> @file: pdb_parser.py @time: 12/8/20 11:36 AM @desc: """ from Bio.PDB.Polypeptide import is_aa import numpy as np import os from Bio.PDB import PDBParser, PDBIO, Select import platform from utils.log_output import Logger logger = Logger(log_path='//output/logs/select_chain.log', is_print=False) def get_single_complex_type_R(structure, header): structs_dic = {} for mdl in structure: for chain in mdl: structs_dic[chain.get_id()] = chain rec_id = [] lig_id = [] n_mdl = len(header['compound']) compound = header['compound'] last_struct = None describ_list = [] target_chain = [] # easy method: assume H/L are Heavy/Light chains --------------------- if 'H' in structs_dic.keys() and 'L' in structs_dic.keys(): rec_id.append('H') rec_id.append('L') lig = 'z' for mdl_id, mdl in compound.items(): chain_list = mdl['chain'] if 'h' in chain_list or 'l' in chain_list: continue last_d = 999 for c in chain_list: if c.isalpha(): chain = structs_dic.get(c.upper()) d1 = calculate_distance(structs_dic['H'], chain) d2 = calculate_distance(structs_dic['L'], chain) d = min(d1, d2) if d < last_d and d != 0: last_d = d lig = c.upper() lig_id.append(lig) return rec_id, lig_id, n_mdl # normal method ------------------------------------------------------- for mdl_id, mdl in compound.items(): chain_list = mdl['chain'] # which chain to select in each model -------- c_id = 'z' if len(target_chain) == 0: for c in chain_list: if c.isalpha() and c < c_id: c_id = c.upper() last_struct = structs_dic.get(c_id.upper()) else: last_d = 999 for c in chain_list: if c.isalpha(): chain = structs_dic.get(c.upper()) distance = calculate_distance(last_struct, chain) if distance < last_d and distance != 0: last_d = distance last_struct = chain c_id = c.upper() target_chain.append(c_id) describ_list.append(mdl['molecule']) # print('\n after select by distance:') # print('target_chain: ', target_chain) # print('describ_list: ', describ_list) # whether receptor or ligand ------------ if n_mdl == 1: pass if n_mdl == 2: rec_id.append(target_chain[0]) lig_id.append(target_chain[1]) if n_mdl >= 3: for des, c in zip(describ_list, target_chain): keywords = 'fab light heavy receptor' if any(w in des and w for w in keywords.split()): rec_id.append(c) else: lig_id.append(c) return rec_id, lig_id, n_mdl def calculate_distance(chain1, chain2): min_distance = 99 for residue1 in chain1: if is_aa(residue1, standard=True): for residue2 in chain2: if is_aa(residue2, standard=True): try: atom1 = residue1['CA'] atom2 = residue2['CA'] distance = np.linalg.norm(atom1.get_coord() - atom2.get_coord()) if distance < min_distance: min_distance = distance except KeyError: continue else: # print(residue1, residue2, 'non - amino acid !!!!!!!!!!!!!!') continue else: continue # print('average_distance: ', distance/n, chain1, chain2) return min_distance # def get_single_complex_by_ascii(header): # """ # To remove duplicate chains in pdb # :param dic: # :return: # """ # select_id = [] # interest_dic = ddict(str) # for k, v in header.items(): # if v not in interest_dic.values(): # interest_dic[k] = v # select_id.append(k) # else: # for old_k, old_v in list(interest_dic.items()): # if v == old_v: # if k < old_k: # interest_dic.pop(old_k) # interest_dic[k] = v # select_id.remove(old_k) # select_id.append(k) # print('\n after select_by_ascii: ') # for k, v in interest_dic.items(): # print(k, v) # return select_id class ChainSelect(Select): def __init__(self, target_chain_ids): self.target_chain_ids = target_chain_ids def accept_chain(self, chain): return chain.id in self.target_chain_ids def save_single_complex_chains(file_path, out_dir): p = PDBParser(QUIET=True, get_header=True) if platform.system() == 'Windows': pdb_id = file_path.split('\\')[-1].replace('.ent.pdb', '') else: pdb_id = file_path.split('/')[-1].replace('.ent.pdb', '') try: structure = p.get_structure(file=file_path, id=pdb_id) header = p.get_header() # trailer = p.get_trailer() except ValueError as ve: print(ve, file_path) raise ValueError # print('header: ') # for k, v in header.items(): # print(k, ' : ', v) # print('\nstructure: ') # for mdl in structure: # for chain in mdl: # print(mdl.get_id(), chain.get_id()) # seq_header = lines_reader(file_path) # print('\nheader: ') # for k, v in seq_header.items(): # print(k, v) # select_by_ascii(seq_header) rec_id, lig_id, n_mdl = get_single_complex_type_R(structure, header) # save pdb if len(rec_id) != 0 and len(lig_id) != 0: io = PDBIO() io.set_structure(structure) save_dir = out_dir + str(n_mdl) + '/' if not os.path.exists(save_dir): os.makedirs(save_dir) sava_name = pdb_id + '_'.join(e for e in rec_id) + '_'.join(e for e in lig_id) + '.pdb' io.save(file=save_dir + sava_name, select=ChainSelect(np.concatenate([rec_id, lig_id], axis=0))) logger.write('grep ', rec_id, lig_id, pdb_id, '>', pdb_id + '.pdb', join_time=True) logger.flush() if __name__ == "__main__": save_single_complex_chains(file_path='/media/zhangxin/Raid0/dataset/PP/4f0z.ent.pdb', out_dir='') <file_sep>/network/readme_for_net_structure.py # encoding: utf-8 """ @author: <NAME> @contact: <EMAIL> @time: 2022/8/24 17:17 @desc: """ <file_sep>/data_engineer/build_pickle.py # import json import os import pickle from os.path import isfile, join from joblib import Parallel, delayed from tqdm import tqdm import numpy as np from arguments import build_parser from data_engineer.protein_parser import build_protein_graph parser = build_parser() args = parser.parse_args() parallel_jobs = args.parallel_jobs def thread_read_write(json_filepath, pkl_filepath): """ Writes and dumps the processed pkl file for each json file. Process json files by data_engineer.protein_parser import build_node_edge """ with open(json_filepath, 'r') as file: json_data = json.load(file) atoms = json_data['atoms'] # [n_atom, 1] res_idx = json_data['res_idx'] # [n_atom] bonds = json_data['bonds'] contacts = json_data['contacts'] # # [n_atom, 5], [n_atom, 25, 3], [n_atom, 3] # atom_fea, neighbor_map, pos = build_node_edge(atoms, bonds, contacts, PyG_format=False) # [n_atom, 3], [n_atom, 5], [n_atom, n_nei], [n_atom, n_nei, 2] pos, atom_fea, edge_idx, edge_attr = build_protein_graph(atoms, bonds, contacts, PyG_format=False) # print(np.shape(pos), np.shape(atom_fea), np.shape(edge_idx), np.shape(edge_attr)) with open(pkl_filepath, 'wb') as file: pickle.dump(pos, file) pickle.dump(atom_fea, file) pickle.dump(edge_idx, file) pickle.dump(edge_attr, file) pickle.dump(res_idx, file) def make_pickle(json_dir, pkl_dir): # Generate pickle files for each pdb file - naming convention is <protein name><pdb name>.pkl if not os.path.exists(pkl_dir): os.makedirs(pkl_dir) # python no parallel for calculation but for i/o read_write_path = [] for json_file in os.listdir(json_dir): json_filepath = join(json_dir, json_file) if isfile(json_filepath) and json_file.endswith('.json'): pdb_id = str(json_file)[0:4] pkl_filepath = pkl_dir + pdb_id + '.pkl' read_write_path.append((json_filepath, pkl_filepath)) print('analysis protein and do i/o from json to pkl use parallel:') Parallel(n_jobs=parallel_jobs)( delayed(thread_read_write)(json_filepath, pkl_filepath) for (json_filepath, pkl_filepath) in tqdm(read_write_path)) if __name__ == "__main__": make_pickle(json_dir='/media/zhangxin/Raid0/dataset/PP/single_complex/bind_sites/json_dir/2/', pkl_dir='/media/zhangxin/Raid0/dataset/PP/single_complex/bind_sites/pkl/test/') <file_sep>/readme.md A DeepLearning project about antibody engineering, hope to give some help to against SARS-CoV-2. Atom Conv3d based on point cloud analysis. <file_sep>/data_engineer/load_from_pkl.py # encoding: utf-8 """ @author: <NAME> @contact: <EMAIL> @file: load_from_pkl.py @time: 5/12/21 5:46 PM @desc: """ import os import numpy as np import platform import pickle import random import glob import torch from torch.utils.data import Dataset from arguments import build_parser from data_engineer.affinity_parser import get_affinity parser = build_parser() args = parser.parse_args() batch_size = args.batch_size random_seed = args.random_seed parallel_jobs = args.parallel_jobs def get_loader(pkl_dir, affinities_path): dataset = PickleDataset(pkl_dir, affinities_path) print('construct dataloader... total: ', dataset.__len__(), ', ', batch_size, ' per batch.') return torch.utils.data.DataLoader(dataset, batch_size=batch_size, sampler=None, collate_fn=collate_padding, shuffle=True, num_workers=parallel_jobs) def get_train_test_validation_sampler(ratio_test, ratio_val): pass def collate_padding(batch): """ Do padding while stack batch in torch data_loader :param batch shape=[bs, 6], and 6 for tuple: (pos, atom_fea, edge_idx, edge_attr, res_idx, affinity) single tensor: [n_atom, 3], [n_atom, 5], [n_atom, n_nei], [n_atom, m_nei, 2], [n_atom] """ max_n_atom = max([x[0].size(0) for x in batch]) # get max atoms n_ngb = batch[0][2].size(1) # num neighbors are same for all so take the first value bs = len(batch) # Batch size # all zeros final_pos = torch.zeros(bs, max_n_atom, 3) final_atom_fea = torch.zeros(bs, max_n_atom, 5) final_edge_idx = torch.zeros(bs, max_n_atom, n_ngb).type(torch.LongTensor) final_edge_attr = torch.zeros(bs, max_n_atom, n_ngb, 2) # final_neighbor_map = torch.zreros(bs, max_n_atom, 25, 3) final_res_idx = torch.zeros(bs, max_n_atom).type(torch.LongTensor) final_atom_mask = torch.zeros(bs, max_n_atom) final_affinity = torch.zeros(bs, 1) # amino_base_idx = 0 # start number of 1st atom batch_protein_ids, amino_crystal = [], 0 for i, (pos, atom_fea, edge_idx, edge_attr, res_idx, affinity) in enumerate(batch): num_atom = atom_fea.size(0) """[n_atom, 3], [n_atom, 5], [n_atom, n_nei], [n_atom, m_nei, 2], [n_atom], 1 """ final_pos[i][:num_atom, :] = pos final_atom_fea[i][:num_atom, :] = atom_fea final_edge_idx[i][:num_atom, :] = edge_idx final_edge_attr[i][:num_atom, :, :] = edge_attr # renumber amino acids in a batch # Final shape of res_idx in a batch: # [000 111 22222 00000] base = 2+1 # [33 4444 55555 33333] base = 5+1 # [6666 777 888 99 666] base = 9+1 final_res_idx[i][:num_atom] = res_idx # + amino_base_idx # list + int # final_res_idx[i][num_atom:] = amino_base_idx # amino_base_idx += torch.max(res_idx) + 1 final_affinity[i] = affinity final_atom_mask[i][:num_atom] = 1 # donate the ture atom rather a padding # new_batch.append([(final_atom_fea, final_pos, final_neighbor_map, final_res_idx, final_atom_mask), # (final_affinity, pdb_id)]) amino_crystal += 1 return [final_pos, final_atom_fea, final_edge_idx, final_edge_attr, final_res_idx, final_atom_mask], final_affinity class PickleDataset(Dataset): def __init__(self, pkl_dir, affinities_path, sample_rate=1): print("Starting pre-processing of raw data_engineer...") self.sample_rate = sample_rate self.affinity_dic = get_affinity(file_path=affinities_path) assert os.path.exists(pkl_dir), '{} does not exist!'.format(pkl_dir) # glob 查找符合特定规则的文件 full path. "*"匹配0个或多个字符;"?"匹配单个字符;"[]"匹配指定范围内的字符,[0-9]匹配数字。 self.filepath_list = self.file_filter(glob.glob(pkl_dir + '/*')) # list['filename', ...] random.seed(random_seed) random.shuffle(self.filepath_list) def __len__(self): return len(self.filepath_list) def __getitem__(self, idx): filepath = self.filepath_list[idx] if platform.system() == 'Windows': pdb_id = filepath.split('\\')[-1][0:4] else: pdb_id = filepath.split('/')[-1][0:4] with open(filepath, 'rb') as f: pos = torch.Tensor(pickle.load(f)) atom_fea = torch.Tensor(pickle.load(f)) edge_idx = torch.Tensor(pickle.load(f)).type(torch.LongTensor) edge_attr = torch.Tensor(pickle.load(f)) res_idx = torch.Tensor(pickle.load(f)).type(torch.LongTensor) # [n_atom, 3], [n_atom, 5], [n_atom, n_nei], [n_atom, m_nei, 2], [n_atom], 1 return pos, atom_fea, edge_idx, edge_attr, res_idx, self.affinity_dic.get(pdb_id) def file_filter(self, input_files): disallowed_file_endings = (".gitignore", ".DS_Store") allowed_file_endings = ".pkl" _input_files = input_files[:int(len(input_files) * self.sample_rate)] return list(filter(lambda x: not x.endswith(disallowed_file_endings) and x.endswith(allowed_file_endings), _input_files)) <file_sep>/data_engineer/pdb_cleansing/main_parallel.py # encoding: utf-8 """ @author: <NAME> @contact: <EMAIL> @file: main_parallel.py @time: 6/2/21 4:11 PM @desc: """ import glob import platform from data_engineer.pdb_cleansing.select_chain import save_single_complex_chains from data_engineer.pdb_cleansing.select_residues import save_bind_sites from joblib import Parallel, delayed from tqdm import tqdm from arguments import build_parser parser = build_parser() args = parser.parse_args() parallel_jobs = args.parallel_jobs bind_radius = args.bind_radius def process_chains(file_dir, out_dir): filepath_list = glob.glob(file_dir + '/*') filepath_list = file_filter(filepath_list) # list['filepath', ...] Parallel(n_jobs=parallel_jobs)(delayed(save_single_complex_chains)(file_path, out_dir) for file_path in tqdm(filepath_list)) def process_residues(log_path, file_dir, out_dir): filepath_list = glob.glob(file_dir + '/*') filepath_list = file_filter(filepath_list) # list['filepath', ...] chain_file_list = [] for line in open(log_path, 'r'): line = line.split() pdb_id = line[3] rec_chains = [x for x in line[1] if x.isalpha()] lig_chains = [x for x in line[2] if x.isalpha()] if len(rec_chains) == 0 or len(lig_chains) == 0: continue for file_path in filepath_list: if platform.system() == 'Windows': p_id = file_path.split('\\')[-1].replace('.pdb', '') else: p_id = file_path.split('/')[-1].replace('.pdb', '') if pdb_id == p_id: chain_file_list.append([rec_chains, lig_chains, file_path]) Parallel(n_jobs=parallel_jobs)(delayed(save_bind_sites) (file_path, out_dir, rec_chains, lig_chains, bind_radius=bind_radius) for [rec_chains, lig_chains, file_path] in tqdm(chain_file_list)) def file_filter(input_files): disallowed_file_endings = (".gitignore", ".DS_Store") allowed_file_endings = ".pdb" rate = 1 input_files = input_files[:int(len(input_files) * rate)] return list(filter(lambda x: not x.endswith(disallowed_file_endings) and x.endswith(allowed_file_endings), input_files)) if __name__ == "__main__": # process_chains(file_dir='/media/zhangxin/Raid0/dataset/PP/2/', # out_dir='/media/zhangxin/Raid0/dataset/PP/single_complex/2/') process_residues(log_path='//output/logs/select_chain.log', file_dir='/media/zhangxin/Raid0/dataset/PP/single_complex/2/', out_dir='/media/zhangxin/Raid0/dataset/PP/single_complex/bind_sites/2/') <file_sep>/network/chemical_unit.py # encoding: utf-8 """ @author: <NAME> @contact: <EMAIL> @file: chemical_unit.py @time: 5/18/21 4:01 PM @desc: """ import torch_geometric as geo import torch from torch.autograd import Variable from torch_geometric.nn import MessagePassing class ChemicalUnit(torch.nn.Module): def __init__(self, w_size=None, n_scale=3, n_neighbors=50): super(ChemicalUnit, self).__init__() if w_size is None: w_size = [19, 3] self.w_size = w_size self.n_scale = n_scale self.n_neighbors = n_neighbors # encode properties of amino acid side chain, like charge, polar and hydrophobic, # we believed network will learn itself by training self.weight_unit = Variable(torch.FloatTensor(self.w_size), requires_grad=True) self.conv_f = torch.nn.Conv2d(in_channels=3, ) self.activate = torch.nn.Sigmoid() pass def forward(self, structure, neighbors, neighbors_index, atom_amino_idx): """ encode conformation and neighbors features of amino acid :param structure: 3D coor of amino acid :param neighbors: list [B, n_atom, n_neighbor=50, 43=40+3] :param neighbors_index: list [B, n_atom, n_neighbor=50] :param atom_amino_idx [B, n_atom] Mapping from the amino idx to atom idx :return: """ motion = () new_structure = torch.bmm(structure, motion) # use coordinate to calculate loss for each amino acid weights coordinate = coordinate_parser(new_structure) output = None def F_motion(self, neighbors, neighbor_index, atom_amino_idx): """ Calculate average Force of side chain use neighbor atoms rather than amino acid, due to many strong chemical bond inside of amino acids, that to say each amino acid is a entry, so we consider the average Force. :param neighbors: [B, n_atom, n_neighbor=50, 43=40+3] :param neighbor_index: [B, n_atom, n_neighbor=50] :param atom_amino_idx [B, n_atom] Mapping from the amino idx to atom idx :return: """ atoms_non_this = [] def F_motion_by_conv(self, neighbors, neighbor_index, atom_amino_idx): pass <file_sep>/data_engineer/run_preprocess.py # encoding: utf-8 """ @author: <NAME> @contact: <EMAIL> @file: run_preprocess.py @time: 5/25/21 11:12 AM @desc: """ import os import glob import platform from subprocess import call from tqdm import tqdm from joblib import Parallel, delayed from arguments import build_parser parser = build_parser() args = parser.parse_args() parallel_jobs = args.parallel_jobs def json_cpp_commands(pdb_path, json_dir): """ Convert a single .pdb file to .json format Parameters ---------- pdb_file: The folder containing pdb files for a protein. """ if platform.system() == 'Windows': pdb_id = pdb_path.split('\\')[-1].replace('.pdb', '') else: pdb_id = pdb_path.split('/')[-1].replace('.pdb', '') json_path = json_dir + pdb_id + '.json' command = '/home/zhangxin/ACS/github/AminoAcidNet/data_engineer/preprocess/get_features' + ' -i ' + pdb_path + ' -j ' + json_path + ' -d 8.0' call(command, shell=True) def make_json(pdb_dir, json_dir): if not os.path.exists(json_dir): os.makedirs(json_dir) path_list = glob.glob(pdb_dir + '/*') pdb_files = file_filter(path_list) Parallel(n_jobs=parallel_jobs)(delayed(json_cpp_commands)(pdb_path, json_dir) for pdb_path in tqdm(pdb_files)) def file_filter(input_files): disallowed_file_endings = (".gitignore", ".DS_Store") allowed_file_endings = ".pdb" rate = 1 allowed_inputs = [] for file in input_files: if os.path.isfile(file): if not file.endswith(disallowed_file_endings) and file.endswith(allowed_file_endings): allowed_inputs.append(file) return allowed_inputs[:int(len(allowed_inputs) * rate)] if __name__ == "__main__": print('read pdb files to json files:') make_json(pdb_dir='/media/zhangxin/Raid0/dataset/PP/single_complex/bind_sites/2/', json_dir='/media/zhangxin/Raid0/dataset/PP/single_complex/bind_sites/json_dir/2/') <file_sep>/utils/algorithm.py # encoding: utf-8 """ @author: <NAME> @contact: <EMAIL> @time: 2022/7/28 11:45 @desc: """ import numpy as np def dichotomy_account_in_sorted(sorted_list, key): l = 0 r = len(sorted_list) - 1 # find the left bound while l < r: mid = (r + l) // 2 if sorted_list[mid] < key: l = mid + 1 else: r = mid # involving mid==key, so the r isn't right left = l # find the right bound l = 0 r = len(sorted_list) - 1 while l < r: mid = (r+l) // 2 if sorted_list[mid] <= key: l = mid + 1 else: l = mid right = l return right - left if __name__ == '__main__': l = dichotomy_account_in_sorted([1, 2, 3, 3, 3, 4], 1) print(l) <file_sep>/arguments.py import configargparse def build_parser(): parser = configargparse.ArgParser(default_config_files=['settings.conf']) # parser.add_argument('-pdb_dir', default='/media/zhangxin/Raid0/dataset/PP/', # help='Directory where all protein pdb files exist') # parser.add_argument('-pkl_dir', default='media/zhangxin/Raid0/dataset/PP/pkl/') # parser.add_argument('-json_dir', default='/media/zhangxin/Raid0/dataset/PP/json/') # parser.add_argument('-h5_dir', default='/media/zhangxin/Raid0/dataset/PP/h5/') # parser.add_argument('-h5_name', default='h5_dataset_id') # parser.add_argument('-cpp_executable', default='preprocess/get_features', # help='Directory where cpp cpp_executable is located') parser.add_argument('-parallel_jobs', default=20, help='Number of threads to use for parallel jobs') parser.add_argument('-get_json_files', default=False, help='Whether to fetch json files or not', action='store_true') parser.add_argument('-override_h5_dataset', default=True, help='Whether to fetch h5 dataset or not') parser.add_argument('-max_neighbors', default=15) parser.add_argument('-bind_radius', default=30) parser.add_argument('-inputs_padding', default=True) # Training setup parser.add_argument('--random_seed', default=123, help='Seed for random number generation', type=int) parser.add_argument('--epochs', default=100, help='Number of epochs', type=int) parser.add_argument('--batch_size', default=3, help='Batch size for training', type=int) parser.add_argument('--train', default=0.5, help='Fraction of training data_engineer', type=float) parser.add_argument('--val', default=0.25, help='Fraction of validation data_engineer', type=float) parser.add_argument('--test', default=0.25, help='Fraction of test data_engineer', type=float) parser.add_argument('--testing', help='If only testing the model', action='store_true') # Optimizer setup parser.add_argument('--lr', default=0.001, help='Learning rate', type=float) # Model setup parser.add_argument('--h_a', default=64, help='Atom hidden embedding dimension', type=int) parser.add_argument('--h_g', default=32, help='Graph hidden embedding dimension', type=int) parser.add_argument('--n_conv', default=4, help='Number of convolution layers', type=int) # Other features parser.add_argument('--save_checkpoints', default=True, help='Stores checkpoints if true', action='store_true') parser.add_argument('--print_freq', default=10, help='Frequency of printing updates between epochs', type=int) parser.add_argument('--workers', default=20, help='Number of workers for data_engineer loading', type=int) return parser <file_sep>/utils/exception_message.py # encoding: utf-8 """ @author: <NAME> @contact: <EMAIL> @file: exception_message.py @time: 3/6/19 @desc: 自定义异常类 """ class ExceptionPassing(Exception): """ 继承自基类 Exception """ def __init__(self, *message, expression=None): super(ExceptionPassing, self).__init__(message) self.expression = expression self.message = str.join('', [str(a) for a in message]) <file_sep>/network/graph.py # encoding: utf-8 """ @author: <NAME> @contact: <EMAIL> @time: 7/26/22 10:26 AM @desc: ALL parameters are >0, and ==0 indicates None or unknown. """ import torch class Atom: def __init__(self, name, id=0, n_bond=4): """bonds: a list involves Bond id""" self.name = name self.id = id self.n_bond = n_bond def to_tensor(self): return torch.Tensor([self.name, self.id, self.n_bond]) class Bond: def __init__(self, name, id=0, distance=2, electrons=0, t1=0, t2=0): self.name = name self.id = id self.distance = distance self.electrons = electrons # single/double-bond self.t1 = t1 # terminal 1 self.t2 = t2 # terminal 2 def to_tensor(self): return torch.Tensor[self.name, self.id, self.distance, self.electrons, self.t1, self.t2] class Formula: def __init__(self, name, id=0, atoms=None, bonds=None): self.name = name self.id = id self.chemical_check(atoms, bonds) self.atoms = atoms self.bonds = bonds def chemical_check(self, atoms, bonds): """check in-degree of all atoms @atoms: tensor [name, id, n_bond], assert atoms are sorted by id. @bonds: ditto [name, id, distance, electrons, t1, t2] algorithm ideas: bonds->slice->flatten->sort->count == atoms->slice->sort ? """ terminal_12 = torch.index_select(bonds, dim=1, index=torch.Tensor([4, 5])) # t1, t2 terminals = terminal_12.flatten() # .view(.numel()) # .reshape(-1) sorted_terminals = torch.sort(terminals, dim=0) _, count1 = sorted_terminals.unique(return_count=True) bond_degree = atoms[:, -1] assert bond_degree.equal(count1), 'chemical checking failed' # _bonds = sum(bonds, []) # multiple dimension to one dimension, sort # for atom in atoms: # assert atom.n_bond == len(atom.bonds) # assert atom.n_bond == pass def chemical_integrate(atoms, bonds, key, n=2, res=False): if n < 2: return key if n == 2: # '-OH' return ['-OH', '-SH'] if n == 3: return ['-NH2', '-CH2', ''] if n == 4: pass <file_sep>/utils/build_h5.py # encoding: utf-8 """ @author: <NAME> @contact: <EMAIL> @file: build_h5.py @time: 5/25/21 11:34 AM @desc: """ import os import json from tqdm import tqdm from joblib import Parallel, delayed import threading import numpy as np import h5py from data_engineer.affinity_parser import get_affinity from arguments import build_parser from data_engineer.protein_parser import build_protein_graph parser = build_parser() args = parser.parse_args() override_h5_dataset = args.override_h5_dataset parallel_jobs = args.parallel_jobs max_neighbors = args.max_neighbors MAX_N_PROTEIN = 9999 MAX_N_ATOM = 99999 # 氨基酸主链的最大队列长度 # global current_n_atom # global file_point # global current_buffer_size # file_point = 0 # current_buffer_size = 1 # current_n_atom = 1 # run interface def make_h5_dataset(json_dir, h5_dir, h5_name): # Generate pickle files for each pdb file - naming convention is <protein name><pdb name>.pkl if not os.path.exists(h5_dir): os.makedirs(h5_dir) # 如果 .hdf5 文件已经存在,选择强制写入还是跳过 if os.path.isfile(h5_dir + h5_name + '.hdf5'): print("Preprocessed file for [" + h5_name + "] already exists.") if override_h5_dataset: print("force_pre_processing_overwrite flag set to True, overwriting old file...") os.remove(h5_dir + h5_name + '.hdf5') construct_h5db_from_list(json_dir, h5_dir, h5_name) else: print("Skipping pre-processing...") else: construct_h5db_from_list(json_dir, h5_dir, h5_name) print("Completed pre-processing.") def thread_read(json_file): json_filepath = args.json_dir + json_file with open(json_filepath, 'r') as file: json_data = json.load(file) atoms = json_data['atoms'] # [n_atom, 1] res_idx = json_data['res_idx'] # [n_atom] bonds = json_data['bonds'] contacts = json_data['contacts'] # [n_atom, 5], [n_atom, 25, 3], [n_atom, 3] atom_fea, neighbor_map, atom_3d = build_protein_graph(atoms, bonds, contacts) n_atom = len(atoms) return n_atom, atom_fea, neighbor_map, atom_3d, res_idx def construct_h5db_from_list(json_dir, h5_dir, h5_name): all_json_files = [json_file for json_file in os.listdir(json_dir) if os.path.isfile(os.path.join(json_dir, json_file)) and json_file.endswith('.json')] num_files = len(all_json_files) affinity_dic = get_affinity(file_path='/media/zhangxin/Raid0/dataset/PP' + '/index/INDEX_general_PP.2019') print('build h5 dataset from ' + str(num_files) + ' json files: ') file_point = 0 current_n_protein = 1 current_n_atom = 1 # create output file file = h5py.File(h5_dir + h5_name + '.hdf5', 'w') dataset_atom = file.create_dataset(name='atom_fea', shape=(current_n_protein, current_n_atom, 5), maxshape=(MAX_N_PROTEIN, MAX_N_ATOM, 5), dtype='float', chunks=True) dataset_3d = file.create_dataset(name='atom_3d', shape=(current_n_protein, current_n_atom, 3), maxshape=(MAX_N_PROTEIN, MAX_N_ATOM, 3), dtype='float', chunks=True) dataset_edge = file.create_dataset(name='edge', shape=(current_n_protein, current_n_atom, max_neighbors, 3), maxshape=(MAX_N_PROTEIN, MAX_N_ATOM, max_neighbors, 3), dtype='float', chunks=True) dataset_res_idx = file.create_dataset(name='res_idx', shape=(current_n_protein, current_n_atom), maxshape=(MAX_N_PROTEIN, MAX_N_ATOM), dtype='float', chunks=True) dataset_affinity = file.create_dataset(name='affinity', shape=(current_n_protein, 1), maxshape=(MAX_N_PROTEIN, 1), dtype='float', chunks=True) print('use ' + str(parallel_jobs) + ' jobs to read json and analysis proteins.') for json_file in tqdm(all_json_files): pdb_id = json_file.replace('.json', '').replace('.ent', '') affinity = affinity_dic.get(pdb_id) # get affinity n_atom, atom_fea, neighbor_map, atom_3d, res_idx = Parallel(n_jobs=parallel_jobs)(delayed(thread_read)(json_file)) if n_atom > MAX_N_ATOM: # 跳过长度超过MAX_SEQUENCE_LEN的蛋白质 print("Dropping protein as length too long:", n_atom) return None # 追加空间分配 if n_atom > current_n_atom: current_n_atom = n_atom dataset_atom.resize(size=(current_n_protein, current_n_atom, 5)) dataset_3d.resize(size=(current_n_protein, current_n_atom, 3)) dataset_edge.resize(size=(current_n_protein, current_n_atom, max_neighbors, 3)) dataset_res_idx.resize(size=(current_n_protein, current_n_atom)) # 追加空间分配, file_point start with 0, 并且指向栈顶 if file_point >= current_n_protein: current_n_protein += 1 dataset_atom.resize(size=(current_n_protein, current_n_atom, 5)) dataset_3d.resize(size=(current_n_protein, current_n_atom, 3)) dataset_edge.resize(size=(current_n_protein, current_n_atom, max_neighbors, 3)) dataset_res_idx.resize(size=(current_n_protein, current_n_atom)) dataset_affinity.resize(size=(current_n_protein, 1)) # if args.inputs_padding: # primary_padded = np.zeros(MAX_N_ATOM) # tertiary_padded = np.zeros((MAX_N_ATOM, 9)) # atom_fea_padded = np.zeros() # # primary_padded[:length] = primary # tertiary_padded[:length, :] = tertiary # else: # primary_padded = primary # tertiary_padded = tertiary dataset_atom[file_point] = atom_fea dataset_3d[file_point] = atom_3d dataset_edge[file_point] = neighbor_map dataset_res_idx[file_point] = res_idx dataset_affinity[file_point] = affinity file_point += 1 if __name__ == "__main__": make_h5_dataset(json_dir=args.json_dir, h5_dir=args.h5_dir, h5_name=args.h5_name)<file_sep>/main.py import torch.nn.init from data_engineer.load_from_pkl import get_loader from arguments import build_parser parser = build_parser() args = parser.parse_args() # make_pickle(json_dir='/media/zhangxin/Raid0/dataset/PP/single_complex/bind_sites/json_dir/2/', # pkl_dir='/media/zhangxin/Raid0/dataset/PP/single_complex/bind_sites/pkl/2/') loader = get_loader(pkl_dir='/media/zhangxin/Raid0/dataset/PP/single_complex/bind_sites/pkl/2/', affinities_path='/media/zhangxin/Raid0/dataset/PP/index/INDEX_general_PP.2019') # models from network.conv import MoleculeConv from network.pooling import MoleculePooling # conv1 = AtomConv(kernel_num=32, k_size=10) # pool1 = AtomPooling(kernel_size=4, stride=4) conv1 = MoleculeConv(kernel_num=32, k_size=10, in_channels=1, node_fea_dim=5, edge_fea_dim=2) pool1 = MoleculePooling(kernel_size=4, stride=4) conv2 = MoleculeConv(kernel_num=16, k_size=10, in_channels=32, node_fea_dim=1) pool2 = MoleculePooling(kernel_size=4, stride=4) conv3 = MoleculeConv(kernel_num=8, k_size=5, in_channels=16, node_fea_dim=1) pool3 = MoleculePooling(kernel_size=4, stride=4) conv4 = MoleculeConv(kernel_num=4, k_size=5, in_channels=8, node_fea_dim=1) pool4 = MoleculePooling(kernel_size=4, stride=4) for [pos, atom_fea, edge_idx, edge_attr, res_idx, atom_mask], affinity in loader: # [bs, n_atom, 3], [bs, n_atom, 5], [bs, n_atom, n_nei], [bs, n_atom, m_nei, 2], [bs, n_atom], [bs] # add channel dimension pos = pos.unsqueeze(1) atom_fea = atom_fea.unsqueeze(1) edge_idx = edge_idx.unsqueeze(1) edge_attr = edge_attr.unsqueeze(1) h1, pos1 = conv1(pos, atom_fea, atom_mask, edge_idx, edge_attr) p_pos, p_fea, p_ridx, p_mask = pool1(pos1, h1, res_idx, atom_mask) h2, pos2 = conv2(p_pos, p_fea, p_mask) p_pos2, p_fea2, p_ridx2, p_mask2 = pool2(pos2, h2, p_ridx, p_mask) h3, pos3 = conv3(p_pos2, p_fea2, p_mask2) p_pos3, p_fea3, p_ridx3, p_mask3 = pool3(pos3, h3, p_ridx2, p_mask2) h4, pos4 = conv4(p_pos3, p_fea3, p_mask3) p_pos4, p_fea4, p_ridx4, p_mask4 = pool4(pos4, h4, p_ridx3, p_mask3) print(p_fea4.size()) pass # dataset = ProteinDataset(pkl_dir=args.pkl_dir, # atom_init_filename=args.atom_init) # loader = DataLoader(dataset, batch_size=3, collate_fn=collate_pool, shuffle=True, num_workers=10, pin_memory=False) # # # def getInputs(inputs, target): # """Move inputs and targets to cuda""" # # input_var = [inputs[0].cuda(), inputs[1].cuda(), inputs[2].cuda(), inputs[3].cuda(), inputs[4].cuda()] # target_var = target.cuda() # return input_var, target_var # # # parser = buildParser() # args = parser.parse_args() # for (atom_fea, nbr_fea, nbr_fea_idx, atom_amino_idx, atom_mask), (affinity, protein_id) in loader: # # structures, _ = dataset[0] # h_b = structures[1].shape[-1] # 2nd dim of structures # # build model # kwargs = { # 'pkl_dir': args.pkl_dir, # Root directory for data_engineer # 'atom_init': args.atom_init, # Atom Init filename # 'h_a': args.h_a, # Dim of the hidden atom embedding learnt # 'h_g': args.h_g, # Dim of the hidden graph embedding after pooling # 'n_conv': args.n_conv, # Number of GCN layers # # 'random_seed': args.seed, # Seed to fix the simulation # 'lr': args.lr, # Learning rate for optimizer # 'h_b': h_b # Dim of the bond embedding initialization # } # # # print("Let's use", torch.cuda.device_count(), "GPUs and Data Parallel Model.") # model = ProteinGCN(**kwargs) # # model = torch.nn.DataParallel(model) # # model.cuda() # # model.train() # # # inputs, target = getInputs([atom_fea, nbr_fea, nbr_fea_idx, atom_amino_idx, atom_mask], affinity) # inputs = [atom_fea, nbr_fea, nbr_fea_idx, atom_amino_idx, atom_mask] # out = model(inputs) # out = model.module.mask_remove(out) # # print(out) <file_sep>/network/conv.py # encoding: utf-8 """ @author: <NAME> @contact: <EMAIL> @file: conv.py @time: 6/9/21 4:55 PM @desc: """ import torch import torch.nn as nn import torch.nn.functional as F class MoleculeConv(nn.Module): """Extract and recombines structure and chemical elements features in multiple channels from local domain of protein graph in batch format, k_size denotes the range of domain. :param k_size: int, num of neighbor atoms which are considered :param kernel_num, int """ def __init__(self, kernel_num, k_size, in_channels, node_fea_dim, edge_fea_dim=1): super(MoleculeConv, self).__init__() self.kernel_num = kernel_num self.k_size = k_size self.in_channels = in_channels self.dim = node_fea_dim self.edge_fea_dim = edge_fea_dim self.leaky_relu = nn.LeakyReLU(inplace=True) self.relu = nn.ReLU(inplace=True) self.sigmoid = nn.Sigmoid() self.angle_weight = nn.Parameter(torch.FloatTensor(self.kernel_num, self.k_size*self.in_channels)) self.scalar_weight = nn.Parameter(torch.FloatTensor(2*self.in_channels*self.dim, self.kernel_num)) self.radius_weight_1 = nn.Parameter(torch.FloatTensor(self.edge_fea_dim, self.kernel_num)) self.radius_weight_2 = nn.Parameter(torch.FloatTensor(self.kernel_num, 1)) nn.init.uniform_(self.angle_weight, -1, 1) nn.init.uniform_(self.scalar_weight, 0, 1) nn.init.uniform_(self.radius_weight_1, -1, 1) nn.init.uniform_(self.radius_weight_2, -1, 1) def forward(self, pos: "(bs, c, n, 3)", node_fea: "(bs, c, n, d)", node_mask: "(bs, n)", edge_idx=None, edge_fea=None): """ Return: (bs, atom_num, kernel_num) """ # TODO: compatibility of pos fea in first layer bs, n = node_mask.size() if edge_idx is None: edge_fea, edge_idx = self.get_edge(pos) # [bs, c, n, k_size, 1], [bs, c, n, k_size] else: edge_idx = edge_idx[:, :, :, 0:self.k_size] edge_fea = edge_fea[:, :, :, 0:self.k_size, :] theta, mask_final = self.cos_theta(pos, edge_idx, node_mask) # [bs, n, k_size, c], [bs, c, n, k_size] fea_cat = self.feature_fusion(node_fea, edge_idx, node_mask) # [bs, n, k_size, c, 2*d] gate = self.message_gating(edge_fea, node_mask) # [bs, n, k_size, c] theta_channel = theta.reshape(bs, n, -1).unsqueeze(-1) # [bs, n, k_size*c, 1] # [bs, n, kernel_num, 1] to [bs, kernel_num, n, 1] fea_struct = torch.matmul(self.angle_weight, theta_channel).permute(0, 2, 1, 3) # [bs, n, k_size, c, 2*d] to # [bs, n, k_size, c*2*d] fea_gated = torch.mul(gate.unsqueeze(-1), fea_cat).reshape(bs, n, self.k_size, -1) fea_elem = torch.matmul(fea_gated, self.scalar_weight) # [bs, n, k_size, kernel_num] # [bs, n, 1, kernel_num] to [bs, kernel_num, n, 1] fea_elem = torch.sum(fea_elem, dim=2, keepdim=True).permute(0, 3, 1, 2) interactions = self.leaky_relu(fea_elem + fea_struct) # [bs, kernel_num, n, 1] interact_masked = torch.mul(mask_final, interactions) # TODO: more powerful method to embed positions of multiple channels new_pos = torch.div(torch.sum(pos, dim=1), self.in_channels) # [bs, n, 3] return interact_masked, new_pos def get_edge(self, pos: "(bs, c, n, 3)"): """ Return: (bs, atom_num, neighbor_num) """ # device = atoms.device # tensor.transpose(1, 2), transposes only 1 and 2 dim, =tf.transpose(0, 2, 1) inner = torch.matmul(pos, pos.transpose(2, 3)) # [bs, c, n, n] quadratic = torch.sum(pos ** 2, dim=3) # [bs, c, n] # [bs, c, n, n] + [bs, c, 1, n] + [bs, c, n, 1] distance = inner * (-2) + quadratic.unsqueeze(2) + quadratic.unsqueeze(3) ngh_distance, ngb_index = torch.topk(distance, k=self.k_size + 1, dim=-1, largest=False) # [bs, c, n, k_size+1] # distance reference itself is 0 and should be ignore # [bs, c, n, k_size+1] to [bs, c, n, k_size, 1] return ngh_distance[:, :, :, 1:].unsqueeze(-1), ngb_index[:, :, :, 1:] def indexing_neighbor(self, tensor: "(bs, c, n, dim)", index: "(bs, c, n, k_size)"): """ tensor: if pos dim=3, and dim=else for fea, c=1 for first layer Return: (bs, c, n, k_size, dim) """ bs, c, _, _ = index.size() idx_0 = torch.arange(bs).view(-1, 1, 1, 1) idx_1 = torch.arange(c).view(-1, 1, 1) tensor_indexed = tensor[idx_0, idx_1, index] return tensor_indexed def get_neighbor_direct_norm(self, pos: "(bs, c, n, dim)", ngb_index: "(bs, c, n, k_size)"): """ Return: (bs, c, n, k_size, 3) """ pos_ngb = self.indexing_neighbor(pos, ngb_index) # [bs, c, n, k_size, 3] neigh_direction = pos_ngb - pos.unsqueeze(3) # [bs, c, n, k_size, 3] - [bs, c, n, 1, 3] neigh_direction_norm = F.normalize(neigh_direction, dim=-1) # unit vector of distance return neigh_direction_norm def cos_theta(self, pos: "(bs, c, n, 3)", edge_index: "(bs, c, n, k_size)", node_mask: "(bs, n)"): """ Embed spatial features :return theta_masked [bs, n, k_size, c] :return mask_final [bs, kernel_num, n, 1]""" nei_direct_norm = self.get_neighbor_direct_norm(pos, edge_index) # [bs, c, n, k_size, 3] nearest = nei_direct_norm[:, :, :, 0, :].unsqueeze(3) # [bs, c, n, 1, 3] else_neigh = nei_direct_norm[:, :, :, 1:, :] # [bs, c, n, k_size-1, 3] theta = else_neigh @ nearest.transpose(3, 4) # [bs, c, n, k_size-1, 1] cos0_theta = F.pad(theta, [0, 0, 1, 0], value=1).squeeze(-1) # cos(0)=1, [bs, c, n, k_size] c = pos.size()[1] mask = node_mask.unsqueeze(1).repeat(1, c, 1).unsqueeze(-1) # [bs, c, n, 1] mask_final = node_mask.unsqueeze(1).repeat(1, self.kernel_num, 1).unsqueeze(-1) # [bs, kernel_num, n, 1] theta_masked = torch.mul(cos0_theta, mask).permute(0, 2, 3, 1) # [bs, n, k_size, c] return theta_masked, mask_final def feature_fusion(self, node_fea: "(bs, c, n, d)", index: "(bs, c, n, k_size)", node_mask: "(bs, n)"): """Fuse elements features, dim=5 in first layer and 1 for else layers""" bs, n = node_mask.size() fea_neigh = self.indexing_neighbor(node_fea, index) # [bs, c, n, k_size, d] node_reps_fea = node_fea.unsqueeze(3).repeat(1, 1, 1, self.k_size, 1) # [bs, c, n, k_size, d] # [bs, c, n, k_size, 2*d] to [bs, n, k_size, c, 2*d] fea_cat = torch.cat([node_reps_fea, fea_neigh], dim=-1).permute(0, 2, 3, 1, 4) mask = node_mask.unsqueeze(-1).unsqueeze(-1).unsqueeze(-1) return torch.mul(fea_cat, mask) def message_gating(self, distance: "(bs, c, n, k_size)", node_mask: "(bs, n)"): """Generate a gate to select elements features based on distance and bond type""" a = self.relu(torch.matmul(distance, self.radius_weight_1)) # [bs, c, n, k_size, kernel_num] # g = torch.max(a, dim=3)[0] # [bs, a_n, nei_n] b = self.relu(torch.matmul(a, self.radius_weight_2)).squeeze(-1) # [bs, c, n, k_size] mask = node_mask.unsqueeze(1).repeat(1, self.in_channels, 1).unsqueeze(-1).repeat(1, 1, 1, self.k_size) g = torch.mul(b, mask) # [bs, c, n, k_size] return self.sigmoid(g.permute(0, 2, 3, 1)) # def cos_theta(vectors: "(bs, a_n, nei_n, 3)"): # nei_n = vectors.size()[2] # assert nei_n % 2 == 0 # # fgs4 = torch.split(vectors, 4, dim=2) # theta4 = fgs4[0] @ fgs4[1].transpose(2, 3) # print(theta4.size()) # # fgs2 = torch.split(vectors, 2, dim=2) # theta2 = fgs2[0] @ fgs2[1].transpose(2, 3) # theta2_2 = fgs2[2] @ fgs2[3].transpose(2, 3) # print(theta2.size()) # # fgs1 = torch.split(vectors, 1, dim=2) # theta1 = fgs1[0] @ fgs1[1].transpose(2, 3) # theta1_2 = fgs1[2] @ fgs1[3].transpose(2, 3) # theta1_3 = fgs1[4] @ fgs1[5].transpose(2, 3) # theta1_4 = fgs1[6] @ fgs1[7].transpose(2, 3) # print(theta1.size()) # def indexing_neighbor(tensor: "(bs, atom_num, dim)", index: "(bs, atom_num, neighbor_num)"): # """ # Return: (bs, atom_num, neighbor_num, dim) torch.Size([3, 26670, 15]) # """ # bs = index.size(0) # id_0 = torch.arange(bs).view(-1, 1, 1) # tensor_indexed = tensor[id_0, index] # return tensor_indexed # # # def get_neighbor_direct_norm(atoms: "(bs, atom_num, 3)", neighbor_index: "(bs, atom_num, neighbor_num)"): # """ # Return: (bs, atom_num, atom_num, 3) # """ # pos_neighbors = indexing_neighbor(atoms, neighbor_index) # [bs, a_n, nei_n, 3] # neigh_direction = pos_neighbors - atoms.unsqueeze(2) # [bs, a_n, nei_n, 3] - [bs, a_n, 1, 3] # neigh_direction_norm = F.normalize(neigh_direction, dim=-1) # unit vector of distance # return neigh_direction_norm # class AtomConv(nn.Module): # """Extract and recombines structure and chemical elements features from local domain of protein graph # in batch format, k_size denotes the range of domain. # :param k_size: int, num of neighbor atoms which are considered # :param kernel_num, int # """ # # def __init__(self, kernel_num, k_size): # super(AtomConv, self).__init__() # self.kernel_num = kernel_num # self.k_size = k_size # # self.leaky_relu = nn.LeakyReLU(inplace=True) # self.relu = nn.ReLU(inplace=True) # self.sigmoid = nn.Sigmoid() # # self.angle_weight = nn.Parameter(torch.FloatTensor(kernel_num, k_size)) # k_size must equal neighbor_num # self.scalar_weight = nn.Parameter(torch.FloatTensor(10, kernel_num)) # self.radius_weight_1 = nn.Parameter(torch.FloatTensor(2, kernel_num)) # self.radius_weight_2 = nn.Parameter(torch.FloatTensor(kernel_num, 1)) # # nn.init.uniform_(self.angle_weight, -1, 1) # nn.init.uniform_(self.scalar_weight, 0, 1) # nn.init.uniform_(self.radius_weight_1, -1, 1) # nn.init.uniform_(self.radius_weight_2, -1, 1) # # def forward(self, pos: "(bs, atom_num, 3)", # atom_fea: "(bs, atom_num, 5)", # edge_index: "(bs, atom_num, nei_n)", # edge_fea: "(bs, atom_num, nei_n, 2)", # atom_mask: "(bs, atom_num)"): # """ # Return: (bs, atom_num, kernel_num) # """ # edge_index = edge_index[:, :, 0:self.k_size] # edge_fea = edge_fea[:, :, 0:self.k_size, :] # # theta, mask_final = self.cos_theta(pos, edge_index, atom_mask) # [bs, a_n, nei_n, 1] # fea_cat = self.feature_fusion(atom_fea, edge_index, atom_mask) # [bs, a_n, nei_n, 10] # gate = self.message_gating(edge_fea, atom_mask) # [bs, a_n, nei_n] # # fea_struct = torch.matmul(self.angle_weight, theta).squeeze() # [bs, a_n, kernel_num] # # fea_elem = torch.matmul(fea_cat, self.scalar_weight) # [bs, a_n, nei_n, kernel_num] # fea_elem = torch.mul(gate, fea_elem) # [bs, a_n, nei_n, kernel_num] # # fea_elem = torch.sum(fea_elem, dim=2).squeeze() # [bs, a_n, kernel_num] # # interactions = self.leaky_relu(fea_elem + fea_struct) # [bs, a_n, kernel_num] # interact_masked = torch.mul(mask_final, interactions) # return interact_masked # # def cos_theta(self, pos, edge_index, atom_mask): # """ # Embed spatial features # :return [bs, a_n, nei_n, 1] """ # nei_direct_norm = get_neighbor_direct_norm(pos, edge_index) # [bs, a_n, nei_n, 3] # nearest = nei_direct_norm[:, :, 0, :].unsqueeze(2) # [2, 15, 1, 3] # else_neigh = nei_direct_norm[:, :, 1:, :] # [2, 15, nei_n-1, 3] # theta = else_neigh @ nearest.transpose(2, 3) # [bs, a_n, nei_n-1, 1] # cos0_theta = F.pad(theta, [0, 0, 1, 0], value=1) # cos(0)=1 # # mask = atom_mask.unsqueeze(-1).repeat(1, 1, self.k_size).unsqueeze(-1) # mask_final = atom_mask.unsqueeze(-1).repeat(1, 1, self.kernel_num) # return torch.mul(cos0_theta, mask), mask_final # # def feature_fusion(self, fea: "(bs, atom_num, 5)", # index: "(bs, atom_num, neighbor_num)", # atom_max: "(bs, atom_num)"): # """Fuse elements features""" # fea_neigh = indexing_neighbor(fea, index) # [bs, a_n, nei_n, 5] # atom_reps_fea = fea.unsqueeze(2).repeat(1, 1, self.k_size, 1) # [bs, a_n, nei_n, 5] # fea_cat = torch.cat([atom_reps_fea, fea_neigh], dim=-1) # [bs, a_n, nei_n, 10] # # mask = atom_max.unsqueeze(-1).repeat(1, 1, self.k_size).unsqueeze(-1) # return torch.mul(fea_cat, mask) # # def message_gating(self, edge_fea, atom_mask): # """Generate a gate to select elements features based on distance and bond type""" # a = self.relu(torch.matmul(edge_fea, self.radius_weight_1)) # [bs, a_n, nei_n, kernel_num] # # g = torch.max(a, dim=3)[0] # [bs, a_n, nei_n] # b = self.relu(torch.matmul(a, self.radius_weight_2)).squeeze() # [bs, a_n, nei_n] # # mask = atom_mask.unsqueeze(-1).repeat(1, 1, self.k_size) # g = torch.mul(b, mask) # g = g.unsqueeze(-1).repeat(1, 1, 1, self.kernel_num) # [bs, a_n, nei_n, kernel_num] # return self.sigmoid(g) # class AbstractConv(nn.Module): # def __init__(self, kernel_num, k_size): # super(AbstractConv, self).__init__() # self.kernel_num = kernel_num # self.k_size = k_size # # self.leaky_relu = nn.LeakyReLU(inplace=True) # self.relu = nn.ReLU(inplace=True) # self.sigmoid = nn.Sigmoid() # # self.angle_weight = nn.Parameter(torch.FloatTensor(kernel_num, k_size)) # k_size must equal neighbor_num # self.scalar_weight = nn.Parameter(torch.FloatTensor(10, kernel_num)) # self.radius_weight_1 = nn.Parameter(torch.FloatTensor(2, kernel_num)) # self.radius_weight_2 = nn.Parameter(torch.FloatTensor(kernel_num, 1)) # # nn.init.uniform_(self.angle_weight, -1, 1) # nn.init.uniform_(self.scalar_weight, 0, 1) # nn.init.uniform_(self.radius_weight_1, -1, 1) # nn.init.uniform_(self.radius_weight_2, -1, 1) # # def forward(self, pos: "(bs, n, 3)", # node_fea: "(bs, n, c)", # node_mask: "(bs, n)"): # """ # Return: (bs, node_num, kernel_num) # """ # distances, edge_index = self.get_edge(pos) # [bs, n, k_size, 1], [bs, n, k_size] # # theta, mask_final = self.cos_theta(pos, edge_index, node_mask) # [bs, a_n, nei_n, 1] # fea_cat = self.feature_fusion(node_fea, edge_index, node_mask) # [bs, a_n, nei_n, 10] # gate = self.message_gating(edge_fea, node_mask) # [bs, a_n, nei_n] # # fea_struct = torch.matmul(self.angle_weight, theta).squeeze() # [bs, a_n, kernel_num] # # fea_elem = torch.matmul(fea_cat, self.scalar_weight) # [bs, a_n, nei_n, kernel_num] # fea_elem = torch.mul(gate, fea_elem) # [bs, a_n, nei_n, kernel_num] # # fea_elem = torch.sum(fea_elem, dim=2).squeeze() # [bs, a_n, kernel_num] # # interactions = self.leaky_relu(fea_elem + fea_struct) # [bs, a_n, kernel_num] # interact_masked = torch.mul(mask_final, interactions) # return interact_masked # # def get_edge(self, pos: "(bs, n, 3)"): # """Return: (bs, atom_num, neighbor_num) # """ # # device = atoms.device # # tensor.transpose(1, 2), transposes only 1 and 2 dim, =tf.transpose(0, 2, 1) # inner = torch.matmul(pos, pos.transpose(1, 2)) # [bs, n, n] # quadratic = torch.sum(pos ** 2, dim=2) # [bs, n] # # [bs, n, n] + [bs, 1, n] + [bs, n, 1] # distance = inner * (-2) + quadratic.unsqueeze(1) + quadratic.unsqueeze(2) # ngh_distance, ngb_index = torch.topk(distance, k=self.k_size + 1, dim=-1, largest=False) # [bs, c, n, k_size+1] # # distance reference itself is 0 and should be ignore # # [bs, n, k_size+1] to [bs, n, k_size, 1] # return ngh_distance[:, :, 1:].unsqueeze(-1), ngb_index[:, :, 1:] # # def cos_theta(self, pos, edge_index, node_mask: "(bs, n)"): # """ # Embed spatial features # :return [bs, a_n, nei_n, 1] """ # nei_direct_norm = get_neighbor_direct_norm(pos, edge_index) # [bs, n, k_size, 3] # nearest = nei_direct_norm[:, :, 0, :].unsqueeze(2) # [bs, n, 1, 3] # else_neigh = nei_direct_norm[:, :, 1:, :] # [bs, n, k_size-1, 3] # theta = else_neigh @ nearest.transpose(2, 3) # [bs, n, k_size-1, 1] # cos0_theta = F.pad(theta, [0, 0, 1, 0], value=1) # cos(0)=1 # # mask = node_mask.unsqueeze(-1).repeat(1, 1, self.k_size).unsqueeze(-1) # mask_final = node_mask.unsqueeze(-1).repeat(1, 1, self.kernel_num) # return torch.mul(cos0_theta, mask), mask_final # # def feature_fusion(self, fea: "(bs, atom_num, 5)", # index: "(bs, atom_num, neighbor_num)", # atom_max: "(bs, atom_num)"): # """Fuse elements features""" # fea_neigh = indexing_neighbor(fea, index) # [bs, a_n, nei_n, 5] # atom_reps_fea = fea.unsqueeze(2).repeat(1, 1, self.k_size, 1) # [bs, a_n, nei_n, 5] # fea_cat = torch.cat([atom_reps_fea, fea_neigh], dim=-1) # [bs, a_n, nei_n, 10] # # mask = atom_max.unsqueeze(-1).repeat(1, 1, self.k_size).unsqueeze(-1) # return torch.mul(fea_cat, mask) # # def message_gating(self, edge_fea, atom_mask): # """Generate a gate to select elements features based on distance and bond type""" # a = self.relu(torch.matmul(edge_fea, self.radius_weight_1)) # [bs, a_n, nei_n, kernel_num] # # g = torch.max(a, dim=3)[0] # [bs, a_n, nei_n] # b = self.relu(torch.matmul(a, self.radius_weight_2)).squeeze() # [bs, a_n, nei_n] # # mask = atom_mask.unsqueeze(-1).repeat(1, 1, self.k_size) # g = torch.mul(b, mask) # g = g.unsqueeze(-1).repeat(1, 1, 1, self.kernel_num) # [bs, a_n, nei_n, kernel_num] # return self.sigmoid(g) # def test(): # import time # bs = 3 # atom_n = 6400 # dim = 3 # nei_n = 15 # must be double # pos = torch.randn(bs, atom_n, dim) # neighbor_index = get_neighbor_index(pos, nei_n) # # conv_1 = AtomConv(kernel_num=32, k_size=14) # # conv_2 = ConvLayer(in_channel=32, out_channel=64, support_num=3) # # pool = PoolLayer(pooling_rate=4, neighbor_num=4) # # # print("Input size: {}".format(pos.size())) # # print(neighbor_index) # # print(pos) # f1 = conv_1(pos, None, neighbor_index, None) # # print("f1 shape: {}".format(f1.size())) # # # f2 = conv_2(neighbor_index, pos, f1) # # print("f2 shape: {}".format(f2.size())) # # # v_pool, f_pool = pool(pos, f2) # # print("pool atom_n shape: {}, f shape: {}".format(v_pool.size(), f_pool.size())) # # # if __name__ == "__main__": # test() <file_sep>/baseline/proteinGCN.py # encoding: utf-8 """ @file: proteinGCN.py @time: 5/14/21 8:47 PM @desc: Forked from malllabiisc/ProteinGCN, see their research for more details """ from __future__ import print_function, division import os import json import shutil import torch import torch.nn as nn import torch.optim as optim from utils.old_utils import randomSeed class ConvLayer(nn.Module): """ Convolutional operation on graphs """ def __init__(self, h_a, h_b, random_seed=None): """ Initialization Parameters ---------- h_a: int Atom embedding dimension h_b: int Bond embedding dimension random_seed: int Seed to reproduce consistent runs """ randomSeed(random_seed) super(ConvLayer, self).__init__() self.h_a = h_a self.h_b = h_b self.fc_full = nn.Linear(2 * self.h_a + self.h_b, 2 * self.h_a) self.sigmoid = nn.Sigmoid() self.activation_hidden = nn.ReLU() self.bn_hidden = nn.BatchNorm1d(2 * self.h_a) self.bn_output = nn.BatchNorm1d(self.h_a) self.activation_output = nn.ReLU() def forward(self, atom_emb, nbr_emb, nbr_adj_list, atom_mask): """ Forward pass :param atom_emb: [B, n_atom_true, h_a], Atom hidden embeddings before convolution :param nbr_emb: [B, n_atom, n_neighbor=50, 43=40+3], Bond embeddings of each atom's neighbors :param nbr_adj_list: [B, n_atom, n_neighbor=50], Indices of the neighbors of each atom :param atom_mask: [B, n_atom, 1], n_atom_true = n_atom :return out Atom hidden embeddings after convolution """ N, n_neighb = nbr_adj_list.shape[1:] # except batch_size B = atom_emb.shape[0] # atom_emb[1, 22470, 64], [ [[0],[1], ... B], [B, n_atom*n_neighbor] ] # [ index_of_protein, order of atom_emb lay ] # [B, N, n_neighb, self.h_a] atom_nbr_emb = atom_emb[torch.arange(B).unsqueeze(-1), nbr_adj_list.view(B, -1)].view(B, N, n_neighb, self.h_a) atom_nbr_emb *= atom_mask.unsqueeze(-1) # [B, n_atom, 1, h_a] copy to [B, n_atom, n_neighb, h_a] concat [B, N, n_neighb, h_a] # [B, n_atom, n_neighb, h_this_a : h_neighbs : h_edge] total_nbr_emb = torch.cat([atom_emb.unsqueeze(2).expand(B, N, n_neighb, self.h_a), atom_nbr_emb, nbr_emb], dim=-1) total_gated_emb = self.fc_full(total_nbr_emb) # [B, n_atom, n_neighb, 2*h_a] total_gated_emb = self.bn_hidden(total_gated_emb.view(-1, self.h_a * 2)).view(B, N, n_neighb, self.h_a * 2) # [B, n_atom, n_neighb, h_a] nbr_filter, nbr_core = total_gated_emb.chunk(2, dim=3) # divide into 2 block along with dim 3 nbr_filter = self.sigmoid(nbr_filter) # 0-1 nbr_core = self.activation_hidden(nbr_core) # features combine from neighbors to this atom with torch.num() nbr_sumed = torch.sum(nbr_filter * nbr_core, dim=2) # [B, n_atom, h_a] nbr_sumed = self.bn_output(nbr_sumed.view(-1, self.h_a)).view(B, N, self.h_a) out = self.activation_output(atom_emb + nbr_sumed) # [B, n_atom, h_a] return out class ProteinGCN(nn.Module): """ Model to predict properties from protein graph - does all the convolution to get the protein embedding """ def __init__(self, **kwargs): super(ProteinGCN, self).__init__() self.build(**kwargs) self.criterion = nn.MSELoss() self.inputs = None self.targets = None self.outputs = None self.loss = 0 self.accuracy = 0 self.optimizer = None lr = kwargs.get('lr', 0.001) self.optimizer = optim.SGD(self.parameters(), lr, momentum=0.9, weight_decay=0) def build(self, **kwargs): # Get atom embeddings, atom_init_file is the one-hot atom matrix # print('...............', kwargs.get('pkl_dir'), kwargs.get('atom_init')) self.atom_init_file = os.path.join(kwargs.get('atom_init')) with open(self.atom_init_file) as f: loaded_embed = json.load(f) # value: [167,], embed_list: [[167,], ...167] embed_list = [torch.tensor(value, dtype=torch.float32) for value in loaded_embed.values()] self.atom_embeddings = torch.stack(embed_list, dim=0) # [167, 167] self.a_init = self.atom_embeddings.shape[-1] # Dim atom embedding init = 167 self.b_init = kwargs.get('h_b') # Dim bond embedding init assert self.a_init is not None and self.b_init is not None self.h_a = kwargs.get('h_a', 64) # Dim of the hidden atom embedding learnt self.n_conv = kwargs.get('n_conv', 4) # Number of GCN layers self.h_g = kwargs.get('h_g', 32) # Dim of the hidden graph embedding after pooling random_seed = kwargs.get('random_seed', None) # Seed to fix the simulation # The model is defined below randomSeed(random_seed) # num_embeddings*embedding_dim self.embed = nn.Embedding.from_pretrained(self.atom_embeddings, freeze=True) # Load atom embeddings from the one hot atom init self.fc_embedding = nn.Linear(self.a_init, self.h_a) self.convs = nn.ModuleList([ConvLayer(self.h_a, self.b_init, random_seed=random_seed) for _ in range(self.n_conv)]) self.conv_to_fc = nn.Linear(self.h_a, self.h_g) self.conv_to_fc_activation = nn.ReLU() self.fc_out = nn.Linear(self.h_g, 1) self.amino_to_fc = nn.Linear(self.h_a, self.h_g) self.amino_to_fc_activation = nn.ReLU() self.fc_amino_out = nn.Linear(self.h_g, 1) def forward(self, inputs): """ Forward pass Parameters ---------- inputs: List [atom_fea, [B, n_atom] nbr_fea, [B, n_atom, n_neighbor=50, 43=40+3] nbr_fea_idx, [B, n_atom, n_neighbor=50] atom_amino_idx, [B, n_atom] atom_mask] [B, n_atom] Returns ------- out : The prediction for the given batch of protein graphs """ [atom_emb, nbr_emb, nbr_adj_list, atom_amino_idx, atom_mask] = inputs # [B, n_atom] -> [B, n_atom, 167] lookup_tensor = self.embed(atom_emb.type(torch.long)) # [B, n_atom, h_a] atom_emb = self.fc_embedding(lookup_tensor) # [1, 23380, 64] # [B, n_atom, 1] expend a dimension atom_mask = atom_mask.unsqueeze(dim=-1) for idx in range(self.n_conv): # [B, n_atom, h_a] atom_emb *= atom_mask # to correct non-atom values to 0 which added by padding atom_emb = self.convs[idx](atom_emb, nbr_emb, nbr_adj_list, atom_mask) # Update the embedding using the mask, to correct non-atom values to 0 which added by padding atom_emb *= atom_mask # [B, n_aa, h_a] generate reside amino acid level embeddings amino_emb, mask_pooled = self.pooling_amino(atom_emb, atom_amino_idx) # [B, n_aa, h_g] amino_emb = self.amino_to_fc(self.amino_to_fc_activation(amino_emb)) amino_emb = self.amino_to_fc_activation(amino_emb) # generate protein graph level embeddings protein_emb = self.pooling(atom_emb, atom_mask) protein_emb = self.conv_to_fc(self.conv_to_fc_activation(protein_emb)) protein_emb = self.conv_to_fc_activation(protein_emb) out = [self.fc_out(protein_emb), self.fc_amino_out(amino_emb), mask_pooled] return out def pooling(self, atom_emb, atom_mask): """ Pooling the atom features to get protein features :param atom_emb: [B, n_atom, h_a] Atom embeddings after convolution :param atom_mask [B, n_atom, 1] """ summed = torch.sum(atom_emb, dim=1) total = atom_mask.sum(dim=1) pooled = summed / total assert (pooled.shape[0], pooled.shape[1]) == (atom_emb.shape[0], atom_emb.shape[2]) return pooled def pooling_amino(self, atom_emb, atom_amino_idx): """ Pooling the atom features to get residue amino acid features using the atom_amino_idx that contains the mapping :param atom_emb: [B, n_atom, h_a] Atom embeddings after convolution :param atom_amino_idx [B, n_atom] Mapping from the amino idx to atom idx """ atom_amino_idx = atom_amino_idx.view(-1).type(torch.LongTensor) # [B*n_atom] atom_emb = atom_emb.view(-1, self.h_a) # [B*n_atom, h_a] max_idx = torch.max(atom_amino_idx) # largest number of this batch min_idx = torch.min(atom_amino_idx) # always 0 in each batch ? # [max_idx + 1, 1] all 1 mask_pooled = atom_amino_idx.new_full(size=(max_idx + 1, 1), fill_value=1, dtype=torch.bool) # torch>1.2 mask_pooled[:min_idx] = 0 # pooled = torch.scatter_add(atom_emb.t(), atom_amino_idx).t() # pooled = torch.scatter_add(input=atom_emb.t(), dim=0, index=atom_amino_idx, src=) return pooled, mask_pooled def save(self, state, is_best, savepath, filename='checkpoint.pth.tar'): """Save model checkpoints""" torch.save(state, savepath + filename) if is_best: shutil.copyfile(savepath + filename, savepath + 'model_best.pth.tar') @staticmethod def mask_remove(out): """Internal function to remove masking after generating residue amino acid level embeddings""" out[1] = torch.masked_select(out[1].squeeze(), out[2].squeeze()).unsqueeze(1) return out def fit(self, outputs, targets, protein_ids, pred=False): """Train the model one step for given inputs""" self.targets = targets self.outputs = outputs assert self.outputs[1].shape == self.targets[1].unsqueeze(1).shape # Calculate MSE loss predicted_targets_global = self.outputs[0] predicted_targets_local = self.outputs[1] predicted_targets = torch.cat([predicted_targets_global, predicted_targets_local]) original_targets = torch.cat([self.targets[0], self.targets[1].unsqueeze(1)]) self.loss = self.criterion(predicted_targets, original_targets) if not pred: self.optimizer.zero_grad() self.loss.backward() self.optimizer.step() # Calculate MAE error self.accuracy = [] self.accuracy.extend([torch.mean(torch.abs(self.outputs[0] - self.targets[0]))]) self.accuracy.extend([torch.mean(torch.abs(self.outputs[1] - self.targets[1]))]) <file_sep>/data_engineer/protein_parser.py # encoding: utf-8 """ @author: <NAME> @contact: <EMAIL> @file: protein_parser.py @time: 5/13/21 5:15 PM @desc: """ import numpy as np from collections import defaultdict as ddict from data_engineer.elem_periodic_map import atoms_periodic_dic, heavy_atom_idx_dic from arguments import build_parser parser = build_parser() args = parser.parse_args() max_neighbors = args.max_neighbors def create_sorted_graph(contacts, bonds, max_neighbors): """ generate the k nearest neighbors for each atom based on distance. :param contacts : list, [[index1, index2, distance, x1, y1, z1, x2, y2, z2], ...] :param bonds : list :param max_neighbors : int Limit for the maximum neighbors to be set for each atom. :param atom_fea: """ bond_true = 1 # is chemical bonds bond_false = 0 # non-chemical bonds neighbor_map = ddict(list) # type list pos_map = {} # type = [('index2', int), ('distance', float), ('bool_bond', int)] for contact in contacts: # atom 3D: x y z pos_map[contact[0]] = [contact[3], contact[4], contact[5]] pos_map[contact[1]] = [contact[6], contact[7], contact[8]] if ([contact[0], contact[1]] or [contact[1], contact[0]]) in bonds: # have bonds with this neighbor # index2, distance, bond_bool neighbor_map[contact[0]].append([contact[1], contact[2], bond_true]) # index1, distance, bond_bool neighbor_map[contact[1]].append([contact[0], contact[2], bond_true]) else: neighbor_map[contact[0]].append([contact[1], contact[2], bond_false]) neighbor_map[contact[1]].append([contact[0], contact[2], bond_false]) edge_idx = [] edge_attr = [] pos = [] # normalize length of neighbors and align with atom for i in range(len(pos_map)): position = pos_map.get(i) neighbors = neighbor_map.get(i) if len(neighbors) < max_neighbors: # true_nbrs = np.sort(np.array(v, dtype=type), order='distance', kind='mergesort').tolist()[0:len(v)] neighbors.sort(key=lambda e: e[1]) neighbors.extend([[0, 0, 0] for _ in range(max_neighbors - len(neighbors))]) else: # neighbor_map[k] = np.sort(np.array(v, dtype=type), order='distance', kind='mergesort').tolist()[ # 0:max_neighbors] neighbors.sort(key=lambda e: e[1]) neighbors = neighbors[0:max_neighbors] pos.append(position) edge_idx.append(np.array(neighbors)[:, 0].tolist()) edge_attr.append(np.array(neighbors)[:, 1:].tolist()) return pos, edge_idx, edge_attr def create_graph(contacts, bonds): bond_true = 1 # is chemical bonds bond_false = 0 # non-chemical bonds edge_idx = [] edge_attr = [] atom_3d = {} for contact in contacts: atom_3d[contact[0]] = [contact[3], contact[4], contact[5]] atom_3d[contact[1]] = [contact[6], contact[7], contact[8]] edge_idx.append([contact[0], contact[1]]) if ([contact[0], contact[1]] or [contact[1], contact[0]]) in bonds: edge_attr.append([contact[2], bond_true]) else: edge_attr.append([contact[2], bond_false]) return edge_idx, edge_attr, list(atom_3d) def build_protein_graph(atoms, bonds, contacts, PyG_format): atom_fea = [] for atom in atoms: type_ = atom.split('_')[1][0] periodic = atoms_periodic_dic[type_] idx = heavy_atom_idx_dic[atom] atom_fea.append(np.concatenate([[idx], periodic], axis=0)) if PyG_format: edge_idx, edge_attr, pos = create_graph(contacts, bonds) else: pos, edge_idx, edge_attr = create_sorted_graph(contacts, bonds, max_neighbors) # [a_n, 3], [a_n, 5], [a_n, nei_n], [a_n, nei_n, 2] return pos, atom_fea, edge_idx, edge_attr <file_sep>/network/pooling.py # encoding: utf-8 """ @author: <NAME> @contact: <EMAIL> @file: pooling.py @time: 6/10/21 4:37 PM @desc: 用于在从 atoms 抽象到 residues,二级结构的时候使用 """ import torch import torch.nn as nn class MoleculePooling(nn.Module): def __init__(self, kernel_size: int = 4, stride: int = 4): super(MoleculePooling, self).__init__() self.kernel_size = kernel_size self.stride = stride self.pool_op = nn.MaxPool1d(kernel_size=self.kernel_size, stride=self.stride, padding=0, return_indices=True) def forward(self, pos: "(bs, n, 3)", node_fea: "(bs, channel, n, dim)", res_idx: "(bs, n)", node_mask: "(bs, n)"): """ Return: vertices_pool: (bs, pool_atom_num, 3), feature_map_pool: (bs, pool_atom_num, channel_num) """ channel_num = node_fea.size()[1] # TODO: deal with dim in pooling or in convolution p_fea_T, index = self.pool_op(node_fea.squeeze()) # [bs, c, n_pooled, 1], [bs, c, n_pooled] p_fea_T = p_fea_T.unsqueeze(-1) """ torch.gather(input, dim, index, out=None) → Tensor Gathers values along an axis specified by dim. For a 3-D tensor the output is specified by: out[i][j][k] = input[index[i][j][k]] [j][k] # dim=0 out[i][j][k] = input[i] [index[i][j][k]] [k] # dim=1 out[i][j][k] = input[i][j] [index[i][j][k]] # dim=2 Parameters: input (Tensor) – The source tensor dim (int) – The axis along which to index index (LongTensor) – The indices of elements to gather out (Tensor, optional) – Destination tensor Example: >>> t = torch.Tensor([[1,2],[3,4]]) >>> torch.gather(t, 1, torch.LongTensor([[0,0],[1,0]])) 1 1 4 3 [torch.FloatTensor of size 2x2] """ pos_rep_T = pos.unsqueeze(1).repeat(1, channel_num, 1, 1) # [bs, c, n, 3] p_pos_T = torch.gather(pos_rep_T, dim=2, index=index.unsqueeze(-1).repeat(1, 1, 1, 3)) # [bs, c, n, 3] # center_pos_T = torch.sum(p_pos_T, dim=1) / self.kernel_size # [bs, n, 3] ridx_rep_T = res_idx.unsqueeze(1).repeat(1, channel_num, 1) # [bs, c, n] p_ridx_T = torch.gather(ridx_rep_T, dim=2, index=index) main_ridx_T = torch.div(torch.sum(p_ridx_T, dim=1), channel_num) main_ridx_T.ceil_() # mask_rep_T = node_mask.unsqueeze(2).repeat(1, 1, channel_num).transpose(1, 2) # [bs, c, n] # p_mask_T = torch.gather(mask_rep_T, dim=2, index=index) # It's impossible to select a 0 elements in MaxPooling op p_mask = self.pool_op(node_mask.unsqueeze(1))[0].squeeze() # [bs, n] return p_pos_T, p_fea_T, main_ridx_T, p_mask # class AtomPooling(nn.Module): # def __init__(self, kernel_size: int = 4, stride: int = 4): # super(AtomPooling, self).__init__() # self.kernel_size = kernel_size # self.stride = stride # self.pool_op = nn.MaxPool1d(kernel_size=self.kernel_size, stride=self.stride, padding=0, return_indices=True) # # def forward(self, # pos: "(bs, n, 3)", # node_fea: "(bs, n, channel)", # res_idx: "(bs, n)", # node_mask: "(bs, n)"): # """ # Return: # vertices_pool: (bs, pool_atom_num, 3), # feature_map_pool: (bs, pool_atom_num, channel_num) # """ # channel_num = node_fea.size()[2] # fea_T = node_fea.transpose(1, 2) # [bs, c, a_n] # p_fea_T, index = self.pool_op(fea_T) # [bs, c, a_n_pooled], [bs, c, a_n_pooled] # """ # torch.gather(input, dim, index, out=None) → Tensor # # Gathers values along an axis specified by dim. # For a 3-D tensor the output is specified by: # out[i][j][k] = input[index[i][j][k]] [j][k] # dim=0 # out[i][j][k] = input[i] [index[i][j][k]] [k] # dim=1 # out[i][j][k] = input[i][j] [index[i][j][k]] # dim=2 # # Parameters: # input (Tensor) – The source tensor # dim (int) – The axis along which to index # index (LongTensor) – The indices of elements to gather # out (Tensor, optional) – Destination tensor # # Example: # >>> t = torch.Tensor([[1,2],[3,4]]) # >>> torch.gather(t, 1, torch.LongTensor([[0,0],[1,0]])) # 1 1 # 4 3 # [torch.FloatTensor of size 2x2] # """ # pos_rep_T = pos.unsqueeze(2).repeat(1, 1, channel_num, 1).transpose(1, 2) # [bs, c, n, 3] # p_pos_T = torch.gather(pos_rep_T, dim=2, index=index.unsqueeze(-1).repeat(1, 1, 1, 3)) # [bs, c, n, 3] # # center_pos_T = torch.sum(p_pos_T, dim=1) / channel_num # [bs, n, 3] # # ridx_rep_T = res_idx.unsqueeze(2).repeat(1, 1, channel_num).transpose(1, 2) # [bs, c, n] # p_ridx_T = torch.gather(ridx_rep_T, dim=2, index=index) # round_ridx_T = torch.div(torch.sum(p_ridx_T, dim=1), channel_num) # [bs, n] # round_ridx_T = round_ridx_T.round() # # # mask_rep_T = node_mask.unsqueeze(2).repeat(1, 1, channel_num).transpose(1, 2) # [bs, c, n] # # p_mask_T = torch.gather(mask_rep_T, dim=2, index=index) # # It's impossible to select a 0 elements in MaxPooling op # p_mask = self.pool_op(node_mask.unsqueeze(1))[0].squeeze() # [bs, n] # # # if self.channel_first: # # return center_pos_T, p_fea_T, round_ridx_T, p_mask # # else: # # return center_pos_T, p_fea_T.transpose(1, 2), round_ridx_T, p_mask # # return p_pos_T, p_fea_T, round_ridx_T, p_mask <file_sep>/baseline/ldk/gcn3d_lkd.py """ @Author: <NAME> @Contact: <EMAIL> @Time: 2020/03/06 @Document: Basic operation/blocks of 3D-GCN """ import math import torch import torch.nn as nn import torch.nn.functional as F def get_neighbor_index(atoms: "(bs, atom_num, 3)", neighbor_num: int): """ Return: (bs, atom_num, neighbor_num) """ bs, a_n, _ = atoms.size() # device = atoms.device # tensor.transpose(1, 2), transposes only 1 and 2 dim, =tf.transpose(0, 2, 1) inner = torch.bmm(atoms, atoms.transpose(1, 2)) # [bs, a_n, a_n] quadratic = torch.sum(atoms ** 2, dim=2) # [bs, a_n] # [bs, a_n, a_n] + [bs, 1, a_n] + [bs, a_n, 1] distance = inner * (-2) + quadratic.unsqueeze(1) + quadratic.unsqueeze(2) neighbor_index = torch.topk(distance, k=neighbor_num + 1, dim=-1, largest=False)[1] neighbor_index = neighbor_index[:, :, 1:] return neighbor_index def get_nearest_index(target: "(bs, v1, 3)", source: "(bs, v2, 3)"): """ Return: (bs, v1, 1) """ inner = torch.bmm(target, source.transpose(1, 2)) # (bs, v1, v2) s_norm_2 = torch.sum(source ** 2, dim=2) # (bs, v2) t_norm_2 = torch.sum(target ** 2, dim=2) # (bs, v1) d_norm_2 = s_norm_2.unsqueeze(1) + t_norm_2.unsqueeze(2) - 2 * inner nearest_index = torch.topk(d_norm_2, k=1, dim=-1, largest=False)[1] return nearest_index def indexing_neighbor(tensor: "(bs, atom_num, dim)", index: "(bs, atom_num, neighbor_num)"): """ Return: (bs, atom_num, neighbor_num, dim) """ bs, _, _ = index.size() id_0 = torch.arange(bs).view(-1, 1, 1) tensor_indexed = tensor[id_0, index] return tensor_indexed def get_neighbor_direct_norm(atoms: "(bs, atom_num, 3)", neighbor_index: "(bs, atom_num, neighbor_num)"): """ Return: (bs, atom_num, atom_num, 3) """ pos_neighbors = indexing_neighbor(atoms, neighbor_index) # [bs, a_n, nei_n, 3] neighbor_direction = pos_neighbors - atoms.unsqueeze(2) # [bs, a_n, nei_n, 3] - [bs, a_n, 1, 3] neighbor_direction_norm = F.normalize(neighbor_direction, dim=-1) # unit vector of distance return neighbor_direction_norm class ConvSurface(nn.Module): """Extract structure features from surface, independent from atom coordinates""" def __init__(self, kernel_num, k_size): super(ConvSurface, self).__init__() self.kernel_num = kernel_num self.k_size = k_size self.relu = nn.ReLU(inplace=True) self.directions = nn.Parameter(torch.FloatTensor(3, k_size * 1)) # linear weight self.initialize() def initialize(self): stdv = 1. / math.sqrt(self.k_size * self.kernel_num) self.directions.data.uniform_(-stdv, stdv) def forward(self, neighbor_index: "(bs, atom_num, neighbor_num)", atoms: "(bs, atom_num, 3)"): """ Return vertices with local feature: (bs, atom_num, kernel_num) """ bs, atom_num, neighbor_num = neighbor_index.size() nei_direct_norm = get_neighbor_direct_norm(atoms, neighbor_index) # [bs, a_n, nei_n, 3] support_direct_norm = F.normalize(self.directions, dim=0) # (3, s * k) theta = nei_direct_norm @ support_direct_norm # theta = torch.bmm(nei_direct_norm, support_direct_norm) # [bs, atom_num, neighbor_num, s*k] theta = self.relu(theta) theta = theta.contiguous().view(bs, atom_num, neighbor_num, self.k_size, self.kernel_num) # to get the biggest [k_size, kernel_num] in neighbor_num neighbors of each atom theta = torch.max(theta, dim=2)[0] # [bs, atom_num, k_size, kernel_num] feature = torch.sum(theta, dim=2) # [bs, atom_num, kernel_num] return feature class ConvLayer(nn.Module): def __init__(self, in_channel, out_channel, support_num): super().__init__() # arguments: self.in_channel = in_channel self.out_channel = out_channel self.support_num = support_num # parameters: self.relu = nn.ReLU(inplace=True) self.weights = nn.Parameter(torch.FloatTensor(in_channel, (support_num + 1) * out_channel)) self.bias = nn.Parameter(torch.FloatTensor((support_num + 1) * out_channel)) self.directions = nn.Parameter(torch.FloatTensor(3, support_num * out_channel)) self.initialize() def initialize(self): stdv = 1. / math.sqrt(self.out_channel * (self.support_num + 1)) self.weights.data.uniform_(-stdv, stdv) self.bias.data.uniform_(-stdv, stdv) self.directions.data.uniform_(-stdv, stdv) def forward(self, neighbor_index: "(bs, vertice_num, neighbor_index)", vertices: "(bs, vertice_num, 3)", feature_map: "(bs, vertice_num, in_channel)"): """ Return: output feature map: (bs, vertice_num, out_channel) """ bs, vertice_num, neighbor_num = neighbor_index.size() neighbor_direction_norm = get_neighbor_direct_norm(vertices, neighbor_index) support_direction_norm = F.normalize(self.directions, dim=0) theta = neighbor_direction_norm @ support_direction_norm # (bs, vertice_num, neighbor_num, support_num * out_channel) theta = self.relu(theta) theta = theta.contiguous().view(bs, vertice_num, neighbor_num, -1) # (bs, vertice_num, neighbor_num, support_num * out_channel) feature_out = feature_map @ self.weights + self.bias # (bs, vertice_num, (support_num + 1) * out_channel) feature_center = feature_out[:, :, :self.out_channel] # (bs, vertice_num, out_channel) feature_support = feature_out[:, :, self.out_channel:] # (bs, vertice_num, support_num * out_channel) # Fuse together - max among product feature_support = indexing_neighbor(feature_support, neighbor_index) # (bs, vertice_num, neighbor_num, support_num * out_channel) activation_support = theta * feature_support # (bs, vertice_num, neighbor_num, support_num * out_channel) activation_support = activation_support.view(bs, vertice_num, neighbor_num, self.support_num, self.out_channel) activation_support = torch.max(activation_support, dim=2)[0] # (bs, vertice_num, support_num, out_channel) activation_support = torch.sum(activation_support, dim=2) # (bs, vertice_num, out_channel) feature_fuse = feature_center + activation_support # (bs, vertice_num, out_channel) return feature_fuse class PoolLayer(nn.Module): def __init__(self, pooling_rate: int = 4, neighbor_num: int = 4): super().__init__() self.pooling_rate = pooling_rate self.neighbor_num = neighbor_num def forward(self, vertices: "(bs, vertice_num, 3)", feature_map: "(bs, vertice_num, channel_num)"): """ Return: vertices_pool: (bs, pool_vertice_num, 3), feature_map_pool: (bs, pool_vertice_num, channel_num) """ bs, vertice_num, _ = vertices.size() neighbor_index = get_neighbor_index(vertices, self.neighbor_num) neighbor_feature = indexing_neighbor(feature_map, neighbor_index) # (bs, vertice_num, neighbor_num, channel_num) pooled_feature = torch.max(neighbor_feature, dim=2)[0] # (bs, vertice_num, channel_num) pool_num = int(vertice_num / self.pooling_rate) sample_idx = torch.randperm(vertice_num)[:pool_num] vertices_pool = vertices[:, sample_idx, :] # (bs, pool_num, 3) feature_map_pool = pooled_feature[:, sample_idx, :] # (bs, pool_num, channel_num) return vertices_pool, feature_map_pool def test(): import time bs = 2 atom_n = 5 dim = 3 nei_n = 3 pos = torch.randn(bs, atom_n, dim) neighbor_index = get_neighbor_index(pos, nei_n) s = 3 conv_1 = ConvSurface(kernel_num=32, k_size=s) conv_2 = ConvLayer(in_channel=32, out_channel=64, support_num=s) pool = PoolLayer(pooling_rate=4, neighbor_num=4) # print("Input size: {}".format(pos.size())) # print(neighbor_index) # print(pos) f1 = conv_1(neighbor_index, pos) # print("f1 shape: {}".format(f1.size())) f2 = conv_2(neighbor_index, pos, f1) # print("f2 shape: {}".format(f2.size())) v_pool, f_pool = pool(pos, f2) # print("pool atom_n shape: {}, f shape: {}".format(v_pool.size(), f_pool.size())) if __name__ == "__main__": test() <file_sep>/data_engineer/install_preprocess.sh git clone https://github.com/gjoni/mylddt mv mylddt ./data/preprocess # shellcheck disable=SC2164 cd data/preprocess/src/ g++ -Wall -Wno-unused-result -pedantic -O3 -mtune=native -std=c++11 *.cpp -o get_features mv get_features ../ <file_sep>/baseline/ldk/model.py # encoding: utf-8 """ @author: <NAME> @contact: <EMAIL> @file: model.py @time: 6/13/21 1:08 PM @desc: """ import torch import torch.nn as nn import torch.nn.functional as F import sys sys.path.append("../../network/") import gcn3d class GCN3D(nn.Module): def __init__(self, support_num: int, neighbor_num: int): super().__init__() self.neighbor_num = neighbor_num self.conv_0 = gcn3d.MoleculeConv(kernel_num=32, k_size=support_num) self.conv_1 = gcn3d.MoleculeConv(32, 64, support_num=support_num) self.pool_1 = gcn3d.PoolLayer(pooling_rate=4, neighbor_num=4) self.conv_2 = gcn3d.MoleculeConv(64, 128, support_num=support_num) self.conv_3 = gcn3d.MoleculeConv(128, 256, support_num=support_num) self.pool_2 = gcn3d.PoolLayer(pooling_rate=4, neighbor_num=4) self.conv_4 = gcn3d.MoleculeConv(256, 1024, support_num=support_num) self.classifier = nn.Sequential( nn.Linear(1024, 256), nn.Dropout(0.3), nn.BatchNorm1d(256), nn.ReLU(inplace=True), nn.Linear(256, 40) ) def forward(self, vertices: "(bs, vertice_num, 3)"): bs, vertice_num, _ = vertices.size() neighbor_index = gcn3d.get_edge(vertices, self.neighbor_num) fm_0 = self.conv_0(neighbor_index, vertices) fm_0 = F.relu(fm_0, inplace=True) fm_1 = self.conv_1(neighbor_index, vertices, fm_0) fm_1 = F.relu(fm_1, inplace=True) vertices, fm_1 = self.pool_1(vertices, fm_1) neighbor_index = gcn3d.get_edge(vertices, self.neighbor_num) fm_2 = self.conv_2(neighbor_index, vertices, fm_1) fm_2 = F.relu(fm_2, inplace=True) fm_3 = self.conv_3(neighbor_index, vertices, fm_2) fm_3 = F.relu(fm_3, inplace=True) vertices, fm_3 = self.pool_2(vertices, fm_3) neighbor_index = gcn3d.get_edge(vertices, self.neighbor_num) fm_4 = self.conv_4(neighbor_index, vertices, fm_3) feature_global = fm_4.max(1)[0] pred = self.classifier(feature_global) return pred def test(): import time sys.path.append("../../network") from util import parameter_number device = torch.device('cuda:0') points = torch.zeros(8, 1024, 3).to(device) model = GCN3D(support_num=1, neighbor_num=20).to(device) start = time.time() output = model(points) print("Inference time: {}".format(time.time() - start)) print("Parameter #: {}".format(parameter_number(model))) print("Inputs size: {}".format(points.size())) print("Output size: {}".format(output.size())) if __name__ == '__main__': test()
ff4d8393fa0dcd77ad24c0cb81257948ae7aa724
[ "Markdown", "Python", "Shell" ]
26
Python
MeetDevin/AminoAcidNet
9af9ab5d56bd57ee2d743f677216e7ce03b83248
1d56f58bbc0b2a4a419cde38179320c2d2eb17f8
refs/heads/main
<repo_name>TomashinOpenSource/FireSafetySimulator<file_sep>/Assets/FireSafety/Scripts/Extinguisher.cs using System.Collections; using System.Collections.Generic; using UnityEngine; using HTC.UnityPlugin.Vive; public class Extinguisher : MonoBehaviour { [Header("Система частиц пены")] public ParticleSystem foamParticle; [Header("Чека")] public Transform seal; private Vector3 startSealPos; [Header("Раструб")] public Transform spray; private Vector3 startSprayPos; private Quaternion startSprayRot; [Header("Джойстики для дочерности")] public Transform[] grabbers; private int lastHand = -1; private void Start() { foamParticle.Stop(); } public void OnGrabbed(BasicGrabbable grabbedObj) { ViveColliderButtonEventData viveEventData; if (!grabbedObj.grabbedEvent.TryGetViveButtonEventData(out viveEventData)) { return; } int currentHand = viveEventData.viveRole.ToRole<HandRole>() == HandRole.RightHand ? 0 : 1; if (!GameManager.IsExtinguisherInHand) { grabbedObj.transform.SetParent(grabbers[currentHand]); GameManager.IsExtinguisherInHand = true; lastHand = currentHand; } else { GameManager.IsExtinguisherInHand = false; if (lastHand == currentHand) { transform.parent = null; } else { OnGrabbed(grabbedObj); } } } public void OnDrop() { if (GameManager.IsExtinguisherInHand) { transform.GetComponent<Rigidbody>().isKinematic = true; transform.localPosition = new Vector3(0, 0, 0); transform.localRotation = new Quaternion(0, 0, 0, 0); } else { transform.GetComponent<Rigidbody>().isKinematic = false; } } public void OnPress() { if (GameManager.IsSealRemoved) { if (foamParticle.isPlaying) { foamParticle.Stop(); foamParticle.transform.GetComponent<CapsuleCollider>().isTrigger = false; foreach (var item in FindObjectsOfType<Fire>()) { item.StopAllCoroutines(); Debug.Log("Stop Extingiush Global"); } } else { foamParticle.Play(); foamParticle.transform.GetComponent<CapsuleCollider>().isTrigger = true; } } } public void OnTakeSeal() { startSealPos = seal.position; } public void OnRemoveSeal() { if (!GameManager.IsSealRemoved && Vector3.Distance(startSealPos, seal.position) > GameManager.DistanseForSeal) { GameManager.IsSealRemoved = true; seal.gameObject.AddComponent<Rigidbody>(); seal.parent = null; } else { seal.position = startSealPos; } } public void OnTakeSpray() { startSprayPos = spray.position; startSprayRot = spray.localRotation; } public void OnDropSpray() { spray.position = startSprayPos; spray.localRotation = startSprayRot; } } <file_sep>/Assets/FireSafety/Scripts/GameManager.cs using System.Collections; using System.Collections.Generic; using UnityEngine; public class GameManager : MonoBehaviour { public static bool IsExtinguisherInHand = false; public static bool IsSealRemoved = false; public static float DistanseForSeal = 0.5f; public const int ExtinguishingTime = 5; } <file_sep>/Assets/FireSafety/Scripts/Fire.cs using System.Collections; using System.Collections.Generic; using UnityEngine; public class Fire : MonoBehaviour { private void OnTriggerEnter(Collider other) { if (other.transform.GetComponent<Foam>()) { Debug.Log("Start Extingiush"); StartCoroutine(Extingiush()); } } private void OnTriggerExit(Collider other) { if (other.transform.GetComponent<Foam>()) { Debug.Log("Stop Extingiush"); StopAllCoroutines(); } } private IEnumerator Extingiush() { Debug.Log("Extingiush"); int time = GameManager.ExtinguishingTime; while (time > 0) { time--; yield return new WaitForSeconds(1f); } Destroy(gameObject); } }
75081525b79caa7736046729aa4020d577b08e68
[ "C#" ]
3
C#
TomashinOpenSource/FireSafetySimulator
46caa80fbb11dd141c3b519e8e0959cdae781e7f
69594e22b7c098062204c16c47a524d9c76910d3
refs/heads/master
<file_sep><?php class FriendsController extends AppController { var $name = 'Friends'; var $uses = array('User', 'Friend', 'Feed', 'Like', 'Jobkind', 'Job', 'Level'); var $components = array('Auth', 'WebApi', 'Timeline'); var $helpers = array('Javascript'); function beforeFilter(){ $this->Auth->userModel = 'User'; $this->Auth->fields = array('username' => 'email', 'password' => '<PASSWORD>'); $this->Auth->loginAction = array('action' => 'login'); $this->Auth->loginRedirect = array('action' => 'index'); $this->Auth->logoutRedirect = array('action' => 'login'); $this->Auth->allow('login', 'logout', 'join'); $this->Auth->loginError = 'email or password is invalid.'; //$this->Auth->authError = 'Please try logon as admin.'; } function index() { $this->Friend->recursive = 0; $this->set('friends', $this->paginate()); } function view($id = null) { $this->Friend->recursive = -1; $this->User->recursive = -1; $this->Jobkind->recursive = -1; $this->Like->recursive = -1; $this->Job->recursive = -1; $this->Level->recursive = -1; $this->Feed->recursive = 0; if (!$id) { $this->Session->setFlash(__('Invalid friend', true)); $this->redirect(array('action' => 'index')); } if (!empty($this->data)) { $this->data['Friend']['user_id'] = $this->Auth->user('id'); if($this->data['Friend']['action'] == 'follow') { $this->Friend->create(); $this->Friend->save($this->data); } elseif ($this->data['Friend']['action'] == 'unfollow') { $unfollows = $this->Friend->find('all', array('conditions'=>array('Friend.user_id'=>$this->Auth->user('id'), 'Friend.friend_id'=>$this->data['Friend']['friend_id']))); foreach($unfollows as $unfollow) { $this->Friend->delete($unfollow['Friend']['id']); } } } $follow = $this->Friend->find('count', array('conditions'=>array('Friend.user_id'=>$this->Auth->user('id'), 'Friend.friend_id'=>$id))); $followed = false; if($follow > 0) $followed = true; $friend = $this->User->read(null, $id); $jobkind = $this->Jobkind->read(null, $friend['User']['current_jobkind_id']); $likecnt = $this->Like->find('count', array('conditions'=>array('Like.user_id'=>$friend['User']['id']))); $checkoutcnt = $this->Job->find('count', array('conditions'=>array('Job.user_id'=>$friend['User']['id'], 'Job.checkout IS NOT NULL'))); $level = $this->Level->find('first', array('conditions'=>array('Level.level'=>$friend['User']['current_level'], 'Level.jobkind_id'=>$friend['User']['current_jobkind_id']))); $feeds = $this->Feed->find('all', array('conditions'=>array('Feed.user_id'=>$friend['User']['id']), 'order'=>'Feed.id DESC', 'limit'=>5)); $timelines = array(); foreach($feeds as $feed) { $feed['Like']['likes'] = $this->Like->find('count', array('conditions'=>array('Like.feed_id'=>$feed['Feed']['id'], 'Like.user_id'=>$feed['Feed']['user_id']))); $feed['Like']['comments'] = $this->Like->find('count', array('conditions'=>array('Like.feed_id'=>$feed['Feed']['id'], 'Like.message IS NOT NULL', 'Like.user_id'=>$feed['Feed']['user_id']))); $feed['Feed']['created'] = $this->Timeline->getActionTime($feed['Feed']['created']); array_push($timelines, $feed); } $this->set('friend', $friend); $this->set('jobkind', $jobkind); $this->set('likecnt', $likecnt); $this->set('checkoutcnt', $checkoutcnt); $this->set('level', $level); $this->set('feeds', $timelines); $this->set('followed', $followed); $this->set('webroot', $this->webroot); } // search friend function search() { $this->User->recursive = 0; $this->Jobkind->recursive = -1; $this->Level->recursive = -1; if(!empty($this->data['Friend']['username'])) { $this->paginate = array( 'model' => 'User', 'conditions' => array('User.username like' => $this->data['Friend']['username'].'%') ); $friends = array(); $lists = $this->paginate(); foreach($lists as $l) { $jobkind = $this->Jobkind->read('name', $l['User']['current_jobkind_id']); $level = $this->Level->find('first', array('conditions'=>array('Level.level'=>$l['User']['current_level'], 'Level.jobkind_id'=>$l['User']['current_jobkind_id']), 'fields'=>array('Level.name'))); $l['User']['jobkind'] = $jobkind['Jobkind']['name']; $l['User']['status'] = $level['Level']['name']; array_push($friends, $l); } $this->set('friends', $friends); } $this->set('title_for_action', 'サポーター検索'); } /* function add() { if (!empty($this->data)) { $this->Friend->create(); if ($this->Friend->save($this->data)) { $this->Session->setFlash(__('The friend has been saved', true)); $this->redirect(array('action' => 'index')); } else { $this->Session->setFlash(__('The friend could not be saved. Please, try again.', true)); } } $users = $this->Friend->User->find('list'); $this->set(compact('users')); } function edit($id = null) { if (!$id && empty($this->data)) { $this->Session->setFlash(__('Invalid friend', true)); $this->redirect(array('action' => 'index')); } if (!empty($this->data)) { if ($this->Friend->save($this->data)) { $this->Session->setFlash(__('The friend has been saved', true)); $this->redirect(array('action' => 'index')); } else { $this->Session->setFlash(__('The friend could not be saved. Please, try again.', true)); } } if (empty($this->data)) { $this->data = $this->Friend->read(null, $id); } $users = $this->Friend->User->find('list'); $this->set(compact('users')); } function delete($id = null) { if (!$id) { $this->Session->setFlash(__('Invalid id for friend', true)); $this->redirect(array('action'=>'index')); } if ($this->Friend->delete($id)) { $this->Session->setFlash(__('Friend deleted', true)); $this->redirect(array('action'=>'index')); } $this->Session->setFlash(__('Friend was not deleted', true)); $this->redirect(array('action' => 'index')); } */ function admin_index() { $this->Friend->recursive = 1; $this->set('friends', $this->paginate()); } function admin_view($id = null) { if (!$id) { $this->Session->setFlash(__('Invalid friend', true)); $this->redirect(array('action' => 'index')); } $this->set('friend', $this->Friend->read(null, $id)); } function admin_add() { if (!empty($this->data)) { $this->Friend->create(); if ($this->Friend->save($this->data)) { $this->Session->setFlash(__('The friend has been saved', true)); $this->redirect(array('action' => 'index')); } else { $this->Session->setFlash(__('The friend could not be saved. Please, try again.', true)); } } $users = $this->Friend->User->find('list'); $this->set(compact('users')); } function admin_edit($id = null) { if (!$id && empty($this->data)) { $this->Session->setFlash(__('Invalid friend', true)); $this->redirect(array('action' => 'index')); } if (!empty($this->data)) { if ($this->Friend->save($this->data)) { $this->Session->setFlash(__('The friend has been saved', true)); $this->redirect(array('action' => 'index')); } else { $this->Session->setFlash(__('The friend could not be saved. Please, try again.', true)); } } if (empty($this->data)) { $this->data = $this->Friend->read(null, $id); } $users = $this->Friend->User->find('list'); $this->set(compact('users')); } function admin_delete($id = null) { if (!$id) { $this->Session->setFlash(__('Invalid id for friend', true)); $this->redirect(array('action'=>'index')); } if ($this->Friend->delete($id)) { $this->Session->setFlash(__('Friend deleted', true)); $this->redirect(array('action'=>'index')); } $this->Session->setFlash(__('Friend was not deleted', true)); $this->redirect(array('action' => 'index')); } } <file_sep><?php $comment_cnt = 0; foreach ($likes as $like) { if ($like['Like']['message']!='') $comment_cnt++; } ?> <?php echo $this->Javascript->link('global', false);?> <?php echo $this->Javascript->link('sync', false);?> <?php echo $this->Javascript->link('charactor', false);?> <?php echo $this->Html->css('tmp', 'stylesheet', array('inline'=>false)); ?> <div class="woodFrame friendTimelineDetail"> <div class="woodWrapper"> <ul> <li data-friend-jobkind="<?php echo $detail['User']['current_jobkind_id']; ?>" data-friend-level="<?php echo $detail['User']['current_level']; ?>" data-feed-id="<?php echo $detail['User']['id']; ?>"> <canvas width="80" height="80" class="avatarIcon"></canvas> <div class="activity"> <p class="comment"> <span><?php echo $detail['User']['username'] ?>さん</span><?php echo $detail['Feed']['message']; ?> </p> <div class="footer"> <p class="icon"><span class="comment"><?php echo $comment_cnt; ?></span><span class="otsu"><?php echo count($likes) ?></span></p> <p class="times"><?php echo $detail['Feed']['action_time'] ?></p> </div> </div> <?php if($like_flg) : ?> <div class="commentForm"> <?php echo $this->Form->create('Feed',array('controller' => 'feed', 'action' => 'detail','url'=>array($detail['Feed']['id']))); ?> <?php echo $this->Form->input('Feed.job_id', array('type'=>'hidden', array('value'=>$detail['Feed']['job_id']))); ?> <p><?php echo $this->Form->input('message', array('type' => 'text', 'class' => 'newRegist', 'placeholder' => 'コメントをいれてあげるぽよ', 'label' => false, 'div' => false)); ?></p> <p class="otsukareBtn"><?php echo $form->submit('comment_btn_otsukare.png', array('alt' => 'オツカレ', 'value' => 'オツカレ', 'width' => '70', 'div' => false)); ?></p> <?php echo $this->Html->image('icon_otsukare_load.png', array('id'=>'otukareLoadIcon', 'style'=>'display:none;')); ?> </form> </div> <?php endif; ?> <div class="commentList"> <?php if($like_flg) { ?> <p class="otsukareBtnSumi" style="display:none;"><?php echo $this->Html->image('comment_btn_otsukare_sumi.png', array('alt'=>'オツカレ済!', 'width'=>'280')); ?></p> <?php } else { ?> <p class="otsukareBtnSumi" style="display:block"><?php echo $this->Html->image('comment_btn_otsukare_sumi.png', array('alt'=>'オツカレ済!', 'width'=>'280')); ?></p> <?php } ?> <ul> <?php foreach ($likes as $like) : if ($like['Like']['message']!='') : ?> <li data-friend-jobkind="<?php echo $like['User']['current_jobkind_id']; ?>" data-friend-level="<?php echo $like['User']['current_level']; ?>"> <a href="<?php echo $this->webroot; ?>friends/view/<?php echo $like['Like']['friend_id']; ?>" > <p class="commentAvatar"><canvas width="80" height="80"></canvas></p> <div class="detail"> <h2><?php echo $like['User']['username']; ?></h2> <p class="text"><?php echo $like['Like']['message']; ?></p> <p class="times"><?php echo $like['Like']['action_time']; ?></p> </div> </a> </li> <?php endif; endforeach; ?> </ul> </div> </li> </ul> <?php if ( $comment_cnt > 5 ) : ?> <p id="moreFeed">もっと読む…<span><?php echo $this->Html->image('icon_otsukare_load.png', array('alt'=>'loading')); ?></span></p> <?php endif; ?> </div> </div><!-- /#friendTimeline --> <file_sep><?php echo $this->Javascript->link('global', false);?> <?php echo $this->Javascript->link('charactor', false);?> <?php echo $this->Javascript->link('sync', false);?> <script> $(function (){ //もっと読むのタップ時に一度だけポーリング $("#moreFeed").bind("click", function (){ $(this).find("span").show(); var Itimers = setInterval(function () { clearInterval(Itimers); Sync.more(5, function (res){ //console.log("応答",res.feeds) if(res.feeds !== null) { var dom = ""; for (var i = 0; i<res.feeds.length; i++) { //1フィードごとに時間を計算する var times = Global.compareTime(res.feeds[i].created); dom += '<li data-friend-jobkind="'+res.feeds[i].jobkind+'" data-friend-level="'+res.feeds[i].level+'" data-friend-level="'+res.feeds[i].id+'"><a href="/a/feeds/detail/'+res.feeds[i].id+'"><canvas width="80" height="80" class="avatarIcon"></canvas><div class="activity"><p class="comment">'+res.feeds[i].body+'</p><div class="footer"><p class="icon"><span class="comment">'+res.feeds[i].likesCount+'</span><span class="otsu">'+res.feeds[i].commentCount+'</span></p><p class="times">'+times+'</p></div></div></a></li>'; } $(dom).appendTo(".woodWrapper ul").hide().slideDown(1000, function (){ $("#moreFeed span").hide(); }); Global.thumbnail2Canvas(); }else{ //もし{feed: null}だったら $("#moreFeed").css({ "background":"url(/a/img/btn_readnomore.png) no-repeat center top", "background-size":"299px 86px", "width":"299px", "height":"86px", "padding-bottom":"0" }); $("#moreFeed span").hide(); } },$("#timeline ul li:last-child").data("feed-id")); }, 500); }); }); </script> <?php echo $this->Html->css('tmp', 'stylesheet', array('inline'=>false)); ?> <div class="mypageBtn"> <p><?php echo $this->Html->link($this->Html->image('header_btn_list.png', array('alt'=>'予定リスト', 'width'=>'117')), array('controller'=>'jobs', 'action'=>'index'), array('escape'=>false)); ?></p> </div> <div class="profile"> <h1><?php echo $user['User']['username']; ?></h1> <p class="profileAvatar" data-friend-jobkind="<?php echo $user['User']['current_jobkind_id']; ?>" data-friend-level="<?php echo $user['User']['current_level']; ?>"> <script> //console.log($(".profileAvatar").data("friend-jobkind"), $(".profileAvatar").data("friend-level")); //var avatarData = {kind:} var s = Charactor.getImage($(".profileAvatar").data("friend-jobkind"), $(".profileAvatar").data("friend-level")); document.write(s); </script> </p> <div class="profileBg"> <div class="profileDetail"> <div class="profileLevel"> <h2><?php echo $level['Level']['name']; ?><span><?php echo $jobkind['Jobkind']['name'] ?></span></h2> <p class="level"><?php echo $user['User']['current_level'] ?></p> </div> <ul class="profileCount"> <li class="otsukare"><?php echo $likecnt; ?></li> <li class="checkout"><?php echo $checkoutcnt; ?></li> </ul> </div><!-- /.profileDetail --> <!-- 未実装 <div class="pointGage"> <p class="meter"><span></span></p> <div class="gage"> <p class="text">LEVEL2まであと<strong>35 pt</strong></p> <p class="point">20 pt</p> </div> </div> --> </div><!-- /.profileBg --> </div><!-- /.profile --> <div id="timeline" class="woodFrame"> <div class="woodWrapper"> <?php if(!empty($feeds)) { // Friend Timeline Loop ?> <ul> <?php foreach($feeds as $feed) { ?> <li data-friend-jobkind="<?php echo $feed['User']['current_jobkind_id']; ?>" data-friend-level="<?php echo $feed['User']['current_level']; ?>" data-feed-id="<?php echo $feed['Feed']['id']; ?>"> <a href="<?php echo $this->webroot; ?>feeds/detail/<?php echo $feed['Feed']['id']; ?>"> <canvas width="80" height="80" class="avatarIcon"></canvas> <div class="activity"> <p class="comment"> <?php echo $feed['Feed']['message']; ?> </p> <div class="footer"> <p class="icon"><span class="comment"><?php echo $feed['Like']['comments']; ?></span> <span class="otsu"><?php echo $feed['Like']['likes']; ?></span></p> <p class="times"><?php echo $feed['Feed']['created']; ?></p> </div> </div> </a> </li> <?php } ?> </ul> <?php } ?> <?php if(!empty($feeds)) { ?> <p id="moreFeed">もっと読む…<span><img src="/a/img/icon_otsukare_load.png" alt="loading"></span></p> <? } else { ?> <p id="nolist"> <?php echo $this->Html->link('予定を登録してバイトをするぽ!', array('controller'=>'jobs', 'action'=>'add')); ?> </p> <? } ?> </div> </div><!-- /#friendTimeline --> <file_sep><?php // オツカレコメントの投稿 $res = '{ success: true, level: "3", jobkind: "2" }'; print( $res ); ?><file_sep><?php class LikesController extends AppController { var $name = 'Likes'; var $helpers = array('Javascript'); function index() { $this->Like->recursive = 0; $this->set('likes', $this->paginate()); } function view($id = null) { if (!$id) { $this->Session->setFlash(__('Invalid like', true)); $this->redirect(array('action' => 'index')); } $this->set('like', $this->Like->read(null, $id)); } function add() { if (!empty($this->data)) { $this->Like->create(); if ($this->Like->save($this->data)) { $this->Session->setFlash(__('The like has been saved', true)); $this->redirect(array('action' => 'index')); } else { $this->Session->setFlash(__('The like could not be saved. Please, try again.', true)); } } $users = $this->Like->User->find('list'); $jobs = $this->Like->Job->find('list'); $jobkinds = $this->Like->Jobkind->find('list'); $feeds = $this->Like->Feed->find('list'); $this->set(compact('users', 'jobs', 'jobkinds', 'feeds')); } function edit($id = null) { if (!$id && empty($this->data)) { $this->Session->setFlash(__('Invalid like', true)); $this->redirect(array('action' => 'index')); } if (!empty($this->data)) { if ($this->Like->save($this->data)) { $this->Session->setFlash(__('The like has been saved', true)); $this->redirect(array('action' => 'index')); } else { $this->Session->setFlash(__('The like could not be saved. Please, try again.', true)); } } if (empty($this->data)) { $this->data = $this->Like->read(null, $id); } $users = $this->Like->User->find('list'); $jobs = $this->Like->Job->find('list'); $jobkinds = $this->Like->Jobkind->find('list'); $feeds = $this->Like->Feed->find('list'); $this->set(compact('users', 'jobs', 'jobkinds', 'feeds')); } function delete($id = null) { if (!$id) { $this->Session->setFlash(__('Invalid id for like', true)); $this->redirect(array('action'=>'index')); } if ($this->Like->delete($id)) { $this->Session->setFlash(__('Like deleted', true)); $this->redirect(array('action'=>'index')); } $this->Session->setFlash(__('Like was not deleted', true)); $this->redirect(array('action' => 'index')); } function admin_index() { $this->Like->recursive = 0; $this->set('likes', $this->paginate()); } function admin_view($id = null) { if (!$id) { $this->Session->setFlash(__('Invalid like', true)); $this->redirect(array('action' => 'index')); } $this->set('like', $this->Like->read(null, $id)); } function admin_add() { if (!empty($this->data)) { $this->Like->create(); if ($this->Like->save($this->data)) { $this->Session->setFlash(__('The like has been saved', true)); $this->redirect(array('action' => 'index')); } else { $this->Session->setFlash(__('The like could not be saved. Please, try again.', true)); } } $users = $this->Like->User->find('list'); $jobs = $this->Like->Job->find('list'); $jobkinds = $this->Like->Jobkind->find('list'); $feeds = $this->Like->Feed->find('list'); $this->set(compact('users', 'jobs', 'jobkinds', 'feeds')); } function admin_edit($id = null) { if (!$id && empty($this->data)) { $this->Session->setFlash(__('Invalid like', true)); $this->redirect(array('action' => 'index')); } if (!empty($this->data)) { if ($this->Like->save($this->data)) { $this->Session->setFlash(__('The like has been saved', true)); $this->redirect(array('action' => 'index')); } else { $this->Session->setFlash(__('The like could not be saved. Please, try again.', true)); } } if (empty($this->data)) { $this->data = $this->Like->read(null, $id); } $users = $this->Like->User->find('list'); $jobs = $this->Like->Job->find('list'); $jobkinds = $this->Like->Jobkind->find('list'); $feeds = $this->Like->Feed->find('list'); $this->set(compact('users', 'jobs', 'jobkinds', 'feeds')); } function admin_delete($id = null) { if (!$id) { $this->Session->setFlash(__('Invalid id for like', true)); $this->redirect(array('action'=>'index')); } if ($this->Like->delete($id)) { $this->Session->setFlash(__('Like deleted', true)); $this->redirect(array('action'=>'index')); } $this->Session->setFlash(__('Like was not deleted', true)); $this->redirect(array('action' => 'index')); } } <file_sep>var Charactor = { chara: { power: { name: "力仕事系、労働", level: [ { lv:"0", url:"chara_power_lv0.png", alt: "ただの平凡なフェアリー" }, { lv:"1", url:"chara_power_lv1.png", alt: "引越しスタッフのピクシー" }, { lv:"2", url:"chara_power_lv2.png", alt: "建築現場のゴブリン" }, { lv:"3", url:"chara_power_lv3.png", alt: "現場チーフのエルフ" }, { lv:"4", url:"chara_power_lv4.png", alt: "筋肉ムキムキになったドワーフ" }, { lv:"5", url:"chara_power_lv5.png", alt: "" } ] }, // 職業:power 終了 events: { name: "イベントスタッフ", level: [ { lv:"0", url:"chara_event_lv0.png", alt: "ただの平凡なフェアリー" }, { lv:"1", url:"chara_event_lv1.png", alt: "ティッシュ配りのピクシー" }, { lv:"2", url:"chara_event_lv2.png", alt: "スポーツ会場警備のゴブリン" }, { lv:"3", url:"chara_event_lv3.png", alt: "コンサートスタッフのエルフ" }, { lv:"4", url:"chara_event_lv4.png", alt: "モーターショーのドワーフ" }, { lv:"5", url:"chara_event_lv5.png", alt: "" } ] }, // 職業:events 終了 sampling: { name: "サンプリングスタッフ", level: [ { lv:"0", url:"chara_sampling_lv0.png", alt: "ただの平凡なフェアリー" }, { lv:"1", url:"chara_sampling_lv1.png", alt: "チラシ配りのピクシー" }, { lv:"2", url:"chara_sampling_lv2.png", alt: "ソーセージ試食のゴブリン" }, { lv:"3", url:"chara_sampling_lv3.png", alt: "コーヒー試飲のエルフ" }, { lv:"4", url:"chara_sampling_lv4.png", alt: "ワイン試飲のほろ酔いドワーフ" }, { lv:"5", url:"chara_sampling_lv5.png", alt: "" } ] }, // 職業:sampling 終了 shop: { name: "店舗スタッフ", level: [ { lv:"0", url:"chara_shop_lv0.png", alt: "ただの平凡なフェアリー" }, { lv:"1", url:"chara_shop_lv1.png", alt: "販売員のピクシー" }, { lv:"2", url:"chara_shop_lv2.png", alt: "チーフのゴブリン" }, { lv:"3", url:"chara_shop_lv3.png", alt: "フロアマネージャーのエルフ" }, { lv:"4", url:"chara_shop_lv4.png", alt: "店長のドワーフ" }, { lv:"5", url:"chara_shop_lv5.png", alt: "" } ] }, // 職業:shop 終了 office: { name: "オフィスワーク", level: [ { lv:"0", url:"chara_office_lv0.png", alt: "ただの平凡なフェアリー" }, { lv:"1", url:"chara_office_lv1.png", alt: "新人事務のピクシー" }, { lv:"2", url:"chara_office_lv2.png", alt: "営業事務のゴブリン" }, { lv:"3", url:"chara_office_lv3.png", alt: "経理で何かを企むエルフ" }, { lv:"4", url:"chara_office_lv4.png", alt: "企画のドワーフ" }, { lv:"5", url:"chara_office_lv5.png", alt: "" } ] }, // 職業:office 終了 teacher: { name: "講師・インストラクター", level: [ { lv:"0", url:"chara_teacher_lv0.png", alt: "ただの平凡なフェアリー" }, { lv:"1", url:"chara_teacher_lv1.png", alt: "アシスタントのピクシー" }, { lv:"2", url:"chara_teacher_lv2.png", alt: "塾講師ののゴブリン" }, { lv:"3", url:"chara_teacher_lv3.png", alt: "英会話教室のエルフ" }, { lv:"4", url:"chara_teacher_lv4.png", alt: "セミナー講師のドワーフ" }, { lv:"5", url:"chara_teacher_lv5.png", alt: "" } ] }, // 職業:teacher 終了 free: { name: "遊び人(その他)", level: [ { lv:"0", url:"chara_free_lv0.png", alt: "ただの平凡なフェアリー" }, { lv:"1", url:"chara_free_lv1.png", alt: "ヘルプのピクシー" }, { lv:"2", url:"chara_free_lv2.png", alt: "夜のお店のゴブリン" }, { lv:"3", url:"chara_free_lv3.png", alt: "悪そうな奴は大体友達なエルフ" }, { lv:"4", url:"chara_free_lv4.png", alt: "夜の女王ドワーフ" }, { lv:"5", url:"chara_free_lv5.png", alt: "" } ] }, // 職業:free 終了 season: { name: "季節系(夏季限定/冬季限定)", level: [ { lv:"0", url:"chara_season_lv0.png", alt: "ただの平凡なフェアリー" }, { lv:"1", url:"chara_season_lv1.png", alt: "海の家のピクシー" }, { lv:"2", url:"chara_season_lv2.png", alt: "山小屋のゴブリン" }, { lv:"3", url:"chara_season_lv3.png", alt: "スキーインストラクターのエルフ" }, { lv:"4", url:"chara_season_lv4.png", alt: "ライフセーバーのドワーフ" }, { lv:"5", url:"chara_season_lv5.png", alt: "" } ] } // 職業:season 終了 }, // chara // -------------------------------- chara 終了 -------------------------------- background: [ { url: "bg_lv0.jpg" }, { url: "bg_lv1.jpg" }, { url: "bg_lv2.jpg" }, { url: "bg_lv3.jpg" }, { url: "bg_lv4.jpg" }, { url: "bg_lv5.jpg" } ], // -------------------------------- 背景 終了 -------------------------------- commonTitle: [ "ノーマル", "羽が生えてる", "ツノ/コンボウ", "耳長/帽子", "目付き悪/ヒゲ", "背後キラキラ?" ], // -------------------------------- 共通特徴 終了 -------------------------------- num2JobTitle: function (num){ var titles = ["power","events","sampling","shop","office","teacher","free","season"]; return titles[num]; }, // -------------------------------- サーバから来た職業数値を文字列にして返す 終了 -------------------------------- thumbBGColor: function (num){ var color = ["cyan","yellow","orange","green","parple","silver"]; //追加可能 return color[num]; }, // -------------------------------- サムネイルの背景色はレベルによって変更される 終了 -------------------------------- getArray: function (jobKind, level, num){ //ここで重ねる画像の配列を返す //引数が0: 背景付き //引数が1: 背景無し //つまり 0だとマイキャラ、1だとサムネイル var imgs = {}; imgs.bg = Charactor.background[level].url; if(level === 0) { imgs.uwamono = "chara_lv0.png"; }else{ $(Charactor.chara).each( function (i, val){ for(var i in this) { if(i === jobKind) { imgs.uwamono = this[i].level[level].url; break; } } }); } if(num === 1) { //背景無し return ["chara_lv0.png", imgs.uwamono]; }else{ //背景あり return [imgs.bg, "chara_lv0.png", imgs.uwamono]; } }, getImage: function (jobKind, level){ var basePath = "/img/avatar/"; var arr = Charactor.getArray(jobKind, level, 0); var container = $("<div />"); var bg = $("<img src='"+basePath+arr[0]+"'>"); var uwamono = $("<img src='"+basePath+arr[2]+"'>"); var bodys = $("<img src='"+basePath+"chara_lv0.png"+"'>"); container.append(bg); if(level === 0) { container.append(bodys); }else{ container.append(bodys); container.append(uwamono); } return container[0].innerHTML; }, getThumbnail: function (jobKind, level, canvas){ //サムネイルにはcanvasで生成する var basePath = "/img/avatar/"; var arr = Charactor.getArray(Charactor.num2JobTitle(jobKind), level, 1); var ctx = canvas.getContext("2d"); var img1 = new Image(); img1.src = basePath+arr[0]+"?"+new Date().getTime(); img1.onload = function () { var scale = 80/img1.height; var img2 = new Image(); img2.src = basePath+arr[1]+"?"+new Date().getTime(); img2.onload = function () { ctx.fillStyle = Charactor.thumbBGColor(level); ctx.fillRect(0,0,80,80); ctx.setTransform(scale, 0, 0, scale, -30, 0); ctx.drawImage(img1, 0, 0); ctx.drawImage(img2, 0, 0); } } } }; // Charactor オブジェクト終了<file_sep><?php class User extends AppModel { var $name = 'User'; var $validate = array( 'username' => array( 'notempty' => array( 'rule' => array('notempty'), 'message' => 'Please input username here.', //'allowEmpty' => false, //'required' => false, //'last' => false, // Stop validation after this rule //'on' => 'create', // Limit validation to 'create' or 'update' operations ), 'maxlength' => array( 'rule' => array('maxlength', '20'), 'message' => 'Usernames must be no larger than 20 characters long.', //'allowEmpty' => false, //'required' => false, //'last' => false, // Stop validation after this rule //'on' => 'create', // Limit validation to 'create' or 'update' operations ), 'unique' => array( 'rule' => 'isUnique', 'message' => 'This username is already use.' ), 'alphaNumeric' => array( 'rule' => 'alphaNumeric', 'message' => 'Username must be alphabet and numeric.' ), ), 'password' => array( 'notempty' => array( 'rule' => array('notempty'), 'message' => 'Please input password here.', 'allowEmpty' => false, //'required' => false, //'last' => false, // Stop validation after this rule //'on' => 'create', // Limit validation to 'create' or 'update' operations ), /* 'minlength' => array( 'rule' => array('minlength', '6'), 'message' => 'Usernames must be at least 6 characters long.', //'allowEmpty' => false, //'required' => false, //'last' => false, // Stop validation after this rule //'on' => 'create', // Limit validation to 'create' or 'update' operations ), 'maxlength' => array( 'rule' => array('maxlength', '100'), 'message' => 'Usernames must be no larger than 20 characters long.', //'allowEmpty' => false, //'required' => false, //'last' => false, // Stop validation after this rule //'on' => 'create', // Limit validation to 'create' or 'update' operations ), */ ), 'join_password' => array( 'notempty' => array( 'rule' => array('notempty'), 'message' => 'Please input password here.', 'allowEmpty' => false, //'required' => false, //'last' => false, // Stop validation after this rule //'on' => 'create', // Limit validation to 'create' or 'update' operations ), 'between' => array( 'rule' => array('between', 6, 20), 'message' => 'Usernames must be at 6-20 characters long.', //'allowEmpty' => false, //'required' => false, //'last' => false, // Stop validation after this rule //'on' => 'create', // Limit validation to 'create' or 'update' operations ), ), 'email' => array( 'email' => array( 'rule' => array('email'), 'message' => 'Invalid Email address.', //'allowEmpty' => false, //'required' => false, //'last' => false, // Stop validation after this rule //'on' => 'create', // Limit validation to 'create' or 'update' operations ), 'notempty' => array( 'rule' => array('notempty'), 'message' => 'Please input email address here.', //'allowEmpty' => false, //'required' => false, //'last' => false, // Stop validation after this rule //'on' => 'create', // Limit validation to 'create' or 'update' operations ), 'unique' => array( 'rule' => 'isUnique', 'message' => 'This username is already use.' ), ), 'point' => array( 'numeric' => array( 'rule' => array('numeric'), //'message' => 'Your custom message here', //'allowEmpty' => false, //'required' => false, //'last' => false, // Stop validation after this rule //'on' => 'create', // Limit validation to 'create' or 'update' operations ), ), ); //The Associations below have been created with all possible keys, those that are not needed can be removed var $hasMany = array( 'Feed' => array( 'className' => 'Feed', 'foreignKey' => 'user_id', 'dependent' => false, 'conditions' => '', 'fields' => '', 'order' => '', 'limit' => '', 'offset' => '', 'exclusive' => '', 'finderQuery' => '', 'counterQuery' => '' ), 'Friend' => array( 'className' => 'Friend', 'foreignKey' => 'user_id', 'dependent' => false, 'conditions' => '', 'fields' => '', 'order' => '', 'limit' => '', 'offset' => '', 'exclusive' => '', 'finderQuery' => '', 'counterQuery' => '' ), /* 'Friend' => array( 'className' => 'Friend', 'foreignKey' => 'friend_id', 'dependent' => false, 'conditions' => '', 'fields' => '', 'order' => '', 'limit' => '', 'offset' => '', 'exclusive' => '', 'finderQuery' => '', 'counterQuery' => '' ), */ 'Job' => array( 'className' => 'Job', 'foreignKey' => 'user_id', 'dependent' => false, 'conditions' => '', 'fields' => '', 'order' => '', 'limit' => '', 'offset' => '', 'exclusive' => '', 'finderQuery' => '', 'counterQuery' => '' ), 'Like' => array( 'className' => 'Like', 'foreignKey' => 'user_id', 'dependent' => false, 'conditions' => '', 'fields' => '', 'order' => '', 'limit' => '', 'offset' => '', 'exclusive' => '', 'finderQuery' => '', 'counterQuery' => '' ) ); } <file_sep> //Grobal(総合) ---------------------------------------------------------------------- Global = { init: function (){ //ページ読み込み完了時処理 Global.setPageBackBtn(); return this; }, setPageBackBtn: function (){ //ヘッダのバックボタンを設定する $(".pageBack a").bind("click", function (e){ e.preventDefault(); window.history.back(); }); return this; }, compareTime : function (tm) { var ds = Date.parse( tm.replace( /-/g, '/') ); var interval = (new Date().getTime() - ds) / 60000; //(差を分刻みで出す) // 1分は60000ミリ秒 // 1時間は60分 = 3,600,000ミリ秒 // 1日は1440分 // 6時間は360分 // 3時間は180分 // 1時間は60分 var time = 0; if (interval > 1440) time= "1日前"; else if (interval > 1440) time= "1日前"; else if (interval > 360) time= "6時間以上前"; else if (interval > 180) time= "3時間以上前"; else if (interval > 60) time= "1時間以上前"; else if (interval >= 30) time= "30分以上前"; else if (interval < 30) { time = parseInt(interval) + "分前" } return time; }, //タイムラインのcanvasを検索してサムネイル変換関数を呼ぶ ---------------------------------------------------------------------- thumbnail2Canvas : function () { if($(".woodWrapper")) { // && !$(".friendTimelineDetail") $(".avatarIcon").each(function(index, element) { var kind = $(this).closest("li").data("friend-jobkind"); var level = $(this).closest("li").data("friend-level"); Charactor.getThumbnail(kind,level,this); }); } }, // 6_friend_timeline2.html用、その人だけのタイムラインのサムネイル作成---------------------------------------------------------------------- search2Canvas : function () { if($(".commentList")) { $(".commentList .commentAvatar").each(function(index, element) { var kind = $(this).closest("li").data("friend-jobkind"); var level = $(this).closest("li").data("friend-level"); Charactor.getThumbnail(kind,level,$(this).find("canvas")[0]); }); } } }; // Grobal end //Grobal(総合) ---------------------------------------------------------------------- //新規登録 ---------------------------------------------------------------------- var Resist = { check: function (){ if($("body").hasClass("nickname")) Resist.registBook(); }, registBook: function () { var inp = $(".newRegistration #_name"); inp.bind("change", function (){ $(".nickname #yourname").text($(this).val()); $("#bookArea").css({"background":"none"}); /*var timers = setTimeout(function (){ $("#bookArea").css({"background":"url(img/regist_book_bg.jpg) no-repeat"}); }, 30);*/ }); } }//Resist end //新規登録 ---------------------------------------------------------------------- var RollOver = { set : function () { var classes = $(".tapping"); classes.each(function (){ var img = $(this).find("img"); var src = img.attr("src").replace(".png", "_on.png?")+new Date().getTime(); var i = new Image().src = src; console.log(src) $(this).bind("touchstart mousedown", function (){ img.attr("src",src); }); }); return this; } } //アクティベート(実行) ---------------------------------------------------------------------- window.onload = function (){ // Grobal Activate Global.init(); //新規登録アクティベート Resist.check(); //サムネイルをcanvasに生成 Global.thumbnail2Canvas(); Global.search2Canvas(); //アクティブボタンの指定 RollOver.set(); } <file_sep><?php // キャラクター構成のためのレベル、職業 $res = "{ level: '4', jobkind: '3', likesCount: '12', checkoutCount: '20', totalPoint: '19546' } "; print( $res ); ?><file_sep><!DOCTYPE HTML> <html> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, user-scalable=no"><!----> <?php echo $this->Html->meta('icon'); ?> <title>トップページ</title> <?php echo $this->Javascript->link('jquery-1.7.min');?> <?php if(!empty($async_json_data)) { ?> <script> var asyncResult = <?php echo $async_json_data; ?> </script> <?php } ?> <?php echo $scripts_for_layout; ?> <?php echo $this->Html->css('style', 'stylesheet', array('inline'=>true)); ?> </head> <body> <div id="container"> <div class="containerInner"> <header> <span class="profileBtn"> <?php echo $this->Html->link($this->Html->image('header_btn_profile.png', array('alt'=>'MyProfile')), array('action' => 'edit'), array('escape' => false));?> </span> <nav> <ul> <li><?php echo $this->Html->link($this->Html->image('header_btn_list.png', array('alt'=>'予定リスト')), array('controller' => 'jobs', 'action' => 'index'), array('escape' => false));?></li> <li><?php echo $this->Html->link($this->Html->image('header_btn_regist.png', array('alt'=>'バイト予定登録')), array('controller' => 'jobs', 'action' => 'add'), array('escape' => false));?></li> <li><?php echo $this->Html->link($this->Html->image('header_btn_supporter.png', array('alt'=>'マイサポーター')), array('controller' => 'feeds', 'action' => 'index'), array('escape' => false, 'title'=>'SNSタイムライン'));?></li> </ul> </nav> </header> <?php echo $this->Session->flash(); ?> <?php echo $content_for_layout; ?> </div><!-- /#contenerInner --> </div><!-- /#container --> <?php echo $this->element('sql_dump'); ?> </body> </html> <file_sep><?php // オツカレコメントの投稿 $res = "{ feeds: [ { id: 200, jobKind: '2', level: '1', userID: '1234', body: '<span>Hidetaro7さん</span>がバイトにチェックインしました。', likesCount: '12', commentCount: '3', created: '2012-01-19 12:00:00' }, { id: 201, jobKind: '1', level: '3', userID: '1234', body: '<span>Tommmmyさん</span>がバイトにチェックインしました。', likesCount: '12', commentCount: '3', created: '2012-01-18 12:00:00' }, { id: 202, jobKind: '4', level: '5', userID: '1234', body: '<span>nakashizuさん</span>がバイトにチェックインしました。', likesCount: '12', commentCount: '3', created: '2012-01-20 18:00:00' }, { id: 203, jobKind: '6', level: '2', userID: '1234', body: '<span>BathTimeFishさん</span>がバイトにチェックインしました。', likesCount: '12', commentCount: '3', created: '2012-01-20 20:00:00' } ] } "; print( $res ); ?><file_sep>-- phpMyAdmin SQL Dump -- version 3.3.9.2 -- http://www.phpmyadmin.net -- -- ホスト: localhost -- 生成時間: 2012 年 1 月 26 日 01:03 -- サーバのバージョン: 5.5.9 -- PHP のバージョン: 5.3.5 SET SQL_MODE="NO_AUTO_VALUE_ON_ZERO"; /*!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 utf8 */; -- -- データベース: `biteup` -- -- -------------------------------------------------------- -- -- テーブルの構造 `feeds` -- CREATE TABLE `feeds` ( `id` int(11) NOT NULL AUTO_INCREMENT COMMENT 'ID', `user_id` int(11) NOT NULL COMMENT 'ユーザーID', `job_id` int(11) NOT NULL COMMENT '仕事予定ID', `message` varchar(255) DEFAULT NULL COMMENT 'メッセージ', `created` datetime NOT NULL COMMENT '作成日', `modified` datetime NOT NULL COMMENT '更新日', PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=5 ; -- -- テーブルのデータをダンプしています `feeds` -- INSERT INTO `feeds` VALUES(1, 5, 1, '仕事がおわった。つかれた〜', '2012-01-03 23:55:05', '2012-01-03 23:56:48'); INSERT INTO `feeds` VALUES(2, 8, 2, '仕事終わったから飲みに行こう!', '2012-01-03 23:55:25', '2012-01-03 23:57:03'); INSERT INTO `feeds` VALUES(3, 5, 2, 'test just checkin to ブロック運び', '2012-01-04 11:26:44', '2012-01-04 11:26:44'); INSERT INTO `feeds` VALUES(4, 5, 2, 'test just checkout to ブロック運び', '2012-01-04 11:27:21', '2012-01-04 11:27:21'); -- -------------------------------------------------------- -- -- テーブルの構造 `friends` -- CREATE TABLE `friends` ( `id` int(11) NOT NULL AUTO_INCREMENT COMMENT 'ID', `user_id` int(11) NOT NULL COMMENT 'ユーザーID', `friend_id` int(11) NOT NULL COMMENT 'フレンドID', `created` datetime NOT NULL COMMENT '作成日', `modified` datetime NOT NULL COMMENT '更新日', PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=5 ; -- -- テーブルのデータをダンプしています `friends` -- INSERT INTO `friends` VALUES(1, 5, 6, '2012-01-25 23:16:42', '2012-01-25 23:16:45'); INSERT INTO `friends` VALUES(2, 5, 7, '2012-01-25 23:16:55', '2012-01-25 23:16:57'); INSERT INTO `friends` VALUES(3, 5, 8, '2012-01-03 21:12:53', '2012-01-03 21:12:53'); INSERT INTO `friends` VALUES(4, 5, 6, '2012-01-03 21:16:53', '2012-01-03 21:16:53'); -- -------------------------------------------------------- -- -- テーブルの構造 `jobkinds` -- CREATE TABLE `jobkinds` ( `id` int(11) NOT NULL AUTO_INCREMENT COMMENT 'ID', `name` varchar(50) NOT NULL COMMENT '名前', `created` datetime NOT NULL COMMENT '作成日', `modified` datetime NOT NULL COMMENT '更新日', PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=4 ; -- -- テーブルのデータをダンプしています `jobkinds` -- INSERT INTO `jobkinds` VALUES(1, '力仕事', '2011-12-28 17:00:20', '2011-12-28 17:00:20'); INSERT INTO `jobkinds` VALUES(2, '頭脳労働', '2011-12-28 17:00:43', '2011-12-28 17:00:43'); INSERT INTO `jobkinds` VALUES(3, 'やっつけ仕事', '2011-12-28 17:00:50', '2011-12-28 17:00:50'); -- -------------------------------------------------------- -- -- テーブルの構造 `jobs` -- CREATE TABLE `jobs` ( `id` int(11) NOT NULL AUTO_INCREMENT COMMENT 'ID', `user_id` int(11) NOT NULL COMMENT 'ユーザーID', `name` varchar(100) NOT NULL COMMENT '予定名', `startdate` date NOT NULL COMMENT '予定日', `starttime` time NOT NULL COMMENT '予定開始時間', `jobtime` int(11) NOT NULL COMMENT '就業時間', `jobkind_id` int(11) NOT NULL COMMENT '業種ID', `checkin` datetime DEFAULT NULL COMMENT 'チェックイン日時', `checkout` datetime DEFAULT NULL, `created` datetime NOT NULL COMMENT '作成日', `modified` datetime NOT NULL COMMENT '更新日', PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=5 ; -- -- テーブルのデータをダンプしています `jobs` -- INSERT INTO `jobs` VALUES(1, 5, 'コンビニのバイト', '2011-12-28', '17:31:00', 4, 2, '2012-01-04 00:14:23', '2012-01-04 00:15:52', '2011-12-28 17:41:24', '2012-01-04 00:25:21'); INSERT INTO `jobs` VALUES(2, 5, 'ブロック運び', '2012-01-05', '10:00:00', 7, 1, '2012-01-04 11:26:44', '2012-01-04 11:27:21', '2011-12-28 17:42:45', '2012-01-04 11:26:06'); INSERT INTO `jobs` VALUES(3, 5, 'バナナのたたき売り', '2012-01-04', '00:19:00', 6, 3, NULL, NULL, '2012-01-04 00:20:18', '2012-01-04 00:20:18'); INSERT INTO `jobs` VALUES(4, 5, '道路の舗装', '2012-01-06', '00:19:00', 8, 1, NULL, NULL, '2012-01-04 00:24:51', '2012-01-04 00:26:37'); -- -------------------------------------------------------- -- -- テーブルの構造 `levels` -- CREATE TABLE `levels` ( `id` int(11) NOT NULL AUTO_INCREMENT COMMENT 'ID', `level` int(11) NOT NULL COMMENT 'レベル', `name` varchar(50) NOT NULL COMMENT '名前', `limit` int(11) NOT NULL COMMENT 'しきい値', `avator` varchar(50) NOT NULL, `created` datetime NOT NULL COMMENT '作成日', `modified` datetime NOT NULL COMMENT '更新日', PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='共通レベル' AUTO_INCREMENT=1 ; -- -- テーブルのデータをダンプしています `levels` -- -- -------------------------------------------------------- -- -- テーブルの構造 `likes` -- CREATE TABLE `likes` ( `id` int(11) NOT NULL AUTO_INCREMENT COMMENT 'ID', `user_id` int(11) NOT NULL COMMENT 'ユーザーID', `friend_id` int(11) NOT NULL COMMENT 'フレンドID', `job_id` int(11) NOT NULL COMMENT '仕事予定ID', `jobkind_id` int(11) NOT NULL COMMENT '業種ID', `feed_id` int(11) NOT NULL COMMENT 'フィードID', `point` int(11) NOT NULL COMMENT 'ポイント', `message` varchar(255) DEFAULT NULL COMMENT 'メッセージ', `from` varchar(50) DEFAULT NULL COMMENT '投稿元', `created` datetime NOT NULL COMMENT '作成日', `modified` datetime NOT NULL COMMENT '更新日', PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=3 ; -- -- テーブルのデータをダンプしています `likes` -- INSERT INTO `likes` VALUES(1, 5, 6, 1, 1, 1, 3, 'おつかれさまでした!', 'facebook', '2012-01-25 23:22:24', '2012-01-25 23:22:24'); INSERT INTO `likes` VALUES(2, 5, 7, 1, 1, 1, 5, NULL, NULL, '2012-01-25 23:26:07', '2012-01-25 23:26:07'); -- -------------------------------------------------------- -- -- テーブルの構造 `users` -- CREATE TABLE `users` ( `id` int(11) NOT NULL AUTO_INCREMENT COMMENT 'ID', `username` varchar(50) NOT NULL COMMENT 'ユーザー名', `password` varchar(100) NOT NULL COMMENT 'パスワード', `email` varchar(100) NOT NULL COMMENT 'Eメール', `point` int(11) NOT NULL COMMENT 'ポイントの合計', `current_jobkind_id` tinyint(4) DEFAULT NULL, `current_level` tinyint(4) NOT NULL DEFAULT '1', `fb_access_token` varchar(255) DEFAULT NULL COMMENT 'Facebook OAuth Token', `created` datetime NOT NULL COMMENT '作成日', `modified` datetime NOT NULL COMMENT '更新日', PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=13 ; -- -- テーブルのデータをダンプしています `users` -- INSERT INTO `users` VALUES(5, 'test', '<PASSWORD>', '<EMAIL>', 0, 1, 1, NULL, '2012-01-03 15:39:20', '2012-01-03 15:39:20'); INSERT INTO `users` VALUES(6, 'hogehoge', '000cdc7f9f5d8cec146544805024347320742ea5', '<EMAIL>', 0, NULL, 0, NULL, '2012-01-03 17:08:09', '2012-01-03 17:08:09'); INSERT INTO `users` VALUES(7, 'fugafuga', 'fe05183229c4bcea432cdcdc7476fea2022cb3ce', '<EMAIL>', 0, NULL, 0, NULL, '2012-01-03 17:08:31', '2012-01-03 17:08:31'); INSERT INTO `users` VALUES(12, 'aaaa', '000cdc7f9f5d8cec146544805024347320742ea5', '<EMAIL>', 0, 0, 0, NULL, '2012-01-20 16:41:13', '2012-01-20 16:41:13'); <file_sep><!DOCTYPE HTML> <html> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, minimum-scale=1.0, maximum-scale=1.0, user-scalable=no"> <title>絵本をつくる</title> <?php echo $this->Javascript->link('jquery-1.7.min');?> <?php echo $this->Javascript->link('global');?> <?php echo $this->Html->css('style', 'stylesheet', array('inline'=>true)); ?> <?php echo $this->Html->css('tmp', 'stylesheet', array('inline'=>true)); ?> </head> <body class="nickname"> <div id="container"> <header> <h1>バイトの妖精</h1> <p class="pageBack tapping"><?php echo $this->Html->link($this->Html->image('header_btn_back.png', array('alt'=>'戻る', 'width'=>'43', 'height'=>'34')), 'javascript:history.go(-1);', array('escape' => false));?></p> <p class="profileBtn tapping"><?php echo $this->Html->link($this->Html->image('header_btn_login.png', array('alt'=>'ログイン', 'width'=>'68', 'height'=>'36')), array('controller' => 'users', 'action' => 'login'), array('escape' => false));?></p> </header> <div id="bookArea"> <p id="yourname"></p> </div> <div id="login" class="newRegistration"> <?php echo $this->Session->flash(); ?> <?php echo $this->Form->create('User', array('class'=>'loginForm'));?> <div class="woodFrame registFrame"> <h1><?php echo $this->Html->image('regist_title_regist.png', array('alt'=>'あなたの絵本をつくる', 'width'=>'298', 'height'=>'54')); ?></h1> <div class="woodWrapper"> <p class="text">あなたの絵本をつくるから、少しだけあなたのことを教えてぽ。</p> <dl> <dt><label for="_name">ニックネーム</label></dt> <dd> <?php echo $this->Form->input('username', array('div'=>false, 'label'=>false, 'id'=>'_name', 'placeholder'=>'ニックネームを入力', 'class'=>'loginRegist')); ?> <br><small>※ 半角英数字で入力するぽ。</small> <dt><label for="_mail">メールアドレス</label></dt> <dd> <?php echo $this->Form->input('email', array('div'=>false, 'label'=>false, 'id'=>'_mail', 'placeholder'=>'メールアドレスを入力', 'class'=>'loginRegist')); ?> <br><small>※ 半角英数字で入力するぽ。</small> </dd> <dt><label for="_pass">パスワード</label></dt> <dd class="ok"><?php echo $this->Form->input('join_password', array('type'=>'password', 'value'=>'', 'id'=>'_pass', 'placeholder'=>'パスワードを入力', 'class'=>'loginRegist', 'div'=>false, 'label'=>false)); ?></dd> <dd><?php echo $this->Form->input('re_password', array('type'=>'password', 'value'=>'', 'id'=>'_pass2', 'placeholder'=>'確認用パスワードの再入力', 'class'=>'loginRegist', 'div'=>false, 'label'=>false)); ?></dd> <br><small>※ 半角英数字6文字以上で入力するぽ。</small> </dd> </dl> </div> </div> <div class="btnArea"> <p><?php echo $this->Html->link($this->Html->image('regist_btn_back.png', array('alt'=>'戻る', 'width'=>'67')), 'javascript:history.go(-1);', array('escape' => false));?></p> <p><?php echo $this->Form->submit('login_btn_regist.png', array('alt'=>"絵本をつくる!", 'value'=>"新規登録送信", 'width'=>"235")); ?></p> </div> <p class="loginAttention"><a href="#">利用ガイドライン</a>に同意の上、[絵本をつくる]ボタンをクリックすると登録が完了致します。個人情報保護方針についても利用ガイドラインからご確認ください。</p> </form> </div> </div><!--/container--> <footer> <nav> <ul> <li class="tapping"><?php echo $this->Html->link($this->Html->image('footer_btn_info.png', array('alt' => '登録情報', 'width' => '68', 'height' => '38')), array('controller'=>'users', 'action'=>'edit'), array('escape'=>false)); ?></a></li> <li class="tapping"><a href="../../s/guideline.html"><?php echo $html->image('footer_btn_guideline.png', array('alt' => '利用ガイドライン', 'width' => '107', 'height' => '38')); ?></a></li> <li class="tapping"><a href="../../s/about.html"><?php echo $html->image('footer_btn_about.png', array('alt' => 'designers hackとは', 'width' => '127', 'height' => '38')); ?></a></li> </ul> </nav> <p class="copyright">Copyright &copy; designers hack All Rights Reserved.</p> </footer> </body> </html> <file_sep><?php class LevelCalcComponent extends Object { var $User; var $Like; var $Level; /* component statup */ function startup(&$controller) { $this->User =& new User(); $this->Like =& new Like(); $this->Level =& new Level(); }//startup() // ユーザーにカレントレベルとカレントジョブIDをセットする function setUserLevel($user_id = null, $jobkind_id = null) { $this->Like->recursive = 0; $this->User->recursive = -1; $uped = array( 'uped' => null, 'name' => '', ); if($user_id) { //現在の最大ポイントのLikeを取得 $conditions = array('Like.friend_id' => $user_id, 'Like.jobkind_id' => $jobkind_id); $order = 'Like.current_point DESC'; $like = $this->Like->find('first', array('conditions'=>$conditions, 'order'=>$order)); //ユーザーのPointが最大のLikeを取得 if(!empty($like)) { $level = $this->changeCurrentLevel($like['Like']['jobkind_id'], $like['Like']['current_point'], $user_id); $this->log($level, LOG_DEBUG); $user = array('User' => array( 'id' => $user_id, 'current_level' => $level['level'], 'current_jobkind_id' => $level['jobkind_id'], )); $this->User->save($user); $uped['uped'] = $level['uped']; $uped['name'] = $level['name']; } } return $uped; } // ユーザーのカレントレベル、カレントジョブIDを変更する // ポイントが足りなければ変更しない function changeCurrentLevel($jobkind_id, $point, $user_id) { $uped = false; $name = ''; //現在ポイントに最も近いそれ以下のレベルを取得 $conditions = array('Level.jobkind_id' => $jobkind_id, 'Level.limit <=' => $point); $order = 'Level.limit DESC'; $level = $this->Level->find('first', array('conditions'=>$conditions, 'order'=>$order)); //カレントユーザーのレベルと比較 $current_level = 0; $current_jobkind_id = 0; $user = $this->User->read(null, $user_id); if($user['User']['current_level'] < $level['Level']['level']) { //ユーザーのレベルより大きいければレベルアップ $current_level = $level['Level']['level']; $current_jobkind_id = $level['Level']['jobkind_id']; $name = $level['Level']['name']; $uped = true; } else { $current_level = $user['User']['current_level']; $current_jobkind_id = $user['User']['current_jobkind_id']; $uped = false; } $this->log($uped, LOG_DEBUG); return array('level'=>$current_level, 'jobkind_id'=>$current_jobkind_id, 'uped'=>$uped, 'name'=>$name); } } <file_sep><div class="feeds view"> <h2><?php __('Feed');?></h2> <dl><?php $i = 0; $class = ' class="altrow"';?> <dt<?php if ($i % 2 == 0) echo $class;?>><?php __('Id'); ?></dt> <dd<?php if ($i++ % 2 == 0) echo $class;?>> <?php echo $feed['Feed']['id']; ?> &nbsp; </dd> <dt<?php if ($i % 2 == 0) echo $class;?>><?php __('User'); ?></dt> <dd<?php if ($i++ % 2 == 0) echo $class;?>> <?php echo $this->Html->link($feed['User']['id'], array('controller' => 'users', 'action' => 'view', $feed['User']['id'])); ?> &nbsp; </dd> <dt<?php if ($i % 2 == 0) echo $class;?>><?php __('Job'); ?></dt> <dd<?php if ($i++ % 2 == 0) echo $class;?>> <?php echo $this->Html->link($feed['Job']['name'], array('controller' => 'jobs', 'action' => 'view', $feed['Job']['id'])); ?> &nbsp; </dd> <dt<?php if ($i % 2 == 0) echo $class;?>><?php __('Message'); ?></dt> <dd<?php if ($i++ % 2 == 0) echo $class;?>> <?php echo $feed['Feed']['message']; ?> &nbsp; </dd> <dt<?php if ($i % 2 == 0) echo $class;?>><?php __('Created'); ?></dt> <dd<?php if ($i++ % 2 == 0) echo $class;?>> <?php echo $feed['Feed']['created']; ?> &nbsp; </dd> <dt<?php if ($i % 2 == 0) echo $class;?>><?php __('Modified'); ?></dt> <dd<?php if ($i++ % 2 == 0) echo $class;?>> <?php echo $feed['Feed']['modified']; ?> &nbsp; </dd> </dl> </div> <div class="actions"> <h3><?php __('Actions'); ?></h3> <ul> <li><?php echo $this->Html->link(__('Edit Feed', true), array('action' => 'edit', $feed['Feed']['id'])); ?> </li> <li><?php echo $this->Html->link(__('Delete Feed', true), array('action' => 'delete', $feed['Feed']['id']), null, sprintf(__('Are you sure you want to delete # %s?', true), $feed['Feed']['id'])); ?> </li> <li><?php echo $this->Html->link(__('List Feeds', true), array('action' => 'index')); ?> </li> <li><?php echo $this->Html->link(__('New Feed', true), array('action' => 'add')); ?> </li> <li><?php echo $this->Html->link(__('List Users', true), array('controller' => 'users', 'action' => 'index')); ?> </li> <li><?php echo $this->Html->link(__('New User', true), array('controller' => 'users', 'action' => 'add')); ?> </li> <li><?php echo $this->Html->link(__('List Jobs', true), array('controller' => 'jobs', 'action' => 'index')); ?> </li> <li><?php echo $this->Html->link(__('New Job', true), array('controller' => 'jobs', 'action' => 'add')); ?> </li> <li><?php echo $this->Html->link(__('List Likes', true), array('controller' => 'likes', 'action' => 'index')); ?> </li> <li><?php echo $this->Html->link(__('New Like', true), array('controller' => 'likes', 'action' => 'add')); ?> </li> </ul> </div> <div class="related"> <h3><?php __('Related Likes');?></h3> <?php if (!empty($feed['Like'])):?> <table cellpadding = "0" cellspacing = "0"> <tr> <th><?php __('Id'); ?></th> <th><?php __('User Id'); ?></th> <th><?php __('Friend Id'); ?></th> <th><?php __('Job Id'); ?></th> <th><?php __('Jobkind Id'); ?></th> <th><?php __('Feed Id'); ?></th> <th><?php __('Point'); ?></th> <th><?php __('Message'); ?></th> <th><?php __('From'); ?></th> <th><?php __('Created'); ?></th> <th><?php __('Modified'); ?></th> <th class="actions"><?php __('Actions');?></th> </tr> <?php $i = 0; foreach ($feed['Like'] as $like): $class = null; if ($i++ % 2 == 0) { $class = ' class="altrow"'; } ?> <tr<?php echo $class;?>> <td><?php echo $like['id'];?></td> <td><?php echo $like['user_id'];?></td> <td><?php echo $like['friend_id'];?></td> <td><?php echo $like['job_id'];?></td> <td><?php echo $like['jobkind_id'];?></td> <td><?php echo $like['feed_id'];?></td> <td><?php echo $like['point'];?></td> <td><?php echo $like['message'];?></td> <td><?php echo $like['from'];?></td> <td><?php echo $like['created'];?></td> <td><?php echo $like['modified'];?></td> <td class="actions"> <?php echo $this->Html->link(__('View', true), array('controller' => 'likes', 'action' => 'view', $like['id'])); ?> <?php echo $this->Html->link(__('Edit', true), array('controller' => 'likes', 'action' => 'edit', $like['id'])); ?> <?php echo $this->Html->link(__('Delete', true), array('controller' => 'likes', 'action' => 'delete', $like['id']), null, sprintf(__('Are you sure you want to delete # %s?', true), $like['id'])); ?> </td> </tr> <?php endforeach; ?> </table> <?php endif; ?> <div class="actions"> <ul> <li><?php echo $this->Html->link(__('New Like', true), array('controller' => 'likes', 'action' => 'add'));?> </li> </ul> </div> </div> <file_sep><?php echo $this->Javascript->link('global', false);?> <?php echo $this->Javascript->link('cal_ui', false);?> <?php echo $this->Javascript->link('ui.timeSelector');?> <?php echo $this->Javascript->link('resistration');?> <?php echo $this->Html->css('tmp', 'stylesheet', array('inline'=>false)); ?> <div id="registration_edit"> <?php //echo $this->Form->create('Job', array('onSubmit'=>'Biteup.checkResist(); return false;'));?> <?php echo $this->Form->create('Job', array('onSubmit'=>'Biteup.checkResist();'));?> <?php echo $this->Form->input('id'); ?> <div class="woodFrame registFrame"> <h1><?php echo $this->Html->image('regist_title_select.png', array('alt'=>'バイト先を選ぶ', 'width'=>298, 'height'=>54)); ?></h1> <div class="woodWrapper"> <dl> <dt id="newEver">バイト先を編集する</dt> <dd><?php echo $this->Form->input('name', array('type'=>'text', 'div'=>false, 'label'=>false, 'placeholder'=>'新しいバイト先をいれてぽ', 'class'=>'newRegist')); ?></dd> <dt>バイト先のジャンルを選ぶ</dt> <dd> <?php echo $this->Form->input('jobkind_id', array('label'=>False, 'div'=>False, 'class'=>'selectWorks')); ?> </dd> </dl> </div> </div> <div class="woodFrame registFrame"> <h1><?php echo $this->Html->image('regist_title_date.png', array('alt'=>'日時を入れてぽ', 'width'=>298, 'height'=>54)); ?></h1> <?php // Job.startdate.year 等で日付値が正常に反映されないのでHTMLを直接書く ?> <input type="hidden" id="JobStartdateYear" name="data[Job][startdate][year]" value="<?php echo date('Y', strtotime($this->data['Job']['startdate'])); ?>"> <input type="hidden" id="JobStartdateMonth" name="data[Job][startdate][month]" value="<?php echo date('n', strtotime($this->data['Job']['startdate'])); ?>"> <input type="hidden" id="JobStartdateDay" name="data[Job][startdate][day]" value="<?php echo date('j', strtotime($this->data['Job']['startdate'])); ?>"> <input type="hidden" id="hdnStartHour" name="data[Job][starttime][hour]" value="<?php echo date('G', strtotime($this->data['Job']['starttime'])); ?>"> <input type="hidden" id="hdnStartMinute" name="data[Job][starttime][min]" value="<?php echo date('i', strtotime($this->data['Job']['starttime'])); ?>"> <input type="hidden" id="hdnEndHour" name="data[Job][jobtime][hour]" value="<?php echo date('G', strtotime($this->data['Job']['jobtime'])); ?>"> <input type="hidden" id="hdnEndMinute" name="data[Job][jobtime][min]" value="<?php echo date('i', strtotime($this->data['Job']['jobtime'])); ?>"> <div class="woodWrapper"> <dl> <dt>カレンダーから日付を選ぶ</dt> <dd id="biteCalCall" class="calender"> <?php if(!empty($this->data['Job']['startdate'])) { echo date('Y年n月j日', strtotime($this->data['Job']['startdate'])); } else { echo 'タップしてぽ!'; } ?> </dd> <dd id="biteCalendar"></dd> <dt>バイトの開始時刻と時間を選ぶ</dt> <dd> <div id="startTime" data-hour="hdnStartHour" data-minute="hdnStartMinute" class="time start"> <em><?php echo date('H', strtotime($this->data['Job']['starttime'])); ?></em> <em><?php echo date('i', strtotime($this->data['Job']['starttime'])); ?></em> </div>から <div id="timeFrame1"></div> <div id="endTime" data-hour="hdnEndHour" data-minute="hdnEndMinute" class="time while"> <em><?php echo date('H', strtotime($this->data['Job']['jobtime'])); ?></em>時間 <em><?php echo date('i', strtotime($this->data['Job']['jobtime'])); ?></em>分</div> <div id="timeFrame2"></div> </dd> </dl> </div> </div> <p class="alC"><?php echo $this->Form->submit('btn_bite_edit.png', array('alt'=>"変更する", 'width'=>"233", 'height'=>"57", 'div'=>false, 'label'=>false)); ?></p> <p class="alC delete"><?php echo $this->Html->link($this->Html->image('btn_bite_delete.png', array('alt'=>'この予定を削除する', 'width'=>'200', 'height'=>'38')), array('action'=>'delete', $this->Form->value('Job.id')), array('escape'=>false), __('Are you sure you want to delete ?', true)); ?></p> </form> </div><!-- /#registration --> <file_sep><?php class TimelineComponent extends Object { var $_controller; function startup(& $controller) { $this->_controller = $controller; } // タイムラインの情報取得。 function getTimeline($user_id) { $friends = $this->_controller->Friend->find('all', array('conditions'=> array('user_id'=>$user_id))); $feed_id = ''; foreach ($friends as $val) { $feed_id .= $val['Friend']['friend_id'].','; } $feed_id = $feed_id.$user_id; $feeds = $this->_controller->Feed->find('all', array('order' => 'Feed.created DESC','conditions'=> array("Feed.user_id IN ($feed_id)"))); $timeline = array(); foreach($feeds as $feed){ $timeline[$feed['Feed']['id']]['name'] = $feed['User']['username']; $comment_cnt = 0; foreach ($feed['Like'] as $like) { if ($like['message']!='') $comment_cnt++; } $timeline[$feed['Feed']['id']]['like_count'] = count($feed['Like']); $timeline[$feed['Feed']['id']]['comment_count'] = $comment_cnt; $timeline[$feed['Feed']['id']]['time'] = $this->getActionTime($feed['Feed']['created']); } return $timeline; } // 〜分前の投稿 function getActionTime($time){ $action = time()-strtotime(date($time)); if ($action < 60) { $pattern = '今'; } elseif (60 <= $action && $action < 180) { $pattern = '1分前'; } elseif (180 <= $action && $action < 300) { $pattern = '3分前'; } elseif (200 <= $action && $action < 600) { $pattern = '5分前'; } elseif (600 <= $action && $action < 900) { $pattern = '10分前'; } elseif (900 <= $action && $action < 1200) { $pattern = '15分前'; } elseif (1200 <= $action && $action < 1800) { $pattern = '20分前'; } elseif (1800 <= $action && $action < 2700) { $pattern = '30分前'; } elseif (2700 <= $action && $action < 3600) { $pattern = '45分前'; } elseif (3600 <= $action && $action < 7200) { $pattern = '1時間前'; } elseif (7200 <= $action && $action < 10800) { $pattern = '2時間前'; } elseif (10800 <= $action && $action < 18000) { $pattern = '3時間前'; } elseif (18000 <= $action && $action < 25200) { $pattern = '5時間前'; } elseif (25200 <= $action && $action < 36000) { $pattern = '7時間前'; } elseif (36000 <= $action && $action < 54000) { $pattern = '10時間前'; } elseif (54000 <= $action && $action < 72000) { $pattern = '15時間前'; } elseif (72000 <= $action && $action < 86400) { $pattern = '20時間前'; } elseif (86400 <= $action && $action < 172800) { $pattern = '1日前'; } elseif (172800 <= $action && $action < 259200) { $pattern = '2日前'; } elseif (259200 <= $action && $action < 604800) { $pattern = '3日前'; } elseif (604800 <= $action && $action < 1209600) { $pattern = '1週間前'; } elseif (1209600 <= $action && $action < 2592000) { $pattern = '2週間前'; } elseif (2592000 <= $action && $action < 7776000) { $pattern = '1ヶ月前'; } elseif (7776000 <= $action && $action < 15552000) { $pattern = '3ヶ月前'; } elseif (15552000 <= $action && $action < 31104000) { $pattern = '半年前'; } else { $pattern = '1年以上前'; } return $pattern; } } <file_sep><?php echo $this->Javascript->link('global', false);?> <?php echo $this->Javascript->link('charactor', false);?> <?php echo $this->Javascript->link('sync', false);?> <script> $(function (){ Sync.once( 9, function (res){ var total = res.totalPoint; var level = res.level; var jobKind = res.jobkind; //もしかしたら要らないかも、、、 //console.log(total); }); }); </script> <?php echo $this->Html->css('tmp', 'stylesheet', array('inline'=>false)); ?> <div class="profile"> <h1><?php echo $friend['User']['username'] ?></h1> <p class="profileAvatar"><!--<img src="img/dummy/dummy_profile.jpg" alt width="320" height="175">--> <script> var s = Charactor.getImage("free", 2); document.write(s); </script> </p> <div class="profileBg"> <div class="profileDetail"> <div class="profileLevel"> <h2><?php echo $level['Level']['name']; ?><span><?php echo $jobkind['Jobkind']['name'] ?></span></h2> <p class="level"><?php echo $friend['User']['current_level'] ?></p> </div> <ul class="profileCount"> <li class="otsukare"><?php echo $likecnt; ?></li> <li class="checkout"><?php echo $checkoutcnt; ?></li> </ul> </div><!-- /.profileDetail --> <!-- 未実装 <div class="pointGage"> <p class="meter"><span></span></p> <div class="gage"> <p class="text">LEVEL9まであと<strong>4015pt</strong></p> <p class="point">19546 pt</p> </div> </div> --> </div><!-- /.profileBg --> </div><!-- /.profile --> <div class="followBtn"> <?php echo $this->Form->create('Friend', array('action'=>'view'.DS.$friend['User']['id'])); ?> <?php echo $this->Form->input('Friend.friend_id', array('type'=>'hidden', 'value'=>$friend['User']['id'])); ?></p> <?php if($followed) { ?> <?php echo $this->Form->input('Friend.action', array('type'=>'hidden', 'value'=>'unfollow')); ?></p> <p><small>あなたは<?php echo $friend['User']['username']; ?>さんをフォローしているぽ</small></p> <p><?php echo $this->Form->submit('btn_unfollow.png', array('alt'=>'アンフォロー', 'width'=>234, 'div'=>false)); ?></p> <?php } else { ?> <?php echo $this->Form->input('Friend.action', array('type'=>'hidden', 'value'=>'follow')); ?></p> <p><?php echo $this->Form->submit('btn_follow.png', array('alt'=>'フォローする', 'width'=>234, 'div'=>false)); ?></p> <?php } ?> </form> </div> <div id="timeline" class="woodFrame"> <div class="woodWrapper"> <?php if(!empty($feeds)) { // Friend Timeline Loop ?> <ul> <?php foreach($feeds as $feed) { ?> <li data-friend-jobkind="<?php echo $feed['User']['current_jobkind_id']; ?>" data-friend-level="<?php echo $feed['User']['current_level']; ?>" data-feed-id="<?php echo $feed['Feed']['id']; ?>"> <a href="<?php echo $this->webroot; ?>feeds/detail/<?php echo $feed['Feed']['id']; ?>"> <canvas width="80" height="80" class="avatarIcon"></canvas> <div class="activity"> <p class="comment"> <span><?php echo $feed['User']['username']; ?>さん</span> <?php echo $feed['Feed']['message']; ?> </p> <div class="footer"> <p class="icon"><span class="comment"><?php echo $feed['Like']['comments']; ?></span> <span class="otsu"><?php echo $feed['Like']['likes']; ?></span></p> <p class="times"><?php echo $feed['Feed']['created']; ?></p> </div> </div> </a> </li> <?php } ?> </ul> <?php } ?> <p id="moreFeed">もっと読む…<span><?php $this->Html->image('icon_otsukare_load.png', array('alt'=>'loading')); ?></span></p> </div> </div><!-- /#friendTimeline --> <file_sep><?php echo $this->Javascript->link('global', false);?> <?php echo $this->Javascript->link('cal_ui', false);?> <?php echo $this->Javascript->link('ui.timeSelector');?> <?php echo $this->Javascript->link('resistration');?> <?php echo $this->Html->css('tmp', 'stylesheet', array('inline'=>false)); ?> <div id="registration"> <?php //echo $this->Form->create('Job', array('onSubmit'=>'Biteup.checkResist(); return false;'));?> <?php echo $this->Form->create('Job', array('onSubmit'=>'Biteup.checkResist();'));?> <div class="woodFrame registFrame"> <h1><?php echo $this->Html->image('regist_title_select.png', array('alt'=>'バイト先を選ぶ', 'width'=>298, 'height'=>54)); ?></h1> <div class="woodWrapper"> <dl> <dt id="haveEver">今までのバイト先から選ぶ</dt> <dd> <?php echo $this->Form->input('job_selected', array('type'=>'select', 'options'=>array_unique($jobs), 'class'=>'selectWorks', 'label'=>false, 'div'=>false, 'id'=>'company')); ?> </dd> <dt id="newEver">新しいバイト先を追加する</dt> <dd style="display: none;"><?php echo $this->Form->input('name', array('type'=>'text', 'div'=>false, 'label'=>false, 'placeholder'=>'新しいバイト先をいれてぽ', 'class'=>'newRegist')); ?></dd> <dt>バイト先のジャンルを選ぶ</dt> <dd> <?php echo $this->Form->input('jobkind_id', array('label'=>False, 'div'=>False, 'class'=>'selectWorks')); ?> </dd> </dl> </div> </div> <div class="woodFrame registFrame"> <h1><?php echo $this->Html->image('regist_title_date.png', array('alt'=>'日時を入れてぽ', 'width'=>298, 'height'=>54)); ?></h1> <?php echo $this->Form->input('Job.startdate.year', array('type'=>'hidden')); ?> <?php echo $this->Form->input('Job.startdate.month', array('type'=>'hidden')); ?> <?php echo $this->Form->input('Job.startdate.day', array('type'=>'hidden')); ?> <?php echo $this->Form->input('Job.starttime.hour', array('type'=>'hidden', 'id'=>'hdnStartHour')); ?> <?php echo $this->Form->input('Job.starttime.min', array('type'=>'hidden', 'id'=>'hdnStartMinute')); ?> <?php echo $this->Form->input('Job.jobtime.hour', array('type'=>'hidden', 'id'=>'hdnEndHour')); ?> <?php echo $this->Form->input('Job.jobtime.min', array('type'=>'hidden', 'id'=>'hdnEndMinute')); ?> <?php //echo $this->Form->input('startdate', array('type'=>'date', 'dateFormat'=>'YMD', 'monthNames'=>False, 'label'=>False)); ?> <?php //echo $this->Form->input('starttime', array('type'=>'time', 'timeFormat'=>'24', 'label'=>False)); ?> <?php //echo $this->Form->input('jobtime', array('type'=>'time', 'timeFormat'=>'24', 'label'=>False)); ?> <div class="woodWrapper"> <dl> <dt>カレンダーから日付を選ぶ</dt> <dd id="biteCalCall" class="calender">タップしてぽ!</dd> <dd id="biteCalendar"></dd> <dt>バイトの開始時刻と時間を選ぶ</dt> <dd> <div id="startTime" data-hour="hdnStartHour" data-minute="hdnStartMinute" class="time start"><em></em><em></em></div>から <div id="timeFrame1"></div> <div id="endTime" data-hour="hdnEndHour" data-minute="hdnEndMinute" class="time while"><em></em>時間<em></em>分</div> <div id="timeFrame2"></div> </dd> </dl> </div> </div> <p class="alC"><?php echo $this->Form->submit('regist_btn.png', array('alt'=>"予定を登録する", 'width'=>"233", 'height'=>"57", 'div'=>false, 'label'=>false)); ?></p> <!-- 勤務時間は#biteCalendar em:first-childに文字列が入っているかで判断 --><!-- 職種はname = jobに設定 --> </form> </div><!-- /#registration --> <file_sep><div class="jobs view"> <h2><?php __('Job');?></h2> <dl><?php $i = 0; $class = ' class="altrow"';?> <dt<?php if ($i % 2 == 0) echo $class;?>><?php __('Id'); ?></dt> <dd<?php if ($i++ % 2 == 0) echo $class;?>> <?php echo $job['Job']['id']; ?> &nbsp; </dd> <dt<?php if ($i % 2 == 0) echo $class;?>><?php __('User'); ?></dt> <dd<?php if ($i++ % 2 == 0) echo $class;?>> <?php echo $this->Html->link($job['User']['id'], array('controller' => 'users', 'action' => 'view', $job['User']['id'])); ?> &nbsp; </dd> <dt<?php if ($i % 2 == 0) echo $class;?>><?php __('Name'); ?></dt> <dd<?php if ($i++ % 2 == 0) echo $class;?>> <?php echo $job['Job']['name']; ?> &nbsp; </dd> <dt<?php if ($i % 2 == 0) echo $class;?>><?php __('Startdate'); ?></dt> <dd<?php if ($i++ % 2 == 0) echo $class;?>> <?php echo $job['Job']['startdate']; ?> &nbsp; </dd> <dt<?php if ($i % 2 == 0) echo $class;?>><?php __('Starttime'); ?></dt> <dd<?php if ($i++ % 2 == 0) echo $class;?>> <?php echo $job['Job']['starttime']; ?> &nbsp; </dd> <dt<?php if ($i % 2 == 0) echo $class;?>><?php __('Jobtime'); ?></dt> <dd<?php if ($i++ % 2 == 0) echo $class;?>> <?php echo $job['Job']['jobtime']; ?> &nbsp; </dd> <dt<?php if ($i % 2 == 0) echo $class;?>><?php __('Jobkind'); ?></dt> <dd<?php if ($i++ % 2 == 0) echo $class;?>> <?php echo $this->Html->link($job['Jobkind']['name'], array('controller' => 'jobkinds', 'action' => 'view', $job['Jobkind']['id'])); ?> &nbsp; </dd> <dt<?php if ($i % 2 == 0) echo $class;?>><?php __('Checkin'); ?></dt> <dd<?php if ($i++ % 2 == 0) echo $class;?>> <?php echo $job['Job']['checkin']; ?> &nbsp; </dd> <dt<?php if ($i % 2 == 0) echo $class;?>><?php __('Created'); ?></dt> <dd<?php if ($i++ % 2 == 0) echo $class;?>> <?php echo $job['Job']['created']; ?> &nbsp; </dd> <dt<?php if ($i % 2 == 0) echo $class;?>><?php __('Modified'); ?></dt> <dd<?php if ($i++ % 2 == 0) echo $class;?>> <?php echo $job['Job']['modified']; ?> &nbsp; </dd> </dl> </div> <div class="actions"> <h3><?php __('Actions'); ?></h3> <ul> <li><?php echo $this->Html->link(__('Edit Job', true), array('action' => 'edit', $job['Job']['id'])); ?> </li> <li><?php echo $this->Html->link(__('Delete Job', true), array('action' => 'delete', $job['Job']['id']), null, sprintf(__('Are you sure you want to delete # %s?', true), $job['Job']['id'])); ?> </li> <li><?php echo $this->Html->link(__('List Jobs', true), array('action' => 'index')); ?> </li> <li><?php echo $this->Html->link(__('New Job', true), array('action' => 'add')); ?> </li> <li><?php echo $this->Html->link(__('List Users', true), array('controller' => 'users', 'action' => 'index')); ?> </li> <li><?php echo $this->Html->link(__('New User', true), array('controller' => 'users', 'action' => 'add')); ?> </li> <li><?php echo $this->Html->link(__('List Jobkinds', true), array('controller' => 'jobkinds', 'action' => 'index')); ?> </li> <li><?php echo $this->Html->link(__('New Jobkind', true), array('controller' => 'jobkinds', 'action' => 'add')); ?> </li> <li><?php echo $this->Html->link(__('List Feeds', true), array('controller' => 'feeds', 'action' => 'index')); ?> </li> <li><?php echo $this->Html->link(__('New Feed', true), array('controller' => 'feeds', 'action' => 'add')); ?> </li> <li><?php echo $this->Html->link(__('List Likes', true), array('controller' => 'likes', 'action' => 'index')); ?> </li> <li><?php echo $this->Html->link(__('New Like', true), array('controller' => 'likes', 'action' => 'add')); ?> </li> </ul> </div> <div class="related"> <h3><?php __('Related Feeds');?></h3> <?php if (!empty($job['Feed'])):?> <table cellpadding = "0" cellspacing = "0"> <tr> <th><?php __('Id'); ?></th> <th><?php __('User Id'); ?></th> <th><?php __('Job Id'); ?></th> <th><?php __('Message'); ?></th> <th><?php __('Created'); ?></th> <th><?php __('Modified'); ?></th> <th class="actions"><?php __('Actions');?></th> </tr> <?php $i = 0; foreach ($job['Feed'] as $feed): $class = null; if ($i++ % 2 == 0) { $class = ' class="altrow"'; } ?> <tr<?php echo $class;?>> <td><?php echo $feed['id'];?></td> <td><?php echo $feed['user_id'];?></td> <td><?php echo $feed['job_id'];?></td> <td><?php echo $feed['message'];?></td> <td><?php echo $feed['created'];?></td> <td><?php echo $feed['modified'];?></td> <td class="actions"> <?php echo $this->Html->link(__('View', true), array('controller' => 'feeds', 'action' => 'view', $feed['id'])); ?> <?php echo $this->Html->link(__('Edit', true), array('controller' => 'feeds', 'action' => 'edit', $feed['id'])); ?> <?php echo $this->Html->link(__('Delete', true), array('controller' => 'feeds', 'action' => 'delete', $feed['id']), null, sprintf(__('Are you sure you want to delete # %s?', true), $feed['id'])); ?> </td> </tr> <?php endforeach; ?> </table> <?php endif; ?> <div class="actions"> <ul> <li><?php echo $this->Html->link(__('New Feed', true), array('controller' => 'feeds', 'action' => 'add'));?> </li> </ul> </div> </div> <div class="related"> <h3><?php __('Related Likes');?></h3> <?php if (!empty($job['Like'])):?> <table cellpadding = "0" cellspacing = "0"> <tr> <th><?php __('Id'); ?></th> <th><?php __('User Id'); ?></th> <th><?php __('Friend Id'); ?></th> <th><?php __('Job Id'); ?></th> <th><?php __('Jobkind Id'); ?></th> <th><?php __('Feed Id'); ?></th> <th><?php __('Point'); ?></th> <th><?php __('Message'); ?></th> <th><?php __('From'); ?></th> <th><?php __('Created'); ?></th> <th><?php __('Modified'); ?></th> <th class="actions"><?php __('Actions');?></th> </tr> <?php $i = 0; foreach ($job['Like'] as $like): $class = null; if ($i++ % 2 == 0) { $class = ' class="altrow"'; } ?> <tr<?php echo $class;?>> <td><?php echo $like['id'];?></td> <td><?php echo $like['user_id'];?></td> <td><?php echo $like['friend_id'];?></td> <td><?php echo $like['job_id'];?></td> <td><?php echo $like['jobkind_id'];?></td> <td><?php echo $like['feed_id'];?></td> <td><?php echo $like['point'];?></td> <td><?php echo $like['message'];?></td> <td><?php echo $like['from'];?></td> <td><?php echo $like['created'];?></td> <td><?php echo $like['modified'];?></td> <td class="actions"> <?php echo $this->Html->link(__('View', true), array('controller' => 'likes', 'action' => 'view', $like['id'])); ?> <?php echo $this->Html->link(__('Edit', true), array('controller' => 'likes', 'action' => 'edit', $like['id'])); ?> <?php echo $this->Html->link(__('Delete', true), array('controller' => 'likes', 'action' => 'delete', $like['id']), null, sprintf(__('Are you sure you want to delete # %s?', true), $like['id'])); ?> </td> </tr> <?php endforeach; ?> </table> <?php endif; ?> <div class="actions"> <ul> <li><?php echo $this->Html->link(__('New Like', true), array('controller' => 'likes', 'action' => 'add'));?> </li> </ul> </div> </div> <file_sep><?php $res = '{ "level": 2, "jobkind": "power" }'; $res = true; print( $res ); ?><file_sep><?php echo $this->Javascript->link('global', false);?> <?php echo $this->Javascript->link('cal_ui', false);?> <script> window.onload = function (){ var ev = "touchstart"; //touchstart $("#biteCalCall").bind(ev, showCalendar); function showCalendar(){ $("#biteCalCall").unbind(ev); var cal = new dhCalUI("biteCalCall","biteCalendar"); $(cal).bind("complete", function (e){ $("#biteCalCall").bind(ev, showCalendar); }); }; } </script> <?php echo $this->Html->css('tmp', 'stylesheet', array('inline'=>false)); ?> <div id="registration_edit"> <?php echo $this->Form->create('Job');?> <div class="woodFrame registFrame"> <h1><?php echo $this->Html->image('regist_title_select.png', array('alt'=>'バイト先を選ぶ', 'width'=>298, 'height'=>54)); ?></h1> <div class="woodWrapper"> <dl> <dt>今までのバイト先から選ぶ</dt> <dd> <select name="company" class="selectWorks"> <option value="-">▼えらんでぽ</option> <option value="ヨドバシカメラ">ヨドバシカメラ</option> <option value="ビックカメラ">ビックカメラ</option> </select> </dd> <dt>新しいバイト先を追加する</dt> <dd><?php echo $this->Form->input('name', array('type'=>'text', 'div'=>false, 'label'=>false, 'placeholder'=>'新しいバイト先をいれてぽ', 'class'=>'newRegist')); ?></dd> <dd><input type="text" placeholder="新しいバイト先を入れてぽ" class="newRegist"></dd> <dt>バイト先のジャンルを選ぶ</dt> <dd> <select name="job" class="selectWorks"> <option value="-">▼ジャンルをえらんでぽ</option> <option value="力仕事・労働">力仕事・労働</option> <option value="オフィスワーク">オフィスワーク</option> </select> </dd> </dl> </div> </div> <div class="woodFrame registFrame"> <h1><img src="img/regist_title_date.png" alt="日時を入れてぽ" width="298" height="54"></h1> <div class="woodWrapper"> <dl> <dt>カレンダーから日付を選ぶ</dt> <dd id="biteCalCall" class="calender">2月10日</dd> <dd id="biteCalendar"></dd> <dt>バイトの開始時刻と時間を選ぶ</dt> <dd> <div class="time start"><em>10</em><em>00</em></div>から <div class="time while"><em>5</em>時間<em>00</em>分</div> </dd> </dl> </div> </div> <p class="alC"><a href="#"><img src="img/btn_edit.png" alt="編集する" width="206" height="60"></a></p> <p class="alC"><a href="#"><img src="img/btn_deletebite.png" alt="予定を削除する" width="144" height="33"></a></p> </form> </div><!-- /#registration --> <div class="jobs view"> <h2><?php __('Job');?></h2> <dl><?php $i = 0; $class = ' class="altrow"';?> <dt<?php if ($i % 2 == 0) echo $class;?>><?php __('Id'); ?></dt> <dd<?php if ($i++ % 2 == 0) echo $class;?>> <?php echo $job['Job']['id']; ?> &nbsp; </dd> <dt<?php if ($i % 2 == 0) echo $class;?>><?php __('User'); ?></dt> <dd<?php if ($i++ % 2 == 0) echo $class;?>> <?php echo $this->Html->link($job['User']['id'], array('controller' => 'users', 'action' => 'view', $job['User']['id'])); ?> &nbsp; </dd> <dt<?php if ($i % 2 == 0) echo $class;?>><?php __('Name'); ?></dt> <dd<?php if ($i++ % 2 == 0) echo $class;?>> <?php echo $job['Job']['name']; ?> &nbsp; </dd> <dt<?php if ($i % 2 == 0) echo $class;?>><?php __('Startdate'); ?></dt> <dd<?php if ($i++ % 2 == 0) echo $class;?>> <?php echo $job['Job']['startdate']; ?> &nbsp; </dd> <dt<?php if ($i % 2 == 0) echo $class;?>><?php __('Starttime'); ?></dt> <dd<?php if ($i++ % 2 == 0) echo $class;?>> <?php echo $job['Job']['starttime']; ?> &nbsp; </dd> <dt<?php if ($i % 2 == 0) echo $class;?>><?php __('Jobtime'); ?></dt> <dd<?php if ($i++ % 2 == 0) echo $class;?>> <?php echo $job['Job']['jobtime']; ?> &nbsp; </dd> <dt<?php if ($i % 2 == 0) echo $class;?>><?php __('Jobkind'); ?></dt> <dd<?php if ($i++ % 2 == 0) echo $class;?>> <?php echo $this->Html->link($job['Jobkind']['name'], array('controller' => 'jobkinds', 'action' => 'view', $job['Jobkind']['id'])); ?> &nbsp; </dd> <dt<?php if ($i % 2 == 0) echo $class;?>><?php __('Checkin'); ?></dt> <dd<?php if ($i++ % 2 == 0) echo $class;?>> <?php echo $job['Job']['checkin']; ?> &nbsp; </dd> <dt<?php if ($i % 2 == 0) echo $class;?>><?php __('Created'); ?></dt> <dd<?php if ($i++ % 2 == 0) echo $class;?>> <?php echo $job['Job']['created']; ?> &nbsp; </dd> <dt<?php if ($i % 2 == 0) echo $class;?>><?php __('Modified'); ?></dt> <dd<?php if ($i++ % 2 == 0) echo $class;?>> <?php echo $job['Job']['modified']; ?> &nbsp; </dd> </dl> </div> <div class="actions"> <h3><?php __('Actions'); ?></h3> <ul> <li><?php echo $this->Html->link(__('Edit Job', true), array('action' => 'edit', $job['Job']['id'])); ?> </li> <li><?php echo $this->Html->link(__('Delete Job', true), array('action' => 'delete', $job['Job']['id']), null, sprintf(__('Are you sure you want to delete # %s?', true), $job['Job']['id'])); ?> </li> <li><?php echo $this->Html->link(__('List Jobs', true), array('action' => 'index')); ?> </li> <li><?php echo $this->Html->link(__('New Job', true), array('action' => 'add')); ?> </li> <li><?php echo $this->Html->link(__('List Users', true), array('controller' => 'users', 'action' => 'index')); ?> </li> <li><?php echo $this->Html->link(__('New User', true), array('controller' => 'users', 'action' => 'add')); ?> </li> <li><?php echo $this->Html->link(__('List Jobkinds', true), array('controller' => 'jobkinds', 'action' => 'index')); ?> </li> <li><?php echo $this->Html->link(__('New Jobkind', true), array('controller' => 'jobkinds', 'action' => 'add')); ?> </li> <li><?php echo $this->Html->link(__('List Feeds', true), array('controller' => 'feeds', 'action' => 'index')); ?> </li> <li><?php echo $this->Html->link(__('New Feed', true), array('controller' => 'feeds', 'action' => 'add')); ?> </li> <li><?php echo $this->Html->link(__('List Likes', true), array('controller' => 'likes', 'action' => 'index')); ?> </li> <li><?php echo $this->Html->link(__('New Like', true), array('controller' => 'likes', 'action' => 'add')); ?> </li> </ul> </div> <div class="related"> <h3><?php __('Related Feeds');?></h3> <?php if (!empty($job['Feed'])):?> <table cellpadding = "0" cellspacing = "0"> <tr> <th><?php __('Id'); ?></th> <th><?php __('User Id'); ?></th> <th><?php __('Job Id'); ?></th> <th><?php __('Message'); ?></th> <th><?php __('Created'); ?></th> <th><?php __('Modified'); ?></th> <th class="actions"><?php __('Actions');?></th> </tr> <?php $i = 0; foreach ($job['Feed'] as $feed): $class = null; if ($i++ % 2 == 0) { $class = ' class="altrow"'; } ?> <tr<?php echo $class;?>> <td><?php echo $feed['id'];?></td> <td><?php echo $feed['user_id'];?></td> <td><?php echo $feed['job_id'];?></td> <td><?php echo $feed['message'];?></td> <td><?php echo $feed['created'];?></td> <td><?php echo $feed['modified'];?></td> <td class="actions"> <?php echo $this->Html->link(__('View', true), array('controller' => 'feeds', 'action' => 'view', $feed['id'])); ?> <?php echo $this->Html->link(__('Edit', true), array('controller' => 'feeds', 'action' => 'edit', $feed['id'])); ?> <?php echo $this->Html->link(__('Delete', true), array('controller' => 'feeds', 'action' => 'delete', $feed['id']), null, sprintf(__('Are you sure you want to delete # %s?', true), $feed['id'])); ?> </td> </tr> <?php endforeach; ?> </table> <?php endif; ?> <div class="actions"> <ul> <li><?php echo $this->Html->link(__('New Feed', true), array('controller' => 'feeds', 'action' => 'add'));?> </li> </ul> </div> </div> <div class="related"> <h3><?php __('Related Likes');?></h3> <?php if (!empty($job['Like'])):?> <table cellpadding = "0" cellspacing = "0"> <tr> <th><?php __('Id'); ?></th> <th><?php __('User Id'); ?></th> <th><?php __('Friend Id'); ?></th> <th><?php __('Job Id'); ?></th> <th><?php __('Jobkind Id'); ?></th> <th><?php __('Feed Id'); ?></th> <th><?php __('Point'); ?></th> <th><?php __('Message'); ?></th> <th><?php __('From'); ?></th> <th><?php __('Created'); ?></th> <th><?php __('Modified'); ?></th> <th class="actions"><?php __('Actions');?></th> </tr> <?php $i = 0; foreach ($job['Like'] as $like): $class = null; if ($i++ % 2 == 0) { $class = ' class="altrow"'; } ?> <tr<?php echo $class;?>> <td><?php echo $like['id'];?></td> <td><?php echo $like['user_id'];?></td> <td><?php echo $like['friend_id'];?></td> <td><?php echo $like['job_id'];?></td> <td><?php echo $like['jobkind_id'];?></td> <td><?php echo $like['feed_id'];?></td> <td><?php echo $like['point'];?></td> <td><?php echo $like['message'];?></td> <td><?php echo $like['from'];?></td> <td><?php echo $like['created'];?></td> <td><?php echo $like['modified'];?></td> <td class="actions"> <?php echo $this->Html->link(__('View', true), array('controller' => 'likes', 'action' => 'view', $like['id'])); ?> <?php echo $this->Html->link(__('Edit', true), array('controller' => 'likes', 'action' => 'edit', $like['id'])); ?> <?php echo $this->Html->link(__('Delete', true), array('controller' => 'likes', 'action' => 'delete', $like['id']), null, sprintf(__('Are you sure you want to delete # %s?', true), $like['id'])); ?> </td> </tr> <?php endforeach; ?> </table> <?php endif; ?> <div class="actions"> <ul> <li><?php echo $this->Html->link(__('New Like', true), array('controller' => 'likes', 'action' => 'add'));?> </li> </ul> </div> </div> <file_sep><?php class FeedsController extends AppController { var $name = 'Feeds'; var $helpers = array('Javascript'); var $components = array('Auth', 'WebApi', 'Timeline', 'LevelCalc', 'Facebook'); var $uses = array('Feed', 'Friend', 'Like', 'Job', 'Level'); function index() { $this->Feed->recursive = 0; $this->set('feeds', $this->paginate()); } function view($id = null) { if (!$id) { $this->Session->setFlash(__('Invalid feed', true)); $this->redirect(array('action' => 'index')); } $this->set('feed', $this->Feed->read(null, $id)); } function add() { if (!empty($this->data)) { $this->Feed->create(); if ($this->Feed->save($this->data)) { $this->Session->setFlash(__('The feed has been saved', true)); $this->redirect(array('action' => 'index')); } else { $this->Session->setFlash(__('The feed could not be saved. Please, try again.', true)); } } $users = $this->Feed->User->find('list'); $jobs = $this->Feed->Job->find('list'); $this->set(compact('users', 'jobs')); } function edit($id = null) { if (!$id && empty($this->data)) { $this->Session->setFlash(__('Invalid feed', true)); $this->redirect(array('action' => 'index')); } if (!empty($this->data)) { if ($this->Feed->save($this->data)) { $this->Session->setFlash(__('The feed has been saved', true)); $this->redirect(array('action' => 'index')); } else { $this->Session->setFlash(__('The feed could not be saved. Please, try again.', true)); } } if (empty($this->data)) { $this->data = $this->Feed->read(null, $id); } $users = $this->Feed->User->find('list'); $jobs = $this->Feed->Job->find('list'); $this->set(compact('users', 'jobs')); } function delete($id = null) { if (!$id) { $this->Session->setFlash(__('Invalid id for feed', true)); $this->redirect(array('action'=>'index')); } if ($this->Feed->delete($id)) { $this->Session->setFlash(__('Feed deleted', true)); $this->redirect(array('action'=>'index')); } $this->Session->setFlash(__('Feed was not deleted', true)); $this->redirect(array('action' => 'index')); } function admin_index() { $this->Feed->recursive = 0; $this->layout = 'admin'; $this->set('feeds', $this->paginate()); } function admin_view($id = null) { $this->layout = 'admin'; if (!$id) { $this->Session->setFlash(__('Invalid feed', true)); $this->redirect(array('action' => 'index')); } $this->set('feed', $this->Feed->read(null, $id)); } function admin_add() { $this->layout = 'admin'; if (!empty($this->data)) { $this->Feed->create(); if ($this->Feed->save($this->data)) { $this->Session->setFlash(__('The feed has been saved', true)); $this->redirect(array('action' => 'index')); } else { $this->Session->setFlash(__('The feed could not be saved. Please, try again.', true)); } } $users = $this->Feed->User->find('list'); $jobs = $this->Feed->Job->find('list'); $this->set(compact('users', 'jobs')); } function admin_edit($id = null) { $this->layout = 'admin'; if (!$id && empty($this->data)) { $this->Session->setFlash(__('Invalid feed', true)); $this->redirect(array('action' => 'index')); } if (!empty($this->data)) { if ($this->Feed->save($this->data)) { $this->Session->setFlash(__('The feed has been saved', true)); $this->redirect(array('action' => 'index')); } else { $this->Session->setFlash(__('The feed could not be saved. Please, try again.', true)); } } if (empty($this->data)) { $this->data = $this->Feed->read(null, $id); } $users = $this->Feed->User->find('list'); $jobs = $this->Feed->Job->find('list'); $this->set(compact('users', 'jobs')); } function admin_delete($id = null) { if (!$id) { $this->Session->setFlash(__('Invalid id for feed', true)); $this->redirect(array('action'=>'index')); } if ($this->Feed->delete($id)) { $this->Session->setFlash(__('Feed deleted', true)); $this->redirect(array('action'=>'index')); } $this->Session->setFlash(__('Feed was not deleted', true)); $this->redirect(array('action' => 'index')); } function timeline() { $id = $this->Auth->user('id'); if (!$id) { $this->Session->setFlash(__('Invalid feed', true)); $this->redirect(array('action' => 'index')); } //フレンドを抽出 $friends = $this->Friend->find('all', array('conditions'=> array('Friend.user_id'=>$this->Auth->user('id')))); if(!empty($friends)) { $arybuf = array(); foreach($friends as $friend) { array_push($arybuf, $friend['Friend']['friend_id']); } array_push($arybuf, $this->Auth->user('id')); $conditions = array('Feed.user_id IN ('.implode(',', $arybuf).')'); $order = array('Feed.created DESC'); $limit = 10; $feeds = $this->Feed->find('all', array('conditions'=>$conditions, 'order'=>$order, 'limit'=>$limit)); $timelines = array(); foreach($feeds as $feed) { $feed['Like']['likes'] = $this->Like->find('count', array('conditions'=>array('Like.feed_id'=>$feed['Feed']['id'], 'Like.user_id'=>$feed['Feed']['user_id']))); $feed['Like']['comments'] = $this->Like->find('count', array('conditions'=>array('Like.feed_id'=>$feed['Feed']['id'], 'Like.message IS NOT NULL', 'Like.user_id'=>$feed['Feed']['user_id']))); $feed['Feed']['created'] = $this->Timeline->getActionTime($feed['Feed']['created']); array_push($timelines, $feed); } $this->set('feeds', $timelines); } $this->set('title_for_action', 'マイサポーター'); /* $this->set('feeds', $this->paginate()); $timeline = $this->Timeline->getTimeline($id); $this->set(compact('timeline')); */ } function detail($feed_id) { if (!$feed_id) { $this->Session->setFlash(__('Invalid feed', true)); $this->redirect(array('action' => 'index')); } $detail = $this->Feed->read('', $feed_id); $detail['Feed']['action_time'] = $this->Timeline->getActionTime($detail['Feed']['created']); $jobs = $this->Job->read('', $detail['Feed']['job_id']); //最新の同業種のLikeを取得 $like = $this->Like->find('first', array('conditions'=> array("Like.jobkind_id" => $jobs['Job']['jobkind_id'], "Like.friend_id" => $this->Auth->user('id')), 'order'=>'Feed.id DESC')); $like_flg = $this->Like->find('first', array('conditions'=> array("Like.feed_id" => $detail['Feed']['id'], "Like.friend_id" => $this->Auth->user('id')))) ? false : true; //Feed.job_id==0の場合は汎用メッセージなので $like_flg = false if($detail['Feed']['job_id'] == 0) $like_flg = false; if (!empty($this->data)) { $data = array(); $data['Like']['user_id'] = $detail['Feed']['user_id']; $data['Like']['friend_id'] = $this->Auth->user('id'); $data['Like']['feed_id'] = $feed_id; $data['Like']['job_id'] = $detail['Feed']['job_id']; $data['Like']['message'] = $this->Auth->user('username').'さんがおつかれ!と言っています。'."\n"; if(!empty($this->data['Feed']['message'])) { $data['Like']['message'] .= $this->data['Feed']['message']; } $data['Like']['jobkind_id'] = $jobs['Job']['jobkind_id']; $data['Like']['point'] = 5; //オツカレポイント $data['Like']['current_point'] = strval(intval($like['Like']['current_point']) + intval($data['Like']['point'])); //現在の職業別ポイントを加算 $this->Like->save($data); $level_uped = $this->LevelCalc->setUserLevel($this->Auth->user('id'), $jobs['Job']['jobkind_id']); //ユーザーのカレントレベル等を変更 if($level_uped['uped']) { //レベルアップした $message = $level_uped['name'].' にレベルアップしました!'; $feed = array( 'user_id' => $this->Auth->user('id'), 'job_id' => 0, 'message' => $message, ); $this->Feed->create(); $this->Feed->save($feed); $this->Facebook->publish($this->Auth->user('id'), $message); } $like_flg = false; } $this->set('feeds', $this->paginate()); $likes = $this->Like->find('all', array('order' => 'Like.created DESC','conditions'=> array("Like.feed_id" => $feed_id))); foreach ($likes as $key => $val){ $likes[$key]['Like']['action_time'] = $this->Timeline->getActionTime($val['Like']['created']); } $this->set(compact('detail', 'likes', 'like_flg')); $this->set('title_for_action', $detail['User']['username'].'の詳細'); } } <file_sep><div class="jobkinds view"> <h2><?php __('Jobkind');?></h2> <dl><?php $i = 0; $class = ' class="altrow"';?> <dt<?php if ($i % 2 == 0) echo $class;?>><?php __('Id'); ?></dt> <dd<?php if ($i++ % 2 == 0) echo $class;?>> <?php echo $jobkind['Jobkind']['id']; ?> &nbsp; </dd> <dt<?php if ($i % 2 == 0) echo $class;?>><?php __('Name'); ?></dt> <dd<?php if ($i++ % 2 == 0) echo $class;?>> <?php echo $jobkind['Jobkind']['name']; ?> &nbsp; </dd> <dt<?php if ($i % 2 == 0) echo $class;?>><?php __('Created'); ?></dt> <dd<?php if ($i++ % 2 == 0) echo $class;?>> <?php echo $jobkind['Jobkind']['created']; ?> &nbsp; </dd> <dt<?php if ($i % 2 == 0) echo $class;?>><?php __('Modified'); ?></dt> <dd<?php if ($i++ % 2 == 0) echo $class;?>> <?php echo $jobkind['Jobkind']['modified']; ?> &nbsp; </dd> </dl> </div> <div class="actions"> <h3><?php __('Actions'); ?></h3> <ul> <li><?php echo $this->Html->link(__('Edit Jobkind', true), array('action' => 'edit', $jobkind['Jobkind']['id'])); ?> </li> <li><?php echo $this->Html->link(__('Delete Jobkind', true), array('action' => 'delete', $jobkind['Jobkind']['id']), null, sprintf(__('Are you sure you want to delete # %s?', true), $jobkind['Jobkind']['id'])); ?> </li> <li><?php echo $this->Html->link(__('List Jobkinds', true), array('action' => 'index')); ?> </li> <li><?php echo $this->Html->link(__('New Jobkind', true), array('action' => 'add')); ?> </li> <li><?php echo $this->Html->link(__('List Jobs', true), array('controller' => 'jobs', 'action' => 'index')); ?> </li> <li><?php echo $this->Html->link(__('New Job', true), array('controller' => 'jobs', 'action' => 'add')); ?> </li> <li><?php echo $this->Html->link(__('List Likes', true), array('controller' => 'likes', 'action' => 'index')); ?> </li> <li><?php echo $this->Html->link(__('New Like', true), array('controller' => 'likes', 'action' => 'add')); ?> </li> </ul> </div> <div class="related"> <h3><?php __('Related Jobs');?></h3> <?php if (!empty($jobkind['Job'])):?> <table cellpadding = "0" cellspacing = "0"> <tr> <th><?php __('Id'); ?></th> <th><?php __('User Id'); ?></th> <th><?php __('Name'); ?></th> <th><?php __('Startdate'); ?></th> <th><?php __('Starttime'); ?></th> <th><?php __('Jobtime'); ?></th> <th><?php __('Jobkind Id'); ?></th> <th><?php __('Checkin'); ?></th> <th><?php __('Created'); ?></th> <th><?php __('Modified'); ?></th> <th class="actions"><?php __('Actions');?></th> </tr> <?php $i = 0; foreach ($jobkind['Job'] as $job): $class = null; if ($i++ % 2 == 0) { $class = ' class="altrow"'; } ?> <tr<?php echo $class;?>> <td><?php echo $job['id'];?></td> <td><?php echo $job['user_id'];?></td> <td><?php echo $job['name'];?></td> <td><?php echo $job['startdate'];?></td> <td><?php echo $job['starttime'];?></td> <td><?php echo $job['jobtime'];?></td> <td><?php echo $job['jobkind_id'];?></td> <td><?php echo $job['checkin'];?></td> <td><?php echo $job['created'];?></td> <td><?php echo $job['modified'];?></td> <td class="actions"> <?php echo $this->Html->link(__('View', true), array('controller' => 'jobs', 'action' => 'view', $job['id'])); ?> <?php echo $this->Html->link(__('Edit', true), array('controller' => 'jobs', 'action' => 'edit', $job['id'])); ?> <?php echo $this->Html->link(__('Delete', true), array('controller' => 'jobs', 'action' => 'delete', $job['id']), null, sprintf(__('Are you sure you want to delete # %s?', true), $job['id'])); ?> </td> </tr> <?php endforeach; ?> </table> <?php endif; ?> <div class="actions"> <ul> <li><?php echo $this->Html->link(__('New Job', true), array('controller' => 'jobs', 'action' => 'add'));?> </li> </ul> </div> </div> <div class="related"> <h3><?php __('Related Likes');?></h3> <?php if (!empty($jobkind['Like'])):?> <table cellpadding = "0" cellspacing = "0"> <tr> <th><?php __('Id'); ?></th> <th><?php __('User Id'); ?></th> <th><?php __('Friend Id'); ?></th> <th><?php __('Job Id'); ?></th> <th><?php __('Jobkind Id'); ?></th> <th><?php __('Feed Id'); ?></th> <th><?php __('Point'); ?></th> <th><?php __('Message'); ?></th> <th><?php __('From'); ?></th> <th><?php __('Created'); ?></th> <th><?php __('Modified'); ?></th> <th class="actions"><?php __('Actions');?></th> </tr> <?php $i = 0; foreach ($jobkind['Like'] as $like): $class = null; if ($i++ % 2 == 0) { $class = ' class="altrow"'; } ?> <tr<?php echo $class;?>> <td><?php echo $like['id'];?></td> <td><?php echo $like['user_id'];?></td> <td><?php echo $like['friend_id'];?></td> <td><?php echo $like['job_id'];?></td> <td><?php echo $like['jobkind_id'];?></td> <td><?php echo $like['feed_id'];?></td> <td><?php echo $like['point'];?></td> <td><?php echo $like['message'];?></td> <td><?php echo $like['from'];?></td> <td><?php echo $like['created'];?></td> <td><?php echo $like['modified'];?></td> <td class="actions"> <?php echo $this->Html->link(__('View', true), array('controller' => 'likes', 'action' => 'view', $like['id'])); ?> <?php echo $this->Html->link(__('Edit', true), array('controller' => 'likes', 'action' => 'edit', $like['id'])); ?> <?php echo $this->Html->link(__('Delete', true), array('controller' => 'likes', 'action' => 'delete', $like['id']), null, sprintf(__('Are you sure you want to delete # %s?', true), $like['id'])); ?> </td> </tr> <?php endforeach; ?> </table> <?php endif; ?> <div class="actions"> <ul> <li><?php echo $this->Html->link(__('New Like', true), array('controller' => 'likes', 'action' => 'add'));?> </li> </ul> </div> </div> <file_sep><!DOCTYPE HTML> <head> <meta charset="UTF-8"> <title>バイトの妖精</title> <link rel="stylesheet" type="text/css" href="css/top.css"> <script type="text/javascript" src="js/smartrollover.js"></script> </head> <body id="top"> <div id="container"> <div id="title"> <p><img src="top_img/text01.gif" alt="あなたのバイト生活が楽しくなる!" width="365" height="26"></p> <h1><img src="top_img/title.gif" width="426" height="90"></h1> </div> <div id="story"> <p>これはあなたとバイト生活を楽しむ不思議な妖精のちょっと不思議なものがたり。<br>あなたの住んでいる世界とはちょっと違う、あなたの絵本の中の世界。<br>絵本の中で妖精が、あなたが来るのを待っているぽ。</p> </div> <div id="atten"> <p>これは、スマートフォン専用のWebアプリですので、パソコンからはアクセスできません。</p> <p>下の「URLを送る」からスマートフォンにメールを送るか、QRコードからアクセスしてください。</p> </div> <p id="mailbutton"><a href="#"><img src="top_img/btn_off.gif" alt="URLを送る" width="322" height="73"></a></p> <p id="qrcode"><img src="top_img/qrcode.gif" alt="QRコード" width="223" height="213"></p> </div> <div id="footer"> <div id="footerinner"> <ul> <li><a href="#">利用ガイドライン</a></li> <li><a href="#">designers hackとは</a></li> </ul> <p>Copyright© designers hack All Rights Reserved.</p> </div> </div> </body> </html> <file_sep><?php echo $this->Javascript->link('global', false);?> <?php echo $this->Javascript->link('checkin_ui', false);?> <?php echo $this->Html->css('tmp', 'stylesheet', array('inline'=>false)); ?> <script> $(function (){ var sl = new checkInUI(); sl.isWorking = true; //勤務中はtrue,つまりチェックアウトが出る sl.init("checkInSlider"); }); </script> <div class="woodFrame listWrap"> <div class="woodWrapper"> <?php if(!empty($jobs)) { ?> <ul> <?php $wday = array( 0 => '日', 1 => '月', 2 => '火', 3 => '水', 4 => '木', 5 => '金', 6 => '土', ); ?> <?php foreach ($jobs as $job): ?> <li> <a href="<?php echo $this->webroot; ?>jobs/edit/<?php echo $job['Job']['id']; ?>"> <div class="kind"> <h3> <?php $this->Html->image('icon_job_sampling.jpg', array('alt'=>'', 'width'=>'25', 'height'=>'25')); ?> <?php echo $job['Job']['name']; ?> <span><? echo $job['Jobkind']['name']; ?></span> </h3> <?php $sd = getdate(strtotime($job['Job']['startdate'].' '.$job['Job']['starttime'])); ?> <p><time datetime="2012-01-02T10:30Z"> <span class="date"><em><?php echo $sd['mon']; ?></em>月<em><?php echo $sd['mday']; ?></em>日<em><?php echo $wday[$sd['wday']]; ?></em>曜日</span> <span class="time"><em><?php echo $sd['hours']; ?></em>時<em><?php echo $sd['minutes']; ?></em>分〜<em><?php echo $job['Job']['jobtime']; ?></em>時間</span> </time></p> </div> </a> </li> <?php endforeach; ?> </ul> <? } else { ?> <p id="nolist">予定はまだないぽ。</p> <? } ?> <!-- test --> <div style="text-align:center;margin-top:10px;"> <?php echo $this->Paginator->prev('<< ' . __('previous', true), array(), null, array('class'=>'disabled'));?> | <?php echo $this->Paginator->numbers();?> | <?php echo $this->Paginator->next(__('next', true) . ' >>', array(), null, array('class' => 'disabled'));?> </div> <!-- test --> </div> </div><!-- /.listWrap --> <file_sep><div class="likes view"> <h2><?php __('Like');?></h2> <dl><?php $i = 0; $class = ' class="altrow"';?> <dt<?php if ($i % 2 == 0) echo $class;?>><?php __('Id'); ?></dt> <dd<?php if ($i++ % 2 == 0) echo $class;?>> <?php echo $like['Like']['id']; ?> &nbsp; </dd> <dt<?php if ($i % 2 == 0) echo $class;?>><?php __('User'); ?></dt> <dd<?php if ($i++ % 2 == 0) echo $class;?>> <?php echo $this->Html->link($like['User']['id'], array('controller' => 'users', 'action' => 'view', $like['User']['id'])); ?> &nbsp; </dd> <dt<?php if ($i % 2 == 0) echo $class;?>><?php __('Friend Id'); ?></dt> <dd<?php if ($i++ % 2 == 0) echo $class;?>> <?php echo $like['Like']['friend_id']; ?> &nbsp; </dd> <dt<?php if ($i % 2 == 0) echo $class;?>><?php __('Job'); ?></dt> <dd<?php if ($i++ % 2 == 0) echo $class;?>> <?php echo $this->Html->link($like['Job']['name'], array('controller' => 'jobs', 'action' => 'view', $like['Job']['id'])); ?> &nbsp; </dd> <dt<?php if ($i % 2 == 0) echo $class;?>><?php __('Jobkind'); ?></dt> <dd<?php if ($i++ % 2 == 0) echo $class;?>> <?php echo $this->Html->link($like['Jobkind']['name'], array('controller' => 'jobkinds', 'action' => 'view', $like['Jobkind']['id'])); ?> &nbsp; </dd> <dt<?php if ($i % 2 == 0) echo $class;?>><?php __('Feed'); ?></dt> <dd<?php if ($i++ % 2 == 0) echo $class;?>> <?php echo $this->Html->link($like['Feed']['id'], array('controller' => 'feeds', 'action' => 'view', $like['Feed']['id'])); ?> &nbsp; </dd> <dt<?php if ($i % 2 == 0) echo $class;?>><?php __('Point'); ?></dt> <dd<?php if ($i++ % 2 == 0) echo $class;?>> <?php echo $like['Like']['point']; ?> &nbsp; </dd> <dt<?php if ($i % 2 == 0) echo $class;?>><?php __('Message'); ?></dt> <dd<?php if ($i++ % 2 == 0) echo $class;?>> <?php echo $like['Like']['message']; ?> &nbsp; </dd> <dt<?php if ($i % 2 == 0) echo $class;?>><?php __('From'); ?></dt> <dd<?php if ($i++ % 2 == 0) echo $class;?>> <?php echo $like['Like']['from']; ?> &nbsp; </dd> <dt<?php if ($i % 2 == 0) echo $class;?>><?php __('Created'); ?></dt> <dd<?php if ($i++ % 2 == 0) echo $class;?>> <?php echo $like['Like']['created']; ?> &nbsp; </dd> <dt<?php if ($i % 2 == 0) echo $class;?>><?php __('Modified'); ?></dt> <dd<?php if ($i++ % 2 == 0) echo $class;?>> <?php echo $like['Like']['modified']; ?> &nbsp; </dd> </dl> </div> <div class="actions"> <h3><?php __('Actions'); ?></h3> <ul> <li><?php echo $this->Html->link(__('Edit Like', true), array('action' => 'edit', $like['Like']['id'])); ?> </li> <li><?php echo $this->Html->link(__('Delete Like', true), array('action' => 'delete', $like['Like']['id']), null, sprintf(__('Are you sure you want to delete # %s?', true), $like['Like']['id'])); ?> </li> <li><?php echo $this->Html->link(__('List Likes', true), array('action' => 'index')); ?> </li> <li><?php echo $this->Html->link(__('New Like', true), array('action' => 'add')); ?> </li> <li><?php echo $this->Html->link(__('List Users', true), array('controller' => 'users', 'action' => 'index')); ?> </li> <li><?php echo $this->Html->link(__('New User', true), array('controller' => 'users', 'action' => 'add')); ?> </li> <li><?php echo $this->Html->link(__('List Jobs', true), array('controller' => 'jobs', 'action' => 'index')); ?> </li> <li><?php echo $this->Html->link(__('New Job', true), array('controller' => 'jobs', 'action' => 'add')); ?> </li> <li><?php echo $this->Html->link(__('List Jobkinds', true), array('controller' => 'jobkinds', 'action' => 'index')); ?> </li> <li><?php echo $this->Html->link(__('New Jobkind', true), array('controller' => 'jobkinds', 'action' => 'add')); ?> </li> <li><?php echo $this->Html->link(__('List Feeds', true), array('controller' => 'feeds', 'action' => 'index')); ?> </li> <li><?php echo $this->Html->link(__('New Feed', true), array('controller' => 'feeds', 'action' => 'add')); ?> </li> </ul> </div> <file_sep><?php class JobsController extends AppController { var $name = 'Jobs'; var $uses = array('Job', 'Feed'); var $helpers = array('Javascript'); var $components = array('Auth', 'WebApi'); function beforeFilter(){ $this->Auth->userModel = 'User'; $this->Auth->loginAction = array('action' => 'login'); $this->Auth->loginRedirect = array('action' => 'index'); $this->Auth->logoutRedirect = array('action' => 'login'); $this->Auth->allow('login', 'logout'); $this->Auth->loginError = 'username or password is invalid.'; $this->Auth->authError = 'Please try logon as admin.'; } function index() { $this->Job->recursive = 0; $this->paginate = array( 'limit' => 5, 'order' => array('Job.created DESC'), 'conditions'=> array('Job.user_id' => $this->Auth->user('id'), 'Job.checkout IS NULL'), ); $pagination = $this->paginate(); $this->set('jobs', $pagination); $this->set('title_for_action', '予定リスト'); } // user check in a job. function checkin($id = null) { if (!$id) { $this->Session->setFlash(__('Invalid job', true)); $this->redirect(array('action' => 'index')); } $job = $this->Job->read(null, $id); if (!empty($job)) { $job['Job']['checkin'] = DboSource::expression('Now()'); if ($this->Job->save($job)) { $message = $this->Auth->user('username') . ' just checkin to ' . $job['Job']['name']; $this->addFeed($message, $job['Job']['id']); $this->Session->setFlash(__('The checkin has been saved', true)); $this->redirect(array('action' => 'index')); } else { $this->Session->setFlash(__('The checkin could not be saved. Please, try again.', true)); } } if (empty($this->data)) { $this->data = $this->Job->read(null, $id); } $users = $this->Job->User->find('list'); $jobkinds = $this->Job->Jobkind->find('list'); $this->set(compact('users', 'jobkinds')); } // user check out a job. function checkout($id = null) { if (!$id) { $this->Session->setFlash(__('Invalid job', true)); $this->redirect(array('action' => 'index')); } $job = $this->Job->read(null, $id); if (!empty($job)) { $job['Job']['checkout'] = DboSource::expression('Now()'); if ($this->Job->save($job)) { $message = $this->Auth->user('username') . ' just checkout to ' . $job['Job']['name']; $this->addFeed($message, $job['Job']['id']); $this->Session->setFlash(__('The checkout has been saved', true)); $this->redirect(array('action' => 'index')); } else { $this->Session->setFlash(__('The checkout could not be saved. Please, try again.', true)); } } if (empty($this->data)) { $this->data = $this->Job->read(null, $id); } $users = $this->Job->User->find('list'); $jobkinds = $this->Job->Jobkind->find('list'); $this->set(compact('users', 'jobkinds')); } function view($id = null) { if (!$id) { $this->Session->setFlash(__('Invalid job', true)); $this->redirect(array('action' => 'index')); } $this->set('job', $this->Job->read(null, $id)); $this->set('title_for_action', '予定詳細'); } function add() { if (!empty($this->data)) { $this->data['Job']['user_id'] = $this->Auth->user('id'); //時間を整形 $this->data['Job']['startdate']['month'] = sprintf('%02d', $this->data['Job']['startdate']['month']); $this->data['Job']['startdate']['day'] = sprintf('%02d', $this->data['Job']['startdate']['day']); $this->data['Job']['starttime']['hour'] = sprintf('%02d', $this->data['Job']['starttime']['hour']); $this->data['Job']['starttime']['min'] = sprintf('%02d', $this->data['Job']['starttime']['min']); $this->data['Job']['jobtime']['hour'] = sprintf('%02d', $this->data['Job']['jobtime']['hour']); $this->data['Job']['jobtime']['min'] = sprintf('%02d', $this->data['Job']['jobtime']['min']); //仕事名を確定 if(empty($this->data['Job']['name'])) { if(!empty($this->data['Job']['job_selected'])) { $job = $this->Job->read('name', $this->data['Job']['job_selected']); $this->data['Job']['name'] = $job['Job']['name']; } } $this->Job->create(); if ($this->Job->save($this->data)) { $this->Session->setFlash(__('The job has been saved', true)); $this->redirect(array('action' => 'index')); } else { $this->Session->setFlash(__('The job could not be saved. Please, try again.', true)); var_dump($this->data); } } $jobs = $this->Job->find('list'); $jobs['new'] = '新しいバイト先を指定'; // 新規登録のためのデータを追加 $jobkinds = $this->Job->Jobkind->find('list'); $this->set(compact('jobkinds', 'jobs')); $this->set('user', $this->Job->User->read(null, $this->Auth->user('id'))); $this->set('title_for_action', '予定登録'); } function edit($id = null) { if (!$id && empty($this->data)) { $this->Session->setFlash(__('Invalid job', true)); $this->redirect(array('action' => 'index')); } if (!empty($this->data)) { //時間を整形 $this->data['Job']['startdate']['month'] = sprintf('%02d', $this->data['Job']['startdate']['month']); $this->data['Job']['startdate']['day'] = sprintf('%02d', $this->data['Job']['startdate']['day']); $this->data['Job']['starttime']['hour'] = sprintf('%02d', $this->data['Job']['starttime']['hour']); $this->data['Job']['starttime']['min'] = sprintf('%02d', $this->data['Job']['starttime']['min']); $this->data['Job']['jobtime']['hour'] = sprintf('%02d', $this->data['Job']['jobtime']['hour']); $this->data['Job']['jobtime']['min'] = sprintf('%02d', $this->data['Job']['jobtime']['min']); //仕事名を確定 if(empty($this->data['Job']['name'])) { if(!empty($this->data['Job']['job_selected'])) { $job = $this->Job->read('name', $this->data['Job']['job_selected']); $this->data['Job']['name'] = $job['Job']['name']; } } if ($this->Job->save($this->data)) { $this->Session->setFlash(__('The job has been saved', true)); $this->redirect(array('action' => 'index')); } else { var_dump($this->data); $this->Session->setFlash(__('The job could not be saved. Please, try again.', true)); } } if (empty($this->data)) { $this->data = $this->Job->read(null, $id); } $jobs = $this->Job->find('list'); $jobs['new'] = '新しいバイト先を指定'; // 新規登録のためのデータを追加 $jobkinds = $this->Job->Jobkind->find('list'); $this->set(compact('jobkinds', 'jobs')); $this->set('user', $this->Job->User->read(null, $this->Auth->user('id'))); $this->set('title_for_action', '予定を編集する'); } function delete($id = null) { if (!$id) { $this->Session->setFlash(__('Invalid id for job', true)); $this->redirect(array('action'=>'index')); } if ($this->Job->delete($id)) { $this->Session->setFlash(__('Job deleted', true)); $this->redirect(array('action'=>'index')); } $this->Session->setFlash(__('Job was not deleted', true)); $this->redirect(array('action' => 'index')); } // add Feed data for SNS TimeLines function addFeed($message =null, $jobid = null) { if(empty($message) || empty($jobid)) { $this->log('The Feed data argments not enough', LOG_DEBUG); } $feed = array('Feed' => array( 'user_id' => $this->Auth->user('id'), 'message' => $message, 'job_id' => $jobid )); if (!empty($feed)) { if (!$this->Feed->save($feed)) { $this->log('Feed was not saved', LOG_DEBUG); $this->log($feed, LOG_DEBUG); } } } /*** Admin Controllers ***/ function admin_index() { $this->layout = 'admin'; $this->Job->recursive = 0; $this->set('jobs', $this->paginate()); } function admin_view($id = null) { $this->layout = 'admin'; if (!$id) { $this->Session->setFlash(__('Invalid job', true)); $this->redirect(array('action' => 'index')); } $this->set('job', $this->Job->read(null, $id)); } function admin_add() { $this->layout = 'admin'; if (!empty($this->data)) { $this->Job->create(); if ($this->Job->save($this->data)) { $this->Session->setFlash(__('The job has been saved', true)); $this->redirect(array('action' => 'index')); } else { $this->Session->setFlash(__('The job could not be saved. Please, try again.', true)); } } $users = $this->Job->User->find('list'); $jobkinds = $this->Job->Jobkind->find('list'); $this->set(compact('users', 'jobkinds')); } function admin_edit($id = null) { $this->layout = 'admin'; if (!$id && empty($this->data)) { $this->Session->setFlash(__('Invalid job', true)); $this->redirect(array('action' => 'index')); } if (!empty($this->data)) { if ($this->Job->save($this->data)) { $this->Session->setFlash(__('The job has been saved', true)); $this->redirect(array('action' => 'index')); } else { $this->Session->setFlash(__('The job could not be saved. Please, try again.', true)); } } if (empty($this->data)) { $this->data = $this->Job->read(null, $id); } $users = $this->Job->User->find('list'); $jobkinds = $this->Job->Jobkind->find('list'); $this->set(compact('users', 'jobkinds')); } function admin_delete($id = null) { if (!$id) { $this->Session->setFlash(__('Invalid id for job', true)); $this->redirect(array('action'=>'index')); } if ($this->Job->delete($id)) { $this->Session->setFlash(__('Job deleted', true)); $this->redirect(array('action'=>'index')); } $this->Session->setFlash(__('Job was not deleted', true)); $this->redirect(array('action' => 'index')); } } <file_sep><?php class FacebookComponent extends Object { var $Facebook; var $User; /* component statup */ function startup(&$controller) { App::import('Vendor', 'facebook/php-sdk/src/facebook'); $this->Facebook = new Facebook(array( /*** App ID & Secret ***/ 'appId' => '206177822805264', 'secret' => '<KEY>', 'cookie' => true, )); $this->User =& new User(); }//startup() // get Facebook Login URL function getLoginUrl() { return $this->Facebook->getLoginUrl(array( 'scope' => 'email,publish_stream,user_checkins,publish_checkins,offline_access', 'display' => 'touch', )); /* Sample: function facebook_login() { $this->autoRender = false; $url = $this->Facebook->getLoginUrl(); $this->redirect($url); } function fbcallback() { $user_id = $this->Auth->user('id'); $this->Facebook->saveUser($user_id); } */ } function saveUser($user_id = null) { if(empty($user_id)) { $this->log('Facebook saveUser(): User ID is empty.', LOG_DEBUG); return false; } $uid = $this->Facebook->getUser(); if(!$uid) { $this->log('Facebook saveUser(): user get failed, UserID='.$user_id, LOG_DEBUG); return false; } $access_token = $this->Facebook->getAccessToken(); if(!$access_token) { $this->log('Facebook saveUser(): access token get failed, FB_uid='.$uid, LOG_DEBUG); return false; } $this->User->recursive = 0; $user = array('User' => array( 'id' => $user_id, 'fb_access_token' => $access_token )); if(!$this->User->save($user,false)) { $this->log('Facebook Access Token cannot save, UserID='.$user_id, LOG_DEBUG); return false; } return true; } function getUser() { return $this->Facebook->getUser(); } // get Access Token function getAccessToken() { $sess = $this->Facebook->getSession(); if(!empty($sess)) { return $this->Facebook->getAccessToken(); } } // get Me (User Profile) function getMe($user_id = null) { if(!$user_id) return false; $user = $this->User->read(null, $user_id); if(empty($user)) return false; if(empty($user['User']['fb_access_token'])) { $this->log('Facebook getMe(): fb_access_token is empty, UserID='.$user_id, LOG_DEBUG); return false; } $attachment = array( 'access_token' => $user['User']['fb_access_token'], ); $me = null; try { $me = $this->Facebook->api('/me', $attachment); } catch (FacebookApiException $e) { $this->log($e->getType(), LOG_DEBUG); $this->log($e->getMessage(), LOG_DEBUG); } return $me; } // publish stream function publish($user_id = null, $message = null) { if(!$user_id || !$message) return false; $user = $this->User->read(null, $user_id); if(empty($user)) return false; if(empty($user['User']['fb_access_token'])) { // $this->log('Facebook publish(): fb_access_token is empty, UserID='.$user_id, LOG_DEBUG); return false; } $attachment = array( 'access_token' => $user['User']['fb_access_token'], 'message' => htmlspecialchars($message), ); try { $this->Facebook->api('/me/feed', 'POST', $attachment); } catch (FacebookApiException $e) { $this->log($e->getType(), LOG_DEBUG); $this->log($e->getMessage(), LOG_DEBUG); return false; } return true; /* * Publish to News Feed $this->Facebook->api('/me/feed', 'POST', array( 'access_token' => "access_token", 'message' => "This is a Message", 'name' => "<NAME>", 'link' => "http://example.com", 'description' => "here description", 'picture'=> "http://example.com/image.jpg" )); */ /* * Checkin Method $this->Facebook->api('/me/checkins', 'POST', array( 'access_token' => 'access_token', 'message' => 'This is a Message', 'name' => '<NAME>', 'link' => 'http://example.com', 'description' => 'heare description', 'place' => 'Place ID', 'picture' => 'http://example.com/image.jpg', 'coordinates' => '{"latitude":"' . 0.123456 . '", "longitude": "' . 0.789012 . '"}' )); */ } } <file_sep><?php echo $this->Javascript->link('global', false);?> <?php echo $this->Javascript->link('checkin_ui', false);?> <?php echo $this->Javascript->link('charactor', false);?> <script> $(function (){ var sl = new checkInUI(); sl.isWorking = true; //勤務中はtrue,つまりチェックアウトが出る sl.init("checkInSlider"); }); </script> <?php echo $this->Html->css('tmp', 'stylesheet', array('inline'=>false)); ?> <div class="searchBox"> <?php echo $this->Form->create('Friend'); ?> <?php echo $this->Form->input('Friend.username', array('label'=>False, 'div'=>False, 'class'=>'searchTxt', 'placeholder'=>'名前を入れてください')); ?> <?php echo $this->Form->submit('search_btn.png', array('value'=>'検索', 'class'=>'searchBtn', 'width'=>'58')); ?> </form> </div> <div class="woodFrame friendList"> <div class="woodWrapper"> <?php if(!empty($friends)) { ?> <ul> <?php foreach($friends as $friend) { ?> <li data-friend-jobkind="<?php echo $friend['User']['current_jobkind_id']; ?>" data-friend-level="<?php echo $friend['User']['current_level']; ?>"> <a href="<?php echo $this->webroot; ?>/friends/view/<?php echo $friend['User']['id']; ?>"> <canvas width="80" height="80" class="avatarIcon"></canvas> <div class="activity"> <h2><?php echo $friend['User']['username'] ?>さん</h2> <div class="friendStatus"> <p class="status"><?php echo $friend['User']['status']; ?></p> <p class="job"><?php echo $friend['User']['jobkind']; ?></p> <p class="level"><?php echo $friend['User']['current_level']; ?></p> </div> </div> </a> </li> <?php } ?> </ul> <?php } else { ?> <p>一致するサポーターがみつかりません</p> <?php } ?> <p id="moreFeed">もっと読む…<span> <?php echo $this->Html->image('icon_otsukare_load.png', array('alt'=>'loading')); ?> </span></p> </div> </div><!-- /#friendTimeline --> <file_sep><!DOCTYPE HTML> <html> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, minimum-scale=1.0, maximum-scale=1.0, user-scalable=no"> <title>ログイン</title> <?php echo $this->Javascript->link('jquery-1.7.min');?> <?php echo $this->Javascript->link('global');?> <?php echo $this->Html->css('style', 'stylesheet', array('inline'=>true)); ?> <?php echo $this->Html->css('tmp', 'stylesheet', array('inline'=>true)); ?> </head> <body class="nickname"> <div id="container"> <header> <h1><?php __('Biteup'); ?></h1> </header> <div id="bookArea"> <p id="yourname"></p> </div> <div id="login" class="newRegistration"> <?php if ($session->check('Message.auth')) echo $session->flash('auth'); ?> <?php echo $this->Session->flash(); ?> <?php echo $this->Form->create('User', array('class'=>'loginForm'));?> <div class="woodFrame registFrame"> <h1><?php echo $this->Html->image('regist_title_login.png', array('alt'=>'ログインする', 'width'=>'298', 'height'=>'54')); ?></h1> <div class="woodWrapper"> <p class="text">あなたの絵本に帰るには、ログインをするぽ。</p> <dl> <dt><label for="_mail">メールアドレス</label></dt> <dd> <?php echo $this->Form->input('email', array('div'=>false, 'label'=>false, 'id'=>'_mail', 'placeholder'=>'メールアドレスを入力', 'class'=>'loginRegist')); ?> <br><small>※ 半角英数字で入力するぽ。</small> </dd> <dt><label for="_pass">パスワード</label></dt> <dd class="ok"> <?php echo $this->Form->input('password', array('div'=>false, 'label'=>false, 'id'=>'_pass', 'placeholder'=>'パスワードを入力', 'class'=>'loginRegist')); ?> <br><small>※ 半角英数字6文字以上で入力するぽ。</small> </dd> </dl> <p class="forgetPW"><a href="#">パスワードを忘れたら</a></p> </div> </div> <p class="alC"><?php echo $this->Form->submit('login_btn_login.png', array('alt'=>'絵本にはいる!', 'width'=>'312', 'div'=>False, 'label'=>False)); ?></p> <p class="forgetPW"><?php echo $this->Html->link(__('Join to World', true), array('action' => 'join'));?></p> </form> </div> </div><!--/container--> <footer> <nav> <ul> <li class="tapping"><?php echo $this->Html->link($this->Html->image('footer_btn_info.png', array('alt' => '登録情報', 'width' => '68', 'height' => '38')), array('controller'=>'users', 'action'=>'edit'), array('escape'=>false)); ?></a></li> <li class="tapping"><a href="#"><?php echo $html->image('footer_btn_guideline.png', array('alt' => '利用ガイドライン', 'width' => '107', 'height' => '38')); ?></a></li> <li class="tapping"><a href="#"><?php echo $html->image('footer_btn_about.png', array('alt' => 'designers hackとは', 'width' => '127', 'height' => '38')); ?></a></li> </ul> </nav> <p class="copyright">Copyright &copy; designers hack All Rights Reserved.</p> </footer> </body> </html> <file_sep>(function($, window) { var ts_info = { name: "ui-time-selector" }; var ts_skin = "<div class='ui-time-selector'>" + "<div class='tenkey-frame'>" + "<span id='ui-btn-0' data-value='0' class='button'>0</span>" + "<span id='ui-btn-1' data-value='1' class='button'>1</span>" + "<span id='ui-btn-2' data-value='2' class='button'>2</span>" + "<span id='ui-btn-3' data-value='3' class='button disabled'>3</span>" + "<span id='ui-btn-4' data-value='4' class='button disabled'>4</span>" + "<span id='ui-btn-5' data-value='5' class='button disabled'>5</span>" + "<span id='ui-btn-6' data-value='6' class='button disabled'>6</span>" + "<span id='ui-btn-7' data-value='7' class='button disabled'>7</span>" + "<span id='ui-btn-8' data-value='8' class='button disabled'>8</span>" + "<span id='ui-btn-9' data-value='9' class='button disabled'>9</span>" + "</div>" + "<span id='ui-btn-back' data-value='back' class='button disabled'>もどる</span>" + "<span id='ui-btn-cancel' data-value='cancel' class='button'>消す</span>" + "<span id='ui-btn-now' data-value='now' class='button'>今の時刻</span>" + "<div class='input-frame'>" + "<span id='ui-input-1' class='input forcus'></span>" + "<span id='ui-input-2' class='input'></span>" + "<span id='ui-input-3' class='input'></span>" + "<span id='ui-input-4' class='input'></span>" + "</div>" + "</div>"; $.fn.timeSelector = function(arg) { var oTarget = $(this); var tHour = oTarget.data("hour"); var tMinute = oTarget.data("minute"); if (!tHour && !tMinute) { return; } var format = (arg.format) ? arg.format : "%H:%M"; var toHour = arg.toHour; var toMinute = arg.toMinute; if (!toHour && !toMinute) { return; } oTarget.on("click", function() { var oHour = $("#" + tHour), oMinute = $("#" + tMinute); var hdnHour = $("#" + toHour), hdnMinute = $("#" + toMinute); var defHour = oHour.val(), defMinute = oMinute.val(); var valH1 = valH2 = valM1 = valM2 = ""; if (defHour != "" && defMinute != "") { if (defHour.length < 2) { valH1 = "0"; valH2 = defHour.charAt(0); } else { valH1 = defHour.charAt(0); valH2 = defHour.charAt(1); } if (defMinute.length < 2) { valM1 = "0"; valM2 = defMinute.charAt(0); } else { valM1 = defMinute.charAt(0); valM2 = defMinute.charAt(1); } } var setId = $(this).attr("id") + "-" + ts_info.name; if (0 < $("#" + setId).size()) { return; } var oWrapper = $(ts_skin).attr("id", setId); if (arg.target) { $("#" + arg.target).append(oWrapper); } else { $("body").append(oWrapper); } var oKeys = oWrapper.find(".button"); var oInput = oWrapper.find(".input"); oInput.filter("[id='ui-input-1']").text(valH1); oInput.filter("[id='ui-input-2']").text(valH2); oInput.filter("[id='ui-input-3']").text(valM1); oInput.filter("[id='ui-input-4']").text(valM2); oKeys.on("touchstart mousedown", function(e) { var oSelf = $(this); oSelf.addClass("tap"); var value = oSelf.data("value"); switch (value) { case "back": if (oSelf.hasClass("disabled")) { break; } var oForcus = oInput.filter("[class*='forcus']"); oForcus.text(""); var oPrev = oForcus.prev(); if (oPrev.size() < 1) { console.log("2"); break; } oForcus.removeClass("forcus"); oPrev.addClass("forcus"); oPrev.text(""); if (oPrev.prev().size() < 1) { oSelf.addClass("disabled") } setButtonConditions(oPrev); break; case "cancel": oWrapper.remove(); break; case "enter": var valKeta1 = oInput.filter("[id='ui-input-1']").text(); var valKeta2 = oInput.filter("[id='ui-input-2']").text(); var valKeta3 = oInput.filter("[id='ui-input-3']").text(); var valKeta4 = oInput.filter("[id='ui-input-4']").text(); setValue(valKeta1, valKeta2, valKeta3, valKeta4); /* oTarget.text(valKeta1 + valKeta2 + ":" + valKeta3 + valKeta4); oHour.val(parseInt(valKeta1 + "" + valKeta2)); oMinute.val(parseInt(valKeta3 + "" + valKeta4)); */ oWrapper.remove(); break; case "now": var now = new Date(); var nowHour = "" + now.getHours(); var nowMinute = "" + now.getMinutes(); if (nowHour.length < 2) { valH1 = "0"; valH2 = nowHour.charAt(0); } else { valH1 = nowHour.charAt(0); valH2 = nowHour.charAt(1); } if (nowMinute.length < 2) { valM1 = "0"; valM2 = nowMinute.charAt(0); } else { valM1 = nowMinute.charAt(0); valM2 = nowMinute.charAt(1); } setValue(valH1, valH2, valM1, valM2); /* oTarget.text(valH1 + "" + valH2 + ":" + valM1 + "" + valM2); oHour.val(parseInt(valH1 + "" + valH2)); oMinute.val(parseInt(valM1 + "" + valM2)); */ oWrapper.remove(); break; default: if (oSelf.hasClass("disabled")) { break; } var oForcus = oInput.filter("[class*='forcus']"); oForcus.text(value); var oNext = oForcus.next(); if (oNext.size() < 1) { var valKeta1 = oInput.filter("[id='ui-input-1']").text(); var valKeta2 = oInput.filter("[id='ui-input-2']").text(); var valKeta3 = oInput.filter("[id='ui-input-3']").text(); var valKeta4 = oInput.filter("[id='ui-input-4']").text(); setValue(valKeta1, valKeta2, valKeta3, valKeta4); /* oTarget.text(valKeta1 + "" + valKeta2 + ":" + valKeta3 + "" + valKeta4); oHour.val(parseInt(valKeta1 + "" + valKeta2)); oMinute.val(parseInt(valKeta3 + "" + valKeta4)); */ oWrapper.remove(); break; } else { oNext.text(""); var oNext2 = oNext.next(); if (0 < oNext2.size()) { oNext2.text(""); var oNext3 = oNext2.next(); if (0 < oNext3.size()) { oNext3.text(""); } } } setButtonConditions(oNext); oForcus.removeClass("forcus"); oNext.addClass("forcus"); $("#ui-btn-back").removeClass("disabled").text("もどる"); break; } function setButtonConditions(obj) { var obFrame = oWrapper.find(".tenkey-frame"); obFrame.find("span").addClass("disabled"); if (obj.attr("id") == "ui-input-1") { obFrame.find("#ui-btn-0, #ui-btn-1, #ui-btn-2").removeClass("disabled"); }else if (obj.attr("id") == "ui-input-2") { if (value == "0" || value == "1") { obFrame.find(".disabled").removeClass("disabled"); } else { obFrame.find("#ui-btn-0, #ui-btn-1, #ui-btn-2, #ui-btn-3").removeClass("disabled"); } } else if (obj.attr("id") == "ui-input-3") { obFrame.find("#ui-btn-0, #ui-btn-1, #ui-btn-2, #ui-btn-3, #ui-btn-4, #ui-btn-5").removeClass("disabled"); } else if (obj.attr("id") == "ui-input-4") { oWrapper.find(".tenkey-frame span").removeClass("disabled"); } } function setValue(valH1, valH2, valM1, valM2) { var setH = valH1 + "" + valH2; var setM = valM1 + "" + valM2; var setVal = format.replace("%H", setH); setVal = setVal.replace("%M", setM); console.log(parseInt(setH, 10)); oTarget.html(setVal); oHour.val(parseInt(setH, 10)); oMinute.val(parseInt(setM, 10)); hdnHour.val(parseInt(setH, 10)); hdnMinute.val(parseInt(setM, 10)); } e.preventDefault(); }).on("touchend mouseup", function(e) { $(this).removeClass("tap"); }); }); }; })(jQuery, window);<file_sep> <!-- 秋葉追加 --> <!-- ↓↓↓↓ このnakashizuは要らない?? --> <!-- ここから、サーバに吐き出してもらいたいscript --> <script> var userData = { rows: [ {userName:"nakashizu",userID:123456}] }; </script> <!-- / ここから、サーバに吐き出してもらいたいscript --> <!-- ここまで このnakashizuは要らない?? --> <?php echo $this->Javascript->link('global', false);?> <?php echo $this->Javascript->link('checkin_ui', false);?> <?php echo $this->Javascript->link('charactor', false);?> <?php echo $this->Javascript->link('sync', false);?> <script> $(function (){ var sl = new checkInUI(); //初回1度だけ、通信をかける Sync.once(2, function (res){ //バイト予定が入っていたら if(res.job.date) { var date = res.job.date.split("-"); var times = res.job.startTime.split("-"); var comments = date[1]+"月"+date[2]+"日 "+times[0]+"時"+times[1]+"分から"+res.job.name+"でバイトが入ってるぽ!"; //バイト先とか、どうする? $(".cloud").text(comments); } }); // //ポーリングスタート、間隔の時間設定はSync内で Sync.start(2,function (res){ console.log(res.job); if(res.job) { sl.init("checkInSlider", res.job.id, false); } }); // //console.log("lastID",$("#timeline ul li:last-child").data("feed-id")) //もっと読むのタップ時に一度だけポーリング $("#moreFeed").bind("click", function (){ $(this).find("span").show(); var Itimers = setInterval(function () { clearInterval(Itimers); Sync.more(5, function (res){ console.log("応答",res.feeds) if(res.feeds !== null) { var dom = ""; for (var i = 0; i<res.feeds.length; i++) { //1フィードごとに時間を計算する var times = Global.compareTime(res.feeds[i].created); dom += '<li data-friend-jobkind="'+res.feeds[i].jobkind+'" data-friend-level="'+res.feeds[i].level+'" data-friend-level="'+res.feeds[i].id+'"><a href="/a/feeds/detail/'+res.feeds[i].id+'"><canvas width="80" height="80" class="avatarIcon"></canvas><div class="activity"><p class="comment">'+res.feeds[i].body+'</p><div class="footer"><p class="icon"><span class="comment">'+res.feeds[i].likesCount+'</span><span class="otsu">'+res.feeds[i].commentCount+'</span></p><p class="times">'+times+'</p></div></div></a></li>'; } $(dom).appendTo(".woodWrapper ul").hide().slideDown(1000, function (){ $("#moreFeed span").hide(); }); Global.thumbnail2Canvas(); }else{ //もし{feed: null}だったら $("#moreFeed").css({ "background":"url(/a/img/btn_readnomore.png) no-repeat center top", "background-size":"299px 86px", "width":"299px", "height":"86px", "padding-bottom":"0" }); $("#moreFeed span").hide(); } },$("#timeline ul li:last-child").data("feed-id")); }, 500); }); // }); </script> <?php echo $this->Html->css('tmp', 'stylesheet', array('inline'=>false)); ?> <?php echo $this->Html->css('jquery.subwindow', 'stylesheet', array('inline'=>false)); ?> <div id="topics"> <div id="checkInSlider" data-user-id="<?php if(!empty($userid)) echo $userid; ?>" data-job-id="<?php if(!empty($latestjob['Job']['id'])) echo $latestjob['Job']['id']; ?>"></div> <div class="cloud"> <?php if(!empty($latestjob)) { ?> <?php $ljd = date_parse($latestjob['Job']['startdate'].' '.$latestjob['Job']['starttime']); ?> <?php echo $ljd['month']; ?>月<?php echo $ljd['day']; ?>日、<?php echo $ljd['hour']; ?>:<?php echo sprintf("%02d", $ljd['minute']); ?>からバイトが入っています! <?php } else { ?> バイトは入ってないぽ。 <?php } ?> </div> </div> <!-- div class="searchBox"> <?php echo $this->Form->create('Friend', array('action'=>'search')); ?> <?php echo $this->Form->input('Friend.username', array('label'=>False, 'div'=>False, 'class'=>'searchTxt', 'placeholder'=>'名前を入れてください')); ?> <?php echo $this->Form->submit('search_btn.png', array('value'=>'検索', 'class'=>'searchBtn', 'width'=>'58')); ?> </form> </div --> <div id="timeline" class="woodFrame"> <div class="woodWrapper"> <?php if(!empty($feeds)) { // Friend Timeline Loop ?> <ul> <?php foreach($feeds as $feed) { ?> <li data-friend-jobkind="<?php echo $feed['User']['current_jobkind_id']; ?>" data-friend-level="<?php echo $feed['User']['current_level']; ?>" data-feed-id="<?php echo $feed['Feed']['id']; ?>"> <a href="<?php echo $this->webroot; ?>feeds/detail/<?php echo $feed['Feed']['id']; ?>"> <canvas width="80" height="80" class="avatarIcon"></canvas> <div class="activity"> <p class="comment"> <span><?php echo $feed['User']['username']; ?>さん</span> <?php echo $feed['Feed']['message']; ?> </p> <div class="footer"> <p class="icon"> <span class="comment"><?php echo $feed['Like']['comments']; ?></span><!--コメント数--> <span class="otsu"><?php echo $feed['Like']['likes']; ?></span><!--オツカレ数--> </p> <p class="times"><?php echo $feed['Feed']['created']; ?></p> </div> </div> </a> </li> <? } ?> </ul> <?php } ?> <?php if(!empty($feeds)) { ?> <p id="moreFeed">もっと読む…<span> <?php echo $this->Html->image('icon_otsukare_load.png', array('alt'=>'loading')); ?> </span></p> <? } else { ?> <p id="nolist"> <?php echo $this->Html->link('友達を探してサポートするぽ!', array('controller'=>'feeds', 'action'=>'timeline')); ?> </p> <? } ?> </div> </div><!-- /#friendTimeline --> <file_sep><?php echo $this->Html->css('tmp', 'stylesheet', array('inline'=>false)); ?> <?php echo $this->Session->flash(); ?> <div id="account"> <div class="woodFrame registFrame noTitle"> <div class="woodWrapper"> <?php echo $this->Form->create('User');?> <?php echo $this->Form->input('id', array('type'=>'hidden', 'value'=>$user['User']['id'])); ?> <dl> <dt>あなたのニックネーム</dt> <dd class="noedit"><?php if(!empty($user['User']['username'])) echo $user['User']['username']; ?></dd> <dt>メールアドレス</dt> <dd class="noedit"><?php if(!empty($user['User']['email'])) echo $user['User']['email']; ?></dd> <dt>Facebook</dt> <?php if(!$fb_uid) { ?> <dd><?php echo $this->Html->link(__('Facebook Authorization', true), array('action' => 'fbauth'));?></dd> <?php } else { ?> <dd><?php echo $this->Html->link(__('My Facebook Account', true), 'http://m.facebook.com/home.php?__user='.$fb_uid); ?></dd> <?php } ?> <dt>新しいパスワードに変更する</dt> <dd><?php //echo $this->Html->link(__('Change Password', true), array('action' => 'chpwd'));?></dd> <dd><?php echo $this->Form->input('new_password', array('type'=>'password', 'div'=>false, 'label'=>false, 'value'=>'', 'class'=>'newRegist', 'placeholder'=>'新しいパスワードを入力するぽ')); ?></dd> <dd><?php echo $this->Form->input('renew_password', array('type'=>'password', 'div'=>false, 'label'=>false, 'value'=>'', 'class'=>'newRegist', 'placeholder'=>'もう一度確認用に入力するぽ')); ?></dd> </dl> <p class="alC"><?php echo $this->Form->submit('btn_edit.png', array('alt'=>"編集する", 'width'=>"206", 'height'=>"60", 'div'=>false, 'label'=>false)); ?></p> </form> </div> </div> <div class="registBtn"> <p><?php echo $this->Html->link($this->Html->image('btn_quit.png', array('alt'=>'Retire', 'width'=>'310')), array('action' => 'retire'), array('escape' => false));?></p> </div> </div><!-- /#account --> <file_sep><!DOCTYPE HTML> <html> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, minimum-scale=1.0, maximum-scale=1.0, user-scalable=no"> <?php echo $this->Html->meta('icon'); ?> <title><?php if(empty($title_for_action)) { echo __('Biteup', true); } else { echo $title_for_action; } ?></title> <?php echo $this->Javascript->link('jquery-1.7.min');?> <?php if(!empty($async_json_data)) { ?> <script> var asyncResult = <?php echo $async_json_data; ?> </script> <?php } ?> <?php echo $scripts_for_layout; ?> <?php echo $this->Html->css('style', 'stylesheet', array('inline'=>true)); ?> </head> <body> <div id="container"> <?php if($this->name == 'Users' && $this->action == 'index') { //トップページ以外は div.contenerInnterを削除する ?> <div class="containerInner"> <? } else { ?> <div> <? } ?> <?php echo $this->element('gnav'); // Global Navigation ?> <?php echo $this->Session->flash(); ?> <?php echo $content_for_layout; ?> </div><!-- /#contenerInner --> </div><!-- /#container --> <footer> <nav> <ul> <li class="tapping"><?php echo $this->Html->link($this->Html->image('footer_btn_info.png', array('alt' => '登録情報', 'width' => '68', 'height' => '38')), array('controller'=>'users', 'action'=>'edit'), array('escape'=>false)); ?></a></li> <li class="tapping"><a href="../../s/guideline.html"><?php echo $html->image('footer_btn_guideline.png', array('alt' => '利用ガイドライン', 'width' => '107', 'height' => '38')); ?></a></li> <li class="tapping"><a href="../../s/about.html"><?php echo $html->image('footer_btn_about.png', array('alt' => 'designers hackとは', 'width' => '127', 'height' => '38')); ?></a></li> </ul> </nav> <p class="copyright">Copyright &copy; designers hack All Rights Reserved.</p> </footer> <?php echo $this->element('sql_dump'); ?> </body> </html> <file_sep><?php class WebApiComponent extends Object { // Result data send as JSON function sendApiResult($dataArray = null) { if(!empty($dataArray)) { $json = json_encode($dataArray); header('Content-type: application/json'); echo $json; } else { header('Content-type: text/plain; charset=utf-8'); echo 'undefined'; } } } <file_sep>function checkInUI () { // // チェックインのスライド用 UI // var container = null, hundle = null, x = 0, timer = null, maxLength = 0, _this = this, cloud =null, jobID = null; this.isWorking = false; // isWorking trueだと勤務中なのでcheckoutを表示、falseの場合はcheckInを表示 this.init = function (target, jobId, _workingFlg) { jobID = jobId; x = 0; container = document.getElementById(target); cloud = $(".cloud")[0]; if ($(".checkInWrapper")[0] != undefined) return false; //もしもスライダが存在してたら中断 else this.isWorking = _workingFlg; //スライダが存在してなかったら、isWorkingを設定 $("#topics").animate({"height": 200}, 200); $(".containerInner").addClass("checkInWrapperDown"); var code = "<div class='checkInWrapper'><div class='hundle'></div></div>"; $(container).removeClass("working").show(0).addClass((_this.isWorking) ? "working" : null); $(container).css({"position":"relative"}); hundle = $(container).append(code).find(".hundle").css({"position":"absolute"})[0]; $(hundle).bind("mousedown touchstart",touchStart); //maxLength = parseInt($(container).width()) - parseInt($(hundle).innerWidth()); maxLength = 320-109; //alert(hundle); } var hundleTouchX = 0; function touchStart (e) { e.preventDefault(); e.stopPropagation(); hundleTouchX = (event.clientX || event.touches[0].clientX); //touchMove();//指タップでも移動処理を1度行う $(window).bind("mousemove touchmove",touchMove); $(hundle).unbind("mousedown touchstart",touchStart); $(window).bind("mouseup touchend",touchEnd); } function touchMove (e) { x = (event.clientX || event.touches[0].clientX) -hundleTouchX; //console.log(event.touches[0].clientX) if ( maxLength < parseInt(x) ) { x = maxLength; } //$(hundle).css({"left": x}); hundle.style.left = x + "px"; } function touchEnd (e) { //console.log(x) //console.log($(container).width(), parseInt($(hundle).css("left"))+parseInt($(hundle).width()) ); $(window).unbind("mouseup touchend",touchEnd); $(window).unbind("mousemove touchmove",touchMove); if(x >= maxLength) { // チェックイン or アウト 確定 submitCheck(); }else{ $(hundle).animate({"left": 0}, 200, function (){ $(hundle).bind("mousedown touchstart",touchStart); }); } } function submitCheck () { var sendMsg = ""; if(_this.isWorking) { //チェックアウトをした //alert("チェックアウトをした"); //$(container).removeClass("working"); sendMsg = "checkOut"; _this.isWorking = false; }else{ //チェックインをした //alert("チェックインをした"); //$(container).addClass("working"); sendMsg = "checkIn"; _this.isWorking = true; } post(sendMsg); } function post (msg) { var sendData = null, codes = null; var job_id = $('#checkInSlider').data('job-id'); var user_id = $('#checkInSlider').data('user-id'); if(msg === "checkIn") { // まあまあ楽 sendData = {"data[jobId]": job_id, "data[userId]": user_id}; // sendData = {"isWorking": true, "workID": jobID, "userID": userData.rows[0].userName}; codes = "<div class='commentArea' style='display:none; top: 40px;'><p class='sendingIcon'>送信中</p></div>"; $(container).append(codes); $(container).find(".commentArea").slideDown(400,function (){ //postSend (sendData); postSendCheckIn (sendData); }); // これでチェックインは終わり }else{ // チェックアウト //console.log(msg) sendData = {"data[jobId]": job_id, "data[userId]": user_id, "data[message]": ""}; //sendData = { "isWorking": false, "workID": "バイトのID", "userID": userData.rows[0].userName, "comment": "ユーザのコメント" }; codes = "<div class='commentArea' style='display:none; top: 40px;'><textarea></textarea><a href='#'>送信する</a></div>"; $(container).append(codes); var tx = $(container).find(".commentArea textarea")[0]; var btn = $(container).find(".commentArea a")[0]; var tx = $(container).find(".commentArea").slideDown(400); $(btn).bind("click", function (e){ e.preventDefault(); //コメントエリアを消す $(container).find(".commentArea").fadeOut(300, function (){ $(container).append("<p class='sendingIcon'><span><img src='/a/img/icon_otsukare_load.png' alt='loading'></span>送信中</p>"); //sendData.comment = $(".commentArea textarea").val(); sendData = {"data[jobId]": job_id, "data[userId]": user_id, "data[message]": $(".commentArea textarea").val()}; postSendCheckOut (sendData); }); }); } function postSend (msgs) { $.ajax({ type: "POST", url: "/test.php", data: msgs, success: function(res){ var timer = setTimeout(function (){ clearTimeout(timer); //alert( "Saved: " + _this.isWorking ); $(container).find(".sendingIcon").text("送信完了しました!"); $(container).delay(1500).fadeOut(500, function (){ if(!_this.isWorking) { //チェックアウト完了、消す、バイト終わりでおつかれさま $(this).children().remove(); $("#topics").animate({"height": 0}, 500); $(".containerInner").removeClass("checkInWrapperDown"); $("html,body").animate({"scrollTop": 0}, 300); //$(cloud).html(""); _this.isWorking = false; }else{ //チェックイン完了、画像、クラス名を変更してfadeIn、仕事中!!! $(container).find(".commentArea").remove(); $(hundle).bind("mousedown touchstart",touchStart); $(hundle).css({"left": 0}); $(container).addClass("working").fadeIn(300); $(cloud).html("バイトなう!<br>がんばるぽ!"); _this.isWorking = true; } // }); }, 1000); } });/**/ }//postSend // 仮のチェックイン処理 function postSendCheckIn (msgs) { $.ajax({ type: "POST", url: "/a/api/users/checkin", data: msgs, success: function(res){ console.log(res); var timer = setTimeout(function (){ clearTimeout(timer); //alert( "Saved: " + _this.isWorking ); $(container).find(".sendingIcon").text("送信完了しました!"); $(container).delay(1500).fadeOut(500, function (){ //チェックイン完了、画像、クラス名を変更してfadeIn、仕事中!!! $(container).find(".commentArea").remove(); $(hundle).bind("mousedown touchstart",touchStart); $(hundle).css({"left": 0}); $(container).addClass("working").fadeIn(300); $(cloud).html("バイトなう!<br>がんばるぽ!"); _this.isWorking = true; }); }, 1000); } });/**/ }//postSend // 仮のチェックアウト処理 function postSendCheckOut (msgs) { $.ajax({ type: "POST", url: "/a/api/users/checkout", data: msgs, success: function(res){ console.log(res); var timer = setTimeout(function (){ clearTimeout(timer); //alert( "Saved: " + _this.isWorking ); $(container).find(".sendingIcon").text("送信完了しました!"); $(container).delay(1500).fadeOut(500, function (){ //チェックアウト完了、消す、バイト終わりでおつかれさま $(this).children().remove(); $("#topics").animate({"height": 0}, 500); $(".containerInner").removeClass("checkInWrapperDown"); $("html,body").animate({"scrollTop": 0}, 300); //$(cloud).html(""); _this.isWorking = false; }); }, 1000); } });/**/ }//postSend } } <file_sep><div class="users view"> <h2><?php __('User');?></h2> <dl><?php $i = 0; $class = ' class="altrow"';?> <dt<?php if ($i % 2 == 0) echo $class;?>><?php __('Id'); ?></dt> <dd<?php if ($i++ % 2 == 0) echo $class;?>> <?php echo $user['User']['id']; ?> &nbsp; </dd> <dt<?php if ($i % 2 == 0) echo $class;?>><?php __('Username'); ?></dt> <dd<?php if ($i++ % 2 == 0) echo $class;?>> <?php echo $user['User']['username']; ?> &nbsp; </dd> <dt<?php if ($i % 2 == 0) echo $class;?>><?php __('Password'); ?></dt> <dd<?php if ($i++ % 2 == 0) echo $class;?>> <?php echo $user['User']['password']; ?> &nbsp; </dd> <dt<?php if ($i % 2 == 0) echo $class;?>><?php __('Email'); ?></dt> <dd<?php if ($i++ % 2 == 0) echo $class;?>> <?php echo $user['User']['email']; ?> &nbsp; </dd> <dt<?php if ($i % 2 == 0) echo $class;?>><?php __('Point'); ?></dt> <dd<?php if ($i++ % 2 == 0) echo $class;?>> <?php echo $user['User']['point']; ?> &nbsp; </dd> <dt<?php if ($i % 2 == 0) echo $class;?>><?php __('Created'); ?></dt> <dd<?php if ($i++ % 2 == 0) echo $class;?>> <?php echo $user['User']['created']; ?> &nbsp; </dd> <dt<?php if ($i % 2 == 0) echo $class;?>><?php __('Modified'); ?></dt> <dd<?php if ($i++ % 2 == 0) echo $class;?>> <?php echo $user['User']['modified']; ?> &nbsp; </dd> </dl> </div> <div class="actions"> <h3><?php __('Actions'); ?></h3> <ul> <li><?php echo $this->Html->link(__('Edit User', true), array('action' => 'edit', $user['User']['id'])); ?> </li> <li><?php echo $this->Html->link(__('Delete User', true), array('action' => 'delete', $user['User']['id']), null, sprintf(__('Are you sure you want to delete # %s?', true), $user['User']['id'])); ?> </li> <li><?php echo $this->Html->link(__('List Users', true), array('action' => 'index')); ?> </li> <li><?php echo $this->Html->link(__('New User', true), array('action' => 'add')); ?> </li> <li><?php echo $this->Html->link(__('List Feeds', true), array('controller' => 'feeds', 'action' => 'index')); ?> </li> <li><?php echo $this->Html->link(__('New Feed', true), array('controller' => 'feeds', 'action' => 'add')); ?> </li> <li><?php echo $this->Html->link(__('List Friends', true), array('controller' => 'friends', 'action' => 'index')); ?> </li> <li><?php echo $this->Html->link(__('New Friend', true), array('controller' => 'friends', 'action' => 'add')); ?> </li> <li><?php echo $this->Html->link(__('List Jobs', true), array('controller' => 'jobs', 'action' => 'index')); ?> </li> <li><?php echo $this->Html->link(__('New Job', true), array('controller' => 'jobs', 'action' => 'add')); ?> </li> <li><?php echo $this->Html->link(__('List Likes', true), array('controller' => 'likes', 'action' => 'index')); ?> </li> <li><?php echo $this->Html->link(__('New Like', true), array('controller' => 'likes', 'action' => 'add')); ?> </li> </ul> </div> <div class="related"> <h3><?php __('Related Feeds');?></h3> <?php if (!empty($user['Feed'])):?> <table cellpadding = "0" cellspacing = "0"> <tr> <th><?php __('Id'); ?></th> <th><?php __('User Id'); ?></th> <th><?php __('Job Id'); ?></th> <th><?php __('Message'); ?></th> <th><?php __('Created'); ?></th> <th><?php __('Modified'); ?></th> <th class="actions"><?php __('Actions');?></th> </tr> <?php $i = 0; foreach ($user['Feed'] as $feed): $class = null; if ($i++ % 2 == 0) { $class = ' class="altrow"'; } ?> <tr<?php echo $class;?>> <td><?php echo $feed['id'];?></td> <td><?php echo $feed['user_id'];?></td> <td><?php echo $feed['job_id'];?></td> <td><?php echo $feed['message'];?></td> <td><?php echo $feed['created'];?></td> <td><?php echo $feed['modified'];?></td> <td class="actions"> <?php echo $this->Html->link(__('View', true), array('controller' => 'feeds', 'action' => 'view', $feed['id'])); ?> <?php echo $this->Html->link(__('Edit', true), array('controller' => 'feeds', 'action' => 'edit', $feed['id'])); ?> <?php echo $this->Html->link(__('Delete', true), array('controller' => 'feeds', 'action' => 'delete', $feed['id']), null, sprintf(__('Are you sure you want to delete # %s?', true), $feed['id'])); ?> </td> </tr> <?php endforeach; ?> </table> <?php endif; ?> <div class="actions"> <ul> <li><?php echo $this->Html->link(__('New Feed', true), array('controller' => 'feeds', 'action' => 'add'));?> </li> </ul> </div> </div> <div class="related"> <h3><?php __('Related Friends');?></h3> <?php if (!empty($user['Friend'])):?> <table cellpadding = "0" cellspacing = "0"> <tr> <th><?php __('Id'); ?></th> <th><?php __('User Id'); ?></th> <th><?php __('Friend Id'); ?></th> <th><?php __('Created'); ?></th> <th><?php __('Modified'); ?></th> <th class="actions"><?php __('Actions');?></th> </tr> <?php $i = 0; foreach ($user['Friend'] as $friend): $class = null; if ($i++ % 2 == 0) { $class = ' class="altrow"'; } ?> <tr<?php echo $class;?>> <td><?php echo $friend['id'];?></td> <td><?php echo $friend['user_id'];?></td> <td><?php echo $friend['friend_id'];?></td> <td><?php echo $friend['created'];?></td> <td><?php echo $friend['modified'];?></td> <td class="actions"> <?php echo $this->Html->link(__('View', true), array('controller' => 'friends', 'action' => 'view', $friend['id'])); ?> <?php echo $this->Html->link(__('Edit', true), array('controller' => 'friends', 'action' => 'edit', $friend['id'])); ?> <?php echo $this->Html->link(__('Delete', true), array('controller' => 'friends', 'action' => 'delete', $friend['id']), null, sprintf(__('Are you sure you want to delete # %s?', true), $friend['id'])); ?> </td> </tr> <?php endforeach; ?> </table> <?php endif; ?> <div class="actions"> <ul> <li><?php echo $this->Html->link(__('New Friend', true), array('controller' => 'friends', 'action' => 'add'));?> </li> </ul> </div> </div> <div class="related"> <h3><?php __('Related Jobs');?></h3> <?php if (!empty($user['Job'])):?> <table cellpadding = "0" cellspacing = "0"> <tr> <th><?php __('Id'); ?></th> <th><?php __('User Id'); ?></th> <th><?php __('Name'); ?></th> <th><?php __('Startdate'); ?></th> <th><?php __('Starttime'); ?></th> <th><?php __('Jobtime'); ?></th> <th><?php __('Jobkind Id'); ?></th> <th><?php __('Checkin'); ?></th> <th><?php __('Created'); ?></th> <th><?php __('Modified'); ?></th> <th class="actions"><?php __('Actions');?></th> </tr> <?php $i = 0; foreach ($user['Job'] as $job): $class = null; if ($i++ % 2 == 0) { $class = ' class="altrow"'; } ?> <tr<?php echo $class;?>> <td><?php echo $job['id'];?></td> <td><?php echo $job['user_id'];?></td> <td><?php echo $job['name'];?></td> <td><?php echo $job['startdate'];?></td> <td><?php echo $job['starttime'];?></td> <td><?php echo $job['jobtime'];?></td> <td><?php echo $job['jobkind_id'];?></td> <td><?php echo $job['checkin'];?></td> <td><?php echo $job['created'];?></td> <td><?php echo $job['modified'];?></td> <td class="actions"> <?php echo $this->Html->link(__('View', true), array('controller' => 'jobs', 'action' => 'view', $job['id'])); ?> <?php echo $this->Html->link(__('Edit', true), array('controller' => 'jobs', 'action' => 'edit', $job['id'])); ?> <?php echo $this->Html->link(__('Delete', true), array('controller' => 'jobs', 'action' => 'delete', $job['id']), null, sprintf(__('Are you sure you want to delete # %s?', true), $job['id'])); ?> </td> </tr> <?php endforeach; ?> </table> <?php endif; ?> <div class="actions"> <ul> <li><?php echo $this->Html->link(__('New Job', true), array('controller' => 'jobs', 'action' => 'add'));?> </li> </ul> </div> </div> <div class="related"> <h3><?php __('Related Likes');?></h3> <?php if (!empty($user['Like'])):?> <table cellpadding = "0" cellspacing = "0"> <tr> <th><?php __('Id'); ?></th> <th><?php __('User Id'); ?></th> <th><?php __('Friend Id'); ?></th> <th><?php __('Job Id'); ?></th> <th><?php __('Jobkind Id'); ?></th> <th><?php __('Feed Id'); ?></th> <th><?php __('Point'); ?></th> <th><?php __('Message'); ?></th> <th><?php __('From'); ?></th> <th><?php __('Created'); ?></th> <th><?php __('Modified'); ?></th> <th class="actions"><?php __('Actions');?></th> </tr> <?php $i = 0; foreach ($user['Like'] as $like): $class = null; if ($i++ % 2 == 0) { $class = ' class="altrow"'; } ?> <tr<?php echo $class;?>> <td><?php echo $like['id'];?></td> <td><?php echo $like['user_id'];?></td> <td><?php echo $like['friend_id'];?></td> <td><?php echo $like['job_id'];?></td> <td><?php echo $like['jobkind_id'];?></td> <td><?php echo $like['feed_id'];?></td> <td><?php echo $like['point'];?></td> <td><?php echo $like['message'];?></td> <td><?php echo $like['from'];?></td> <td><?php echo $like['created'];?></td> <td><?php echo $like['modified'];?></td> <td class="actions"> <?php echo $this->Html->link(__('View', true), array('controller' => 'likes', 'action' => 'view', $like['id'])); ?> <?php echo $this->Html->link(__('Edit', true), array('controller' => 'likes', 'action' => 'edit', $like['id'])); ?> <?php echo $this->Html->link(__('Delete', true), array('controller' => 'likes', 'action' => 'delete', $like['id']), null, sprintf(__('Are you sure you want to delete # %s?', true), $like['id'])); ?> </td> </tr> <?php endforeach; ?> </table> <?php endif; ?> <div class="actions"> <ul> <li><?php echo $this->Html->link(__('New Like', true), array('controller' => 'likes', 'action' => 'add'));?> </li> </ul> </div> </div> <file_sep><?php class UsersController extends AppController { var $name = 'Users'; var $helpers = array('Javascript'); var $components = array('Auth', 'WebApi', 'Facebook', 'Timeline'); var $uses = array('User', 'Friend', 'Feed', 'Like', 'Job', 'Level', 'Jobkind'); function beforeFilter(){ $this->Auth->userModel = 'User'; $this->Auth->fields = array('username' => 'email', 'password' => '<PASSWORD>'); $this->Auth->loginAction = array('action' => 'login'); $this->Auth->loginRedirect = array('action' => 'index'); $this->Auth->logoutRedirect = array('action' => 'login'); $this->Auth->allow('login', 'logout', 'join'); $this->Auth->loginError = __('email or password is invalid.', true); //$this->Auth->authError = 'Please try logon as admin.'; } function index() { $this->Friend->recursive = 0; $this->Feed->recursive = 1; $this->Like->recursive = -1; $this->Job->recursive = -1; //直近の仕事を抽出 with api_jobalert $futu = strtotime('+30 minutes'); $datestr = date('Y-m-d', $futu); $timestr = date('H:i:s', $futu); $conditions = array('Job.startdate'=>$datestr, 'Job.starttime <'=>$timestr, 'Job.checkin IS NULL', 'Job.checkout IS NULL', 'Job.user_id'=>$this->Auth->user('id')); $latestjob = $this->Job->find('first', array('conditions'=>$conditions)); //フレンドを抽出 $friends = $this->Friend->find('all', array('conditions'=> array('Friend.user_id'=>$this->Auth->user('id')))); if(!empty($friends)) { $arybuf = array(); foreach($friends as $friend) { array_push($arybuf, $friend['Friend']['friend_id']); } array_push($arybuf, $this->Auth->user('id')); $conditions = array('Feed.user_id IN ('.implode(',', $arybuf).')'); $order = array('Feed.created DESC'); $limit = 10; $feeds = $this->Feed->find('all', array('conditions'=>$conditions, 'order'=>$order, 'limit'=>$limit)); $timelines = array(); foreach($feeds as $feed) { $feed['Like']['likes'] = $this->Like->find('count', array('conditions'=>array('Like.feed_id'=>$feed['Feed']['id'], 'Like.user_id'=>$feed['Feed']['user_id']))); $feed['Like']['comments'] = $this->Like->find('count', array('conditions'=>array('Like.feed_id'=>$feed['Feed']['id'], 'Like.message IS NOT NULL', 'Like.user_id'=>$feed['Feed']['user_id']))); $feed['Feed']['created'] = $this->Timeline->getActionTime($feed['Feed']['created']); array_push($timelines, $feed); } $this->set('feeds', $timelines); } $this->set('title_for_action', 'バイトの妖精'); $this->set('userid', $this->Auth->user('id')); $this->set('nickname', $this->Auth->user('username')); $this->set('latestjob', $latestjob); } // list follow Users function followusers() { $this->Friend->recursive = 1; $this->paginate = array( 'conditions' => array('Friend.user_id' => $this->Auth->user('id')) ); $this->set('users', $this->paginate('Friend')); } // user follow a friend function follow($id = null) { $this->Friend->recursive = 0; if (!$id) { $this->Session->setFlash(__('Invalid id for user', true)); $this->redirect(array('action'=>'searchfriend')); } // 既にフォローされているか? $followed = $this->Friend->find('first', array('conditions'=>array('Friend.user_id'=>$this->Auth->user('id'), 'Friend.friend_id'=>$id))); if(!empty($followed)) { $this->Session->setFlash(__('This user is already followed', true)); $this->redirect(array('action'=>'searchfriend')); } // Friend データを構成 $friend = array('Friend' => array('user_id' => $this->Auth->user('id'), 'friend_id' => $id)); $this->User->create(); if ($this->User->Friend->save($friend)) { $this->Session->setFlash(__('followed!', true)); $this->redirect(array('action' => 'followusers')); } else { $this->Session->setFlash(__('The user could not be saved. Please, try again.', true)); } } // user unfollow a friend function unfollow($id = null) { if (!$id) { $this->Session->setFlash(__('Invalid id for follower', true)); $this->redirect(array('action'=>'followusers')); } $friend = $this->User->Friend->find('first', array('conditions'=>array('Friend.friend_id'=>$id, 'Friend.user_id'=>$this->Auth->user('id')))); if($friend) { if ($this->User->Friend->delete($friend['Friend']['id'])) { $this->Session->setFlash(__('unfollowed!', true)); $this->redirect(array('action'=>'followusers')); } } $this->Session->setFlash(__('This Friend unfollow is unabled', true)); $this->redirect(array('action' => 'followusers')); } function view($id = null) { if(!$id) $id = $this->Auth->user('id'); $this->User->recursive = -1; $this->Jobkind->recursive = -1; $this->Like->recursive = -1; $this->Job->recursive = -1; $this->Level->recursive = -1; $this->Feed->recursive = 0; if (!$id) { $this->Session->setFlash(__('Invalid friend', true)); $this->redirect(array('action' => 'index')); } $user = $this->User->read(null, $id); $jobkind = $this->Jobkind->read(null, $user['User']['current_jobkind_id']); $likecnt = $this->Like->find('count', array('conditions'=>array('Like.user_id'=>$user['User']['id']))); $checkoutcnt = $this->Job->find('count', array('conditions'=>array('Job.user_id'=>$user['User']['id'], 'Job.checkout IS NOT NULL'))); $level = $this->Level->find('first', array('conditions'=>array('Level.level'=>$user['User']['current_level'], 'Level.jobkind_id'=>$user['User']['current_jobkind_id']))); $feeds = $this->Feed->find('all', array('conditions'=>array('Feed.user_id'=>$user['User']['id']), 'order'=>'Feed.id DESC', 'limit'=>5)); $timelines = array(); foreach($feeds as $feed) { $feed['Like']['likes'] = $this->Like->find('count', array('conditions'=>array('Like.feed_id'=>$feed['Feed']['id'], 'Like.user_id'=>$feed['Feed']['user_id']))); $feed['Like']['comments'] = $this->Like->find('count', array('conditions'=>array('Like.feed_id'=>$feed['Feed']['id'], 'Like.message IS NOT NULL', 'Like.user_id'=>$feed['Feed']['user_id']))); $feed['Feed']['created'] = $this->Timeline->getActionTime($feed['Feed']['created']); array_push($timelines, $feed); } $this->set('user', $user); $this->set('jobkind', $jobkind); $this->set('likecnt', $likecnt); $this->set('checkoutcnt', $checkoutcnt); $this->set('level', $level); $this->set('feeds', $timelines); $this->set('title_for_action', 'マイページ'); } function join() { $this->layout = ''; if (!empty($this->data)) { // 1.join_passwordがある場合、passwordをハッシュ化して格納 if(!empty($this->data['User']['join_password']) && !empty($this->data['User']['re_password'])) { if($this->data['User']['join_password'] == $this->data['User']['re_password']) { $this->data["User"]["password"] = $this->Auth->password($this->data['User']['join_password']); } else { $this->Session->setFlash(__('Password columns must input same words', true)); $this->redirect(array('action' => 'join')); } } $this->data['User']['point'] = 0; //アカウント登録時の初期ポイントを設定 $this->data['User']['current_jobkind_id'] = 1; //アカウント登録時の職業IDを設定 $this->data['User']['current_level'] = 1; //アカウント登録時のレベルを設定 $this->User->create(); if ($this->User->save($this->data)) { //$this->Session->setFlash(__('The user has been saved', true)); $this->redirect(array('action' => 'index')); } else { $this->Session->setFlash(__('The user could not be saved. Please, try again.', true)); } } } function edit() { $id = $this->Auth->user('id'); // get User.id for Auth Session if (!$id && empty($this->data)) { $this->Session->setFlash(__('Invalid user', true)); $this->redirect(array('action' => 'index')); } if (!empty($this->data)) { if($this->data['User']['new_password']) { if($this->data['User']['new_password'] == $this->data['User']['renew_password']) { //パスワード照合 $this->data['User']['password'] = $this->Auth->password($this->data['User']['new_password']); } if ($this->User->save($this->data)) { $this->Session->setFlash(__('The user has been saved', true)); $this->redirect(array('action' => 'edit')); } else { $this->Session->setFlash(__('The user could not be saved. Please, try again.', true)); } } } if ($id) { $this->set('user', $this->User->read(null, $id)); } // Facebook 連携 $fb_uid = null; $fb_uid = $this->Facebook->getUser(); if($fb_uid == 0) { $me = $this->Facebook->getMe($this->Auth->user('id')); $fb_uid = $me['id']; } $this->set('fb_uid', $fb_uid); } function retire($id = null) { if(!$id) $id = $this->Auth->user('id'); if (!$id) { $this->Session->setFlash(__('Invalid id for user', true)); $this->redirect(array('action'=>'index')); } // リタイヤ処理用画面のリダイレクトが未決定 /* if ($this->User->delete($id)) { $this->Session->setFlash(__('User deleted', true)); $this->redirect(array('action'=>'index')); } */ /* impl not yet... */ } function delete($id = null) { if (!$id) { $this->Session->setFlash(__('Invalid id for user', true)); $this->redirect(array('action'=>'index')); } if ($this->User->delete($id)) { $this->Session->setFlash(__('User deleted', true)); $this->redirect(array('action'=>'index')); } $this->Session->setFlash(__('User was not deleted', true)); $this->redirect(array('action' => 'index')); } //Facebook認証へのリダイレクト function fbauth() { $this->autoRender = false; if($this->Facebook->getUser()) { //認証OK後 save&redirect if($this->Facebook->saveUser($this->Auth->user('id'))) { $this->Session->setFlash('Facebook Authorized'); } else { $this->Session->setFlash(__('Error: cannot Authorized to Facebook', true)); } $this->redirect('edit'); } $this->redirect($this->Facebook->getLoginUrl()); } function login() { $this->layout = ''; } function logout() { $this->redirect($this->Auth->logout()); } /*** API Contollers ***/ // チェックイン中 状態を返す (checkin=trueであればcheckoutUIを表示する) function api_ischeckin() { $this->autoRender = false; $conditions = array('Job.checkin IS NOT NULL', 'Job.checkout IS NULL', 'Job.user_id'=>$this->Auth->user('id')); $jobs = $this->Job->find('first', array('conditions'=>$conditions)); $flag = false; $user_id = $this->Auth->user('id'); $job_id = 0; if(empty($jobs)) { $flag = false; } else { $flag = true; $job_id = $jobs['Job']['id']; } $data = array('checkin'=>$flag, 'jobId'=>$job_id, 'userId'=>$user_id); $this->WebApi->sendApiResult($data); } // チェックイン中 状態を返す (checkin=trueであればcheckoutUIを表示する) function api_ischeckout() { $this->autoRender = false; $conditions = array('Job.checkin IS NOT NULL', 'Job.checkout IS NULL', 'Job.user_id'=>$this->Auth->user('id')); $jobs = $this->Job->find('first', array('conditions'=>$conditions)); $flag = false; $user_id = $this->Auth->user('id'); $job_id = 0; if(empty($jobs)) { $flag = false; } else { $flag = true; $job_id = $jobs['Job']['id']; } $data = array('checkout'=>$flag, 'jobId'=>$job_id, 'userId'=>$user_id); $this->WebApi->sendApiResult($data); } // async checkin function api_checkin() { $this->autoRender = false; $thos->Job->recursive = -1; $data = array('checkin'=>array('success'=>false)); if(!empty($this->data)) { $job = $this->Job->find('first', array('fields'=>array('Job.id'), 'conditions'=>array('Job.id'=>$this->data['jobId'], 'Job.user_id'=>$this->data['userId']))); if(!empty($job)) { $job['Job']['checkin'] = date('Y-m-d H:i:s'); if ($this->Job->save($job)) { $data = array('checkin'=>array('success'=>true)); } else { $data = array('checkin'=>array('success'=>false, 'message'=>'system error, data save failure')); } } else { $data = array('checkin'=>array('success'=>false, 'message'=>'counldnot find job')); } $pmsg = 'がバイトにチェックインしました。'."\n"; //Feedにメッセージを登録 $feed = array('Feed' => array( 'user_id'=> $this->data['userId'], 'job_id'=> $this->data['jobId'], 'message'=>$pmsg )); $this->Feed->create(); if ($this->Feed->save($feed)) { $data = array('checkin'=>array('success'=>true)); $pubmsg = $this->Auth->user('username').$pmsg; $this->Facebook->publish($this->Auth->user('id'), $pubmsg); // message publish to Facebook } else { $data = array('checkin'=>array('success'=>false, 'message'=>'system error, feed data save failure')); } } else { $data = array('checkin'=>array('success'=>false, 'message'=>'post data is null')); } $this->WebApi->sendApiResult($data); } // async checkout function api_checkout() { $this->autoRender = false; $thos->Job->recursive = -1; $thos->Feed->recursive = -1; $data = array('checkout'=>array('success'=>false)); if(!empty($this->data)) { //Jobにチェックアウトタイムを登録 $job = $this->Job->find('first', array('fields'=>array('Job.id', 'Job.name'), 'conditions'=>array('Job.id'=>$this->data['jobId'], 'Job.user_id'=>$this->data['userId']))); if(!empty($job)) { $job['Job']['checkout'] = date('Y-m-d H:i:s'); if ($this->Job->save($job)) { $data = array('checkout'=>array('success'=>true)); } else { $data = array('checkout'=>array('success'=>false, 'message'=>'system error, job data save failure')); } } else { $data = array('checkout'=>array('success'=>false, 'message'=>'counldnot find job')); } $pmsg = 'が'.$job['Job']['name'].'からチェックアウトしました。'."\n"; //Feedにメッセージを登録 $feed = array('Feed' => array( 'user_id'=> $this->data['userId'], 'job_id'=> $this->data['jobId'], 'message'=>$pmsg.$this->data['message'] )); $this->Feed->create(); if ($this->Feed->save($feed)) { $data = array('checkout'=>array('success'=>true)); $pubmsg = $this->Auth->user('username').$pmsg.$this->data['message']; $this->Facebook->publish($this->Auth->user('id'), $pubmsg); // publish to Facebook } else { $data = array('checkout'=>array('success'=>false, 'message'=>'system error, feed data save failure')); } } else { $data = array('checkout'=>array('success'=>false, 'message'=>'post data is null')); } $this->WebApi->sendApiResult($data); } // async data what information count for badge. function api_infocount() { $this->autoRender = false; //どこからが未読かを判定するトリガが未設計 } // async data what users charactor level. function api_getlevel() { $this->autoRender = false; $this->User->recursive = 1; $fields = array('User.current_level', 'User.current_jobkind_id'); $conditions = array('User.id'=>$this->Auth->user('id')); $user = $this->User->find('first', array('fields'=>$fields, 'conditions'=>$conditions)); $data = array('level'=>0); if(!empty($user)) { $data = array( 'level' => $user['User']['current_level'], 'jobkind' => $user['User']['current_jobkind_id'], ); } $this->WebApi->sendApiResult($data); } // async data what appear jobs near checkin. function api_jobalert() { $this->autoRender = false; $this->Job->recursive = 1; $futu = strtotime('+30 minutes'); $datestr = date('Y-m-d', $futu); $timestr = date('H:i:s', $futu); $conditions = array('Job.startdate'=>$datestr, 'Job.starttime <'=>$timestr, 'Job.checkin IS NULL', 'Job.checkout IS NULL', 'Job.user_id'=>$this->Auth->user('id')); $job = $this->Job->find('first', array('conditions'=>$conditions)); $data = array('job'=>false); if(!empty($job)) { $data = array('job' => array( 'id' => $job['Job']['id'], 'userId' => $job['Job']['user_id'], 'name' => $job['Job']['name'], 'date' => $job['Job']['startdate'], 'startTime' => $job['Job']['starttime'], )); } $this->WebApi->sendApiResult($data); } // async data what appear jobs near checkout. function api_checkoutalert() { $this->autoRender = false; $this->Job->recursive = 1; $futu = strtotime('+30 minutes'); $datestr = date('Y-m-d H:i:s', $futu); $sql = 'SELECT id, name, startdate, starttime FROM jobs as Job WHERE checkin IS NOT NULL and checkout IS NULL and user_id = '.$this->Auth->user('id').' and addtime( addtime( startdate, starttime ) , jobtime ) < \''.$datestr.'\''; $job = $this->Job->query($sql); $data = array('job'=>false); if(!empty($job)) { $data = array('job' => array( 'id' => $job[0]['Job']['id'], 'userId' => $job['Job']['user_id'], 'name' => $job[0]['Job']['name'], 'date' => $job[0]['Job']['startdate'], 'startTime' => $job[0]['Job']['starttime'], )); } $this->WebApi->sendApiResult($data); } // async data what past feeds function api_tl($last_feed_id = null) { $this->autoRender = false; $this->Feed->recursive = 1; $this->Like->recursive = -1; if($last_feed_id) { $conditions = array('Feed.id <'=>intval($last_feed_id), 'Feed.user_id'=>$this->Auth->user('id')); } else { $conditions = array('Feed.user_id'=>$this->Auth->user('id')); } $order = array('Feed.id DESC'); $limit = 10; $feeds = $this->Feed->find('all', array('conditions'=>$conditions, 'order'=>$order, 'limit'=>$limit)); if(!empty($feeds)) { $data = array('feeds'=>array()); foreach($feeds as $feed) { $likesCount = $this->Like->find('count', array('conditions'=>array('Like.feed_id'=>$feed['Feed']['id']))); $commentCount = $this->Like->find('count', array('conditions'=>array('Like.feed_id'=>$feed['Feed']['id'], 'Like.message IS NOT NULL'))); $message = $feed['Feed']['message']; $row = array( 'id' => $feed['Feed']['id'], 'jobkind' => $feed['User']['current_jobkind_id'], 'level' => $feed['User']['current_level'], 'userId' => $feed['User']['id'], 'body' => $message, 'likesCount' => $likesCount, 'commentCount' => $commentCount, 'created' => $feed['Feed']['created'] ); array_push($data['feeds'], $row); } } else { $data = array('feeds'=>null); } $this->WebApi->sendApiResult($data); } // user follow a friend function api_follow($id = null) { $this->autoRender = false; $this->Friend->recursive = 0; if (!$id) { $data = array('success'=>false, 'error'=>'noid'); $this->WebApi->sendApiResult($data); return false; } // 既にフォローされているか? $followed = $this->Friend->find('first', array('conditions'=>array('Friend.user_id'=>$this->Auth->user('id'), 'Friend.friend_id'=>$id))); if(!empty($followed)) { $data = array('success'=>false, 'error'=>'alreadyfollowed', 'userid'=>$id); $this->WebApi->sendApiResult($data); return false; } // Friend データを構成 $friend = array('Friend' => array('user_id' => $this->Auth->user('id'), 'friend_id' => $id)); $this->User->create(); if ($this->User->Friend->save($friend)) { $data = array('success'=>true, 'userid'=>$id); $this->WebApi->sendApiResult($data); return true; } else { $this->WebApi->sendApiResult(null); } } // user unfollow a friend function api_unfollow($id = null) { $this->autoRender = false; if (!$id) { $data = array('success'=>false, 'error'=>'noid'); $this->WebApi->sendApiResult($data); return false; } $friend = $this->User->Friend->find('first', array('conditions'=>array('Friend.friend_id'=>$id, 'Friend.user_id'=>$this->Auth->user('id')))); if($friend) { if ($this->User->Friend->delete($friend['Friend']['id'])) { $data = array('success'=>true, 'userid'=>$id); $this->WebApi->sendApiResult($data); } return true; } $this->WebApi->sendApiResult(null); } // get all charactor data function api_getcharactors() { $this->autoRender = false; $this->Level->recursive = -1; $this->Jobkind->recursive = -1; $jobkinds = $this->Jobkind->find('all'); $levels = $this->Level->find('all', array('Order'=>array('jobkind_id', 'level'))); $data = array(); foreach($jobkinds as $jobkind) { $row = array( $jobkind['Jobkind']['code'] => array( 'name' => $jobkind['Jobkind']['name'], 'level' => array() ) ); foreach($levels as $level) { if($jobkind['Jobkind']['id'] == $level['Level']['jobkind_id']) { $cinfs = array( 'lv' => $level['Level']['level'], 'url' => $level['Level']['avator'], 'alt' => $level['Level']['name'], ); array_push($row[$jobkind['Jobkind']['code']]['level'], $cinfs); } } array_push($data, $row); } $this->WebApi->sendApiResult($data); } //*** Admin Controllers *** function admin_index() { $this->User->recursive = 0; $this->layout = 'admin'; $this->set('users', $this->paginate()); } function admin_view($id = null) { $this->layout = 'admin'; if (!$id) { $this->Session->setFlash(__('Invalid user', true)); $this->redirect(array('action' => 'index')); } $this->set('user', $this->User->read(null, $id)); } function admin_add() { $this->layout = 'admin'; if (!empty($this->data)) { $this->User->create(); if ($this->User->save($this->data)) { $this->Session->setFlash(__('The user has been saved', true)); $this->redirect(array('action' => 'index')); } else { $this->Session->setFlash(__('The user could not be saved. Please, try again.', true)); } } } function admin_edit($id = null) { $this->layout = 'admin'; if (!$id && empty($this->data)) { $this->Session->setFlash(__('Invalid user', true)); $this->redirect(array('action' => 'index')); } if (!empty($this->data)) { if ($this->User->save($this->data)) { $this->Session->setFlash(__('The user has been saved', true)); $this->redirect(array('action' => 'index')); } else { $this->Session->setFlash(__('The user could not be saved. Please, try again.', true)); } } if (empty($this->data)) { $this->data = $this->User->read(null, $id); } } function admin_delete($id = null) { if (!$id) { $this->Session->setFlash(__('Invalid id for user', true)); $this->redirect(array('action'=>'index')); } if ($this->User->delete($id)) { $this->Session->setFlash(__('User deleted', true)); $this->redirect(array('action'=>'index')); } $this->Session->setFlash(__('User was not deleted', true)); $this->redirect(array('action' => 'index')); } }
c60047b4c8234f5160465f026ef49222829f7caf
[ "JavaScript", "SQL", "HTML", "PHP" ]
39
PHP
bathtimefish/biteup
738682a3ca0e43cf9ace9aa2674051f209f1057b
ab93cfe1522782ebf48c86d9065f8de60f722cf1
refs/heads/master
<repo_name>evklein/SongFriend-Android<file_sep>/app/src/main/java/com/hasherr/songfriend/android/fragments/record/RecordMenuFragment.java package com.hasherr.songfriend.android.fragments.record; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.support.design.widget.FloatingActionButton; import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.ListView; import com.hasherr.songfriend.android.R; import com.hasherr.songfriend.android.project.PathListener; import com.hasherr.songfriend.android.ui.adapter.AudioListArrayAdapter; import com.hasherr.songfriend.android.ui.handler.DeleteDialogHandler; import com.hasherr.songfriend.android.ui.handler.ListHandler; import com.hasherr.songfriend.android.ui.listener.FloatingActionButtonListener; import com.hasherr.songfriend.android.utility.FileUtilities; /** * Created by Evan on 1/18/2016. */ public class RecordMenuFragment extends Fragment implements FloatingActionButtonListener, PathListener, ListHandler.ListHandlerListener { private Activity parentActivity; private ListHandler listHandler; private String recordingPath; private View view; @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { view = inflater.inflate(R.layout.layout_record, container, false); initPath(); initFloatingActionButton(); initListHandler(); return view; } @Override public void initPath() { recordingPath = getArguments().getString(FileUtilities.RECORDING_TAG); } @Override public void initFloatingActionButton() { FloatingActionButton floatingActionButton = (FloatingActionButton) view.findViewById(R.id.addRecordingFloatingActionButton); floatingActionButton.setBackgroundTintList(getResources().getColorStateList(R.color.logoGreen)); floatingActionButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { RecordDialogFragment recordDialogFragment = getRecordDialogFragment(); recordDialogFragment.setTargetFragment(RecordMenuFragment.this, FileUtilities.MODIFY_REQUEST_CODE); recordDialogFragment.show(getFragmentManager(), "fragment_dialog_record"); } }); } @Override public void onActivityResult(int requestCode, int resultCode, Intent data) // For refreshing with RecordDialogFragment. { super.onActivityResult(requestCode, resultCode, data); listHandler.refresh(FileUtilities.getSortedFilePathsReverse(recordingPath)); } @Override public void onAttach(Activity activity) { super.onAttach(activity); parentActivity = activity; } @Override public void initListHandler() { listHandler = new ListHandler((ListView) view.findViewById(R.id.recordingListView), new AudioListArrayAdapter(parentActivity, FileUtilities.getSortedFilePathsReverse(recordingPath))); listHandler.initListViewItemClick(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { PlayDialogFragment playDialogFragment = getPlayDialogFragment((String) parent.getItemAtPosition(position)); playDialogFragment.show(getFragmentManager(), "fragment_dialog_play"); } }); listHandler.initListViewLongItemClick(new AdapterView.OnItemLongClickListener() { @Override public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) { String itemToDelete = (String) parent.getItemAtPosition(position); DeleteDialogHandler deleteDialogHandler = new DeleteDialogHandler(); deleteDialogHandler.initialize(getActivity(), "Delete Recording", "Are you sure you want to delete this recording?", itemToDelete, recordingPath, false, listHandler); deleteDialogHandler.show(); return true; } }); } private RecordDialogFragment getRecordDialogFragment() { RecordDialogFragment recordDialogFragment = new RecordDialogFragment(); Bundle recordingInfo = new Bundle(); recordingInfo.putString(FileUtilities.RECORDING_TAG, recordingPath); recordDialogFragment.setArguments(recordingInfo); return recordDialogFragment; } private PlayDialogFragment getPlayDialogFragment(String path) { PlayDialogFragment playDialogFragment = new PlayDialogFragment(); Bundle recordingInfo = new Bundle(); recordingInfo.putString(FileUtilities.RECORDING_TAG, path); playDialogFragment.setArguments(recordingInfo); return playDialogFragment; } } <file_sep>/app/src/main/java/com/hasherr/songfriend/android/ui/handler/DeleteDialogHandler.java package com.hasherr.songfriend.android.ui.handler; import android.app.AlertDialog; import android.content.Context; import android.content.DialogInterface; import android.view.ContextThemeWrapper; import android.view.View; import com.hasherr.songfriend.android.R; import com.hasherr.songfriend.android.utility.FileUtilities; import java.io.File; /** * Created by Evan on 2/6/2016. */ public class DeleteDialogHandler { private Context context; private AlertDialog.Builder dialogBuilder; private AlertDialog dialog; private String pathOfItemToDelete; private String basePath; private ListHandler listHandler; private boolean directoryOnly; public void initialize(Context context, String title, String message, String pathOfItemToDelete, String basePath, boolean directoryOnly, ListHandler listHandler) { this.context = context; this.pathOfItemToDelete = pathOfItemToDelete; this.basePath = basePath; this.listHandler = listHandler; this.directoryOnly = directoryOnly; dialogBuilder = new AlertDialog.Builder(new ContextThemeWrapper(context, R.style.Theme_Delete)); dialogBuilder.setTitle(title); dialogBuilder.setMessage(message); setPositiveButton(); setNegativeButton(); } public void show() { dialog = dialogBuilder.show(); setDividerColor(R.color.logoGreen); } private void setPositiveButton() { dialogBuilder.setPositiveButton("Yes", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { FileUtilities.delete(new File(pathOfItemToDelete)); refreshList(); dialog.cancel(); } }); } private void setNegativeButton() { dialogBuilder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.cancel(); } }); } private void refreshList() { if (directoryOnly) listHandler.refresh(FileUtilities.getDirectoryList(basePath)); else listHandler.refresh(FileUtilities.getPathList(basePath)); } private void setDividerColor(int colorID) { int titleDividerId = context.getResources().getIdentifier("titleDivider", "id", "android"); View titleDivider = dialog.findViewById(titleDividerId); if (titleDivider != null) titleDivider.setBackgroundColor(context.getResources().getColor(colorID)); } } <file_sep>/README.md # SongFriend-Android # Song-Friend is made for songwriters and musicians who want to write and record while on the move with an intuitive, simple interface that allows for speedy composition. ### Status ### SongFriend development has been ceased due to a lack of interest in the project. There are no current plans to continue the development process as of now. ![](http://www.evklein.com/static/images/screenshots/Song-Friend/song_friend_2.png) <file_sep>/app/src/main/java/com/hasherr/songfriend/android/ui/handler/BlinkerHandler.java package com.hasherr.songfriend.android.ui.handler; import android.widget.ImageView; import com.hasherr.songfriend.android.R; /** * Created by Evan on 2/8/2016. */ public class BlinkerHandler { ImageView blinkerView; int blinkerCount; boolean isBlinkerOn; public BlinkerHandler(ImageView blinkerView) { this.blinkerView = blinkerView; blinkerCount = 1; isBlinkerOn = true; } public void manageBlinker() { blinkerCount++; if (blinkerCount >= 10) { if (isBlinkerOn) { isBlinkerOn = false; blinkerView.setBackgroundResource(R.drawable.blinker_off); } else { isBlinkerOn = true; blinkerView.setBackgroundResource(R.drawable.blinker_on); } blinkerCount = 1; } } } <file_sep>/app/src/main/java/com/hasherr/songfriend/android/fragments/lyrics/LyricMenuFragment.java package com.hasherr.songfriend.android.fragments.lyrics; import android.os.Bundle; import android.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.Button; import com.hasherr.songfriend.android.R; import com.hasherr.songfriend.android.ui.adapter.CustomDragArrayAdapter; import com.hasherr.songfriend.android.utility.FileUtilities; import com.nhaarman.listviewanimations.appearance.simple.SwingRightInAnimationAdapter; import com.nhaarman.listviewanimations.itemmanipulation.DynamicListView; import java.util.ArrayList; /** * Created by Evan on 1/18/2016. */ public class LyricMenuFragment extends Fragment { private DynamicListView dynamicListView; @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.layout_lyric, container, false); dynamicListView = (DynamicListView) view.findViewById(R.id.lyricSectionDragView); ArrayList<String> b = new ArrayList<>(); b.add("Introduction"); b.add("Chorus"); b.add("Verse"); b.add("Chorus"); b.add("Bridge"); b.add("Verse"); b.add("Chorus"); b.add("Solo"); b.add("Chorus"); CustomDragArrayAdapter a = new CustomDragArrayAdapter(getActivity(), R.layout.drag_drop_row, R.id.list_row_draganddrop_textview, b); SwingRightInAnimationAdapter animationAdapter = new SwingRightInAnimationAdapter(a); animationAdapter.setAbsListView(dynamicListView); dynamicListView.setAdapter(animationAdapter); dynamicListView.enableDragAndDrop(); dynamicListView.setOnItemLongClickListener( new AdapterView.OnItemLongClickListener() { @Override public boolean onItemLongClick(final AdapterView<?> parent, final View view, final int position, final long id) { dynamicListView.startDragging(position); return true; } }); return view; } private void initAddLyricSection(View view) { final Button addLyricSectionButton = (Button) view.findViewById(R.id.addLyricSectionButton); addLyricSectionButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { AddLyricSectionDialogFragment addLyricSectionDialogFragment = new AddLyricSectionDialogFragment(); addLyricSectionDialogFragment.setTargetFragment(LyricMenuFragment.this, FileUtilities.MODIFY_REQUEST_CODE); addLyricSectionDialogFragment.show(getFragmentManager(), "add_lyric_section_dialog_fragment"); } }); } } <file_sep>/app/src/main/java/com/hasherr/songfriend/android/ProjectActivity.java package com.hasherr.songfriend.android; import android.os.Bundle; import android.support.design.widget.TabLayout; import android.support.v4.view.ViewPager; import android.view.MenuItem; import com.hasherr.songfriend.android.ui.adapter.CustomPagerAdapter; import com.hasherr.songfriend.android.custom.ToolBarActivity; import com.hasherr.songfriend.android.utility.FileUtilities; public class ProjectActivity extends ToolBarActivity { private String projectName; private String draftName; private String lyricPath; private String recordingPath; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_project); initPath(); initToolbar(R.id.projectActivityToolbar, projectName + " - " + draftName); createDirectories(); initTabs(); } private void initTabs() { TabLayout tabLayout = (TabLayout) findViewById(R.id.projectActivityTabLayout); tabLayout.setSelectedTabIndicatorColor(getResources().getColor(R.color.logoGreen)); tabLayout.addTab(tabLayout.newTab().setText("Write")); tabLayout.addTab(tabLayout.newTab().setText("Record")); tabLayout.addTab(tabLayout.newTab().setText("Perform")); tabLayout.setTabGravity(TabLayout.GRAVITY_FILL); initViewPager(tabLayout); } private void initViewPager(TabLayout tabLayout) { final ViewPager viewPager = (ViewPager) findViewById(R.id.projectActivityViewPager); CustomPagerAdapter pagerAdapter = new CustomPagerAdapter(getSupportFragmentManager(), lyricPath, recordingPath); viewPager.setAdapter(pagerAdapter); viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout)); tabLayout.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() { @Override public void onTabSelected(TabLayout.Tab tab) { viewPager.setCurrentItem(tab.getPosition(), true); } @Override public void onTabUnselected(TabLayout.Tab tab) { } @Override public void onTabReselected(TabLayout.Tab tab) { } }); } @Override public boolean onOptionsItemSelected(MenuItem item) { finish(); return true; } @Override protected void initValues() { projectName = FileUtilities.getDirectoryAtLevel(getIntent().getExtras().getString(FileUtilities.DIRECTORY_TAG), FileUtilities.PROJECT_LEVEL); draftName = FileUtilities.getDirectoryAtLevel(getIntent().getExtras().getString(FileUtilities.DIRECTORY_TAG), FileUtilities.DRAFT_LEVEL); } @Override public void initPath() { path = getIntent().getExtras().getString(FileUtilities.DIRECTORY_TAG); } private void createDirectories() { lyricPath = path + "/lyrics"; recordingPath = path + "/recording"; FileUtilities.createDirectory(lyricPath); FileUtilities.createDirectory(recordingPath); } } <file_sep>/app/src/main/java/com/hasherr/songfriend/android/project/PathListener.java package com.hasherr.songfriend.android.project; /** * Created by evan on 2/12/16. */ public interface PathListener { void initPath(); } <file_sep>/app/src/main/java/com/hasherr/songfriend/android/custom/ToolBarActivity.java package com.hasherr.songfriend.android.custom; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import com.hasherr.songfriend.android.project.IntentManager; import com.hasherr.songfriend.android.project.PathListener; /** * Created by evan on 1/8/16. */ public abstract class ToolBarActivity extends AppCompatActivity implements PathListener { protected String path; protected IntentManager intentManager; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); intentManager = new IntentManager(); initValues(); } @Override public void onPause() { super.onPause(); overridePendingTransition(0, 0); } protected void initToolbar(int toolbarID, String toolbarMessage) { Toolbar toolbar = (Toolbar) findViewById(toolbarID); toolbar.setTitle(toolbarMessage); setSupportActionBar(toolbar); getSupportActionBar().setDisplayHomeAsUpEnabled(true); getSupportActionBar().setDisplayShowHomeEnabled(true); } protected abstract void initValues(); } <file_sep>/app/src/main/java/com/hasherr/songfriend/android/ui/listener/FloatingActionButtonListener.java package com.hasherr.songfriend.android.ui.listener; /** * Created by Evan on 2/6/2016. */ public interface FloatingActionButtonListener { void initFloatingActionButton(); } <file_sep>/app/src/main/java/com/hasherr/songfriend/android/utility/FileUtilities.java package com.hasherr.songfriend.android.utility; import android.os.Environment; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.util.*; /** * Created by Evan on 1/3/2016. */ public class FileUtilities { public final static String INTERNAL_DIRECTORY = Environment.getExternalStorageDirectory().getAbsolutePath(); public final static String PROJECT_DIRECTORY = INTERNAL_DIRECTORY + "/SongFriend"; public final static String DIRECTORY_TAG = "directory_tag"; public final static String RECORDING_TAG = "recordingPath"; public final static String MODIFY_RECORDING_TAG = "modify_recording_tag"; public final static int MODIFY_REQUEST_CODE = 7743; public final static int PROJECT_LEVEL = 1; public final static int DRAFT_LEVEL = 2; public static String getFileNameNoExtension(String fileName, String fileType) { return fileName.substring(0, fileName.indexOf("." + fileType)); } public static void delete(File itemToDelete) { if (itemToDelete.isDirectory()) { File[] allFiles = itemToDelete.listFiles(); for (File f : allFiles) { if (f.isDirectory()) delete(f); else f.delete(); } } itemToDelete.delete(); } public static void createDirectory(String path) { File directory = new File(path); if (!directory.exists()) directory.mkdir(); } public static void createDirectory(Hashtable<String, String> elements, String directoryToWriteTo) throws IOException { File directory = new File(directoryToWriteTo); directory.mkdir(); writeInfoFile(elements, directory); } // Splits a directory into pieces and then reads the particular directory at the specified level(s). public static String getDirectoryAtLevel(String directoryPath, int level) { File directoryToSearch = new File(directoryPath); String[] allDirs = directoryToSearch.getAbsolutePath().split("/"); ArrayList<String> allDirectories = new ArrayList<>(); for (String s : allDirs) allDirectories.add(s); int returnItemIndex = 0; if (level == FileUtilities.PROJECT_LEVEL) returnItemIndex = allDirectories.indexOf("SongFriend") + 1; else if (level == FileUtilities.DRAFT_LEVEL) returnItemIndex = allDirectories.indexOf("SongFriend") + 2; String directoryNameToReturn = allDirectories.get(returnItemIndex); return directoryNameToReturn; } public static void writeInfoFile(Hashtable<String, String> elements, File directoryToWriteTo) throws IOException { File infoFile = new File(directoryToWriteTo.getAbsolutePath() + "/" + elements.get("title") + ".txt"); FileOutputStream outputStream = new FileOutputStream(infoFile); byte[] indent = "\n".getBytes(); Iterator<Map.Entry<String, String>> iterator = elements.entrySet().iterator(); while (iterator.hasNext()) { String element = iterator.next().getValue(); outputStream.write(element.getBytes()); outputStream.write(indent); } outputStream.close(); } public static ArrayList<String> reverseArray(ArrayList<String> array) { Collections.reverse(array); return array; } public static ArrayList<String> getDirectoryList(String baseDirectory) { ArrayList<String> fileNames = new ArrayList<String>(); File dir = new File(baseDirectory); File[] allDirs = dir.listFiles(); for (File f : allDirs) if (f.isDirectory()) fileNames.add(f.getName()); return fileNames; } public static ArrayList<String> getFileList(String baseDirectory) { ArrayList<String> fileNames = new ArrayList<>(); File dir = new File(baseDirectory); File[] allFiles = dir.listFiles(); for (File f : allFiles) fileNames.add(f.getName()); return fileNames; } public static ArrayList<String> getPathList(String baseDirectory) { ArrayList<String> fileNames = getFileList(baseDirectory); ArrayList<String> paths = new ArrayList<>(); for (int i = 0; i < fileNames.size(); i++) paths.add(baseDirectory + "/" + fileNames.get(i)); return paths; } public static ArrayList<String> getSortedFilePaths(String path) { File[] files = new File(path).listFiles(); Arrays.sort(files, new Comparator<File>() { @Override public int compare(File f1, File f2) { return Long.valueOf(f1.lastModified()).compareTo(f2.lastModified()); } }); ArrayList<String> orderedPaths = new ArrayList<>(); for (int i = 0; i < files.length; i++) orderedPaths.add(files[i].getAbsolutePath()); return orderedPaths; } public static ArrayList<String> getSortedFilePathsReverse(String path) { return reverseArray(getSortedFilePaths(path)); } } <file_sep>/app/src/main/java/com/hasherr/songfriend/android/fragments/record/PlayDialogOnSeekBarChangeListener.java package com.hasherr.songfriend.android.fragments.record; import android.media.MediaPlayer; import android.widget.SeekBar; /** * Created by Evan on 2/12/2016. */ public class PlayDialogOnSeekBarChangeListener implements SeekBar.OnSeekBarChangeListener { private MediaPlayer mediaPlayer; public PlayDialogOnSeekBarChangeListener(MediaPlayer mediaPlayer) { this.mediaPlayer = mediaPlayer; } @Override public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) { if (mediaPlayer != null && fromUser) { mediaPlayer.seekTo(progress); } } @Override public void onStartTrackingTouch(SeekBar seekBar) { } @Override public void onStopTrackingTouch(SeekBar seekBar) { } } <file_sep>/app/src/main/java/com/hasherr/songfriend/android/ui/listener/CustomOrientationListener.java package com.hasherr.songfriend.android.ui.listener; /** * Created by Evan on 2/6/2016. */ public interface CustomOrientationListener { void setSpecifiedOrientation(); } <file_sep>/app/src/main/java/com/hasherr/songfriend/android/ui/adapter/CustomPagerAdapter.java package com.hasherr.songfriend.android.ui.adapter; import android.os.Bundle; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentPagerAdapter; import com.hasherr.songfriend.android.fragments.lyrics.LyricMenuFragment; import com.hasherr.songfriend.android.fragments.play.PerformFragment; import com.hasherr.songfriend.android.fragments.record.RecordMenuFragment; import com.hasherr.songfriend.android.utility.FileUtilities; /** * Created by Evan on 1/18/2016. */ public class CustomPagerAdapter extends FragmentPagerAdapter { private String lyricPath; private String recordingPath; public CustomPagerAdapter(FragmentManager fm, String lyricPath, String recordingPath) { super(fm); this.lyricPath = lyricPath; this.recordingPath = recordingPath; } @Override public Fragment getItem(int position) { switch (position) { case 0: return new LyricMenuFragment(); case 1: RecordMenuFragment recordMenuFragment = new RecordMenuFragment(); Bundle recordingBundle = new Bundle(); recordingBundle.putString(FileUtilities.RECORDING_TAG, recordingPath); recordMenuFragment.setArguments(recordingBundle); return recordMenuFragment; case 2: return new PerformFragment(); default: return null; } } @Override public int getCount() { return 3; } } <file_sep>/app/src/main/java/com/hasherr/songfriend/android/project/IntentManager.java package com.hasherr.songfriend.android.project; import android.content.Context; import android.content.Intent; import android.os.Bundle; /** * Created by evan on 1/8/16. */ public class IntentManager { private Bundle extrasBundle; private Intent intent; public IntentManager() { extrasBundle = new Bundle(); } public void makePathBundle(String key, String filePath) { extrasBundle.putString(key, filePath); } public Intent createIntent(Context initContext, Class newClass) { intent = new Intent(initContext, newClass); intent.putExtras(extrasBundle); return intent; } }<file_sep>/app/src/main/java/com/hasherr/songfriend/android/NewDraftActivity.java package com.hasherr.songfriend.android; import android.graphics.PorterDuff; import android.os.Bundle; import android.util.Log; import android.view.MenuItem; import android.view.View; import android.widget.ArrayAdapter; import android.widget.Spinner; import android.widget.TextView; import com.hasherr.songfriend.android.custom.CustomNewItemActivity; import com.hasherr.songfriend.android.utility.FileUtilities; import java.io.IOException; import java.util.ArrayList; public class NewDraftActivity extends CustomNewItemActivity { private String projectName; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_new_draft); initToolbar(R.id.newDraftToolbar, "New Draft - " + projectName); initSpinner(); initPath(); } @Override protected void createElements() { elements.put("title", getEditTextContents(R.id.draftTitleEditText)); elements.put("description", getEditTextContents(R.id.draftDescriptionEditText)); } @Override public void initPath() { path = FileUtilities.PROJECT_DIRECTORY + "/" + projectName + "/" + getEditTextContents(R.id.draftTitleEditText); } public void createDraft(View view) throws IOException { if (!hasErrors()) { super.createItem(view); startActivity(intentManager.createIntent(NewDraftActivity.this, ProjectActivity.class)); } } @Override public boolean onOptionsItemSelected(MenuItem item) // Handles the back arrow on the Toolbar. { finish(); return true; } @Override public boolean hasErrors() { TextView errorTextView = (TextView) findViewById(R.id.draftTitleEditText); String title = getEditTextContents(R.id.draftTitleEditText).toLowerCase(); if (title.equals("")) { errorTextView.setText("Please add a title."); return true; } Log.wtf("PATH IS ", path); ArrayList<String> allItemNames = FileUtilities.getDirectoryList(path); for (String s : allItemNames) { if (s.toLowerCase().equals(title)) { errorTextView.setText("That draft already exists."); return true; } } return false; } @Override protected void initValues() { projectName = FileUtilities.getDirectoryAtLevel(getIntent().getExtras().getString(FileUtilities.DIRECTORY_TAG), FileUtilities.PROJECT_LEVEL); } private void initSpinner() { Spinner draftSpinner = (Spinner) findViewById(R.id.draftSpinner); draftSpinner.getBackground().setColorFilter(getResources().getColor(R.color.logoGreen), PorterDuff.Mode.SRC_ATOP); // Sets spinner arrow icon to green ArrayList<String> draftArrayList = FileUtilities.getDirectoryList( FileUtilities.PROJECT_DIRECTORY + "/" + projectName); draftArrayList.add(0, "New Draft"); ArrayAdapter<String> draftArrayAdapter = new ArrayAdapter<String>(this, R.layout.spinner_element, draftArrayList); draftSpinner.setAdapter(draftArrayAdapter); } } <file_sep>/.gradle/2.4/taskArtifacts/cache.properties #Wed Feb 10 20:16:00 EST 2016 <file_sep>/app/src/main/java/com/hasherr/songfriend/android/project/Killable.java package com.hasherr.songfriend.android.project; /** * Created by evan on 1/29/16. */ public interface Killable { // For elements that need to be destroyed instantly. void kill(); }
d6115901fb06f6d58cb2479304403052f7df1b8d
[ "Markdown", "Java", "INI" ]
17
Java
evklein/SongFriend-Android
7aa4119533a82f92edc5940c1cadd00ca669ef18
4678c76d9a6050e59cbd5953b902067eb6d05c9b
refs/heads/master
<repo_name>Mohit-Patil/MoEcho<file_sep>/app/src/main/java/com/example/mohit/moecho/activities/PlayerActivity.kt package com.example.mohit.moecho.activities import android.app.ProgressDialog import android.content.Intent import android.os.Bundle import android.widget.Toast import com.example.mohit.moecho.R import com.google.android.youtube.player.YouTubeBaseActivity import com.google.android.youtube.player.YouTubeInitializationResult import com.google.android.youtube.player.YouTubePlayer import com.google.android.youtube.player.YouTubePlayer.Provider import com.google.android.youtube.player.YouTubePlayerView class PlayerActivity : YouTubeBaseActivity(), YouTubePlayer.OnInitializedListener { var youTubeView: YouTubePlayerView? = null val YOUTUBE_API_KEY = "<KEY>" var playerStateChangeListener: MyPlayerStateChangeListener? = null var playbackEventListener: MyPlaybackEventListener? = null var dialog: ProgressDialog? = null val youTubePlayerProvider: Provider? get() = youTubeView override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_player) youTubeView = findViewById(R.id.youtube_view) youTubeView!!.initialize(YOUTUBE_API_KEY, this) playerStateChangeListener = MyPlayerStateChangeListener() playbackEventListener = MyPlaybackEventListener() dialog = ProgressDialog(this) dialog?.setMessage("Please wait while the song is loading") dialog?.show() } override fun onInitializationSuccess(provider: Provider, player: YouTubePlayer, wasRestored: Boolean) { player.setPlayerStateChangeListener(playerStateChangeListener) player.setPlaybackEventListener(playbackEventListener) if (!wasRestored) { // player.play(); player.loadVideo(StepTwo.Statified.qq) dialog?.dismiss() //player.play() } } override fun onInitializationFailure(provider: Provider, errorReason: YouTubeInitializationResult) { if (errorReason.isUserRecoverableError) { errorReason.getErrorDialog(this, RECOVERY_REQUEST).show() } else { val error = String.format(getString(R.string.player_error), errorReason.toString()) //Toast.makeText(this, error, Toast.LENGTH_LONG).show() } } override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent) { if (requestCode == RECOVERY_REQUEST) { // Retry initialization if user performed a recovery action youTubePlayerProvider!!.initialize(YOUTUBE_API_KEY, this) } } fun showMessage(message: String) { Toast.makeText(this, message, Toast.LENGTH_LONG).show() } inner class MyPlaybackEventListener : YouTubePlayer.PlaybackEventListener { override fun onPlaying() { // Called when playback starts, either due to user action or call to play(). showMessage("Playing") } override fun onPaused() { // Called when playback is paused, either due to user action or call to pause(). showMessage("Paused") } override fun onStopped() { // Called when playback stops for a reason other than being paused. //L̥showMessage("Stopped") } override fun onBuffering(b: Boolean) { // Called when buffering starts or ends. } override fun onSeekTo(i: Int) { // Called when a jump in playback position occurs, either // due to user scrubbing or call to seekRelativeMillis() or seekToMillis() } } inner class MyPlayerStateChangeListener : YouTubePlayer.PlayerStateChangeListener { override fun onLoading() { // Called when the player is loading a video // At this point, it's not ready to accept commands affecting playback such as play() or pause() } override fun onLoaded(s: String) { // Called when a video is done loading. // Playback methods such as play(), pause() or seekToMillis(int) may be called after this callback. } override fun onAdStarted() { // Called when playback of an advertisement starts. } override fun onVideoStarted() { // Called when playback of the video starts. } override fun onVideoEnded() { // Called when the video reaches its end. } override fun onError(errorReason: YouTubePlayer.ErrorReason) { // Called when an error occurs. } } companion object { val RECOVERY_REQUEST = 1 } }<file_sep>/app/src/main/java/com/example/mohit/moecho/activities/StepTwo.kt package com.example.mohit.moecho.activities import android.content.Context import android.content.Intent import android.net.ConnectivityManager import android.os.Bundle import android.support.v7.app.AppCompatActivity import android.widget.Button import android.widget.EditText import android.widget.Toast import com.example.mohit.moecho.R import com.google.api.client.googleapis.json.GoogleJsonResponseException import com.google.api.client.http.HttpRequestInitializer import com.google.api.client.http.javanet.NetHttpTransport import com.google.api.client.json.jackson2.JacksonFactory import com.google.api.services.youtube.YouTube import com.google.api.services.youtube.model.SearchResult import java.io.IOException class StepTwo : AppCompatActivity() { var searchsongbutton: Button? = null var searchquery: EditText? = null internal var tosearch: String? = null internal var videoid: String? = null var qt: String? = null object Statified { var search: String? = null var qq: String? = null } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_steptwo) searchsongbutton = findViewById<Button>(R.id.searchbuttonsong) searchquery = findViewById(R.id.searchquery) searchsongbutton?.setOnClickListener { var searchquery1 = searchquery?.text.toString() Statified.search = searchquery1 if (searchquery1.isEmpty()) { searchquery?.error = "Song Name is required" searchquery?.requestFocus() } else { val manager = applicationContext .getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager val activeNetwork = manager.activeNetworkInfo if (null != activeNetwork) { if (activeNetwork.type == ConnectivityManager.TYPE_WIFI || activeNetwork.type == ConnectivityManager.TYPE_MOBILE) { qt = ytsearch(searchquery1) var clickIntent = Intent(this, PlayerActivity::class.java) //clickIntent.putExtra("videoid", qq) startActivity(clickIntent) //System.out.println("Has Connection") } } else { Toast.makeText(this, "No Internet Connection", Toast.LENGTH_SHORT).show() } } } } internal fun ytsearch(queryTerm: String): String { // Read the developer key from the properties file. val youtube: YouTube val HTTP_TRANSPORT = NetHttpTransport() val JSON_FACTORY = JacksonFactory() val NUMBER_OF_VIDEOS_RETURNED: Long = 1 try { // This object is used to make YouTube Data API requests. The last // argument is required, but since we don't need anything // initialized when the HttpRequest is initialized, we override // the interface and provide a no-op function. youtube = YouTube.Builder(HTTP_TRANSPORT, JSON_FACTORY, HttpRequestInitializer { }).setApplicationName("youtube-cmdline-search-sample").build() // Prompt the user to enter a query term. // Define the API request for retrieving search results. val search = youtube.search().list("id,snippet") // Set your developer key from the {{ Google Cloud Console }} for // non-authenticated requests. See: // {{ https://cloud.google.com/console } val apiKey = "<KEY>" search.key = apiKey search.q = queryTerm // Restrict the search results to only include videos. See: // https://developers.google.com/youtube/v3/docs/search/list#type search.type = "video" // To increase efficiency, only retrieve the fields that the // application uses. search.fields = "items(id/videoId,snippet/title,snippet/thumbnails/default/url)" search.maxResults = NUMBER_OF_VIDEOS_RETURNED // Call the API and print results. class PrimeThread : Thread() { override fun run() { try { val searchResponse = search.execute() val searchResultList = searchResponse.items if (searchResultList != null) { videoid = prettyPrint(searchResultList.iterator(), queryTerm) } } catch (e: IOException) { e.printStackTrace() } } } val p = PrimeThread() p.start() } catch (e: GoogleJsonResponseException) { System.err.println( "There was a service error: " + e.details.code + " : " + e.details.message ) } catch (e: IOException) { System.err.println("There was an IO error: " + e.cause + " : " + e.message) } catch (t: Throwable) { t.printStackTrace() } return "Qwerty" } /* * Prompt the user to enter a query term and return the user-specified term. */ /* * Prints out all results in the Iterator. For each result, print the * title, video ID, and thumbnail. * * @param iteratorSearchResults Iterator of SearchResults to print * * @param query Search query (String) */ internal fun prettyPrint(iteratorSearchResults: Iterator<SearchResult>, query: String): String { //System.out.println("\n============================================================="); //System.out.println( // " First " + NUMBER_OF_VIDEOS_RETURNED + " videos for search on \"" + query + "\"."); //System.out.println("=============================================================\n"); if (!iteratorSearchResults.hasNext()) { println(" There aren't any results for your query.") } while (iteratorSearchResults.hasNext()) { val singleVideo = iteratorSearchResults.next() val rId = singleVideo.id Statified.qq = rId.videoId // Confirm that the result represents a video. Otherwise, the // item will not contain a video ID. } return "Despacito" } }<file_sep>/README.md # MoEcho Submission for a project for www.internshala.com <file_sep>/app/src/main/java/com/example/mohit/moecho/activities/SplashActivity.kt package com.example.mohit.moecho.activities import android.Manifest import android.content.Context import android.content.Intent import android.content.pm.PackageManager <<<<<<< HEAD ======= import android.os.Build import android.support.v7.app.AppCompatActivity >>>>>>> master import android.os.Bundle import android.os.Handler import android.support.annotation.RequiresApi import android.support.v4.app.ActivityCompat import android.support.v7.app.AppCompatActivity import android.widget.Toast import com.example.mohit.moecho.R class SplashActivity : AppCompatActivity() { @RequiresApi(Build.VERSION_CODES.JELLY_BEAN) private var permissionsString = arrayOf( Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.MODIFY_AUDIO_SETTINGS, Manifest.permission.READ_PHONE_STATE, Manifest.permission.PROCESS_OUTGOING_CALLS, Manifest.permission.RECORD_AUDIO ) @RequiresApi(Build.VERSION_CODES.JELLY_BEAN) override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_splash) if (!hasPermissions(this@SplashActivity, *permissionsString)) { //We have to Ask for Permissions ActivityCompat.requestPermissions(this@SplashActivity, permissionsString, 131) } else { Handlr(this@SplashActivity) } } override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<out String>, grantResults: IntArray) { super.onRequestPermissionsResult(requestCode, permissions, grantResults) when (requestCode) { 131 -> { if (grantResults.isNotEmpty() && grantResults[0] == PackageManager.PERMISSION_GRANTED && grantResults[0] == PackageManager.PERMISSION_GRANTED && grantResults[0] == PackageManager.PERMISSION_GRANTED && grantResults[0] == PackageManager.PERMISSION_GRANTED && grantResults[0] == PackageManager.PERMISSION_GRANTED ) { Handlr(this@SplashActivity) } else { Toast.makeText(this@SplashActivity, "Please Grant All the Permissions", Toast.LENGTH_SHORT).show() this.finish() } return } else -> { Toast.makeText(this@SplashActivity, "Something went Wrong", Toast.LENGTH_SHORT).show() this.finish() return } } } private fun hasPermissions(context: Context, vararg permissions: String): Boolean { var hasAllpermisiions = true for (permission in permissions) { val res = context.checkCallingOrSelfPermission(permission) if (res != PackageManager.PERMISSION_GRANTED) { hasAllpermisiions = false } } return hasAllpermisiions } fun Handlr(context: Context) { Handler().postDelayed({ val startAct = Intent(this@SplashActivity, MainActivity::class.java) startActivity(startAct) this.finish() }, 1000) } } <file_sep>/app/src/main/java/com/example/mohit/moecho/databases/EchoDatabase.kt package com.example.mohit.moecho.databases import android.content.ContentValues import android.content.Context import android.database.sqlite.SQLiteDatabase import android.database.sqlite.SQLiteOpenHelper <<<<<<< HEAD import com.example.mohit.moecho.resources.songs ======= import com.example.mohit.moecho.Songs import java.lang.Exception >>>>>>> master class EchoDatabase : SQLiteOpenHelper { private var _songList = ArrayList<Songs>() object Staticated { var DB_VERSION = 1 const val DB_NAME = "FavoriteDatabase" const val TABLE_NAME = "FavoriteTable" const val COLUMN_ID = "SongId" const val COLUMN_SONG_TITLE = "SongTitle" const val COLUMN_SONG_ARTIST = "SongArtist" const val COLUMN_SONG_PATH = "SongPath" } constructor(context: Context?, name: String?, factory: SQLiteDatabase.CursorFactory?, version: Int) : super( context, name, factory, version ) constructor(context: Context?) : super( context, Staticated.DB_NAME, null, Staticated.DB_VERSION ) override fun onCreate(sqLiteDatabase: SQLiteDatabase?) { <<<<<<< HEAD sqLiteDatabase?.execSQL("CREATE TABLE " + Staticated.TABLE_NAME + "(" + Staticated.COLUMN_ID + " INTEGER," + Staticated.COLUMN_SONG_ARTIST + " TEXT," + Staticated.COLUMN_SONG_TITLE + " TEXT," + Staticated.COLUMN_SONG_PATH + " TEXT);") ======= sqLiteDatabase?.execSQL("CREATE TABLE " + Staticated.TABLE_NAME + "(" + Staticated.COLUMN_ID + " INTEGER," + Staticated.COLUMN_SONG_ARTIST + " STRING," + Staticated.COLUMN_SONG_TITLE + " STRING," + Staticated.COLUMN_SONG_PATH + " STRING);") >>>>>>> master } override fun onUpgrade(db: SQLiteDatabase?, oldVersion: Int, newVersion: Int) { } fun storeAsFavourite(id: Int?, artist: String?, songTitle: String?, path: String?) { val db = this.writableDatabase val contentValues = ContentValues() contentValues.put(Staticated.COLUMN_ID, id) contentValues.put(Staticated.COLUMN_SONG_ARTIST, artist) contentValues.put(Staticated.COLUMN_SONG_TITLE, songTitle) contentValues.put(Staticated.COLUMN_SONG_PATH, path) db.insert(Staticated.TABLE_NAME, null, contentValues) db.close() } fun queryDBList(): ArrayList<Songs>? { try { val db = this.readableDatabase val queryparams = "SELECT * FROM " + Staticated.TABLE_NAME val cSor = db.rawQuery(queryparams, null) if (cSor.moveToFirst()) { do { var _id = cSor.getInt(cSor.getColumnIndexOrThrow(Staticated.COLUMN_ID)) var _artist = cSor.getString(cSor.getColumnIndexOrThrow(Staticated.COLUMN_SONG_ARTIST)) var _title = cSor.getString(cSor.getColumnIndexOrThrow(Staticated.COLUMN_SONG_TITLE)) var _songPath = cSor.getString(cSor.getColumnIndexOrThrow(Staticated.COLUMN_SONG_PATH)) _songList.add(Songs(_id.toLong(), _title, _artist, _songPath, 0)) } while (cSor.moveToNext()) } else { db.close() return null } db.close() cSor.close() } catch (e: Exception) { e.printStackTrace() } return _songList } fun checkifIdExists(_id: Int): Boolean { var storeId = -1090 val db = this.readableDatabase val query_params = "SELECT * FROM " + Staticated.TABLE_NAME + " WHERE SongId = '$_id'" val cSor = db.rawQuery(query_params, null) if (cSor.moveToFirst()) { do { storeId = cSor.getInt(cSor.getColumnIndexOrThrow(Staticated.COLUMN_ID)) } while (cSor.moveToNext()) } else { db.close() return false } cSor.close() db.close() cSor.close() return storeId != -1090 } fun deleteFavorite(_id: Int) { val db = this.writableDatabase db.delete(Staticated.TABLE_NAME, Staticated.COLUMN_ID + "=" + _id, null) db.close() } fun checkSize(): Int { var counter = 0 val db = this.readableDatabase val query_params = "SELECT * FROM " + Staticated.TABLE_NAME val cSor = db.rawQuery(query_params, null) if (cSor.moveToFirst()) { do { counter += 1 } while (cSor.moveToNext()) } else { db.close() return 0 } cSor.close() db.close() cSor.close() return counter } }<file_sep>/app/src/main/java/com/example/mohit/moecho/fragments/MainScreenFragment.kt package com.example.mohit.moecho.fragments import android.annotation.SuppressLint import android.app.Activity import android.content.Context import android.media.MediaPlayer import android.os.Bundle import android.provider.MediaStore import android.support.v4.app.Fragment import android.support.v7.widget.DefaultItemAnimator import android.support.v7.widget.LinearLayoutManager import android.support.v7.widget.RecyclerView import android.support.v7.widget.SearchView import android.view.* import android.widget.ImageButton import android.widget.RelativeLayout import android.widget.TextView import com.example.mohit.moecho.R import com.example.mohit.moecho.adapters.MainScreenAdapter <<<<<<< HEAD import com.example.mohit.moecho.fragments.MainScreenFragment.Statified.playPauseButton import com.example.mohit.moecho.resources.songs ======= import com.example.mohit.moecho.Songs >>>>>>> master import kotlinx.android.synthetic.main.fragment_main_screen.* import java.util.* <<<<<<< HEAD ======= import android.view.ViewGroup import com.example.mohit.moecho.fragments.MainScreenFragment.Statified.playPauseButton >>>>>>> master class MainScreenFragment : Fragment() { var getSongsList: ArrayList<Songs>? = null var nowPlayingBottomBar: RelativeLayout? = null var songTitle: TextView? = null var visibleLayout: RelativeLayout? = null var noSongs: TextView? = null var recyclerView: RecyclerView? = null var myActivity: Activity? = null var _mainScreenAdapter: MainScreenAdapter? = null var trackPosition: Int = 0 <<<<<<< HEAD var flag = 0 ======= private val BACK_STACK_ROOT_TAG = "main_fragment" >>>>>>> master @SuppressLint("StaticFieldLeak") object Statified { var mediaPlayer: MediaPlayer? = null var sizeofarr: Int? = null <<<<<<< HEAD @SuppressLint("StaticFieldLeak") ======= >>>>>>> master var playPauseButton: ImageButton? = null } override fun onAttach(context: Context?) { super.onAttach(context) myActivity = context as Activity } override fun onAttach(activity: Activity?) { super.onAttach(activity) myActivity = activity } override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { val view = inflater.inflate(R.layout.fragment_main_screen, container, false) setHasOptionsMenu(true) activity?.title = "All Songs" visibleLayout = view?.findViewById<RelativeLayout>(R.id.visibleLayout) noSongs = view?.findViewById(R.id.nosongs) nowPlayingBottomBar = view?.findViewById(R.id.hiddenbarmainscreen) songTitle = view?.findViewById<TextView>(R.id.songTitleMainScreen) songTitle?.isSelected = true playPauseButton = view?.findViewById<ImageButton>(R.id.playpausebutton) recyclerView = view?.findViewById<RecyclerView>(R.id.contentMain) SongPlayingFragment.Statified.mediaplayer?.setOnCompletionListener { SongPlayingFragment.Staticated.onSongComplete() songTitle?.text = SongPlayingFragment.Statified.currentSongHelper?.songTitle _mainScreenAdapter?.notifyDataSetChanged() } return view } override fun onCreateOptionsMenu(menu: Menu?, inflater: MenuInflater?) { menu?.clear() inflater?.inflate(R.menu.main, menu) val searchItem = menu?.findItem(R.id.search) val searchView = searchItem?.actionView as SearchView searchView.queryHint = "Search Song or Artist" searchView.setOnQueryTextListener(object : SearchView.OnQueryTextListener { @SuppressLint("SyntheticAccessor") override fun onQueryTextChange(query: String): Boolean { flag = 1 var name_to_saerch = query.toLowerCase() var newList: ArrayList<songs>? = ArrayList<songs>() for (songs in getSongsList!!) { var name = songs.songTitle.toLowerCase() var artist = songs.artist.toLowerCase() if (name.contains(name_to_saerch, true)) newList?.add(songs) else if (artist.contains(name_to_saerch, true)) newList?.add(songs) } _mainScreenAdapter?.filter_data(newList) return true } override fun onQueryTextSubmit(query: String): Boolean { return true } }) return } override fun onActivityCreated(savedInstanceState: Bundle?) { super.onActivityCreated(savedInstanceState) getSongsList = getSongsFromPhone() val mLayoutManager = LinearLayoutManager(myActivity) val prefs = activity?.getSharedPreferences("action_sort", Context.MODE_PRIVATE) val action_sort_ascending = prefs?.getString("action_sort_ascending", "true") val action_sort_recent = prefs?.getString("action_sort_recent", "false") if (SongPlayingFragment.Statified?.mediaplayer?.isPlaying == null || SongPlayingFragment.Statified?.mediaplayer?.isPlaying == false) { hiddenbarmainscreen?.layoutParams?.height = 0 visibleLayout?.layoutParams?.height = -2 } if (Statified.sizeofarr == 0) { visibleLayout?.visibility = View.INVISIBLE noSongs?.visibility = View.VISIBLE } else { _mainScreenAdapter = MainScreenAdapter(getSongsList as ArrayList<Songs>, myActivity as Context) recyclerView?.layoutManager = mLayoutManager recyclerView?.itemAnimator = DefaultItemAnimator() recyclerView?.adapter = _mainScreenAdapter } if (getSongsList != null) { if (action_sort_ascending!!.equals("true", true)) { Collections.sort(getSongsList, Songs.Statified.nameComparator) _mainScreenAdapter?.notifyDataSetChanged() } else if (action_sort_recent!!.equals("true", true)) { Collections.sort(getSongsList, Songs.Statified.dateComparator) _mainScreenAdapter?.notifyDataSetChanged() } } if (SongPlayingFragment.Statified?.currentSongHelper?.isPlaying == true) { bottomBarSetup() } } override fun onOptionsItemSelected(item: MenuItem?): Boolean { val switcher = item?.itemId if (switcher == R.id.action_sort_ascending) { val editor = myActivity?.getSharedPreferences("action_sort", Context.MODE_PRIVATE)?.edit() editor?.putString("action_sort_ascending", "true") editor?.putString("action_sort_recent", "false") editor?.apply() if (getSongsList != null) { Collections.sort(getSongsList, Songs.Statified.nameComparator) } _mainScreenAdapter?.notifyDataSetChanged() return false } else if (switcher == R.id.action_sort_recent) { val editor = myActivity?.getSharedPreferences("action_sort", Context.MODE_PRIVATE)?.edit() editor?.putString("action_sort_ascending", "false") editor?.putString("action_sort_recent", "true") editor?.apply() if (getSongsList != null) { Collections.sort(getSongsList, Songs.Statified.dateComparator) } _mainScreenAdapter?.notifyDataSetChanged() return false } return super.onOptionsItemSelected(item) } <<<<<<< HEAD fun getSongsFromPhone(): ArrayList<songs> { var arrayList = ArrayList<songs>() ======= override fun onAttach(context: Context?) { super.onAttach(context) myActivity = context as Activity } override fun onAttach(activity: Activity?) { super.onAttach(activity) myActivity = activity } fun getSongsFromPhone(): ArrayList<Songs> { var arrayList = ArrayList<Songs>() >>>>>>> master var contentResolver = myActivity?.contentResolver var songuri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI var songCursor = contentResolver?.query(songuri, null, null, null, null) if (songCursor != null && songCursor.moveToFirst()) { val songId = songCursor.getColumnIndex(MediaStore.Audio.Media._ID) val songTitle = songCursor.getColumnIndex(MediaStore.Audio.Media.TITLE) val songArtist = songCursor.getColumnIndex(MediaStore.Audio.Media.ARTIST) val songData = songCursor.getColumnIndex(MediaStore.Audio.Media.DATA) val dateIndex = songCursor.getColumnIndex(MediaStore.Audio.Media.DATE_ADDED) while (songCursor.moveToNext()) { var currentId = songCursor.getLong(songId) var currentTitle = songCursor.getString(songTitle) var currentArtist = songCursor.getString(songArtist) var currentData = songCursor.getString(songData) var currentDate = songCursor.getLong(dateIndex) <<<<<<< HEAD arrayList.add( songs( currentId, currentTitle, currentArtist, currentData, currentDate ) ) ======= arrayList.add(Songs(currentId, currentTitle, currentArtist, currentData, currentDate)) >>>>>>> master } } songCursor?.close() Statified.sizeofarr = arrayList.size return arrayList } fun bottomBarSetup() { try { bottomBarClickHandler() songTitle?.text = SongPlayingFragment.Statified.currentSongHelper?.songTitle if (SongPlayingFragment.Statified.mediaplayer?.isPlaying as Boolean) { nowPlayingBottomBar?.visibility = View.VISIBLE } else { nowPlayingBottomBar?.visibility = View.INVISIBLE } } catch (e: Exception) { e.printStackTrace() } } fun bottomBarClickHandler() { nowPlayingBottomBar?.setOnClickListener({ MainScreenFragment.Statified.mediaPlayer = SongPlayingFragment.Statified.mediaplayer val songPlayingFragment = SongPlayingFragment() var args = Bundle() args.putString("songArtist", SongPlayingFragment.Statified.currentSongHelper?.songArtist) args.putString("path", SongPlayingFragment.Statified.currentSongHelper?.songPath) args.putString("songTitle", SongPlayingFragment.Statified.currentSongHelper?.songTitle) args.putInt("SongId", SongPlayingFragment.Statified.currentSongHelper?.songId?.toInt() as Int) args.putInt( "songPosition", SongPlayingFragment.Statified.currentSongHelper?.currentPosition?.toInt() as Int ) args.putParcelableArrayList("songData", SongPlayingFragment.Statified.fetchSongs) args.putString("MainBottomBar", "success") songPlayingFragment.arguments = args fragmentManager?.popBackStackImmediate() fragmentManager!!.beginTransaction() .replace(R.id.details_fragment, songPlayingFragment) .addToBackStack("MainScreen") .commit() }) playPauseButton?.setOnClickListener({ if (SongPlayingFragment.Statified.mediaplayer?.isPlaying as Boolean) { SongPlayingFragment.Statified.mediaplayer?.pause() playPauseButton?.setBackgroundResource(R.drawable.play_icon) trackPosition = SongPlayingFragment.Statified.mediaplayer?.currentPosition as Int } else { SongPlayingFragment.Statified.mediaplayer?.seekTo(trackPosition) SongPlayingFragment.Statified.mediaplayer?.start() playPauseButton?.setBackgroundResource(R.drawable.pause_icon) } }) } } <file_sep>/app/src/main/java/com/example/mohit/moecho/utils/CaptureBroadcast.kt package com.example.mohit.moecho.utils import android.app.Service import android.content.BroadcastReceiver import android.content.Context import android.content.Intent import android.telephony.TelephonyManager import com.example.mohit.moecho.R <<<<<<< HEAD ======= import com.example.mohit.moecho.activities.MainActivity import com.example.mohit.moecho.fragments.FavouriteFragment import com.example.mohit.moecho.fragments.MainScreenFragment >>>>>>> master import com.example.mohit.moecho.fragments.SongPlayingFragment class CaptureBroadcast : BroadcastReceiver() { override fun onReceive(context: Context?, intent: Intent?) { if (intent?.action == Intent.ACTION_NEW_OUTGOING_CALL) { try { NotificationBuilder.Statified.notificationManager?.cancel(1998) } catch (e: Exception) { e.printStackTrace() } try { if (SongPlayingFragment.Statified.mediaplayer?.isPlaying as Boolean) { SongPlayingFragment.Statified.mediaplayer?.pause() SongPlayingFragment.Statified.playpauseImageButton?.setBackgroundResource(R.drawable.play_icon) } } catch (e: Exception) { e.printStackTrace() } } else if (intent?.action == android.media.AudioManager.ACTION_AUDIO_BECOMING_NOISY) { try { if (SongPlayingFragment.Statified.mediaplayer?.isPlaying as Boolean) { SongPlayingFragment.Statified.playing = true SongPlayingFragment.Statified.mediaplayer?.pause() SongPlayingFragment.Statified.playpauseImageButton?.setBackgroundResource(R.drawable.play_icon) } } catch (e: Exception) { e.printStackTrace() } } else if (intent?.action == android.media.AudioManager.ACTION_AUDIO_BECOMING_NOISY) { try { if (SongPlayingFragment.Statified.mediaplayer?.isPlaying as Boolean) { SongPlayingFragment.Statified.playing = true SongPlayingFragment.Statified.mediaplayer?.pause() SongPlayingFragment.Statified.playpauseImageButton?.setBackgroundResource(R.drawable.play_icon) } } catch (e: Exception) { e.printStackTrace() } } else { val tm: TelephonyManager = context?.getSystemService(Service.TELEPHONY_SERVICE) as TelephonyManager when (tm.callState) { TelephonyManager.CALL_STATE_RINGING -> { try { NotificationBuilder.Statified.notificationManager?.cancel(1998) } catch (e: Exception) { e.printStackTrace() } try { if (SongPlayingFragment.Statified.mediaplayer?.isPlaying as Boolean) { SongPlayingFragment.Statified.mediaplayer?.pause() SongPlayingFragment.Statified.playing = true SongPlayingFragment.Statified.playpauseImageButton?.setBackgroundResource(R.drawable.play_icon) MainScreenFragment.Statified.playPauseButton?.setBackgroundResource(R.drawable.play_icon) FavouriteFragment.Statified.playPauseButton?.setBackgroundResource(R.drawable.play_icon) } } catch (e: Exception) { e.printStackTrace() } } TelephonyManager.CALL_STATE_IDLE -> { // not in call try { if (SongPlayingFragment.Statified.mediaplayer?.isPlaying as Boolean == false && SongPlayingFragment.Statified.playing) { SongPlayingFragment.Statified.mediaplayer?.start() SongPlayingFragment.Statified.playing = false SongPlayingFragment.Statified.playpauseImageButton?.setBackgroundResource(R.drawable.pause_icon) } } catch (e: Exception) { e.printStackTrace() } } else -> { } } } } }<file_sep>/app/src/main/java/com/example/mohit/moecho/Songs.kt package com.example.mohit.moecho.resources import android.annotation.SuppressLint import android.os.Parcel import android.os.Parcelable @SuppressLint("ParcelCreator") <<<<<<<< HEAD:app/src/main/java/com/example/mohit/moecho/resources/songs.kt class songs(var songID: Long, var songTitle: String, var artist: String, var songData: String, var dateAdded: Long) : ======== class Songs(var songID: Long, var songTitle: String, var artist: String, var songData: String, var dateAdded: Long) : >>>>>>>> master:app/src/main/java/com/example/mohit/moecho/Songs.kt Parcelable { override fun writeToParcel(dest: Parcel?, flags: Int) { } override fun describeContents(): Int { TODO("not implemented") //To change body of created functions use File | Settings | File Templates. } object Statified { <<<<<<<< HEAD:app/src/main/java/com/example/mohit/moecho/resources/songs.kt var nameComparator: Comparator<songs> = Comparator<songs> { song1, song2 -> ======== var nameComparator: Comparator<Songs> = Comparator { song1, song2 -> >>>>>>>> master:app/src/main/java/com/example/mohit/moecho/Songs.kt val songOne = song1.songTitle.toUpperCase() val songTwo = song2.songTitle.toUpperCase() songOne.compareTo(songTwo) } <<<<<<<< HEAD:app/src/main/java/com/example/mohit/moecho/resources/songs.kt var dateComparator: Comparator<songs> = Comparator<songs> { song1, song2 -> ======== var dateComparator: Comparator<Songs> = Comparator { song1, song2 -> >>>>>>>> master:app/src/main/java/com/example/mohit/moecho/Songs.kt val songOne = song1.dateAdded.toDouble() val songTwo = song2.dateAdded.toDouble() songTwo.compareTo(songOne) } } }<file_sep>/app/src/main/java/com/example/mohit/moecho/fragments/AboutUsFragment.kt package com.example.mohit.moecho.fragments import android.os.Bundle import android.support.v4.app.Fragment import android.view.* import com.example.mohit.moecho.R class AboutUsFragment : Fragment() { override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { activity?.title = "About Me" return inflater.inflate(R.layout.fragment_about_us, container, false) } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setHasOptionsMenu(true) } override fun onPrepareOptionsMenu(menu: Menu?) { super.onPrepareOptionsMenu(menu) val item: MenuItem? = menu?.findItem(R.id.action_sort) val searchItem = menu?.findItem(R.id.search) item?.isVisible = false searchItem?.isVisible = false } }<file_sep>/app/src/main/java/com/example/mohit/moecho/activities/StepOne.kt package com.example.mohit.moecho.activities import android.content.Context import android.content.Intent import android.net.ConnectivityManager import android.os.Bundle import android.support.v7.app.AppCompatActivity import android.widget.Button import android.widget.Toast import com.example.mohit.moecho.R class StepOne : AppCompatActivity() { var steponenext: Button? = null override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_stepone) steponenext = findViewById(R.id.steponenext) steponenext?.setOnClickListener { val manager = applicationContext .getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager val activeNetwork = manager.activeNetworkInfo if (null != activeNetwork) { if (activeNetwork.type == ConnectivityManager.TYPE_WIFI) { var clickIntent = Intent(this@StepOne, StepTwo::class.java) startActivity(clickIntent) System.out.println("Has Connection") } if (activeNetwork.type == ConnectivityManager.TYPE_MOBILE) { var clickIntent = Intent(this@StepOne, StepTwo::class.java) startActivity(clickIntent) System.out.println("Has Connection") } } else { Toast.makeText(this, "No Internet Connection", Toast.LENGTH_SHORT).show() } } } }<file_sep>/app/src/main/java/com/example/mohit/moecho/activities/MainActivity.kt package com.example.mohit.moecho.activities import android.annotation.SuppressLint import android.app.Notification import android.app.NotificationChannel import android.app.NotificationManager import android.content.Context import android.content.Intent import android.os.Build import android.os.Bundle import android.support.annotation.RequiresApi import android.support.v4.widget.DrawerLayout import android.support.v7.app.ActionBarDrawerToggle import android.support.v7.app.AppCompatActivity import android.support.v7.widget.DefaultItemAnimator import android.support.v7.widget.LinearLayoutManager import android.support.v7.widget.RecyclerView import android.support.v7.widget.Toolbar import android.widget.Button import com.example.mohit.moecho.R import com.example.mohit.moecho.activities.MainActivity.Statified.notificationManager import com.example.mohit.moecho.adapters.NavigationDrawerAdapter import com.example.mohit.moecho.fragments.FavouriteFragment import com.example.mohit.moecho.fragments.MainScreenFragment import com.example.mohit.moecho.fragments.SongPlayingFragment import com.example.mohit.moecho.utils.NotificationBuilder class MainActivity : AppCompatActivity() { @SuppressLint("SyntheticAccessor") var navigationDrawerIconsList: ArrayList<String> = arrayListOf() var imagesForNavdrawer = intArrayOf( R.drawable.navigation_allsongs, R.drawable.navigation_favorites, R.drawable.navigation_settings, R.drawable.navigation_aboutus ) var buttonplayer: Button? = null var trackNotificationBuilder: Notification? = null var notificationChannel: NotificationChannel? = null var channelId = "com.example.mohit.moecho.activities" var description = "Song Playing Notification" @SuppressLint("StaticFieldLeak") object Statified { @SuppressLint("StaticFieldLeak") var drawerLayout: DrawerLayout? = null var notificationManager: NotificationManager? = null var IS_MUSIC_SCREEN_MAIN = false } @RequiresApi(Build.VERSION_CODES.JELLY_BEAN) override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) val toolbar = findViewById<Toolbar>(R.id.toolbar) setSupportActionBar(toolbar) Statified.drawerLayout = findViewById(R.id.drawer_layout) buttonplayer = findViewById<Button>(R.id.buttonplayer) buttonplayer?.setOnClickListener { try { if (SongPlayingFragment.Statified.currentSongHelper?.isPlaying as Boolean) { SongPlayingFragment.Statified.mediaplayer?.pause() MainScreenFragment.Statified.playPauseButton?.setBackgroundResource(R.drawable.play_icon) FavouriteFragment.Statified.playPauseButton?.setBackgroundResource(R.drawable.play_icon) SongPlayingFragment.Statified.playpauseImageButton?.setBackgroundResource(R.drawable.play_icon) } } catch (e: java.lang.Exception) { e.printStackTrace() } var clickIntent = Intent(this@MainActivity, StepOne::class.java) startActivity(clickIntent) } navigationDrawerIconsList.add("All Songs") navigationDrawerIconsList.add("Favorites") navigationDrawerIconsList.add("Settings") navigationDrawerIconsList.add("About Me") val toggle = ActionBarDrawerToggle( this@MainActivity, Statified.drawerLayout, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close ) Statified.drawerLayout?.addDrawerListener(toggle) toggle.syncState() val mainScreenFragment = MainScreenFragment() this.supportFragmentManager .beginTransaction() .replace(R.id.details_fragment, mainScreenFragment, "MainScreenFragment") .commit() val _navigationAdapter = NavigationDrawerAdapter(navigationDrawerIconsList, imagesForNavdrawer, this) _navigationAdapter.notifyDataSetChanged() val navigation_recycler_view = findViewById<RecyclerView>(R.id.navigationrecyclerview) navigation_recycler_view.layoutManager = LinearLayoutManager(this) navigation_recycler_view.itemAnimator = DefaultItemAnimator() navigation_recycler_view.adapter = _navigationAdapter navigation_recycler_view.setHasFixedSize(true) notificationManager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager /*if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { notificationChannel = NotificationChannel(channelId, description, NotificationManager.IMPORTANCE_HIGH) notificationManager?.createNotificationChannel(notificationChannel as NotificationChannel) trackNotificationBuilder = Notification.Builder(this, channelId) .setContentTitle("A track is playing in the background") .setSmallIcon(R.drawable.echo_logo) .setContentIntent(pintent) .setOngoing(true) .setAutoCancel(true) .build() } else { trackNotificationBuilder = Notification.Builder(this) .setContentTitle("A track is playing in the background") .setSmallIcon(R.drawable.echo_logo) .setContentIntent(pintent) .setOngoing(true) .setAutoCancel(true) .build() }*/ } override fun onStart() { super.onStart() try { NotificationBuilder.Statified.notificationManager?.cancel(1998) } catch (e: Exception) { e.printStackTrace() } } override fun onStop() { super.onStop() try { if (SongPlayingFragment.Statified.mediaplayer?.isPlaying as Boolean) { val intentnotif = Intent(applicationContext, NotificationBuilder::class.java) intentnotif.action = NotificationBuilder().ACTION_PLAY startService(intentnotif) } } catch (e: Exception) { e.printStackTrace() } } override fun onResume() { super.onResume() try { NotificationBuilder.Statified?.notificationManager?.cancel(1998) } catch (e: Exception) { e.printStackTrace() } } override fun onDestroy() { try { if (SongPlayingFragment.Statified.mediaplayer?.isPlaying as Boolean) { NotificationBuilder.Statified.notificationManager?.notify(1998, trackNotificationBuilder) } } catch (e: Exception) { e.printStackTrace() } super.onDestroy() } } <file_sep>/app/src/main/java/com/example/mohit/moecho/utils/NotificationBuilder.kt package com.example.mohit.moecho.utils import android.annotation.SuppressLint import android.app.NotificationChannel import android.app.NotificationManager import android.app.PendingIntent import android.app.Service import android.content.Context import android.content.Intent import android.graphics.Color import android.media.session.MediaController import android.media.session.MediaSession import android.media.session.MediaSessionManager import android.os.Build import android.os.IBinder import android.support.v4.app.NotificationCompat import android.util.Log import com.example.mohit.moecho.R import com.example.mohit.moecho.activities.MainActivity import com.example.mohit.moecho.fragments.SongPlayingFragment class NotificationBuilder : Service() { override fun onBind(intent: Intent?): IBinder? { TODO("not implemented") //To change body of created functions use File | Settings | File Templates. } val ACTION_PLAY = "action_play" val ACTION_PAUSE = "action_pause" val ACTION_REWIND = "action_rewind" val ACTION_FAST_FORWARD = "action_fast_foward" val ACTION_NEXT = "action_next" val ACTION_PREVIOUS = "action_previous" val ACTION_STOP = "action_stop" val mManager: MediaSessionManager? = null var mSession: MediaSession? = null var mController: MediaController? = null var channelId = "com.example.mohit.moecho.activities" var builder: NotificationCompat.Builder? = null object Statified { var notificationManager: NotificationManager? = null } fun handleIntent(intent: Intent?) { if (intent == null || intent.action == null) return val action = intent.action if (action!!.equals(ACTION_PLAY, ignoreCase = true)) { mController?.transportControls?.play() } else if (action.equals(ACTION_PAUSE, ignoreCase = true)) { mController?.transportControls?.pause() } else if (action.equals(ACTION_FAST_FORWARD, ignoreCase = true)) { mController?.transportControls?.fastForward() } else if (action.equals(ACTION_REWIND, ignoreCase = true)) { mController?.transportControls?.rewind() } else if (action.equals(ACTION_PREVIOUS, ignoreCase = true)) { mController?.transportControls?.skipToPrevious() } else if (action.equals(ACTION_NEXT, ignoreCase = true)) { mController?.transportControls?.skipToNext() } else if (action.equals(ACTION_STOP, ignoreCase = true)) { mController?.transportControls?.stop() } } override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int { if (mManager == null) { initMediaSessions() } try { handleIntent(intent) } catch (e: Exception) { e.printStackTrace() } return super.onStartCommand(intent, flags, startId) } fun initMediaSessions() { mSession = MediaSession(applicationContext, "simple player session") mController = MediaController(applicationContext, mSession!!.sessionToken) mSession!!.setCallback(object : MediaSession.Callback() { override fun onPlay() { super.onPlay() SongPlayingFragment.Statified.mediaplayer?.start() SongPlayingFragment.Statified.currentSongHelper?.isPlaying = true SongPlayingFragment.Statified.playpauseImageButton?.setBackgroundResource(R.drawable.pause_icon) Log.e("NotificationBuilder", "onPlay") buildNotification(generateAction(android.R.drawable.ic_media_pause, "Pause", ACTION_PAUSE)) } override fun onPause() { super.onPause() SongPlayingFragment.Statified.mediaplayer?.pause() SongPlayingFragment.Statified.currentSongHelper?.isPlaying = false SongPlayingFragment.Statified.playpauseImageButton?.setBackgroundResource(R.drawable.play_icon) Log.e("NotificationBuilder", "onPause") buildNotification(generateAction(android.R.drawable.ic_media_play, "Play", ACTION_PLAY)) } override fun onSkipToNext() { super.onSkipToNext() Log.e("NotificationBuilder", "onSkipToNext") SongPlayingFragment.Statified.currentSongHelper?.isPlaying = true if (SongPlayingFragment.Statified.currentSongHelper?.isshuffle as Boolean) { SongPlayingFragment.Staticated.playNext("PlayNextLikeNormalShuffle") } else { SongPlayingFragment.Staticated.playNext("PlayNextNormal") } buildNotification(generateAction(android.R.drawable.ic_media_pause, "Pause", ACTION_PAUSE)) } override fun onSkipToPrevious() { super.onSkipToPrevious() Log.e("NotificationBuilder", "onSkipToPrevious") SongPlayingFragment.Statified.currentSongHelper?.isPlaying = true SongPlayingFragment.Staticated.playPrevious() buildNotification(generateAction(android.R.drawable.ic_media_pause, "Pause", ACTION_PAUSE)) } override fun onStop() { super.onStop() Log.e("NotificationBuilder", "onStop") val notificationManager = applicationContext.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager notificationManager.cancel(1) val intent = Intent(applicationContext, NotificationBuilder::class.java) stopService(intent) } } ) } fun generateAction(icon: Int, title: String, intentAction: String): NotificationCompat.Action { val intent = Intent(applicationContext, NotificationBuilder::class.java) intent.action = intentAction val pendingIntent = PendingIntent.getService(applicationContext, 1, intent, 0) return NotificationCompat.Action.Builder(icon, title, pendingIntent).build() } @SuppressLint("NewApi", "InlinedApi") fun buildNotification(action: NotificationCompat.Action) { val description = mController?.metadata?.description val playbackState = mController?.playbackState val style = android.support.v4.media.app.NotificationCompat.MediaStyle() .setShowActionsInCompactView() .setShowCancelButton(true) val intent = Intent(this, MainActivity::class.java) var pendingIntent = PendingIntent.getActivity( this, System.currentTimeMillis().toInt(), intent, 0 ) try { if ((Build.VERSION.SDK_INT >= Build.VERSION_CODES.O)) { var notificationChannel = NotificationChannel(channelId, "MoEcho", NotificationManager.IMPORTANCE_HIGH) if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { Statified.notificationManager?.createNotificationChannel(notificationChannel) } builder = NotificationCompat.Builder(this, channelId) .setColorized(true) .setColor(Color.parseColor("#9D2A58")) .setSmallIcon(R.drawable.echo_logo) .setContentTitle(SongPlayingFragment.Statified?.currentSongHelper?.songTitle) .setContentText(SongPlayingFragment.Statified?.currentSongHelper?.songArtist) .setContentIntent(pendingIntent) .setOnlyAlertOnce(true) .setVisibility(NotificationCompat.VISIBILITY_PUBLIC) .setOngoing(true) .setAutoCancel(true) .setStyle(style) } else { builder = NotificationCompat.Builder(this) .setColorized(true) .setColor(Color.parseColor("#9D2A58")) .setSmallIcon(R.drawable.echo_logo) .setContentTitle(SongPlayingFragment.Statified?.currentSongHelper?.songTitle) .setContentText(SongPlayingFragment.Statified?.currentSongHelper?.songArtist) .setContentIntent(pendingIntent) .setOngoing(true) .setAutoCancel(true) .setOnlyAlertOnce(true) .setVisibility(NotificationCompat.VISIBILITY_PUBLIC) .setStyle(style) } builder?.addAction(generateAction(android.R.drawable.ic_media_previous, "Previous", ACTION_PREVIOUS)) builder?.addAction(action) builder?.addAction(generateAction(android.R.drawable.ic_media_next, "Next", ACTION_NEXT)) style.setShowActionsInCompactView(0, 1, 2, 3) Statified.notificationManager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager val notificationManager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager notificationManager.notify(1, builder?.build()) } catch (e: Exception) { e.printStackTrace() } } override fun onUnbind(intent: Intent): Boolean { mSession?.release() return super.onUnbind(intent) } override fun onTaskRemoved(rootIntent: Intent?) { try { val notificationManager = applicationContext.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager notificationManager.cancel(1) super.onTaskRemoved(rootIntent) } catch (e: Exception) { e.printStackTrace() } } }<file_sep>/app/src/main/java/com/example/mohit/moecho/resources/CurrentSongHelper.kt package com.example.mohit.moecho.resources class CurrentSongHelper { var songArtist: String? = null var songTitle: String? = null var songPath: String? = null var songId: Long = 0 var currentPosition: Int = 0 var isPlaying: Boolean = false var isLoop: Boolean = false var isshuffle: Boolean = false <<<<<<< HEAD:app/src/main/java/com/example/mohit/moecho/resources/CurrentSongHelper.kt ======= >>>>>>> master:app/src/main/java/com/example/mohit/moecho/CurrentSongHelper.kt }
6dd56b5a1538cc2354b1968a988350a2268686aa
[ "Markdown", "Kotlin" ]
13
Kotlin
Mohit-Patil/MoEcho
46838741ef21fc31bed16de2de7b3b6f32a3bc8a
5be0117a1962aacd858ca1749e28ffa1e2c0dfcb
refs/heads/master
<file_sep>module.exports = function(grunt) { grunt.initConfig({ pkg: grunt.file.readJSON('package.json'), express: { options: { // Override defaults here port: 9000 }, dev: { options: { script: '../server.js' } }, }, less: { options: {}, dist: { files: {'dist/css/main.css': 'less/styles.less'} }, }, cssmin: { options: { shorthandCompacting: false, roundingPrecision: -1 }, dist: { files: { 'dist/css/main.min.css': 'dist/css/main.css' } }, }, ngtemplates: { dist: { cwd: '', src: ['partials/**/*.html'], dest: 'js/partials.js', options: { module: 'esLunch', htmlmin: { collapseBooleanAttributes: true, collapseWhitespace: true, removeAttributeQuotes: true, removeComments: true, removeEmptyAttributes: true, removeRedundantAttributes: true, removeScriptTypeAttributes: true, removeStyleLinkTypeAttributes: true } } }, }, concat: { options: { separator: ';' }, dist: { src: [ 'bower_components/angular/angular.js', 'bower_components/angular-animate/angular-animate.js', 'bower_components/angular-aria/angular-aria.js', 'bower_components/angular-messages/angular-messages.js', 'bower_components/angular-material/angular-material.js', 'bower_components/angular-ui-router/release/angular-ui-router.js', 'js/index.js', 'js/partials.js', 'js/controllers/*.js', 'js/services/*.js', 'js/directives/*.js', 'js/filters/*.js' ], dest: 'dist/js/everything.concat.js' } }, uglify: { options: { banner: '/*! <%= pkg.name %> <%= grunt.template.today("dd-mm-yyyy") %> */\n', mangle: true }, dist: { files: { 'dist/js/everything.min.js': ['<%= concat.dist.dest %>'] } } }, jshint: { files: ['Gruntfile.js', 'js/**/*.js'], options: { // options here to override JSHint defaults globals: { jQuery: true, console: true, module: true, document: true } } }, watch: { js: { files: ['js/**/*.js'], tasks: ['jscompile'] }, less: { files: ['less/**/*.less'], tasks: ['lesscompile'] }, html: { files: ['partials/**/*.html'], tasks: ['htmlcompile'] } } }); grunt.loadNpmTasks('grunt-express-server'); grunt.loadNpmTasks('grunt-contrib-less'); grunt.loadNpmTasks('grunt-contrib-cssmin'); grunt.loadNpmTasks('grunt-angular-templates'); grunt.loadNpmTasks('grunt-contrib-concat'); grunt.loadNpmTasks('grunt-contrib-uglify'); grunt.loadNpmTasks('grunt-contrib-jshint'); grunt.loadNpmTasks('grunt-contrib-watch'); grunt.registerTask('test', ['jshint']); grunt.registerTask('jscompile', ['concat', 'uglify']); grunt.registerTask('lesscompile', ['less', 'cssmin']); grunt.registerTask('htmlcompile', ['ngtemplates', 'concat', 'uglify']); grunt.registerTask('build', ['less', 'cssmin', 'ngtemplates', 'concat', 'uglify']); grunt.registerTask('server', ['test', 'build', 'express', 'watch']); grunt.registerTask('default', ['jshint', 'concat', 'uglify']); };
682e3d5c935a3a5d2bedbbb5162474b9d63066d8
[ "JavaScript" ]
1
JavaScript
MatthewJohnson3154/eslunch
2065758f3104703d814a65b560fb71099f5eabfb
6eb71087900fcdc9a9f4b6380e0f38d802a5035f
refs/heads/master
<file_sep># Based on: https://github.com/robb-j/common/blob/master/web-stack/docker-compose.yml version: '3.5' # Name our network # (useful if you want to use external docker-compose files) networks: default: name: web_stack # Named volumes # (Places to store data that will persist a `docker-compose down`) volumes: mysql_data: pugs_assets: dev_assets: # The container services that make up our stack services: # * * * * System * * * * # # Nginx container for managing http(s) traffic # Its configuration is automatically generated and mounted in using volumes nginx: container_name: nginx image: nginx:1-alpine restart: always labels: com.github.jrcs.letsencrypt_nginx_proxy_companion.nginx_proxy: "true" ports: - 80:80 - 443:443 volumes: - ./nginx/confd:/etc/nginx/conf.d - ./nginx/vhostd:/etc/nginx/vhost.d - ./html:/usr/share/nginx/html - ./certs:/etc/nginx/certs:ro - ./common.conf:/etc/nginx/common.conf:ro - ./redirs.conf:/etc/nginx/conf.d/redirs.conf:ro # Nginx configuration generator # (looks at container.VIRTUAL_HOST) # to generate nginx config and mounts them into `nginx` & reloads it # see -> https://github.com/jwilder/docker-gen nginx-gen: container_name: nginx-gen image: jwilder/docker-gen restart: always volumes: - ./nginx/confd:/etc/nginx/conf.d - ./nginx/vhostd:/etc/nginx/vhost.d - ./html:/usr/share/nginx/html - ./certs:/etc/nginx/certs:ro - ./nginx.tmpl.conf:/etc/docker-gen/templates/nginx.tmpl:ro - /var/run/docker.sock:/tmp/docker.sock:ro command: '-notify-sighup nginx -watch -wait 5s:30s /etc/docker-gen/templates/nginx.tmpl /etc/nginx/conf.d/default.conf' # Letsencrypt cert generator # (looks at container.LETSENCRYPT_HOST & container.LETSENCRYPT_EMAIL) # to generate SSL certs and mounts them into `nginx` & reloads # see -> https://github.com/JrCs/docker-letsencrypt-nginx-proxy-companion letsencrypt: image: jrcs/letsencrypt-nginx-proxy-companion container_name: letsencrypt restart: always environment: NGINX_DOCKER_GEN_CONTAINER: nginx-gen NGINX_PROXY_CONTAINER: nginx volumes: - ./nginx/confd:/etc/nginx/conf.d - ./nginx/vhostd:/etc/nginx/vhost.d - ./html:/usr/share/nginx/html - ./certs:/etc/nginx/certs:rw - /var/run/docker.sock:/var/run/docker.sock:ro # * * * * Services * * * * # # Mysql database to store instance & geographical data mysql: image: mysql:5.7 container_name: mysql restart: unless-stopped ports: - 3306:3306 volumes: - mysql_data:/var/lib/mysql env_file: - secrets/mysql.env # Geography service for geographical data # https://github.com/make-place/geography geo: image: mkpl/geography:1.1.1 restart: always env_file: - secrets/geo.env environment: - API_PORT=80 - VIRTUAL_HOST=geo.mkpl.co - LETSENCRYPT_HOST=geo.mkpl.co - LETSENCRYPT_EMAIL=<EMAIL> # Automatic daily mysql > AWS S3 backups backup: image: schickling/mysql-backup-s3 restart: always env_file: - secrets/backup.env environment: - MYSQL_HOST=mysql - SCHEDULE=@daily # A site index, to highlight availble services index-site: image: robbj/site-index:1.1.0 restart: always container_name: index volumes: - ./sites.yml:/app/web/sites.yml environment: - VIRTUAL_HOST=explore.make.place - LETSENCRYPT_HOST=explore.make.place - LETSENCRYPT_EMAIL=<EMAIL> # * * * * Deployments * * * * # # A deployment of the php platform on pugs.place pug-spotter: image: mkpl/php-platform:3.6.1 restart: unless-stopped volumes: - pugs_assets:/app/assets env_file: - secrets/common.env - secrets/pugs.env environment: PRIMARY_COL: #f95162 ADMIN_EMAIL: <EMAIL> VIRTUAL_HOST: pugs.place LETSENCRYPT_HOST: pugs.place LETSENCRYPT_EMAIL: <EMAIL> # A deployment of a static holding page on wip.make.place holding-site: image: mkpl/static-pages:0.2.1 env_file: - secrets/common.env environment: CONFIG_KEYS: SITE_MODE,SITE_TITLE SITE_MODE: unavailable SITE_TITLE: Make Place VIRTUAL_HOST: wip.make.place LETSENCRYPT_HOST: wip.make.place LETSENCRYPT_EMAIL: <EMAIL> <file_sep>#!/usr/bin/env bash # A script for a continuous deloyment to deploy servers # Attempts to `docker-compose up` any arguments passed # e.g. `sh ./deploy.sh nginx mysql geo` # Go to the stack cd /srv/stack # Pull the latest changes git pull origin master # Restart instances for name in "$@" do echo "Restarting $name" docker-compose up -d "$name" done <file_sep># Example Make Place deployment stack An example docker-compose stack used to deploy one or more instances of Make Place. Fork this repo to create your own for your stack, to contains all of your instances. ## Features * Automatic nginx reverse proxy generation * Automatic (free) SSL certificate generation * Secure by default, your secrets are only ever on your server * Containerised, each deployment is separate and cannot interaction with each other * Scalable, add more deployments by modifying Yaml files * Optional GitLab pipeline to automatically deploy when you push changes ## Prerequisites * Working knowledge of MySQL, Bash, SSH & Git ## System requirements * Docker * docker-compose ## How it works 1. You have your repo fork checked out locally and on the server. 2. You have the repo checked out on the server with your secrets filled in. 3. To make deployments you configure your `docker-compose.yml` locally and push it to git. 4. You can run `ssh user@server.io deploy deployment-a deployment-b` to deploy changes, which could be executed from a continuous deployment pipeline. ## Local setup Follow these steps to setup a local repository, where `$YOUR_REPO` is the git url of your fork. ```bash # Clone your repo fork locally git clone $YOUR_REPO # Get the latest nginx template curl https://raw.githubusercontent.com/jwilder/nginx-proxy/master/nginx.tmpl -o nginx.tmpl.conf # Make the example .gitignore a real one mv example.gitignore .gitignore # Configure your deployments (see below) # Push the changes git add -A git commit -m ":rocket: Configuring stack" git push -u origin master ``` ## Deployment configuration Deployments are defined as services in the `docker-compose.yml` at the bottom. To add a deployment, copy/replace the `pug-spotter` service and make the following changes: 1. Setup an assets volume 1. Set `pugs_assets` to something unique 2. Add it as an entry to the root level `volumes` at the top 2. Set `secrets/pugs.env` to a new secrets filename 3. Configure the deployment's environment * Set `VIRTUAL_HOST` & `LETSENCRYPT_HOST` to your domain * Set `LETSENCRYPT_EMAIL` to your email address to receive letsencrypt errors * See the [platform repo](https://github.com/make-place/php-platform/blob/master/README.md#environment-variables) for instance configuration ## Server setup Follow these steps to set up a Make Place server, using your stack repo, where $YOUR_USERNAME is the user you sign in with, e.g. `root` or `rob`. > You can use the user commands later to set up a `deploy` user in server group ```bash # Connect to your server ssh root@my-server.io # Setup a server usergroup sudo groupadd server sudo usermod -aG docker,server $YOUR_USERNAME # Create a stack directory & give it group-based permissions mkdir /srv/stack sudo chown -R $YOUR_USERNAME:server /srv/stack sudo chmod -R g+ws /srv/stack # Setup the directory cd /srv/stack git clone $YOUR_REPO # Create any .env files at this point # i.e. recreate your local secrets/ folder on the server # Ensure to set mysql.env's root password and remember this value # Startup the core core containers docker-compose up -d nginx nginx-gen letsencrypt mysql # Configure your mysql now (i.e. with a GUI like Sequel Pro) # Add a databases for each deployment and one for the geo service & access # You should have access with username `root` and the password from above # Fill in your .env files with credentials, see secrets/ for what should be set # Start up the rest of the server docker-compose up -d # Setup the deploy script for CI/CD sudo ln -s deploy.sh /usr/bin/deploy sudo chmod +x /usr/bin/deploy # Setup your geography service # ref: https://github.com/make-place/geography#sample-deployment # Your server is up and running ``` ## First deployment setup When you have just added a deployment, follow these steps on the server:, where $DEPLOYMENT is your deployment name & $URL is it's url. ```bash # Go to the stack cd /srv/stack # un-comment & set DEFAULT_USER & DEFAULT_PASS temporarily nano secrets/$DEPLOYMENT.env # Restart the container docker-compose up -d $DEPLOYMENT # Setup the deployment, performing migrations and setting up the cache # You can sign in with the details your put in $DEPLOYMENT.env open $URL/dev/build?flush # Visit /admin and set your user's password to a secure password open $URL/admin # Re-comment DEFAULT_USER & DEFAULT_PASS in $DEPLOYMENT.env nano secrets/$DEPLOYMENT.env # Restart the container docker-compose up -d $DEPLOYMENT # Your deployment is up and running # You can configure it through the CMS ``` ## Updating a deployment ```bash # For example, deploy pug-spotter & holding site after updating $YOUR_REPO ssh rob@make.place deploy pug-spotter holding-site ``` ## Further work & ideas * Separate core & deployment services into 2 docker-compose files * Setup continuous integration with GitLab with a `deploy` user * Modify your `nginx.tmpl.conf` to use a custom error page * Update `sites.yml` to reflect new deployments * Add to `redirs.conf` to implement custom nginx redirects * Use the `mkpl/static-pages` docker image to add holding sites
e9c8e30da64576ba4769c6d621acc820a4c38ed2
[ "Markdown", "YAML", "Shell" ]
3
YAML
make-place/example-web-stack
7f4d225d36a23d7d043b088f18b21b6fa8231570
b22dd3f257bd881b80f668d9954ddd63100d7691
refs/heads/main
<file_sep>const { JSDOM } = require("jsdom"); const { WebhookClient } = require("discord.js"); const BM_URL = "https://www.bonjourmadame.fr/"; async function getMadameData() { return JSDOM.fromURL(BM_URL).then(({ window }) => { const { document } = window; const rawUrl = document.querySelector(".post-content img").src; if (!rawUrl) { throw new Error("Madame est introuvable :-("); } const title = document .querySelector(".post-title") .textContent.replace(/\t/g, "") .replace(/\n/g, ""); const picture = rawUrl.split("?")[0]; return { picture, title }; }); } async function sendMadame() { const madameData = await getMadameData(); const webhookClient = new WebhookClient( process.env.WEBHOOK_ID, process.env.WEBHOOK_TOKEN ); await webhookClient.send({ content: madameData.title, username: "Bonjour Madame", files: [madameData.picture], }); return madameData; } exports.handler = async function () { try { const madameData = await sendMadame(); return { statusCode: 200, body: JSON.stringify(madameData) }; } catch (error) { console.error({ error }); return { statusCode: 500, body: JSON.stringify({ message: error.message }), }; } };
91cdd7ee577f5f2a704164970e3aa0a8c1897938
[ "JavaScript" ]
1
JavaScript
zyhou/bonjour-madame
87423497a4a678ac3b51171ce5e8dd4828ce93dd
e3af94b971e575025ba062b2cf6486a4e770aa5c
refs/heads/master
<file_sep>import React, { Component } from "react"; import Grid from "@material-ui/core/Grid"; import { Link } from "react-router-dom"; import AppBar from "@material-ui/core/AppBar"; import ShoppingCartIcon from "@material-ui/icons/ShoppingCart"; import CachedIcon from "@material-ui/icons/Cached"; import EditIcon from "@material-ui/icons/Edit"; import ArrowBackIcon from "@material-ui/icons/ArrowBack"; import Fab from '@material-ui/core/Fab'; import AddIcon from '@material-ui/icons/Add'; export default class Toolbar extends Component { refreshPage = () => { this.props.reOpen(); }; activateAddIcon = () => { this.props.Add(); }; changeShow = () => { this.props.edit(); }; render() { if (this.props.refresh === "refreshButton") { return ( <div className="toolbr"> <AppBar style={{ color: "white", height: 60 }}> <Grid container spacing={3}> <Grid item xs={2}> <Link to="/manager/edit"> <EditIcon style={{marginLeft:20}} onClick={() => this.changeShow()} className="editIcon" > Edit </EditIcon> </Link> </Grid> <Grid className="name" item sm xs={8}> <h4 className="toolbrStyle"> ההזמנות שלי</h4> </Grid> <Grid className="toolbarRefresh" item xs={2}> <CachedIcon style={{marginRight:25}} onClick={() => this.refreshPage()}></CachedIcon> </Grid> </Grid> </AppBar> </div> ); } else if (this.props.edit === "editbutton") { return ( <div className="toolbr"> <Fab color="primary" onClick={() => this.activateAddIcon()} aria-label="add" style={{'position': 'fixed', 'bottom': '20px', 'left': '20px'}}> <Link style={{color:"white"}} to ="/manager/additem"> <AddIcon /></Link> </Fab> <AppBar style={{ color: "white", height: 60 }}> <Grid container spacing={3}> <Grid style={{transform:"translateY(4%)"}} item xs={3}> <Link to="/manager/homepage"> <ArrowBackIcon className="backIcon">ArrowBack</ArrowBackIcon> </Link> </Grid> <Grid className="name" item xs={6}> <h4 className="toolbrStyle"> כל המוצרים</h4> </Grid> <Grid className="toolbarRefresh" item xs={3}> </Grid> </Grid> </AppBar> </div> ); } else if (this.props.addState === "backTo") { return ( <div className="toolbr"> <AppBar style={{ color: "white", height: 60 }}> <Grid container spacing={3}> <Grid item xs></Grid> <Grid className="name" item xs={8}> <h4 className="toolbrStyle"> מוצר חדש</h4> </Grid> <Grid className="toolbarRefreshOnAdd" item xs> </Grid> </Grid> </AppBar> </div> ); } else if (this.props.currentPage=== "cart") { return ( <div className="toolbr"> {/* <Fab color="primary" aria-label="add" style={{'position': 'fixed', 'bottom': '20px', 'right': '20px'}}> <Link style={{color:"white"}} to ="/client/cart"><ShoppingCartIcon/></Link> </Fab> */} <AppBar style={{ color: "white", height: 60 }}> <Grid container spacing={3}> <Grid style={{transform:"translateY(3%)"}} item xs> <Link to="/client/store"> <ArrowBackIcon className="backIcon"> ArrowBack </ArrowBackIcon> </Link> </Grid> <Grid className="name" item xs={8}> <Link className="linkintoolbar" to="/client/store"> <h4 className="toolbrStyle"> השוק שלי</h4> </Link> </Grid> <Grid className="toolbarRefresh" item xs></Grid> </Grid> </AppBar> </div> ); }else if (this.props.summery === "summeryPage") { return ( <div className="toolbr"> {/* <Fab color="primary" aria-label="add" style={{'position': 'fixed', 'bottom': '20px', 'right': '20px'}}> <Link style={{color:"white"}} to ="/client/cart"><ShoppingCartIcon/></Link> </Fab> */} <AppBar style={{ color: "white", height: 60 }}> <Grid container spacing={3}> <Grid item xs> <Link to="/manager/homepage"> <ArrowBackIcon className="backIcon"> ArrowBack </ArrowBackIcon> </Link> </Grid> <Grid className="name" item xs={8}> <Link className="linkintoolbar" to="/client/store"> <h4 className="toolbrStyle"> סיכום כמויות</h4> </Link> </Grid> <Grid className="toolbarRefresh" item xs></Grid> </Grid> </AppBar> </div> ); }else{ return ( <div className="toolbr"> <Fab color="primary" aria-label="add" style={{'position': 'fixed', 'bottom': '20px', 'right': '20px'}}> <Link style={{color:"white", transform:"translateY(10%)"}} to ="/client/cart"><ShoppingCartIcon/></Link> </Fab> <AppBar style={{ color: "white", height: 60 }}> <Grid container spacing={3}> <Grid item xs> </Grid> <Grid className="name" item xs={8}> <Link className="linkintoolbar" to="/client/store"> <h4 className="toolbrStyle"> השוק שלי</h4> </Link> </Grid> <Grid className="toolbarRefresh" item xs></Grid> </Grid> </AppBar> </div> ) } } } <file_sep>import React, { Component } from "react"; import { Route } from "react-router-dom"; import StorePage from "./StorePage.js"; import CartPage from "./CartPage.js"; export default class Client extends Component { constructor(props) { super(props); this.state = { allCart: [], }; } updateItemAmount=(itemWithNewAmount)=>{ let element for (let i = 0; i < this.state.allCart.length; i++) { element = this.state.allCart[i]; if (element.item.Id === itemWithNewAmount.item.Id ) { element.amount = itemWithNewAmount.amount } } this.setState({allCart:this.state.allCart}) } addItemToCart = (item, amount) => { let newItem = { item: item, amount: amount }; let element if (this.state.allCart.length <= 0 ) { this.setState({ allCart: [...this.state.allCart, newItem] }); }else{ for (let i = 0; i < this.state.allCart.length; i++) { element = this.state.allCart[i]; if (element.item.Id === item.Id) { element.amount = parseFloat(element.amount) + parseFloat(amount) return } } this.setState({ allCart: [...this.state.allCart, newItem] }); } }; deleteItemFromCart = (id) => { let newCart = this.state.allCart.filter((item) => item.item.Id !== id); this.setState({ allCart : newCart }); }; truncateCart = () => { this.setState({ allCart: [] }); }; render() { return ( <React.Fragment> <Route exact path="/client/store"> <StorePage allCart={this.state.allCart} addItemToCart={this.addItemToCart} /> </Route> <Route exact path="/client/cart"> <CartPage cleanCart={this.truncateCart} deleteItemFromCart={this.deleteItemFromCart} cart={this.state.allCart} itemAmountUpdate={this.updateItemAmount} /> </Route> </React.Fragment> ); } } <file_sep>import React, { Component } from "react"; import Toolbar from "./Toolbar.js"; import NewItem from "./NewItem.js"; import Axios from "axios"; import { Redirect } from "react-router-dom"; import Button from "@material-ui/core/Button"; import TextField from "@material-ui/core/TextField"; import CircularProgress from "@material-ui/core/CircularProgress"; import config from "../config"; const styles = { prog: { position: "absolute", top: "0px", height: "100%", width: "100%", display: "flex", justifyContent: "center", alignContent: "center", flexDrection: "column", backgroundColor: "rgb(0,0,0, 0.5)", }, circBar: { position: "absolute", top: "300px", }, }; export default class EditStorePage extends Component { constructor(props) { super(props); this.state = { allItems: [], progressBar: true, minimumShow:false, minimumOrder:0 }; } componentDidMount=()=>{ this.storeItemsOnServer() this.getMinimumFromServer() } getMinimumFromServer=()=>{ Axios.get(`${config.server}/orderMin/${config.clientId}`).then( (res)=>{ this.setState({minimumOrder:res.data.Value}) } ) } setMinimumOrder=()=>{ let minimum = {orderMin:this.state.minimumOrder} Axios.post(`${config.server}/updateOrderMin/${config.clientId}`, minimum) .then(() =>{ this.setState({minimumShow:false}) }).catch((error)=>{ console.log(error); alert("משהו השתבש נסה מאוחר יותר "); }) } showMinimum=()=>{ this.setState({minimumShow:true}) } storeItemsOnServer = () => { Axios.get(`${config.server}/allitems/${config.clientId}`).then( (res) => { this.setState({ allItems: res.data, progressBar: false }); } ) .catch((error) =>{ console.log(error); alert("משהו השתבש נסה מאוחר יותר "); }) }; directIntoNewRoute = () => { return <Redirect to ="/manager/additem"/> }; deleteItemFromList = (id) => { let newList= this.state.allItems.filter((item) => { return item.Id!==id }) this.setState({ allItems: newList }); }; render() { return ( <div> <div style={{ zIndex: 1, marginBottom: 62 }}> <Toolbar reOpen={this.storeItemsOnServer} Add={this.directIntoNewRoute} edit={"editbutton"} /> </div> {!this.state.minimumShow ? ( <div style={{textAlign:"right"}}> <Button style={{color:"blue", fontWeight:"bolder"}} onClick={()=>this.showMinimum()}>שנה מינימום הזמנה</Button> </div>) : ( <div style={{textAlign:"right"}}> <Button variant="contained" color="primary" style={{fontWeight:"bolder" , marginRight:80}} onClick={()=>this.setMinimumOrder()}> הגדר </Button> <TextField type="number" defaultValue={this.state.minimumOrder} onChange={(m) =>{this.setState({minimumOrder:m.target.value}) }} style={{width:100}} /> </div>)} {this.state.allItems.map((element, key) => { return ( <NewItem delete={this.deleteItemFromList} key={element.Id} item={element} /> ); })} {this.state.progressBar ? ( <div style={styles.prog}> <CircularProgress style={styles.circBar} size={68} /> </div> ) : ( <br /> )} </div> ); } } <file_sep>import React, { Component } from 'react'; import './App.css'; import EditStorePage from "./components/EditStorePage"; import ManagerPage from './components/ManagerPage'; import Client from './components/Client'; import LoadingPage from "./components/LoadingPage"; import AddNewItemPage from './components/AddNewItemPage'; import SummeryPage from './components/SummeryPage'; import {HashRouter as Router , Route , Switch} from 'react-router-dom'; import { create } from 'jss'; import rtl from 'jss-rtl'; import { createMuiTheme, ThemeProvider } from '@material-ui/core/styles'; import { StylesProvider, jssPreset } from '@material-ui/core/styles'; const theme = createMuiTheme({ direction: 'rtl' }); const jss = create({ plugins: [...jssPreset().plugins, rtl()] }); export default class App extends Component { constructor(props) { super(props) this.state = { allOrders:"" } } updateAllItemsList=(a)=>{ this.setState({all:a}) } updateStateWithList=(a)=>{ this.setState({all:a}) } activatestoreItemsOnServer=()=>{ } updateAllOrders=(all)=>{ this.setState({allOrders:all}) } render() { return ( <div className="AllApp"> <ThemeProvider theme={theme}> <StylesProvider jss={jss}> <Router> <Switch> <Route exact path="/"> <LoadingPage /> </Route> <Route exact path ="/manager/homepage"> <ManagerPage allOrders={this.updateAllOrders}/> </Route> <Route exact path="/manager/edit"> <EditStorePage /> </Route> <Route exact path ="/manager/additem"> <AddNewItemPage activatestoreItemsOnServer={this.activatestoreItemsOnServer} updateState ={this.updateStateWithList}allItems={this.updateAllItemsList} /> </Route> <Route exact path ="/manager/summery"> <SummeryPage orders={this.state.allOrders}/> </Route> <Client/> </Switch> </Router> </StylesProvider> </ThemeProvider> </div> ) } } <file_sep>import React, { Component } from "react"; import Toolbar from "./Toolbar.js"; import TableHead from "@material-ui/core/TableHead"; import TableRow from "@material-ui/core/TableRow"; import TableBody from "@material-ui/core/TableBody"; import TableCell from "@material-ui/core/TableCell"; import Table from "@material-ui/core/Table"; import DeleteForeverIcon from "@material-ui/icons/DeleteForever"; import Button from "@material-ui/core/Button"; import TextField from "@material-ui/core/TextField"; import CircularProgress from "@material-ui/core/CircularProgress"; import config from "../config"; import Axios from "axios"; const styles = { prog: { position: "absolute", top: "0px", height: "100%", width: "100%", display: "flex", justifyContent: "center", alignContent: "center", flexDrection: "column", backgroundColor: "rgb(0,0,0, 0.5)", }, circBar: { position: "absolute", top: "400px", }, }; export default class CartPage extends Component { constructor(props) { super(props); this.state = { Name: "", Number: "", progressBar: false, OrderMinimum: 0, amount: 0, }; } componentDidMount = () => { Axios.get(`${config.server}/orderMin/${config.clientId}`) .then((res) => { this.setState({ OrderMinimum: res.data }); }) .catch((error) => { console.log(error); alert("משהו השתבש נסה שוב מאוחר יותר "); }); }; increaseAmount = (element) => { for (let i = 0; i < this.props.cart.length; i++) { let cart = this.props.cart[i]; if (cart.item.Id === element.item.Id) { cart.amount = parseInt(element.amount) + 1; this.props.itemAmountUpdate(cart); } } }; decreaseAmount = (element) => { for (let i = 0; i < this.props.cart.length; i++) { let cart = this.props.cart[i]; if (cart.item.Id === element.item.Id && element.amount > 1) { cart.amount = parseInt(element.amount) - 1; this.props.itemAmountUpdate(cart); } } }; getSumOfAllCart = (cart) => { let sum = 0; for (let i = 0; i < cart.length; i++) { sum = sum + cart[i].item.Price * cart[i].amount; } return sum; }; sendOrder = (sum) => { let phoneNumberString = this.state.Number.toString(); let order = { Cart: this.props.cart, Name: this.state.Name, Number: this.state.Number, ClientId: config.ClientId, }; if (sum >= parseInt(this.state.OrderMinimum.Value)) { if ( phoneNumberString[0] === "0" && phoneNumberString[1] === "5" && phoneNumberString.length === 10 && this.state.Name !== undefined && this.state.Name.length <= 15 ) { this.setState({ progressBar: true }, () => { Axios.post(`${config.server}/order/${config.clientId}`, order) .then((res) => { alert("הזמנה בוצעה בהצלחה"); this.props.cleanCart(); this.setState({ progressBar: false }); }) .catch((error) => { console.log(error); alert("משהו השתבש נסה מאוחר יותר "); this.setState({ progressBar: false }); }); }); } else { document.getElementById("error").innerHTML = "הכנס מספר בן 10 ספרות המתחיל ב 05 & אורך מקסימלי לשם הוא 15 תווים "; } } else { alert(`מינימום הזמנה של ${this.state.OrderMinimum.Value}`); } }; render() { document.body.style.backgroundColor = "rgb(211, 207, 207)"; let totalSum = this.getSumOfAllCart(this.props.cart); return ( <div> <Toolbar currentPage="cart" /> <Table className="cartDiv"> <TableHead> <TableRow> <TableCell></TableCell> <TableCell style={{ textAlign: "center" }}> <span style={{ fontWeight: 600 }}>מחיר</span> </TableCell> <TableCell style={{ textAlign: "center" }}> <span style={{ fontWeight: 600 }}>כמות</span> </TableCell> <TableCell style={{ textAlign: "center" }}> <span style={{ fontWeight: 600 }}>מוצר</span> </TableCell> </TableRow> </TableHead> <TableBody> {this.props.cart.map((element) => { let totalItemPrice = ( element.amount * element.item.Price ).toFixed(2); let itemAmount = parseFloat(element.amount).toFixed(2); return ( <TableRow key={element.item.Id}> <TableCell style={{ textAlign: "center" }}> <DeleteForeverIcon onClick={() => this.props.deleteItemFromCart(element.item.Id) } /> </TableCell> <TableCell style={{ textAlign: "center" }}> {totalItemPrice} </TableCell> <TableCell style={{ textAlign: "center" }}> <button onClick={() => this.decreaseAmount(element)} className="incDecBtn" style={{ width: 20 }} > - </button> <span style={{ marginRight: 6, marginLeft: 6 }}> {itemAmount} </span> <button className="incDecBtn" onClick={() => this.increaseAmount(element)} > + </button> </TableCell> <TableCell> <span style={{ fontWeight: "bolder" }}> {element.item.Name} </span> </TableCell> </TableRow> ); })} <TableRow> <TableCell></TableCell> <TableCell style={{ textAlign: "center" }}> :סה"כ <br /> {totalSum.toFixed(2)} <br /> ש"ח </TableCell> <TableCell></TableCell> </TableRow> </TableBody> </Table> <div style={{ textAlign: "center" }}> <br /> <TextField style={{ textAlign: "center" }} onChange={(event) => this.setState({ Name: event.target.value })} type="text" id="standard-basic" label="שם מלא" maxLength={12} erorText="הכנס רק 10 תווים" /> <br /> <TextField style={{ textAlign: "center" }} onChange={(event) => this.setState({ Number: event.target.value })} type="number" id="standard-basic" label="מספר טלפון" /> <br /> <p id="error"></p> <br /> <Button variant="contained" color="primary" onClick={() => this.sendOrder(totalSum)} > בצע הזמנה </Button> {this.state.progressBar ? ( <div style={styles.prog}> <CircularProgress style={styles.circBar} size={68} /> </div> ) : ( <br /> )} </div> </div> ); } } <file_sep>import React, { Component } from "react"; import Item from "./Item"; import Toolbar from "./Toolbar"; import Grid from "@material-ui/core/Grid"; import Container from "@material-ui/core/Container"; import CircularProgress from "@material-ui/core/CircularProgress"; import Axios from "axios"; import config from "../config"; const styles = { prog: { position: "absolute", top: "0px", height: "100%", width: "100%", display: "flex", justifyContent: "center", alignContent: "center", flexDrection: "column", backgroundColor: "rgb(0,0,0, 0.5)", }, circBar: { position: "absolute", top: "400px", }, }; export default class StorePage extends Component { constructor(props) { super(props); this.state = { allItems: [], progressBar: true, }; } componentDidMount = () => { Axios.get(`${config.server}/allitems/${config.clientId}`).then( (res) => { this.setState({ allItems: res.data, progressBar: false }); } ).catch((error) =>{ console.log(error); alert("משהו השתבש נסה מאוחר יותר "); }) }; render() { document.body.style.backgroundColor = "rgb(211, 207, 207)"; return ( <div className="storediv"> <Toolbar /> <Container> <Grid container spacing={3}> {this.state.allItems.map((element) => { return ( <Grid className="itemBrake" key={element.Id} item xs={6}> <Item allCart= {this.props.allCart} is={this.state.include} itemIncluded={this.itemIncluded} addItemToCart={this.props.addItemToCart} item={element} /> </Grid> ); })} </Grid> </Container> <div className="footer"> <img className="footerLogoStyle" src="footer-logo_transparent.jpeg" alt="allRightReserved" /> </div> {this.state.progressBar ? ( <div style={styles.prog}> <CircularProgress style={styles.circBar} size={68} /> </div> ) : ( <br /> )} </div> ); } } <file_sep>import React, { Component } from "react"; import Axios from "axios"; import Button from "@material-ui/core/Button"; import ExpansionPanel from "@material-ui/core/ExpansionPanel"; import ExpansionPanelSummary from "@material-ui/core/ExpansionPanelSummary"; import ExpansionPanelDetails from "@material-ui/core/ExpansionPanelDetails"; import Typography from "@material-ui/core/Typography"; import ExpandMoreIcon from "@material-ui/icons/ExpandMore"; import TableRow from "@material-ui/core/TableRow"; import TableBody from "@material-ui/core/TableBody"; import TableCell from "@material-ui/core/TableCell"; import Table from "@material-ui/core/Table"; import CircularProgress from "@material-ui/core/CircularProgress"; import FiberManualRecordIcon from '@material-ui/icons/FiberManualRecord'; import config from "../config" const styles = { prog: { zIndex:3, position: "absolute", top: "0px", height: "100%", width: "100%", display: "flex", justifyContent: "center", alignContent: "center", flexDrection: "column", backgroundColor: "rgb(0,0,0, 0.5)", }, circBar: { position: "absolute", top: "400px", }, }; export default class Order extends Component { constructor(props) { super(props) this.state = { proggresBar:false } } closeOrder = (id , address , callback ) => { let Identity = { id: id }; this.setState({proggresBar:true} , ()=>{ Axios.post( address, Identity ).then(() => { this.setState({proggresBar:false}) console.log(address); console.log(Identity); callback() }).catch((error)=>{ console.log(error); alert("משהו השתבש נסה שוב מאוחר יותר ") }) }) }; sumUpEachItemAddedToCart = (orders) => { var sum = 0; for (let i = 0; i < orders.length; i++) { sum = sum + orders[i].item.Price * orders[i].amount; } return sum; }; showAllOrders =(status)=> { let sumup = this.sumUpEachItemAddedToCart(this.props.order.Cart); let dotColor = status === 2 ? "red" : "green" let actionButton = status === 2 ? <Button // onClick={() => this.finishedOrder(this.props.order)} onClick={() => this.closeOrder(this.props.order.Id, `${config.server}/closeOrder` , () => {this.props.deletedOrder(this.props.order.Id)})} variant="contained" color="primary" > סגור הזמנה </Button> : <Button onClick={() => this.closeOrder(this.props.order.Id , `${config.server}/prepareOrder` , ()=> {this.props.funcToReorgenizeOrders(this.props.order)})} // onClick={() => this.closeOrder(this.props.order.Id)} variant="contained" color="primary" > הכנתי הזמנה </Button> return ( <div> <ExpansionPanel> <div className="PanelStyle"> <ExpansionPanelSummary expandIcon={<ExpandMoreIcon />} aria-controls="panel1a-content" id="panel1a-header" > <Typography> <span style={{ fontWeight: "bolder" }}> <FiberManualRecordIcon style={{color:dotColor, width:13, marginRight: '10px', top: '8px', position: 'relative'}}></FiberManualRecordIcon> {this.props.order.Name} </span> <br />{" "} <span className="numberStyleofOrder"> {" "} {this.props.order.Number} </span> </Typography> </ExpansionPanelSummary> </div> <ExpansionPanelDetails className={"expansionColor"} style={{'display': 'block', 'textAlign': 'center'}}> <div> <Table> <TableBody style={{ textAlign: "right" }}> {this.props.order.Cart.map((element) => { var total = element.amount * element.item.Price; return ( <TableRow key={element.item.Id}> <TableCell style={{ textAlign: "center" }}> {total.toFixed(2)} </TableCell> <TableCell style={{ textAlign: "center" }}> {parseFloat(element.amount).toFixed(2)} </TableCell> <TableCell> <span style={{ fontWeight: "bolder" }}> {element.item.Name} </span> </TableCell> </TableRow> ); })} <TableRow> <TableCell></TableCell> <TableCell style={{ textAlign: "left" }}> {sumup.toFixed(2)} :סה"כ </TableCell> <TableCell></TableCell> </TableRow> </TableBody> </Table> <div style={{ textAlign: "left" }}> {actionButton} </div> </div> </ExpansionPanelDetails> </ExpansionPanel> </div> ); } render() { if (this.state.proggresBar) { return <div style={styles.prog}> <CircularProgress style={styles.circBar}size={68}/></div>; } return( <div> {this.showAllOrders(this.props.order.Status)} </div> ) } } <file_sep>import React, { Component } from 'react' import Toolbar from './Toolbar'; import TableHead from "@material-ui/core/TableHead"; import TableRow from "@material-ui/core/TableRow"; import TableBody from "@material-ui/core/TableBody"; import TableCell from "@material-ui/core/TableCell"; import Table from "@material-ui/core/Table"; export default class SummeryPage extends Component { constructor(props) { super(props) this.state = { itemsArray:[] } } componentDidMount=()=>{ this.getOrderSummery(this.props.orders) } getOrderSummery=(orders)=>{ let itemsArray=[] for (let i = 0; i < orders.length; i++) { let element = orders[i]; for (let j = 0; j < element.Cart.length; j++) { let item = element.Cart[j]; let maybeItemArr = itemsArray.filter((prod) => { return prod.item.Id === item.item.Id; }) if(maybeItemArr.length === 0){ itemsArray.push(item); } else{ maybeItemArr[0].amount = parseFloat(item.amount) + parseFloat(maybeItemArr[0].amount); } } } this.setState({itemsArray:itemsArray}) } render() { return ( <div> <Toolbar summery={"summeryPage"}/> <div style={{marginTop:60}}> <Table> <TableHead > <TableRow> <TableCell> <span style={{fontWeight:"bold"}}> יחידה</span> </TableCell> <TableCell> <span style={{fontWeight:"bold"}}>כמות</span> </TableCell> <TableCell> <span style={{fontWeight:"bold"}}>מוצר</span> </TableCell> <TableCell></TableCell> </TableRow> </TableHead> <TableBody> {this.state.itemsArray.map((element, key) => { return <TableRow key={key}> <TableCell>{element.item.Units}</TableCell> <TableCell>{element.amount}</TableCell> <TableCell> <span style={{fontWeight:500}}>{element.item.Name}</span></TableCell> <TableCell style={{fontWeight:"bold"}}>{key+1}</TableCell> </TableRow> })} </TableBody> </Table> </div> </div> ) } } <file_sep>import React, { Component } from "react"; import Button from "@material-ui/core/Button"; import Card from "@material-ui/core/Card"; import CardMedia from "@material-ui/core/CardMedia"; import CardContent from "@material-ui/core/CardContent"; import CardActions from "@material-ui/core/CardActions"; import TextField from "@material-ui/core/TextField"; import CheckIcon from '@material-ui/icons/Check'; export default class Item extends Component { constructor(props) { super(props); this.state = { focusStatus: false, amount: 0, units:"", inCartSign:false }; } addItem = () => { if (this.state.amount > 0 && this.state.amount <= 100) { this.props.addItemToCart(this.props.item, this.state.amount ); this.setState({ focusStatus: false , inCartSign:true }); } else { document.getElementById("message").innerHTML = "הכנס כמות בין 0-100"; } }; toggleFocusStatuc = () => { if (!this.state.focusStatus) { this.setState({ focusStatus: true }); } else { this.setState({ focusStatus: false }); } }; updateUnits=(u)=>{ this.setState({units:u.target.value}) } getCardContent = () => { return this.state.focusStatus ? ( <div style={{'marginBottom': '-10px'}}> <span className="edit">כמות</span> <TextField style={{ paddingTop: 0}} type="number" id="standard-basic" label="כמות" onChange={(event) => {this.setState({ amount: event.target.value }); }} /> <p id="message"></p> </div> ): ( <React.Fragment> מחיר ל{`${this.props.item.Units}`} <br /> ₪ {this.props.item.Price} </React.Fragment> ) }; getCardActions = () => { if (this.state.focusStatus) { return <React.Fragment> <Button onClick={this.toggleFocusStatuc} size="small" color="primary"> חזור </Button> <Button size="small" onClick={() => this.addItem()} color="primary" > הוסף </Button> </React.Fragment> }else { return <React.Fragment> <Button size="small" onClick={this.toggleFocusStatuc} color="primary"> הוסף לעגלה { this.props.allCart.filter((element) => element.item.Id === this.props.item.Id).length !== 0 ? <CheckIcon style={{color:"green", width:18, height:15}} > Check </CheckIcon> : <br />} </Button> </React.Fragment> } } render() { let cardContent = this.getCardContent(); let cardActions = this.getCardActions(); return <div className="eachItem"> <Card className="eachItem"> <CardMedia image={this.props.item.Image} style={{ height: "100px" }}></CardMedia> <CardContent style={{ textAlign: "right" }}> <span className="itemnamestyle" style={{ fontFamily: "Arial", fontWeight: "700", fontSize: "20px" }} > {this.props.item.Name} </span> <br /> {cardContent} </CardContent> <CardActions>{cardActions} </CardActions> </Card> </div>; } } <file_sep>import React, { Component } from "react"; import Item from "./Item.js"; import Button from "@material-ui/core/Button"; import TextField from "@material-ui/core/TextField"; import Grid from "@material-ui/core/Grid"; import Container from "@material-ui/core/Container"; import { Link, Redirect } from "react-router-dom"; import Axios from "axios"; import Toolbar from "./Toolbar.js"; import Select from "@material-ui/core/Select"; import MenuItem from "@material-ui/core/MenuItem"; import FormControl from "@material-ui/core/FormControl"; import InputLabel from "@material-ui/core/InputLabel"; import CircularProgress from "@material-ui/core/CircularProgress"; import config from "../config"; const styles = { prog: { position: "absolute", top: "0px", height: "100%", width: "100%", display: "flex", justifyContent: "center", alignContent: "center", flexDrection: "column", backgroundColor: "rgb(0,0,0, 0.5)", }, circBar: { position: "absolute", top: "300px", }, }; export default class AddNewItem extends Component { constructor(props) { super(props); this.state = { newPrice: "", newImage: "https://clipartstation.com/wp-content/uploads/2017/11/x-clipart-3.png", newName: "", direction: false, units: "", proggressBar: true, }; } sendToServerNewItem = () => { let newname = this.state.newName; let newprice = this.state.newPrice; let newimage = this.state.newImage; let units = this.state.units; let newItem = { Name: newname, Price: newprice, Image: newimage, Units: units, ClientId: config.clientId, }; if (this.state.newName !== "" && this.state.newPrice !== "") { this.setState({ proggressBar: false }, () => { Axios.post(`${config.server}/addItem/${config.clientId}`, newItem) .then((res) => { if (res.status === 200 && res.data === "done") { return this.setState({ direction: true, proggressBar: true }); } }) .catch((error) => { alert("משהו השתבש נסה מאוחר יותר "); }); }); } }; render() { if (this.state.direction) { return <Redirect to="/manager/edit" />; } if (this.state.proggressBar) { return ( <div className="AddStyleCard"> <Toolbar reOpen={this.refreshPage} addState={"backTo"} /> { <TextField style={{ width: 180 }} id="standard-basic" onChange={(n) => { this.setState({ newName: n.target.value }); }} label="שם" /> } <br /> <TextField style={{ width: 180 }} type="number" id="standard-basic" label="מחיר " onChange={(p) => { this.setState({ newPrice: p.target.value }); }} /> <br /> <FormControl> <InputLabel id="demo-simple-select-label">יחידת מידה</InputLabel> <Select style={{ width: 180 }} labelId="demo-simple-select-label" id="demo-simple-select" onChange={(u) => { this.setState({ units: u.target.value }); }} > <MenuItem value={"קילוגרם"}>ק"ג</MenuItem> <MenuItem value={"יחידות"}>יחידות</MenuItem> <MenuItem value={"גרם"}>גרם</MenuItem> </Select> </FormControl> <br /> <TextField style={{ width: 180 }} type="string" id="standard-basic" label="תמונה" onChange={(i) => { this.setState({ newImage: i.target.value }); }} /> <br /> <br /> <Button size="small" color="primary"> <Link style={{ color: "#3f51b5" }} to="/manager/edit"> חזור </Link> </Button> <Button size="small" onClick={() => this.sendToServerNewItem()} color="primary" > הוסף </Button> <div style={{ marginTop: "50px", textAlign: "center" }}> <Container> <Grid container spacing={3}> <Grid item xs={3} /> <Grid className="itemBrake" item xs={6}> <Item addItemToCart={() => {}} allCart={[]} item={{ Id: -1, Name: this.state.newName, Price: this.state.newPrice, Image: this.state.newImage, Units: this.state.units, }} /> </Grid> <Grid item xs={3} /> </Grid> </Container> </div> </div> ); } else { return ( <div style={styles.prog}> <CircularProgress style={styles.circBar} size={68} /> </div> ); } } } <file_sep>import React, { Component } from "react"; import Order from "./Order.js"; import Toolbar from "./Toolbar.js"; import Axios from "axios"; import { Link, Redirect } from "react-router-dom"; import CircularProgress from "@material-ui/core/CircularProgress"; import Button from "@material-ui/core/Button"; import config from "../config"; const styles = { prog: { position: "absolute", top: "0px", height: "100%", width: "100%", display: "flex", justifyContent: "center", alignContent: "center", flexDrection: "column", backgroundColor: "rgb(0,0,0, 0.5)", }, circBar: { position: "absolute", top: "300px", }, }; export default class ManagerPage extends Component { constructor(props) { super(props); this.state = { unreadyOrders: [], progressBar: false, readyOrders: [], }; } componentDidMount = () => { this.GetOrderFromServer(); }; GetOrderFromServer = () => { this.setState({ progressBar: true }, () => { Axios.get(`${config.server}/openOrders/${config.clientId}`) .then((res) => { console.log(res); let allorders = []; let finishedOrderList = []; for (let i = 0; i < res.data.length; i++) { let element = res.data[i]; let order = JSON.parse(element.OrderData); order.Id = element.Id; order.Status = element.Status; if (order.Status === 1) { allorders.unshift(order); } else if (order.Status === 2) { finishedOrderList.unshift(order); } } this.props.allOrders(allorders); this.setState({ unreadyOrders: allorders, progressBar: false, readyOrders: finishedOrderList, }); }) .catch((error) => { console.log(error); alert("משהו השתבש נסה שוב מאוחר יותר"); }); }); }; redirectToEditPage = () => { return <Redirect to="/manager/edit" />; }; deleteOrder = (id) => { let newOrdersArray = this.state.readyOrders.filter((item) => { return item.Id !== id; }); this.setState({ readyOrders: newOrdersArray }); }; moveOrderToReady = (order) => { let finished = this.state.readyOrders; let newList = this.state.unreadyOrders.filter((item) => { return item.Id !== order.Id; }); order.Status = 2; finished.unshift(order); this.setState({ readyOrders: finished, unreadyOrders: newList }); }; render() { document.body.style.backgroundColor = "rgb(211, 207, 207)"; let pageBody; if (this.state.progressBar) { pageBody = ( <div style={styles.prog}> <CircularProgress style={styles.circBar} size={68} /> </div> ); } else { pageBody = this.state.unreadyOrders.length === 0 && this.state.readyOrders.length === 0 ? ( <h4 style={{ marginTop: 70, textAlign: "center" }}>אין הזמנות</h4> ) : ( <div style={{ marginTop: 62 }}> <div style={{ textAlign: "right" }}> <Link style={{ textDecoration: "none" }} to="/manager/summery"> <Button style={{ color: "blue" }}> הצג סיכום כמויות מוצרים </Button> </Link> </div> {this.state.unreadyOrders.map((element) => { return ( <Order size={this.state.unreadyOrders.length} funcToReorgenizeOrders={this.moveOrderToReady} key={element.Id} order={element} /> ); })} {this.state.readyOrders.map((pro) => { return ( <Order order={pro} key={pro.Id} deletedOrder={this.deleteOrder} /> ); })} </div> ); } return ( <React.Fragment> <Toolbar edit={this.redirectToEditPage} reOpen={this.GetOrderFromServer} refresh={"refreshButton"} /> {pageBody} </React.Fragment> ); } }
776c475be68ca7ae3b71876735fa833e59d5abbb
[ "JavaScript" ]
11
JavaScript
Doriel1121/delivery
a6c3706fde1b88b12313e695d8fd78a1b47d59a8
5de7d89de26576d1a0c85aea9c0fa454bf92d5f5
refs/heads/master
<repo_name>Creatune/Flowchart-Wizard-React<file_sep>/src/index.js import React from "react"; import ReactDOM from "react-dom"; import "./styles.css"; import Graphics from "./App.js"; ReactDOM.render(<Graphics />, document.getElementById("root"));<file_sep>/src/App.js import React, { Component } from "react"; import { Stage, Layer, Rect, Transformer, Ellipse, Star, Text, Arrow, Group } from "react-konva"; import Connector from "./Connect.jsx"; import Toolbar from "./Toolbar.js"; const Rectangle = ({ shapeProps, onSelect, onChange }) => { const shapeRef = React.useRef() return ( <Group> <Rect onClick={() => onSelect(shapeRef)} onTap={() => onSelect(shapeRef)} ref= {shapeRef} {...shapeProps} name="rectangle" draggable onDragEnd={(e) => { onChange({ ...shapeProps, x: e.target.x(), y: e.target.y() }) }} onTransformEnd-{...(e) => { const node = shapeRef.current; const scaleX = node.scaleX(); const scaleY = node.scaleY(); node.scaleX(1); node.scaleY(1); onChange({ ...shapeProps, x: node.x(), y: node.y(), width: Math.max(5, node.width() * scaleX), height: Math.max(node.height() * scaleY) }); }} /> </Group> ) } class TransformerComponent extends React.Component { componentDidMount() { this.checkNode(); } componentDidUpdate() { this.checkNode(); } checkNode() { const stage = this.transformer.getStage(); const { selectedShapeName } = this.props; if (selectedShapeName === "") { this.transformer.detach(); return; } const selectedNode = stage.findOne("." + selectedShapeName); if (selectedNode === this.transformer.node()) { return; } if (selectedNode) { this.transformer.attachTo(selectedNode); } else { this.transformer.detach(); } this.transformer.getLayer().batchDraw(); } render() { if (this.props.selectedShapeName.includes("text")) { var stuff = ( <Transformer ref={node => { this.transformer = node; }} name="transformer" boundBoxFunc={(oldBox, newBox) => { newBox.width = Math.max(30, newBox.width); return newBox; }} enabledAnchors={["middle-left", "middle-right"]} /> ); } else if (this.props.selectedShapeName.includes("star")) { var stuff = ( <Transformer ref={node => { this.transformer = node; }} name="transformer" enabledAnchors={[ "top-left", "top-right", "bottom-left", "bottom-right" ]} /> ); } else if (this.props.selectedShapeName.includes("arrow")) { var stuff = ( <Transformer ref={node => { this.transformer = node; }} name="transformer" resizeEnabled={false} rotateEnabled={false} /> ); } else { var stuff = ( <Transformer ref={node => { this.transformer = node; }} name="transformer" keepRatio={true} /> ); } return stuff; } } var history = []; var historyStep = 0; class Graphics extends Component { constructor(props) { super(props); this.state = { layerX: 0, layerY: 0, layerScale: 1, selectedShapeName: "", errMsg: "", rectangles: [], ellipses: [], stars: [], texts: [], arrows: [], connectors: [], currentTextRef: "", shouldTextUpdate: true, textX: 0, textY: 0, textEditVisible: false, arrowDraggable: false, newArrowRef: "", count: 0, newArrowDropped: false, newConnectorDropped: false, arrowEndX: 0, arrowEndY: 0, isTransforming: false, lastFill: null, saving: null, saved: [], roadmapId: null, alreadyCreated: false, publishing: false, title: "", category: "", description: "", thumbnail: "", isPasteDisabled: false, ellipseDeleteCount: 0, starDeleteCount: 0, arrowDeleteCount: 0, textDeleteCount: 0, rectDeleteCount: 0 }; this.handleWheel = this.handleWheel.bind(this); } handleSave = () => { const rects = this.state.rectangles, ellipses = this.state.ellipses, stars = this.state.stars, texts = this.state.texts, arrows = this.state.arrows; if ( JSON.stringify(this.state.saved) !== JSON.stringify([rects, ellipses, stars, texts, arrows]) ) { this.setState({ saved: [rects, ellipses, stars, texts, arrows] }); let arrows1 = this.state.arrows; arrows1.forEach(eachArrow => { //for "from & to of each arrow" if (eachArrow.from && eachArrow.from.attrs) { if (eachArrow.from.attrs.name.includes("text")) { eachArrow.from.textWidth = eachArrow.from.textWidth; eachArrow.from.textHeight = eachArrow.from.textHeight; } } if (eachArrow.to && eachArrow.to.attrs) { if (eachArrow.to.attrs.name.includes("text")) { eachArrow.to.attrs.textWidth = eachArrow.to.textWidth; eachArrow.to.attrs.textHeight = eachArrow.to.textHeight; } } }); if (this.state.roadmapId) { //if draft already exists this.setState({ saving: true }); fetch("/api/roadmap/modifyDraftDB", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ roadmapId: this.state.roadmapId, data: { rects: rects, ellipses: ellipses, stars: stars, texts: texts, arrows: arrows1 } }) }).then(res => { this.setState({ saving: false }); }); } else { //if first time pressing sav this.setState({ saving: true }); fetch("/api/roadmap/saveRoadmapToDB", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ userId: this.props.auth.user.id, roadmapType: "draft", data: { rects: rects, ellipses: ellipses, stars: stars, texts: texts, arrows: arrows } }) }).then(res => res.json().then(data => { this.setState({ saving: false }); this.setState({ roadmapId: data.roadmapId }); }) ); } } }; handleStageClick = e => { var pos = this.refs.layer2.getStage().getPointerPosition(); var shape = this.refs.layer2.getIntersection(pos); console.log("texts", this.state.texts); if ( shape !== null && shape.name() !== undefined && shape !== undefined && shape.name() !== undefined ) { this.setState( { selectedShapeName: shape.name() }, () => { this.refs.graphicStage.draw(); } ); } //arrow logic if (this.state.newArrowRef !== "") { if (this.state.previousShape) { if (this.state.previousShape.attrs.id !== "ContainerRect") { //console.log(this.refs.graphicStage.findOne("." + this.state.newArrowRef)); // this.state.arrows.map(eachArrow => { if (eachArrow.name === this.state.newArrowRef) { eachArrow.to = this.state.previousShape; } }); //console.log(newConnector, this.state.newArrowRef); //newConnector.setAttr("to", this.state.previousShape); //console.log(newConnector); } } //handle connector more //if the currentArrow ref has a from, and that e.target.attrs.id isn't containerRect, //then find the current shape with stage find name and then yeah this.state.arrows.map(eachArrow => { if (eachArrow.name === this.state.newArrowRef) { eachArrow.fill = "black"; eachArrow.stroke = "black"; } }); //arrow logic, there's e.evt.pageX, pageY this.setState({ arrowDraggable: false, newArrowRef: "" }); } }; handleMouseOver = event => { //get the currennt arrow ref and modify its position by filtering & pushing again //console.log("lastFill: ", this.state.lastFill); var pos = this.refs.graphicStage.getPointerPosition(); var shape = this.refs.graphicStage.getIntersection(pos); if (shape && shape.attrs.link) { document.body.style.cursor = "pointer"; } else { document.body.style.cursor = "default"; } //if we are moving an arrow if (this.state.newArrowRef !== "") { //filling color logic: var transform = this.refs.layer2.getAbsoluteTransform().copy(); transform.invert(); pos = transform.point(pos); this.setState({ arrowEndX: pos.x, arrowEndY: pos.y }); //last non arrow object if (shape && shape.attrs && shape.attrs.name != undefined) { // console.log(shape); if (!shape.attrs.name.includes("arrow")) { //after first frame if (this.state.previousShape) if (this.state.previousShape !== shape) { //arrow entered a new shape //set current arrow to blue if (this.state.previousShape.attrs.id !== "ContainerRect") { this.state.arrows.map(eachArrow => { if (eachArrow.name === this.state.newArrowRef) { eachArrow.fill = "black"; eachArrow.stroke = "black"; } }); this.forceUpdate(); } else { this.state.arrows.map(eachArrow => { if (eachArrow.name === this.state.newArrowRef) { eachArrow.fill = "#ccf5ff"; eachArrow.stroke = "#ccf5ff"; } }); this.forceUpdate(); } } //if arrow is moving in a single shape } if (!shape.attrs.name.includes("arrow")) { this.setState({ previousShape: shape }); } } } var arrows = this.state.arrows; arrows.map(eachArrow => { if (eachArrow.name === this.state.newArrowRef) { var index = arrows.indexOf(eachArrow); let currentArrow = eachArrow; currentArrow.points = [ currentArrow.points[0], currentArrow.points[1], pos.x, pos.y /* event.evt.pageY - document.getElementById("NavBar").getBoundingClientRect().height */ ]; this.state.arrows[index] = currentArrow; } }); }; handleWheel(event) { if ( this.state.rectangles.length === 0 && this.state.ellipses.length === 0 && this.state.stars.length === 0 && this.state.texts.length === 0 && this.state.arrows.length === 0 ) { } else { event.evt.preventDefault(); const scaleBy = 1.2; const stage = this.refs.graphicStage; const layer = this.refs.layer2; const oldScale = layer.scaleX(); const mousePointTo = { x: stage.getPointerPosition().x / oldScale - this.state.layerX / oldScale, y: stage.getPointerPosition().y / oldScale - this.state.layerY / oldScale }; const newScale = event.evt.deltaY < 0 ? oldScale * scaleBy : oldScale / scaleBy; layer.scale({ x: newScale, y: newScale }); /* console.log( oldScale, mousePointTo, stage.getPointerPosition().x, stage.getPointerPosition().y ); */ this.setState({ layerScale: newScale, layerX: -(mousePointTo.x - stage.getPointerPosition().x / newScale) * newScale, layerY: -(mousePointTo.y - stage.getPointerPosition().y / newScale) * newScale }); } } componentDidUpdate(prevProps, prevState) { let prevMainShapes = [ prevState.rectangles, prevState.ellipses, prevState.stars, prevState.arrows, prevState.connectors, prevState.texts ]; let currentMainShapes = [ this.state.rectangles, this.state.ellipses, this.state.stars, this.state.arrows, this.state.connectors, this.state.texts ]; if (!this.state.redoing && !this.state.isTransforming) if (JSON.stringify(this.state) !== JSON.stringify(prevState)) { if ( JSON.stringify(prevMainShapes) !== JSON.stringify(currentMainShapes) ) { //if text shouldn't update, don't append to history if (this.state.shouldTextUpdate) { var uh = history; history = uh.slice(0, historyStep + 1); //console.log("sliced", history); var toAppend = this.state; history = history.concat(toAppend); //console.log("new", history); historyStep += 1; //console.log(history, historyStep, history[historyStep]); } } } else { //console.log("compoenntDidUpdate but attrs didn't change"); } this.state.redoing = false; } handleUndo = () => { if (!this.state.isTransforming) { if (!this.state.textEditVisible) { if (historyStep === 0) { return; } historyStep -= 1; this.setState( { rectangles: history[historyStep].rectangles, arrows: history[historyStep].arrows, ellipses: history[historyStep].ellipses, stars: history[historyStep].stars, texts: history[historyStep].texts, connectors: history[historyStep].connectors, redoing: true, selectedShapeName: this.shapeIsGone(history[historyStep]) ? "" : this.state.selectedShapeName }, () => { this.refs.graphicStage.draw(); } ); } } }; handleRedo = () => { if (historyStep === history.length - 1) { return; } historyStep += 1; const next = history[historyStep]; this.setState( { rectangles: next.rectangles, arrows: next.arrows, ellipses: next.ellipses, stars: next.stars, texts: next.texts, redoing: true, selectedShapeName: this.shapeIsGone(history[historyStep]) ? "" : this.state.selectedShapeName }, () => { this.forceUpdate(); } ); }; shapeIsGone = returnTo => { var toReturn = true; let currentShapeName = this.state.selectedShapeName; let [rectangles, ellipses, stars, arrows, texts] = [ returnTo.rectangles, returnTo.ellipses, returnTo.stars, returnTo.arrows, returnTo.texts ]; rectangles.map(eachRect => { if (eachRect.name === currentShapeName) { toReturn = false; } }); ellipses.map(eachEllipse => { if (eachEllipse.name === currentShapeName) { toReturn = false; } }); stars.map(eachStar => { if (eachStar.name === currentShapeName) { toReturn = false; } }); arrows.map(eachArrow => { if (eachArrow.name === currentShapeName) { toReturn = false; } }); texts.map(eachText => { if (eachText.name === currentShapeName) { toReturn = false; } }); return toReturn; }; IsJsonString = str => { try { JSON.parse(str); } catch (e) { return false; } return true; }; async componentDidMount() { history.push(this.state); this.setState({ selectedShapeName: "" }); //if draft } render() { let saveText; let saving = this.state.saving; if (saving !== null) { if (saving) { saveText = <div style={{ color: "white" }}>Saving</div>; } else { saveText = <div style={{ color: "white" }}>Saved</div>; } } const canvas = document.createElement("canvas"); const ctx = canvas.getContext("2d"); var gradient = ctx.createLinearGradient(0, 0, 100, 100); gradient.addColorStop(0.0, "red"); gradient.addColorStop(1 / 6, "orange"); gradient.addColorStop(2 / 6, "yellow"); gradient.addColorStop(3 / 6, "green"); gradient.addColorStop(4 / 6, "aqua"); gradient.addColorStop(5 / 6, "blue"); gradient.addColorStop(1.0, "purple"); const errMsg = this.state.errMsg; let errDisplay; if (errMsg !== "") { errDisplay = ( <div className="errMsginner"> <span style={{ color: "white" }}> {errMsg !== "" ? errMsg : null} </span> </div> ); } else { } const countryOptions = [ { key: "1", value: "Machine Learning", text: "Machine Learning" }, { key: "2", value: "Computer Science", text: "Computer Science" }, { key: "3", value: "Software Engineering", text: "Software Engineering" }, { key: "12", value: "Technology", text: "Technology" }, { key: "4", value: "Engineering", text: "Engineering" }, { key: "6", value: "Sciences and Mathematics", text: "Sciences and Mathematics" }, { key: "7", value: "Law, Economics and Social Sciences", text: "Law, Economics and Social Sciences" }, { key: "8", value: "Humanities", text: "Humanities" }, { key: "9", value: "Linguistics and Cultural Studies", text: "Linguistics and Cultural Studies" }, { key: "10", value: "Art and Music", text: "Art and Music" }, { key: "11", value: "Lifestyle", text: "Lifestyle" }, { key: "13", value: "Others", text: "Others" } ]; return ( <React.Fragment> <div onKeyDown={event => { const x = 88, deleteKey = 46, copy = 67, paste = 86, z = 90, y = 89; if ( ((event.ctrlKey && event.keyCode === x) || event.keyCode === deleteKey) && !this.state.isPasteDisabled ) { if (this.state.selectedShapeName !== "") { var that = this; //delete it from the state too let name = this.state.selectedShapeName; let rectDeleted = false, ellipseDeleted = false, starDeleted = false, arrowDeleted = false, textDeleted = false; var rects = this.state.rectangles.filter(function (eachRect) { if (eachRect.name === name) { that.setState({ rectDeleteCount: that.state.rectDeleteCount + 1 }); } return eachRect.name !== name; }); var ellipses = this.state.ellipses.filter(function (eachRect) { if (eachRect.name === name) { that.setState({ ellipseDeleteCount: that.state.ellipseDeleteCount + 1 }); } return eachRect.name !== name; }); var stars = this.state.stars.filter(function (eachRect) { if (eachRect.name === name) { that.setState({ starDeleteCount: that.state.starDeleteCount + 1 }); } return eachRect.name !== name; }); var arrows = this.state.arrows.filter(function (eachRect) { if (eachRect.name === name) { that.setState({ arrowDeleteCount: that.state.arrowDeleteCount + 1 }); } return eachRect.name !== name; }); var texts = this.state.texts.filter(function (eachRect) { if (eachRect.name === name) { that.setState({ textDeleteCount: that.state.textDeleteCount + 1 }); } return eachRect.name !== name; }); this.setState({ rectangles: rects, ellipses: ellipses, stars: stars, arrows: arrows, texts: texts, selectedShapeName: "" }); } } else if (event.shiftKey && event.ctrlKey && event.keyCode === z) { this.handleRedo(); } else if (event.ctrlKey && event.keyCode === z) { this.handleUndo(); } else if (event.ctrlKey && event.keyCode === y) { this.handleRedo(); } else if (event.ctrlKey && event.keyCode === copy) { if (this.state.selectedShapeName !== "") { //find it let name = this.state.selectedShapeName; let copiedElement = null; if (name.includes("rect")) { copiedElement = this.state.rectangles.filter(function ( eachRect ) { return eachRect.name === name; }); } else if (name.includes("ellipse")) { copiedElement = this.state.ellipses.filter(function ( eachRect ) { return eachRect.name === name; }); } else if (name.includes("star")) { copiedElement = this.state.stars.filter(function (eachRect) { return eachRect.name === name; }); } else if (name.includes("text")) { copiedElement = this.state.texts.filter(function (eachRect) { return eachRect.name === name; }); } else if (name.includes("arrow")) { copiedElement = this.state.arrows.filter(function (eachRect) { return eachRect.name === name; }); } this.setState({ copiedElement: copiedElement }, () => { console.log("copied ele", this.state.copiedElement); }); } } else if ( event.ctrlKey && event.keyCode === paste && !this.state.isPasteDisabled ) { let copiedElement = this.state.copiedElement[0]; console.log(copiedElement); var length; if (copiedElement) { if (copiedElement.attrs) { } else { if (copiedElement.name.includes("rectangle")) { length = this.state.rectangles.length + 1 + this.state.rectDeleteCount; var toPush = { x: copiedElement.x + 10, y: copiedElement.y + 10, width: copiedElement.width, height: copiedElement.height, stroke: copiedElement.stroke, strokeWidth: copiedElement.strokeWidth, name: "rectangle" + (this.state.rectangles.length + this.state.rectDeleteCount + 1), ref: "rectangle" + (this.state.rectangles.length + this.state.rectDeleteCount + 1), fill: copiedElement.fill, useImage: copiedElement.useImage, link: copiedElement.link, rotation: copiedElement.rotation }; let newName = this.state.selectedShapeName; this.setState( prevState => ({ rectangles: [...prevState.rectangles, toPush] }), () => { this.setState({ selectedShapeName: "rectangle" + this.state.rectangles.length }); } ); } else if (copiedElement.name.includes("arrow")) { length = this.state.arrows.length + 1 + this.state.arrowDeleteCount; if (copiedElement.to || copiedElement.from) { this.setState( { errMsg: "Connectors cannot be pasted" }, () => { var that = this; setTimeout(function () { that.setState({ errMsg: "" }); }, 1000); } ); } else { var toPush = { points: [ copiedElement.points[0] + 30, copiedElement.points[1] + 30, copiedElement.points[2] + 30, copiedElement.points[3] + 30 ], fill: copiedElement.fill, link: copiedElement.link, stroke: copiedElement.stroke, strokeWidth: copiedElement.strokeWidth, name: "arrow" + (this.state.arrows.length + 1 + this.state.arrowDeleteCount), ref: "arrow" + (this.state.arrows.length + 1 + this.state.arrowDeleteCount), rotation: copiedElement.rotation }; let newName = this.state.selectedShapeName; this.setState( prevState => ({ arrows: [...prevState.arrows, toPush] }), () => { this.setState({ selectedShapeName: "arrow" + this.state.arrows.length }); } ); } } else if (copiedElement.name.includes("ellipse")) { length = this.state.ellipses.length + 1 + this.state.ellipseDeleteCount; var toPush = { x: copiedElement.x + 10, y: copiedElement.y + 10, radiusX: copiedElement.radiusX, radiusY: copiedElement.radiusY, stroke: copiedElement.stroke, strokeWidth: copiedElement.strokeWidth, name: "ellipse" + (this.state.ellipses.length + 1 + this.state.ellipseDeleteCount), ref: "ellipse" + (this.state.ellipses.length + 1 + this.state.ellipseDeleteCount), fill: copiedElement.fill, link: copiedElement.link, useImage: copiedElement.useImage, rotation: copiedElement.rotation }; let newName = this.state.selectedShapeName; this.setState( prevState => ({ ellipses: [...prevState.ellipses, toPush] }), () => { this.setState({ selectedShapeName: "ellipse" + this.state.ellipses.length }); } ); } else if (copiedElement.name.includes("star")) { length = this.state.stars.length + 1 + this.state.starDeleteCount; var toPush = { x: copiedElement.x + 10, y: copiedElement.y + 10, link: copiedElement.link, innerRadius: copiedElement.innerRadius, outerRadius: copiedElement.outerRadius, stroke: copiedElement.stroke, strokeWidth: copiedElement.strokeWidth, name: "star" + (this.state.stars.length + 1 + this.state.starDeleteCount), ref: "star" + (this.state.stars.length + 1 + this.state.starDeleteCount), fill: copiedElement.fill, useImage: copiedElement.useImage, rotation: copiedElement.rotation }; let newName = this.state.selectedShapeName; this.setState( prevState => ({ stars: [...prevState.stars, toPush] }), () => { this.setState({ selectedShapeName: "star" + this.state.stars.length }); } ); } else if (copiedElement.name.includes("text")) { length = this.state.texts.length + 1 + this.state.textDeleteCount; var toPush = { x: copiedElement.x + 10, y: copiedElement.y + 10, link: copiedElement.link, name: "text" + (this.state.texts.length + 1 + this.state.textDeleteCount), ref: "text" + (this.state.texts.length + 1 + this.state.textDeleteCount), fill: copiedElement.fill, fontSize: copiedElement.fontSize, fontFamily: copiedElement.fontFamily, useImage: copiedElement.useImage, text: copiedElement.text, width: copiedElement.width, rotation: copiedElement.rotation }; let newName = this.state.selectedShapeName; this.setState( prevState => ({ texts: [...prevState.texts, toPush] }), () => { this.setState( { selectedShapeName: "text" + (this.state.texts.length + this.state.textDeleteCount) }, () => { console.log(this.state.selectedShapeName); } ); } ); } } } } }} tabIndex="0" style={{ outline: "none" }} > <Stage onClick={this.handleStageClick} onMouseMove={this.handleMouseOver} onWheel={event => this.handleWheel(event)} height={window.innerHeight} width={window.innerWidth} ref="graphicStage" > <Layer scaleX={this.state.layerScale} scaleY={this.state.layerScale} x={this.state.layerX} y={this.state.layerY} height={window.innerHeight} width={window.innerWidth} draggable onDragEnd={() => { this.setState({ layerX: this.refs.layer2.x(), layerY: this.refs.layer2.y() }); }} ref="layer2" > <Rect x={-5 * window.innerWidth} y={-5 * window.innerHeight} height={window.innerHeight * 10} width={window.innerWidth * 10} name="" id="ContainerRect" /> {this.state.rectangles.map(eachRect => { return ( <Rect onClick={() => { var that = this; if (eachRect.link !== undefined && eachRect.link !== "") { this.setState( { errMsg: "Links will not be opened in create mode" }, () => { setTimeout(function () { that.setState({ errMsg: "" }); }, 1000); } ); } }} onTransformStart={() => { this.setState({ isTransforming: true }); let rect = this.refs[eachRect.ref]; rect.setAttr("lastRotation", rect.rotation()); }} onTransform={() => { let rect = this.refs[eachRect.ref]; if (rect.attrs.lastRotation !== rect.rotation()) { this.state.arrows.map(eachArrow => { if ( eachArrow.to && eachArrow.to.name() === rect.name() ) { this.setState({ errMsg: "Rotating rects with connectors might skew things up!" }); } if ( eachArrow.from && eachArrow.from.name() === rect.name() ) { this.setState({ errMsg: "Rotating rects with connectors might skew things up!" }); } }); } rect.setAttr("lastRotation", rect.rotation()); }} onTransformEnd={() => { this.setState({ isTransforming: false }); let rect = this.refs[eachRect.ref]; this.setState( prevState => ({ errMsg: "", rectangles: prevState.rectangles.map(eachRect => eachRect.name === rect.attrs.name ? { ...eachRect, width: rect.width() * rect.scaleX(), height: rect.height() * rect.scaleY(), rotation: rect.rotation(), x: rect.x(), y: rect.y() } : eachRect ) }), () => { this.forceUpdate(); } ); rect.setAttr("scaleX", 1); rect.setAttr("scaleY", 1); }} rotation={eachRect.rotation} ref={eachRect.ref} fill={eachRect.fill} name={eachRect.name} x={eachRect.x} y={eachRect.y} width={eachRect.width} height={eachRect.height} stroke={eachRect.stroke} strokeWidth={eachRect.strokeWidth} strokeScaleEnabled={false} draggable onDragMove={() => { this.state.arrows.map(eachArrow => { if (eachArrow.from !== undefined) { if (eachRect.name === eachArrow.from.attrs.name) { eachArrow.points = [ eachRect.x, eachRect.y, eachArrow.points[2], eachArrow.points[3] ]; this.forceUpdate(); } } if (eachArrow.to !== undefined) { if (eachRect.name == eachArrow.to.attrs.name) { eachArrow.points = [ eachArrow.points[0], eachArrow.points[1], eachRect.x, eachRect.y ]; this.forceUpdate(); } } }); }} onDragEnd={event => { //cannot compare by name because currentSelected might not be the same //have to use ref, which appears to be overcomplicated var shape = this.refs[eachRect.ref]; /* this.state.rectangles.map(eachRect => { if (eachRect.name === shape.attrs.name) { shape.position({ x: event.target.x(), y: event.target.y() }); } });*/ this.setState(prevState => ({ rectangles: prevState.rectangles.map(eachRect => eachRect.name === shape.attrs.name ? { ...eachRect, x: event.target.x(), y: event.target.y() } : eachRect ) })); }} /> ); })} {this.state.ellipses.map(eachEllipse => ( <Ellipse ref={eachEllipse.ref} name={eachEllipse.name} x={eachEllipse.x} y={eachEllipse.y} rotation={eachEllipse.rotation} radiusX={eachEllipse.radiusX} radiusY={eachEllipse.radiusY} fill={eachEllipse.fill} stroke={eachEllipse.stroke} strokeWidth={eachEllipse.strokeWidth} strokeScaleEnabled={false} onClick={() => { var that = this; if ( eachEllipse.link !== undefined && eachEllipse.link !== "" ) { this.setState( { errMsg: "Links will not be opened in create mode" }, () => { setTimeout(function () { that.setState({ errMsg: "" }); }, 1000); } ); } }} onTransformStart={() => { this.setState({ isTransforming: true }); let ellipse = this.refs[eachEllipse.ref]; ellipse.setAttr("lastRotation", ellipse.rotation()); }} onTransform={() => { let ellipse = this.refs[eachEllipse.ref]; if (ellipse.attrs.lastRotation !== ellipse.rotation()) { this.state.arrows.map(eachArrow => { if ( eachArrow.to && eachArrow.to.name() === ellipse.name() ) { this.setState({ errMsg: "Rotating ellipses with connectors might skew things up!" }); } if ( eachArrow.from && eachArrow.from.name() === ellipse.name() ) { this.setState({ errMsg: "Rotating ellipses with connectors might skew things up!" }); } }); } ellipse.setAttr("lastRotation", ellipse.rotation()); }} onTransformEnd={() => { this.setState({ isTransforming: false }); let ellipse = this.refs[eachEllipse.ref]; let scaleX = ellipse.scaleX(), scaleY = ellipse.scaleY(); this.setState(prevState => ({ errMsg: "", ellipses: prevState.ellipses.map(eachEllipse => eachEllipse.name === ellipse.attrs.name ? { ...eachEllipse, radiusX: ellipse.radiusX() * ellipse.scaleX(), radiusY: ellipse.radiusY() * ellipse.scaleY(), rotation: ellipse.rotation(), x: ellipse.x(), y: ellipse.y() } : eachEllipse ) })); ellipse.setAttr("scaleX", 1); ellipse.setAttr("scaleY", 1); this.forceUpdate(); }} draggable onDragMove={() => { console.log( "name of ellipse moving: ", eachEllipse.name, "new x y", eachEllipse.x, eachEllipse.y ); this.state.arrows.map(eachArrow => { if (eachArrow.from !== undefined) { console.log("prevArrow: ", eachArrow.points); if (eachEllipse.name == eachArrow.from.attrs.name) { eachArrow.points = [ eachEllipse.x, eachEllipse.y, eachArrow.points[2], eachArrow.points[3] ]; this.forceUpdate(); this.refs.graphicStage.draw(); } console.log("new arrows:", eachArrow.points); } if (eachArrow.to !== undefined) { if (eachEllipse.name === eachArrow.to.attrs.name) { eachArrow.points = [ eachArrow.points[0], eachArrow.points[1], eachEllipse.x, eachEllipse.y ]; this.forceUpdate(); this.refs.graphicStage.draw(); } } }); }} onDragEnd={event => { //cannot compare by name because currentSelected might not be the same //have to use ref, which appears to be overcomplicated var shape = this.refs[eachEllipse.ref]; this.setState(prevState => ({ ellipses: prevState.ellipses.map(eachEllipse => eachEllipse.name === shape.attrs.name ? { ...eachEllipse, x: event.target.x(), y: event.target.y() } : eachEllipse ) })); this.refs.graphicStage.draw(); }} /> ))} {this.state.stars.map(eachStar => ( <Star ref={eachStar.ref} name={eachStar.name} x={eachStar.x} y={eachStar.y} innerRadius={eachStar.innerRadius} outerRadius={eachStar.outerRadius} numPoints={eachStar.numPoints} stroke={eachStar.stroke} strokeWidth={eachStar.strokeWidth} fill={eachStar.fill} strokeScaleEnabled={false} rotation={eachStar.rotation} onClick={() => { var that = this; if (eachStar.link !== undefined && eachStar.link !== "") { this.setState( { errMsg: "Links will not be opened in create mode" }, () => { setTimeout(function () { that.setState({ errMsg: "" }); }, 1000); } ); } }} onTransformStart={() => { this.setState({ isTransforming: true }); }} onTransformEnd={() => { this.setState({ isTransforming: false }); let star = this.refs[eachStar.ref]; let scaleX = star.scaleX(), scaleY = star.scaleY(); this.setState(prevState => ({ stars: prevState.stars.map(eachStar => eachStar.name === star.attrs.name ? { ...eachStar, innerRadius: star.innerRadius() * star.scaleX(), outerRadius: star.outerRadius() * star.scaleX(), rotation: star.rotation(), x: star.x(), y: star.y() } : eachStar ) })); star.setAttr("scaleX", 1); star.setAttr("scaleY", 1); this.forceUpdate(); }} draggable onDragMove={() => { this.state.arrows.map(eachArrow => { if (eachArrow.from !== undefined) { if (eachStar.name == eachArrow.from.attrs.name) { eachArrow.points = [ eachStar.x, eachStar.y, eachArrow.points[2], eachArrow.points[3] ]; this.forceUpdate(); } } if (eachArrow.to !== undefined) { if (eachStar.name === eachArrow.to.attrs.name) { eachArrow.points = [ eachArrow.points[0], eachArrow.points[1], eachStar.x, eachStar.y ]; this.forceUpdate(); } } }); }} onDragEnd={event => { //cannot compare by name because currentSelected might not be the same //have to use ref, which appears to be overcomplicated var shape = this.refs[eachStar.ref]; this.setState(prevState => ({ stars: prevState.stars.map(eachStar => eachStar.name === shape.attrs.name ? { ...eachStar, x: event.target.x(), y: event.target.y() } : eachStar ) })); }} /> ))} {this.state.texts.map(eachText => ( //perhaps this.state.texts only need to contain refs? //so that we only need to store the refs to get more information <Text textDecoration={eachText.link ? "underline" : ""} onTransformStart={() => { var currentText = this.refs[this.state.selectedShapeName]; currentText.setAttr("lastRotation", currentText.rotation()); }} onTransform={() => { var currentText = this.refs[this.state.selectedShapeName]; currentText.setAttr( "width", currentText.width() * currentText.scaleX() ); currentText.setAttr("scaleX", 1); currentText.draw(); if ( currentText.attrs.lastRotation !== currentText.rotation() ) { this.state.arrows.map(eachArrow => { if ( eachArrow.to && eachArrow.to.name() === currentText.name() ) { this.setState({ errMsg: "Rotating texts with connectors might skew things up!" }); } if ( eachArrow.from && eachArrow.from.name() === currentText.name() ) { this.setState({ errMsg: "Rotating texts with connectors might skew things up!" }); } }); } currentText.setAttr("lastRotation", currentText.rotation()); }} onTransformEnd={() => { var currentText = this.refs[this.state.selectedShapeName]; this.setState(prevState => ({ errMsg: "", texts: prevState.texts.map(eachText => eachText.name === this.state.selectedShapeName ? { ...eachText, width: currentText.width(), rotation: currentText.rotation(), textWidth: currentText.textWidth, textHeight: currentText.textHeight, x: currentText.x(), y: currentText.y() } : eachText ) })); currentText.setAttr("scaleX", 1); currentText.draw(); }} link={eachText.link} width={eachText.width} fill={eachText.fill} name={eachText.name} ref={eachText.ref} rotation={eachText.rotation} fontFamily={eachText.fontFamily} fontSize={eachText.fontSize} x={eachText.x} y={eachText.y} text={eachText.text} draggable onDragMove={() => { this.state.arrows.map(eachArrow => { if (eachArrow.from !== undefined) { if (eachText.name === eachArrow.from.attrs.name) { eachArrow.points = [ eachText.x, eachText.y, eachArrow.points[2], eachArrow.points[3] ]; this.forceUpdate(); } } if (eachArrow.to !== undefined) { if (eachText.name === eachArrow.to.attrs.name) { eachArrow.points = [ eachArrow.points[0], eachArrow.points[1], eachText.x, eachText.y ]; this.forceUpdate(); } } }); }} onDragEnd={event => { //cannot compare by name because currentSelected might not be the same //have to use ref, which appears to be overcomplicated var shape = this.refs[eachText.ref]; this.setState(prevState => ({ texts: prevState.texts.map(eachtext => eachtext.name === shape.attrs.name ? { ...eachtext, x: event.target.x(), y: event.target.y() } : eachtext ) })); }} onClick={() => { var that = this; if (eachText.link !== undefined && eachText.link !== "") { this.setState( { errMsg: "Links will not be opened in create mode" }, () => { setTimeout(function () { that.setState({ errMsg: "" }); }, 1000); } ); //var win = window.open(eachText.link, "_blank"); //win.focus(); } }} onDblClick={() => { // turn into textarea var stage = this.refs.graphicStage; var text = stage.findOne("." + eachText.name); this.setState({ textX: text.absolutePosition().x, textY: text.absolutePosition().y, textEditVisible: !this.state.textEditVisible, text: eachText.text, textNode: eachText, currentTextRef: eachText.ref, textareaWidth: text.textWidth, textareaHeight: text.textHeight, textareaFill: text.attrs.fill, textareaFontFamily: text.attrs.fontFamily, textareaFontSize: text.attrs.fontSize }); let textarea = this.refs.textarea; textarea.focus(); text.hide(); var transformer = stage.findOne(".transformer"); transformer.hide(); this.refs.layer2.draw(); }} /> ))} {this.state.arrows.map(eachArrow => { if (!eachArrow.from && !eachArrow.to) { return ( <Arrow ref={eachArrow.ref} name={eachArrow.name} points={[ eachArrow.points[0], eachArrow.points[1], eachArrow.points[2], eachArrow.points[3] ]} stroke={eachArrow.stroke} fill={eachArrow.fill} draggable onDragEnd={event => { //set new points to current position //usually: state => star => x & y //now: state => arrow => attr => x & y let oldPoints = [ eachArrow.points[0], eachArrow.points[1], eachArrow.points[2], eachArrow.points[3] ]; let shiftX = this.refs[eachArrow.ref].attrs.x; let shiftY = this.refs[eachArrow.ref].attrs.y; let newPoints = [ oldPoints[0] + shiftX, oldPoints[1] + shiftY, oldPoints[2] + shiftX, oldPoints[3] + shiftY ]; this.refs[eachArrow.ref].position({ x: 0, y: 0 }); this.refs.layer2.draw(); this.setState(prevState => ({ arrows: prevState.arrows.map(eachArr => eachArr.name === eachArrow.name ? { ...eachArr, points: newPoints } : eachArr ) })); }} /> ); } else if ( eachArrow.name === this.state.newArrowRef && (eachArrow.from || eachArrow.to) ) { return ( <Connector name={eachArrow.name} from={eachArrow.from} to={eachArrow.to} arrowEndX={this.state.arrowEndX} arrowEndY={this.state.arrowEndY} current={true} stroke={eachArrow.stroke} fill={eachArrow.fill} /> ); } else if (eachArrow.from || eachArrow.to) { //if arrow construction is completed return ( <Connector name={eachArrow.name} from={eachArrow.from} to={eachArrow.to} points={eachArrow.points} current={false} stroke={eachArrow.stroke} fill={eachArrow.fill} /> ); } })} {this.state.selectedShapeName.includes("text") ? ( <TransformerComponent selectedShapeName={this.state.selectedShapeName} /> ) : ( <TransformerComponent selectedShapeName={this.state.selectedShapeName} /> )} </Layer> <Layer height={window.innerHeight} width={window.innerWidth} ref="layer" > <Toolbar layer={this.refs.layer2} rectName={ this.state.rectangles.length + 1 + this.state.rectDeleteCount } ellipseName={ this.state.ellipses.length + 1 + this.state.ellipseDeleteCount } starName={ this.state.stars.length + 1 + this.state.starDeleteCount } textName={ this.state.texts.length + 1 + this.state.textDeleteCount } newArrowOnDragEnd={toPush => { if (toPush.from !== undefined) { // console.log("we are making a connector"); var transform = this.refs.layer2 .getAbsoluteTransform() .copy(); transform.invert(); let uh = transform.point({ x: toPush.x, y: toPush.y }); toPush.x = uh.x; toPush.y = uh.y; var newArrow = { points: toPush.points, ref: "arrow" + (this.state.arrows.length + 1 + this.state.arrowDeleteCount), name: "arrow" + (this.state.arrows.length + 1 + this.state.arrowDeleteCount), from: toPush.from, stroke: toPush.stroke, strokeWidth: toPush.strokeWidth, fill: toPush.fill }; // console.log(newArrow); this.setState(prevState => ({ arrows: [...prevState.arrows, newArrow], newArrowDropped: true, newArrowRef: newArrow.name, arrowEndX: toPush.x, arrowEndY: toPush.y })); } else { // console.log("we are making just an aarrow"); var transform = this.refs.layer2 .getAbsoluteTransform() .copy(); transform.invert(); let uh = transform.point({ x: toPush.x, y: toPush.y }); toPush.x = uh.x; toPush.y = uh.y; var newArrow = { points: [toPush.x, toPush.y, toPush.x, toPush.y], ref: "arrow" + (this.state.arrows.length + 1 + this.state.arrowDeleteCount), name: "arrow" + (this.state.arrows.length + 1 + this.state.arrowDeleteCount), from: toPush.from, stroke: toPush.stroke, strokeWidth: toPush.strokeWidth, fill: toPush.fill }; this.setState(prevState => ({ arrows: [...prevState.arrows, newArrow], newArrowDropped: true, newArrowRef: newArrow.name, arrowEndX: toPush.x, arrowEndY: toPush.y })); } //this.refs updates after forceUpdate (because arrow gets instantiated), might be risky in the future //only this.state.arrows.length because it was pushed earlier, cancelling the +1 }} appendToRectangles={stuff => { var layer = this.refs.layer2; var toPush = stuff; var stage = this.refs.graphicStage; var transform = this.refs.layer2 .getAbsoluteTransform() .copy(); transform.invert(); var pos = transform.point({ x: toPush.x, y: toPush.y }); if (layer.attrs.x !== null || layer.attrs.x !== undefined) { toPush.x = pos.x; toPush.y = pos.y; } this.setState(prevState => ({ rectangles: [...prevState.rectangles, toPush], selectedShapeName: toPush.name })); }} appendToEllipses={stuff => { var layer = this.refs.layer2; var toPush = stuff; var stage = this.refs.graphicStage; var transform = this.refs.layer2 .getAbsoluteTransform() .copy(); transform.invert(); var pos = transform.point({ x: toPush.x, y: toPush.y }); if (layer.attrs.x !== null || layer.attrs.x !== undefined) { toPush.x = pos.x; toPush.y = pos.y; } this.setState(prevState => ({ ellipses: [...prevState.ellipses, toPush], selectedShapeName: toPush.name })); }} appendToStars={stuff => { var layer = this.refs.layer2; var toPush = stuff; var stage = this.refs.graphicStage; var transform = this.refs.layer2 .getAbsoluteTransform() .copy(); transform.invert(); var pos = transform.point({ x: toPush.x, y: toPush.y }); if (layer.attrs.x !== null || layer.attrs.x !== undefined) { toPush.x = pos.x; toPush.y = pos.y; } this.setState(prevState => ({ stars: [...prevState.stars, toPush], selectedShapeName: toPush.name })); }} appendToTexts={stuff => { var layer = this.refs.layer2; var toPush = stuff; var stage = this.refs.graphicStage; var transform = this.refs.layer2 .getAbsoluteTransform() .copy(); transform.invert(); var pos = transform.point({ x: toPush.x, y: toPush.y }); if (layer.attrs.x !== null || layer.attrs.x !== undefined) { toPush.x = pos.x; toPush.y = pos.y; } this.setState(prevState => ({ texts: [...prevState.texts, toPush] })); //we can also just get element by this.refs.toPush.ref // let text = stage.findOne("." + toPush.name); let text = this.refs[toPush.ref]; //this.setState({firstTimeTextEditing: true}); text.fire("dblclick"); }} /> </Layer> </Stage> <textarea ref="textarea" id="textarea" value={this.state.text} onChange={e => { this.setState({ text: e.target.value, shouldTextUpdate: false }); }} onKeyDown={e => { if (e.keyCode === 13) { this.setState({ textEditVisible: false, shouldTextUpdate: true }); // get the current textNode we are editing, get the name from there //match name with elements in this.state.texts, let node = this.refs[this.state.currentTextRef]; console.log("node width before set", node.textWidth); let name = node.attrs.name; this.setState( prevState => ({ selectedShapeName: name, texts: prevState.texts.map(eachText => eachText.name === name ? { ...eachText, text: this.state.text } : eachText ) }), () => { this.setState(prevState => ({ texts: prevState.texts.map(eachText => eachText.name === name ? { ...eachText, textWidth: node.textWidth, textHeight: node.textHeight } : eachText ) })); } ); node.show(); this.refs.graphicStage.findOne(".transformer").show(); } }} onBlur={() => { this.setState({ textEditVisible: false, shouldTextUpdate: true }); // get the current textNode we are editing, get the name from there //match name with elements in this.state.texts, let node = this.refs.graphicStage.findOne( "." + this.state.currentTextRef ); let name = node.attrs.name; this.setState( prevState => ({ selectedShapeName: name, texts: prevState.texts.map(eachText => eachText.name === name ? { ...eachText, text: this.state.text } : eachText ) }), () => { this.setState(prevState => ({ texts: prevState.texts.map(eachText => eachText.name === name ? { ...eachText, textWidth: node.textWidth, textHeight: node.textHeight } : eachText ) })); } ); node.show(); this.refs.graphicStage.findOne(".transformer").show(); this.refs.graphicStage.draw(); }} style={{ //set position, width, height, fontSize, overflow, lineHeight, color display: this.state.textEditVisible ? "block" : "none", position: "absolute", top: this.state.textY + 80 + "px", left: this.state.textX + "px", width: "300px", height: "300px", overflow: "hidden", fontSize: this.state.textareaFontSize, fontFamily: this.state.textareaFontFamily, color: this.state.textareaFill, border: "none", padding: "0px", margin: "0px", outline: "none", resize: "none", background: "none" }} /> <div className="errMsg">{errDisplay}</div> </div> </React.Fragment> ); } } const mapStateToProps = state => ({ auth: state.auth }); export default Graphics;
c932a9239662d7d8188d0e5d6300404b3a9ca317
[ "JavaScript" ]
2
JavaScript
Creatune/Flowchart-Wizard-React
9a404b55db82d6a95b48122d657dc57e8a37ef69
58c70761e54d05b4c749a37f1012b093516c5177
refs/heads/master
<file_sep>import {get, post } from './http'; /* =======================用户相关函数====================== */ //判断管理员是否登录成功 export const getLoginStatus = (params) => post(`admin/login/status`, params); //查询用户 export const getAllUser = () => get(`/user/getAllUser`); //添加用户 export const setUser = (params) => post(`/user/add`, params); //修改用户 export const updateUser = (params) => post(`/user/update`, params); //删除用户 export const deleteUser = (id) => get(`/user/delete?id=${id}`); //切换用户是否被锁定 export const isLocked = (flag, id) => get(`/user/toggleFlag?flag=${flag}&id=${id}`); //通过用户id查询相关信息 export const getByPrimaryKey = (id) => get(`/user/getByPrimaryKey?id=${id}`); /* =======================动态相关函数====================== */ //获取信息 export const getShareByUserId = (userId) => get(`/sceneryshare/user/scenery?userId=${userId}`); //删除记录 export const deleteShare = (id) => get(`/sceneryshare/delete?id=${id}`); //设置/取消精华 export const toggleEssence = (essence, id) => get(`/sceneryshare/toggleEssence?essence=${essence}&id=${id}`); //获取所有的动态 export const getAllShare = () => get(`/sceneryshare/getAllSceneryShare`); //通过用户id获取总动态数 export const getCountByUserId = (userId) => get(`/sceneryshare/getCountByUserId?userId=${userId}`); //设置是否可见 export const toggleVisible = (visible, id) => get(`/sceneryshare/toggleVisible?visible=${visible}&id=${id}`); //修改动态属性 export const updateShare = (params) => post(`/sceneryshare/update`, params); /* =======================景区相关函数====================== */ //获取所有的景区信息 export const getAllScenery = () => get(`/scenery/getAllScenery`); //删除景点 export const deleteScenery = (id) => get(`/scenery/delete?id=${id}`); //切换景点是否可用 export const toggleFlag = (flag, id) => get(`/scenery/toggleFlag?flag=${flag}&id=${id}`); //获取一级景点 export const getFirstScenery = () => get(`/scenery/getFirstScenery`); //修改景点类型 export const updateType = (type,id) => get(`/scenery/updateType?type=${type}&id=${id}`); //修改父景点id export const updateParentId = (parentId,id) => get(`/scenery/updateParentId?parentId=${parentId}&id=${id}`); //通过主键获取景点信息 export const getSceneryById = (id) => get(`/scenery/getByPrimaryKey?id=${id}`); /* =======================意见反馈相关函数====================== */ //获取意见反馈列表 export const getAllFeedback = () => get(`/feedback/getAllFeedback`); //回复意见 export const reply = (params) => post(`/feedback/reply`, params); /* =======================信息统计相关函数====================== */ //最近七天新增数据 export const getLatestWeekNew = () => get(`/info/getLatestWeekNew`);
8d6a350e58a8533c4d78b9a9ec51c0608ccc283f
[ "JavaScript" ]
1
JavaScript
lxy6083/sceneryshare-manage
11cf72a5c03cfe7cdd72dbcb82925a06a1b9e8ed
e566e9ebfeff1531a5f261afffa9bb748db205b4
refs/heads/master
<repo_name>hidrorium/ricco<file_sep>/inputDct.php <!Doctype html> <?php session_start(); if(isset($_SESSION['login']) && $_SESSION['login'] == 1) { ?> <html> <head> <title>Dictionary Management</title> <link rel="stylesheet" type="text/css" href="Style/Style.css"> </head> <body> <div class="isi"> <h3>INPUT DICTIONARY</h3> <form id="task" action="" method="POST"> <table> <tr> <td><select> <option value="">Select Category</option> </select> </td> <td></td> <td></td> </tr> <tr> <td>ID</td> <td>:</td> <td><input type="text" name="id" placeholder="ID" /></td> </tr> <tr> <td>Word</td> <td>:</td> <td><input type="text" name="word" placeholder="Word" /></td> </tr> <tr> <td></td> <td></td> <td><input type="submit" name="input" value="INPUT" /></td> </tr> <tr> <td><input type="submit" name="back" value="BACK" /></td> <td></td> <td></td> </tr> </table> </form> </div> </body> </html> <?php } else { echo "Anda belum login, silahkan login dulu."; echo "<a href='Login.php'>Login</a>"; } ?>
b138204e873df15dfa460a907de4ecf8f2e5e543
[ "PHP" ]
1
PHP
hidrorium/ricco
dc1724a3c0b21541bc97e4593c7847c085c7fbb7
de1468c3bab2705a3a91adf2334747bfe4213fc1
refs/heads/master
<file_sep>#define _GNU_SOURCE #include <stdio.h> #include <stdlib.h> #include "env_settings.h" // for GetStringSetting #include "logging.h" // for Log, LogErrno #include "banner.h" /*! \brief Read banner message from file * * \param banner Array of pointers to store the banner lines * \param num_lines The number of lines read from the file * \param max_lines Maximum number of lines to read * \return 0 if sucsessful, 1 if unable to open file, 2 if error reading */ int ReadBannerFile(char **banner, int *num_lines, int max_lines) { int rtn = 0; const char *filename = GetStringSetting("XSECURELOCK_BANNER_FILE", BANNER_FILENAME); FILE *fp; fp = fopen(filename, "r"); if (fp == NULL) { *num_lines = 0; Log("Failed to open banner file %s", filename); return 1; } char **line = banner; size_t line_len; *num_lines = 0; ssize_t read; for (int i=0;i < max_lines; i++) { banner[i] = NULL; } while ((read = getline(line, &line_len, fp)) != -1) { // Remove last newline (*line)[read - 1] = 0; (*num_lines)++; if (*num_lines >= max_lines) { rtn = 2; break; } line++; } fclose(fp); return rtn; } <file_sep># Building debian package The debian package can be built using `git-buildpackage` from the git repository using: ``` mkdir -p ../build-area uscan --force-download --destdir ../build-area gbp buildpackage --git-debian-branch=debian -uc -us --git-tarball-dir=../build-area --git-export-dir=../build-area ``` The changelog can be updated with ``` gbp dch [-N <version> | -S <snapshot>] --debian-branch=debian --git-author --since <tag> ``` <file_sep>#define _GNU_SOURCE #include <stdio.h> #include <stdlib.h> #include <string.h> #include <pwd.h> #include <grp.h> #include <unistd.h> #include "env_settings.h" // for GetStringSetting #include "logging.h" // for Log, LogErrno #include "userfile.h" const char *userfile_match_string[] = { "NO_MATCH", "USERNAME_MATCH", "GROUP_MATCH" }; int IsMemberOfGroup(const char *username, const char *grname, int *match) { int i, ngroups; gid_t *groups; struct passwd *pw; struct group *gr; *match = 0; pw = getpwnam(username); if (pw == NULL) { return USERFILE_ERROR; } ngroups = 0; getgrouplist(username, pw->pw_gid, NULL, &ngroups); groups = malloc(ngroups * sizeof (gid_t)); if (groups == NULL) { Log("Unable to allocate memory"); return USERFILE_ERROR; } if (getgrouplist(username, pw->pw_gid, groups, &ngroups) == -1) { Log("getgrouplist returned -1"); return USERFILE_ERROR; } for (i = 0; i < ngroups; i++) { gr = getgrgid(groups[i]); if (gr != NULL) { if (!strcmp(grname, gr->gr_name)) { *match = 1; break; } } } free(groups); return USERFILE_SUCCESS; } int UserInAuthListFile(const char * filename, const char* username, int *match) { int rtn = USERFILE_SUCCESS; *match = 0; FILE *fp; fp = fopen(filename, "r"); if (fp == NULL) { Log("Failed to open user file %s", filename); return USERFILE_ERROR; } char *line = NULL; size_t len = 0; ssize_t nread; while ((nread = getline(&line, &len, fp)) != -1) { // Remove newline at end line[strcspn(line, "\r\n")] = 0; // Tokenize const char *tokens = "\t :"; char *_line; char *token = strtok_r(line, tokens, &_line); if (token[0] != '#') { if(token[0] == '@') { // Process a group token++; // Remove @ if (IsMemberOfGroup(username, token, match) != USERFILE_SUCCESS) { *match = USERFILE_NO_MATCH; rtn = USERFILE_ERROR; break; } else { if (*match) { *match = USERFILE_GROUP_MATCH; rtn = USERFILE_SUCCESS; } } } else { if (strcmp(username, token) == 0) { // We have a match *match = USERFILE_USER_MATCH; rtn = USERFILE_SUCCESS; } } if (*match) { while ((token = strtok_r(NULL, tokens, &_line)) != NULL) { // Proces tokens } break; } } } free(line); fclose(fp); return rtn; } int UserInAuthListPriv(const char* username, int *match) { int rtn; #ifdef SECURE const char *filename = USERFILE_PRIV; #else const char *filename = GetStringSetting("XSECURELOCK_USERFILE_PRIV", USERFILE_PRIV); #endif rtn = UserInAuthListFile(filename, username, match); return rtn; } int UserInAuthListBlock(const char* username, int *match) { int rtn; #ifdef SECURE const char *filename = USERFILE_BLOCK; #else const char *filename = GetStringSetting("XSECURELOCK_USERFILE_BLOCK", USERFILE_BLOCK); #endif rtn = UserInAuthListFile(filename, username, match); return rtn; } int UserInAuthListAny(const char* username, int *match) { int rtn; #ifdef SECURE const char *filename = USERFILE_ANY; #else const char *filename = GetStringSetting("XSECURELOCK_USERFILE_ANY", USERFILE_ANY); #endif rtn = UserInAuthListFile(filename, username, match); return rtn; } int UserInNoBlankList(const char* username, int *match) { int rtn; #ifdef SECURE const char *filename = USERFILE_NOBLANK; #else const char *filename = GetStringSetting("XSECURELOCK_USERFILE_BLANK", USERFILE_NOBLANK); #endif rtn = UserInAuthListFile(filename, username, match); return rtn; } <file_sep>#!/bin/bash - set -a -u GSETTINGS=/usr/bin/gsettings XSET=/usr/bin/xset XAUTOLOCK_TIME=15 XAUTOLOCK=/usr/bin/xautolock XSECURELOCK=@bindir@/xsecurelock if [ -f "@sysconfdir@/xsecurelock/config" ]; then source @sysconfdir@/xsecurelock/config fi # Disable the built in screensaver and show wallpaper if command -v ${GSETTINGS} > /dev/null 2>&1 then ${GSETTINGS} set org.gnome.desktop.session idle-delay 0 > /dev/null 2>&1 ${GSETTINGS} set org.gnome.desktop.screensaver idle-activation-enabled false > /dev/null 2>&1 ${GSETTINGS} set org.gnome.desktop.screensaver lock-enabled false > /dev/null 2>&1 ${GSETTINGS} set org.cinnamon.desktop.session idle-delay 0 > /dev/null 2>&1 ${GSETTINGS} set org.mate.screensaver idle-activation-enabled false > /dev/null 2>&1 fi if command -v xset > /dev/null 2>&1 then sleep 10; ${XSET} s off > /dev/null 2>&1 sleep 10; ${XSET} s noblank > /dev/null 2>&1 fi exec ${XAUTOLOCK} -time ${XAUTOLOCK_TIME} -secure -locker ${XSECURELOCK} <file_sep># Copyright 2014 Google Inc. All rights reserved. # # 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. CLEANFILES = macros = \ -DHELPER_PATH=\"$(pkglibexecdir)\" \ -DDOCS_PATH=\"$(docdir)\" \ -DAUTH_EXECUTABLE=\"@auth_executable@\" \ -DAUTHPROTO_EXECUTABLE=\"@authproto_executable@\" \ -DGLOBAL_SAVER_EXECUTABLE=\"@global_saver_executable@\" \ -DSAVER_EXECUTABLE=\"@saver_executable@\" \ -DPAM_SERVICE_NAME=\"@pam_service_name@\" \ -DBANNER_FILENAME=\"@banner_filename@\" \ -DUSERFILE_BLOCK=\"@userfile_block@\" \ -DUSERFILE_PRIV=\"@userfile_priv@\" \ -DUSERFILE_ANY=\"@userfile_any@\" \ -DUSERFILE_NOBLANK=\"@userfile_noblank@\" if HAVE_LIBBSD macros += -DHAVE_LIBBSD endif if PAM_CHECK_ACCOUNT_TYPE macros += -DPAM_CHECK_ACCOUNT_TYPE endif if HAVE_DPMS_EXT macros += -DHAVE_DPMS_EXT endif if HAVE_FONTCONFIG macros += -DHAVE_FONTCONFIG endif if HAVE_XSCREENSAVER_EXT macros += -DHAVE_XSCREENSAVER_EXT endif if HAVE_XSYNC_EXT macros += -DHAVE_XSYNC_EXT endif if HAVE_XCOMPOSITE_EXT macros += -DHAVE_XCOMPOSITE_EXT endif if HAVE_XF86MISC_EXT macros += -DHAVE_XF86MISC_EXT endif if HAVE_XFIXES_EXT macros += -DHAVE_XFIXES_EXT endif if HAVE_XFT_EXT macros += -DHAVE_XFT_EXT endif if HAVE_XRANDR_EXT macros += -DHAVE_XRANDR_EXT endif if HAVE_XKB_EXT macros += -DHAVE_XKB_EXT endif if ANY_USER_AUTH macros += -DANY_USER_AUTH endif if NO_BLANK macros += -DNO_BLANK endif if BANNER macros += -DBANNER endif if WALLPAPER macros += -DWALLPAPER endif if SYSLOG macros += -DSYSLOG endif if SECURE macros += -DSECURE endif bin_PROGRAMS = \ xsecurelock xsecurelock_SOURCES = \ auth_child.c auth_child.h \ env_settings.c env_settings.h \ env_info.c env_info.h \ logging.c logging.h \ mlock_page.h \ main.c \ saver_child.c saver_child.h \ unmap_all.c unmap_all.h \ util.c util.h \ version.c version.h \ wait_pgrp.c wait_pgrp.h \ wm_properties.c wm_properties.h \ xscreensaver_api.c xscreensaver_api.h \ incompatible_compositor.xbm \ userfile.c userfile.h nodist_xsecurelock_SOURCES = \ env_helpstr.inc xsecurelock_CPPFLAGS = $(macros) $(LIBBSD_CFLAGS) xsecurelock_LDADD = $(LIBBSD_LIBS) helpersdir = $(pkglibexecdir) helpers_SCRIPTS = \ helpers/saver_blank if HAVE_HTPASSWD helpers_SCRIPTS += \ helpers/authproto_htpasswd endif if HAVE_MPLAYER helpers_SCRIPTS += \ helpers/saver_mplayer endif if HAVE_MPV helpers_SCRIPTS += \ helpers/saver_mpv endif if HAVE_PAMTESTER helpers_SCRIPTS += \ helpers/authproto_pamtester endif if HAVE_XSCREENSAVER helpers_SCRIPTS += \ helpers/saver_xscreensaver endif helpers_PROGRAMS = \ pgrp_placeholder pgrp_placeholder_SOURCES = \ helpers/pgrp_placeholder.c helpers_PROGRAMS += \ saver_multiplex saver_multiplex_SOURCES = \ env_settings.c env_settings.h \ helpers/monitors.c helpers/monitors.h \ helpers/saver_multiplex.c \ logging.c logging.h \ saver_child.c saver_child.h \ wait_pgrp.c wait_pgrp.h \ wm_properties.c wm_properties.h \ xscreensaver_api.c xscreensaver_api.h saver_multiplex_CPPFLAGS = $(macros) helpers_PROGRAMS += \ dimmer dimmer_SOURCES = \ env_settings.c env_settings.h \ helpers/dimmer.c \ logging.c logging.h \ wm_properties.c wm_properties.h dimmer_CPPFLAGS = $(macros) if HAVE_IDLE_TIMER helpers_PROGRAMS += \ until_nonidle until_nonidle_SOURCES = \ env_settings.c env_settings.h \ helpers/until_nonidle.c \ logging.c logging.h \ wait_pgrp.c wait_pgrp.h until_nonidle_CPPFLAGS = $(macros) endif helpers_PROGRAMS += \ auth_x11 auth_x11_SOURCES = \ env_info.c env_info.h \ env_settings.c env_settings.h \ helpers/authproto.c helpers/authproto.h \ helpers/auth_x11.c \ helpers/monitors.c helpers/monitors.h \ logging.c logging.h \ mlock_page.h \ util.c util.h \ wait_pgrp.c wait_pgrp.h \ wm_properties.c wm_properties.h \ xscreensaver_api.c xscreensaver_api.h auth_x11_CPPFLAGS = $(macros) $(FONTCONFIG_CFLAGS) $(XFT_CFLAGS) $(LIBBSD_CFLAGS) auth_x11_LDADD = $(FONTCONFIG_LIBS) $(XFT_LIBS) $(LIBBSD_LIBS) if BANNER auth_x11_SOURCES += \ banner.c banner.h endif if HAVE_PAM helpers_PROGRAMS += \ authproto_pam authproto_pam_SOURCES = \ env_info.c env_info.h \ env_settings.c env_settings.h \ helpers/authproto.c helpers/authproto.h \ helpers/authproto_pam.c \ logging.c logging.h \ mlock_page.h \ util.c util.h if ANY_USER_AUTH authproto_pam_SOURCES += \ userfile.c userfile.h endif authproto_pam_CPPFLAGS = $(macros) $(LIBBSD_CFLAGS) authproto_pam_LDADD = $(LIBBSD_LIBS) endif doc_DATA = \ CONTRIBUTING \ LICENSE \ README.md \ README-NSLS2.md if HAVE_PANDOC man1_MANS = xsecurelock.1 xsecurelock.1.md: doc/xsecurelock.1.md README.md { \ grep -B 9999 'ENV VARIABLES HERE' doc/xsecurelock.1.md; \ grep -A 9999 'ENV VARIABLES START' README.md |\ grep -B 9999 'ENV VARIABLES END'; \ grep -A 9999 'ENV VARIABLES HERE' doc/xsecurelock.1.md; \ } > xsecurelock.1.md xsecurelock.1: xsecurelock.1.md $(path_to_pandoc) -s -f markdown -t man -o $@ $< CLEANFILES += xsecurelock.1.md xsecurelock.1 endif # Some tools that we sure don't wan to install noinst_PROGRAMS = cat_authproto nvidia_break_compositor get_compositor remap_all cat_authproto_SOURCES = \ logging.c logging.h \ helpers/authproto.c helpers/authproto.h \ test/cat_authproto.c \ util.c util.h nvidia_break_compositor_SOURCES = \ test/nvidia_break_compositor.c nvidia_break_compositor_CPPFLAGS = $(macros) get_compositor_SOURCES = \ test/get_compositor.c get_compositor_CPPFLAGS = $(macros) remap_all_SOURCES= \ test/remap_all.c \ unmap_all.c unmap_all.h remap_all_CPPFLAGS = $(macros) FORCE: version.c: FORCE if [ -n "$(GIT_VERSION)" ]; then \ echo "const char *const git_version = \"$(GIT_VERSION)\";" \ > version.c; \ elif git describe --always --dirty >/dev/null 2>&1; then \ echo "const char *const git_version = \"` \ git describe --always --dirty \ `\";" > version.c; \ else \ : version.c must exist in non-git builds.; \ cat version.c; \ fi .PRECIOUS: version.c # Old one is better than none. env_helpstr.inc: README.md # Autogenerate for --help. grep -A 9999 'ENV VARIABLES START' "$<" |\ grep -B 9999 'ENV VARIABLES END' |\ grep '^[ *]' |\ sed -e 's,\\\|",\\&,g; s,$$,\\n",; s,^,",;' > "$@" xsecurelock-main.$(OBJEXT): env_helpstr.inc EXTRA_DIST = \ CONTRIBUTING \ LICENSE \ README.md \ README-NSLS2.md \ autogen.sh \ doc/xsecurelock.1.md \ ensure-documented-settings.sh \ helpers/saver_blank \ incompatible_compositor.xbm.sh \ run-iwyu.sh \ run-linters.sh \ test/*.c \ test/*.sh \ test/*.xdo \ version.c examplesdir = $(docdir)/examples dist_examples_DATA = \ doc/examples/saver_livestreams if HAVE_DOXYGEN doxyfile.stamp: $(DOXYGEN) Doxyfile echo Timestamp > doxyfile.stamp CLEANFILES += doxyfile.stamp all-local: doxyfile.stamp clean-local: $(RM) -r $(top_srcdir)/doxy endif scripts/run-xsecurelock: scripts/run-xsecurelock.in $(SED) \ -e 's|[@]libexecdir@|$(libexecdir)|g' \ -e 's|[@]bindir@|$(bindir)|g' \ -e 's|[@]sysconfdir@|$(sysconfdir)|g' \ < "$<" > "$@" scripts/saver-xsecurelock: scripts/saver-xsecurelock.in $(SED) \ -e 's|[@]datarootdir@|$(datarootdir)|g' \ < "$<" > "$@" autostart/xsecurelock.desktop: autostart/xsecurelock.desktop.in $(SED) \ -e 's|[@]libexecdir@|$(libexecdir)|g' \ -e 's|[@]bindir@|$(bindir)|g' \ -e 's|[@]sysconfdir@|$(sysconfdir)|g' \ < "$<" > "$@" if BANNER config/banner: config/banner.in $(PAR) j1w@banner_width@ < "$<" | \ $(AWK) -v w=@banner_width@ '{if (NR>1) {printf "%-*s\n", w, $$0} else {printf "%s\n", $$0}}' >\ "$@" endif autolockdir = $(pkglibexecdir) autolock_SCRIPTS = \ scripts/saver-xsecurelock runscriptdir = $(bindir) runscript_SCRIPTS = \ scripts/run-xsecurelock autostartdir = $(sysconfdir)/xdg/autostart autostart_DATA = \ autostart/xsecurelock.desktop CLEANFILES += scripts/run-xsecurelock \ scripts/saver-xsecurelock xsecurelocksysconfdir=$(sysconfdir)/xsecurelock xsecurelocksysconf_DATA = config/config if BANNER xsecurelocksysconf_DATA += config/banner CLEANFILES += config/banner endif if ANY_USER_AUTH xsecurelocksysconf_DATA += \ config/userfile-priv \ config/userfile-block \ config/userfile-any endif xsecurelocksysconf_DATA += \ config/userfile-noblank if HAVE_PAM xsecurelockpamdir=$(sysconfdir)/pam.d xsecurelockpam_DATA = config/xsecurelock-nsls2 endif iconsdir = $(datadir)/xsecurelock icons_DATA = icons/lock.png install-data-hook: chmod 4755 $(DESTDIR)$(helpersdir)/authproto_pam <file_sep>#ifndef USERFILE_H #define USERFILE_H enum userfile_rtn { USERFILE_SUCCESS = 0, USERFILE_ERROR = 1 }; enum userfile_tokens { USERFILE_NO_MATCH = 0x00, USERFILE_USER_MATCH = 0x01, USERFILE_GROUP_MATCH = 0x02, }; extern const char *userfile_match_string[]; int UserInAuthListPriv(const char* username, int *match); int UserInAuthListBlock(const char* username, int *match); int UserInAuthListAny(const char* username, int *match); int UserInNoBlankList(const char* username, int *match); #endif <file_sep>#ifndef BANNER_H #define BANNER_H #define BANNER_MAX_LINES 50 int ReadBannerFile(char **banner, int *num_lines, int max_lines); #endif <file_sep>#!/bin/sh /usr/bin/feh --scale-down --auto-zoom -x --geometry 100x100 \ @datarootdir@/xsecurelock/lock.png <file_sep># NSLS-II Specific Changes This outlines the changes made to this version for NSLS-II specific changes. All changes to the upstream code are contained within compiler pre-processing directives set through _autoconf_. This enables the upstream and changed versions to both be built through the same code base. It also allows for better auditing of changes. In addition to these changes, CI is provided on Azure Pipelines and upstream changes are automatically included. Debian packaging is provided in the attached `debian` directory. ## Any User Authentication The screen locker can be configured to prompt for login information to allow for any user to authenticate and unlock the screen. This is handled by passing the option `--with-any-user-auth` to the configure script. The unlocking of the screen is controlled by 3 userfiles. * A list of users and groups who are blocked from unlocking the screen locker(blocked). * A list of users and groups who can always unlock the screen locker (priv). * A list of users and groups from which, if they are the user who locked the screen then any other authenticated user should be able to unlock the screen. The file format is of the form: ```config # Userlist for xsecurelock # # format is <username/@groupname> # # any user listed here swilkins @blgroups ``` The filenames of these files are governed by the `--with-userfile-blocked=<filename>`, `--with-userfile-priv=<filename>` and `--with-userfile-any=<filename>` for the _blocked_, _privileged_ and _any_ users respectively. If further restrictions on authentication are required, this should be done via PAM by modifying the PAM service file For example, the PAM stack could contain the _pam_listfile_ module to restrict unlocking to a subset of users. ## Banner Text Using the configure options `--enable-banner` and `--with-banner-filename` a logon banner can be included at the unlock prompt. The color of that banner can be set using the environmental variable `XSECURELOCK_AUTH_BANNER_COLOR` to make it more (or less) prominent. Alternatively the environmental variable `XSECURELOCK_BANNER_FILENAME` can be used to override this. ## Wallpaper Passing the option `--enable-wallpaper` enables the background pixmap `wallpaper.xbm` to provide a more "textured" background to the unlock page. ## No Blank Passing the option `--enable-no-blank` causes the locker to be "transparent". This is acomplished by never raising the blanker and screensaver windows although they are still mapped. The screensaver process is still run, so a lock icon (for example) can be shown when the screensaver is run. ## Syslog Passing the option `--enable-syslog` will enable the syslog logging in the `authproto_pam.c` module. This adds some syslog messages (in the auth context) for logging the authentication. ## Secure Passing the option `--enable-secure` causes the screen locker to ignore the environmental variables which can override the user files and the configuration for which PAM config to use. <file_sep>#!/usr/bin/make -f # -*- makefile -*- # include /usr/share/dpkg/pkg-info.mk export DH_VERBOSE=1 export DEB_BUILD_MAINT_OPTIONS = hardening=+all %: dh $@ --with autoreconf override_dh_auto_configure: dh_auto_configure -- \ --with-pam \ --with-pam-service-name=xsecurelock \ --with-banner-filename=/etc/xsecurelock/banner \ --with-userfile-priv=/etc/xsecurelock/userfile-priv \ --with-userfile-block=/etc/xsecurelock/userfile-block \ --with-userfile-any=/etc/xsecurelock/userfile-any \ --with-userfile-noblank=/etc/xsecurelock/userfile-noblank \ --enable-any-user-auth \ --enable-banner \ --enable-wallpaper \ --enable-no-blank \ --enable-secure \ --enable-syslog \ --with-fontconfig \ --without-htpasswd \ --with-mplayer=/usr/bin/mplayer \ --with-mpv=/usr/bin/mpv \ --with-pamtester=no \ --with-xcomposite \ --with-xf86misc=no \ --with-xrandr \ --with-xss \ --with-xsync \ --with-xfixes \ --with-xft \ --with-xkb override_dh_auto_build: GIT_VERSION="$(DEB_VERSION_UPSTREAM)" dh_auto_build override_dh_autoreconf: dh_autoreconf ./autogen.sh override_dh_auto_install: dh_auto_install find ./debian -type f -name "LICENSE" -delete override_dh_auto_clean: dh_auto_clean -rm version.c
fa774c0bfb818809fc35473b827f8af869e0b20a
[ "Markdown", "C", "Makefile", "Shell" ]
10
C
stuwilkins/xsecurelock
feb253a7c9281b6195e4e83173171eb32adddeba
f64bd183e362d750f19981b16273c18c46f78caf
refs/heads/master
<file_sep>#include<stdio.h> #define f(x) (1/(1+x*x)) #include<math.h> int main() { float a,b,h,x[10],y[10],iv; int n,i; printf("Enter upper limit(b) and lower limit(a):"); scanf("%f%f",&b,&a); printf("Enter the no of segment say(n):"); scanf("%d",&n); h=(b-a)/n; x[0]=a; x[n]=b; for(i=1;i<n;i++) { x[i]=x[i-1]+h; y[i]=f(x[i]); } iv=f(a)+f(b); for(i=1;i<n;i++) { if(i%2==0) { iv=iv+2*y[i]; } else { iv=iv+4*y[i]; } } iv=iv*(h/3); printf("%f is a solution of integral value",iv); return 0; }
c910d424d611877dea8ef38061a6e21cc5c6fa85
[ "C" ]
1
C
anishboss/nmprograms
a118817638690d0a642627016d4281e2f53d4388
01498e01910e88ff4f3572180393038312676ab3
refs/heads/master
<repo_name>evandde/isox<file_sep>/include/Run.hh #ifndef RUN_HH #define RUN_HH #include "G4Run.hh" class Run : public G4Run { public: Run(); ~Run() override; virtual void RecordEvent(const G4Event *) override; virtual void Merge(const G4Run *) override; G4double GetEDep() const { return fEDep; } private: G4int fEDepHCID; G4double fEDep; }; #endif // RUN_HH <file_sep>/README.md # geant4template Template code for Geant4 MC simulation <file_sep>/src/RunAction.cc #include "RunAction.hh" #include "Run.hh" #include "G4RunManager.hh" #include "G4SystemOfUnits.hh" RunAction::RunAction() : G4UserRunAction() { } RunAction::~RunAction() { } G4Run *RunAction::GenerateRun() { return new Run; } void RunAction::BeginOfRunAction(const G4Run *aRun) { G4RunManager::GetRunManager()->SetPrintProgress(static_cast<G4int>(aRun->GetNumberOfEventToBeProcessed() * .1)); } void RunAction::EndOfRunAction(const G4Run *aRun) { auto nOfEvents = aRun->GetNumberOfEvent(); if (nOfEvents == 0) return; auto theRun = static_cast<const Run *>(aRun); auto eDep = theRun->GetEDep(); G4cout << "--- Run results ---\n" << "Total events in this run: " << nOfEvents << "\n" << "Deposited energy per primary [MeV]: " << (eDep / nOfEvents) / MeV << "\n\n"; } <file_sep>/CMakeLists.txt #---------------------------------------------------------------------------- # Setup the project cmake_minimum_required(VERSION 3.8 FATAL_ERROR) project(isox) #---------------------------------------------------------------------------- # Find Geant4 package, activating all available UI and Vis drivers by default # find_package(Geant4 REQUIRED ui_all vis_all) #---------------------------------------------------------------------------- # Setup Geant4 include directories and compile definitions # Setup include directory for this project # include(${Geant4_USE_FILE}) include_directories(${PROJECT_SOURCE_DIR}/include) #---------------------------------------------------------------------------- # Locate sources and headers for this project # NB: headers are included so they will show up in IDEs # file(GLOB sources ${PROJECT_SOURCE_DIR}/src/*.cc) file(GLOB headers ${PROJECT_SOURCE_DIR}/include/*.hh) #---------------------------------------------------------------------------- # Add the executable, and link it to the Geant4 libraries # add_executable(isox isox.cc ${sources} ${headers}) target_link_libraries(isox ${Geant4_LIBRARIES}) #---------------------------------------------------------------------------- # Copy all scripts to the build directory. This is so that we can run the # executable directly because it relies on these scripts being in the current # working directory. # set(SCRIPTS run.mac vis.mac ) foreach(_script ${SCRIPTS}) configure_file( ${PROJECT_SOURCE_DIR}/${_script} ${PROJECT_BINARY_DIR}/${_script} COPYONLY ) endforeach() <file_sep>/isox.cc // // ******************************************************************** // * License and Disclaimer * // * * // * The Geant4 software is copyright of the Copyright Holders of * // * the Geant4 Collaboration. It is provided under the terms and * // * conditions of the Geant4 Software License, included in the file * // * LICENSE and available at http://cern.ch/geant4/license . These * // * include a list of copyright holders. * // * * // * Neither the authors of this software system, nor their employing * // * institutes,nor the agencies providing financial support for this * // * work make any representation or warranty, express or implied, * // * regarding this software system or assume any liability for its * // * use. Please see the license in the file LICENSE and URL above * // * for the full disclaimer and the limitation of liability. * // * * // * This code implementation is the result of the scientific and * // * technical work of the GEANT4 collaboration. * // * By using, copying, modifying or distributing the software (or * // * any work based on the software) you agree to acknowledge its * // * use in resulting scientific publications, and indicate your * // * acceptance of all terms of the Geant4 Software license. * // ******************************************************************** // // /// \author <NAME> /// \email <EMAIL> /// \homepage evandde.github.io /// \brief Template code for Geant4 (Geant4 10.6.p02) #include "DetectorConstruction.hh" #include "G4PhysListFactory.hh" #include "QBBC.hh" #include "ActionInitialization.hh" #ifdef G4MULTITHREADED #include "G4MTRunManager.hh" #else #include "G4RunManager.hh" #endif #include "G4UImanager.hh" #include "G4VisExecutive.hh" #include "G4UIExecutive.hh" namespace { void PrintUsage() { G4cerr << " Usage: " << G4endl << " ProjectName [-option1 value1] [-option2 value2] ..." << G4endl; G4cerr << "\t--- Option lists ---" << "\n\t[-m] <Set macrofile> default: " "vis.mac" ", inputtype: string" #ifdef G4MULTITHREADED << "\n\t[-t] <Set nThreads> default: 1, inputtype: int, Max: " << G4Threading::G4GetNumberOfCores() #endif << "\n\t[-p] <Set physics> default: 'QBBC', inputtype: string" << G4endl; } } // namespace int main(int argc, char **argv) { // Default setting for main() arguments G4String macroFilePath; #ifdef G4MULTITHREADED G4int nThreads = 1; #endif G4String physName; // Parsing main() Arguments for (G4int i = 1; i < argc; i = i + 2) { if (G4String(argv[i]) == "-m") macroFilePath = argv[i + 1]; #ifdef G4MULTITHREADED else if (G4String(argv[i]) == "-t") nThreads = G4UIcommand::ConvertToInt(argv[i + 1]); #endif else if (G4String(argv[i]) == "-p") physName = argv[i + 1]; else { PrintUsage(); return 1; } } if (argc > 7) { PrintUsage(); return 1; } // Set random engine and seed number G4Random::setTheEngine(new CLHEP::RanecuEngine); G4Random::setTheSeed(time(nullptr)); // Construct the default run manager #ifdef G4MULTITHREADED auto runManager = new G4MTRunManager; runManager->SetNumberOfThreads(nThreads); #else auto runManager = new G4RunManager; #endif // Set mandatory initialization classes runManager->SetUserInitialization(new DetectorConstruction); G4VModularPhysicsList* phys; if(physName.empty()) phys = new QBBC; else { G4PhysListFactory factory; phys = factory.GetReferencePhysList(physName); } runManager->SetUserInitialization(phys); runManager->SetUserInitialization(new ActionInitialization); // Initialize run runManager->Initialize(); // Initialize visualization auto visManager = new G4VisExecutive; visManager->Initialize(); // Get the pointer to the User Interface manager auto UImanager = G4UImanager::GetUIpointer(); // Process macro or start UI session if (macroFilePath.empty()) { // interactive mode (if no macrofile) auto ui = new G4UIExecutive(argc, argv); UImanager->ApplyCommand("/control/execute vis.mac"); ui->SessionStart(); delete ui; } else { // batch mode G4String command = "/control/execute "; UImanager->ApplyCommand(command + macroFilePath); } // Job termination // Free the store: user actions, physics_list and detector_description are // owned and deleted by the run manager, so they should not be deleted // in the main() program ! delete visManager; delete runManager; } <file_sep>/include/PrimaryGeneratorAction.hh #ifndef PRIMARYGENERATORACTION_HH #define PRIMARYGENERATORACTION_HH #include "G4VUserPrimaryGeneratorAction.hh" class G4GeneralParticleSource; class PrimaryGeneratorAction : public G4VUserPrimaryGeneratorAction { public: PrimaryGeneratorAction(); virtual ~PrimaryGeneratorAction() override; virtual void GeneratePrimaries(G4Event *) override; private: G4GeneralParticleSource *fPrimary; }; #endif <file_sep>/include/ActionInitialization.hh #ifndef ACTIONINITIALIZATION_HH #define ACTIONINITIALIZATION_HH #include "G4VUserActionInitialization.hh" class ActionInitialization : public G4VUserActionInitialization { public: ActionInitialization(); virtual ~ActionInitialization() override; virtual void BuildForMaster() const override; virtual void Build() const override; }; #endif <file_sep>/src/Run.cc #include "Run.hh" #include "G4SDManager.hh" #include "G4Event.hh" #include "G4THitsMap.hh" Run::Run() : G4Run(), fEDepHCID(-1), fEDep(0.) { } Run::~Run() { } void Run::RecordEvent(const G4Event *anEvent) { if (fEDepHCID == -1) fEDepHCID = G4SDManager::GetSDMpointer()->GetCollectionID("Detector/EDep"); auto HCE = anEvent->GetHCofThisEvent(); if (!HCE) return; auto hitsMap = static_cast<G4THitsMap<G4double> *>(HCE->GetHC(fEDepHCID)); for (const auto &iter : *(hitsMap->GetMap())) { auto eDep = *(iter.second); if (eDep > 0.) fEDep += eDep; } G4Run::RecordEvent(anEvent); } void Run::Merge(const G4Run *aRun) { auto localRun = static_cast<const Run *>(aRun); fEDep += localRun->fEDep; G4Run::Merge(aRun); } <file_sep>/src/DetectorConstruction.cc #include "DetectorConstruction.hh" #include "G4SystemOfUnits.hh" #include "G4NistManager.hh" #include "G4Box.hh" #include "G4Tubs.hh" #include "G4LogicalVolume.hh" #include "G4PVPlacement.hh" #include "G4VisAttributes.hh" #include "G4SDManager.hh" #include "G4MultiFunctionalDetector.hh" #include "G4PSEnergyDeposit.hh" DetectorConstruction::DetectorConstruction() : G4VUserDetectorConstruction() { } DetectorConstruction::~DetectorConstruction() { } G4VPhysicalVolume *DetectorConstruction::Construct() { // materials G4NistManager *nist = G4NistManager::Instance(); auto matAir = nist->FindOrBuildMaterial("G4_AIR"); auto matAl = nist->FindOrBuildMaterial("G4_Al"); auto matGe = nist->FindOrBuildMaterial("G4_Ge"); auto matNaI = nist->FindOrBuildMaterial("G4_SODIUM_IODIDE"); // vis auto visWhiteWire = new G4VisAttributes(G4Color::White()); visWhiteWire->SetForceWireframe(); auto visBlueSol = new G4VisAttributes(G4Color::Blue()); visBlueSol->SetForceSolid(); auto visCyanSol = new G4VisAttributes(G4Color::Cyan()); visCyanSol->SetForceSolid(); auto colorPurpleAlpha5 = G4Color(.3, 0., 1., .5); auto visPurpleAlpha5Sol = new G4VisAttributes(colorPurpleAlpha5); visPurpleAlpha5Sol->SetForceSolid(); auto colorYellowAlpha5 = G4Color::Yellow(); colorYellowAlpha5.SetAlpha(0.5); auto visYellowAlpha5Sol = new G4VisAttributes(colorYellowAlpha5); visYellowAlpha5Sol->SetForceSolid(); auto colorCyanAlpha5 = G4Color::Cyan(); colorCyanAlpha5.SetAlpha(0.5); auto visCyanAlpha5Sol = new G4VisAttributes(colorCyanAlpha5); visCyanAlpha5Sol->SetForceSolid(); auto colorMagentaAlpha5 = G4Color::Magenta(); colorMagentaAlpha5.SetAlpha(0.5); auto visMagnetaAlpha5Sol = new G4VisAttributes(colorMagentaAlpha5); visMagnetaAlpha5Sol->SetForceSolid(); // World auto worldSize = 1. * m; auto solWorld = new G4Box("World", .5 * worldSize, .5 * worldSize, .5 * worldSize); auto lvWorld = new G4LogicalVolume(solWorld, matAir, "World"); lvWorld->SetVisAttributes(visWhiteWire); auto pvWorld = new G4PVPlacement(0, G4ThreeVector(), lvWorld, "World", nullptr, false, 0); // HPGe main detector auto mainDetHeight = 12. * cm; auto mainDetDiam = 7.8 * cm; auto solMainDet = new G4Tubs("MainDet", 0., .5 * mainDetDiam, .5 * mainDetHeight, 0., 360. * deg); auto lvMainDet = new G4LogicalVolume(solMainDet, matGe, "MainDet"); lvMainDet->SetVisAttributes(visBlueSol); auto pvMainDet = new G4PVPlacement(0, G4ThreeVector(0., 0., 0.), lvMainDet, "MainDet", lvWorld, false, 0); // HPGe main detector cooler line auto mainDetCoolerLineHeight = 5. * cm; auto mainDetCoolerLineDiam = 1.5 * cm; auto solMainDetCoolerLine = new G4Tubs("MainDetCoolerLine", 0., .5 * mainDetCoolerLineDiam, .5 * mainDetCoolerLineHeight, 0., 360. * deg); auto lvMainDetCoolerLine = new G4LogicalVolume(solMainDetCoolerLine, matAl, "MainDetCoolerLine"); lvMainDetCoolerLine->SetVisAttributes(visCyanSol); new G4PVPlacement(0, pvMainDet->GetObjectTranslation() + G4ThreeVector(0., 0., -solMainDet->GetZHalfLength() - solMainDetCoolerLine->GetZHalfLength()), lvMainDetCoolerLine, "MainDetCoolerLine", lvWorld, false, 999); // NaI(Tl) sub detector auto subDetX1 = 14. * cm; auto subDetX2 = 7.8 * cm; auto subDetY1 = 10. * cm; auto subDetY2 = 7.8 * cm; auto subDetY3 = 10. * cm; auto subDetZ0 = 23.5 * cm; auto subDetZ1 = 10. * cm; auto solSubDet1 = new G4Box("SubDet1", .5 * subDetX2, .5 * subDetY2, .5 * subDetZ1); auto lvSubDet1 = new G4LogicalVolume(solSubDet1, matNaI, "SubDet1"); lvSubDet1->SetVisAttributes(visYellowAlpha5Sol); auto pvSubDet1 = new G4PVPlacement(0, pvMainDet->GetObjectTranslation() + G4ThreeVector(0., 0., solMainDet->GetZHalfLength() + solSubDet1->GetZHalfLength()), lvSubDet1, "SubDet1", lvWorld, false, 1); auto solSubDet2 = new G4Box("SubDet2", .5 * subDetX2, .5 * subDetY1, .5 * subDetZ0); auto lvSubDet2 = new G4LogicalVolume(solSubDet2, matNaI, "SubDet2"); lvSubDet2->SetVisAttributes(visMagnetaAlpha5Sol); new G4PVPlacement(0, pvSubDet1->GetObjectTranslation() + G4ThreeVector(0., -solSubDet1->GetYHalfLength() - solSubDet2->GetYHalfLength(), solSubDet1->GetZHalfLength() - solSubDet2->GetZHalfLength()), lvSubDet2, "SubDet2", lvWorld, false, 2); auto solSubDet3 = new G4Box("SubDet3", .5 * subDetX2, .5 * subDetY3, .5 * subDetZ0); auto lvSubDet3 = new G4LogicalVolume(solSubDet3, matNaI, "SubDet3"); lvSubDet3->SetVisAttributes(visCyanAlpha5Sol); new G4PVPlacement(0, pvSubDet1->GetObjectTranslation() + G4ThreeVector(0., solSubDet1->GetYHalfLength() + solSubDet3->GetYHalfLength(), solSubDet1->GetZHalfLength() - solSubDet3->GetZHalfLength()), lvSubDet3, "SubDet3", lvWorld, false, 3); auto solSubDet4 = new G4Box("SubDet4", .5 * subDetX1, .5 * (subDetY1 + subDetY2 + subDetY3), .5 * subDetZ0); auto lvSubDet4 = new G4LogicalVolume(solSubDet4, matNaI, "SubDet4"); lvSubDet4->SetVisAttributes(visPurpleAlpha5Sol); new G4PVPlacement(0, pvSubDet1->GetObjectTranslation() + G4ThreeVector(-solSubDet1->GetXHalfLength() - solSubDet4->GetXHalfLength(), 0., solSubDet1->GetZHalfLength() - solSubDet4->GetZHalfLength()), lvSubDet4, "SubDet4", lvWorld, false, 4); return pvWorld; } void DetectorConstruction::ConstructSDandField() { auto mfdDetector = new G4MultiFunctionalDetector("Detector"); G4SDManager::GetSDMpointer()->AddNewDetector(mfdDetector); auto psEDep = new G4PSEnergyDeposit("EDep"); mfdDetector->RegisterPrimitive(psEDep); SetSensitiveDetector("MainDet", mfdDetector); } <file_sep>/src/PrimaryGeneratorAction.cc #include "PrimaryGeneratorAction.hh" #include "G4GeneralParticleSource.hh" PrimaryGeneratorAction::PrimaryGeneratorAction() : G4VUserPrimaryGeneratorAction() { fPrimary = new G4GeneralParticleSource(); } PrimaryGeneratorAction::~PrimaryGeneratorAction() { delete fPrimary; } void PrimaryGeneratorAction::GeneratePrimaries(G4Event *anEvent) { fPrimary->GeneratePrimaryVertex(anEvent); } <file_sep>/include/DetectorConstruction.hh #ifndef DETECTORCONSTRUCTION_HH #define DETECTORCONSTRUCTION_HH #include "G4VUserDetectorConstruction.hh" class G4VPhysicalVolume; class G4LogicalVolume; class DetectorConstruction : public G4VUserDetectorConstruction { public: DetectorConstruction(); virtual ~DetectorConstruction() override; virtual G4VPhysicalVolume *Construct() override; virtual void ConstructSDandField() override; }; #endif
b64042dd8b317c73d4754303f63b9333d4963990
[ "Markdown", "CMake", "C++" ]
11
C++
evandde/isox
e8d8dc7703d9ff60de5efe9054c72e23b51e5e97
245cc2669663e57c60133bcf94355903d78ebfe3
refs/heads/main
<file_sep>using System; using System.Collections.Generic; using System.Threading.Tasks; using AetherSense.Triggers; using Buttplug; using Dalamud.Logging; using Dalamud.Plugin; namespace AetherSense { public class Devices { private List<Device> devices = new List<Device>(); public readonly List<Group> Groups = new List<Group>(); public int Count => this.devices.Count; public IReadOnlyCollection<Device> All => this.devices.AsReadOnly(); public Devices() { for (int groupId = 0; groupId < 10; groupId++) { this.Groups.Add(new Group(this, groupId)); } } public void Clear() { this.devices.Clear(); } public void AddDevice(ButtplugClientDevice clientDevice) { Device device = new Device(clientDevice); this.devices.Add(device); } public void RemoveDevice(ButtplugClientDevice clientDevice) { foreach (Device device in this.devices) { if (device.ClientDevice == clientDevice) { this.devices.Remove(device); return; } } } public async Task Write(List<TriggerBase> triggers, int delta) { foreach(Group group in this.Groups) { await group.Write(triggers, delta); } } public class Group { public readonly int GroupId; private readonly Devices devices; public double DesiredIntensity { get; private set; } = 0; public double CurrentIntensity { get; set; } public double Maximum { get; set; } public Group(Devices devices, int id) { this.devices = devices; this.GroupId = id; } public async Task Write(List<TriggerBase> triggers, int delta) { this.DesiredIntensity = 0; foreach (TriggerBase trigger in triggers) { if (!trigger.Enabled || trigger.Pattern == null) continue; if (!trigger.Pattern.Active) continue; if (trigger.DeviceGroup != 0 && trigger.DeviceGroup != this.GroupId) continue; this.DesiredIntensity += trigger.Pattern.DevicesIntensity; } // Get the maximum intensity this.Maximum = Math.Max(this.DesiredIntensity, this.Maximum); // drag the max value down towards 1.0 at a rate of 0.001 per ms this.Maximum -= delta * 0.001; this.Maximum = Math.Max(1.0, this.Maximum); this.CurrentIntensity = this.DesiredIntensity / this.Maximum; if (!Plugin.Configuration.Enabled) this.CurrentIntensity = 0; foreach (Device device in this.devices.devices) { try { if (device.Group != this.GroupId) continue; device.Intensity = this.CurrentIntensity; await device.Write(); } catch (Exception ex) { PluginLog.Error(ex, "Failed to write to device"); } } } } } } <file_sep>using System; using System.Collections.Generic; using System.Threading.Tasks; using Dalamud.Logging; using Dalamud.Plugin; using ImGuiNET; using Newtonsoft.Json; namespace AetherSense.Patterns { public abstract class PatternBase { [JsonIgnore] public bool Active { get; private set; } [JsonIgnore] public int DurationLeft { get; private set; } [JsonIgnore] public double DevicesIntensity { get; protected set; } = 0; private Task lastRunTask; public void OnEditorGuiTop() { ImGui.SameLine(); ImGui.PushButtonRepeat(true); if (ImGui.ArrowButton("##TestButton", ImGuiDir.Right)) { this.RunFor(1000); } ImGui.PushButtonRepeat(false); this.OnEditorGui(); } protected abstract void OnEditorGui(); public void RunFor(int duration) { if (this.Active) { this.DurationLeft = Math.Max(this.DurationLeft, duration); return; } Task.Run(async () => { await this.RunForAsync(duration); }); } public async Task RunForAsync(int duration) { if (this.Active) { this.DurationLeft = Math.Max(this.DurationLeft, duration); return; } this.DurationLeft = duration; this.Begin(); while (this.DurationLeft > 0) { await Task.Delay(100); this.DurationLeft -= 100; } this.End(); } public virtual void Begin() { this.Active = true; // the last task may not have completed, but it should shortly ////if (this.lastRunTask != null && !this.lastRunTask.IsCompleted && !this.lastRunTask.IsFaulted) //// throw new Exception("Last pattern task did not complete"); this.lastRunTask = Task.Run(this.Run); } public virtual void End() { this.Active = false; if (this.lastRunTask.IsFaulted) { PluginLog.Error(this.lastRunTask.Exception, "Error in pattern task"); } } protected virtual Task Run() { return Task.CompletedTask; } } } <file_sep>using Buttplug; using Dalamud.Configuration; using Dalamud.Plugin; using ImGuiNET; using System; using System.Threading.Tasks; using AetherSense.Triggers; using System.IO; using AetherSense.Patterns; using Dalamud.IoC; using Dalamud.Game.Command; using Dalamud.Logging; using Dalamud.Game.Gui; namespace AetherSense { public sealed class Plugin : IDalamudPlugin { [PluginService] public static ChatGui ChatGui { get; private set; } = null!; [PluginService] public static CommandManager CommandManager { get; private set; } = null!; public static DalamudPluginInterface DalamudPluginInterface; public static Configuration Configuration; public static Devices Devices = new Devices(); public static ButtplugClient Buttplug; public static ButtplugConnectorException lastConnectionError; public string Name => "AetherSense"; private bool enabled; private bool debugVisible; private bool configurationIsVisible; private bool configurationWasVisible = false; public Plugin(DalamudPluginInterface pluginInterface) { DalamudPluginInterface = pluginInterface; pluginInterface.Inject(this); ////Configuration = DalamudPluginInterface.GetPluginConfig() as Configuration ?? new Configuration(); CommandManager.AddHandler("/sense", "Opens the Aether Sense configuration window", this.OnShowConfiguration); CommandManager.AddHandler("/senseDebug", "Opens the Aether Sense debug window", this.OnShowDebug); DalamudPluginInterface.UiBuilder.Draw += OnGui; DalamudPluginInterface.UiBuilder.OpenConfigUi += () => this.configurationIsVisible = true; Devices.Clear(); Configuration = Configuration.Load(); Task.Run(this.Connect); _ = Task.Run(this.Run); this.LoadTriggers(); } /// <summary> /// Initializes the plugin in mock test mode outside of the game /// </summary> /// <param name="configuration">the plugin configuration to use</param> /// <returns>an action to be invoked for ImGUI drawing</returns> public Action InitializeMock() { Configuration = Configuration.Load(); Task.Run(this.Connect); _ = Task.Run(this.Run); this.LoadTriggers(); Task.Run(async () => { await Task.Delay(500); this.OnShowDebug(null); this.OnShowConfiguration(null); }); return this.OnGui; } public async Task Connect() { if (!Configuration.Enabled) return; PluginLog.Information("Connecting to buttplug"); try { if (Buttplug == null) { Buttplug = new ButtplugClient("Aether Sense"); Buttplug.DeviceAdded += this.OnDeviceAdded; Buttplug.DeviceRemoved += this.OnDeviceRemoved; Buttplug.ScanningFinished += (o, e) => { Task.Run(async () => { await Task.Delay(1000); try { await Buttplug.StartScanningAsync(); } catch (Exception) { } }); }; } if (!Buttplug.Connected) { lastConnectionError = null; try { /*PluginLog.Information("Connect to embedded buttplug server"); ButtplugEmbeddedConnectorOptions connectorOptions = new ButtplugEmbeddedConnectorOptions(); connectorOptions.ServerName = "Aether Sense Server";*/ PluginLog.Information("Connect to buttplug local server"); ButtplugWebsocketConnectorOptions wsOptions = new ButtplugWebsocketConnectorOptions(new Uri(Configuration.ServerAddress)); await Buttplug.ConnectAsync(wsOptions); } catch (ButtplugConnectorException ex) { lastConnectionError = ex; this.OnShowConfiguration(null); throw; } } PluginLog.Information("Scan for devices"); await Buttplug.StartScanningAsync(); } catch (Exception ex) { PluginLog.Error(ex, "Buttplug exception"); } } private async Task Run() { this.enabled = true; PluginLog.Information("Running"); while (this.enabled) { await Devices.Write(Configuration.Triggers, 250); await Task.Delay(250); } } private void LoadTriggers() { PluginLog.Information("Loading Triggers"); foreach (TriggerBase trigger in Configuration.Triggers) { if (!trigger.Enabled || Plugin.DalamudPluginInterface == null) continue; PluginLog.Information(" > " + trigger.Name); trigger.Attach(); } } private void UnloadTriggers() { // Unload triggers as we are stopping. PluginLog.Information("Unloading Triggers"); foreach (TriggerBase trigger in Configuration.Triggers) { if (Plugin.DalamudPluginInterface == null) continue; trigger.Detach(); } } public void Dispose() { DalamudPluginInterface.UiBuilder.Draw -= OnGui; CommandManager.ClearHandlers(); DalamudPluginInterface.Dispose(); this.UnloadTriggers(); this.enabled = false; } public void OnGui() { if (this.debugVisible && ImGui.Begin("Aether Sense Status", ref this.debugVisible)) { DebugWindow.OnGui(); ImGui.End(); } if (this.configurationIsVisible && ImGui.Begin("Aether Sense", ref this.configurationIsVisible)) { this.configurationWasVisible = true; ConfigurationEditor.OnGui(); ImGui.End(); } // Have we just closed the config window if (!this.configurationIsVisible && this.configurationWasVisible) { this.configurationWasVisible = false; Configuration.Save(); Task.Run(this.Connect); _ = Task.Run(this.Run); this.LoadTriggers(); return; } } private void OnDeviceAdded(object sender, DeviceAddedEventArgs e) { PluginLog.Information("Device {0} added", e.Device.Name); Devices.AddDevice(e.Device); } private void OnDeviceRemoved(object sender, DeviceRemovedEventArgs e) { PluginLog.Information("Device {0} removed", e.Device.Name); Devices.RemoveDevice(e.Device); } private void OnShowConfiguration(string args) { this.UnloadTriggers(); this.configurationIsVisible = true; } private void OnShowDebug(string args) { this.debugVisible = true; } } } <file_sep>using System.Threading.Tasks; using Dalamud.Plugin; using ImGuiNET; namespace AetherSense.Patterns { public class ConstantPattern : PatternBase { private float intensity = 1.0f; public float Intensity { get => this.intensity; set => this.intensity = value; } public override void Begin() { base.Begin(); this.DevicesIntensity = this.Intensity; } protected override void OnEditorGui() { ImGui.SliderFloat("Intensity", ref this.intensity, 0.0f, 1.0f); } } } <file_sep>using AetherSense.Patterns; using ImGuiNET; using AetherSense.Triggers; using System; using System.Collections.Generic; using AetherSense.Utils; namespace AetherSense { public static class ConfigurationEditor { public static List<Type> TriggerTypes = new List<Type>() { typeof(ChatTrigger), }; public static List<Type> PatternTypes = new List<Type>() { typeof(ConstantPattern), typeof(AlternatingPattern), typeof(WavePattern) }; public static void OnGui() { if (Plugin.lastConnectionError != null) { ImGui.Text("Failed to connect to Buttplug server:\nIs the server running and available?"); } else { ImGui.Text("Triggers are disabled while this window is visible."); } bool enabled = Plugin.Configuration.Enabled; ImGui.Checkbox("Enabled", ref enabled); Plugin.Configuration.Enabled = enabled; string address = Plugin.Configuration.ServerAddress; ImGui.InputText("Server", ref address, 99); Plugin.Configuration.ServerAddress = address; if (ImGui.BeginTabBar("##ConfigTabBar", ImGuiTabBarFlags.None)) { if (ImGui.BeginTabItem("Triggers")) { ImGui.Columns(2, "##TriggerBar", false); ImGui.SetColumnWidth(0, 150); if (ImGui.Button("Reset Triggers")) { Configuration defaultConfig = Configuration.GetDefaultConfiguration(); Plugin.Configuration.Triggers = defaultConfig.Triggers; } ImGui.NextColumn(); if (ImGui.BeginCombo("Add New Trigger", null, ImGuiComboFlags.NoPreview)) { foreach (Type type in TriggerTypes) { if (ImGui.Selectable(NameUtility.ToName(type.Name))) { TriggerBase trigger = (TriggerBase)Activator.CreateInstance(type); Plugin.Configuration.Triggers.Add(trigger); trigger.Name = "New " + NameUtility.ToName(type.Name); } } ImGui.EndCombo(); } ImGui.Columns(1); ImGui.Separator(); int indexToDelete = -1; for (int i = 0; i < Plugin.Configuration.Triggers.Count; i++) { bool keep = Plugin.Configuration.Triggers[i].OnEditorGuiTop(i); if (!keep) { indexToDelete = i; } } if (indexToDelete != -1) Plugin.Configuration.Triggers.RemoveAt(indexToDelete); ImGui.EndTabItem(); } if (ImGui.BeginTabItem("Devices")) { ImGui.Columns(2); ImGui.Text("Name"); ImGui.NextColumn(); ImGui.Text("Group"); ImGui.NextColumn(); foreach (Device device in Plugin.Devices.All) { string name = device.ClientDevice.Name; if (!Plugin.Configuration.DeviceGroups.ContainsKey(name)) Plugin.Configuration.DeviceGroups.Add(name, 1); ImGui.Text(name); ImGui.NextColumn(); int group = Plugin.Configuration.DeviceGroups[name]; string label = group == 0 ? "Disabled" : "Group " + group; if (ImGui.BeginCombo($"##{name}combo", label)) { for (int n = 0; n < 10; n++) { label = n == 0 ? "Disabled" : "Group " + n; if (ImGui.Selectable(label, n == group)) { group = n; } } ImGui.EndCombo(); } Plugin.Configuration.DeviceGroups[name] = group; } } ImGui.EndTabBar(); } } } } <file_sep>using System.Threading.Tasks; using AetherSense.Patterns; using AetherSense.Triggers; using ImGuiNET; namespace AetherSense { public static class DebugWindow { public static void OnGui() { if (ImGui.Button("Clear Devices")) { Plugin.Devices.Clear(); } if (Plugin.Configuration.Enabled) { foreach (Devices.Group group in Plugin.Devices.Groups) { ImGui.Text("Group: " + group.GroupId); ImGui.SameLine(); ImGui.Text(group.DesiredIntensity.ToString("F2")); ImGui.SameLine(); ImGui.Text("/"); ImGui.SameLine(); ImGui.Text(group.Maximum.ToString("F2")); ImGui.SameLine(); ImGui.ProgressBar((float)group.CurrentIntensity); } } else { ImGui.Text("AetherSense is disabled"); } ImGui.Text($"Triggers: {Plugin.Configuration.Triggers.Count}"); int attachedCount = 0; foreach (TriggerBase trigger in Plugin.Configuration.Triggers) { string ac = trigger.IsAttached ? "X" : " "; ImGui.Text($" [{ac}] {trigger.Name} {trigger.CooldownLeft}"); if (trigger.IsAttached) attachedCount++; if (trigger.Pattern != null && trigger.Pattern.Active) { ImGui.Text($" {trigger.Pattern.GetType().Name} - {trigger.Pattern.DurationLeft}ms"); } } ImGui.Text($"{attachedCount} loaded"); ImGui.Text($"Devices: {Plugin.Devices.Count}"); foreach (Device device in Plugin.Devices.All) { ImGui.Text($" > {device.ClientDevice.Name}"); } } } } <file_sep>using System; using System.Text.RegularExpressions; using Dalamud.Game.Text; using Dalamud.Game.Text.SeStringHandling; using Dalamud.Logging; using Dalamud.Plugin; using ImGuiNET; namespace AetherSense.Triggers { public class ChatTrigger : TriggerBase { private string regexPattern = ""; private int duration = 1000; private int cooldown = 250; private bool wasPreviousMessageYou = false; private bool onlyYou = true; private DateTime cooldownUntil = DateTime.MinValue; public int Duration { get => this.duration; set => this.duration = value; } public int Cooldown { get => this.cooldown; set => this.cooldown = value; } public override int CooldownLeft { get { if (DateTime.Now > cooldownUntil) return 0; return (int)((cooldownUntil - DateTime.Now).TotalMilliseconds); } } public bool OnlyYou { get => this.onlyYou; set => onlyYou = value; } public string RegexPattern { get => this.regexPattern; set => this.regexPattern = value; } public override void Attach() { base.Attach(); Plugin.ChatGui.ChatMessage += this.OnChatMessage; } public override void Detach() { base.Detach(); Plugin.ChatGui.ChatMessage -= this.OnChatMessage; } public override void OnEditorGui() { ImGui.SameLine(); ImGui.Checkbox("Only Self", ref this.onlyYou); if (ImGui.IsItemHovered()) ImGui.SetTooltip("This trigger will only work if the proceding line in the log begins with 'You', eg. 'You cast' or 'You use'"); ImGui.InputText("Regex", ref this.regexPattern, 100); if (ImGui.IsItemHovered()) ImGui.SetTooltip("A regex-format string to check each chat message with."); ImGui.InputInt("Duration", ref this.duration); if (ImGui.IsItemHovered()) ImGui.SetTooltip("The duration to run the selected pattern for when this trigger runs."); ImGui.InputInt("Cooldown", ref this.cooldown); if (ImGui.IsItemHovered()) ImGui.SetTooltip("The cooldown before this trigger can be run again."); } private void OnChatMessage(XivChatType type, uint senderId, ref SeString sender, ref SeString message, ref bool isHandled) { if (this.Pattern == null) return; this.OnChatMessage(sender.TextValue, message.TextValue); } public void OnChatMessage(string sender, string message) { // Don't process any chat messages if the plugin is globally disabled if (!Plugin.Configuration.Enabled) return; bool isSystem = string.IsNullOrEmpty(sender); if (this.OnlyYou) { bool currentMessageWasYou = (isSystem && (message.StartsWith("You") || message.StartsWith("Vous") || message.StartsWith("Du"))); if (!this.wasPreviousMessageYou) { this.wasPreviousMessageYou = currentMessageWasYou; return; } } // Add the sender back into the message before regex. if (!isSystem) message = sender + ": " + message; if (!Regex.IsMatch(message, this.RegexPattern)) return; if (DateTime.Now < cooldownUntil) return; cooldownUntil = DateTime.Now.AddMilliseconds(this.Cooldown); PluginLog.Information($"Triggered: {this.Name} with chat message: \"{message}\""); this.Pattern.RunFor(this.Duration); } } } <file_sep>using System; using System.Collections.Generic; using System.Numerics; using AetherSense.Patterns; using AetherSense.Utils; using ImGuiNET; using Newtonsoft.Json; namespace AetherSense.Triggers { public abstract class TriggerBase { private string name = ""; private bool enabled = true; public string Name { get => this.name; set => this.name = value; } public bool Enabled { get => this.enabled; set => this.enabled = value; } public virtual int CooldownLeft => 0; [JsonIgnore] public bool IsAttached { get; private set; } public PatternBase Pattern { get; set; } = new ConstantPattern(); public int DeviceGroup { get; set; } = 0; public virtual void Attach() { this.IsAttached = true; } public virtual void Detach() { this.IsAttached = false; } public bool OnEditorGuiTop(int index) { bool keepEntry = true; ImGui.PushID("entry_" + index.ToString()); string check = this.enabled ? "X" : " "; bool open = ImGui.CollapsingHeader(index.ToString(), ref keepEntry); ImGui.SameLine(); ImGui.Text($"[{check}] {this.name}"); if (open) { ImGui.InputText("Name", ref this.name, 32); ImGui.Columns(2); ImGui.Checkbox("Enable", ref this.enabled); ImGui.NextColumn(); // Group selector string label = this.DeviceGroup == 0 ? "All" : "Group " + this.DeviceGroup; if (ImGui.BeginCombo($"Devices", label)) { for (int n = 0; n < 10; n++) { label = n == 0 ? "All" : "Group " + n; if (ImGui.Selectable(label, n == this.DeviceGroup)) { this.DeviceGroup = n; } } ImGui.EndCombo(); } ImGui.Columns(1); ImGui.Separator(); ImGui.Columns(2); ImGui.Spacing(); this.OnEditorGui(); ImGui.NextColumn(); if (ImGui.BeginCombo("Pattern", NameUtility.ToName(this.Pattern.GetType().Name))) { foreach (Type type in ConfigurationEditor.PatternTypes) { if (ImGui.Selectable(NameUtility.ToName(type.Name))) { this.Pattern = (PatternBase)Activator.CreateInstance(type); } } ImGui.EndCombo(); } if (this.Pattern != null) { this.Pattern.OnEditorGuiTop(); } ImGui.NextColumn(); ImGui.Columns(1); } ImGui.PopID(); return keepEntry; } public abstract void OnEditorGui(); } } <file_sep>using AetherSense.Triggers; using Dalamud.Logging; using Dalamud.Plugin; using Newtonsoft.Json; using System; using System.Collections.Generic; using System.IO; namespace AetherSense { [Serializable] public class Configuration { public static readonly JsonSerializerSettings Settings = new JsonSerializerSettings() { TypeNameHandling = TypeNameHandling.Objects, TypeNameAssemblyFormatHandling = TypeNameAssemblyFormatHandling.Simple, Formatting = Formatting.Indented, }; public bool Enabled { get; set; } = true; public string ServerAddress { get; set; } = "ws://127.0.0.1:12345"; public List<TriggerBase> Triggers { get; set; } = new List<TriggerBase>(); public Dictionary<string, int> DeviceGroups { get; set; } = new Dictionary<string, int>(); public static Configuration Load() { string path = GetPath(); if (!File.Exists(path)) { PluginLog.Information("Loading default configuration"); return GetDefaultConfiguration(); } string json = File.ReadAllText(path); return JsonConvert.DeserializeObject<Configuration>(json, Settings); } public static Configuration GetDefaultConfiguration() { string dir = Plugin.DalamudPluginInterface.GetPluginDirectory(); string path = Path.Combine(dir, "DefaultConfiguration.json"); if (!File.Exists(path)) { throw new Exception($"Unable to locate default configuration at {path}"); } string json = File.ReadAllText(path); return JsonConvert.DeserializeObject<Configuration>(json, Settings); } public void Save() { string json = JsonConvert.SerializeObject(this, Settings); string path = GetPath(); File.WriteAllText(path, json); ////Plugin.DalamudPluginInterface.SavePluginConfig(this); } private static string GetPath() { if (Plugin.DalamudPluginInterface == null) return "config.json"; string path = Path.Combine(Plugin.DalamudPluginInterface.GetPluginConfigDirectory() + "/config.json"); if (File.Exists(path)) return path; // Migrate old config name string oldPath = Path.Combine(Plugin.DalamudPluginInterface.GetPluginConfigDirectory() + "_custom.json"); if (File.Exists(oldPath)) File.Move(oldPath, path); // Magrate other old config name string oldPath2 = Path.Combine(Plugin.DalamudPluginInterface.GetPluginConfigDirectory() + "config.json"); if (File.Exists(oldPath2)) File.Move(oldPath2, path); return path; } } } <file_sep>using System; using System.Threading.Tasks; using Buttplug; namespace AetherSense { public class Device { public readonly ButtplugClientDevice ClientDevice; private double lastIntensity; public double Intensity { get; set; } public int Group { get { int group = 1; if (!Plugin.Configuration.DeviceGroups.TryGetValue(this.ClientDevice.Name, out group)) group = 1; return group; } } public Device(ButtplugClientDevice clientDevice) { this.ClientDevice = clientDevice; } public async Task Write() { if (this.Intensity == this.lastIntensity) return; this.lastIntensity = this.Intensity; double i = Math.Max(this.Intensity, 0); i = Math.Min(i, 1); await this.ClientDevice.SendVibrateCmd(i); if (i <= 0) { await this.ClientDevice.SendVibrateCmd(0); await this.ClientDevice.SendStopDeviceCmd(); } } } } <file_sep>using System; using System.Globalization; using System.Numerics; using System.Reflection; using System.Runtime.Serialization; using Dalamud.Configuration; using Dalamud.Plugin; using Serilog; using Serilog.Core; using Serilog.Events; using Veldrid; using Veldrid.Sdl2; using Veldrid.StartupUtilities; namespace ImGuiNET { public class Program { private static AetherSense.Plugin plugin = new AetherSense.Plugin(null); private static Sdl2Window _window; private static GraphicsDevice _gd; private static CommandList _cl; private static ImGuiController _controller; private static Vector3 _clearColor = new Vector3(0.45f, 0.55f, 0.6f); public static void Main(string[] args) { LoggerConfiguration loggers = new LoggerConfiguration().MinimumLevel.Verbose().Enrich.FromLogContext(); loggers.WriteTo.Logger(logger => logger.WriteTo.Console(restrictedToMinimumLevel: LogEventLevel.Verbose)); Log.Logger = loggers.CreateLogger(); Log.Logger.Information("Logger is initialized"); Action a = plugin.InitializeMock(); // Create window, GraphicsDevice, and all resources necessary for the demo. VeldridStartup.CreateWindowAndGraphicsDevice( new WindowCreateInfo(50, 50, 1280, 720, WindowState.Normal, "ImGui.NET Sample Program"), new GraphicsDeviceOptions(true, null, true, ResourceBindingModel.Improved, true, true), out _window, out _gd); _window.Resized += () => { _gd.MainSwapchain.Resize((uint)_window.Width, (uint)_window.Height); _controller.WindowResized(_window.Width, _window.Height); }; _cl = _gd.ResourceFactory.CreateCommandList(); _controller = new ImGuiController(_gd, _gd.MainSwapchain.Framebuffer.OutputDescription, _window.Width, _window.Height); Random random = new Random(); // Main application loop while (_window.Exists) { InputSnapshot snapshot = _window.PumpEvents(); if (!_window.Exists) { break; } _controller.Update(1f / 60f, snapshot); // Feed the input events to our ImGui controller, which passes them through to ImGui. a.Invoke(); ImGui.ShowDemoWindow(); _cl.Begin(); _cl.SetFramebuffer(_gd.MainSwapchain.Framebuffer); _cl.ClearColorTarget(0, new RgbaFloat(_clearColor.X, _clearColor.Y, _clearColor.Z, 1f)); _controller.Render(_gd, _cl); _cl.End(); _gd.SubmitCommands(_cl); _gd.SwapBuffers(_gd.MainSwapchain); } // Clean up Veldrid resources _gd.WaitForIdle(); _controller.Dispose(); _cl.Dispose(); _gd.Dispose(); } } }
3a8381925dbbbbe1203b6d6e6ccbaadbbe379ec0
[ "C#" ]
11
C#
TiefieBlau/AetherSense
c0c1eec08b8668405fa13fb6d252636aee27a895
d1977f2173855fb35e340295079d68654cc9e983
refs/heads/master
<repo_name>PavelNedoshivin/Multiplying-Using-FFT<file_sep>/README.md <b>Multiplying Using FFT</b><br> This is implemenation of application for multiplying big integers using Fast Fourier Transform made by SUAI student, <NAME>.<br> Features: loading from file or reading from console, counting time when using FFT or not.<br> <file_sep>/FFT/main.cpp #include "fft.h" int main(int argc, char** argv) { FFT* example = new FFT; try { example->load(argv[1]); double time1 = clock(); example->multiply(); double time2 = clock(); double time = (time2 - time1) / (double)CLOCKS_PER_SEC; std::cout << "FFT runtime: " << time << std::endl; example->save(argv[2]); } catch (WrongInputException& o) { std::cout << "Error: " << o.what() << std::endl; } delete example; FFT* lab = new FFT; try { lab->load(argv[1]); double time1 = clock(); lab->multiply_simple(); double time2 = clock(); double time = (time2 - time1) / (double)CLOCKS_PER_SEC; std::cout << "Classic runtime: " << time << std::endl; lab->save(argv[2]); } catch (WrongInputException& o) { std::cout << "Error: " << o.what() << std::endl; } delete lab; return 0; }<file_sep>/FFT/fft.h /** * @mainpage * The program is designed to multiply two long numbers. * Multiplication occurs in two ways: with the help of FFT and "column". * Organized file input/output numbers. * @author <NAME> 2017 * @warning It is prohibited to send symbols other than numbers to program. * @note fft.h contains many basic libraries like iostream, vector, string, algorithm. * @page pagereq System requirements * There are no special requirements for system. */ /** * @file fft.h Library of FFT class. Contains main methods like file input/outut and multiplying itself. * @file fft.cpp This file contains implementation of FFT class methods. * @file main.cpp This file is created for running program. Also communicates with command line. */ #ifndef FFT_H #define FFT_H #include <fstream> #include <iostream> #include <algorithm> #include <vector> #include <complex> #include <string> #include <ctime> typedef std::complex<double> cd; typedef std::vector<cd> vcd; ///WrongInputException is exception (successor of std::exception). Displays the corresponding text when an input error occurs. Input error: not numbers, but other characters in the input file. class WrongInputException : public std::exception { private: std::string str; public: ///Constructor WrongInputException(char* text) { str = text; } ///Displaying the error message const std::string& what() { return str; } }; ///FFT is the main working class. Can multiply long numbers in two ways. Stores numbers and result in integer vectors. class FFT { private: std::vector<int> first; std::vector<int> second; std::vector<int> result; bool sign; void transform(vcd& a, bool invert); void set_sign(); public: FFT(); FFT(const std::vector<int>& o1, const std::vector<int>& o2); FFT(const FFT& o); FFT& operator=(const FFT& o); void set_first(const std::vector<int>& o); void set_second(const std::vector<int>& o); std::istream& read(std::istream& in); std::ostream& write(std::ostream& out); friend std::istream& operator>>(std::istream& in, FFT& o); friend std::ostream& operator<<(std::ostream& out, FFT& o); void load(const std::string& filename); void save(const std::string& filename); void multiply(); void multiply_simple(); ~FFT(); }; #endif<file_sep>/FFT/fft.cpp #include "fft.h" void FFT::set_sign() { sign = false; if (first.size()) { if (first[first.size() - 1] < 0) { sign = !sign; first[first.size() - 1] = -first[first.size() - 1]; } } if (second.size()) { if (second[second.size() - 1] < 0) { sign = !sign; second[second.size() - 1] = -second[second.size() - 1]; } } } void FFT::transform(vcd& a, bool invert) { int n = a.size(); for (int i = 1, j = 0; i < n; i++) { int bit = n >> 1; for (; j >= bit; bit >>= 1) { j -= bit; } j += bit; if (i < j) { swap(a[i], a[j]); } } for (int len = 2; len <= n; len <<= 1) { double ang = 2 * 3.14159265358979323846 / len * (invert ? -1 : 1); cd wlen(cos(ang), sin(ang)); for (int i = 0; i < n; i += len) { cd w(1); for (int j = 0; j < len / 2; j++) { cd u = a[i + j]; cd v = a[i + j + len / 2] * w; a[i + j] = u + v; a[i + j + len / 2] = u - v; w *= wlen; } } } if (invert) { for (int i = 0; i < n; i++) { a[i] /= n; } } } /** * @name Constructors * @{ */ /** * Default constructor (empty) */ FFT::FFT() { ; } /** * Constructor. The input is reference on integer vectors. * @param o1 - the first number * @param o2 - the second number */ FFT::FFT(const std::vector<int>& o1, const std::vector<int>& o2) { first = o1; second = o2; set_sign(); } /** * Copying constructor. * @param o - a reference to the FFT class from which the class will be copied */ FFT::FFT(const FFT& o) { first = o.first; second = o.second; result = o.result; sign = o.sign; } /** * @} */ /** * Assignment operator. Copies the fields of the object. * @param o - a reference to the FFT class from which the class will be copied * @return this */ FFT& FFT::operator=(const FFT& o) { first = o.first; second = o.second; result = o.result; sign = o.sign; return *this; } /** * Set-method. Sets the first number. * @param o - reference to the vector of integers */ void FFT::set_first(const std::vector<int>& o) { first = o; set_sign(); } /** * Set-method. Sets the second number. * @param o - reference to the vector of integers */ void FFT::set_second(const std::vector<int>& o) { second = o; set_sign(); } /** * Reading operation. * @param in - input stream * @return in */ std::istream& FFT::read(std::istream& in) { std::string buff; in >> buff; bool flag = false; int i = 0; first.resize(buff.size()); if (buff[0] == '-') { i = 1; flag = true; first.resize(buff.size() - 1); } while (i < buff.size()) { if ((buff[i] >= '0') && (buff[i] <= '9')) { first[buff.size() - 1 - i] = buff[i] - '0'; if ((i == 1) && (flag)) { first[buff.size() - 2] = -first[buff.size() - 2]; } i++; } else { throw WrongInputException("wrong input exception"); } } in >> buff; i = 0; flag = false; second.resize(buff.size()); if (buff[0] == '-') { i = 1; flag = true; second.resize(buff.size() - 1); } while (i < buff.size()) { if ((buff[i] >= '0') && (buff[i] <= '9')) { second[buff.size() - 1 - i] = buff[i] - '0'; if ((i == 1) && (flag)) { second[buff.size() - 2] = -second[buff.size() - 2]; } i++; } else { throw WrongInputException("wrong input exception"); } } set_sign(); return in; } /** * Writing operation. * @param out - output stream * @return out */ std::ostream& FFT::write(std::ostream& out) { int i = result.size() - 1; while ((result[i] == 0) && (i > 0)) { i--; } if (sign) { result[i] = -result[i]; } while (i >= 0) { out << result[i]; i--; } out << std::endl; return out; } /** * The input operator (>>). * @param in - input stream * @param o - the FFT class, in which vectors will be read * @return in */ std::istream& operator>>(std::istream& in, FFT& o) { o.read(in); return in; } /** * The output operator (<<). * @param out - output stream * @param o - FFT class, from which the result vector will be written * @return out */ std::ostream& operator<<(std::ostream& out, FFT& o) { o.write(out); return out; } /** * Loading from file. * @param filename - the name of the file in which there are 2 vectors of integers */ void FFT::load(const std::string& filename) { std::ifstream fin(filename, std::ios_base::in); fin.exceptions(std::ios_base::failbit | std::ios_base::badbit); fin.seekg(std::ios_base::beg); fin >> *this; fin.close(); } /** * Uploading to file. * @param filename - the name of the file to which the result vector will be written */ void FFT::save(const std::string& filename) { std::ofstream fout(filename, std::ios_base::out | std::ios_base::trunc); fout.exceptions(std::ios_base::failbit | std::ios_base::badbit); fout << *this; fout.close(); } /** * Multiplication with FFT */ void FFT::multiply() { vcd complex1(first.begin(), first.end()); vcd complex2(second.begin(), second.end()); size_t n = 1; while (n < std::max(first.size(), second.size())) { n <<= 1; } n <<= 1; complex1.resize(n); complex2.resize(n); transform(complex1, false); transform(complex2, false); for (size_t i = 0; i < n; i++) { complex1[i] *= complex2[i]; } transform(complex1, true); result.resize(n); for (size_t i = 0; i < n; i++) { result[i] = int(complex1[i].real() + 0.5); } int mod = 0; for (int i = 0; i < result.size(); i++) { result[i] += mod; mod = result[i] / 10; result[i] %= 10; }; } /** * Multiplication by "column" */ void FFT::multiply_simple() { result.resize(first.size() + second.size() + 1); int i = 0; while (i < first.size()) { int j = 0; while (j < second.size()) { result[i + j] += first[i] * second[j]; j++; } i++; } for (i = 0; i < result.size() - 1; i++) { result[i + 1] += result[i] / 10; result[i] %= 10; } } /** * Destructor */ FFT::~FFT() { ; }
bc06057f0a07c4626e8bea44d0ca8f5860fec964
[ "Markdown", "C++" ]
4
Markdown
PavelNedoshivin/Multiplying-Using-FFT
0c5feb1036c24db34302a7c3b440e021f3daeae1
66ef727b347a1e79705c8499fdb9e6917fe2a356
refs/heads/master
<file_sep> import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.Date; import java.util.Random; import javax.swing.JOptionPane; import javax.swing.JTextField; /* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ /** * * @author <NAME> */ public class Account extends javax.swing.JFrame { Connection con; ResultSet rs; PreparedStatement pst; public Account() { super("Create Account"); initComponents(); con=javaconnect.connectDB(); RandomAcc(); RandomMICR(); RandomPIN(); } /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") public void RandomAcc(){ Random ra=new Random(); jTextField1.setText(""+ra.nextInt(1000000000+1)); } public void RandomMICR(){ Random ra=new Random(); jTextField2.setText("12035"); } public void RandomPIN(){ Random ra=new Random(); jTextField3.setText(""+ra.nextInt(19922+1)); } public void Bal(){ String sql="insert into Balances(Name,Acc,MICR_No,Balance) values(?,?,?,?)"; try{ pst=con.prepareStatement(sql); pst.setString(1,jTextField5.getText()); pst.setString(2,jTextField1.getText()); pst.setString(3,jTextField2.getText()); pst.setString(4,jTextField10.getText()); pst.execute(); } catch(Exception e) { JOptionPane.showMessageDialog(null,e); } } // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { buttonGroup1 = new javax.swing.ButtonGroup(); jLabel1 = new javax.swing.JLabel(); jPanel1 = new javax.swing.JPanel(); jButton1 = new javax.swing.JButton(); jRadioButton2 = new javax.swing.JRadioButton(); jLabel8 = new javax.swing.JLabel(); jTextField5 = new javax.swing.JTextField(); jTextField7 = new javax.swing.JTextField(); jLabel7 = new javax.swing.JLabel(); jTextField1 = new javax.swing.JTextField(); jDateChooser1 = new com.toedter.calendar.JDateChooser(); jLabel6 = new javax.swing.JLabel(); jLabel2 = new javax.swing.JLabel(); jComboBox1 = new javax.swing.JComboBox(); jLabel11 = new javax.swing.JLabel(); jTextField4 = new javax.swing.JTextField(); jTextField6 = new javax.swing.JTextField(); jTextField2 = new javax.swing.JTextField(); jButton3 = new javax.swing.JButton(); jTextField3 = new javax.swing.JTextField(); jLabel12 = new javax.swing.JLabel(); jLabel13 = new javax.swing.JLabel(); jLabel5 = new javax.swing.JLabel(); jLabel9 = new javax.swing.JLabel(); jLabel10 = new javax.swing.JLabel(); jLabel4 = new javax.swing.JLabel(); jLabel3 = new javax.swing.JLabel(); jRadioButton1 = new javax.swing.JRadioButton(); jLabel14 = new javax.swing.JLabel(); jTextField9 = new javax.swing.JTextField(); jButton4 = new javax.swing.JButton(); jComboBox3 = new javax.swing.JComboBox(); jLabel16 = new javax.swing.JLabel(); jTextField10 = new javax.swing.JTextField(); jComboBox2 = new javax.swing.JComboBox(); jLabel15 = new javax.swing.JLabel(); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); jLabel1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/d.png"))); // NOI18N jLabel1.setText(" "); jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 51, 51), 4), "New Account", javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, javax.swing.border.TitledBorder.DEFAULT_POSITION, new java.awt.Font("Tahoma", 1, 24), new java.awt.Color(0, 51, 51))); // NOI18N jButton1.setBackground(new java.awt.Color(0, 153, 0)); jButton1.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N jButton1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/rsz_images_1.jpg"))); // NOI18N jButton1.setText("Create"); jButton1.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton1ActionPerformed(evt); } }); buttonGroup1.add(jRadioButton2); jRadioButton2.setText("FEMALE"); jLabel8.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N jLabel8.setText("Name"); jTextField5.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jTextField5ActionPerformed(evt); } }); jLabel7.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N jLabel7.setText("ADDRESS"); jTextField1.setEditable(false); jLabel6.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N jLabel6.setText("GENDER"); jLabel2.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N jLabel2.setText("ACCOUNT NO"); jComboBox1.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Select", "Saving", "Current" })); jComboBox1.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jComboBox1ActionPerformed(evt); } }); jLabel11.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N jLabel11.setText("Caste"); jTextField2.setEditable(false); jTextField2.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jTextField2ActionPerformed(evt); } }); jButton3.setBackground(new java.awt.Color(204, 0, 0)); jButton3.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N jButton3.setIcon(new javax.swing.ImageIcon(getClass().getResource("/rsz_clear.jpg"))); // NOI18N jButton3.setText("Clear"); jButton3.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton3ActionPerformed(evt); } }); jTextField3.setEditable(false); jLabel12.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N jLabel12.setText("Mobile No."); jLabel13.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N jLabel13.setText("Security Q."); jLabel5.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N jLabel5.setText("ACCOUNT TYPE"); jLabel9.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N jLabel9.setText("DOB"); jLabel10.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N jLabel10.setText("Nationlaity"); jLabel4.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N jLabel4.setText("PIN"); jLabel3.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N jLabel3.setText("MICR NO"); buttonGroup1.add(jRadioButton1); jRadioButton1.setText("MALE"); jRadioButton1.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jRadioButton1ActionPerformed(evt); } }); jLabel14.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N jLabel14.setText("Answer"); jTextField9.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jTextField9ActionPerformed(evt); } }); jButton4.setBackground(new java.awt.Color(0, 51, 51)); jButton4.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N jButton4.setIcon(new javax.swing.ImageIcon(getClass().getResource("/rsz_1back.png"))); // NOI18N jButton4.setText("Back"); jButton4.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton4ActionPerformed(evt); } }); jComboBox3.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Select", "Hindu", "Muslim", "Christian", "Others" })); jLabel16.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N jLabel16.setText("AMOUNT"); jComboBox2.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "What's your nick name?", "What's your pet's name?", "What you want to be?" })); javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1); jPanel1.setLayout(jPanel1Layout); jPanel1Layout.setHorizontalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addContainerGap() .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addGap(91, 91, 91) .addComponent(jButton1) .addGap(70, 70, 70) .addComponent(jButton4, javax.swing.GroupLayout.PREFERRED_SIZE, 98, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(90, 90, 90) .addComponent(jButton3, javax.swing.GroupLayout.PREFERRED_SIZE, 97, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(jPanel1Layout.createSequentialGroup() .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel3) .addComponent(jLabel2) .addComponent(jLabel4) .addComponent(jLabel5) .addComponent(jLabel6) .addComponent(jLabel7) .addComponent(jLabel16)) .addGap(18, 18, 18) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, 154, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jTextField2, javax.swing.GroupLayout.PREFERRED_SIZE, 154, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jTextField3, javax.swing.GroupLayout.PREFERRED_SIZE, 154, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jRadioButton1) .addGroup(jPanel1Layout.createSequentialGroup() .addGap(10, 10, 10) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addComponent(jRadioButton2) .addComponent(jComboBox1, javax.swing.GroupLayout.PREFERRED_SIZE, 133, javax.swing.GroupLayout.PREFERRED_SIZE))) .addComponent(jTextField4, javax.swing.GroupLayout.DEFAULT_SIZE, 160, Short.MAX_VALUE) .addComponent(jTextField10)) .addGap(42, 42, 42) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel10) .addComponent(jLabel13) .addComponent(jLabel12) .addComponent(jLabel11) .addComponent(jLabel14)) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addGap(34, 34, 34) .addComponent(jComboBox3, javax.swing.GroupLayout.PREFERRED_SIZE, 120, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(jPanel1Layout.createSequentialGroup() .addGap(18, 18, 18) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false) .addComponent(jTextField7, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 157, Short.MAX_VALUE) .addComponent(jTextField6, javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jTextField9) .addComponent(jComboBox2, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))))) .addGroup(jPanel1Layout.createSequentialGroup() .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel8) .addComponent(jLabel9)) .addGap(53, 53, 53) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jTextField5, javax.swing.GroupLayout.PREFERRED_SIZE, 158, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jDateChooser1, javax.swing.GroupLayout.PREFERRED_SIZE, 158, javax.swing.GroupLayout.PREFERRED_SIZE)))))) .addContainerGap(12, Short.MAX_VALUE)) ); jPanel1Layout.setVerticalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addContainerGap() .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel2) .addComponent(jLabel8) .addComponent(jTextField5, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(23, 23, 23)) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup() .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 5, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(18, 18, 18))) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel3) .addComponent(jTextField2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel9)) .addComponent(jDateChooser1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(23, 23, 23) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel4) .addComponent(jTextField3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel10) .addComponent(jComboBox3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(26, 26, 26) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel5) .addComponent(jComboBox1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel11) .addComponent(jTextField6, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(27, 27, 27) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel6) .addComponent(jRadioButton1) .addComponent(jRadioButton2) .addComponent(jLabel12) .addComponent(jTextField7, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(25, 25, 25) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel7) .addComponent(jTextField4, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel13) .addComponent(jComboBox2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(13, 13, 13) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel14) .addComponent(jTextField9, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel16) .addComponent(jTextField10, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(52, 52, 52) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jButton1, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jButton4) .addComponent(jButton3))) .addGap(27, 27, 27)) ); jLabel15.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N jLabel15.setForeground(new java.awt.Color(153, 0, 0)); jLabel15.setText("Thank you for visiting our side"); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() .addContainerGap(223, Short.MAX_VALUE) .addComponent(jLabel15) .addGap(219, 219, 219)) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() .addGap(0, 10, Short.MAX_VALUE) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGap(10, 10, 10) .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addComponent(jLabel1)) .addContainerGap()) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addComponent(jLabel1) .addGap(1, 1, 1) .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(jLabel15, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addGap(28, 28, 28)) ); setSize(new java.awt.Dimension(666, 588)); setLocationRelativeTo(null); }// </editor-fold>//GEN-END:initComponents private void jTextField2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jTextField2ActionPerformed // TODO add your handling code here: }//GEN-LAST:event_jTextField2ActionPerformed private void jComboBox1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jComboBox1ActionPerformed // TODO add your handling code here: }//GEN-LAST:event_jComboBox1ActionPerformed private void jTextField5ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jTextField5ActionPerformed // TODO add your handling code here: }//GEN-LAST:event_jTextField5ActionPerformed private void jTextField9ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jTextField9ActionPerformed // TODO add your handling code here: }//GEN-LAST:event_jTextField9ActionPerformed private void jButton4ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton4ActionPerformed // TODO add your handling code here: setVisible(false); Authentication ob =new Authentication(); ob.setVisible(true); }//GEN-LAST:event_jButton4ActionPerformed private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton3ActionPerformed // TODO add your handling code here: jTextField1.setText(""); jTextField2.setText(""); jTextField3.setText(""); jTextField4.setText(""); jTextField5.setText(""); jTextField6.setText(""); jTextField7.setText(""); jTextField9.setText(""); jTextField10.setText(""); }//GEN-LAST:event_jButton3ActionPerformed private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed String sql="insert into Account(Acc,Name,DOB,Pin,Acc_Type,Nationality,Caste,MICR_No,Gender,Mob,Address,Sec_Q,Sec_A,Balance) values(?,?,?,?,?,?,?,?,?,?,?,?,?,?)"; try { DateFormat df = new SimpleDateFormat("MM/dd/yyyy"); Date today=jDateChooser1.getDate(); String reportDate = df.format(today); pst=con.prepareStatement(sql); pst.setString(1,jTextField1.getText()); pst.setString(2,jTextField5.getText()); pst.setString(3,reportDate); pst.setString(4,jTextField3.getText()); pst.setString(5,(String)jComboBox1.getSelectedItem()); pst.setString(6,(String)jComboBox3.getSelectedItem()); pst.setString(7,jTextField6.getText()); pst.setString(8,jTextField2.getText()); jRadioButton1.setActionCommand("Male"); jRadioButton2.setActionCommand("Female"); pst.setString(9,buttonGroup1.getSelection().getActionCommand()); pst.setString(10,jTextField7.getText()); pst.setString(11,jTextField4.getText()); pst.setString(12,(String)jComboBox2.getSelectedItem()); pst.setString(13,jTextField9.getText()); pst.setString(14,jTextField10.getText()); pst.execute(); JOptionPane.showMessageDialog(null,"Account Created Sccessfully"); Bal(); } catch(Exception e){ JOptionPane.showMessageDialog(null,e); } }//GEN-LAST:event_jButton1ActionPerformed private void jRadioButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jRadioButton1ActionPerformed // TODO add your handling code here: }//GEN-LAST:event_jRadioButton1ActionPerformed /** * @param args the command line arguments */ public static void main(String args[]) { /* Set the Nimbus look and feel */ //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) "> /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel. * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html */ try { for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { if ("Nimbus".equals(info.getName())) { javax.swing.UIManager.setLookAndFeel(info.getClassName()); break; } } } catch (ClassNotFoundException ex) { java.util.logging.Logger.getLogger(Account.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(Account.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(Account.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(Account.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } //</editor-fold> /* Create and display the form */ java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new Account().setVisible(true); } }); } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.ButtonGroup buttonGroup1; private javax.swing.JButton jButton1; private javax.swing.JButton jButton3; private javax.swing.JButton jButton4; private javax.swing.JComboBox jComboBox1; private javax.swing.JComboBox jComboBox2; private javax.swing.JComboBox jComboBox3; private com.toedter.calendar.JDateChooser jDateChooser1; private javax.swing.JLabel jLabel1; private javax.swing.JLabel jLabel10; private javax.swing.JLabel jLabel11; private javax.swing.JLabel jLabel12; private javax.swing.JLabel jLabel13; private javax.swing.JLabel jLabel14; private javax.swing.JLabel jLabel15; private javax.swing.JLabel jLabel16; private javax.swing.JLabel jLabel2; private javax.swing.JLabel jLabel3; private javax.swing.JLabel jLabel4; private javax.swing.JLabel jLabel5; private javax.swing.JLabel jLabel6; private javax.swing.JLabel jLabel7; private javax.swing.JLabel jLabel8; private javax.swing.JLabel jLabel9; private javax.swing.JPanel jPanel1; private javax.swing.JRadioButton jRadioButton1; private javax.swing.JRadioButton jRadioButton2; private javax.swing.JTextField jTextField1; private javax.swing.JTextField jTextField10; private javax.swing.JTextField jTextField2; private javax.swing.JTextField jTextField3; private javax.swing.JTextField jTextField4; private javax.swing.JTextField jTextField5; private javax.swing.JTextField jTextField6; private javax.swing.JTextField jTextField7; private javax.swing.JTextField jTextField9; // End of variables declaration//GEN-END:variables } <file_sep>import java.io.*; import java.net.*; import org.jfree.chart.*; import org.jfree.data.xy.*; import org.jfree.ui.*; import org.jfree.chart.plot.*; import org.jfree.chart.renderer.xy.XYLineAndShapeRenderer; import java.awt.*; import javax.swing.*; public class MyServer extends ApplicationFrame { static int [][]arr; static int z=0,i=0,y=0; static int [][]arr1; public static ChartPanel chartPanel; public static JFreeChart chart; public MyServer(final String title) { super(title); y++; final XYSeries series = new XYSeries("Availbale Datas"); final XYSeries series1 = new XYSeries("Remote Datas"); for(int k=0;k<i;k++) { series.add(arr1[k][0],arr1[k][1]); } for(int k=0;k<z;k++) { series1.add(arr[k][0],arr[k][1]); } final XYSeriesCollection data = new XYSeriesCollection(); data.addSeries(series); data.addSeries(series1); chart= ChartFactory.createScatterPlot("X-Y CO-ordinates","X","Y", data, PlotOrientation.VERTICAL,true,true,false); // chartPanel.setVisible(false); // jP=new JPanel(); ChartFrame chartPanel=new ChartFrame("",chart); //chartPanel.setPreferredSize(new java.awt.Dimension(500, 270)); final XYPlot plot = (XYPlot)chart.getPlot( ); /*XYLineAndShapeRenderer renderer = new XYLineAndShapeRenderer( ); renderer.setSeriesPaint( 0 , Color.GREEN ); renderer.setSeriesPaint( 1 , Color.BLUE ); plot.setRenderer( renderer );*/ plot.setBackgroundPaint(new Color(255,228,196)); //chartPanel.add(jf); chartPanel.setVisible(true); chartPanel.setSize(500,300); chartPanel.setLocationRelativeTo(null); try{ if(y==z) chartPanel.setVisible(false); }catch(Exception e){} } public static void main(String[] args)throws Exception{ BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); System.out.println("Enter the file name"); String f=br.readLine(); BufferedReader br1=new BufferedReader(new FileReader(f)); String st; while((st=br1.readLine())!=null){ i++; } BufferedReader br2=new BufferedReader(new FileReader(f)); arr1=new int[i][2]; int m=0,n=0; while((st=br2.readLine())!=null){ String[] words=st.split(" "); int l=words.length; for(int h=0;h<l;h++) { arr1[m][n]=Integer.parseInt(words[h]); n++; if(n>1){ n=0; m++;} } } System.out.println("Available Datas"); for(int j=0;j<i;j++) { for(int k=0;k<2;k++) System.out.print(arr1[j][k]+"\t"); System.out.println(); } ServerSocket ss=new ServerSocket(6666); System.out.println("Server is waiting for dats of present in remote machine"); Socket s=ss.accept(); System.out.println("Connection Establishd\nReceiveing Datas"); DataInputStream dis=new DataInputStream(s.getInputStream()); String str=" "; arr=new int[100][2]; System.out.println("Remote Datas"); while(!str.equals("END")){ str=(String)dis.readUTF(); if(!str.equals("END")){ String[] words=str.split(" "); for(int i=0;i<words.length;i++) { arr[z][i]=Integer.parseInt(words[i]); System.out.print(arr[z][i]+" "); } z++; System.out.println(); } } final MyServer demo = new MyServer("Real Time Sys Display"); demo.pack(); RefineryUtilities.centerFrameOnScreen(demo); demo.setVisible(true); ss.close(); //catch(Exception e){System.out.println(e);} } } <file_sep>package com.controller; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.SQLException; import com.db.Provider; import com.db.Users; public class UsersDao { public static int save(Users u) { int status=0; try { Connection con=Provider.getConnection(); System.out.print("Hi"+con); String sql="Insert into Third values(?,?,?,?,?,?)"; PreparedStatement pst=con.prepareStatement(sql); pst.setString(1,u.getReg()); pst.setString(2,u.getName()); pst.setString(3,u.getBranch()); pst.setString(4,u.getBg()); pst.setString(5,u.getDob()); pst.setString(6,u.getMob()); status=pst.executeUpdate(); System.out.print(status); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } return status; } } <file_sep># Projects are mainly based on jdbc javasript and SQL.Port no.=9090 <file_sep> import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.time.LocalTime; import java.util.Calendar; import java.util.GregorianCalendar; import javax.swing.JDialog; import javax.swing.JOptionPane; import javax.swing.JTabbedPane; import net.proteanit.sql.DbUtils; /* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ /** * * @author <NAME> */ public class MyPage extends javax.swing.JFrame { Connection con; ResultSet rs; PreparedStatement pst; public MyPage() { super("Home"); initComponents(); con=javaconnect.connectDB(); jTextField1.setText(Authentication.x); jPasswordField1.setEchoChar('*'); Calender(); Table(); Table1(); } public void Calender(){ Calendar cal=new GregorianCalendar(); int month=cal.get(Calendar.MONTH); int year=cal.get(Calendar.YEAR); int day=cal.get(Calendar.DAY_OF_MONTH); jTextField2.setText(+day+"-"+(month+1)+"-"+year); } public void Table() { String sql="select Acc,Name,DOB,Acc_Type,Gender from Account"; try{ pst=con.prepareStatement(sql); rs=pst.executeQuery(); jTable1.setModel(DbUtils.resultSetToTableModel(rs)); } catch(Exception e) { JOptionPane.showMessageDialog(null, e); } finally{ try{ rs.close(); pst.close(); } catch(Exception e){ JOptionPane.showMessageDialog(null, e); } } } public void Table1() { String x=jTextField1.getText(); String sql="select Acc_No,Name,Transfer_Amount,Recieve_Amount,Date,Time from Tra where Acc='"+x+"'"; try{ pst=con.prepareStatement(sql); rs=pst.executeQuery(); jTable2.setModel(DbUtils.resultSetToTableModel(rs)); } catch(Exception e) { JOptionPane.showMessageDialog(null,"here"+e); } finally{ try{ rs.close(); pst.close(); } catch(Exception e){ JOptionPane.showMessageDialog(null, e); } } } /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { jLabel1 = new javax.swing.JLabel(); jLabel2 = new javax.swing.JLabel(); jLabel3 = new javax.swing.JLabel(); jTextField1 = new javax.swing.JTextField(); jTextField2 = new javax.swing.JTextField(); jTabbedPane1 = new javax.swing.JTabbedPane(); jPanel4 = new javax.swing.JPanel(); jLabel24 = new javax.swing.JLabel(); jLabel25 = new javax.swing.JLabel(); jLabel26 = new javax.swing.JLabel(); jLabel27 = new javax.swing.JLabel(); jTextField25 = new javax.swing.JTextField(); jTextField26 = new javax.swing.JTextField(); jTextField27 = new javax.swing.JTextField(); jTextField28 = new javax.swing.JTextField(); jButton10 = new javax.swing.JButton(); jButton11 = new javax.swing.JButton(); jPanel5 = new javax.swing.JPanel(); jScrollPane1 = new javax.swing.JScrollPane(); jTable1 = new javax.swing.JTable(); jPanel6 = new javax.swing.JPanel(); jScrollPane2 = new javax.swing.JScrollPane(); jTable2 = new javax.swing.JTable(); jPanel7 = new javax.swing.JPanel(); jLabel28 = new javax.swing.JLabel(); jLabel29 = new javax.swing.JLabel(); jLabel30 = new javax.swing.JLabel(); jLabel31 = new javax.swing.JLabel(); jLabel32 = new javax.swing.JLabel(); jLabel33 = new javax.swing.JLabel(); jTextField29 = new javax.swing.JTextField(); jTextField30 = new javax.swing.JTextField(); jTextField31 = new javax.swing.JTextField(); jTextField32 = new javax.swing.JTextField(); jTextField33 = new javax.swing.JTextField(); jTextField34 = new javax.swing.JTextField(); jPanel8 = new javax.swing.JPanel(); jLabel34 = new javax.swing.JLabel(); jLabel35 = new javax.swing.JLabel(); jTextField36 = new javax.swing.JTextField(); jButton12 = new javax.swing.JButton(); jButton13 = new javax.swing.JButton(); jButton14 = new javax.swing.JButton(); jPasswordField1 = new javax.swing.JPasswordField(); jPanel1 = new javax.swing.JPanel(); jLabel4 = new javax.swing.JLabel(); jLabel5 = new javax.swing.JLabel(); jLabel6 = new javax.swing.JLabel(); jLabel7 = new javax.swing.JLabel(); jLabel8 = new javax.swing.JLabel(); jTextField3 = new javax.swing.JTextField(); jTextField4 = new javax.swing.JTextField(); jTextField5 = new javax.swing.JTextField(); jTextField6 = new javax.swing.JTextField(); jTextField7 = new javax.swing.JTextField(); jLabel9 = new javax.swing.JLabel(); jLabel10 = new javax.swing.JLabel(); jLabel11 = new javax.swing.JLabel(); jLabel12 = new javax.swing.JLabel(); jLabel13 = new javax.swing.JLabel(); jTextField8 = new javax.swing.JTextField(); jTextField9 = new javax.swing.JTextField(); jTextField10 = new javax.swing.JTextField(); jTextField11 = new javax.swing.JTextField(); jTextField12 = new javax.swing.JTextField(); jButton1 = new javax.swing.JButton(); jButton3 = new javax.swing.JButton(); jPanel2 = new javax.swing.JPanel(); jLabel14 = new javax.swing.JLabel(); jLabel15 = new javax.swing.JLabel(); jLabel16 = new javax.swing.JLabel(); jLabel17 = new javax.swing.JLabel(); jTextField13 = new javax.swing.JTextField(); jTextField14 = new javax.swing.JTextField(); jTextField15 = new javax.swing.JTextField(); jTextField16 = new javax.swing.JTextField(); jTextField17 = new javax.swing.JTextField(); jButton4 = new javax.swing.JButton(); jButton5 = new javax.swing.JButton(); jPanel3 = new javax.swing.JPanel(); jLabel18 = new javax.swing.JLabel(); jLabel19 = new javax.swing.JLabel(); jLabel20 = new javax.swing.JLabel(); jLabel21 = new javax.swing.JLabel(); jLabel22 = new javax.swing.JLabel(); jTextField18 = new javax.swing.JTextField(); jTextField19 = new javax.swing.JTextField(); jTextField20 = new javax.swing.JTextField(); jTextField21 = new javax.swing.JTextField(); jTextField22 = new javax.swing.JTextField(); jButton6 = new javax.swing.JButton(); jTextField23 = new javax.swing.JTextField(); jButton7 = new javax.swing.JButton(); jLabel23 = new javax.swing.JLabel(); jTextField24 = new javax.swing.JTextField(); jButton8 = new javax.swing.JButton(); jButton9 = new javax.swing.JButton(); jPanel9 = new javax.swing.JPanel(); jLabel36 = new javax.swing.JLabel(); jLabel37 = new javax.swing.JLabel(); jLabel38 = new javax.swing.JLabel(); jLabel39 = new javax.swing.JLabel(); jLabel40 = new javax.swing.JLabel(); jButton2 = new javax.swing.JButton(); jButton15 = new javax.swing.JButton(); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); jLabel1.setIcon(new javax.swing.ImageIcon("M:\\ADVJAVA\\NETBEANS\\Banking_Management_System\\src\\d.png")); // NOI18N jLabel2.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N jLabel2.setText("User"); jLabel3.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N jLabel3.setText("Date"); jTextField1.setEditable(false); jTextField2.setEditable(false); jTabbedPane1.setBackground(new java.awt.Color(255, 255, 255)); jTabbedPane1.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(255, 51, 51))); jPanel4.setBackground(new java.awt.Color(153, 255, 255)); jPanel4.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 102, 102), 2)); jLabel24.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N jLabel24.setText("Name"); jLabel25.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N jLabel25.setText("Available Balance"); jLabel26.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N jLabel26.setText("Withdrawl Amount"); jLabel27.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N jLabel27.setText("Reamaining Balance"); jTextField25.setEditable(false); jTextField26.setEditable(false); jTextField28.setEditable(false); jButton10.setBackground(new java.awt.Color(51, 51, 51)); jButton10.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N jButton10.setIcon(new javax.swing.ImageIcon("C:\\Users\\Mohan\\Pictures\\ICONS\\rsz_show.jpg")); // NOI18N jButton10.setText("Show"); jButton10.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton10ActionPerformed(evt); } }); jButton11.setBackground(new java.awt.Color(204, 153, 0)); jButton11.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N jButton11.setIcon(new javax.swing.ImageIcon("C:\\Users\\Mohan\\Pictures\\ICONS\\rsz_wd.jpg")); // NOI18N jButton11.setText("Withdarw"); jButton11.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton11ActionPerformed(evt); } }); javax.swing.GroupLayout jPanel4Layout = new javax.swing.GroupLayout(jPanel4); jPanel4.setLayout(jPanel4Layout); jPanel4Layout.setHorizontalGroup( jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel4Layout.createSequentialGroup() .addGap(117, 117, 117) .addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel24) .addComponent(jLabel25) .addComponent(jLabel26) .addComponent(jLabel27)) .addGap(30, 30, 30) .addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addComponent(jTextField25) .addComponent(jTextField26) .addComponent(jTextField27) .addComponent(jTextField28, javax.swing.GroupLayout.DEFAULT_SIZE, 152, Short.MAX_VALUE)) .addGap(18, 18, 18) .addComponent(jButton10) .addContainerGap(76, Short.MAX_VALUE)) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel4Layout.createSequentialGroup() .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jButton11) .addGap(203, 203, 203)) ); jPanel4Layout.setVerticalGroup( jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel4Layout.createSequentialGroup() .addGap(54, 54, 54) .addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addGroup(jPanel4Layout.createSequentialGroup() .addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addGroup(jPanel4Layout.createSequentialGroup() .addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel24) .addComponent(jTextField25, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(35, 35, 35) .addComponent(jLabel25)) .addComponent(jTextField26, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(46, 46, 46) .addComponent(jLabel26)) .addComponent(jTextField27, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(36, 36, 36) .addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addComponent(jLabel27) .addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jTextField28, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jButton10))) .addGap(18, 18, 18) .addComponent(jButton11) .addContainerGap(102, Short.MAX_VALUE)) ); jTabbedPane1.addTab("Withdrawl", jPanel4); jPanel5.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 153, 0), 2)); jTable1.setModel(new javax.swing.table.DefaultTableModel( new Object [][] { {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null} }, new String [] { "Title 1", "Title 2", "Title 3", "Title 4" } )); jScrollPane1.setViewportView(jTable1); javax.swing.GroupLayout jPanel5Layout = new javax.swing.GroupLayout(jPanel5); jPanel5.setLayout(jPanel5Layout); jPanel5Layout.setHorizontalGroup( jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel5Layout.createSequentialGroup() .addContainerGap() .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 578, Short.MAX_VALUE) .addContainerGap()) ); jPanel5Layout.setVerticalGroup( jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel5Layout.createSequentialGroup() .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 380, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(0, 15, Short.MAX_VALUE)) ); jTabbedPane1.addTab("Customer List", jPanel5); jPanel6.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(153, 153, 0), 2)); jTable2.setModel(new javax.swing.table.DefaultTableModel( new Object [][] { {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null} }, new String [] { "Title 1", "Title 2", "Title 3", "Title 4" } )); jScrollPane2.setViewportView(jTable2); javax.swing.GroupLayout jPanel6Layout = new javax.swing.GroupLayout(jPanel6); jPanel6.setLayout(jPanel6Layout); jPanel6Layout.setHorizontalGroup( jPanel6Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel6Layout.createSequentialGroup() .addContainerGap() .addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 578, Short.MAX_VALUE) .addContainerGap()) ); jPanel6Layout.setVerticalGroup( jPanel6Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel6Layout.createSequentialGroup() .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 382, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(0, 13, Short.MAX_VALUE)) ); jTabbedPane1.addTab("Transaction", jPanel6); jPanel7.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 204, 204), 2)); jLabel28.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N jLabel28.setText("Name"); jLabel29.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N jLabel29.setText("MICR_NO"); jLabel30.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N jLabel30.setText("Available Balance"); jLabel31.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N jLabel31.setText("Rate of Interest"); jLabel32.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N jLabel32.setText("MOD Balance"); jLabel33.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N jLabel33.setText("Nomonation Registered"); jTextField29.setEditable(false); jTextField30.setEditable(false); jTextField31.setEditable(false); jTextField32.setEditable(false); jTextField33.setEditable(false); jTextField34.setEditable(false); javax.swing.GroupLayout jPanel7Layout = new javax.swing.GroupLayout(jPanel7); jPanel7.setLayout(jPanel7Layout); jPanel7Layout.setHorizontalGroup( jPanel7Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel7Layout.createSequentialGroup() .addGap(112, 112, 112) .addGroup(jPanel7Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel28) .addComponent(jLabel29) .addComponent(jLabel30) .addComponent(jLabel31) .addComponent(jLabel32) .addComponent(jLabel33)) .addGap(22, 22, 22) .addGroup(jPanel7Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addComponent(jTextField29) .addComponent(jTextField30) .addComponent(jTextField31) .addComponent(jTextField32) .addComponent(jTextField33) .addComponent(jTextField34, javax.swing.GroupLayout.DEFAULT_SIZE, 159, Short.MAX_VALUE)) .addContainerGap(162, Short.MAX_VALUE)) ); jPanel7Layout.setVerticalGroup( jPanel7Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel7Layout.createSequentialGroup() .addGap(59, 59, 59) .addGroup(jPanel7Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addGroup(jPanel7Layout.createSequentialGroup() .addGroup(jPanel7Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addGroup(jPanel7Layout.createSequentialGroup() .addGroup(jPanel7Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addGroup(jPanel7Layout.createSequentialGroup() .addGroup(jPanel7Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addComponent(jLabel28) .addComponent(jTextField29, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(31, 31, 31) .addGroup(jPanel7Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel29) .addComponent(jTextField30, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(33, 33, 33) .addComponent(jLabel30)) .addComponent(jTextField31, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(35, 35, 35) .addComponent(jLabel31)) .addComponent(jTextField32, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(32, 32, 32) .addComponent(jLabel32)) .addComponent(jTextField33, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(33, 33, 33) .addGroup(jPanel7Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel33) .addComponent(jTextField34, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addContainerGap(61, Short.MAX_VALUE)) ); jTabbedPane1.addTab("View Balance", jPanel7); jPanel8.setBackground(new java.awt.Color(204, 204, 255)); jPanel8.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(51, 51, 255), 2)); jLabel34.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N jLabel34.setText("Enter Old Pin"); jLabel35.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N jLabel35.setText("New Pin"); jButton12.setIcon(new javax.swing.ImageIcon("C:\\Users\\Mohan\\Pictures\\ICONS\\rsz_11cahnge.png")); // NOI18N jButton12.setText("Change"); jButton12.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton12ActionPerformed(evt); } }); jButton13.setIcon(new javax.swing.ImageIcon("C:\\Users\\Mohan\\Pictures\\ICONS\\rsz_clear.jpg")); // NOI18N jButton13.setText("Clear"); jButton13.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton13ActionPerformed(evt); } }); jButton14.setIcon(new javax.swing.ImageIcon("C:\\Users\\Mohan\\Pictures\\ICONS\\rsz_1eye.png")); // NOI18N jButton14.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton14ActionPerformed(evt); } }); javax.swing.GroupLayout jPanel8Layout = new javax.swing.GroupLayout(jPanel8); jPanel8.setLayout(jPanel8Layout); jPanel8Layout.setHorizontalGroup( jPanel8Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel8Layout.createSequentialGroup() .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jButton12) .addGap(61, 61, 61) .addComponent(jButton13) .addGap(89, 89, 89)) .addGroup(jPanel8Layout.createSequentialGroup() .addGap(137, 137, 137) .addGroup(jPanel8Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel34) .addComponent(jLabel35)) .addGap(49, 49, 49) .addGroup(jPanel8Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addComponent(jTextField36) .addComponent(jPasswordField1, javax.swing.GroupLayout.DEFAULT_SIZE, 144, Short.MAX_VALUE)) .addGap(18, 18, 18) .addComponent(jButton14) .addContainerGap(124, Short.MAX_VALUE)) ); jPanel8Layout.setVerticalGroup( jPanel8Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel8Layout.createSequentialGroup() .addGap(75, 75, 75) .addGroup(jPanel8Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel34) .addComponent(jButton14) .addComponent(jPasswordField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(34, 34, 34) .addGroup(jPanel8Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel35) .addComponent(jTextField36, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(18, 18, 18) .addGroup(jPanel8Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jButton12) .addComponent(jButton13)) .addContainerGap(196, Short.MAX_VALUE)) ); jTabbedPane1.addTab("Change Pin", jPanel8); jPanel1.setBackground(new java.awt.Color(255, 204, 255)); jPanel1.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 51), 2)); jLabel4.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N jLabel4.setText("Name"); jLabel5.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N jLabel5.setText("DOB"); jLabel6.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N jLabel6.setText("Nationality"); jLabel7.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N jLabel7.setText("Gender"); jLabel8.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N jLabel8.setText("Address"); jTextField3.setEditable(false); jTextField4.setEditable(false); jTextField5.setEditable(false); jTextField6.setEditable(false); jTextField7.setEditable(false); jLabel9.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N jLabel9.setText("Account No"); jLabel10.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N jLabel10.setText("Account Type"); jLabel11.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N jLabel11.setText("Caste"); jLabel12.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N jLabel12.setText("MOBILE"); jLabel13.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N jLabel13.setText("Security Q."); jTextField8.setEditable(false); jTextField9.setEditable(false); jTextField10.setEditable(false); jTextField11.setEditable(false); jTextField12.setEditable(false); jButton1.setIcon(new javax.swing.ImageIcon("C:\\Users\\Mohan\\Pictures\\ICONS\\rsz_1edit.jpg")); // NOI18N jButton1.setText("Edit"); jButton1.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton1ActionPerformed(evt); } }); jButton3.setIcon(new javax.swing.ImageIcon("C:\\Users\\Mohan\\Pictures\\ICONS\\rsz_save.png")); // NOI18N jButton3.setText("Save"); jButton3.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton3ActionPerformed(evt); } }); javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1); jPanel1.setLayout(jPanel1Layout); jPanel1Layout.setHorizontalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addGap(20, 20, 20) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel6) .addComponent(jLabel7) .addComponent(jLabel8)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false) .addComponent(jTextField6, javax.swing.GroupLayout.DEFAULT_SIZE, 151, Short.MAX_VALUE) .addComponent(jTextField5) .addComponent(jTextField7))) .addGroup(jPanel1Layout.createSequentialGroup() .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel4) .addComponent(jLabel5)) .addGap(46, 46, 46) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addComponent(jTextField3, javax.swing.GroupLayout.PREFERRED_SIZE, 151, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jTextField4, javax.swing.GroupLayout.PREFERRED_SIZE, 151, javax.swing.GroupLayout.PREFERRED_SIZE)))) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 43, Short.MAX_VALUE) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addGroup(jPanel1Layout.createSequentialGroup() .addComponent(jLabel9) .addGap(31, 31, 31) .addComponent(jTextField8, javax.swing.GroupLayout.PREFERRED_SIZE, 146, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(jPanel1Layout.createSequentialGroup() .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel10) .addComponent(jLabel11) .addComponent(jLabel12) .addComponent(jLabel13)) .addGap(18, 18, 18) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jTextField9) .addComponent(jTextField10) .addComponent(jTextField11) .addComponent(jTextField12))) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup() .addComponent(jButton1) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(jButton3))) .addContainerGap(54, Short.MAX_VALUE)) ); jPanel1Layout.setVerticalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addGap(31, 31, 31) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel9) .addComponent(jTextField8, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(jPanel1Layout.createSequentialGroup() .addGap(3, 3, 3) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel4) .addComponent(jTextField3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(25, 25, 25) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel5) .addComponent(jTextField4, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel10) .addComponent(jTextField9, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(28, 28, 28) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel6) .addComponent(jTextField5, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel11) .addComponent(jTextField10, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(31, 31, 31) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel7) .addComponent(jTextField6, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel12) .addComponent(jTextField11, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(28, 28, 28) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel8) .addComponent(jTextField7, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel13) .addComponent(jTextField12, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))) .addGap(18, 18, 18) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jButton3) .addComponent(jButton1)) .addContainerGap(108, Short.MAX_VALUE)) ); jTabbedPane1.addTab("Profile", jPanel1); jPanel2.setBackground(new java.awt.Color(204, 255, 204)); jPanel2.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(102, 102, 255), 2)); jLabel14.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N jLabel14.setText("Name"); jLabel15.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N jLabel15.setText("Account No."); jLabel16.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N jLabel16.setText("Available Balamce"); jLabel17.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N jLabel17.setText("Deposite Amount"); jTextField13.setEditable(false); jTextField14.setEditable(false); jTextField15.setEditable(false); jTextField17.setEditable(false); jButton4.setBackground(new java.awt.Color(255, 153, 51)); jButton4.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N jButton4.setIcon(new javax.swing.ImageIcon("C:\\Users\\Mohan\\Pictures\\ICONS\\rsz_total.jpg")); // NOI18N jButton4.setText("Total"); jButton4.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton4ActionPerformed(evt); } }); jButton5.setBackground(new java.awt.Color(51, 204, 0)); jButton5.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N jButton5.setIcon(new javax.swing.ImageIcon("C:\\Users\\Mohan\\Pictures\\ICONS\\rsz_dep.png")); // NOI18N jButton5.setText("Deposite"); jButton5.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton5ActionPerformed(evt); } }); javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2); jPanel2.setLayout(jPanel2Layout); jPanel2Layout.setHorizontalGroup( jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel2Layout.createSequentialGroup() .addGap(103, 103, 103) .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addGroup(jPanel2Layout.createSequentialGroup() .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel14) .addComponent(jLabel15) .addComponent(jLabel16) .addComponent(jLabel17)) .addGap(19, 19, 19) .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addComponent(jTextField13) .addComponent(jTextField14) .addComponent(jTextField15) .addGroup(jPanel2Layout.createSequentialGroup() .addComponent(jTextField16, javax.swing.GroupLayout.PREFERRED_SIZE, 82, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(jTextField17, javax.swing.GroupLayout.DEFAULT_SIZE, 74, Short.MAX_VALUE)))) .addComponent(jButton5)) .addGap(18, 18, 18) .addComponent(jButton4) .addContainerGap(105, Short.MAX_VALUE)) ); jPanel2Layout.setVerticalGroup( jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel2Layout.createSequentialGroup() .addGap(67, 67, 67) .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel14) .addComponent(jTextField13, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(26, 26, 26) .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel15) .addComponent(jTextField14, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(29, 29, 29) .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel16) .addComponent(jTextField15, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(29, 29, 29) .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel17) .addComponent(jTextField16, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jTextField17, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jButton4)) .addGap(27, 27, 27) .addComponent(jButton5) .addContainerGap(109, Short.MAX_VALUE)) ); jTabbedPane1.addTab("Deposite", jPanel2); jPanel3.setBackground(new java.awt.Color(255, 255, 102)); jPanel3.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 102, 102), 2)); jLabel18.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N jLabel18.setText("Name"); jLabel19.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N jLabel19.setText("Account Number"); jLabel20.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N jLabel20.setText("Available Balance"); jLabel21.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N jLabel21.setText("Transfer Amount"); jLabel22.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N jLabel22.setText("Credit Account No"); jTextField18.setEditable(false); jTextField19.setEditable(false); jTextField20.setEditable(false); jTextField22.setEditable(false); jButton6.setBackground(new java.awt.Color(255, 51, 51)); jButton6.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N jButton6.setIcon(new javax.swing.ImageIcon("C:\\Users\\Mohan\\Pictures\\ICONS\\rsz_total.jpg")); // NOI18N jButton6.setText("Remain"); jButton6.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton6ActionPerformed(evt); } }); jButton7.setBackground(new java.awt.Color(102, 102, 102)); jButton7.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N jButton7.setIcon(new javax.swing.ImageIcon("C:\\Users\\Mohan\\Pictures\\ICONS\\rsz_show.jpg")); // NOI18N jButton7.setText("Show"); jButton7.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton7ActionPerformed(evt); } }); jLabel23.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N jLabel23.setText("Credit Acc. Holder"); jTextField24.setEditable(false); jButton8.setBackground(new java.awt.Color(0, 102, 255)); jButton8.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N jButton8.setIcon(new javax.swing.ImageIcon("C:\\Users\\Mohan\\Pictures\\ICONS\\rsz_transfer.jpg")); // NOI18N jButton8.setText("Transfer"); jButton8.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton8ActionPerformed(evt); } }); jButton9.setBackground(new java.awt.Color(153, 153, 0)); jButton9.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N jButton9.setIcon(new javax.swing.ImageIcon("C:\\Users\\Mohan\\Pictures\\ICONS\\rsz_cancel.jpg")); // NOI18N jButton9.setText("Cancel"); jButton9.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton9ActionPerformed(evt); } }); javax.swing.GroupLayout jPanel3Layout = new javax.swing.GroupLayout(jPanel3); jPanel3.setLayout(jPanel3Layout); jPanel3Layout.setHorizontalGroup( jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel3Layout.createSequentialGroup() .addGap(109, 109, 109) .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel3Layout.createSequentialGroup() .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel18) .addComponent(jLabel19) .addComponent(jLabel20) .addComponent(jLabel21) .addComponent(jLabel22)) .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addGroup(jPanel3Layout.createSequentialGroup() .addGap(31, 31, 31) .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addComponent(jTextField18) .addComponent(jTextField19) .addComponent(jTextField20) .addGroup(jPanel3Layout.createSequentialGroup() .addComponent(jTextField21, javax.swing.GroupLayout.PREFERRED_SIZE, 66, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(jTextField22, javax.swing.GroupLayout.DEFAULT_SIZE, 75, Short.MAX_VALUE)))) .addGroup(jPanel3Layout.createSequentialGroup() .addGap(32, 32, 32) .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jTextField24) .addComponent(jTextField23) .addGroup(jPanel3Layout.createSequentialGroup() .addGap(21, 21, 21) .addComponent(jButton8) .addGap(0, 30, Short.MAX_VALUE)))))) .addGroup(jPanel3Layout.createSequentialGroup() .addComponent(jLabel23) .addGap(195, 195, 195))) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addComponent(jButton6) .addComponent(jButton9, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jButton7, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) .addContainerGap(92, Short.MAX_VALUE)) ); jPanel3Layout.setVerticalGroup( jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel3Layout.createSequentialGroup() .addGap(38, 38, 38) .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addComponent(jLabel18) .addComponent(jTextField18, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(33, 33, 33) .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel19) .addComponent(jTextField19, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(26, 26, 26) .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel20) .addComponent(jTextField20, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(33, 33, 33) .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel21) .addComponent(jTextField21, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jTextField22, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jButton6)) .addGap(35, 35, 35) .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel22) .addComponent(jTextField23, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(25, 25, 25) .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel23) .addComponent(jTextField24, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jButton7)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jButton8) .addComponent(jButton9)) .addContainerGap(39, Short.MAX_VALUE)) ); jTabbedPane1.addTab("Transfer", jPanel3); jPanel9.setBackground(new java.awt.Color(204, 255, 255)); jPanel9.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 204, 102), 2)); jLabel36.setIcon(new javax.swing.ImageIcon("C:\\Users\\Mohan\\Pictures\\Saved Pictures\\AAEAAQAAAAAAAAjAAAAAJDU1YmNlMTJiLWIzYjMtNDg4ZC05YjkxLWY2NjRkNjEyZGNlOQ.jpg")); // NOI18N jLabel37.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N jLabel37.setForeground(new java.awt.Color(255, 51, 51)); jLabel37.setText("FaceBook"); jLabel38.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N jLabel38.setText("- <NAME>"); jLabel39.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N jLabel39.setForeground(new java.awt.Color(255, 0, 0)); jLabel39.setText("Instagram"); jLabel40.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N jLabel40.setText("-moha9n"); javax.swing.GroupLayout jPanel9Layout = new javax.swing.GroupLayout(jPanel9); jPanel9.setLayout(jPanel9Layout); jPanel9Layout.setHorizontalGroup( jPanel9Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel9Layout.createSequentialGroup() .addGap(61, 61, 61) .addComponent(jLabel36) .addGroup(jPanel9Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel9Layout.createSequentialGroup() .addGap(100, 100, 100) .addGroup(jPanel9Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel37) .addGroup(jPanel9Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addComponent(jLabel40) .addComponent(jLabel39)))) .addGroup(jPanel9Layout.createSequentialGroup() .addGap(112, 112, 112) .addComponent(jLabel38))) .addContainerGap(120, Short.MAX_VALUE)) ); jPanel9Layout.setVerticalGroup( jPanel9Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel9Layout.createSequentialGroup() .addGroup(jPanel9Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel9Layout.createSequentialGroup() .addGap(59, 59, 59) .addComponent(jLabel36)) .addGroup(jPanel9Layout.createSequentialGroup() .addGap(79, 79, 79) .addComponent(jLabel37) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(jLabel38) .addGap(18, 18, 18) .addComponent(jLabel39) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jLabel40))) .addContainerGap(136, Short.MAX_VALUE)) ); jTabbedPane1.addTab("About", jPanel9); jButton2.setIcon(new javax.swing.ImageIcon("C:\\Users\\Mohan\\Pictures\\ICONS\\rsz_1eye.png")); // NOI18N jButton2.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton2ActionPerformed(evt); } }); jButton15.setIcon(new javax.swing.ImageIcon("C:\\Users\\Mohan\\Pictures\\ICONS\\rsz_exit.png")); // NOI18N jButton15.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton15ActionPerformed(evt); } }); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addContainerGap() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jTabbedPane1) .addGroup(layout.createSequentialGroup() .addComponent(jLabel1) .addGap(59, 59, 59) .addComponent(jButton15, javax.swing.GroupLayout.PREFERRED_SIZE, 31, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(58, 58, 58) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel2) .addComponent(jLabel3)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, 110, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jButton2, javax.swing.GroupLayout.PREFERRED_SIZE, 44, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(0, 0, Short.MAX_VALUE)) .addGroup(layout.createSequentialGroup() .addComponent(jTextField2) .addGap(3, 3, 3))))) .addContainerGap()) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGap(16, 16, 16) .addComponent(jLabel1)) .addGroup(layout.createSequentialGroup() .addGap(13, 13, 13) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jButton2, javax.swing.GroupLayout.Alignment.TRAILING) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel2) .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGap(21, 21, 21) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jTextField2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel3))) .addGroup(layout.createSequentialGroup() .addGap(1, 1, 1) .addComponent(jButton15, javax.swing.GroupLayout.PREFERRED_SIZE, 31, javax.swing.GroupLayout.PREFERRED_SIZE))))) .addGap(26, 26, 26) .addComponent(jTabbedPane1) .addContainerGap()) ); setSize(new java.awt.Dimension(645, 588)); setLocationRelativeTo(null); }// </editor-fold>//GEN-END:initComponents private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed // TODO add your handling code here: jTextField3.setEditable(true); jTextField7.setEditable(true); jTextField10.setEditable(true); jTextField11.setEditable(true); }//GEN-LAST:event_jButton1ActionPerformed private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed String sql="select * from Account where Acc=?"; try{ pst=con.prepareStatement(sql); pst.setString(1,jTextField1.getText()); rs=pst.executeQuery(); if(rs.next()) { jTextField3.setText(rs.getString("Name")); jTextField13.setText(rs.getString("Name")); jTextField18.setText(rs.getString("Name")); jTextField25.setText(rs.getString("Name")); jTextField29.setText(rs.getString("Name")); jTextField4.setText(rs.getString("DOB")); jTextField5.setText(rs.getString("Nationality")); jTextField6.setText(rs.getString("Gender")); jTextField7.setText(rs.getString("Address")); jTextField8.setText(rs.getString("Acc")); jTextField14.setText(rs.getString("Acc")); jTextField19.setText(rs.getString("Acc")); jTextField9.setText(rs.getString("Acc_Type")); jTextField10.setText(rs.getString("Caste")); jTextField11.setText(rs.getString("Mob")); jTextField12.setText(rs.getString("Sec_Q")); jTextField15.setText(rs.getString("Balance")); jTextField20.setText(rs.getString("Balance")); jTextField26.setText(rs.getString("Balance")); jTextField30.setText("12035"); jTextField32.setText("3.07%"); jTextField33.setText("Rs 0.00"); jTextField34.setText("No"); jTextField31.setText(rs.getString("Balance")); rs.close(); pst.close(); } else { JOptionPane.showMessageDialog(null,"Enter a valid account number"); } } catch(Exception e) { JOptionPane.showMessageDialog(null, e); } finally { try{ rs.close(); pst.close(); } catch(Exception e){ JOptionPane.showMessageDialog(null, e); } } // TODO add your handling code here: }//GEN-LAST:event_jButton2ActionPerformed private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton3ActionPerformed try{ String v=jTextField1.getText(); String v1=jTextField3.getText(); String v2=jTextField7.getText(); String v3=jTextField10.getText(); String v4=jTextField11.getText(); String sql1="update Balances set Name='"+v1+"' where Acc='"+v+"'"; String sql="update Account set Address='"+v2+"',Name='"+v1+"',Caste='"+v3+"',Mob='"+v4+"' where Acc='"+v+"'"; pst=con.prepareStatement(sql); PreparedStatement pst1=con.prepareStatement(sql1); pst.execute(); pst1.execute(); JOptionPane.showMessageDialog(null,"Profile has been updated successfully"); } catch(Exception e){ JOptionPane.showMessageDialog(null,e); } // TODO add your handling code here: }//GEN-LAST:event_jButton3ActionPerformed private void jButton4ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton4ActionPerformed try{ String a=jTextField15.getText(); String b=jTextField16.getText(); int sum=Integer.parseInt(a)+Integer.parseInt(b); String c=String.valueOf(sum); jTextField17.setText(c); } catch(Exception e){ JOptionPane.showMessageDialog(null, e); } // TODO add your handling code here: }//GEN-LAST:event_jButton4ActionPerformed private void jButton5ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton5ActionPerformed String v=jTextField1.getText(); String sql="update Balances set Balance=? where Acc='"+v+"'"; String sql1="update Account set Balance=? where Acc='"+v+"'"; try{ pst=con.prepareStatement(sql); pst.setString(1,jTextField17.getText()); PreparedStatement pst1=con.prepareStatement(sql1); pst1.setString(1,jTextField17.getText()); pst.execute(); pst1.execute(); pst.close(); pst1.close(); JOptionPane.showMessageDialog(null,"Requsested amount deposited sucessfully"); jTextField13.setText(""); jTextField14.setText(""); jTextField15.setText(""); jTextField16.setText(""); jTextField17.setText(""); } catch(Exception e) { JOptionPane.showMessageDialog(null, e); } // TODO add your handling code here: }//GEN-LAST:event_jButton5ActionPerformed private void jButton6ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton6ActionPerformed try{ String a=jTextField20.getText(); String b=jTextField21.getText(); int sum=Integer.parseInt(a)-Integer.parseInt(b); if(sum<100) { JOptionPane.showMessageDialog(null,"Your account balance can't be debited below 100"); jTextField21.setText(""); } else { String c=String.valueOf(sum); jTextField22.setText(c); } } catch(Exception e){ JOptionPane.showMessageDialog(null, e); } // TODO add your handling code here: }//GEN-LAST:event_jButton6ActionPerformed private void jButton9ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton9ActionPerformed jTextField23.setText(""); jTextField24.setText(""); // TODO add your handling code here: }//GEN-LAST:event_jButton9ActionPerformed private void jButton7ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton7ActionPerformed String x=jTextField23.getText(); String sql="Select * from Balances where Acc='"+x+"'"; try{ pst=con.prepareStatement(sql); rs=pst.executeQuery(); if(rs.next()) { jTextField24.setText(rs.getString(1)); } else { JOptionPane.showMessageDialog(null,"Enter a valid Account number"); } rs.close(); pst.close(); } catch(Exception e) { JOptionPane.showMessageDialog(null, e); } finally { try{ rs.close(); pst.close(); } catch(Exception e) { JOptionPane.showMessageDialog(null, e); } } // TODO add your handling code here: }//GEN-LAST:event_jButton7ActionPerformed public static String cal(String x,String y) { int sum=Integer.parseInt(x)+Integer.parseInt(y); String z=String.valueOf(sum); return z; } private void jButton8ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton8ActionPerformed String sql="update Account set Balance=? where Acc=?"; String sql1="update Balances set Balance=? where Acc=?"; String sql2="select Balance from Balances where Acc=?"; String sql3="update Account set Balance=? where Acc=?"; String sq="update Balances set Balance=? where Acc=?"; String ss="insert into Tra(Acc_No,Name,Transfer_Amount,Recieve_Amount,Date,Time,Acc) values(?,?,?,?,?,?,?)"; String s="insert into Tra(Acc_No,Name,Transfer_Amount,Recieve_Amount,Date,Time,Acc) values(?,?,?,?,?,?,?)"; try{ pst=con.prepareStatement(sql); PreparedStatement pst1=con.prepareStatement(sql1); PreparedStatement pst2=con.prepareStatement(sql2); PreparedStatement pst3=con.prepareStatement(sql3); PreparedStatement pst4=con.prepareStatement(sq); PreparedStatement pst5=con.prepareStatement(ss); PreparedStatement pst6=con.prepareStatement(s); pst.setString(2,jTextField1.getText()); pst.setString(1,jTextField22.getText()); DateFormat dateFormat = new SimpleDateFormat("hh:mm a"); LocalTime l = LocalTime.now(); pst1.setString(2,jTextField1.getText()); pst1.setString(1,jTextField22.getText()); pst5.setString(1,jTextField23.getText()); pst5.setString(2,jTextField24.getText()); pst5.setString(5,jTextField2.getText()); pst5.setString(3,jTextField21.getText()); pst5.setString(7,jTextField1.getText()); pst5.setString(6,l.toString()); pst5.setString(4,""); pst6.setString(1,jTextField1.getText()); pst6.setString(2,jTextField18.getText()); pst6.setString(5,jTextField2.getText()); pst6.setString(4,jTextField21.getText()); pst6.setString(7,jTextField23.getText()); pst6.setString(6,l.toString()); pst6.setString(3,""); pst.execute(); pst1.execute(); pst5.execute(); pst6.execute(); pst2.setString(1,jTextField23.getText()); rs=pst2.executeQuery(); if(rs.next()) { String x=rs.getString(1); String m= MyPage.cal(x,jTextField21.getText()); pst3.setString(2,jTextField23.getText()); pst3.setString(1,m); pst4.setString(2,jTextField23.getText()); pst4.setString(1,m); pst3.execute(); pst4.execute(); rs.close(); pst.close(); pst1.close(); pst2.close(); pst3.close(); pst4.close(); JOptionPane.showMessageDialog(null,"Transfer Succcessful"); } Table1(); } catch(Exception e) { JOptionPane.showMessageDialog(null, e); } // TODO add your handling code here: }//GEN-LAST:event_jButton8ActionPerformed private void jButton10ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton10ActionPerformed String x=jTextField26.getText(); String y=jTextField27.getText(); int rem=Integer.parseInt(x)-Integer.parseInt(y); if(rem<100) { JOptionPane.showMessageDialog(null,"Account Balnce must not have less than 100"); jTextField27.setText(""); } else { jTextField28.setText(String.valueOf(rem)); } // TODO add your handling code here: }//GEN-LAST:event_jButton10ActionPerformed private void jButton11ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton11ActionPerformed String x=jTextField1.getText(); String sql="Update Account set Balance=? where Acc='"+x+"'"; String sql1="Update Balances set Balance=? where Acc='"+x+"'"; try{ pst=con.prepareStatement(sql); PreparedStatement pst1=con.prepareStatement(sql1); pst.setString(1,jTextField28.getText()); pst1.setString(1,jTextField28.getText()); pst.execute(); pst1.execute(); pst.close(); pst1.close(); JOptionPane.showMessageDialog(null,"Collect Your Cash..Visit Again"); } catch(Exception e) { JOptionPane.showMessageDialog(null, e); } }//GEN-LAST:event_jButton11ActionPerformed private void jButton13ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton13ActionPerformed jPasswordField1.setText(""); jTextField36.setText(""); jPasswordField1.setEchoChar('*'); }//GEN-LAST:event_jButton13ActionPerformed private void jButton12ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton12ActionPerformed String sql="update Account set Pin=? where Pin=?"; try{ pst=con.prepareStatement(sql); pst.setString(1,jTextField36.getText()); pst.setString(2,jPasswordField1.getText()); int s=pst.executeUpdate(); if(s>0) { JOptionPane.showMessageDialog(null,"PIN changed Successfully"); jPasswordField1.setEchoChar('*'); } else { JOptionPane.showMessageDialog(null,"Enter your Old pin correctly"); jPasswordField1.setText(""); jTextField36.setText(""); jPasswordField1.setEchoChar('*'); } jTextField36.setText(""); jPasswordField1.setText(""); } catch(Exception e){ JOptionPane.showMessageDialog(null, e); } }//GEN-LAST:event_jButton12ActionPerformed private void jButton14ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton14ActionPerformed jPasswordField1.setEchoChar((char)0); }//GEN-LAST:event_jButton14ActionPerformed private void jButton15ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton15ActionPerformed JDialog.setDefaultLookAndFeelDecorated(true); int response = JOptionPane.showConfirmDialog(null, "Do you want to Signout?", "Confirm", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE); if (response == JOptionPane.YES_OPTION) { setVisible(false); Authentication ob=new Authentication(); ob.setVisible(true); } // TODO add your handling code here: }//GEN-LAST:event_jButton15ActionPerformed /** * @param args the command line arguments */ public static void main(String args[]) { /* Set the Nimbus look and feel */ //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) "> /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel. * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html */ try { for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { if ("Nimbus".equals(info.getName())) { javax.swing.UIManager.setLookAndFeel(info.getClassName()); break; } } } catch (ClassNotFoundException ex) { java.util.logging.Logger.getLogger(MyPage.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(MyPage.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(MyPage.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(MyPage.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } //</editor-fold> /* Create and display the form */ java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new MyPage().setVisible(true); } }); } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton jButton1; private javax.swing.JButton jButton10; private javax.swing.JButton jButton11; private javax.swing.JButton jButton12; private javax.swing.JButton jButton13; private javax.swing.JButton jButton14; private javax.swing.JButton jButton15; private javax.swing.JButton jButton2; private javax.swing.JButton jButton3; private javax.swing.JButton jButton4; private javax.swing.JButton jButton5; private javax.swing.JButton jButton6; private javax.swing.JButton jButton7; private javax.swing.JButton jButton8; private javax.swing.JButton jButton9; private javax.swing.JLabel jLabel1; private javax.swing.JLabel jLabel10; private javax.swing.JLabel jLabel11; private javax.swing.JLabel jLabel12; private javax.swing.JLabel jLabel13; private javax.swing.JLabel jLabel14; private javax.swing.JLabel jLabel15; private javax.swing.JLabel jLabel16; private javax.swing.JLabel jLabel17; private javax.swing.JLabel jLabel18; private javax.swing.JLabel jLabel19; private javax.swing.JLabel jLabel2; private javax.swing.JLabel jLabel20; private javax.swing.JLabel jLabel21; private javax.swing.JLabel jLabel22; private javax.swing.JLabel jLabel23; private javax.swing.JLabel jLabel24; private javax.swing.JLabel jLabel25; private javax.swing.JLabel jLabel26; private javax.swing.JLabel jLabel27; private javax.swing.JLabel jLabel28; private javax.swing.JLabel jLabel29; private javax.swing.JLabel jLabel3; private javax.swing.JLabel jLabel30; private javax.swing.JLabel jLabel31; private javax.swing.JLabel jLabel32; private javax.swing.JLabel jLabel33; private javax.swing.JLabel jLabel34; private javax.swing.JLabel jLabel35; private javax.swing.JLabel jLabel36; private javax.swing.JLabel jLabel37; private javax.swing.JLabel jLabel38; private javax.swing.JLabel jLabel39; private javax.swing.JLabel jLabel4; private javax.swing.JLabel jLabel40; private javax.swing.JLabel jLabel5; private javax.swing.JLabel jLabel6; private javax.swing.JLabel jLabel7; private javax.swing.JLabel jLabel8; private javax.swing.JLabel jLabel9; private javax.swing.JPanel jPanel1; private javax.swing.JPanel jPanel2; private javax.swing.JPanel jPanel3; private javax.swing.JPanel jPanel4; private javax.swing.JPanel jPanel5; private javax.swing.JPanel jPanel6; private javax.swing.JPanel jPanel7; private javax.swing.JPanel jPanel8; private javax.swing.JPanel jPanel9; private javax.swing.JPasswordField jPasswordField1; private javax.swing.JScrollPane jScrollPane1; private javax.swing.JScrollPane jScrollPane2; private javax.swing.JTabbedPane jTabbedPane1; private javax.swing.JTable jTable1; private javax.swing.JTable jTable2; private javax.swing.JTextField jTextField1; private javax.swing.JTextField jTextField10; private javax.swing.JTextField jTextField11; private javax.swing.JTextField jTextField12; private javax.swing.JTextField jTextField13; private javax.swing.JTextField jTextField14; private javax.swing.JTextField jTextField15; private javax.swing.JTextField jTextField16; private javax.swing.JTextField jTextField17; private javax.swing.JTextField jTextField18; private javax.swing.JTextField jTextField19; private javax.swing.JTextField jTextField2; private javax.swing.JTextField jTextField20; private javax.swing.JTextField jTextField21; private javax.swing.JTextField jTextField22; private javax.swing.JTextField jTextField23; private javax.swing.JTextField jTextField24; private javax.swing.JTextField jTextField25; private javax.swing.JTextField jTextField26; private javax.swing.JTextField jTextField27; private javax.swing.JTextField jTextField28; private javax.swing.JTextField jTextField29; private javax.swing.JTextField jTextField3; private javax.swing.JTextField jTextField30; private javax.swing.JTextField jTextField31; private javax.swing.JTextField jTextField32; private javax.swing.JTextField jTextField33; private javax.swing.JTextField jTextField34; private javax.swing.JTextField jTextField36; private javax.swing.JTextField jTextField4; private javax.swing.JTextField jTextField5; private javax.swing.JTextField jTextField6; private javax.swing.JTextField jTextField7; private javax.swing.JTextField jTextField8; private javax.swing.JTextField jTextField9; // End of variables declaration//GEN-END:variables } <file_sep>compile.on.save=true file.reference.sqlitejdbc-v056.jar=C:\\Users\\Mohan\\Downloads\\Adv Java\\J2EE-FINAL(64x)\\JAR\\sqlitejdbc-v056.jar\\sqlitejdbc-v056.jar user.properties.file=C:\\Users\\Mohan\\AppData\\Roaming\\NetBeans\\8.0.1\\build.properties
630af52b0525f1ad827acba057c1df69346e2b7b
[ "Markdown", "Java", "INI" ]
6
Java
mo223han/Serevelet_pro
378b6430c8d846a6a14384a3bd1f1503a161e522
24dc5ef5f43cc99b1b53a5edd9d1ef96c19d8a90
refs/heads/master
<file_sep># Zookeeper A simple distributed bank management system which uses Zookeeper to ensure consistency, availability and fault tolerance. ## Aim The aim of this project is to create a simple distributed bank system made of application servers connected to a Zookeeper ensemble (or standalone if locally). Client requests (in this case STDIN commands) can be sent to any application server. In case the request is sent to the leader elected amongst the application servers, the request is processed by that server and forwarded to all the other applications servers. In case of a request sent to a non-leader application server, however, there are 2 cases: *_read_* requests are processed by the application server itself; *_create_*, *_update_* and *_delete_* requests are forwarded to the application server leader, which processes it and, when terminated, forwards them to all the other application servers. ## Dependencies This project depends on 3 libraries: 1. [zookeeper-3.4.10](https://repo1.maven.org/maven2/org/apache/zookeeper/zookeeper/3.4.10/zookeeper-3.4.10.jar) 2. [slf4j-simple](https://mvnrepository.com/artifact/org.slf4j/slf4j-simple/1.7.25) 3. [slf4j-api](https://mvnrepository.com/artifact/org.slf4j/slf4j-api/1.7.25) These dependecies can be downloaded and imported manually into the project (e.g. for development). ## Zookeeper Ensemble To enable the functionalities provided by the application servers, a Zookeeper Ensemble (or Standalone if in localhost) need to be started. For the standalone version we only need to start the Zookeeper server, which can be achieved running the zkServer.sh script which can be found inside the uncompressed jar, under the /bin folder (/zookeeper-3.4.10/bin/zkServer.sh). The standalone will use the default configuration file (/zookeeper-3.4.10/conf/zoo.cfg). To achieve the same result for an Ensemble, create different configurations file and edit the *clientPort* attribute. The ensemble also provides a CLI (/zookeeper-3.4.10/bin/zkCli.sh) which can be used to manage the Zookeeper structure (see Znodes, read data, delete nodes, etc.). ## Application Servers The application servers are really simple Java applications. The database is made of a HashMap data structures, which stores information abour customers (account id, owner and current balance). The set of operations provided by the application are the standard CRUD (Creata, Read, Update, Delete). The application can be run from the command line, providing a basic UI which allows to execute the above-mentioned operations. ## Communication Communications never happen directly between application servers. Each of the application server is connected to a Zookeper ensemble which functions like a service bus. ![Zookeeper Ensemble](images/znodes.png?raw=true) In the above image it can be seen the structure of the Zookeeper ensemble. Under the root node "/" (1) several nodes are created (2): an election node, a members node and an operation node. All of these nodes are PERSISTENT, meaning that they are not associated with the current session and, therefore, are never deleted. #### Election Node The Election node is used to register all the application servers which are part of the cluster. Everytime a new application server is started, an EPHEMERAL_SEQUENTIAL (3) node is created under the root election node (/election). This mechanism enable to perform operations such as Leader election amongst all the nodes. The algorithm used for choosing the leader amongst all the application servers is very simple: the node with the lowest id will be elected as leader. #### Members Node The Members node is used to enforce Fault Detection. As previously described for the Election Node, everytime that an application server joins the cluster, an EPHEMERAL_SEQUENTIAL (3) node is created under the members node (/members). Everytime that a new member joins the Members node, a watch that check its existance is set. This watch will be triggered if/when the node goes down (either crashed, or gets stopped). The watcher process is responsible for starting a new application server, thus ensuring fault detection and automatic recovery. #### Operations Node The Operations node is used to enforce the consistency of the cluster. As above, everytime that an application server joins the cluster, a PERSISTENT_SEQUENTIAL (3) node is created under the operations node (/operation). This node is set to be PERSISTENT because numerous sub-nodes (4) will be created under each application server operation's node, one for each operation to be executed. To achieve consistency, in fact, all the application servers need to execute the same set of operations. The strategy for ensuring consistency is as follow: 1. Read operations: when a read operation is sent to any node (being it a leader node or a simple node), it is processed by the node itself; 2. Write operations: when a write operation is received by an application server, we distinguish two cases: 1. the operation is received by the leader: the application server executes it and forwards it to all the other nodes; 2. the operation is received by a non leader node: the operation is forwarded from this node to the leader, which will execute it and, then, forward it to all the other nodes. N.B.: Even though the /members and /elections znodes could be merged into a single node, for the purpose of this assignment and for the separation of concerns (=easier understanding of what's going on under the hood), I preferred to keep them separated. ## Conclusions The aim of this assignment was not to develop a complex application, but rather to enforce consistency, availability and fault-tolerance amongst all the applications of a cluster. For this purpose, Zookeper came in hand providing a mean for these operations. Znodes and watches, in fact, enabled to achieve the above-mentioned goals in a straightforward way, simply by waiting for changes in the Zookeeper Ensemble Znodes structure. <file_sep>package es.upm.dit.dscc.actreplica.watchers; import es.upm.dit.dscc.actreplica.Bank; import es.upm.dit.dscc.actreplica.node_managers.ElectionManager; import org.apache.zookeeper.KeeperException; import org.apache.zookeeper.WatchedEvent; import org.apache.zookeeper.Watcher; /** * A watcher class for the /election znode. * This watcher is triggered when the leader node fails * or exits. A new election is then triggered. */ public class ElectionWatcher implements Watcher { private ElectionManager electionManager; public ElectionWatcher(ElectionManager electionManager){ this.electionManager = electionManager; } @Override public void process(WatchedEvent event) { try { electionManager.leaderElection(); } catch (KeeperException | InterruptedException e) { e.printStackTrace(); } } } <file_sep>package es.upm.dit.dscc.actreplica.watchers; import es.upm.dit.dscc.actreplica.Bank; import es.upm.dit.dscc.actreplica.OperationBank; import es.upm.dit.dscc.actreplica.OperationEnum; import es.upm.dit.dscc.actreplica.node_managers.ElectionManager; import es.upm.dit.dscc.actreplica.node_managers.OperationsManager; import org.apache.zookeeper.KeeperException; import org.apache.zookeeper.WatchedEvent; import org.apache.zookeeper.Watcher; import org.apache.zookeeper.ZooKeeper; import org.apache.zookeeper.data.Stat; import java.io.IOException; import java.util.Iterator; import java.util.List; /** * Created by Stefano on 20/01/2018. */ public class OperationsWatcher implements Watcher { private ZooKeeper zk; private Bank bank; private String nodename; public OperationsWatcher(ZooKeeper zk, String nodename, Bank bankInstance){ this.zk = zk; this.bank = bankInstance; this.nodename = nodename; } @Override public void process(WatchedEvent event) { if (event.getPath().equals(this.nodename)) { List<String> operations = null; try { operations = zk.getChildren(this.nodename, false); } catch (KeeperException | InterruptedException e) { e.printStackTrace(); } System.out.println("Operations: " + operations); for (String operation_id : operations) { String nodePath = this.nodename + "/" + operation_id; byte[] data = null; try { data = zk.getData(nodePath, false, null); Stat stat = zk.exists(nodePath, false); zk.delete(nodePath, stat.getVersion()); } catch (KeeperException | InterruptedException e) { e.printStackTrace(); } finally { OperationBank operation = null; try { operation = OperationBank.byteToObj(data); } catch (IOException | ClassNotFoundException e) { e.printStackTrace(); } bank.handleReceiverMsg(operation); if (this.bank.getIsLeader()) this.bank.sendMessages.forwardOperationToFollowers(operation); } } } try { zk.getChildren(this.nodename, this); } catch (KeeperException | InterruptedException e) { e.printStackTrace(); } } }
fa5c6af47578dad712dd1b465efb792b462dc758
[ "Markdown", "Java" ]
3
Markdown
stefanomunarini/Zookeeper
e9e3890afa7e692eca2ac10ab882c7b70ff3481e
76e3653f7040199a2ec2b8f0730409359cdd92b4
refs/heads/master
<repo_name>playr1983g/excel-templating<file_sep>/Classes/ExcelTemplatingInterface.php <?php namespace Devpunk\ExcelTemplating\Classes; interface ExcelTemplatingInterface { public function render(\SplFileInfo $file, array $data); } <file_sep>/Classes/CellFinderInterface.php <?php namespace Devpunk\ExcelTemplating\Classes; interface CellFinderInterface { public function findByKey($key); } <file_sep>/Classes/CellCreatorInterface.php <?php namespace Devpunk\ExcelTemplating\Classes; interface CellCreatorInterface { public function create($cell, CellOffsetInterface $offset); }<file_sep>/Classes/CellOffsetInterface.php <?php namespace Devpunk\ExcelTemplating\Classes; interface CellOffsetInterface { public function getXOffset(); public function getYOffset(); } <file_sep>/Classes/CoordinateInterface.php <?php namespace Devpunk\ExcelTemplating\Classes; interface CoordinateInterface { public function getX(); public function getY(); /** * @param $baseCellCoordinate * @return CoordinateInterface */ public function diff($baseCellCoordinate); } <file_sep>/Classes/TableInterface.php <?php namespace Devpunk\ExcelTemplating\Classes; interface TableInterface { /** * @param $regex * @return CellInterface[] */ public function findCellsByRegex($regex); /** * @param CoordinateInterface $coordinates * @return CellInterface */ public function getCell(CoordinateInterface $coordinates); public function insertRowBefore(CoordinateInterface $coordinates); public function insertRowAfter(CoordinateInterface $coordinates); public function insertColumnBefore(CoordinateInterface $coordinates); public function insertColumnAfter(CoordinateInterface $coordinates); }<file_sep>/Classes/TableOffsetReaderInterface.php <?php namespace Devpunk\ExcelTemplating\Classes; interface TableOffsetReaderInterface { public function read(TableInterface $table); } <file_sep>/Classes/CellMapperInterface.php <?php namespace Devpunk\ExcelTemplating\Classes; interface CellMapperInterface { public function setValue($value, $index = null); } <file_sep>/Classes/TableOffsetReader.php <?php namespace Devpunk\ExcelTemplating\Classes; class TableOffsetReader implements TableOffsetReaderInterface { const DELIMITER = ":"; const ARRAY_SYMBOL = "#"; public function read(TableInterface $table) { $cells = $table->findCellsByRegex($templateCellsRegex); $pathedCells = $this->sortSiblings($cells, $cells); } /** * @param CellInterface[] $cells * @return CellInterface[][] */ private function sortSiblings(array $cells) { $pathedCells = []; foreach ($cells as $cell) { $value = $cell->getValue(); $parts = explode(self::DELIMITER, $value); foreach ($parts as $part) { if (!isset($pathedCells[$part])) { $pathedCells[$part] = []; } $pathedCells &= $pathedCells[$part]; } $pathedCells[] = $cell; } return $pathedCells; } /** * @param array $left * @param array $right * @param CoordinateInterface[] $offsets */ private function calculateOffsets($left, $right, array $offsets) { if ($left instanceof CellInterface) { // match } /** @var CellInterface $currentLeftFromRightSide */ $currentLeftFromRightSide = $this->getOuterCell($right, 0); $currentLeftFromLeftSide = $this->getOuterCell($left, 0); $coordinateLeftFromRightSide = $currentLeftFromRightSide->getCoordinate(); $coordinateLeftFromLeftSide = $currentLeftFromLeftSide->getCoordinate(); $offsetCoordinate = $coordinateLeftFromRightSide->diff($coordinateLeftFromLeftSide); array_push($offsets, $offsetCoordinate); if (isset($left[0]) && isset($left[1])) { $this->calculateOffsets($left[0], $left[1], $offsets); return; } //calculate assoc too $this->calculateOffsets(reset($left), reset($right), $offsets); } private function getOuterCell(array $cells, $index = 0) { /** @var CellInterface|array $currentOuterCell */ $currentOuterCell = $cells; while (is_array($currentOuterCell)) { if (isset($currentOuterCell[$index])) { $currentOuterCell = $currentOuterCell[$index]; continue; } $currentOuterCell = reset($currentOuterCell); } return $currentOuterCell; } }<file_sep>/Classes/CellInterface.php <?php namespace Devpunk\ExcelTemplating\Classes; interface CellInterface { /** * @param $value * @return $this */ public function setValue($value); /** * @return mixed */ public function getValue(); /** * @return CoordinateInterface */ public function getCoordinate(); /** * @return TableInterface */ public function getTable(); } <file_sep>/spec/Devpunk/ExcelTemplating/Classes/ExcelTemplatingSpec.php <?php namespace spec\Devpunk\ExcelTemplating\Classes; use PhpSpec\ObjectBehavior; use Prophecy\Argument; class ExcelTemplatingSpec extends ObjectBehavior { function it_is_initializable() { $this->shouldHaveType('Devpunk\ExcelTemplating\Classes\ExcelTemplating'); $this->shouldHaveType('Devpunk\ExcelTemplating\Classes\ExcelTemplatingInterface'); } function it_is_cool() { $this->shouldHaveType('Devpunk\ExcelTemplating\Classes\ExcelTemplating'); } } <file_sep>/Classes/ExcelTemplating.php <?php namespace Devpunk\ExcelTemplating\Classes; /** * Class ExcelTemplating * */ class ExcelTemplating implements ExcelTemplatingInterface { public function render(\SplFileInfo $file, array $data) { foreach ($data as $key => $d) { } } }<file_sep>/Classes/CellTraverserInterface.php <?php namespace Devpunk\ExcelTemplating\Classes; interface CellTraverserInterface { public function getNextCell($cell, CellOffsetInterface $cellOffset); public function getPreviousCell($cell, CellOffsetInterface $cellOffset); }<file_sep>/Classes/TableWriterInterface.php <?php namespace Devpunk\ExcelTemplating\Classes; interface TableWriterInterface { public function write(TableInterface $table, array $data); }
51326d528ba0afddafad214f7a03a0d16294686a
[ "PHP" ]
14
PHP
playr1983g/excel-templating
ee90b5346f849889ce1b3ca23380fde2065a7a48
4240ded90502272f8a8ad6588543aa4c6ba3ee22
refs/heads/master
<file_sep>import React from "react"; import { connect } from "react-redux" //Components import { Footer } from "../components/Footer"; import Content from "../components/Content"; import NavBar from "../components/NavBar"; import LogIn from "../components/Login"; //Actions import { setName } from "../actions/userActions"; import { setSection } from "../actions/sectionActions"; import { setType } from "../actions/logInActions"; import { setSubcontent } from "../actions/sectionActions"; class App extends React.Component { render() { switch (this.props.logInReducer.typeUser) { case "Administrator": if (this.props.sectionReducer.subcontent == "updateApplicant") { //crear objeto usando el applicantReducer para despues enviarlo como prop applicantData return ( <div id="admin" className="container-flow" style={{ display: "none" }}> <NavBar onClick={this.props.setSection} section={this.props.sectionReducer.actualSection} /> <Content sectionType={this.props.sectionReducer.actualSection} subcontentType={this.props.sectionReducer.subcontent} //applicantData={} /> <Footer /> </div> ); } else { return ( <div id="admin" className="container-flow" style={{ display: "none" }}> <NavBar onClick={this.props.setSection} section={this.props.sectionReducer.actualSection} /> <Content sectionType={this.props.sectionReducer.actualSection} subcontentType={this.props.sectionReducer.subcontent} /> <Footer /> </div> ); } break; case "NormalUser": return ( <div id="admin" className="container-flow" style={{ display: "none" }}> <NavBar onClick={this.props.setSection} section={this.props.sectionReducer.actualSection} /> <Content sectionType={this.props.sectionReducer.actualSection} subcontentType={this.props.sectionReducer.subcontent} /> <Footer /> </div> ); break; default: return ( <div className="container-flow"> <LogIn setType={this.props.setType} /> </div> ); break; } } componentDidUpdate() { $("#admin").slideDown("slow"); } } // <Main changerUsername={() => this.props.setName("Anna")}/> // User username={this.props.user.name}/> // <NavBar onClick={this.props.setSection} section={this.props.sectionReducer.actualSection}/> //<Content sectionType={this.props.sectionReducer.actualSection}/> //<Footer/> const mapStateToProps = (state) => { return { sectionReducer: state.sectionReducer, logInReducer: state.logInReducer, }; }; const mapDispatchToProps = (dispatch) => { return { setName: (name) => { dispatch(setName(name)); }, setAge: (age) => { dispatch(setAge(age)); }, setSection: (section,subcontent) => { dispatch(setSection(section)); dispatch(setSubcontent(subcontent)); }, setType: (type, name) => { dispatch(setType(type, name)); }, }; }; export default connect(mapStateToProps, mapDispatchToProps)(App); <file_sep>import React from 'react'; export const ClerkForm = (props) => { return ( <div> <div className="form-group"> <label for="department">Departamento:</label> <input type="text" className="form-control input-sm" id="department" name="department"/> </div> <div className="form-group"> <label for="position">Posicion:</label> <input type="text" className="form-control input-sm" id="position" name="position"/> </div> </div> ); }<file_sep> const logInReducer = (state = { typeUser : "none", name : "" }, action) => { switch (action.type) { case "SET_TYPE": console.log(action.payload); switch (action.payload.typeUser) { case "Administrator": state = { typeUser: action.payload.typeUser, name : "" } break; case "NormalUser": state = { typeUser: action.payload.typeUser, name: action.payload.name } break; default: break; } break; default: break; } return state; } export default logInReducer;<file_sep>const initState = { model : '', brand : '', category: '', barcode :'', stateID:'' }; const equipmentReducer = (state = initState, action) => { switch (action.type) { case "SET_EQUIPMENT_INFO": state = { ...state, model : action.payload.model, brand : action.payload.brand, category : action.payload.category, barcode : action.payload.barcode, stateID : action.payload.state } break; default: break; } return state; }; export default equipmentReducer;<file_sep>import React from "react"; import "../styles/SubMenu.css"; import { connect } from "react-redux"; import Table from "../components/Table" import { Button } from "./Button"; import ApplicantForm from "../containers/ApplicantForm"; import {setSubcontent} from "../actions/sectionActions"; class SubMenu extends React.Component{ render(){ let type = this.props.subMenuType; let subMenuHTML; switch (type) { case "Prestamos": subMenuHTML = ( <div className="row"> <div className="row"> </div> <div className="col-xs-12 col-md-offset-2"> <Button buttonType={"Prestar"} clicked={this.props.setSubcontent}/> <Button buttonType={"Renovar"} clicked={this.props.setSubcontent}/> <Button buttonType={"Devolver"} clicked={this.props.setSubcontent}/> </div> </div> ); break; case "Solicitantes": subMenuHTML = ( <div className="row"> <div className="row"> </div> <div className="col-xs-12 col-md-offset-2"> <Button buttonType={"añadirSolicitante"} clicked={this.props.setSubcontent}/> <Button buttonType={"listarSolicitante"} clicked={this.props.setSubcontent}/> <Button buttonType={"Moroso"} clicked={this.props.setSubcontent}/> </div> </div> ); break; case "Audiovisuales": subMenuHTML = ( <div className="row"> <div className="col-xs-12 col-md-offset-2"> <Button buttonType={"añadirAudio"} clicked={this.props.setSubcontent} /> <Button buttonType={"listaAudio"} clicked={this.props.setSubcontent} /> </div> </div> ); break; case "Historial": subMenuHTML = ( <div className="row"> <div className="col-xs-12 col-md-offset-2"> </div> </div> ); break; case "Estadisticas": subMenuHTML = ( <div className="row"> <div className="col-xs-12 col-md-offset-2"> </div> </div> ); break; default: break; } return( <div> {subMenuHTML} </div> ) } } const mapStateToProps = (state) => { return { sectionReducer: state.sectionReducer }; }; const mapDispatchToProps = (dispatch) => { return { setSubcontent: (type) => { dispatch(setSubcontent(type)); } }; }; export default connect(mapStateToProps, mapDispatchToProps)(SubMenu);<file_sep>import React from 'react'; import "../styles/Form.css"; import { Input, InputElement, SelectElement ,InputChangedHandler} from "../components/FormsUI/Input"; import axios from 'axios' class LoanForm extends React.Component { constructor(props) { super(); this.selectOptions = [ {value:'00:00', displayValue: '00:00'}, {value:'01:00', displayValue: '01:00'}, {value:'02:00', displayValue: '02:00'}, {value:'03:00', displayValue: '03:00'}, {value:'04:00', displayValue: '04:00'}, {value:'05:00', displayValue: '05:00'}, {value:'06:00', displayValue: '06:00'}, {value:'07:00', displayValue: '07:00'}, {value:'07:30', displayValue: '07:30'}, {value:'08:00', displayValue: '08:00'}, {value:'08:30', displayValue: '08:30'}, {value:'09:00', displayValue: '09:00'}, {value:'09:30', displayValue: '9:30'}, {value:'10:00', displayValue: '10:00'}, {value:'10:30', displayValue: '10:30'}, {value:'11:00', displayValue: '11:00'}, {value:'11:30', displayValue: '11:30'}, {value:'12:00', displayValue: '12:00'}, {value:'12:30', displayValue: '12:30'}, {value:'13:00', displayValue: '13:00'}, {value:'13:30', displayValue: '13:30'}, {value:'14:00', displayValue: '14:00'}, {value:'14:30', displayValue: '14:30'}, {value:'15:00', displayValue: '15:00'}, {value:'15:30', displayValue: '15:30'}, {value:'16:00', displayValue: '16:00'}, {value:'16:30', displayValue: '16:30'}, {value:'17:00', displayValue: '17:00'}, {value:'17:30', displayValue: '17:30'}, {value:'18:00', displayValue: '18:00'}, {value:'18:30', displayValue: '18:30'}, {value:'19:00', displayValue: '19:00'}, {value:'19:30', displayValue: '19:30'}, {value:'20:00', displayValue: '20:00'}, {value:'20:30', displayValue: '20:30'}, {value:'21:00', displayValue: '21:00'}, {value:'21:30', displayValue: '21:30'}, {value:'22:00', displayValue: '22:00'}, {value:'23:00', displayValue: '23:00'}, {value:'24:00', displayValue: '24:00'}, ] this.state = { form: { barcode: InputElement('text', 'Barcode', '', "barcode","Codigo de Barras"), peopleLicenseOrId: InputElement('text', 'Carnet/Cedula', '', 'peopleLicenseOrId', 'Carnet'), endDate: SelectElement(this.selectOptions, '', "finishDate",'Fecha Devolucion'), } }; } onSubmitHandler = (event) => { event.preventDefault(); const formData = {}; for (let formElementIdentifier in this.state.form) { formData[formElementIdentifier] = this.state.form[formElementIdentifier].value; } switch (this.props.function) { case 'CREATE': axios.post('http://localhost:8080/loans/loan', formData) .then(response => { alert('Prestamo Creado' + response); }); break; case 'EDIT': axios.put('http://localhost:8080/loans/renew/', formData) .then(response => { alert('prestamo Renovado' + response); }); break; case 'RETURN': axios.put('http://localhost:8080/loans/return/', formData) .then(response => { alert('prestamo Devuelto' + response); }); break; } } formTypeHandler = () =>{ switch(this.props.function){ case "CREATE": this.setState({form: { barcode: InputElement('text', 'Barcode', '', "barcode","Codigo de Barras"), peopleLicenseOrId: InputElement('text', 'Carnet/Cedula', '', 'peopleLicenseOrId', 'Carnet'), endDate: InputElement('date','fecha', '', "endDate",'Fecha Devolucion'), }}); break; case "EDIT": this.setState({form: { barcode: InputElement('text', 'Barcode', '', "barcode","Codigo de Barras"), endDate: SelectElement(this.selectOptions, '', "finishDate",'Fecha Devolucion'), }}); break; case "RETURN": this.setState({form: { barcode: InputElement('text', 'Barcode', '', "barcode","Codigo de Barras") }}); break; } } componentDidUpdate(nextProps){ if(!(this.props.function == nextProps.function)){ this.formTypeHandler(); } } render() { const formElementsArray = []; for (let key in this.state.form) { //Creates an array to loop through an object attributes formElementsArray.push({ id: key, //left side of attribute config: this.state.form[key] //right side attribute }); } return ( <div className="formSpace"> <div className="row"> <form onSubmit={(event) => this.onSubmitHandler(event)}> <div className="col-sm-2"> {formElementsArray.map(formElement => ( <div> <Input key={formElement.id} elementType={formElement.config.elementType} elementConfig={formElement.config.elementConfig} value={formElement.config.value} label = {formElement.config.label} changed={(event) => this.setState({form: InputChangedHandler(event, formElement.id, this.state)})} /> </div> ))} </div> <div className="col-sm-2"> <button type="submit" className="btn btn-primary">{(this.props.function === 'CREATE') ? "Crear" : "Actualizar"}</button> </div> </form> </div> </div> ); } }; export default LoanForm;<file_sep>var express = require('express'); var router = express.Router(); var Student = require('../models/Student'); var Person = require('../models/Person'); var Clerk = require('../models/Clerk'); const DB_Connnection = require('../DB_Connnection').db_connection; const sql = require('../DB_Connnection').sql; const config = require('../DB_Connnection').config; /* Get people listing. */ router.get('/states', function(req, res, next) { //res.writeHead(200,{'Content-Type':'application/json'}); DB_Connnection.then(pool => { return pool.request().execute('showStates'); }).then(result => { res.send(result.recordsets[0]); }).catch(err => { res.send('Fallo al ejecutar procedimiento.' + err); }); }); //get states router.get('/', function(req, res, next) { //res.writeHead(200,{'Content-Type':'application/json'}); DB_Connnection.then(pool => { return pool.request().execute('showPeople'); }).then(result => { res.send(result.recordsets[0]); }).catch(err => { res.send('Fallo al ejecutar procedimiento.' + err); }); }); //get district router.get('/districts', function(req, res, next) { //res.writeHead(200,{'Content-Type':'application/json'}); DB_Connnection.then(pool => { return pool.request().execute('showDistricts'); }).then(result => { res.send(result.recordsets[0]); }).catch(err => { res.send('Fallo al ejecutar procedimiento.' + err); }); }); //get cities router.get('/cities', function(req, res, next) { //res.writeHead(200,{'Content-Type':'application/json'}); DB_Connnection.then(pool => { return pool.request().execute('showCities'); }).then(result => { res.send(result.recordsets[0]); }).catch(err => { res.send('Fallo al ejecutar procedimiento.' + err); }); }); //get locations router.get('/locations', function(req, res, next) { //res.writeHead(200,{'Content-Type':'application/json'}); DB_Connnection.then(pool => { return pool.request().execute('showLocations'); }).then(result => { res.send(result.recordsets[0]); }).catch(err => { res.send('Fallo al ejecutar procedimiento.' + err); }); }); /* GET students listing. */ router.get('/students', function(req, res, next) { //res.writeHead(200,{'Content-Type':'application/json'}); DB_Connnection.then(pool => { console.log("conecto"); return pool.request().execute('showStudents'); }).then(result => { res.send(result.recordsets[0]); }).catch(err => { console.log(err); res.send('Fallo al ejecutar procedimiento.' + err); }); }); function popullatePersonPool(pool, req) { let applicant = req.body; //This is the applicant for the person object let person = new Person(applicant.identification, applicant.name, applicant.lastname, applicant.email, applicant.tel, applicant.cel, applicant.expireDate, applicant.ID_district, applicant.signals, applicant.location); console.log(person.identification); console.log(person.name); console.log(person.lastname); console.log(person.email); console.log(person.tel); console.log(person.cel); console.log(person.expireDate); console.log(person.districtID); console.log(applicant.signals); console.log(applicant.location); pool.input('identification',sql.Int, person.identification) .input('name', sql.NVarChar(50),person.name) .input('lastname', sql.NVarChar(50), person.lastname) .input('email', sql.NVarChar(50), person.email) .input('tel', sql.NVarChar(15), person.tel) .input('cel', sql.NVarChar(15), person.cel) .input('expireDate', sql.DateTime, person.expireDate) .input('ID_district', sql.SmallInt, person.districtID) .input('signals', sql.NVarChar(50), person.signals) .input('locationID', sql.SmallInt, person.locationID); }; /* Create and save a student */ router.post('/student', function(req, res, next) { let student = req.body; let validatedStudent = new Student(student.studentID, student.career); console.log(student.studentID); console.log(student.career); //Send to database the person validating data DB_Connnection.then(pool => { let poolRequest = pool.request(); popullatePersonPool(poolRequest, req); return poolRequest.input('studentID', sql.VarChar(10), validatedStudent.studentID) .input('career', sql.NVarChar(50), validatedStudent.career) .output('ID', sql.Int) .execute('createStudent'); }).then(result => { res.send("User created: " + result.output); }).catch(err => { res.send('Fallo al ejecutar procedimiento.' + err); }); }); //this made the update of the student router.put('/student', function(req, res, next) { let ID = req.body.ID; let student = req.body; let validatedStudent = new Student(student.studentID, student.career); //Send to database the person validating data // @identification int, @name varchar(50), @lastname varchar(50), @email varchar(50), @tel varchar(15) // ,@cel varchar(15), @expireDate datetime, @ID_district smallint, // @signals varchar(50), @locationID smallint,@studentLicense varchar(10), @career varchar(50),@Old_studentLicense varchar(10), @id int output) DB_Connnection.then(pool => { let poolRequest = pool.request(); popullatePersonPool(poolRequest, req); return poolRequest .input('studentLicense', sql.VarChar(10), validatedStudent.studentID) .input('career', sql.NVarChar(50), validatedStudent.career) .input('Old_studentLicense', sql.VarChar(10), student.old) .output('id', sql.Int, ID) .execute('updateStudents'); }).then(result => { res.send("User updated: " + ID); }).catch(err => { res.send('Fallo al ejecutar procedimiento.' + err); }); }); //delete an student ENVIAR EL CARNET router.delete('/student/:id', function(req, res, next) { DB_Connnection.then(pool => { console.log(req.params.id); return pool.request() .input('studentLicense', sql.NVarChar, req.params.id) .execute('deleteStudent'); }).then(result => { res.send("Student deleted: " + req.params.id); }).catch(err => { res.send(err); }); }); router.get('/clerks', function(req, res, next) { //res.writeHead(200,{'Content-Type':'application/json'}); DB_Connnection.then(pool => { return pool.request().execute('showClerks'); }).then(result => { res.send(result.recordsets[0]); }).catch(err => { res.send('Fallo al ejecutar procedimiento.' + err); }); }); //create the new clerk router.post('/clerk', function(req, res, next) { let clerk = req.body; let validateClerk = new Clerk(clerk.department, clerk.position); //Send to database the person validating data DB_Connnection.then(pool => { console.log(validateClerk.department); console.log(validateClerk.position); let poolRequest = pool.request(); popullatePersonPool(poolRequest, req); return poolRequest.input('department', sql.VarChar(50), validateClerk.department) .input('position', sql.VarChar(50), validateClerk.position) .output('ID', sql.Int) .execute('createClerk'); }).then(result => { res.send("clerk created: " + result.output); }).catch(err => { res.send('Fallo al ejecutar procedimiento.' + err); }); }); //update the clerk router.put('/clerk', function(req, res, next) { let ID = req.body.ID; let clerk = req.body; let validateClerk = new Clerk(clerk.department, clerk.position); //Send to database the person validating data DB_Connnection.then(pool => { let poolRequest = pool.request(); popullatePersonPool(poolRequest, req); return poolRequest.input('Department', sql.NVarChar(50), validateClerk.department) .input('Position',sql.VarChar(50), validateClerk.position) .input('Old_identification',sql.VarChar(50), clerk.old) .output('id', sql.Int, ID) .execute('updateClerks'); }).then(result => { res.send("clerk updated: " + ID); }).catch(err => { res.send('Fallo al ejecutar procedimiento.' + err); }); }); // delete clerk ENVIAR la cedula router.delete('/clerk/:id', function(req, res, next) { DB_Connnection.then(pool => { return pool.request() .input('identification', sql.VarChar(50), req.params.id) .execute('deleteClerk'); }).then(result => { res.send("Clerk deleted: " + req.params.id); }).catch(err => { res.send("Clerk couldn't be deleted"); }); }); module.exports = router; <file_sep>var express = require('express'); var path = require('path'); var favicon = require('serve-favicon'); var logger = require('morgan'); var cookieParser = require('cookie-parser'); var bodyParser = require('body-parser'); var index = require('./routes/index'); var users = require('./routes/users'); var applicants = require('./routes/applicants'); var av_equipment = require('./routes/av_equipments'); var delinquencies = require('./routes/delinquencies'); var loans = require('./routes/loans'); var app = express(); // uncomment after placing your favicon in /public //app.use(favicon(path.join(__dirname, 'public', 'favicon.ico'))); //app.use(logger('dev')); app.use(bodyParser.json()); app.use(bodyParser.urlencoded({ extended: false })); //app.use(cookieParser()); app.use(express.static(path.join(__dirname, 'dist'))); app.use('/app', express.static(__dirname + './dist/app')); app.use('/images', express.static(__dirname + '/public/images')); app.use('/', index); app.use('/users', users); app.use('/applicants', applicants); app.use('/av_equipments', av_equipment); app.use('/delinquencies', delinquencies); app.use('/loans', loans); // catch 404 and forward to error handler app.use(function(req, res, next) { var err = new Error('Not Found'); err.status = 404; next(err); }); // error handler app.use(function(err, req, res, next) { // set locals, only providing error in development res.locals.message = err.message; res.locals.error = req.app.get('env') === 'development' ? err : {}; // render the error page res.status(err.status || 500); res.sendFile('./dist/index.html'); }); app.listen(8080); //module.exports = app; <file_sep>const initState = { dataType: "", loadedData : null, selectedData: null, numberRows: 0 }; const tableReducer = (state = initState, action) => { switch(action.type){ case 'CHANGE_DATA_TYPE': state= { ...state, dataType : action.payload } break; case 'CHANGE_ROW_NUMBER': state= { ...state, numberRows : action.payload } break; } return state; } export default tableReducer;<file_sep>import React, { Component } from 'react'; import SpicyDatatable from 'spicy-datatable'; import "../styles/spicyTable.css"; import axios from 'axios'; import Modal from './Modal' class Table extends Component { state = { loadedData: null, selectedData: null, } dataRouteHandler = () => { console.log("Sends: " + this.props.tableType); let route = ''; switch (this.props.tableType) { case 'students': route = 'applicants/students'; break; case 'clerks': route = 'applicants/clerks'; break; case 'av_equipment': route = 'av_equipments'; break; case 'loans': route = 'loans'; break; case 'defaulters': route = 'delinquencies'; break; } return route; } columnsHandler = () => { let columns = []; switch (this.props.tableType) { case 'students': columns = [{ key: 'button', label: '', }, { key: 'id', label: 'Cedula', }, { key: 'studentId', label: 'Carnet', }, { key: 'name', label: 'Nombre', }, { key: 'lastname', label: 'Apellidos', }, { key: 'email', label: 'Email', }, { key: 'homePhone', label: 'Telefono Casa', }, { key: 'phone', label: 'Celular', }, { key: 'career', label: 'Carrera', }, { key: 'validDate', label: 'Fecha validez', }, { key: 'address', label: 'Direccion', }, { key: 'location', label: 'Localidad', }, { key: 'district', label: 'Distrito', } ]; break; case 'clerks': columns = [{ key: 'id', label: 'Cedula', }, { key: 'name', label: 'Nombre', }, { key: 'lastname', label: 'Apellidos', }, { key: 'phone', label: 'Telefono', }, { key: 'homePhone', label: 'Telefono Casa', }, { key: 'department', label: 'Departamento', }, { key: 'position', label: 'Posicion', }, { key: 'validDate', label: 'Fecha validez', }, { key: 'address', label: 'Direccion', }, { key: 'location', label: 'Localidad', }, { key: 'district', label: 'Distrito', } ]; break; case 'av_equipment': columns = [{ key: 'barcode', label: 'Codigo de barra', }, { key: 'category', label: 'Categoria', }, { key: 'brand', label: 'Marca', }, { key: 'model', label: 'Modelo', }, { key: 'state', label: 'Estado', } ]; break; case 'loans': columns = [ { key: 'barcode', label: 'Codigo de Barras', }, { key: 'id', label: 'Cedula', }, { key: 'name', label: 'Nombre', }, { key: 'lastname', label: 'Apellidos', }, { key: 'loanDate', label: 'Fecha Prestamo', }, { key: 'returnDate', label: 'Fecha Retorno', }, { key: 'returnedDate', label: 'Fecha Devuelto', } ]; break; case 'defaulters': columns = [ { key: 'barcode', label: 'Codigo de Barras', }, { key: 'id', label: 'Cedula', }, { key: 'name', label: 'Nombre', }, { key: 'lastname', label: 'Apellidos', }, { key: 'delqDate', label: 'Fecha Creación', }, { key: 'numDays', label: 'Numero de dias', }, { key: 'loanStartDate', label: 'Inicio Prestamo', }, { key: 'loanFinishDate', label: 'Fecha Fin Prestamo', }, { key: 'returnedDate', label: 'Fecha Entrega Prestamo', }]; break; } return columns; } rowsHandler = () => { let rows = []; if (this.state.loadedData) { switch (this.props.tableType) { case 'students': rows = this.state.loadedData.map(row => { return { id: row.identification, studentId: row.studentLicense, name: row.name, lastname: row.lastname, email: row.email, phone: row.cel, homePhone: row.tel, career: row.career, validDate: row.expireDate, address: row.address, location: row.locationName, district: row.DistrictName, onClickHandler: this.optionSelectedHandler } }); console.log(this.state.loadedData[0].expireDate); break; case 'clerks': rows = this.state.loadedData.map(row => { return { id: row.identification, name: row.name, lastname: row.lastname, email: row.email, phone: row.cel, homePhone: row.tel, department: row.department, position: row.position, validDate: row.expireDate, address: row.address, location: row.locationName, district: row.DistrictName, onClickHandler: this.optionSelectedHandler } }); break; case 'av_equipment': rows = this.state.loadedData.map(row => { return { barcode: row.barcode, category: row.category, brand: row.brandType, model: row.Model, state: row.stateType, onClickHandler: this.optionSelectedHandler } }); break; case 'loans': rows = this.state.loadedData.map(row => { return { id: row.identification, name: row.name, lastname: row.lastname, studentId: row.carnet, barcode: row.barcode, loanDate: row.loanStartDate, returnDate: row.loanFinishDate, returnedDate: row.returnedDate, onClickHandler: this.optionSelectedHandler } }); break; case 'defaulters': rows = this.state.loadedData.map(row => { return { id: row.identification, name: row.name, lastname: row.lastname, barcode: row.barcode, category: row.category, numDays: row.numDays, delqDate: row.delqdDate, loanStartDate: row.loanStartDate, loanFinishDate: row.loanFinishDate, returnedDate: row.returnedDate, onClickHandler: this.optionSelectedHandler } }); break; } } return rows; } //la opcion de onClickHandler que trae spicy por defecto envia un event, un row y el index //Es solo de recibirlos como params en la function handler //Hace que el state sea toda la info de la row (como objeto) y muestra el modal optionSelectedHandler = (event, row, index) => { this.setState({ selectedData: row }); $('#myModal').modal('show'); } componentDidMount() { let route = this.dataRouteHandler(); console.log("Route" + route) if (!this.state.loadedData) { axios.get('http://localhost:8080/' + route) .then(response => { this.setState({ loadedData: response.data }); }); } } componentDidUpdate(prevState, prevProps) { console.log("HIZO UPDATE TABLE...Prev: " + prevState.tableType + "Table type: " + this.props.tableType + " Prev prop state..:") console.log(prevProps.tableType); if (prevState.tableType !== this.props.tableType) { let route = this.dataRouteHandler(); console.log("Entra:" + route); axios.get('http://localhost:8080/' + route) .then(response => { this.setState({ loadedData: response.data }); }); } } refresh() { let route = this.dataRouteHandler(); console.log("Entra:" + route); axios.get('http://localhost:8080/' + route) .then(response => { this.setState({ loadedData: response.data }); }); } render() { const key = 'tableTest'; const config = { searchLabel: 'Buscar:', searchPlaceholder: ' ', nextPageLabel: '->', previousPageLabel: '<-', itemsPerPageLabel: 'Numero de entradas', entryCountLabels: ['Mostrando', 'a', 'de', 'entradas'], itemsPerPageOptions: [5] } let columns = this.columnsHandler(); let rows = this.rowsHandler(); let modal = null; //Este if hace que si el state es nulo(no se han seleccionado datos) no cargue ningún modal if (this.state.selectedData) { modal = <Modal selectedData={this.state.selectedData} refresh={this.refresh.bind(this)} type={this.props.tableType} /> } return ( <div className='row'> <div className='col-xs-10 col-xs-offset-1'> <SpicyDatatable tableKey={key} columns={columns} rows={rows} config={config} /> </div> {modal} </div> ); } } export default Table;<file_sep>module.exports = function(studentID, career) { //Validar con patrones this.studentID = studentID; this.career = career; }<file_sep>const sql = require('mssql'); const config = { user: 'sa', password: '<PASSWORD>', server: 'localhost\\SQLEXPRESS_2016', // You can use 'localhost\\instance' to connect to named instance database: 'Biblioteca(Production)' } module.exports = { db_connection : sql.connect(config), sql : sql, config : config };<file_sep>module.exports = function(model,brand,category,barcode,state) { this.model = model; this.brand = brand; this.category = category; this.barcode = barcode; this.state = state; }<file_sep>export function setSection(section,subcontent) { return { type: "SET_SECTION", payload: {section,subcontent} }; } export function setSubcontent(subcontent) { return { type: "SET_SUBCONTENT", payload: subcontent }; } <file_sep>import {createStore,combineReducers} from "redux"; import thunk from "redux-thunk" import userReducer from "./reducers/userReducer"; import sectionReducer from "./reducers/sectionReducer"; import logInReducer from "./reducers/logInReducer"; import applicantReducer from "./reducers/applicantReducer"; import tableReducer from './reducers/tableReducer'; import { applyMiddleware } from "redux"; import equipmentReducer from "./reducers/equipmentReducer" export default createStore( combineReducers({sectionReducer, logInReducer, applicantReducer,tableReducer, equipmentReducer}), {}, applyMiddleware(thunk) ); <file_sep>export function setDataType(dataType){ return{ type: "CHANGE_DATA_TYPE", payload: dataType } }<file_sep>import React from "react"; import "../styles/footer.css"; export const Footer = (props) => { return ( <div className="footerDiv container-flow"> <div className="wrap"> <div className="row footer"> <div className="col-xs-5"> <img className="logoUCR" src="../images/ucr.svg"/> <img className="logoUCR" src="../images/UCRlogo.png"/> </div> <div className="col-xs-5"> <p >© Biblioteca Recinto de Grecia, Universidad de Costa Rica</p> </div> </div> </div> </div> ) } <file_sep>import React from 'react'; import './Input.css'; import axios from 'axios'; class BootModal extends React.Component { constructor(props) { super(); this.state = { value : '' }; } onSubmitHandler = (event) => { event.preventDefault(); axios.post('http://localhost:8080/' + this.props.url, this.state) .then(response => { alert(this.props.label + ": " + this.state.value + " guardada."); this.props.renderData(); }); } inputChangedHandler = (event) => { this.setState({value: event.target.value}); } render() { return ( <div> <button type="button" className="btn btn-info btn-sm" data-toggle="modal" data-target={'#'+this.props.modalID}>Nueva {this.props.label}</button> <div className="modal fade" id={this.props.modalID} role="dialog"> <div className="modal-dialog"> <div className="modal-content"> <div className="modal-header"> <button type="button" className="close" data-dismiss="modal">&times;</button> <h4 className="modal-title">Nueva {this.props.label}</h4> </div> <div className="modal-body"> <form onSubmit={(event) => this.onSubmitHandler(event)}> <div className="form-group"> <label for={this.props.name}>{this.props.label}: </label> <input className="form-control input-sm" type="text" name={this.props.name} id={this.props.name} onChange={(event)=> this.inputChangedHandler(event)}/> </div> <br/> <input type="submit" className="btn btn-success btn-sm" value="Guardar"/> </form> </div> <div className="modal-footer"> <button type="button" className="btn btn-default" data-dismiss="modal">Close</button> </div> </div> </div> </div> </div> ); } }; export default BootModal; <file_sep>import React from "react"; import "../styles/LogIn.css"; import axios from 'axios'; import { Button } from "./Button"; export default class LogIn extends React.Component { constructor(props) { super(); } render() { let logInHtml = ( <div className="divLogIn container-fluid" id="logIn"> <div className="row logoDiv"> <div className="col-xs-12 col-md-offset-4"> <div className="logo"> <h1><a><img src="../images/BRGlogo.png" alt="" /></a></h1> </div> </div> </div> <div className="row"> <div className="buttonDiv col-xs-6 col-md-4 col-md-offset-4"> <Button buttonType={"administrator"} hideLogIn={this.hideLogIn.bind(this)} /> <Button buttonType={"normalUser"} hideLogIn={this.hideLogIn.bind(this)} /> <label className="labelError" id="errorMessage" >Contraseña o nombre de usuario incorrecto trate de nuevo!</label> <label className="labelError" id="forgotPassword" onClick={() => this.showPuk()}>Se te olvido la contraseña? Recuperara!</label> <div className="pukDiv"> <div className="pukDivContent"> <label>Ingrese el nombre de usuario y el codigo PUK para recuperar la contraseña</label><br /> <label>Nombre de usuario</label> <input type="text" className="form-control inputPUK" name="userName" id="userNamePuk" /><br /> <label>Codigo PUK</label> <input type="password" className="form-control inputPUK" name="password" id="passwordPuk" /><br /> <input type="submit" className="btn btn-primary" value="Recover" onClick={() => this.recoverPassword()} /> <label className="labelError" id="errorMessagePuk" >El PUK ingresado es incorrecto</label> <label className="labelError" id="errorMessageUsername" >El usuario ingresado no existe en la base de datos</label> </div> <label className="labelPassword">La contraseña de la cuenta solicitada es: </label> <br /> <label className="labelPassword" id="labelPassword" ></label> </div> </div> </div> </div> ); return logInHtml; } recoverPassword() { let userName = document.getElementById("userNamePuk").value; let puk = document.getElementById("passwordPuk").value; console.log(userName + " *** " + puk); if (puk == "123") { console.log("puk correcto"); axios.post('http://localhost:8080/users/restorePassword', { username: userName, }).then((response) => { if (response.data.pass === "") { $(".labelError").hide(); $("#errorMessageUsername").slideDown("slow"); } else { document.getElementById("labelPassword").innerHTML = response.data.pass; $(".pukDivContent").hide(); $(".labelPassword").show(); } }) } else { $(".labelError").hide(); $("#errorMessagePuk").slideDown("slow"); } } showPuk() { $("#errorMessage").hide(); $("#forgotPassword").hide(); $(".pukDiv").slideDown("slow"); } hideLogIn(type) { let username = ""; let password = ""; if (document.getElementById("user").value == "") { username = "admin"; password = document.getElementById("passwordAdmin").value; } else { username = document.getElementById("user").value; password = document.getElementById("<PASSWORD>User").value; } axios.post('http://localhost:8080/users/validate', { username: username, password: <PASSWORD> }).then((response) => { console.log(response.data); if (response.data.valid) { $("#logIn").slideUp("slow", () => { console.log(type); switch (type) { case "Administrator": console.log("Administrator"); this.props.setType(type, "admin"); break; case "NormalUser": console.log("normalUser"); this.props.setType(type, username); break; default: break; } }); } else { $(".labelError").hide(); $("#errorMessage").slideDown("slow"); $("#forgotPassword").slideDown("slow"); } }) } } <file_sep>var express = require('express'); var router = express.Router(); const db_connection = require('../DB_Connnection').db_connection; const sql = require('../DB_Connnection').sql; let User = require('../models/User'); /* GET users listing. */ router.get('/', function(req, res, next) { //res.writeHead(200,{'Content-Type':'application/json'}); //connect to db to get users instead db_connection.then(pool => { // Stored procedure return pool.request().execute('showUsers'); }).then(result => { res.send(result.recordsets[0]); }).catch(err => { res.send('Fallo al recuperar usuarios.' + err); }); }); router.post('/user', function(req, res, next) { let user = req.body; let validatedUser = new User(user.id,user.username,user.password,user.tipo,user.estado,user.mail,user.name); db_connection.then(pool => { return pool.request() .input('UserName', sql.VarChar(50), validatedUser.id) .input('Password', sql.VarChar(50), validatedUser.password) .input('type', sql.Bit, validatedUser.type) .input('state', sql.VarChar(50), validatedUser.state) .input('email', sql.VarChar(50), validatedUser.email) .input('Name', sql.VarChar(50), validatedUser.name) .output('ID', sql.Int) .execute('createUser'); }).then(result => { res.send(result.output); }).catch(err => { // ... error checks res.send("Error to post user"); }); }); /* router.put('/user/:id', function(req, res, next) { return pool.request() .input('input_parameter', sql.Int, value) .output('output_parameter', sql.VarChar(50)) .execute('procedure_name') }).then(result => { console.dir(result) }).catch(err => { // ... error checks res.send("You are updating user: " + req.params.id); });*/ router.delete('/user/:id', function(req, res, next) { let id = req.params.id; db_connection.then(pool => { return pool.request() .input('id', sql.SmallInt, id) .output('ID', sql.SmallInt) .execute('deleteUser'); }).then(result => { console.dir(result) }).catch(err => { // ... error checks res.send("You are deleting user: " + req.params.id); }); }); /*Validate user for login @param user {username, password} */ router.post('/validate', function(req, res, next) { db_connection.then(pool => { return pool.request() .input('username_email',sql.NVarChar(50), req.body.username ) .input('password', sql.NVarChar(50), req.body.password) .output('valid', sql.Bit, 0) .execute('validateUser'); }).then(result => { res.send(result.output); }).catch(err => { res.send('Fallo al ejecutar procedimiento.' + err); }); }); //restore password router.post('/restorePassword', function(req, res, next) { db_connection.then(pool => { return pool.request() .input('userName',sql.NVarChar(50), req.body.username ) .output('pass', sql.NVarChar(50), "") .execute('returnPass'); }).then(result => { res.send(result.output); }).catch(err => { res.send('Fallo al ejecutar procedimiento.' + err); }); }); module.exports = router; <file_sep>import React from "react"; import "../styles/content.css"; import SubMenu from "./SubMenu"; import ApplicantForm from "../containers/ApplicantForm"; import TableHandler from "../containers/TableHandler"; import EquipmentForm from "../containers/EquipmentForm"; import LoanForm from "../containers/LoanForm"; class Content extends React.Component { render() { let subContent; switch(this.props.subcontentType){ case "applicantForm": subContent = <ApplicantForm function="CREATE" /> break; case "studentsTable": subContent = <TableHandler tableType='students' /> break; case "clerksTable": subContent = <TableHandler tableType='clerks' /> break; case "tableDefaulters": subContent = <TableHandler tableType='defaulters'/> break; case "tableAV": subContent = <TableHandler tableType='av_equipment'/> break; case "tableLoans": subContent = <TableHandler tableType='loans'/> break; case "updateApplicant": subContent= <ApplicantForm function="UPDATE"/> break; case "añadirAudio": subContent= <EquipmentForm function="CREATE"/> break; case "updateEquipment": subContent= <EquipmentForm function="UPDATE"/> break; case "loanForm": subContent= <LoanForm function="CREATE"/> break; case "renewForm": subContent= <LoanForm function="EDIT"/> break; case "returnForm": subContent= <LoanForm function="RETURN"/> break; } let contentHtml = ( <div className="contentDiv container"> <div className="row"> <div className="col-xs-12"> {subContent} </div> </div> <div className="row"> <SubMenu subMenuType={this.props.sectionType} /> </div> </div> ); return ( <div>{contentHtml}</div> ); } } export default Content;<file_sep>import React from "react"; import "../styles/navBar.css"; //export const NavBar = (props) => { export default class NavBar extends React.Component { constructor(props) { super(); } render() { let type = this.props.section; let subMenuHTML; switch (type) { case "Prestamos": subMenuHTML = ( <div className="divHeader container-fluid"> <div className="row"> <div className="btm_border"> <div className="h_bg"> <div className="wrap"> <div className="header"> <div className="logo"> <h1><a href="index.html"><img src="../images/BRGlogo.png" alt="" /></a></h1> </div> <div className="clear"></div> </div> <div className='h_btm'> <div className='cssmenu'> <ul> <li className="active"><a onClick={() => this.props.onClick("Prestamos","loanForm")}><span>Prestamos</span></a></li> <li><a onClick={() => this.props.onClick("Solicitantes","applicantForm")}><span>Solicitantes</span></a></li> <li><a onClick={() => this.props.onClick("Audiovisuales","añadirAudio")}><span>Audiovisuales</span></a></li> <li><a onClick={() => this.props.onClick("Historial", "tableLoans")}><span>Historial</span></a></li> <li><a onClick={() => this.props.onClick("Estadisticas")}><span>Estadisticas</span></a></li> </ul> </div> <div className="clear"></div> </div> </div> </div> </div> </div> </div> ); break; case "Solicitantes": subMenuHTML = ( <div className="divHeader container-fluid"> <div className="row"> <div className="btm_border"> <div className="h_bg"> <div className="wrap"> <div className="header"> <div className="logo"> <h1><a href="index.html"><img src="../images/BRGlogo.png" alt="" /></a></h1> </div> <div className="clear"></div> </div> <div className='h_btm'> <div className='cssmenu'> <ul> <li><a onClick={() => this.props.onClick("Prestamos","loanForm")}><span>Prestamos</span></a></li> <li className="active"><a onClick={() => this.props.onClick("Solicitantes","applicantForm")}><span>Solicitantes</span></a></li> <li><a onClick={() => this.props.onClick("Audiovisuales","añadirAudio")}><span>Audiovisuales</span></a></li> <li><a onClick={() => this.props.onClick("Historial", "tableLoans")}><span>Historial</span></a></li> <li><a onClick={() => this.props.onClick("Estadisticas")}><span>Estadisticas</span></a></li> </ul> </div> <div className="clear"></div> </div> </div> </div> </div> </div> </div> ); break; case "Audiovisuales": subMenuHTML = ( <div className="divHeader container-fluid"> <div className="row"> <div className="btm_border"> <div className="h_bg"> <div className="wrap"> <div className="header"> <div className="logo"> <h1><a href="index.html"><img src="../images/BRGlogo.png" alt="" /></a></h1> </div> <div className="clear"></div> </div> <div className='h_btm'> <div className='cssmenu'> <ul> <li><a onClick={() => this.props.onClick("Prestamos","loanForm")}><span>Prestamos</span></a></li> <li><a onClick={() => this.props.onClick("Solicitantes","applicantForm")}><span>Solicitantes</span></a></li> <li className="active"><a onClick={() => this.props.onClick("Audiovisuales","añadirAudio")}><span>Audiovisuales</span></a></li> <li><a onClick={() => this.props.onClick("Historial", "tableLoans")}><span>Historial</span></a></li> <li><a onClick={() => this.props.onClick("Estadisticas")}><span>Estadisticas</span></a></li> </ul> </div> <div className="clear"></div> </div> </div> </div> </div> </div> </div> ); break; case "Historial": subMenuHTML = ( <div className="divHeader container-fluid"> <div className="row"> <div className="btm_border"> <div className="h_bg"> <div className="wrap"> <div className="header"> <div className="logo"> <h1><a href="index.html"><img src="../images/BRGlogo.png" alt="" /></a></h1> </div> <div className="clear"></div> </div> <div className='h_btm'> <div className='cssmenu'> <ul> <li><a onClick={() => this.props.onClick("Prestamos","loanForm")}><span>Prestamos</span></a></li> <li><a onClick={() => this.props.onClick("Solicitantes","applicantForm")}><span>Solicitantes</span></a></li> <li><a onClick={() => this.props.onClick("Audiovisuales","añadirAudio")}><span>Audiovisuales</span></a></li> <li className="active"><a onClick={() => this.props.onClick("Historial", "tableLoans")}><span>Historial</span></a></li> <li><a onClick={() => this.props.onClick("Estadisticas")}><span>Estadisticas</span></a></li> </ul> </div> <div className="clear"></div> </div> </div> </div> </div> </div> </div> ); break; case "Estadisticas": subMenuHTML = ( <div className="divHeader container-fluid"> <div className="row"> <div className="btm_border"> <div className="h_bg"> <div className="wrap"> <div className="header"> <div className="logo"> <h1><a href="index.html"><img src="../images/BRGlogo.png" alt="" /></a></h1> </div> <div className="clear"></div> </div> <div className='h_btm'> <div className='cssmenu'> <ul> <li><a onClick={() => this.props.onClick("Prestamos","loanForm")}><span>Prestamos</span></a></li> <li><a onClick={() => this.props.onClick("Solicitantes","applicantForm")}><span>Solicitantes</span></a></li> <li><a onClick={() => this.props.onClick("Audiovisuales","añadirAudio")}><span>Audiovisuales</span></a></li> <li><a onClick={() => this.props.onClick("Historial", "tableLoans")}><span>Historial</span></a></li> <li className="active"><a onClick={() => this.props.onClick("Estadisticas")}><span>Estadisticas</span></a></li> </ul> </div> <div className="clear"></div> </div> </div> </div> </div> </div> </div> ); break; default: break; } return subMenuHTML; } } <file_sep>import React from "react"; import {connect} from 'react-redux'; import "../styles/Form.css"; import {Input, InputElement, SelectElement,InputChangedHandler} from "../components/FormsUI/Input"; import axios from 'axios'; import BootModal from '../components/FormsUI/BootModal'; class EquipmentForm extends React.Component { constructor(props) { super(); const UPDATE = (props.function == 'UPDATE') ? true : false; this.state = { old_barcode : (UPDATE) ? props.equipment.barcode: '', old_model : (UPDATE) ? props.equipment.model: '', categoryID:0, brandID:0, stateID:0, form: { barcode : InputElement('text', 'Nombre', (UPDATE)?props.equipment.barcode:'' , "barcode", "Codigo Barras"), category : SelectElement( [ {value:'1', displayValue: 'toDeploy'},] ,'','category', "Categoria"), model : InputElement('text', 'Modelo', (UPDATE)?props.equipment.model:'' , "model", "Modelo"), brand : SelectElement( [ {value:'1', displayValue: 'VAIO'}, {value:'2', displayValue: 'Apple'}] ,'','brand', "Marca"), state : SelectElement( [ {value:'1', displayValue: 'Prestada'}, {value:'2', displayValue: 'Disponible'}] ,'','state', "Estado") }, loadedCategories: null, loadedBrands: null, loadedStates: null }; } onSubmitHandler = (event) => { event.preventDefault(); const formData = {}; for (let formElementIdentifier in this.state.form) { formData[formElementIdentifier] = this.state.form[formElementIdentifier].value; } switch (this.props.function) { case 'CREATE': axios.post('http://localhost:8080/av_equipments/av_equipment', formData) .then(response => { alert("Equipo Creado \n Codigo de Barras: " + formData.barcode); }); break; case 'UPDATE': let data = { ...formData, old_barcode : this.state.old_barcode, old_model: this.state.old_model }; axios.put('http://localhost:8080/av_equipments/av_equipment/'+ data.old_barcode, data) .then(response => { alert("Equipo Actualizado \n Codigo de Barras: " + formData.barcode); }); break; } } renderData() { const UPDATE = (this.props.function == 'UPDATE') ? true : false; axios.get('http://localhost:8080/av_equipments/categories') .then(response =>{ this.setState({loadedCategories:response.data}); let categories = this.state.loadedCategories.map(category => { if (this.state.categoryID === 0 && category.category === this.props.equipment.category) { this.state.categoryID = category.id_category; } return{ value: category.id_category, displayValue: category.category } }); this.setState({form : { ...this.state.form, category : SelectElement(categories, (UPDATE)?this.state.categoryID:1, 'category','Categoria') }}); }); axios.get('http://localhost:8080/av_equipments/brands') .then(response =>{ this.setState({loadedBrands:response.data}); let brands = this.state.loadedBrands.map(brand =>{ if (this.state.brandID === 0 && brand.brandType === this.props.equipment.brand) { this.state.brandID = brand.id_brand; } return{ value: brand.id_brand, displayValue: brand.brandType } }); this.setState({form : { ...this.state.form, brand : SelectElement( brands,(UPDATE)?this.state.brandID:1,'brand', "Marca") }}); }); axios.get('http://localhost:8080/av_equipments/states') .then(response =>{ this.setState({loadedStates:response.data}); let states = this.state.loadedStates.map(state =>{ if(this.state.stateID === 0 && state.stateType === this.props.equipment.stateID) { this.state.stateID = state.id_state; } return{ value: state.id_state, displayValue: state.stateType } }); this.setState({form : { ...this.state.form, state : SelectElement(states,(UPDATE)?this.state.stateID:1,'state', "Estado") }}); }); } componentWillMount(){ this.renderData(); } render() { const formElementsArray = []; for (let key in this.state.form) { //Creates an array to loop through an object attributes formElementsArray.push({ id: key, //left side of attribute config: this.state.form[key] //right side attribute }); } return ( <div className="formSpace"> <div className="row"> {/* <form> falta onSubmit */} <form onSubmit={(event) => this.onSubmitHandler(event)}> <div className="col-sm-2"> {formElementsArray.map(formElement => ( <Input key={formElement.id} elementType={formElement.config.elementType} elementConfig={formElement.config.elementConfig} value={formElement.config.value} label={formElement.config.label} changed={(event) => this.setState({form: InputChangedHandler(event, formElement.id, this.state)})} /> ))} <div className="col-sm-4"> <br/> <button type="submit" className="btn btn-primary">{(this.props.function === 'CREATE')?"Crear":"Actualizar"}</button> </div> </div> </form> <br/> <br/> <br/> <br/> <br/> <BootModal modalID="cat" name="category" label="Categoria" url="av_equipments/category" renderData={this.renderData.bind(this)}/> <br/> <br/> <br/> <br/> <br/> <BootModal modalID="brand" name="brand" label="Marca" url="av_equipments/brand" renderData={this.renderData.bind(this)}/> </div> </div> ); } } const mapStateToProps = (state) => { return { equipment: state.equipmentReducer, }; }; const mapDispatchToProps = (dispatch) => { return { }; }; export default connect(mapStateToProps, mapDispatchToProps)(EquipmentForm);<file_sep>import React, { Component } from 'react'; import { connect } from 'react-redux'; import Table from '../components/Table'; import { setDataType } from '../actions/tableActions'; import {Button} from "../components/Button"; import {setSubcontent} from "../actions/sectionActions"; class TableHandler extends Component { render() { let applicantsButtons = null; if (this.props.tableType === "students" || this.props.tableType === "clerks"){ applicantsButtons = <div className="btn-group optionsButton"> <button type="button" className="btn btn-primary" onClick={() => this.props.setSubcontent("studentsTable")}>Estudiante</button> <button type="button" className="btn btn-primary" onClick={() => this.props.setSubcontent("clerksTable")}>Funcionario</button> </div> } console.log("did render" + this.props.tableReducer.dataType) return ( <div> {applicantsButtons} {this.switchTableType()} </div> ); } switchTableType() { console.log() let tableType = <Table tableType={this.props.tableType}/> return tableType } componentWillMount(){ console.log("ENTRE A componentWillMount()") this.props.setDataType(this.props.tableType); } }; const mapStateToProps = (state) => { return { tableReducer: state.tableReducer, applicantReducer: state.applicantReducer }; }; const mapDispatchToProps = (dispatch) => { return { setDataType: (dataType) => { dispatch(setDataType(dataType)); }, setApplicant: (type, name) => { dispatch(setApplicant(type, name)); }, setSubcontent: (type) => { dispatch(setSubcontent(type)); } } }; export default connect(mapStateToProps, mapDispatchToProps)(TableHandler);<file_sep> const sectionReducer = (state = { actualSection : "Prestamos", subcontent: "loanForm" },action) => { switch (action.type) { case "SET_SECTION": state = { ...state, actualSection : action.payload.section, subcontent : action.payload.subcontent } break; case "SET_SUBCONTENT": console.log("setting sub content: ********* " + action.payload); state = { ...state, subcontent: action.payload } break; default: break; } return state; } export default sectionReducer;<file_sep>module.exports = function(type,hour){ let today = new Date(); let dd = today.getDate(); let mm = today.getMonth(); //January is 0! let yyyy = today.getFullYear(); let hh = today.getHours(); let mn = today.getMinutes(); if(dd < 10){ dd= "0"+dd; } if(mm < 10){ mm= "0"+mm; } if(hh < 10){ hh= "0"+hh; } if(mn < 10){ mn= "0"+mn; } if(type == 'actual'){ today = yyyy + '-'+mm+"-"+dd+"T"+hh+":"+mm+":00Z"; }else if(type == 'end'){ today = yyyy + '-'+mm+"-"+dd+"T"+hour+":00Z"; } this.date = new Date(today); }; <file_sep>var express = require('express'); var router = express.Router(); const db_connection = require('../DB_Connnection').db_connection; const sql = require('../DB_Connnection').sql; router.get('/', function (req, res, next) { db_connection.then(pool => { console.log("conecto"); return pool.request().execute('showDelinquencies'); }).then(result => { res.send(result.recordsets[0]); }).catch(err => { res.send('fallo al mostrar morosidades' + err); }); }); module.exports = router;
1625228e70aef5598e2e44f6aadd753bbf29d6a3
[ "JavaScript" ]
27
JavaScript
St7-07/Library
ad331466a576caf58da66c9eccea5b2c8aa0e8a0
e1bf94e753459e18ea98d84a3f65a8775ec2184a
refs/heads/main
<file_sep># -*- coding: utf-8 -*- import re import requests import time import random import csv import json import urllib from lxml import etree, html # 构造headers信息 headers = { 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36' } def get_text(name): """ 从运动员界面爬取bio,返回列表 """ url = 'https://olympics.com/en/athletes/'+name # 目标网址 try: response = requests.get(url, headers=headers) # 请求获取网页信息 except: print('服务器请求失败') response.encoding = response.apparent_encoding # 编码格式 # fh = open('test.txt', 'w') # fh.write(response.content.decode("utf-8",'ignore')) # fh.close() Text = etree.HTML(response.text) a_x = Text.xpath('//*[@id="content"]/section[2]/div/div[2]/div/div/p/text()') return a_x def get_name(): """ 通过API爬取运动员姓名,返回姓名 """ try: # time.sleep(random.randint(0, 3)) # 控制访问速度 resp = urllib.request.urlopen('https://olympics.com/en/api/v1/search/default/athletes') except: print('API请求失败') ele_json = json.loads(resp.read()) names = [] for i in range(len(ele_json["modules"][0]["content"])): names.append(ele_json["modules"][0]["content"][i]["slug"]) return names def main(): count = 0 f = open('athletes.txt', 'w', encoding='utf-8') # 创建一个csv文件 print("ok") writer = csv.writer(f, delimiter='\t', quoting=csv.QUOTE_ALL) row = ['name','bios'] # 设置行首 writer.writerow(row) names = get_name() print( len(names), "rows of data to be written",) for i in range(len(names)): bios = get_text(names[i]) # print(type(bios)) row = [names[i],bios] writer.writerow(row) print("a row written", i) f.close() if __name__ == '__main__': main() <file_sep># Olympic-athletes-reporter<file_sep> import sys import os from transformers import AutoTokenizer, AutoModelForSeq2SeqLM from transformers import TFAutoModelWithLMHead from pptx import Presentation from pptx.util import Inches import re from html.parser import HTMLParser import urllib import urllib.request import requests from selenium import webdriver import time import json import codecs from urllib.request import urlretrieve import shutil #pip install sentencepiece #pip install protobuf import xmind from xmind.core.const import TOPIC_DETACHED from xmind.core.markerref import MarkerId from xmind.core.topic import TopicElement title_page = 0 normal_page = 1 normal_page2 = 2 two_page = 3 interlude_page = 4 pic_page = 5 templates = {} templates['ai'] = 1 templates['idea'] = 2 templates['abstract'] = 3 templates['color'] = 4 class Img_downloader(HTMLParser): def __init__(self): HTMLParser.__init__(self) self.cnt = 0 @staticmethod def _attr(attrlist, attrname): for attr in attrlist: if attr[0] == attrname: return attr[1] return None def restart(self, ccnt): self.cnt = ccnt def handle_starttag(self, tag, attrs): if self.cnt > 0: global img_idx if tag == 'img' and 'mimg' in self._attr(attrs, 'class'): location = self._attr(attrs, 'src') urlretrieve(location, './image/{}.jpeg'.format(img_idx)) img_idx += 1 self.cnt -= 1 user_agent = 'Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)' headers = {'User-Agent': user_agent} option = webdriver.ChromeOptions() # 隐藏窗口 option.add_argument('headless') # 防止打印一些无用的日志 option.add_experimental_option("excludeSwitches", ['enable-automation', 'enable-logging']) driver = webdriver.Chrome("chromedriver.exe", chrome_options=option) url = "https://www.bing.com/images/search?q=" img_downloader = Img_downloader() generation_args = {} img_idx = 0 def set_args(): generation_args["num_beams"] = 3 generation_args["early_stopping"] = True generation_args["num_return_sequences"] = 1 generation_args["max_length"] = 20 def generate_title(context, model, tokenizer, args): inputs = tokenizer(text=context, return_tensors="pt") outputs = model.generate(**inputs, **args) return tokenizer.decode(outputs[0], skip_special_tokens=True) def generate_abstract(context, model, tokenizer): inputs = tokenizer.encode(context, return_tensors="tf", max_length=512) outputs = model.generate(inputs, max_length=200, min_length=20, length_penalty=1.0, num_beams=4, early_stopping=True) return tokenizer.decode(outputs[0], skip_special_tokens=True) def get_data(t, content): passage = content.split('\n') print(passage) data = [] # if t == '0': # title = generate_title(content, title_model, title_tokenizer, generation_args) # else: # title = t title = t for i in range(len(passage)): p = passage[i] abstract = generate_abstract(p, abstract_model, abstract_tokenizer) subtitle = generate_title(p, title_model, title_tokenizer, generation_args) data.append(subtitle + '.') data[i] += abstract data[i] = re.sub(r'\.|;|;', '\n', data[i]) return title, data def get_pic(title, ccnt): driver.get(url + title) res = driver.page_source img_downloader.restart(ccnt) img_downloader.feed(res) def generate_ppt(author, title, data, style): style_val = templates[style] prs = Presentation('template' + str(style_val) + '.pptx') cover = prs.slides.add_slide(prs.slide_layouts[title_page]) t = cover.shapes.title subtitle = cover.placeholders[1] t.text = title subtitle.text = author for i in range(len(data)): d = data[i].split('\n') if '' in d: d.remove('') interlude = prs.slides.add_slide(prs.slide_layouts[interlude_page]) t = interlude.shapes.title t.text = d[0] if len(d) == 3: slide = prs.slides.add_slide(prs.slide_layouts[two_page]) else: slide = prs.slides.add_slide(prs.slide_layouts[normal_page]) t = slide.shapes.title t.text = d[0] if len(d) == 3: get_pic(d[0], 1) img = './image/{}.jpeg'.format(img_idx - 1) pic = slide.shapes.add_picture(image_file=img, left=Inches(5.5), top=Inches(3.5), width=Inches(4), height=Inches(2)) slide.shapes._spTree.insert(1, pic._element) for j in range(1, 3): content = slide.placeholders[j] content.text = d[j] else: get_pic(d[0], 1) img = './image/{}.jpeg'.format(img_idx - 1) pic = slide.shapes.add_picture(image_file=img, left=Inches(5.5), top=Inches(3.5), width=Inches(4), height=Inches(2)) slide.shapes._spTree.insert(1, pic._element) content = slide.placeholders[1] for j in range(1, len(d)): content.text = content.text + '\n' + d[j] end = prs.slides.add_slide(prs.slide_layouts[interlude_page]) t = end.shapes.title t.text = 'TH<NAME>' filename = author + '.pptx' prs.save(filename) if os.path.exists('.\\static\\PPT\\' + filename): os.remove('.\\static\\PPT\\' + filename) shutil.move(filename, '.\\static\\PPT') def generate_xmind(author, title, data): workbook = xmind.load('.\\static\\xmind\\' + author + '.xmind') first_sheet = workbook.getPrimarySheet() # 获取第一个画布 first_sheet.setTitle(title) # 设置画布名称 root_topic1 = first_sheet.getRootTopic() # 获取画布中心主题,默认创建画布时会新建一个空白中心主题 root_topic1.setTitle(title) # 设置主题名称 for i in range(len(data)): d = data[i].split('\n') if '' in d: d.remove('') sub_topic1 = root_topic1.addSubTopic() # 创建子主题,并设置名称 sub_topic1.setTitle(d[0]) for j in range(1, len(d)): sub_topic2 = sub_topic1.addSubTopic() sub_topic2.setTitle(d[j]) xmind.save(workbook) if __name__ == '__main__': with open('athletes.txt', encoding='utf-8',errors='ignore') as f: input_data = f.read() #print(input_data) tmp = input_data.split('\n\n') len = len(tmp) titles = [] contents = [] for i in range(1,len-1): titles.append(tmp[i].split('\t')[0]) print(tmp[i].split('\t')[1]) contents.append(tmp[i].split('\t')[1]) set_args() # title_model_select = 'pbmstrk/t5-large-arxiv-abstract-title' # title_tokenizer = AutoTokenizer.from_pretrained(title_model_select) # title_model = AutoModelForSeq2SeqLM.from_pretrained(title_model_select) abstract_model_select = "t5-base" abstract_model = TFAutoModelWithLMHead.from_pretrained(abstract_model_select) abstract_tokenizer = AutoTokenizer.from_pretrained(abstract_model_select) for i in range(1,len-1): title, data = get_data(titles[i], contents[i]) #title = 'abc' #data = ['apple\nred\nfresh', 'pineapple\nnotapple\nyellow'] generate_ppt(titles[i], title[i], data, 1) generate_xmind(titles[i], title[i], data) with open('output.txt', 'w', encoding='utf-8') as fout: fout.write(title + '_' + name)
e00eab7711b48d1cb96e15256335a7491b432891
[ "Markdown", "Python" ]
3
Python
TommyXiee/Olympic-athletes-reporter
ae052b6ece528ab4531c98e8990895b65ea5be17
2d634c164a358a0353c4009ee58849df846c4f08
refs/heads/master
<repo_name>ciga2011/fabric<file_sep>/scripts/compile_protos.sh #!/bin/bash # # Copyright IBM Corp. All Rights Reserved. # # SPDX-License-Identifier: Apache-2.0 # set -eux -o pipefail # Find all proto dirs to be processed PROTO_DIRS=$(eval \ find "$(pwd) \ -path $(pwd)/vendor -prune -o \ -path $(pwd)/.build -prune -o \ -name '*.proto' \ -exec readlink -f {} \; \ -print0" | xargs -n 1 dirname | sort -u | grep -v testdata) for dir in ${PROTO_DIRS}; do protoc --proto_path="$dir" --go_out=plugins=grpc,paths=source_relative:"$dir" "$dir"/*.proto done <file_sep>/integration/externalbuilders/golang/bin/launch #!/bin/bash # Copyright IBM Corp. All Rights Reserved. # # SPDX-License-Identifier: Apache-2.0 set -euo pipefail if [ "$#" -ne 4 ]; then echo "Expected 4 directories got $#" exit 1 fi SOURCE=$1 PACKAGE_ID=$(jq -r .package_id $2/metadata.json) OUTPUT=$3 ARTIFACTS=$4 export CORE_CHAINCODE_ID_NAME="${PACKAGE_ID}" export CORE_TLS_CLIENT_CERT_PATH="$ARTIFACTS/client.crt" export CORE_TLS_CLIENT_KEY_PATH="$ARTIFACTS/client.key" export CORE_PEER_TLS_ROOTCERT_FILE="$ARTIFACTS/root.crt" # Note, for strange historical reasons, the chaincode expects the cert and key # to be base64 encoded, but not the root cert. jq -r .client_cert $ARTIFACTS/chaincode.json > "$CORE_TLS_CLIENT_CERT_PATH" jq -r .client_key $ARTIFACTS/chaincode.json > "$CORE_TLS_CLIENT_KEY_PATH" jq -r .root_cert $ARTIFACTS/chaincode.json | base64 --decode > "$CORE_PEER_TLS_ROOTCERT_FILE" if [ -z "$(cat $CORE_TLS_CLIENT_CERT_PATH)" ] ; then export CORE_PEER_TLS_ENABLED=false else export CORE_PEER_TLS_ENABLED=true fi "$OUTPUT/chaincode" -peer.address=$(jq -r .peer_address "$ARTIFACTS/chaincode.json") & PID=$? sleep 5 disown kill -0 $PID exit $? <file_sep>/core/ledger/kvledger/upgrade.go /* Copyright IBM Corp. All Rights Reserved. SPDX-License-Identifier: Apache-2.0 */ package kvledger import ( "github.com/hyperledger/fabric/common/ledger/util/leveldbhelper" "github.com/pkg/errors" ) // UpgradeDataFormat upgrades existing ledger databases to the v2.0 formats func UpgradeDataFormat(rootFSPath string) error { fileLockPath := fileLockPath(rootFSPath) fileLock := leveldbhelper.NewFileLock(fileLockPath) if err := fileLock.Lock(); err != nil { return errors.Wrap(err, "as another peer node command is executing,"+ " wait for that command to complete its execution or terminate it before retrying") } defer fileLock.Unlock() // For now, it only upgrades idStore. // More upgrades will be added. return UpgradeIDStoreFormat(rootFSPath) } // UpgradeIDStoreFormat upgrades the format for idStore func UpgradeIDStoreFormat(rootFSPath string) error { logger.Debugf("Attempting to upgrade idStore data format to current format %s", string(idStoreFormatVersion)) dbPath := LedgerProviderPath(rootFSPath) db := leveldbhelper.CreateDB(&leveldbhelper.Conf{DBPath: dbPath}) db.Open() defer db.Close() idStore := &idStore{db, dbPath} return idStore.upgradeFormat() }
364819dcc2c8869309f724063de062e1f0b13b36
[ "Go", "Shell" ]
3
Shell
ciga2011/fabric
538bc885c0fea50d5b0e0692091244b59b8c8a49
515be9a0ede2fb5fc8705a13b64c076cbbf3ca72
refs/heads/master
<repo_name>GrupoOperacionalRDO/WebThreshGame_gamejam<file_sep>/Assets/Entities/UI/Controller/Score.cs using System.Collections; using UnityEngine; using UnityEngine.UI; public class Score : MonoBehaviour { private ThreshBehaviour thresh; private int score = 10; private Text scoreText; void Awake () { EventManager.AddListener ("OnEnemyDestroyed", this.OnEnemyDestroyed); thresh = GameObject.FindObjectOfType<ThreshBehaviour> (); #if UNITY_EDITOR score = 100; #endif scoreText = GameObject.Find ("ScoreText").GetComponent<Text>(); if (!scoreText) { Debug.LogError("Can't find the ScoreText"); } } void Update() { scoreText.text = "Score: " + score; #if UNITY_EDITOR if (Input.GetKeyDown(KeyCode.Q)) { Debug.Log("Score cheat!"); score += 100; } #endif } public bool UseScore(int amount) { if((score - amount) < 0) return false; score -= amount; return true; } private void OnEnemyDestroyed () { score += thresh.value; } } <file_sep>/Assets/Entities/UI/Controller/UpgradeButton.cs using UnityEngine; using UnityEngine.UI; using System.Collections; public class UpgradeButton : MonoBehaviour { private UpgradeController upgradeController; public GameObject rangeButton; public GameObject speedButton; public GameObject incomeButton; private Text rangeLevelText; private Text speedLevelText; private Text incomeLevelText; private Text rangeCostText; private Text speedCostText; private Text incomeCostText; void Awake () { upgradeController = GameObject.FindObjectOfType<UpgradeController>(); if (!upgradeController) { Debug.LogError("Can't find the UpgradeController"); } InitializeButtonsText(); } void InitializeButtonsText() { RangeButtonInitialize(); SpeedButtonInitialize(); IncomeButtonInitialize(); } void RangeButtonInitialize() { Button btn = rangeButton.transform.Find("Plus").GetComponent<Button>(); btn.onClick.AddListener(() => upgradeController.UpgradeRange()); rangeLevelText = rangeButton.transform.Find("LevelPanel/LevelText").GetComponent<Text>(); rangeCostText = rangeButton.transform.Find("ValuePanel/ValueText").GetComponent<Text>(); } void SpeedButtonInitialize() { Button btn = speedButton.transform.Find("Plus").GetComponent<Button>(); btn.onClick.AddListener(() => upgradeController.UpgradeSpeed()); speedLevelText = speedButton.transform.Find("LevelPanel/LevelText").GetComponent<Text>(); speedCostText = speedButton.transform.Find("ValuePanel/ValueText").GetComponent<Text>(); } void IncomeButtonInitialize() { Button btn = incomeButton.transform.Find("Plus").GetComponent<Button>(); btn.onClick.AddListener(() => upgradeController.UpgradeIncome()); incomeLevelText = incomeButton.transform.Find("LevelPanel/LevelText").GetComponent<Text>(); incomeCostText = incomeButton.transform.Find("ValuePanel/ValueText").GetComponent<Text>(); } void Update () { // Set the cost's value rangeCostText.text = upgradeController.RangeCost.ToString(); speedCostText.text = upgradeController.SpeedCost.ToString(); incomeCostText.text = upgradeController.IncomeCost.ToString(); // Set the level's value rangeLevelText.text = upgradeController.RangeLevel.ToString(); speedLevelText.text = upgradeController.SpeedLevel.ToString(); incomeLevelText.text = upgradeController.IncomeLevel.ToString(); } } <file_sep>/Assets/Entities/Wall/Wall.cs using UnityEngine; using System.Collections; public class Wall : MonoBehaviour { public float multiplier = 1f; void Start () { Vector3 newSize = General.GetCameraSize() * multiplier; GetComponent<BoxCollider2D> ().size = newSize; } void OnTriggerExit2D(Collider2D collision){ EventManager.HandleMessage ("OnWallHit"); } // Update is called once per frame void Update () { } } <file_sep>/Assets/Entities/UI/Background/AutoScalingBg.cs using UnityEngine; using System.Collections; [ExecuteInEditMode] public class AutoScalingBg : MonoBehaviour { void OnGUI () { this.GetComponent<Transform>().localScale = General.GetCameraSize(); } } <file_sep>/Assets/Entities/Enemy/EnemyBehaviour.cs using UnityEngine; using System.Collections; public class EnemyBehaviour : MonoBehaviour { public Sprite[] sprite; private SpriteRenderer spriteRenderer; void Awake () { GameObject parent = GameObject.Find ("Enemies"); if(!parent){ parent = new GameObject("Enemies"); } transform.parent = parent.transform; spriteRenderer = GetComponent<SpriteRenderer>(); spriteRenderer.sprite = sprite[Random.Range(0, sprite.Length)]; } public void DestroyEnemy(){ EventManager.HandleMessage("OnEnemyDestroyed"); Destroy(this.gameObject); } void OnBecameInvisible(){ Destroy(this.gameObject); } } <file_sep>/Assets/Entities/UI/StartMenu/ThreshStartMenu.cs using UnityEngine; using System.Collections; public class ThreshStartMenu : MonoBehaviour { public float paddle = 2f; void Start() { Vector3 bounds = General.GetCameraSize(); float leftBound = -(bounds.x / 2) + paddle; Vector3 pos = transform.position; pos.x = leftBound; transform.position = pos; } } <file_sep>/Assets/Entities/Thresh/ThreshBehaviour.cs using UnityEngine; using System.Collections; public class ThreshBehaviour : MonoBehaviour { public GameObject hookPrefab, hookPrefabChild1, hookPrefabChild2; public float speed = 15.0f, maxRange = 3; public int value = 1; public bool bounce = false; public bool multipleHooks = false; public bool phase = false; private GameObject hookHand; private float angle; private Vector3 hookPos; void Start () { hookHand = transform.Find("ThreshHandHook").gameObject; if(!hookHand){ Debug.LogError("Can't find ThreshHandHook GameObject"); } } public GameObject GetHandHook(){ return hookHand; } void Update(){ if(Input.GetMouseButtonDown(0)){ CalculateAngle(); if(CanCreateHook()){ EventManager.HandleMessage("OnHookCreated"); } } } bool CanCreateHook(){ if (General.IsPointerOverUIObject()){ return false; }else if(GameObject.FindObjectsOfType<HookBehaviour>().Length > 0){ return false; }else if (angle <= 85 && angle >= -85) { return false; } return true; } void CalculateAngle(){ hookPos = hookHand.transform.position; Vector2 mousePos = Camera.main.ScreenToWorldPoint(Input.mousePosition); angle = Mathf.Atan2((mousePos.x - hookPos.x), (mousePos.y - hookPos.y)) * Mathf.Rad2Deg; } public void HookThrow() { GameObject hookInstance = Instantiate (hookPrefab, hookPos, Quaternion.identity) as GameObject; hookInstance.transform.Rotate (0, 0, -angle); hookInstance.GetComponent<HookBehaviour> ().SetVelocity (speed); if (multipleHooks) { GameObject hookInstance1 = Instantiate (hookPrefabChild1, hookPos, Quaternion.identity) as GameObject; hookInstance1.transform.Rotate (0, 0, -angle - 30); hookInstance1.GetComponent<SecondaryHookBehaviour> ().SetVelocity (speed); GameObject hookInstance2 = Instantiate (hookPrefabChild2, hookPos, Quaternion.identity) as GameObject; hookInstance2.transform.Rotate (0, 0, -angle + 30); hookInstance2.GetComponent<SecondaryHookBehaviour> ().SetVelocity (speed); } } } <file_sep>/Assets/Entities/Hook/SecondaryHookBehaviour.cs using UnityEngine; using System.Collections; public class SecondaryHookBehaviour : HookBehaviour { void Awake() { base.Configure(); } protected override void Update () { base.Update (); } protected override void DestroyHook(){ Destroy (this.gameObject); } } <file_sep>/Assets/Entities/UI/Controller/UniqueUpgradeButton.cs using UnityEngine; using UnityEngine.UI; using System.Collections; public class UniqueUpgradeButton : MonoBehaviour { private UniqueUpgradeController upgradeController; public GameObject bounceButton; public GameObject multipleHookButton; public GameObject phaseButton; private Text bounceCostText; private Text multipleHookCostText; private Text phaseCostText; void Awake () { upgradeController = GameObject.FindObjectOfType<UniqueUpgradeController>(); if (!upgradeController) { Debug.LogError("Can't find the UniqueUpgradeController"); } InitializeButtonsText(); } void InitializeButtonsText() { BounceButtonInitialize(); MultipleHookButtonInitialize(); PhaseButtonInitialize(); } public void OnBouceUpgradePressed() { if (upgradeController.BounceUpgrade()) { bounceButton.GetComponentInChildren<Button>().interactable = false; } } public void OnMultipleHooksUpgradePressed() { if (upgradeController.MultipleHooksUpgrade()) { multipleHookButton.GetComponentInChildren<Button>().interactable = false; } } public void OnPhasesUpgradePressed() { if (upgradeController.PhaseUpgrade()) { phaseButton.GetComponentInChildren<Button>().interactable = false; } } void BounceButtonInitialize() { bounceButton.transform.Find("UpgradeIcon").GetComponent<Button>().onClick.AddListener(this.OnBouceUpgradePressed); bounceCostText = bounceButton.transform.Find("ValuePanel/ValueText").GetComponent<Text>(); } void MultipleHookButtonInitialize() { multipleHookButton.transform.Find("UpgradeIcon").GetComponent<Button>().onClick.AddListener(this.OnMultipleHooksUpgradePressed); multipleHookCostText = multipleHookButton.transform.Find("ValuePanel/ValueText").GetComponent<Text>(); } void PhaseButtonInitialize() { phaseButton.transform.Find("UpgradeIcon").GetComponent<Button>().onClick.AddListener(this.OnPhasesUpgradePressed); phaseCostText = phaseButton.transform.Find("ValuePanel/ValueText").GetComponent<Text>(); } void Update () { // Set the cost's value bounceCostText.text = upgradeController.BounceCost.ToString(); multipleHookCostText.text = upgradeController.MultipleHookCost.ToString(); phaseCostText.text = upgradeController.PhaseCost.ToString(); } } <file_sep>/Assets/PlayerPrefsManager/PlayerPrefsManager.cs using UnityEngine; using System.Collections; public class PlayerPrefsManager : MonoBehaviour { const string HIGH_SCORE_KEY = "high_score"; // High score public static void SetHighScore(int score){ if (score >= 0f) { PlayerPrefs.SetInt (HIGH_SCORE_KEY, score); } else { Debug.LogError("High score can't be a negative number!"); } } public static int GetHighScore(){ return PlayerPrefs.GetInt (HIGH_SCORE_KEY); } } <file_sep>/Assets/Entities/Hook/HookBehaviour.cs using UnityEngine; using System.Collections; public class HookBehaviour : MonoBehaviour { protected ThreshBehaviour thresh; protected LineRenderer lineRender; protected Rigidbody2D thisRigidbody; protected GameObject hookHand; protected GameObject hookCord; protected float speed; protected float timeCounter; protected void Configure() { thresh = GameObject.FindObjectOfType<ThreshBehaviour> (); hookCord = transform.Find("HookLinePoint").gameObject; thisRigidbody = GetComponent<Rigidbody2D>(); lineRender = GetComponent<LineRenderer> (); hookHand = thresh.GetHandHook(); lineRender.SetPosition(0, hookHand.transform.position); lineRender.SetPosition (1, hookCord.transform.position); } void Awake() { Configure (); } public void SetVelocity(float speed) { if (!thisRigidbody) { thisRigidbody = GetComponent<Rigidbody2D>(); } this.speed = speed; thisRigidbody.velocity = transform.up * speed; } // Update is called once per frame protected void UpdateHandler() { MaxRangeDestroy (); lineRender.SetPosition (1, hookCord.transform.position); float distance = Vector2.Distance(hookHand.transform.position, hookCord.transform.position); lineRender.material.mainTextureScale = new Vector2(distance * 2, 1); } protected virtual void Update () { UpdateHandler (); } protected void OnTriggerEnter2D(Collider2D coll) { EnemyBehaviour en = coll.GetComponent<EnemyBehaviour>(); if (en) { en.DestroyEnemy(); if (!thresh.phase) DestroyHook(); } } protected void OnTriggerExit2D(Collider2D coll) { Wall wall = coll.GetComponent<Wall>(); if (wall) { if (thresh.bounce) { float angle = 0; Vector3 bounds = General.GetCameraSize(); float topBound = bounds.y / 2; float rightBound = bounds.x / 2; if (Mathf.Abs(transform.position.y) >= topBound) { float ang = 90 - transform.eulerAngles.z; angle = transform.eulerAngles.z + (2 * ang); } else if (Mathf.Abs(transform.position.x) >= rightBound) { angle = -transform.eulerAngles.z; } transform.eulerAngles = new Vector3(0, 0, angle); SetVelocity(speed); } else { DestroyHook(); } } } protected void MaxRangeDestroy() { timeCounter += Time.deltaTime; float distance = speed * timeCounter; if (distance > thresh.maxRange) { DestroyHook (); } } protected virtual void DestroyHook() { EventManager.HandleMessage("OnHookDestroyed"); SecondaryHookBehaviour[] secondaries = GameObject.FindObjectsOfType<SecondaryHookBehaviour>(); foreach(SecondaryHookBehaviour sh in secondaries) { sh.DestroyHook(); } Destroy (this.gameObject); } } <file_sep>/Assets/Entities/Enemy/SpawnController.cs using UnityEngine; using System.Collections; using System.Collections.Generic; public class SpawnController : MonoBehaviour { public GameObject enemyPrefab; public float spawnTime = 3f; private float timer; private float minX = -21.0f, minY = -5.0f, maxX = -19.0f, maxY = 4.0f; // Use this for initialization void Start () { if (!enemyPrefab) { Debug.LogError("No instance of enemy found"); } InstantiateEnemy (); } void InstantiateEnemy(){ Vector3 position = new Vector3(Random.Range(minX, maxX), Random.Range(minY, maxY)); GameObject enemy = Instantiate (enemyPrefab, position, Quaternion.identity) as GameObject; enemy.GetComponent<Rigidbody2D> ().velocity = enemy.transform.right * Random.Range (3,10); } // Update is called once per frame void Update () { timer += Time.deltaTime; if (timer > spawnTime) { InstantiateEnemy(); timer = 0; } } } <file_sep>/Assets/EventManager/EventManager.cs using System.Collections; using System.Collections.Generic; using UnityEngine; public class EventManager : MonoBehaviour { public delegate void Listener (); private static Dictionary<string, List<Listener>> listenerCallback = null; public static void AddListener(string eventName, Listener callback) { if (listenerCallback == null) { listenerCallback = new Dictionary<string, List<Listener>>(); } if (!listenerCallback.ContainsKey(eventName)) { listenerCallback.Add(eventName, new List<Listener>()); } // If already if (listenerCallback[eventName].Contains(callback)) { return; } listenerCallback[eventName].Add(callback); } public static void RemoveListener(string eventName, Listener callback) { if (listenerCallback == null) { return; } if (!listenerCallback.ContainsKey(eventName)) { return; } // If already listenerCallback[eventName].Remove(callback); } public static void HandleMessage(string eventName) { if (listenerCallback.ContainsKey(eventName)) { foreach (Listener callback in listenerCallback[eventName]) { if (callback == null) { continue; } callback(); } } } } <file_sep>/Assets/Entities/UpgradeController/UpgradeController.cs using UnityEngine; using System.Collections; public class UpgradeController : MonoBehaviour { private ThreshBehaviour thresh; private Score scoreController; private int rangeCost = 2; private int speedCost = 2; private int incomeCost = 2; private int rangeLevel = 0; private int speedLevel = 0; private int incomeLevel = 0; public int RangeCost { get { return rangeCost; } } public int SpeedCost { get { return speedCost; } } public int IncomeCost { get { return incomeCost; } } public int RangeLevel { get { return rangeLevel; } } public int SpeedLevel { get { return speedLevel; } } public int IncomeLevel { get { return incomeLevel; } } void Awake () { thresh = GameObject.FindObjectOfType<ThreshBehaviour> (); scoreController = GameObject.FindObjectOfType<Score>(); } #if UNITY_EDITOR void Update() { if (Input.GetKeyDown(KeyCode.W)) { Debug.Log("Upgrade cheat!"); UpgradeSpeed(); UpgradeIncome(); UpgradeRange(); } } #endif public bool UpgradeSpeed() { if (scoreController.UseScore(speedCost)) { thresh.speed += 0.5f; speedLevel++; speedCost *= 2; return true; } return false; } public bool UpgradeIncome() { if (scoreController.UseScore(incomeCost)) { thresh.value += 1; incomeLevel++; incomeCost *= 2; return true; } return false; } public bool UpgradeRange() { if (scoreController.UseScore(rangeCost)) { thresh.maxRange += 3f; rangeLevel++; rangeCost *= 2; return true; } return false; } } <file_sep>/Assets/Entities/Thresh/ThreshThrow.cs using System.Collections; using UnityEngine; public class ThreshThrow : MonoBehaviour { const string HOOK_THROW = "Throwing"; private ThreshBehaviour thresh; private Animator animator; void Awake() { thresh = GetComponentInParent<ThreshBehaviour>(); animator = GetComponent<Animator>(); EventManager.AddListener("OnHookCreated", this.OnHookCreated); EventManager.AddListener("OnHookDestroyed", this.OnHookDestroyed); } void OnDisable() { EventManager.RemoveListener("OnHookCreated", this.OnHookCreated); EventManager.RemoveListener("OnHookDestroyed", this.OnHookDestroyed); } void OnHookCreated() { animator.SetBool(HOOK_THROW, true); } void OnHookDestroyed() { animator.SetBool(HOOK_THROW, false); } void HookThrow() { thresh.HookThrow(); } } <file_sep>/Assets/Scripts/General.cs using UnityEngine; using UnityEngine.UI; using UnityEngine.EventSystems; using System.Collections; using System.Collections.Generic; public class General : MonoBehaviour { /// <summary> /// Cast a ray to test if Input.mousePosition is over any UI object in EventSystem.current. This is a replacement /// for IsPointerOverGameObject() which does not work on Android in 4.6.0f3 /// </summary> public static bool IsPointerOverUIObject() { PointerEventData eventDataCurrentPosition = new PointerEventData(EventSystem.current); eventDataCurrentPosition.position = new Vector2(Input.mousePosition.x, Input.mousePosition.y); List<RaycastResult> results = new List<RaycastResult>(); EventSystem.current.RaycastAll(eventDataCurrentPosition, results); return results.Count > 0; } /// <summary> /// Cast a ray to test if screenPosition is over any UI object in canvas. This is a replacement /// for IsPointerOverGameObject() which does not work on Android in 4.6.0f3 /// </summary> public static bool IsPointerOverUIObject(Canvas canvas, Vector2 screenPosition) { PointerEventData eventDataCurrentPosition = new PointerEventData(EventSystem.current); eventDataCurrentPosition.position = screenPosition; GraphicRaycaster uiRaycaster = canvas.gameObject.GetComponent<GraphicRaycaster>(); List<RaycastResult> results = new List<RaycastResult>(); uiRaycaster.Raycast(eventDataCurrentPosition, results); return results.Count > 0; } /// <summary> /// Cast a ray to test if screenPosition is over any UI object in canvas. This is a replacement /// for IsPointerOverGameObject() which does not work on Android in 4.6.0f3 /// </summary> public static Vector3 GetCameraSize () { float quadHeight = Camera.main.orthographicSize * 2.0f; float quadWidth = quadHeight * Screen.width / Screen.height; return new Vector3(quadWidth, quadHeight, 1); } } <file_sep>/Assets/LevelManager/LevelManager.cs using UnityEngine; using System.Collections; using UnityEngine.SceneManagement; public class LevelManager : MonoBehaviour { public void LoadNextLevel () { SceneManager.LoadScene(SceneManager.GetActiveScene().buildIndex + 1, LoadSceneMode.Single); } } <file_sep>/Assets/Entities/UpgradeController/UniqueUpgradeController.cs using UnityEngine; using UnityEngine.UI; using System.Collections; public class UniqueUpgradeController : MonoBehaviour { private ThreshBehaviour thresh; private Score scoreController; private int bounceCost = 2; private int multipleHookCost = 2; private int phaseCost = 2; public int BounceCost { get { return bounceCost; } } public int MultipleHookCost { get { return multipleHookCost; } } public int PhaseCost { get { return phaseCost; } } void Start () { thresh = GameObject.FindObjectOfType<ThreshBehaviour> (); scoreController = GameObject.FindObjectOfType<Score>(); } #if UNITY_EDITOR void Update() { if (Input.GetKeyDown(KeyCode.E)) { Debug.Log("Unique upgrade cheat!"); BounceUpgrade(); MultipleHooksUpgrade(); PhaseUpgrade(); } } #endif public bool BounceUpgrade() { if(thresh.bounce) return true; if (scoreController.UseScore(bounceCost)) { thresh.bounce = true; return true; } return false; } public bool MultipleHooksUpgrade() { if (thresh.multipleHooks) return true; if (scoreController.UseScore(multipleHookCost)) { thresh.multipleHooks = true; return true; } return false; } public bool PhaseUpgrade() { if (thresh.phase) return true; if (scoreController.UseScore(phaseCost)) { thresh.phase = true; return true; } return false; } }
f47ab02916fb6f91ce117a83f230cd8b01f9adef
[ "C#" ]
18
C#
GrupoOperacionalRDO/WebThreshGame_gamejam
f986ce8b4040f6d77c745fb6ce49b6600563a50a
11aeffd0ca314d4c07977d35aaa4cf6f5c092b1b
refs/heads/main
<file_sep>module Customers::ReceiversHelper end <file_sep>class Users::ReceiversController < ApplicationController end <file_sep>class Users::CartProductsController < ApplicationController end <file_sep>class CreateOrdres < ActiveRecord::Migration[5.2] def change create_table :ordres do |t| t.integer :customer_id t.integer :shipping_cost t.integer :total_payment t.integer :how_to_pay t.integer :order_status t.string :postal_code t.string :address t.string :receiver_name t.datetime :created_at t.datetime :updated_at t.timestamps end end end <file_sep>class CreateOrderedProducts < ActiveRecord::Migration[5.2] def change create_table :ordered_products do |t| t.integer :product_id t.integer :order_id t.integer :count t.integer :tax_included_price t.string :production_status t.datetime :created_at t.datetime :updated_at t.timestamps end end end <file_sep>class ApplicationController < ActionController::Base before_action :configure_permitted_parameters, if: :devise_controller? def after_sign_in_path_for(resource) if current_admin admins_products_path else root_path end end def after_sign_out_path_for(resource) case params[:logout] when "0" root_path when "1" new_admin_session_path end end protected def configure_permitted_parameters devise_parameter_sanitizer.permit(:sign_up, keys: [:family_name, :first_name, :family_name_kana, :first_name_kana, :phone_number, :postal_code, :address ]) end end <file_sep>class Product < ApplicationRecord belongs_to :product_type has_many :cart_products has_many :ordered_products attachment :image end <file_sep>class Admins::ProductTypesController < ApplicationController def index @product_type = ProductType.new @product_types = ProductType.all end def create @product_type = ProductType.new(product_type_params) if @product_type.save redirect_to admins_product_types_path end end def edit @product_type = ProductType.find(params[:id]) end def update @product_type = ProductType.find(params[:id]) if @product_type.update(product_type_params) redirect_to admins_product_types_path end end private def product_type_params params.require(:product_type).permit(:name) end end <file_sep>class Ordre < ApplicationRecord end <file_sep>class Admins::OrderedProductsController < ApplicationController end <file_sep>class Admins::UsersController < ApplicationController def index @users = User.all end def show @user = User.find(params[:id]) end def edit @user = User.find(params[:id]) end def update @user = User.find(params[:id]) if @user.update(user_params) redirect_to admins_user_path(@user.id) end end private def user_params params.require(:user).permit(:family_name, :first_name, :family_name_kana, :first_name_kana, :postal_code, :address, :phone_number, :email, :is_deleted) end end <file_sep>Rails.application.routes.draw do devise_for :users, controllers: { registrations: 'users/registrations', sessions: 'users/sessions', passwords: '<PASSWORD>' } devise_for :admins, controllers: { registrations: 'admins/registrations', sessions: 'admins/sessions', passwords: '<PASSWORD>' } # For details on the DSL available within this file, see http://guides.rubyonrails.org/routing.html root to: 'homes#top' get '/about' => 'homes#about' namespace :admins do resources :users, except:[:new, :create, :destory] resources :products, except:[:destory] resources :product_types, except:[:new, :show, :destory] resources :orders, only:[:index, :show, :update] resources :ordered_products, only:[:update] end scope module: :users do resource :users, only:[:show] do collection do get 'unsubscribe' patch 'withdraw' end end resources :products, only:[:index, :show] resources :cart_products, except:[:new, :show, :edit] do collection do delete 'destory_all' end end resources :receivers, except:[:new, :show] resources :orders, except:[:edit, :update, :destory] do collection do post 'comfirm' get 'finish' end end end end <file_sep>class Users::OrdersController < ApplicationController end
0629eb25e4c76994e2b6eb4952900b46b2afac52
[ "Ruby" ]
13
Ruby
hayate112/ECsite
10536fe9276b358b8db777d03eed53242d44e4cb
e024ca6cb356e4bd4fb9fe04ca8a6bf7f348d2ef
refs/heads/master
<repo_name>21parkkyu/airbnb-clone<file_sep>/README.md # Airbnb Clone Cloning Airbnb with Python,Django,Tailwind and more...<file_sep>/conversations/urls.py from django.urls import path from . import views app_name = "conversations" urlpatterns = [path("go/<int:a_pk>/<int:b_pk>", views.go_conversation, name="go")] <file_sep>/conversations/migrations/0003_auto_20191120_1331.py # Generated by Django 2.2.5 on 2019-11-20 04:31 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('conversations', '0002_auto_20191120_1207'), ] operations = [ migrations.AlterField( model_name='message', name='message', field=models.TextField(), ), ] <file_sep>/conversations/views.py from django.db.models import Q from django.shortcuts import render from users import models as user_models from . import models def go_conversation(request, a_pk, b_pk): user_one = user_models.User.objects.get_or_none(pk=a_pk) user_two = user_models.User.objects.get_or_none(pk=b_pk) if user_one is not None and user_two is not None: conversation = models.Conversation.objects.get( Q(participants=user_one) & Q(participants=user_two) ) print(conversation)
f62a3efb9668b14c43854956892bcad17520d0b8
[ "Markdown", "Python" ]
4
Markdown
21parkkyu/airbnb-clone
9f8b5ac89b7dba4eeea6e104614faf8fd35592e6
0768912455283b2237fa7d001070a62400fbd067
refs/heads/main
<repo_name>nguyenhuuthang-tdc/UX_UI-practice<file_sep>/personal_CV/index.html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <link rel="stylesheet" type="text/css" href="font-awesome/css/font-awesome.min.css"> <link rel="stylesheet" type="text/css" href="css/style.css"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Layout</title> </head> <body> <section class="header" id="section1"> <div class="container"> <nav class="flex between item-center"> <div class="brand flex item-center"> <i class="fa fa-spinner"></i> <p>Coders</p> </div> <ul class="flex navbar"> <li><a href="#section1">Home</a></li> <li><a href="#section2">About</a></li> <li><a href="#section3">Service</a></li> <li><a href="#section4">Pages</a></li> <li><a href="#section5">Blog</a></li> </ul> <button class="btn btn-primary">Contact</button> </nav> <div class="me flex item-center justity-center"> <div class="left"> <img src="image/man.png" alt="photo" width="500" height="500"> </div> <div class="right"> <h3><NAME></h3> <h2>I'm a FullStack <span>Programmer</span></h2> <p>Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.</p> <button class="btn btn-second">Download CV</button> </div> </div> </div> </section> <section class="about" id="section2"> <div class="container"> <div class="say-hi flex item-center between"> <div class="left basis-40"> <img src="image/3.jpg" width="300" height="350"> </div> <div class="rightt basis-60"> <h2>About <span>Me</span></h2> <h3>Hello! I'm <NAME>.</h3> <p>Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged.</p> <p>It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged.</p> <div class="online"> <i class="fa fa-facebook-official" aria-hidden="true"></i> <i class="fa fa-instagram active" aria-hidden="true"></i> <i class="fa fa-twitter" aria-hidden="true"></i> <i class="fa fa-youtube-play" aria-hidden="true"></i> <i class="fa fa-gitlab" aria-hidden="true"></i> </div> </div> </div> </div> </section> <section class="service" id="section3"> <div class="container"> <div class="heading-text"> <h1><span>Our </span>Services</h1> <p>We provide high stander clean websites for your business solutions</p> </div> <div class="service-content"> <div class="path"> <i class="fa fa-pencil" aria-hidden="true"></i> <div class="content"> <h2>Graphic Design</h2> <p>Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s.</p> </div> </div> <div class="path"> <i class="fa fa-code" aria-hidden="true"></i> <div class="content"> <h2>Web Development</h2> <p>Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s.</p> </div> </div> <div class="path"> <i class="fa fa-briefcase" aria-hidden="true"></i> <div class="content"> <h2>Media Marketing</h2> <p>Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s.</p> </div> </div> <div class="path"> <i class="fa fa-desktop" aria-hidden="true"></i> <div class="content"> <h2>Web Design</h2> <p>Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s.</p> </div> </div> <div class="path"> <i class="fa fa-film" aria-hidden="true"></i> <div class="content"> <h2>Motion Graphic</h2> <p>Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s.</p> </div> </div> <div class="path"> <i class="fa fa-mobile" aria-hidden="true"></i> <div class="content"> <h2>Apps</h2> <p>Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s.</p> </div> </div> </div> </div> </section> <section class="freelancer"> <div class="container"> <h2>I Am Available For Freelancer.</h2> <p>We provide high stander clean websites for your business solutions</p> <button class="btn btn-primary">Download CV</button> </div> </section> <section class="client"> <div class="container"> <div class="heading-text"> <h1><span>Our </span>Client</h1> <p>We provide high stander clean websites for your business solutions</p> </div> <div class="slider"> <div class="slides flex"> <input type="radio" name="radio-btn" id="radio1"> <input type="radio" name="radio-btn" id="radio2"> <input type="radio" name="radio-btn" id="radio3"> <input type="radio" name="radio-btn" id="radio4"> <div class="slide first"> <img src="image/1.jpg" width="150" height="150"> <p>"Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s"</p> <h5>- <NAME> Company ABC</h5> </div> <div class="slide"> <img src="image/2.jpg" width="150" height="150"> <p>"Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s"</p> <h5>- <NAME> Company ABC</h5> </div> <div class="slide"> <img src="image/3.jpg" width="150" height="150"> <p>"Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s"</p> <h5>- <NAME> Company ABC</h5> </div> <div class="slide"> <img src="image/4.jpg" width="150" height="150"> <p>"Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s"</p> <h5>- <NAME> Company ABC</h5> </div> </div> </div> <div class="navigation-manual flex justity-center"> <label for="radio1" id="lb1" class="manual-btn"></label> <label for="radio2" id="lb2" class="manual-btn"></label> <label for="radio3" id="lb3" class="manual-btn"></label> <label for="radio4" id="lb4" class="manual-btn"></label> </div> </div> </section> <section class="work"> <div class="container"> <div class="heading-text"> <h1><span>Our </span>Works</h1> <p>We provide high stander clean websites for your business solutions</p> </div> <div class="img-grid"> <div class="img-box"> <div class="contents flex justity-center item-center"> <h3>Category</h3> <p>Web Development</p> </div> <img src="image/5.jpg"> </div> <div class="img-box"> <div class="contents flex justity-center item-center"> <h3>Category</h3> <p>Web Development</p> </div> <img src="image/6.jpg"> </div> <div class="img-box"> <div class="contents flex justity-center item-center"> <h3>Category</h3> <p>Web Development</p> </div> <img src="image/7.jpg"> </div> <div class="img-box"> <div class="contents flex justity-center item-center"> <h3>Category</h3> <p>Web Development</p> </div> <img src="image/8.jpg"> </div> <div class="img-box"> <div class="contents flex justity-center item-center"> <h3>Category</h3> <p>Web Development</p> </div> <img src="image/9.jpg"> </div> <div class="img-box"> <div class="contents flex justity-center item-center"> <h3>Category</h3> <p>Web Development</p> </div> <img src="image/10.jpg"> </div> </div> </div> </section> <section class="blog" id="section5"> <div class="container"> <div class="heading-text"> <h1><span>Our </span>Blog</h1> <p>We provide high stander clean websites for your business solutions</p> </div> <div class="box flex justity-center item-center"> <div class="element"> <img src="image/6.jpg"> <div class="text"> <h3>Occusamus et iusto odio</h3> <h4>May 12 2017</h4> <p>Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s</p> <a href="#">Read More</a> </div> </div> <div class="element"> <img src="image/8.jpg"> <div class="text"> <h3>Occusamus et iusto odio</h3> <h4>May 12 2017</h4> <p>Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s</p> <a href="#">Read More</a> </div> </div> <div class="element"> <img src="image/6.jpg"> <div class="text"> <h3>Occusamus et iusto odio</h3> <h4>May 12 2017</h4> <p>Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s</p> <a href="#">Read More</a> </div> </div> </div> </div> </section> <section class="contact"> <div class="container"> <div class="heading-text"> <h1><span>Contact </span>Us</h1> <p>We provide high stander clean websites for your business solutions</p> </div> <div class="card-wrapper flex justity-center item-center"> <div class="card"> <i class="fa fa-mobile" aria-hidden="true"></i> <div class="address"> <h3>Call Us On</h3> <p>+84844370255</p> </div> </div> <div class="card"> <i class="fa fa-envelope-o" aria-hidden="true"></i> <div class="address"> <h3>Email Us At</h3> <p><EMAIL></p> </div> </div> <div class="card"> <i class="fa fa-building-o" aria-hidden="true"></i> <div class="address"> <h3>Visit Office</h3> <p>53 Vo Van Ngan St , Linh Chieu Ward , Thu Duc District , HCM City</p> </div> </div> </div> <form action="#"> <div class="input-field"> <div class="name flex between"> <input type="text" name="name" placeholder="Your Name *" required> <input type="email" name="email" placeholder="Your Email *" required> </div> <div class="subject"> <input type="text" name="subject" placeholder="Your Subject *" required> </div> <textarea placeholder="Your Message" cols="30" rows="10" required></textarea> </div> <div class="btn-input"> <button type="submit" class="btn btn-primary">Send</button> </div> </form> </div> </section> <footer class="footer"> <div class="container"> <div class="brand flex justity-center below"> <i class="fa fa-spinner"></i> <p>Coders</p> </div> <div class="icon"> <i class="fa fa-facebook" aria-hidden="true"></i> <i class="fa fa-twitter" aria-hidden="true"></i> <i class="fa fa-instagram" aria-hidden="true"></i> <i class="fa fa-youtube" aria-hidden="true"></i> <i class="fa fa-mobile" aria-hidden="true"></i> <p>CopyRight 2020@ Name PSD Tutorials All right</p> </div> </div> </footer> <script src="js/jquery-3.3.1.min.js"></script> <script src="js/bootstrap.min.js"></script> <script src="js/main.js"></script> <script type="text/javascript"> count = 1; setInterval(function(){ if(count > 4) { count = 1; } document.getElementById('radio' + count).checked = true; if(count == 1) { document.getElementById('lb' + count).style.background = "var(--primary)"; document.getElementById('lb' + eval(count+3)).style.background = "none"; } else { document.getElementById('lb' + count).style.background = "var(--primary)"; document.getElementById('lb' + eval(count-1)).style.background = "none"; } count++; },3000); </script> </body> </html><file_sep>/starbucks/public/js/main.js //tao bien //3 thumb let thumb = document.querySelectorAll(".thumb-item"); //img big var img = document.querySelector(".img"); //circle var circle = document.querySelector(".circle"); //logo var logo_image = document.querySelector(".logo"); //brand nme var brand_name = document.querySelector(".br-name"); //btn learn var btn = document.querySelector(".btn"); // hàm thay đổi màu và src ảnh function changeColorImage(color,logo,src) { img.src = src circle.style.background = color brand_name.style.color = color btn.style.background = color logo_image.src = logo } <file_sep>/responsive/js/main.js $('.nav-menu a').on('click',function(e) { if(this.hash !== '') { e.preventDefault(); const hash = this.hash; $('html, body').animate({ scrollTop: $(hash).offset().top }, 1000); } }); /* SCROLL REVEAL ANIMATION */ const sr = ScrollReveal({ origin : 'top', distance : '80px', duration : '500', reset : 'true', }) /* SCROLL HOME */ sr.reveal('.home_title', {}) sr.reveal('.home_img', {delay:200}) sr.reveal('.link_info', {delay:300}) sr.reveal('.btn',{delay:200}) /* SCROLL ABOUT */ sr.reveal('.about_title', {}) sr.reveal('.about_img', {delay:100}) sr.reveal('.about_text', {delay:200}) /* SCROLL SKILL */ sr.reveal('.skill_title', {}) sr.reveal('.skill_sub_title', {delay:100}) sr.reveal('.txt', {delay:200}) sr.reveal('.skill_data', {interval:50}) sr.reveal('.skill_img', {delay:200}) /* SCROLL WORK */ sr.reveal('.work_title', {}) sr.reveal('.work_img', {interval:50}) /* SCROLL CONTACT */ sr.reveal('.contact_title', {}) sr.reveal('.contact_input', {interval:80}) <file_sep>/README.md # UX_UI-practice templates HTML were written by HTML CSS &amp; JS
85f4a6ef243709786bd198b8598d7bd252ed1eb5
[ "JavaScript", "HTML", "Markdown" ]
4
HTML
nguyenhuuthang-tdc/UX_UI-practice
cf1d7e2ed0a100cc1b1326cae3f8b513f744fefa
8ff05c5e23432802990be1e999370ee1c97103a5
refs/heads/master
<repo_name>namoraghavay/jagadgururambhadracharya.org<file_sep>/Portal/src/Repos/NHibernateSessionFactory.cs using System; using guruji.Domain; using guruji.ViewServices; using NHibernate; using NHibernate.Cfg; namespace guruji.Repos { public class NHibernateSessionFactory : IDisposable { private readonly ISessionFactory sessionFactory; private static readonly NHibernateSessionFactory instance = new NHibernateSessionFactory(); public static NHibernateSessionFactory Instance() { return instance; } private NHibernateSessionFactory() { NHibernate.Cfg.Environment.UseReflectionOptimizer = false; var cfg = new Configuration(); cfg.SetProperty("connection.connection_string", Config.PortalConnectionString); cfg.SetProperty("connection.provider", "NHibernate.Connection.DriverConnectionProvider"); cfg.SetProperty("connection.driver_class", "NHibernate.Driver.MySqlDataDriver"); cfg.SetProperty("dialect", "NHibernate.Dialect.MySQL5Dialect"); cfg.SetProperty("proxyfactory.factory_class", "NHibernate.ByteCode.Castle.ProxyFactoryFactory, NHibernate.ByteCode.Castle"); cfg.SetProperty("show_sql", Config.LogSqlQueries); cfg.AddAssembly(typeof(Event).Assembly); sessionFactory = cfg.BuildSessionFactory(); } public IEventRepository EventRepository { get { return new EventRepository(sessionFactory); } } public INewsRepository NewsRepository { get { return new NewsRepository(sessionFactory); } } public IUserRoleRepository UserRoleRepository { get { return new UserRoleRepository(sessionFactory); } } public IUserRepository UserRepository { get { return new UserRepository(sessionFactory); } } public void Dispose() { sessionFactory.Dispose(); } public void Close() { sessionFactory.Close(); } } } <file_sep>/Portal/src/Repos/NewsRepository.cs using System.Collections.Generic; using guruji.Domain; using NHibernate; namespace guruji.Repos { public class NewsRepository : Repository, INewsRepository { public NewsRepository(ISessionFactory sessionFactory) : base(sessionFactory) { } public NewsItem GetNewsItemById(int id) { return Load<NewsItem>(id); } public IList<NewsItem> GetNewsItems() { var newsItems = RunNamedQuery<NewsItem>("load.important.news.items", null); foreach (var item in newsItems) { item.NewsContent.DescriptionHtml.Replace("<![CDATA[", string.Empty).Replace("]]>", string.Empty); } return newsItems; } public IList<NewsItem> GetArchivedNewsItems() { return RunNamedQuery<NewsItem>("load.archived.news.items", null); } } public interface INewsRepository : IRepository { NewsItem GetNewsItemById(int id); IList<NewsItem> GetNewsItems(); IList<NewsItem> GetArchivedNewsItems(); } } <file_sep>/Portal/src/Controllers/PortalAuthorizeAttribute.cs using System; using System.Web; using System.Web.Mvc; using guruji.Domain; namespace guruji.Controllers { public class PortalAuthorizeAttribute : AuthorizeAttribute { public new UserRole Roles; public PortalAuthorizeAttribute() { Order = 2; } protected override bool AuthorizeCore(HttpContextBase httpContext) { if (httpContext == null) throw new ArgumentNullException("httpContext"); return IsAuthorized((new PortalSession().PortalUser).Role); } public bool IsAuthorized(UserRole role) { return (Roles & role) == role; } protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext) { base.HandleUnauthorizedRequest(filterContext); throw new UnauthorizedException(); } } public class UnauthorizedException : HttpException { public UnauthorizedException() : base(401, "UnAuthorized") { } } }<file_sep>/Portal/src/ViewModels/HtmlPageViewModel.cs namespace guruji.ViewModels { public class HtmlPageViewModel { public object Html { get; set; } public string PageName { get; set; } public string BrowserTitle { get { const string TITLE = "Rambhadracharya - "; if (PageName == "biography") return TITLE + "Biography"; if (PageName == "literatureHome") return TITLE + "Literature"; if (PageName == "awards") return TITLE + "Awards and Prizes"; if (PageName == "virudavali") return TITLE + "Virudavali"; if (PageName == "jrhu") return TITLE + "Jagadguru Rambhadracharya Handicapped University"; if (PageName == "biographyTulsidas") return TITLE + "Biography of <NAME> Ji"; if (PageName == "hanumanChalisa") return TITLE + "Hanuman Chalisa"; if (PageName == "raghavSeva") return TITLE + "Raghav Seva - Vedic tradition"; if (PageName == "manas") return TITLE + "Shri Ramcharimanas Introduction and Download"; return TITLE; } } } }<file_sep>/Portal/src/Controllers/AboutGurujiController.cs using System.Web.Mvc; namespace guruji.Controllers { public class AboutGurujiController : BaseController { public ActionResult Biography() { return HtmlViewFor("biography"); } public ActionResult LiteratureHome() { return HtmlViewFor("literatureHome"); } public ActionResult Awards() { return HtmlViewFor("awards"); } public ActionResult Virudavali() { return HtmlViewFor("virudavali"); } } }<file_sep>/Portal/src/Domain/Contact.cs using System; namespace guruji.Domain { [Serializable] public class Contact { public string Name { get; set; } public string PhoneNumber { get; set; } public string Email { get; set; } } }<file_sep>/Portal/src/Services/ContentService.cs using System; using System.Collections.Generic; using guruji.Domain; using guruji.Repos; namespace guruji.Services { public interface IContentService { IList<Event> GetUpcomingEvents(); IList<NewsItem> GetNewsItems(); IList<NewsItem> GetArchivedNewsItems(); void SaveOrUpdateEvent(Event evt); void DeleteEvent(Event evt); Event LoadEventById(Int32 id); void SaveOrUpdateNews(NewsItem newsItem); void DeleteNews(NewsItem newsItem); NewsItem LoadNewsById(Int32 id); IList<Event> GetUpcomingKathas(); } public class ContentService : IContentService { public IUserRoleRepository userRoleRepository; public IEventRepository eventRepository; public INewsRepository newsItemRepository; private static readonly IContentService instance = new ContentService(NHibernateSessionFactory.Instance()); public static IContentService Instance() { return instance; } private ContentService(NHibernateSessionFactory repositoryFactory) { eventRepository = repositoryFactory.EventRepository; newsItemRepository = repositoryFactory.NewsRepository; userRoleRepository = repositoryFactory.UserRoleRepository; } public IList<Event> GetUpcomingEvents() { return eventRepository.GetAllUpcomingEvents(); } public IList<Event> GetUpcomingKathas() { return eventRepository.GetAllUpcomingKathas(); } public IList<NewsItem> GetNewsItems() { return newsItemRepository.GetNewsItems(); } public IList<NewsItem> GetArchivedNewsItems() { return newsItemRepository.GetArchivedNewsItems(); } public void SaveOrUpdateEvent(Event evt) { eventRepository.SaveOrUpdate(evt); } public void DeleteEvent(Event evt) { eventRepository.Delete(evt); } public Event LoadEventById(Int32 evtId) { return eventRepository.Load<Event>(evtId); } public void SaveOrUpdateNews(NewsItem newsItem) { newsItemRepository.SaveOrUpdate(newsItem); } public void DeleteNews(NewsItem newsItem) { newsItemRepository.Delete(newsItem); } public NewsItem LoadNewsById(Int32 newsId) { return newsItemRepository.Load<NewsItem>(newsId); } } } <file_sep>/Portal/test/IntegrationTests/Repos/NewsItemTest.cs //using System; //using Castle.Facilities.NHibernateIntegration; //using guruji.Domain; //using guruji.Repos; //using guruji.WindsorConfig; //using NUnit.Framework; // //namespace PortalTests.IntegrationTests.Repos //{ // [TestFixture] // public class NewsItemTest // { // private ISessionManager sessionManager; // private INewsItemRepository repository; // // [SetUp] // public void SetUp() // { // sessionManager = PortalWindsorContainerFactory.GetContainer().Resolve<ISessionManager>(); // repository = new NewsItemRepository(sessionManager); // } // // [Test] // public void SaveNewsItem() // { // var newsItem = new NewsItem // { // Importance = Importance.H, // NewsDate = DateTime.Today.AddDays(-4), // Title = "<NAME>a met <NAME> at Rashtrapati Bhavan", // NewsContent = new NewsContent // { // DescriptionHtmlFileName = "rashtrapati_bhavan.html", // SourceCuttingImage = "rashtrapati_bhavan.jpg", // SourceName = "<NAME>", // Teaser = "<NAME> awarding <NAME>" // } // }; // repository.Save(newsItem); // Assert.That(repository.GetNewsItems().Count, Is.EqualTo(4)); // } // // [Test] // public void SaveArchivedNewsItem() // { // var archivedNewsItem = new NewsItem // { // Importance = Importance.A, // NewsDate = DateTime.Today.AddDays(-6), // Title = "Jagadguru Rambhadracharya met <NAME> at Rashtrapati Bhavan", // NewsContent = new NewsContent // { // DescriptionHtmlFileName = "rashtrapati_bhavan.html", // SourceCuttingImage = "rashtrapati_bhavan.jpg", // SourceName = "<NAME>", // Teaser = "<NAME> awarding <NAME>" // } // }; // repository.Save(archivedNewsItem); // Assert.That(repository.GetArchivedNewsItems().Count, Is.EqualTo(1)); // } // } //} <file_sep>/Portal/src/Domain/NewsItem.cs using System; using guruji.Common; namespace guruji.Domain { public class NewsItem : BaseEntity { public virtual string Title { get; set; } protected internal virtual char ImportanceDb { get; set; } public virtual DateTime NewsDate { get; set; } protected internal virtual string NewsContentXml { get; set; } public virtual Importance Importance { get { return (Importance)Enum.Parse(typeof(Importance), ImportanceDb.ToString(), true); } set { ImportanceDb = Enum.GetName(typeof(Importance), value).ToCharArray()[0]; } } public virtual NewsContent NewsContent { get { return new Serializer().Deserialize<NewsContent>(NewsContentXml); } set { NewsContentXml = new Serializer().Serialize(value); } } } }<file_sep>/Portal/src/Repos/EventRepository.cs using System.Collections.Generic; using guruji.Domain; using NHibernate; namespace guruji.Repos { public class EventRepository : Repository, IEventRepository { public EventRepository(ISessionFactory sessionFactory) : base(sessionFactory) { } public Event GetEventById(int id) { return Load<Event>(id); } public IList<Event> GetAllUpcomingEvents() { return RunNamedQuery<Event>("load.upcoming.events", null); } public IList<Event> GetAllUpcomingKathas() { return RunNamedQuery<Event>("load.upcoming.kathas", null); } public void SaveOrUpdate(Event evt) { base.SaveOrUpdate(evt); } } public interface IEventRepository : IRepository { Event GetEventById(int id); IList<Event> GetAllUpcomingEvents(); void SaveOrUpdate(Event evt); IList<Event> GetAllUpcomingKathas(); } } <file_sep>/Portal/src/ViewModels/EventsViewModel.cs using System.Collections.Generic; using guruji.Domain; namespace guruji.ViewModels { public class EventsViewModel { public IList<Event> Kathas { get; set; } public IList<Event> Events { get; set; } public EventsKathasTabs DefaultTab { get; set; } } public enum EventsKathasTabs { Katha, Events } } <file_sep>/Portal/src/Mappers/EventMapper.cs using System; using guruji.Domain; using guruji.ViewModels; namespace guruji.Mappers { public class EventMapper { public Event MapFormToDomain(EventForm form) { return new Event { Id = form.Id, Title = form.Title, IsKatha = form.IsKatha, EventBeginDate = form.EventBeginDate, EventEndDate = form.EventEndDate, EventContent = form.EventContent, TelecastBeginDate = form.TelecastBeginDate, TelecastEndDate = form.TelecastEndDate, TelecastContent = form.TelecastContent, Importance = (Importance)Enum.Parse(typeof(Importance), form.Importance) }; } } }<file_sep>/Portal/src/ViewServices/FileService.cs using System.IO; namespace guruji.ViewServices { public interface IFileService { bool Exists(string path); string Contents(string path); } public class FileService : IFileService { public bool Exists(string fileSystemPath) { return File.Exists(fileSystemPath); } public string Contents(string fileSystemPath) { return File.ReadAllText(fileSystemPath); } } }<file_sep>/Portal/src/Controllers/HomePageController.cs using System.Collections.Generic; using System.Text; using System.Web.Mvc; using guruji.Domain; using guruji.Services; using guruji.ViewModels; using guruji.ViewServices; using System.Linq; namespace guruji.Controllers { public class HomePageController : BaseController { private readonly IContentService contentService = ContentService.Instance(); public ActionResult Home(string landingPageName) { var upcomingKathas = contentService.GetUpcomingKathas(); var newsItems = contentService.GetNewsItems(); var ticker = BuildNewsTicker(upcomingKathas); var homePageViewModel = new HomePageViewModel { UpcomingEvent = upcomingKathas == null ? null : upcomingKathas.First(), LatestNews = newsItems.First(), Ticker = ticker }; return View("HomePage", homePageViewModel); } private string BuildNewsTicker(IList<Event> kathas) { var ticker = new StringBuilder("|| "); foreach (var k in kathas) { ticker.Append(k.Title).Append(" from ").Append(k.EventBeginDate.ToString(Config.DatePattern)).Append(" to ") .Append(k.EventEndDate.ToString(Config.DatePattern)).Append(" at ").Append(k.EventContent.Location); if (k.TelecastContent != null) { ticker.Append(". " + ((k.TelecastContent.IsLive) ? "Live" : "Recorded") + " Telecast on " + k.TelecastContent.ChannelName); } ticker.Append(" || "); } return ticker.ToString(); } } }<file_sep>/Portal/src/Domain/BaseEntity.cs using System; namespace guruji.Domain { public class BaseEntity { public virtual Int32 Id { get; set; } } }<file_sep>/Portal/src/WindsorConfig/PortalWindsorContainerConfig.cs using System.Collections.Generic; using System.Reflection; using System.Web.Mvc; using Castle.Core; using Castle.MicroKernel.Registration; using Castle.Windsor; using guruji.Common; using guruji.Controllers; using guruji.Repos; using guruji.Services; using guruji.ViewServices; namespace guruji.WindsorConfig { public class PortalWindsorContainerConfig { public static WindsorContainer container = WindsorContainerFactory.Container; public PortalWindsorContainerConfig() { Configure(); } public WindsorContainer Container { get { return container; } } public void Configure() { NHibernateFacility.Configure(Container, new List<string> { "guruji" }); Container.AddComponentLifeStyle<IPortalSession, PortalSession>(LifestyleType.Singleton); Container.AddComponentLifeStyle<IContentService, ContentService>(LifestyleType.Singleton); Container.AddComponentLifeStyle<IRepository, Repository>(LifestyleType.Singleton); Container.AddComponentLifeStyle<IUserRepository, UserRepository>(LifestyleType.Singleton); Container.AddComponentLifeStyle<IProfileService, ProfileService>(LifestyleType.Singleton); Container.AddComponentLifeStyle<IUserRoleRepository, UserRoleRepository>(LifestyleType.Singleton); Container.AddComponentLifeStyle<IEventRepository, EventRepository>(LifestyleType.Singleton); Container.AddComponentLifeStyle<INewsItemRepository, NewsItemRepository>(LifestyleType.Singleton); Container.AddComponentLifeStyle<ILoginHandler, LoginHandler>(LifestyleType.Singleton); Container.AddComponentLifeStyle<Config, Config>(LifestyleType.Singleton); var controllers = AllTypes.Of<Controller>().FromAssembly(Assembly.GetExecutingAssembly()); Container.Register(controllers.Configure(c => c.LifeStyle.Transient.Named(c.Implementation.Name.ToLower()))); Container.AddComponentLifeStyle<IFileService, FileService>(LifestyleType.Singleton); Container.AddComponentLifeStyle<IControllerFileService, ControllerFileService>(LifestyleType.Singleton); Container.AddComponentLifeStyle<IViewLocationCache, DefaultViewLocationCache>(LifestyleType.Singleton); Container.AddComponentLifeStyle<IViewEngine, PortalViewEngine>(LifestyleType.Singleton); } } }<file_sep>/Portal/src/ViewModels/NewsViewModel.cs using System.Collections.Generic; using guruji.Domain; namespace guruji.ViewModels { public class NewsViewModel { public IList<NewsItem> MediaNews { get; set; } public IList<NewsItem> TulsipeethNews { get; set; } public NewsTabs DefaultTab { get; set; } } public enum NewsTabs { Tulsipeeth, Media } } <file_sep>/Portal/src/Repos/UserRoleRepository.cs using guruji.Domain; using NHibernate; namespace guruji.Repos { public class UserRoleRepository : Repository, IUserRoleRepository { public UserRoleRepository(ISessionFactory sessionFactory) : base(sessionFactory) { } public Role GetRoleById(int id) { return Load<Role>(id); } } public interface IUserRoleRepository : IRepository { Role GetRoleById(int id); } } <file_sep>/Portal/src/WindsorConfig/PortalWindsorContainerFactory.cs using Castle.Windsor; namespace guruji.WindsorConfig { public static class PortalWindsorContainerFactory { private static readonly PortalWindsorContainerConfig Config; static PortalWindsorContainerFactory() { Config = new PortalWindsorContainerConfig(); } public static WindsorContainer GetContainer() { return Config.Container; } } }<file_sep>/Portal/test/IntegrationTests/Repos/EventTest.cs //using System; //using System.Collections.Generic; //using Castle.Facilities.NHibernateIntegration; //using guruji.Domain; //using guruji.Repos; //using guruji.WindsorConfig; //using NUnit.Framework; // //namespace PortalTests.IntegrationTests.Repos //{ // [TestFixture] // public class EventTest // { // private ISessionManager sessionManager; // private IEventRepository repository; // // [SetUp] // public void SetUp() // { // sessionManager = PortalWindsorContainerFactory.GetContainer().Resolve<ISessionManager>(); // repository = new EventRepository(sessionManager); // } // // [Test] // public void TestSaveEvent() // { // var eventToPersist = new Event // { // Title = "Valmikiya Ramayan at Kanpur", // IsKatha = true, // EventBeginDate = DateTime.Today.AddDays(8), // EventEndDate = DateTime.Today.AddDays(20), // Importance = Importance.H, // TelecastBeginDate = DateTime.Today, // TelecastEndDate = DateTime.Today.AddDays(1), // EventContent = new EventContent // { // ContactDetail = new List<Contact> // { // new Contact // { // Email = "<EMAIL>", // Name = "abc", // PhoneNumber = "32323453434" // }, // new Contact // { // Email = "<EMAIL>", // Name = "sds", // PhoneNumber = "43434343434" // } // }, // ContentPageStyle = "Normal", // Descrption = "This katha will be based on <NAME> along with <NAME>", // Location = "Motijheel, Kanpur", // Image_large = "valmik_ramayan_motijheel_large.png", // Image_small = "valmik_ramayan_motijheel_small.png", // Teaser = "<NAME>" // }, // TelecastContent = new TelecastContent // { // ChannelName = "Sanskar", // IsLive = true // } // }; // repository.Save(eventToPersist); // var events = repository.GetAllUpcomingEvents(); //// Assert.That(events.Count, Is.EqualTo(1)); // } // } //} <file_sep>/Portal/src/Repos/UserRepository.cs using guruji.Domain; using NHibernate; namespace guruji.Repos { public class UserRepository : Repository, IUserRepository { public UserRepository(ISessionFactory sessionFactory) : base(sessionFactory) { } public PortalUser LoadUser(string emailId) { return RunNamedQuery<PortalUser>("load.by.email", "email", emailId); } public void DeleteUser(string emailId) { var user = LoadUser(emailId); Delete(user); } public void DisableUser(string emailId) { var user = LoadUser(emailId); user.Status = UserStatus.Deleted; SaveOrUpdate(user); } } public interface IUserRepository : IRepository { void DeleteUser(string emailId); PortalUser LoadUser(string emailAddress); void DisableUser(string emailId); } } <file_sep>/Portal/src/ViewModels/EventForm.cs using System; using guruji.Domain; namespace guruji.ViewModels { public class EventForm { public Int32 Id { get; set; } public string Title { get; set; } public bool IsKatha { get; set; } public DateTime EventBeginDate { get; set; } public DateTime EventEndDate { get; set; } public EventContent EventContent { get; set; } public TelecastContent TelecastContent { get; set; } public DateTime TelecastBeginDate { get; set; } public DateTime TelecastEndDate { get; set; } public string Importance { get; set; } } }<file_sep>/db/create_tables.sql CREATE TABLE `event` ( `ID` bigint(20) unsigned NOT NULL AUTO_INCREMENT, `TITLE` varchar(100) NOT NULL, `IS_KATHA` char(1) NOT NULL DEFAULT 'N', `IMPORTANCE` char(1) DEFAULT 'M', `EVT_CONTENT` longtext, `EVT_BEGIN_DATE` datetime NOT NULL, `EVT_END_DATE` datetime NOT NULL, `TELE_CONTENT` longtext, `TELE_BEGIN_DATE` datetime DEFAULT NULL, `TELE_END_DATE` datetime DEFAULT NULL, PRIMARY KEY (`ID`) ) ENGINE=InnoDB AUTO_INCREMENT=19 DEFAULT CHARSET=latin1; CREATE TABLE `news` ( `ID` bigint(20) unsigned NOT NULL AUTO_INCREMENT, `TITLE` varchar(100) NOT NULL, `IMPORTANCE` char(1) NOT NULL DEFAULT 'M', `DATE` datetime NOT NULL, `MAIN_CONTENT` longtext, PRIMARY KEY (`ID`) ) ENGINE=InnoDB AUTO_INCREMENT=7 DEFAULT CHARSET=latin1 ; CREATE TABLE `user` ( `ID` bigint(20) unsigned NOT NULL AUTO_INCREMENT, `EMAIL` varchar(255) NOT NULL, `PASSWORD` varchar(3000) NOT NULL, `STATUS` varchar(50) NOT NULL DEFAULT 'Inactive', `FIRST_NAME` varchar(50) NOT NULL, `MIDDLE_NAME` varchar(50) DEFAULT NULL, `LAST_NAME` varchar(50) DEFAULT NULL, `ROLE` varchar(50) NOT NULL DEFAULT 'General', `SUCCESSFULL_LOGINS` int(11) DEFAULT NULL, `LAST_LOGIN_DATE` datetime DEFAULT NULL, PRIMARY KEY (`ID`), UNIQUE KEY `EMAIL_UNIQUE` (`EMAIL`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1 ; <file_sep>/Portal/src/HtmlExtensions/ViewDataDictionaryExtensions.cs using System; using System.Web.Mvc; namespace guruji.HtmlExtensions { public static class ViewDataDictionaryExtensions { public static T ModelFor<T>(this ViewDataDictionary viewData) { if (viewData.ContainsKey(typeof(T).ToString())) { return (T)viewData[typeof(T).ToString()]; } throw new Exception("Requested Model not available for this view: " + typeof(T)); } } }<file_sep>/Portal/src/Controllers/SocialServiceController.cs using System.Web.Mvc; namespace guruji.Controllers { public class SocialServiceController : BaseController { public ActionResult Jrhu() { return HtmlViewFor("jrhu"); } public ActionResult Donate() { return View("JrhuDonate"); } } }<file_sep>/Portal/test/IntegrationTests/Repos/UserTest.cs //using System; //using Castle.Facilities.NHibernateIntegration; //using guruji.Domain; //using guruji.Repos; //using guruji.WindsorConfig; //using NUnit.Framework; // //namespace PortalTests.IntegrationTests.Repos //{ // [TestFixture] // public class UserTest // { // private ISessionManager sessionManager; // private IUserRepository repository; // private PortalUser portalUser; // // [SetUp] // public void SetUp() // { // sessionManager = PortalWindsorContainerFactory.GetContainer().Resolve<ISessionManager>(); // repository = new UserRepository(sessionManager); // portalUser = new PortalUser // { // Email = "<EMAIL>", // FirstName = "man", // MiddleName = "kum", // LastName = "shu", // LastLoginDate = DateTime.Today, // Role = UserRole.Admin, // Status = UserStatus.Active, // SuccessfullLogins = 1, // Password = new Password("<PASSWORD>") // }; // } // // [Test] // public void SaveUser() // { // repository.Save(portalUser); // var loadUser = repository.LoadUser(portalUser.Email); // Assert.That(loadUser.Email, Is.EqualTo("<EMAIL>")); // } // // [Test] // public void DisableUser() // { // repository.Save(portalUser); // repository.DisableUser(portalUser.Email); // var loadUser = repository.LoadUser(portalUser.Email); // Assert.That(loadUser.Status, Is.EqualTo(UserStatus.Deleted)); // } // // [TearDown] // public void TearDown() // { // repository.DeleteUser(portalUser.Email); // portalUser = null; // } // } //} <file_sep>/Portal/src/Controllers/ArticlesController.cs using System.Web.Mvc; namespace guruji.Controllers { public class ArticlesController : BaseController { public ActionResult ViewArticle(string htmlName) { return HtmlViewFor(htmlName); } } }<file_sep>/Portal/src/Domain/EventContent.cs using System; using System.Collections.Generic; namespace guruji.Domain { [Serializable] public class EventContent { public string ContentPageStyle { get; set; } public string Teaser { get; set; } public string Image_small { get; set; } public string Image_large { get; set; } public string Location { get; set; } public List<Contact> ContactDetail { get; set; } public string Descrption { get; set; } } }<file_sep>/db/create_scheduled_tasks.sql SET GLOBAL event_scheduler = 1; create event archive_events on schedule every 1000 SECOND do update gu.event set IMPORTANCE='A' where EVT_BEGIN_DATE < now(); create event archive_news on schedule every 1 DAY do update `gu`.`news`set IMPORTANCE='A' WHERE (YEAR(date)<=YEAR(CURRENT_DATE())-1) AND (DAYOFMONTH(date)<=DAYOFMONTH(CURRENT_DATE())) AND (MONTH(date)<=MONTH(CURRENT_DATE())); <file_sep>/Portal/src/HtmlExtensions/HtmlElement.cs using System.Web.Mvc; namespace guruji.HtmlExtensions { public static class HtmlElement { public static string RichtextRouteLink(this UrlHelper urlHelper,string linkText, string routeName, object routeValues ) { var url = urlHelper.RouteUrl(routeName, routeValues); if(string.IsNullOrEmpty(url)) return linkText; var tagBuilder = new TagBuilder("a") {InnerHtml = linkText}; tagBuilder.MergeAttribute("href",url); return tagBuilder.ToString(); } public static string MetaTag(this HtmlHelper helper, string name, string content) { return string.Format(@"<meta name=""{0}"" content=""{1}"" />", name, content); } } }<file_sep>/Portal/src/ViewServices/PortalViewEngine.cs using System; using System.Collections.Generic; using System.Linq; using System.Web.Mvc; namespace guruji.ViewServices { public class PortalViewEngine : IViewEngine { private readonly IControllerFileService controllerFileService; private readonly IViewLocationCache viewLocationCache; private readonly string[] viewFileLocations = new[] { "~/Views/<controller_name>/<view_name>.ascx", "~/Views/<view_name>.ascx", "~/Views/<controller_name>/<view_name>.aspx", "~/Views/<view_name>.aspx", }; private readonly string[] masterFileLocations = new[] { "~/Views/<controller_name>/<view_name>.master", "~/Views/Masters/<view_name>.master" }; public PortalViewEngine(IControllerFileService controllerFileService, IViewLocationCache viewLocationCache) { this.controllerFileService = controllerFileService; this.viewLocationCache = viewLocationCache; } public ViewEngineResult FindPartialView(ControllerContext controllerContext, string partialViewName, bool useCache) { return FindView(controllerContext, partialViewName, null, useCache); } public ViewEngineResult FindView(ControllerContext controllerContext, string viewName, string masterName, bool useCache) { var viewPath = GetCachedViewPath(controllerContext, viewName); var masterPath = GetCachedMasterPath(controllerContext, masterName); return CreateViewEngineResult(viewPath, masterPath); } public void ReleaseView(ControllerContext controllerContext, IView view) { var disposable = view as IDisposable; if (disposable != null) { disposable.Dispose(); } } private string GetCachedViewPath(ControllerContext controllerContext, string viewName) { return IsFullServerPath(viewName) ? viewName : GetFilePath(viewName, controllerContext, viewFileLocations); } private string GetCachedMasterPath(ControllerContext controllerContext, string masterName) { return string.IsNullOrEmpty(masterName) ? string.Empty : GetFilePath(masterName, controllerContext, masterFileLocations); } private string GetFilePath(string fileName, ControllerContext controllerContext, IEnumerable<string> locations) { var key = GetKey(controllerContext, fileName); var location = viewLocationCache.GetViewLocation(controllerContext.HttpContext, key); return location ?? GetAndCacheFilePath(fileName, controllerContext, locations); } private ViewEngineResult CreateViewEngineResult(string viewPath, string masterPath) { return string.IsNullOrEmpty(masterPath) ? new ViewEngineResult(new WebFormView(viewPath), this) : new ViewEngineResult(new WebFormView(viewPath, masterPath), this); } private static string GetKey(ControllerContext context, string viewName) { return context.RouteData.GetRequiredString("controller") + viewName; } private string GetAndCacheFilePath(string fileName, ControllerContext controllerContext, IEnumerable<string> fileLocations) { try { var directoryName = GetViewDirectoryName(controllerContext.Controller); var path = GetVirtualPath(directoryName, fileName, fileLocations, controllerContext); viewLocationCache.InsertViewLocation(controllerContext.HttpContext, GetKey(controllerContext, fileName), path); return path; } catch (Exception ex) { throw new ArgumentOutOfRangeException(string.Format("Unable to find file for view [{0}]", fileName), ex); } } private string GetVirtualPath(string directoryName, string fileName, IEnumerable<string> fileLocations, ControllerContext controllerContext) { Func<string, string> pathReplacer = location => location.Replace("<controller_name>", directoryName) .Replace("<view_name>", fileName); Func<string, bool> fileFinder = serverPath => controllerFileService.ServerFileExists(serverPath, controllerContext); return fileLocations.Select(pathReplacer).First(fileFinder); } private static string GetViewDirectoryName(ControllerBase controller) { return controller.GetType().Name.Replace("Controller", string.Empty); } private static bool IsFullServerPath(string viewName) { return viewName.StartsWith("~/"); } } }<file_sep>/Portal/src/ViewModels/HomePageViewModel.cs using guruji.Domain; namespace guruji.ViewModels { public class HomePageViewModel { public Event UpcomingEvent { get; set; } public NewsItem LatestNews { get; set; } public string Ticker { get; set; } } } <file_sep>/Portal/src/ViewModels/NewsForm.cs using System; using guruji.Domain; namespace guruji.ViewModels { public class NewsForm { public Int32 Id { get; set; } public string Title { get; set; } public DateTime NewsDate { get; set; } public string Importance { get; set; } public NewsContent NewsContent { get; set; } } }<file_sep>/Portal/src/Common/Serializer.cs using System; using System.IO; using System.Text; using System.Xml.Serialization; namespace guruji.Common { public class Serializer : ISerializer { public virtual T Deserialize<T>(string xml) { var serializer = new XmlSerializer(typeof(T)); return (T)serializer.Deserialize(new StringReader(xml)); } public string Serialize(object obj) { var serializer = new XmlSerializer(obj.GetType()); var stringBuilder = new StringBuilder(); var stringWriter = new StringWriter(stringBuilder); serializer.Serialize(stringWriter, obj); return stringWriter.ToString(); } public T Deserialize<T>(string xml, Action<T> action) { var t = Deserialize<T>(xml); action(t); return t; } } public interface ISerializer { T Deserialize<T>(string xml); T Deserialize<T>(string input, Action<T> action); string Serialize(object obj); } } <file_sep>/Portal/src/Common/NHibernateFacility.cs using System.Collections.Generic; using Castle.Core.Configuration; using Castle.Windsor; using guruji.ViewServices; namespace guruji.Common { public static class NHibernateFacility { private static void CreateItem(MutableConfiguration parent, string key, string value) { var item = parent.CreateChild("item"); item.Attributes.Add("key", key); item.Value = value; } public static void Configure(IWindsorContainer container, IList<string> assembliesToLoad) { var facility = new MutableConfiguration("facility"); facility.Attributes.Add("id", "nhibernatefacility"); facility.Attributes.Add("isWeb", "isWeb"); facility.Attributes.Add("defaultFlushMode", "Commit"); var factory = facility.CreateChild("factory"); factory.Attributes.Add("id", "nhibernate.factory"); var settings = factory.CreateChild("settings"); CreateItem(settings, "connection.connection_string", Config.PortalConnectionString); CreateItem(settings, "connection.provider", "NHibernate.Connection.DriverConnectionProvider"); CreateItem(settings, "connection.driver_class", "NHibernate.Driver.MySqlDataDriver"); CreateItem(settings, "dialect", "NHibernate.Dialect.MySQL5Dialect"); CreateItem(settings, "proxyfactory.factory_class", "NHibernate.ByteCode.Castle.ProxyFactoryFactory, NHibernate.ByteCode.Castle"); CreateItem(settings, "show_sql", Config.LogSqlQueries); var assemblies = factory.CreateChild("assemblies"); foreach (var assebly in assembliesToLoad) { assemblies.CreateChild("assembly", assebly); } container.Kernel.ConfigurationStore.AddFacilityConfiguration("nHibernateFacility", facility); container.AddFacility<Castle.Facilities.NHibernateIntegration.NHibernateFacility>("nHibernateFacility"); } } }<file_sep>/Portal/src/PortalViewMasterPage.cs using System.Web.Mvc; using guruji.HtmlExtensions; namespace guruji { public class PortalViewMasterPage : ViewMasterPage { public T1 ModelFor<T1>() { return ViewData.ModelFor<T1>(); } } } <file_sep>/Portal/src/Controllers/GalleryController.cs using System.IO; using System.Web.Mvc; using guruji.Domain; using guruji.ViewModels; namespace guruji.Controllers { public class GalleryController : BaseController { public ActionResult ViewPictureGallery() { var pictureGallery = new AlbumGallery(Server.MapPath("/ViewContent/photo_gallery")); return View("Gallery", new AlbumGalleryViewModel(GetSelectedAlbum(), pictureGallery.AlbumsFolders)); } public ActionResult ViewVideoGallery() { var gallery = Gallery.ConstructGallery(System.IO.File.ReadAllText(Server.MapPath("/") + "/ViewContent/videos/gallery.xml")); return View("Videos", new VideoGalleryViewModel(GetSelectedAlbum(), gallery.Albums)); } public ActionResult ViewAudioGallery() { var audioGallery = new AlbumGallery(Server.MapPath("/ViewContent/audio_gallery")); return View("Audios", new AlbumGalleryViewModel(GetSelectedAlbum(), audioGallery.AlbumsFolders)); } private string GetSelectedAlbum() { var pathSplit = Request.Url.AbsolutePath.Split('/'); return pathSplit[pathSplit.Length - 1]; } } } <file_sep>/Portal/src/Domain/PortalUser.cs using System; namespace guruji.Domain { public class PortalUser : BaseEntity { public virtual string Email { get; set; } public virtual Password Password { get; set; } public virtual string FirstName { get; set; } public virtual string MiddleName { get; set; } public virtual string LastName { get; set; } public virtual Int32 SuccessfullLogins { get; set; } public virtual DateTime LastLoginDate { get; set; } protected internal virtual string RoleDb { get; set; } protected internal virtual string StatusDb { get; set; } public virtual UserStatus Status { get { return (UserStatus)Enum.Parse(typeof(UserStatus), StatusDb, true); } set { StatusDb = Enum.GetName(typeof(UserStatus), value); } } public virtual UserRole Role { get { return (UserRole)Enum.Parse(typeof(UserRole), RoleDb, true); } set { RoleDb = Enum.GetName(typeof (UserRole), value); } } public static PortalUser CreateGuestUser() { return new PortalUser { Role = UserRole.Guest }; } public virtual bool IsLoggedIn() { return (!Role.Equals(UserRole.Guest)); } } public class FacebookUser : PortalUser { public string FacebookId { get; set; } } public enum UserStatus { Active, Inactive, Deleted } [Flags] public enum UserRole { Guest = 0, General = 1, Admin = 2, Facebook = 4 } } <file_sep>/Portal/src/Domain/Role.cs namespace guruji.Domain { public class Role : BaseEntity { public virtual string Name { get; set; } } } <file_sep>/Portal/src/Domain/NewsContent.cs using System; namespace guruji.Domain { [Serializable] public class NewsContent { public string SourceCuttingImage { get; set; } public string SourceLink { get; set; } public string SourceName { get; set; } public string Teaser { get; set; } public string DescriptionHtml { get; set; } } }<file_sep>/Portal/src/Domain/Password.cs using System.Security.Cryptography; using System.Text; namespace guruji.Domain { public class Password { public string EncryptedPassword { get; private set; } protected Password() { } public Password(string plainTextPassword) { EncryptedPassword = Encrypt(plainTextPassword); } private string Encrypt(string plainText) { var strHex = new StringBuilder(); var MessageBytes = UnicodeEncoding.Default.GetBytes(plainText); var sha512 = new SHA512Managed(); var computedHash = sha512.ComputeHash(MessageBytes); foreach (var b in computedHash) strHex.AppendFormat("{0:x2}", b); return strHex.ToString(); } public bool Equals(Password other) { if (ReferenceEquals(null, other)) return false; if (ReferenceEquals(this, other)) return true; return Equals(other.EncryptedPassword, EncryptedPassword); } public override bool Equals(object obj) { if (ReferenceEquals(null, obj)) return false; if (ReferenceEquals(this, obj)) return true; if (obj.GetType() != typeof(Password)) return false; return Equals((Password)obj); } public override int GetHashCode() { return EncryptedPassword.GetHashCode(); } } }<file_sep>/Portal/src/Controllers/EventController.cs using System.Web.Mvc; using guruji.Domain; using guruji.Mappers; using guruji.Services; using guruji.ViewModels; namespace guruji.Controllers { public class EventController : BaseController { private readonly IContentService contentService = ContentService.Instance(); [PortalAuthorize(Roles = UserRole.Admin)] public ActionResult SaveOrUpdateEvent(EventForm eventForm) { var eventMapper = new EventMapper(); contentService.SaveOrUpdateEvent(eventMapper.MapFormToDomain(eventForm)); return GetUpcomingEvents(); } [PortalAuthorize(Roles = UserRole.Admin)] public ActionResult DeleteEvent(EventForm eventForm) { contentService.DeleteEvent(contentService.LoadEventById(eventForm.Id)); return GetUpcomingEvents(); } [PortalAuthorize(Roles = UserRole.Admin | UserRole.General | UserRole.Guest | UserRole.Facebook)] public ActionResult GetUpcomingEvents() { var eventsViewModel = new EventsViewModel { Events = contentService.GetUpcomingEvents(), DefaultTab = EventsKathasTabs.Events }; return View("EventsHome", eventsViewModel); } [PortalAuthorize(Roles = UserRole.Admin | UserRole.General | UserRole.Guest | UserRole.Facebook)] public ActionResult GetUpcomingKathas() { var kathasViewModel = new EventsViewModel { Kathas = contentService.GetUpcomingKathas(), DefaultTab = EventsKathasTabs.Katha }; return View("EventsHome", kathasViewModel); } } } <file_sep>/Portal/src/ViewServices/Config.cs using System.Configuration; namespace guruji.ViewServices { public class Config { public static string LogSqlQueries { get { return ConfigurationManager.AppSettings["LogSqlQueries"]; } } public static string DatePattern { get { return ConfigurationManager.AppSettings["DatePattern"]; } } public static string PortalConnectionString { get { return ConfigurationManager.ConnectionStrings["PortalConnectionString"].ConnectionString; } } public static string WebmasterEmail { get { return ConfigurationManager.AppSettings["WebmasterEmail"]; } } public static string FacebookAppId { get { return ConfigurationManager.AppSettings["FacebookAppId"]; } } } }<file_sep>/Portal/src/Mappers/NewsMapper.cs using System; using guruji.Domain; using guruji.ViewModels; namespace guruji.Mappers { public class NewsMapper { public NewsItem MapFormToEntity(NewsForm form) { return new NewsItem { Id = form.Id, Title = form.Title, NewsDate = form.NewsDate, Importance = (Importance)Enum.Parse(typeof(Importance), form.Importance), NewsContent = form.NewsContent }; } } }<file_sep>/Portal/src/Common/WindsorContainerFactory.cs using Castle.Windsor; namespace guruji.Common { public static class WindsorContainerFactory { public static WindsorContainer Container = new WindsorContainer(); } }<file_sep>/Portal/src/ViewServices/ControllerFileService.cs using System.Web; using System.Web.Mvc; namespace guruji.ViewServices { public interface IControllerFileService { bool ServerFileExists(string path, ControllerContext context); string Contents(string serverPath, HttpContextBase httpContext); } public class ControllerFileService : IControllerFileService { private readonly IFileService fileService; public ControllerFileService(IFileService fileService) { this.fileService = fileService; } public bool ServerFileExists(string serverPath, ControllerContext controllerContext) { var fileSystemPath = MapPath(controllerContext.HttpContext, serverPath); return fileService.Exists(fileSystemPath); } public string Contents(string serverPath, HttpContextBase httpContext) { var fileSystemPath = MapPath(httpContext, serverPath); return fileService.Contents(fileSystemPath); } private string MapPath(HttpContextBase httpContext, string serverPath) { return httpContext.Server.MapPath(serverPath); } } }<file_sep>/Portal/src/Controllers/LoginHandler.cs using System; using System.Web; using guruji.Domain; using guruji.Services; using MvcContrib; namespace guruji.Controllers { public interface ILoginHandler { void Login(string email, string password, bool keepMeSignedIn); void Logout(); } public class LoginHandler : ILoginHandler { private readonly IProfileService profileService; private readonly IPortalSession session; private static readonly ILoginHandler instance = new LoginHandler(); public static ILoginHandler Instance() { return instance; } private LoginHandler() { profileService = ProfileService.Instance(); session = new PortalSession(); } public void Login(string email, string password, bool keepMeSignedIn) { LoginAndMapUser(() => profileService.AuthenticateUser(email, new Password(password))); } protected virtual HttpContextBase GetHttpContext() { return new HttpContextProvider(HttpContext.Current).Context; } public void Logout() { session.PortalUser = PortalUser.CreateGuestUser(); } private void LoginAndMapUser(Func<PortalUser> getUser) { session.PortalUser = getUser(); } } }<file_sep>/Portal/src/PortalViewPage.cs using System.Web.Mvc; using guruji.HtmlExtensions; namespace guruji { public class PortalViewPage<T> : ViewPage<T> where T : class { public T1 ModelFor<T1>() { return ViewData.ModelFor<T1>(); } } public class PortalViewPage : ViewPage { public T1 ModelFor<T1>() { return ViewData.ModelFor<T1>(); } } }<file_sep>/Portal/src/ViewModels/RouteNames.cs namespace guruji.ViewModels { public enum RouteNames { Root, Biography, Literature, Awards, KathasSchedule, OtherProgramsSchedule, TulsipeethNews, MediaNews, PhotoGallery, VideoGallery, JRHU, JRHUDonate, FConnect, FLogout, Virudavali, TulsidasBiography, Downloads, HanumanChalisa, RaghavSeva, Manas, Login, AudioGallery, CriticalEdition } }<file_sep>/Portal/src/ViewModels/VideoGalleryViewModel.cs using System.Collections.Generic; using System.Linq; using System.Web; using guruji.Domain; namespace guruji.ViewModels { public class VideoGalleryViewModel { public VideoGalleryViewModel(string selectedAlbum, List<Album> albums) { SelectedAlbum = albums.Find(x => x.Name == selectedAlbum); Albums = albums; } public List<Album> Albums { get; private set; } public Album SelectedAlbum { get; private set; } private Dictionary<int, string> AlbumDictionary { get { var albumDictionary = new Dictionary<int, string>(); for (int index = 0; index < Albums.Count; index++) { albumDictionary.Add(index + 1, Albums[index].Name); } return albumDictionary; } } public int StartCarouselIndex { get { return AlbumDictionary.Where(x => x.Value == HttpUtility.UrlDecode(SelectedAlbum.Name)).FirstOrDefault().Key; } } } }<file_sep>/Portal/src/Controllers/BaseController.cs using System.Web.Mvc; using guruji.ViewModels; namespace guruji.Controllers { public class BaseController : Controller { protected ActionResult HtmlViewFor(string htmlFileName) { string path = Server.MapPath("/"); object html = System.IO.File.ReadAllText(path + "/ViewContent/html/" + htmlFileName + ".html"); return View("HtmlPage", new HtmlPageViewModel {Html = html, PageName = htmlFileName}); } } }<file_sep>/Portal/src/Controllers/AuthenticationController.cs using System.Web.Mvc; using guruji.Domain; using guruji.Services; using System.Linq; namespace guruji.Controllers { public class AuthenticationController : BaseController { private readonly ILoginHandler loginHandler; public AuthenticationController() { loginHandler = LoginHandler.Instance(); } [AcceptVerbs(HttpVerbs.Post)] public ActionResult Login(string email, string password, string returnUrl) { try { loginHandler.Login(email, password, true); } catch (UserNotAuthorizedException) { Response.StatusCode = 403; return new ContentResult { Content = "Your Login or Password is incorrect." }; } if (!string.IsNullOrEmpty(returnUrl)) return Redirect(returnUrl); return new EmptyResult(); } public string FConnect() { if (Request.Url != null) { var query = Request.Url.Query; new PortalSession().PortalUser = new FacebookUser{FacebookId = query.Split('&').First().Replace("?", ""), Role = UserRole.Facebook}; } return "done"; } public void FLogout() { new PortalSession().PortalUser = PortalUser.CreateGuestUser(); } public ActionResult Logout(string returnUrl) { loginHandler.Logout(); return Redirect("default.aspx"); } } } <file_sep>/Portal/src/Controllers/PortalSession.cs using System.Web; using System.Web.SessionState; using guruji.Domain; namespace guruji.Controllers { public interface IPortalSession { PortalUser PortalUser { get; set; } } public class PortalSession : IPortalSession { private static HttpSessionState Session { get { return HttpContext.Current.Session; } } public PortalUser PortalUser { get { return (PortalUser) Session["user"]; } set { Session["user"] = value; } } } }<file_sep>/Portal/src/Controllers/DownloadController.cs using System.Web.Mvc; namespace guruji.Controllers { public class DownloadController : BaseController { public ActionResult Show() { return View("downloads"); } } }<file_sep>/Portal/src/Domain/AlbumGallery.cs using System; using System.Collections.Generic; using System.IO; using guruji.Common; namespace guruji.Domain { public class AlbumGallery { public DirectoryInfo[] AlbumsFolders { get; set; } public AlbumGallery(string galleryPath) { AlbumsFolders = new DirectoryInfo(galleryPath).GetDirectories(); } } [Serializable] public class Gallery { public List<Album> Albums { get; set; } public static Gallery ConstructGallery(string albumXml) { return new Serializer().Deserialize<Gallery>(albumXml); } } [Serializable] public class Album { public string Name { get; set; } public string Title { get; set; } public string Description { get; set; } public List<Video> Videos { get; set; } } [Serializable] public class Video { public string Iframe { get; set; } public string Title { get; set; } public string Id { get; set; } } } <file_sep>/Portal/src/Domain/Event.cs using System; using guruji.Common; namespace guruji.Domain { public class Event : BaseEntity { public virtual string Title { get; set; } protected internal virtual char IsKathaDb { get; set; } protected internal virtual string EventContentXml { get; set; } public virtual DateTime EventBeginDate { get; set; } public virtual DateTime EventEndDate { get; set; } protected internal virtual string TelecastContentXml { get; set; } public virtual DateTime TelecastBeginDate { get; set; } public virtual DateTime TelecastEndDate { get; set; } protected internal virtual char ImportanceDb { get; set; } public virtual bool IsKatha { get { return IsKathaDb == 'Y'; } set { IsKathaDb = value ? 'Y' : 'N'; } } public virtual Importance Importance { get { return (Importance) Enum.Parse(typeof (Importance), ImportanceDb.ToString(), true); } set { ImportanceDb = Enum.GetName(typeof(Importance), value).ToCharArray()[0]; } } public virtual EventContent EventContent { get { return EventContentXml == null ? null : new Serializer().Deserialize<EventContent>(EventContentXml); } set { EventContentXml = new Serializer().Serialize(value); } } public virtual TelecastContent TelecastContent { get { return TelecastContentXml == null ? null: new Serializer().Deserialize<TelecastContent>(TelecastContentXml); } set { TelecastContentXml = new Serializer().Serialize(value); } } } public enum Importance { H, M, L, A } } <file_sep>/Portal/src/Services/ProfileService.cs using System; using guruji.Domain; using guruji.Repos; namespace guruji.Services { public interface IProfileService { PortalUser AuthenticateUser(string email, Password password); } public class ProfileService : IProfileService { private readonly IUserRepository userRepository; private static readonly IProfileService instance = new ProfileService(NHibernateSessionFactory.Instance()); public static IProfileService Instance() { return instance; } private ProfileService(NHibernateSessionFactory repositoryFactory) { userRepository = repositoryFactory.UserRepository; } public PortalUser AuthenticateUser(string email, Password password) { PortalUser user; try { user = userRepository.LoadUser(email); } catch (Exception) { throw new UserNotAuthorizedException(); } if (!password.Equals(user.Password)) throw new UserNotAuthorizedException(); return user; } } public class UserNotAuthorizedException : Exception { } } <file_sep>/Portal/src/Global.asax.cs using System; using System.Web; using System.Web.Configuration; using System.Web.Mvc; using guruji.Controllers; using guruji.Domain; using guruji.ViewServices; namespace guruji { public class MvcApplication : HttpApplication { public static void RegisterRoutes() { DescribeRoutes.Register(); } protected void Application_Start() { RegisterRoutes(); InitializeViewEngine(); } private static void InitializeViewEngine() { ViewEngines.Engines.Clear(); ViewEngines.Engines.Add(new PortalViewEngine(new ControllerFileService(new FileService()), new DefaultViewLocationCache())); } protected void Application_Error(object sender, EventArgs e) { if (!HttpContext.Current.IsCustomErrorEnabled) return; var customErrorsSection = WebConfigurationManager.GetWebApplicationSection("system.web/customErrors") as CustomErrorsSection; CustomErrorHandler.HandleError(GetHttpServer(Server), GetHttpResponse(Response), customErrorsSection); } public virtual HttpServerUtilityBase GetHttpServer(HttpServerUtility httpServerUtility) { return new HttpServerUtilityWrapper(httpServerUtility); } public virtual HttpResponseBase GetHttpResponse(HttpResponse response) { return new HttpResponseWrapper(response); } protected void Session_Start(object sender, EventArgs e) { new PortalSession().PortalUser = PortalUser.CreateGuestUser(); } } }<file_sep>/Portal/src/Controllers/CustomErrorHandler.cs using System; using System.Web; using System.Web.Configuration; namespace guruji.Controllers { public static class CustomErrorHandler { public static void HandleError(HttpServerUtilityBase server, HttpResponseBase response, CustomErrorsSection customErrorsSection) { CustomError customError = GetCustomError(server.GetLastError(), customErrorsSection); server.ClearError(); response.Clear(); response.WriteFile(customError.Redirect); response.StatusCode = customError.StatusCode; } private static CustomError GetCustomError(Exception exception, CustomErrorsSection section) { var httpException = exception as HttpException; var defaultError = section.Errors.Get("500"); if (httpException == null) return defaultError; var customError = section.Errors.Get(httpException.GetHttpCode().ToString()); return customError ?? defaultError; } } }<file_sep>/Portal/src/ViewModels/AlbumGalleryViewModel.cs using System.Collections.Generic; using System.IO; using System.Linq; using System.Web; namespace guruji.ViewModels { public class AudioPlayerViewModel { public string JwPlayerId { get; set; } public string SelectedAlbum { get; set; } } public class AlbumGalleryViewModel { public AlbumGalleryViewModel(string selectedAlbumName, DirectoryInfo[] albumFolders) { AlbumFolders = albumFolders; SelectedAlbumFolder = selectedAlbumName; } public string SelectedAlbumFolder { get; private set; } public DirectoryInfo[] AlbumFolders { get; private set; } public int StartCarouselIndex { get { return AlbumDictionary.Where(x => x.Value == HttpUtility.UrlDecode(SelectedAlbumFolder)).FirstOrDefault().Key; } } private Dictionary<int, string> AlbumDictionary { get { var albumDictionary = new Dictionary<int, string>(); for (int index = 0; index < AlbumFolders.Length; index++) { albumDictionary.Add(index + 1, AlbumFolders[index].ToString()); } return albumDictionary; } } } } <file_sep>/Portal/src/Repos/Repository.cs using System.Collections.Generic; using NHibernate; namespace guruji.Repos { public class Repository : IRepository { private ISessionFactory SessionFactory { get; set; } protected Repository(ISessionFactory sessionFactory) { SessionFactory = sessionFactory; } public T Load<T>(object id) { using (var session = SessionFactory.OpenSession()) { return session.Get<T>(id); } } public void SaveOrUpdate<T>(T entity) { using (var session = SessionFactory.OpenSession()) { session.SaveOrUpdate(entity); session.Flush(); } } public void Save<T>(T entity) { using (var session = SessionFactory.OpenSession()) { session.Save(entity); session.Flush(); } } public T RunNamedQuery<T>(string queryName, string parameterName, object parameterValue) { using (ISession session = SessionFactory.OpenSession()) { IQuery query = session.GetNamedQuery(queryName); query.SetParameter(parameterName, parameterValue); return query.UniqueResult<T>(); } } public IList<T> RunNamedQuery<T>(string queryName, params NamedQueryParameter[] parameters) { using (var session = SessionFactory.OpenSession()) { IQuery query = session.GetNamedQuery(queryName); return query.List<T>(); } } public void Delete<T>(T entity) { using (var session = SessionFactory.OpenSession()) { session.Delete(entity); session.Flush(); } } } public class NamedQueryParameter { public string Name { get; private set; } public object Value { get; private set; } public NamedQueryParameter(string name, object value) { Name = name; Value = value; } } public interface IRepository { T Load<T>(object id); void SaveOrUpdate<T>(T entity); void Save<T>(T entity); void Delete<T>(T entity); T RunNamedQuery<T>(string queryName, string parameterName, object parameterValue); IList<T> RunNamedQuery<T>(string queryName, params NamedQueryParameter[] parameters); } }<file_sep>/Portal/src/Controllers/NewsController.cs using System.Web.Mvc; using guruji.Domain; using guruji.Mappers; using guruji.Services; using guruji.ViewModels; using System.Linq; namespace guruji.Controllers { public class NewsController : BaseController { private readonly IContentService contentService = ContentService.Instance(); [PortalAuthorize(Roles = UserRole.Admin)] public ActionResult SaveOrUpdateNews(NewsForm newsForm) { var newsMapper = new NewsMapper(); contentService.SaveOrUpdateNews(newsMapper.MapFormToEntity(newsForm)); return GetTulsipeethNews(); } [PortalAuthorize(Roles = UserRole.Admin)] public ActionResult DeleteNews(NewsForm newsForm) { contentService.DeleteNews(contentService.LoadNewsById(newsForm.Id)); return GetTulsipeethNews(); } [PortalAuthorize(Roles = UserRole.Admin | UserRole.General | UserRole.Guest | UserRole.Facebook)] public ActionResult GetTulsipeethNews() { var newsItems = contentService.GetNewsItems(); var tulsipeethNewsModel = new NewsViewModel { TulsipeethNews = newsItems.Where(x => string.IsNullOrEmpty(x.NewsContent.SourceName)).ToList(), DefaultTab = NewsTabs.Tulsipeeth }; return View("NewsHome", tulsipeethNewsModel); } [PortalAuthorize(Roles = UserRole.Admin | UserRole.General | UserRole.Guest | UserRole.Facebook)] public ActionResult GetMediaNews() { var newsItems = contentService.GetNewsItems(); var mediaNewsModel = new NewsViewModel { MediaNews = newsItems.Where(x => !string.IsNullOrEmpty(x.NewsContent.SourceName)).ToList(), DefaultTab = NewsTabs.Media }; return View("NewsHome", mediaNewsModel); } } }<file_sep>/Portal/src/Domain/TelecastContent.cs using System; namespace guruji.Domain { [Serializable] public class TelecastContent { public bool IsLive { get; set; } public string ChannelName { get; set; } } }
a167f78c24453ae89e828bb88b488e9059a6c426
[ "C#", "SQL" ]
63
C#
namoraghavay/jagadgururambhadracharya.org
1c23de5d90039d30fa9d90007438b3e0f0ef9d56
8f1f466c1ca48a27c4cd638db2611274a8db63ae
refs/heads/master
<repo_name>WreewanMorhee/ReactBlingBlingText<file_sep>/App.js import React from 'react' import ReactDOM from 'react-dom' const App = (props) => { return ( <section class='example'> <div class='box'> <div class='energy-text energy-transfer'> <BlingBlingText text={'雅斯蘭黛 艾維尼爾'} /> </div> </div> </section> ) } export default App <file_sep>/src/Text.js import React from 'react' const Text = ({letter, css_style}) => { return ( <span style={{ transition: '.2s linear', display: 'inline-block' ...css_style }}>{letter}</span> ) } export default Text <file_sep>/README.md # BlingBlingText make your text fancy ! <file_sep>/src/App.js const App = ({ data }) => ( <> {data.map(({ class_name, ...props }) => { const comp_list = Array.from(document.querySelectorAll(class_name)) return comp_list.map((ele, index) => ( <BlingBlingText key={`${class_name}-index-${index + 1}`} element={ele} {...props} /> )) })} </> ) import React from 'react' import ReactDOM from 'react-dom' import BlingBlingText from './BlingBlingText' export const init = props => { const container = document.createElement("DIV") document.body.appendChild(container) ReactDOM.render(<App {...props} />, container) }
87de6a620bc4a44701bb4e65adf086a9447dfbb4
[ "JavaScript", "Markdown" ]
4
JavaScript
WreewanMorhee/ReactBlingBlingText
440e19fb54b78eb72ef99fac49aee1c40ee31bc5
0e6ea7fb86b7d9b4877ddbf03822a22881784558
refs/heads/master
<repo_name>sendev1/cxf-server<file_sep>/build.gradle import org.springframework.boot.gradle.tasks.bundling.BootBuildImage plugins { id "org.springframework.boot" version "2.4.2" id "io.spring.dependency-management" version "1.0.11.RELEASE" id 'java' id("no.nils.wsdl2java") version "0.12" } group = 'com.cxf' version = '0.0.1-SNAPSHOT' sourceCompatibility = '11' repositories { mavenLocal() mavenCentral() maven { url = uri("https://repo.spring.io/milestone") } maven { url = uri("https://repo.spring.io/snapshot") } } dependencies { //implementation("org.springframework.experimental:spring-graalvm-native:0.9.0-SNAPSHOT") implementation "org.springframework.experimental:spring-graalvm-native:0.9.0-SNAPSHOT" implementation "org.springframework.boot:spring-boot-starter-web" implementation "org.apache.cxf:cxf-spring-boot-starter-jaxws:3.4.2" implementation "org.springframework.boot:spring-boot-starter-validation" implementation 'org.springframework:spring-context-indexer' implementation "javax.activation:activation:1.1.1" implementation "javax.xml.bind:jaxb-api:2.3.1" implementation "com.sun.xml.bind:jaxb-core:2.3.0.1" implementation "com.sun.xml.bind:jaxb-impl:2.3.0.1" compileOnly "org.graalvm.nativeimage:svm:21.0.0" wsdl2java "com.sun.xml.bind:jaxb-impl:2.3.3" testImplementation('org.springframework.boot:spring-boot-starter-test') { exclude group: "org.junit.vintage', module: 'junit-vintage-engine" } } test { useJUnitPlatform() } wsdl2java { // Note that java classes will be generated under build/generatedsources wsdlsToGenerate = [ [file("src/main/resources/wsdl/helloworld.wsdl")] ] wsdlDir = file("src/main/resources/wsdl") ext.cxfVersion = "3.4.2" } <file_sep>/compile-only.sh #!/usr/bin/env bash ARTIFACT=server MAINCLASS=com.cxf.server.ServerApplication VERSION=0.0.1-SNAPSHOT GREEN='\033[0;32m' RED='\033[0;31m' NC='\033[0m' mkdir -p build/native-image JAR="$ARTIFACT-$VERSION.jar" rm -f $ARTIFACT echo "Unpacking $JAR" cd build/native-image jar -xvf ../libs/$JAR cp -R META-INF BOOT-INF/classes LIBPATH=$(find BOOT-INF/lib | tr '\n' ':') CP=BOOT-INF/classes:$LIBPATH GRAALVM_VERSION=$(native-image --version) echo "Compiling $ARTIFACT with $GRAALVM_VERSION" native-image \ --verbose \ --allow-incomplete-classpath \ --no-fallback \ --no-server \ --enable-all-security-services \ -H:Name=${ARTIFACT} \ -H:+ReportExceptionStackTraces \ -Dspring.xml.ignore=false \ -Dspring.spel.ignore=true \ -Dspring.native.remove-yaml-support=true \ --initialize-at-run-time=org.hibernate.validator.internal.engine.messageinterpolation.el.SimpleELContext \ -cp ${CP} \ ${MAINCLASS} # --allow-incomplete-classpath \ # -Dorg.apache.cxf.jmx.disabled=true \ # -Dcxf.metrics.enabled=false \ # -Dmanagement.metrics.binders.jvm.enabled=false \ # -Dcxf.metrics.enabled=false \ # --initialize-at-run-time=org.hibernate.validator.internal.engine.messageinterpolation.el.SimpleELContext \ # -H:TraceClassInitialization=true \ # -Dspring.native.mode=agent # -Dspring.native.remove-xml-support=false \ # -Dspring.spel.ignore=false \ # -Dspring.native.remove-yaml-support=false \ # --initialize-at-run-time=org.hibernate.validator.internal.engine.messageinterpolation.el.SimpleELContext \ <file_sep>/Makefile .PHONY: build build: ./gradlew build compile: build ./compile-only.sh # -agentlib:jdwp=transport=dt_socket,server=y,suspend=n,address=*:5005 \ runjar: echo "profiling to generate config.." java -jar build/libs/server-0.0.1-SNAPSHOT.jar \ -agentlib:jdwp=transport=dt_socket,server=y,suspend=n,address=*:5005 -Dorg.apache.cxf.JDKBugHacks.all=true \ -Djava.util.logging.config.file=./src/main/resources/logging.properties profile: echo "profiling to generate config.." java -agentlib:native-image-agent=config-output-dir=src/main/resources/META-INF/native-image \ -jar build/libs/server-0.0.1-SNAPSHOT.jar \ -Dorg.apache.cxf.JDKBugHacks.all=true \ -Dorg.graalvm.nativeimage.imagecode=agent \ -Djava.util.logging.config.file=./src/main/resources/logging.properties clean: ./gradlew clean run: ./build/native-image/server -Dorg.apache.cxf.JDKBugHacks.all=true d-build: docker build \ --pull \ -f Dockerfile \ -t krisfoster/cxf:01 . d-run: docker run --rm -it -P krisfoster/cxf:01 /bin/bash <file_sep>/src/main/resources/application.properties cxf.path=/cxf/ws spring.main.allow-bean-definition-overriding=true<file_sep>/compile.sh #!/usr/bin/env bash ARTIFACT=server MAINCLASS=com.cxf.server.ServerApplication VERSION=0.0.1-SNAPSHOT GREEN='\033[0;32m' RED='\033[0;31m' NC='\033[0m' rm -rf build mkdir -p build/native-image echo "Packaging $ARTIFACT with Maven" ./gradlew build JAR="$ARTIFACT-$VERSION.jar" rm -f $ARTIFACT echo "Unpacking $JAR" cd build/native-image jar -xvf ../libs/$JAR cp -R META-INF BOOT-INF/classes LIBPATH=`find BOOT-INF/lib | tr '\n' ':'` CP=BOOT-INF/classes:$LIBPATH GRAALVM_VERSION=`native-image --version` echo "Compiling $ARTIFACT with $GRAALVM_VERSION" native-image \ --verbose \ --allow-incomplete-classpath \ --no-fallback \ --no-server \ --enable-all-security-services \ -H:Name=${ARTIFACT} \ -H:+ReportExceptionStackTraces \ -Dspring.xml.ignore=false \ -Dspring.spel.ignore=true \ -Dspring.native.remove-yaml-support=true \ --initialize-at-run-time=org.hibernate.validator.internal.engine.messageinterpolation.el.SimpleELContext \ -cp ${CP} \ ${MAINCLASS} # --initialize-at-run-time=org.hibernate.validator.internal.engine.messageinterpolation.el.SimpleELContext \<file_sep>/Dockerfile FROM krisfoster/graal-ee-ol-base-debug:21.0.0.2-JDK8 RUN mkdir app COPY . /app WORKDIR app RUN make compile
19b599d9b5201551a32d5a8af71bccc6b8ee1738
[ "Makefile", "INI", "Gradle", "Dockerfile", "Shell" ]
6
Gradle
sendev1/cxf-server
61d282a5151d2416b8e605cb01d3edd1eaf38089
796204285ff4001a216c106cc2b3f4c4af59af64
refs/heads/main
<file_sep>const { prompt } = require("inquirer"); const { writeFile } = require("fs"); const generateHTML = require("./src/generateHTML"); const Engineer = require("./lib/engineer"); const Intern = require("./lib/intern"); const Manager = require("./lib/manager"); const employees = []; const managerQuestions = [ { type: 'input', message: 'What is the team manager\'s name?', name: 'managerName', default: '<NAME>' }, { type: 'input', message: 'What is the team manager\'s employee id #?', name: 'managerID', default: 'format: 123456' }, { type: 'input', message: 'What is the team manager\'s email address?', name: 'managerEmail', default: '<EMAIL>' }, { type: 'input', message: 'What is the team manager\'s office phone number (format: 555-555-5555)?', name: 'managerPhone', default: '555-555-5555' } ]; const engineerQuestions = [ { type: 'input', message: 'What is your engineer\'s name?', name: 'engineerName', default: '<NAME>' }, { type: 'input', message: 'What is your engineer\'s employee id #?', name: 'engineerID', default: 'format: 123456' }, { type: 'input', message: 'What is your engineer\'s email address?', name: 'engineerEmail', default: '<EMAIL>' }, { type: 'input', message: 'What is your engineer\'s GitHub username?', name: 'engineerGitHub', default: 'moedoe.git' } ]; const internQuestions = [ { type: 'input', message: 'What is your intern\'s name?', name: 'internName', default: '<NAME>' }, { type: 'input', message: 'What is your intern\'s employee id #?', name: 'internID', default: 'format: 123456' }, { type: 'input', message: 'What is your intern\'s email address?', name: 'internEmail', default: '<EMAIL>' }, { type: 'input', message: 'What is your intern\'s school?', name: 'internSchool', default: 'UNC' } ]; const addAnotherEmployee = [ { type: 'list', message: 'What type of team member would you like to add?', choices: ['Engineer', 'Intern', 'I don\'t want to add any more team members'], name: 'employeeType', default: 'Engineer', } ]; async function startQuestions() { console.log('Please build your team') const { managerName, managerID, managerEmail, managerPhone } = await prompt(managerQuestions); const addNewEmployee = await prompt(addAnotherEmployee); const newManager = new Manager(managerName, managerID, managerEmail, managerPhone); employees.push(newManager); nextEmployee(addNewEmployee.employeeType); }; async function nextEmployee(answers) { if (answers === 'Engineer') { const { engineerName, engineerID, engineerEmail, engineerGithub } = await prompt(engineerQuestions); const addNewEmployee = await prompt(addAnotherEmployee); const newEngineer = new Engineer(engineerName, engineerID, engineerEmail, engineerGithub); employees.push(newEngineer); nextEmployee(addNewEmployee.employeeType); return } else if (answers === 'Intern') { const { internName, internID, internEmail, internSchool } = await prompt(internQuestions); const addNewEmployee = await prompt(addAnotherEmployee); const newIntern = new Intern(internName, internID, internEmail, internSchool); employees.push(newIntern); nextEmployee(addNewEmployee.employeeType); return } console.log('Team complete!') const data = await generateHTML(employees); writeToFile(data); }; function writeToFile(data) { writeFile('./dist/index.html', data, (err) => { if (err) { return console.log(err); } else { console.log("Team saved successfully."); } }); } function init() { startQuestions(); } init();<file_sep>const fs = require('fs'); const managerCard = manager => { return ` <div class="card col shadow p-3 mb-5 bg-body rounded" style="width: 18rem"> <div class="manager-body card-body"> <h5 class="card-title">${manager.name} </h5> <p class="card-text"> ☕ Manager </p> </div> <ul class="list-group list-group-flush"> <li class="list-group-item"><strong>ID: </strong>${manager.id}</li> <li class="list-group-item"><strong>Email: </strong>${manager.email}</li> <li class="list-group-item"><strong>Office Number: </strong>${manager.officeNumber}</li> </ul> </div>` } const engineerCard = engineer => { console.log(engineer); return ` <div class="card col shadow p-3 mb-5 bg-body rounded" style="width: 18rem"> <div class="engineer-body card-body"> <h5 class="card-title">${engineer.name}</h5> <p class="card-text"> 👓 Engineer </p> </div> <ul class="list-group list-group-flush"> <li class="list-group-item"><strong>ID: </strong>${engineer.id}</li> <li class="list-group-item"><strong>Email: </strong>${engineer.email}</li> <li class="list-group-item"><strong>GitHub: </strong>${engineer.github}</li> </ul> </div>` } const internCard = intern => { return ` <div class="card col shadow p-3 mb-5 bg-body rounded" style="width: 18rem"> <div class="intern-body card-body"> <h5 class="card-title">${intern.name}</h5> <p class="card-text"> 🎓 Intern </p> </div> <ul class="list-group list-group-flush"> <li class="list-group-item"><strong>ID: </strong>${intern.id}</li> <li class="list-group-item"><strong>Email: </strong>${intern.email}</li> <li class="list-group-item"><strong>School: </strong>${intern.school}</li> </ul> </div>` } const generateTeam = team => { var teamMembers = []; teamMembers.push(team.filter(employee => employee.getRole() === 'Manager').map(manager => managerCard(manager))); teamMembers.push(team.filter(employee => employee.getRole() === 'Engineer').map(engineer => engineerCard(engineer))); teamMembers.push(team.filter(employee => employee.getRole() === 'Intern').map(intern => internCard(intern))); return teamMembers.join('') } // GenerateHTML const generateHTML = teamMembers => { return `<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta http-equiv="X-UA-Compatible" content="IE=edge" /> <meta name="viewport" content="width=<device-width>, initial-scale=1.0" /> <link rel="preconnect" href="https://fonts.googleapis.com" /> <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin /> <link href="https://fonts.googleapis.com/css2?family=Red+Hat+Display:wght@400;500;700;900&display=swap" rel="stylesheet" /> <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="<KEY>" crossorigin="anonymous"> <link rel="stylesheet" href="./style.css" /> <title>Team Generator</title> </head> <body> <header>My Team</header> <div class="card-container"> <div class="container d-flex justify-content-center"> <div class="row"> ${generateTeam(teamMembers)} </div> </div> </div> </body> </html>` } module.exports = generateHTML;<file_sep># TeamGenerator **<NAME>** <br /> ## User Story A Node.js command-line application that takes in information about employees on a software engineering team, then generates an HTML webpage that displays summaries for each person. <br /> **Important**: * Uses the [Inquirer package](https://www.npmjs.com/package/inquirer). * Uses the [Jest package](https://www.npmjs.com/package/jest) for a suite of unit tests. The application will be invoked by using the following command: ```bash node index.js ``` <br /> [![Video](assets/images/screenshot2.png)](https://www.youtube.com/watch?v=aNHSrD5t4cw) <br /> <br /> ## Mock-Up The following image shows a mock-up of the generated HTML’s appearance: ![HTML Webpage](assets/images/screenshot.png) <br />
80b53425d07547c0662d465dd90cd1185f81bef9
[ "JavaScript", "Markdown" ]
3
JavaScript
brittnc/TeamGenerator
f42aae41fa58666dff9b2e99799d05f6d334dd7c
f2e116c000498b998775efd714329404efedde8f
refs/heads/master
<file_sep>[package] publish = false name = "hello_world" version = "0.1.0" authors = ["<NAME> <<EMAIL>>"] workspace = "../.." [dependencies] [target.asmjs-unknown-emscripten] rustflags = [ "-Clink-args=-s EXPORTED_FUNCTIONS=['_say_hello']", ] <file_sep># simple-wasm-example **A [Rust](https://www.rust-lang.org/) lib, compiled to [WASM](https://developer.mozilla.org/en-US/docs/WebAssembly), with fallback to [asm.js](http://asmjs.org).** I have given up for now though, because the tooling is just not ready yet. [There are two `rustc` backends (`wasm32_unknown_emscripten` and `wasm32_unknown_unknown`)](https://github.com/rust-lang/rust/tree/fedce67cd21dc08ece5a484fe1a060346acac98a/src/librustc_back/target) and [some issues to be dealt with](https://github.com/rust-lang/rust/issues?q=is%3Aopen+is%3Aissue+label%3AO-wasm). [Emscripten](https://kripken.github.io/emscripten-site/index.html) IMHO is a nightmare to work with, and its generated JS wrapper code is not very portable. [![build status](https://img.shields.io/codeship/a0aaa5a0-055d-0136-7f21-62225b813afe.svg)](https://app.codeship.com/projects/280737) ![ISC-licensed](https://img.shields.io/github/license/derhuerst/simple-wasm-example.svg) [![chat with me on Gitter](https://img.shields.io/badge/chat%20with%20me-on%20gitter-512e92.svg)](https://gitter.im/derhuerst) [![support me on Patreon](https://img.shields.io/badge/support%20me-on%20patreon-fa7664.svg)](https://patreon.com/derhuerst) ## Building The following tools are expected to be installed and/or available via `$PATH`. You can use [`install.sh`](scripts/install.sh) to install them automatically. - `emcc` from the [Emscripten SDK](https://kripken.github.io/emscripten-site/docs/getting_started/downloads.html) with the [`latest` tools](https://kripken.github.io/emscripten-site/docs/tools_reference/emsdk.html#tools-and-sdk-targets) - [`cargo`](https://doc.rust-lang.org/cargo/getting-started/installation.html) `nightly`. - the `asmjs-unknown-unknown` and `wasm32-unknown-unknown` `rustc` targets ```shell npm run build npm test ``` ## Contributing If you have a question or have difficulties using `simple-wasm-example`, please double-check your code and setup first. If you think you have found a bug or want to propose a feature, refer to [the issues page](https://github.com/derhuerst/simple-wasm-example/issues). <file_sep>#[no_mangle] pub extern "C" fn say_hello() { println!("Hello, world!"); } fn main() {} <file_sep>[workspace] members = ["src/hello_world"] <file_sep>'use strict' const sayHello = require('.') sayHello() <file_sep>#!/bin/bash set -e # rustup curl https://sh.rustup.rs -sSf | sh -s -- -y --default-toolchain nightly export PATH="$HOME/.cargo/bin:$PATH" # asm.js & WASM targets rustup target add asmjs-unknown-unknown --toolchain nightly rustup target add wasm32-unknown-unknown --toolchain nightly # Emscripten SDK wget -q 'https://s3.amazonaws.com/mozilla-games/emscripten/releases/emsdk-portable.tar.gz' tar -xzv -f emsdk-portable.tar.gz source ./emsdk-portable/emsdk_env.sh emsdk update emsdk install latest --enable-wasm emsdk activate latest <file_sep>'use strict' const path = require('path') let sayHello if (WebAssembly) { const module = require(path.join(__dirname, 'hello_world.wasm.js')) sayHello = module._say_hello } else { const module = require(path.join(__dirname, 'hello_world.asm.js')) sayHello = module.cwrap('say_hello', '', []) } module.exports = sayHello
b49f31e153d10af77dab56e51a458e708a794f65
[ "TOML", "JavaScript", "Markdown", "Rust", "Shell" ]
7
TOML
derhuerst/simple-wasm-example
9fb3cb3f528a6d9ace106378da56ff9156828204
c392b1d5b0a98f0eec5e385c1ad1cd9003b0372a
refs/heads/master
<repo_name>K-Tros/DWA15-P3<file_sep>/app/Http/Controllers/UserGeneratorController.php <?php namespace Project3\Http\Controllers; use Project3\Http\Controllers\Controller; use Illuminate\Http\Request; class UserGeneratorController extends Controller { /** * Responds to requests to GET /user-generator. * Returns the default view. */ public function getIndex() { return view('user-generator.user-generator'); } /** * Responds to requests to POST /user-generator */ public function postGenerate(Request $request) { $this->validate($request, [ 'users' => 'required|numeric|between:1,99' ]); $users = $request->input('users', '0'); $birthdate = $request->input('birthdate'); $profile = $request->input('profile'); return view('user-generator.user-generator', ['users' => $users, 'birthdate' => $birthdate, 'profile' => $profile]); } } <file_sep>/app/Events/Event.php <?php namespace Project3\Events; abstract class Event { // } <file_sep>/readme.md # Project 3 - Developer's Best Friend ## Live URL <http://p3.krtsoftwaredev.me> ## Description A multi-page application that provides three separate functions. 1) A lorem ipsum generator that takes a number and return that many paragraphs of lorem ipsum filler text. 2) A random user generator that takes a number and has two optional checkboxes for including random profile filler text and/or a random birthday. 3) An xkcd style password generate(see https://github.com/K-Tros/DWA15-P2, it is functionally similar to this application). The home page provides some brief descriptions of each of these. ## Demo <http://screencast.com/t/sT4yCiqg6> ## Details for teaching team No special notes for this project. ## Outside code * Bootstrap: http://getbootstrap.com/ * Laravel: https://laravel.com/ * Lorem Ipsum Generator: https://packagist.org/packages/badcow/lorem-ipsum * Faker: https://packagist.org/packages/fzaninotto/faker # Kevin's TODOs * ~~Add css and other styling.~~ * ~~Figure out request url issues in master.blade.php.~~ * ~~Add actual forms to generator pages.~~ * ~~Add logic to interpret and use form inputs.~~ * ~~Add composer packages for generating lorem-ipsum and random users.~~ * ~~Generally just add more detail to pages.~~ * ~~Figure out why the footer doesn't look pretty.~~ * ~~Above and beyond stuff (add project 2 into this? probably use a hardcoded list to speed it up)~~ Limited the size of the word list for performance reasons. # Laravel PHP Framework [![Build Status](https://travis-ci.org/laravel/framework.svg)](https://travis-ci.org/laravel/framework) [![Total Downloads](https://poser.pugx.org/laravel/framework/d/total.svg)](https://packagist.org/packages/laravel/framework) [![Latest Stable Version](https://poser.pugx.org/laravel/framework/v/stable.svg)](https://packagist.org/packages/laravel/framework) [![Latest Unstable Version](https://poser.pugx.org/laravel/framework/v/unstable.svg)](https://packagist.org/packages/laravel/framework) [![License](https://poser.pugx.org/laravel/framework/license.svg)](https://packagist.org/packages/laravel/framework) Laravel is a web application framework with expressive, elegant syntax. We believe development must be an enjoyable, creative experience to be truly fulfilling. Laravel attempts to take the pain out of development by easing common tasks used in the majority of web projects, such as authentication, routing, sessions, queueing, and caching. Laravel is accessible, yet powerful, providing powerful tools needed for large, robust applications. A superb inversion of control container, expressive migration system, and tightly integrated unit testing support give you the tools you need to build any application with which you are tasked. ## Official Documentation Documentation for the framework can be found on the [Laravel website](http://laravel.com/docs). ## Contributing Thank you for considering contributing to the Laravel framework! The contribution guide can be found in the [Laravel documentation](http://laravel.com/docs/contributions). ## Security Vulnerabilities If you discover a security vulnerability within Laravel, please send an e-mail to <NAME> at <EMAIL>. All security vulnerabilities will be promptly addressed. ## License The Laravel framework is open-sourced software licensed under the [MIT license](http://opensource.org/licenses/MIT) <file_sep>/app/Http/Controllers/LoremIpsumController.php <?php namespace Project3\Http\Controllers; use Project3\Http\Controllers\Controller; use Illuminate\Http\Request; class LoremIpsumController extends Controller { /** * Responds to requests to GET /lorem-ipsum. * Returns the default view. */ public function getIndex() { return view('lorem-ipsum.lorem-ipsum'); } /** * Responds to requests to POST /lorem-ipsum */ public function postGenerate(Request $request) { $this->validate($request, [ 'paragraphs' => 'required|numeric|between:1,99' ]); $paragraphs = $request->input('paragraphs', '0'); return view('lorem-ipsum.lorem-ipsum')->with('paragraphs',$paragraphs); } } <file_sep>/app/Http/routes.php <?php /* |-------------------------------------------------------------------------- | Application Routes |-------------------------------------------------------------------------- | | This route group applies the "web" middleware group to every route | it contains. The "web" middleware group is defined in your HTTP | kernel and includes session state, CSRF protection, and more. | */ Route::group(['middleware' => ['web']], function () { // Route::get('/', function () { return view('index'); }); // Gets main page for lorem ipsum Route::get('/lorem-ipsum', 'LoremIpsumController@getIndex'); // Posts for submitting the lorem ipsum generator form Route::post('/lorem-ipsum', 'LoremIpsumController@postGenerate'); // Gets main page for random user generator Route::get('/user-generator', 'UserGeneratorController@getIndex'); // Posts for submitting the random user generator form Route::post('/user-generator', 'UserGeneratorController@postGenerate'); // Gets main page for password generator Route::get('/password-generator', 'PasswordGeneratorController@getIndex'); // Posts for submitting the password generator form Route::post('/password-generator', 'PasswordGeneratorController@postGenerate'); }); <file_sep>/app/Http/Controllers/PasswordGeneratorController.php <?php namespace Project3\Http\Controllers; use Project3\Http\Controllers\Controller; use Illuminate\Http\Request; class PasswordGeneratorController extends Controller { /** * Responds to requests to GET /password-generator. * Returns the default view. */ public function getIndex() { return view('password-generator.password-generator'); } /** * Responds to requests to POST /password-generator */ public function postGenerate(Request $request) { $this->validate($request, [ 'number_of_words' => 'required|numeric|between:1,20' ]); $number_of_words = $request->input('number_of_words', '3'); $add_number = $request->input('add_number'); $add_symbol = $request->input('add_symbol'); $case = $request->input('case'); # populate list of words from external page. DOMDocument logic courtesy of http://stackoverflow.com/questions/17638165/get-ul-li-a-string-values-and-store-them-in-a-variable-or-array-php $words = []; # there are 15 pages to scrape, where the numbers in the url are i and i + 1, so start at i = 1 and increment by 2 for ($i=1; $i <= 17; $i = $i + 2) { # pad numbers for url with a zero if they are single digit $first_number = $i < 10 ? '0' . $i : $i; $second_number = $i + 1 < 10 ? '0' . ($i + 1) : ($i + 1); $html = file_get_contents('http://www.paulnoll.com/Books/Clear-English/words-' . $first_number . '-' . $second_number . '-hundred.html'); $doc = new \DOMDocument(); @$doc->loadHTML($html); foreach ($doc->getElementsByTagName('li') as $li) { $words[] = $li->nodeValue; } } $words_count = count($words); $symbols = array('~', '!', '@', '#', '$', '%', '^', '&', '*', '(', ')', '+', '=', '\\', '/', '<', '>', '?', '.', ',', ':', ';'); $symbols_count = count($symbols); $password = ''; $error = ''; # build the password into an array $temp_array = array_rand($words, $number_of_words); foreach ($temp_array as $value) { # strip all special characters and white space $clean = trim(preg_replace('/[^A-Za-z0-9]/', '', $words[$value])); # Check whether to convert to all uppercase or all lowercase, default lowercase $clean = $case == 'upper' ? strtoupper($clean) : strtolower($clean); $password = $clean . '-' . $password; } # remove trailing hyphen $password = substr($password, 0, -1); # add a number if needed if (isset($add_number)) { $password = $password . rand(0, 9); } # add a symbol if needed if (isset($add_symbol)) { $password = $password . $symbols[rand(0, $symbols_count - 1)]; } return view('password-generator.password-generator')->with('password',$password); } }
ec60fc924419d0d7612bec8d828c291a866e8b51
[ "Markdown", "PHP" ]
6
PHP
K-Tros/DWA15-P3
6eda07f5692f83f8fd886727f33ca035f6dd0c74
b9a9460081f93d4c069c478a9e6c9fa64f13f1f3
refs/heads/master
<file_sep>"""Name-en-US: CSV Reader Description-en-US: Ingests CSV data from a file, and uses it to change an object's PSR.' """ import c4d import csv def SetStatus(status): op[c4d.ID_USERDATA,3] = status def main(): # Init SetStatus("") # User Inputs csv_filename = op[c4d.ID_USERDATA,2] if not (csv_filename): SetStatus("Please load a *.csv file.") return sniffer = csv.Sniffer() sniff_range = 4096 with open(csv_filename, 'r') as f: dialect = sniffer.sniff( f.read(sniff_range), delimiters=";,\t" ) f.seek(0) # Return to the start has_header = sniffer.has_header(f.read(sniff_range)) f.seek(0) reader = csv.reader(f, dialect) for row in reader: print row # TODO: Read in data, and map it to fields by header name.<file_sep># C4D-CSV CSV Importer for Cinema 4D
a54af93cbb668b8c2ac000523aa8a9b1f51a32d2
[ "Markdown", "Python" ]
2
Python
donovankeith/C4D-CSV
ddfd78abcca045d9069955923b80764b0951dd26
ceb757b4d0073027bca9505425afb1af9fc84812
refs/heads/master
<repo_name>sansuke05/dakimakura_arduino<file_sep>/dakimakura.ino #include <SoftwareSerial.h> #define buttonPin A0 int buttonState = 0; SoftwareSerial android(12,13); void setup() { android.begin(115200); Serial.begin(19200); Serial.write("init"); pinMode(buttonPin, INPUT); } void loop() { buttonState = digitalRead(buttonPin); if(buttonState == HIGH || Serial.available()) { Serial.write("Pushed!\n"); android.write("1"); delay(1000); } }
47b7622e18df1fd315bcb7e1ad40d62ce11d1b5e
[ "C++" ]
1
C++
sansuke05/dakimakura_arduino
c440a990fa51ba6936406041947c11a8d2f021eb
c96e026c61d80a1523263122ce612f83d7535283
refs/heads/master
<repo_name>doctor12th/test_task<file_sep>/README.md 1. MYSQL: create views from existing database 2. PHP: select and sort created views, using JQuery and JSON <file_sep>/getdata.php <?php switch ($_GET['view']) { case 'faktury' : $viewName = 'faktury'; $orderBy = 'faktura'; break; case 'faktury_pozycje' : $viewName = 'faktury_pozycje'; $orderBy = 'id'; break; default: $viewName = 'faktury'; break; } $where1 = !empty($_GET['filter_date']) ? 'WHERE data = :filter_date' : ''; $where2 = !empty($_GET['filter_id']) ? " WHERE symbol = :filter_id" : ''; $orderType = (isset($_GET['sort_type'])) ? "DESC" : "ASC"; $order = $orderBy && $orderType ? " ORDER BY $orderBy $orderType " : ''; $sql = "SELECT * FROM $viewName $where1 $where2 $order"; $queryParams = array(); if ($where1) $queryParams[':filter_date'] = $_GET['filter_date']; if ($where2) $queryParams[':filter_id'] = $_GET['filter_id']; $databaseConnection = new PDO("mysql:host=localhost;dbname=test", "root", ""); $databaseConnection->exec("set names utf8"); $statement = $databaseConnection->prepare($sql); $statement->execute($queryParams); $data = $statement->fetchAll(PDO::FETCH_ASSOC); header('Content-Type: application/json'); echo json_encode($data);
c6b87ae26d27d6364ed7fcf07bd0102c1d5c2e6a
[ "Markdown", "PHP" ]
2
Markdown
doctor12th/test_task
9b370e0f9819febaf1d9105491c546699f860b61
568a105f7c238651107075beb12113f2ef8d08ad
refs/heads/master
<repo_name>PawanGulati/NITmdb<file_sep>/movie/migrations/0007_auto_20200413_0717.py # Generated by Django 3.0.5 on 2020-04-13 01:47 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('movie', '0006_auto_20200413_0650'), ] operations = [ migrations.AlterField( model_name='movie', name='IMDB_rating', field=models.FloatField(default=0, max_length=10), ), ] <file_sep>/movie/views.py from django.shortcuts import redirect from django.views.generic import ListView, DetailView, CreateView, DeleteView, UpdateView from django.contrib.auth.mixins import LoginRequiredMixin, UserPassesTestMixin from django.urls import reverse_lazy from .models import Movie # Create your views here. class MovieListView(ListView): model = Movie ordering = ['-release_date'] paginate_by = 6 class MovieDetailView(DetailView): model = Movie class MovieCreateView(LoginRequiredMixin, CreateView): model = Movie fields = ['movie_name', 'description', 'poster_image', 'genre', 'language', 'IMDB_rating', 'cast', 'carousal_pic1', 'carousal_pic2', 'carousal_pic3'] def form_valid(self, form): form.instance.director = self.request.user return super().form_valid(form) class MovieUpdateView(LoginRequiredMixin, UserPassesTestMixin, UpdateView): model = Movie fields = ['movie_name', 'description', 'poster_image', 'genre', 'language', 'IMDB_rating', 'cast', 'carousal_pic1', 'carousal_pic2', 'carousal_pic3'] def form_valid(self, form): form.instance.director = self.request.user return super().form_valid(form) def test_func(self): movie = self.get_object() if self.request.user == movie.director: return True return False class MovieDeleteView(LoginRequiredMixin, UserPassesTestMixin, DeleteView): model = Movie fields = ['movie_name', 'description', 'poster_image', 'genre', 'language', 'IMDB_rating', 'cast', 'carousal_pic1', 'carousal_pic2', 'carousal_pic3'] success_url = reverse_lazy('movie_list') def test_func(self): movie = self.get_object() if self.request.user == movie.director: return True return False class MovieListView(ListView): model = Movie ordering = ['-release_date'] movie_value = request.GET.get('movie_searched') paginate_by = 6 def get_queryset(self): movies = class GenreListView(ListView): pass # redirecting root to homepage '/movie' def indexView(req): return redirect('movie/') <file_sep>/movie/migrations/0008_auto_20200413_0725.py # Generated by Django 3.0.5 on 2020-04-13 01:55 import django.core.validators from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('movie', '0007_auto_20200413_0717'), ] operations = [ migrations.AlterField( model_name='movie', name='IMDB_rating', field=models.FloatField(default=0, validators=[django.core.validators.MaxLengthValidator(10), django.core.validators.MinLengthValidator(0)]), ), ] <file_sep>/movie/migrations/0012_auto_20200413_1533.py # Generated by Django 3.0.5 on 2020-04-13 10:03 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('movie', '0011_auto_20200413_1447'), ] operations = [ migrations.AlterField( model_name='movie', name='carousal_pic1', field=models.ImageField(default='default.jpg', upload_to='images'), ), migrations.AlterField( model_name='movie', name='carousal_pic2', field=models.ImageField(default='default.jpg', upload_to='images'), ), migrations.AlterField( model_name='movie', name='carousal_pic3', field=models.ImageField(default='default.jpg', upload_to='images'), ), migrations.AlterField( model_name='movie', name='poster_image', field=models.ImageField(default='default.jpg', upload_to='images'), ), ] <file_sep>/movie/templates/movie/movie_form.html {% extends "movie/base.html" %} {% load crispy_forms_tags %} {% block content %} <div class="container p-3"> <center> {% if form.instance.pk is not None %} <h1>Update your Movie</h1> {% else %} <h1>Create your own Movie</h1> {% endif %} </center> <br> <form method="post" accept-charset="utf-8"> {% csrf_token %} {{form|crispy}} <input type="submit" name="create_movie" class="btn btn-info" style="width:100%"> </form> </div> {% endblock content %}<file_sep>/movie/templates/movie/movie_list.html {% extends "movie/base.html" %} {% load static %} {% block content %} <div class="root"> <div class="container p-3" style='height:calc(100% - 56px); '> <div class="row"> <div class="col-sm-12" style="width:100%;"> <div class="row"> {% for movie in movie_list %} <div class="col-sm-4"> {% include "movie/movie_card.html" %} </div> {% endfor %} </div> </div> <div class="col-sm-12 d-flex justify-content-center"> {% include "movie/pagination-bar.html" %} </div> </div> </div> </div> {% endblock content %}<file_sep>/movie/migrations/0009_auto_20200413_0837.py # Generated by Django 3.0.5 on 2020-04-13 03:07 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('movie', '0008_auto_20200413_0725'), ] operations = [ migrations.AlterField( model_name='movie', name='IMDB_rating', field=models.FloatField(default=0), ), migrations.AlterField( model_name='movie', name='carousal_pic1', field=models.ImageField(null=True, upload_to='movies'), ), migrations.AlterField( model_name='movie', name='carousal_pic2', field=models.ImageField(null=True, upload_to='movies'), ), migrations.AlterField( model_name='movie', name='carousal_pic3', field=models.ImageField(null=True, upload_to='movies'), ), ] <file_sep>/movie/models.py from django.db import models from django.contrib.auth.models import User from django.utils import timezone from django.urls import reverse_lazy # from django.core import validators # from django.core.validators import MaxLengthValidator, MinLengthValidator # resizing image pillow from PIL import Image # Create your models here.to, on_delete class Movie(models.Model): GENRE = ( ('ACTION', 'ACTION'), ('DRAMA', 'DRAMA'), ('CRIME', 'CRIME'), ('COMEDY', 'COMEDY'), ('ROMANCE', 'ROMANCE'), ('MYSTERY', 'MYSTERY'), ) LANGUAGE = ( ('EN', 'English'), ('HN', 'Hindi'), ('FR', 'French'), ('CH', 'Chineese'), ('KO', 'Korean'), ) movie_name = models.CharField(max_length=200, null=True) description = models.TextField(max_length=500, null=True) poster_image = models.ImageField(default='images/default.jpg', upload_to='images') genre = models.CharField(choices=GENRE, max_length=7, null=True) language = models.CharField(choices=LANGUAGE, max_length=7, null=True) release_date = models.DateTimeField(default=timezone.now) IMDB_rating = models.FloatField(default=0,) director = models.ForeignKey(User, on_delete=models.CASCADE, null=True) cast = models.CharField(max_length=100, null=True) carousal_pic1 = models.ImageField( default='default.jpg', upload_to='images') carousal_pic2 = models.ImageField( default='default.jpg', upload_to='images') carousal_pic3 = models.ImageField( default='default.jpg', upload_to='images') def truncate_str(self): return self.description[0:100] + ' ....' # redirection after creation of movie def get_absolute_url(self, **kwargs): return reverse_lazy('movie_detail', kwargs={'pk': self.pk}) def __str__(self): return self.movie_name # implementing image resizing def save(self): super().save() img = Image.open(self.poster_image.path) if img.height > 100 or img.width > 100: print(0) output_size = (100, 100) img.thumbnail(output_size) img.save(self.poster_image.path) # TODO will see if get time to do class Review(models.Model): pass class Comment(models.Model): pass class Download_link(models.Model): movie = models.ForeignKey( Movie, on_delete=models.CASCADE, related_name='links', null=True) link = models.URLField(default='#') <file_sep>/movie/urls.py from django.urls import path, include from . import views urlpatterns = [ path('', views.MovieListView.as_view(), name='movie_list'), path('<int:pk>', views.MovieDetailView.as_view(), name='movie_detail'), path('new/', views.MovieCreateView.as_view(), name='movie_create'), path('<int:pk>/update/', views.MovieUpdateView.as_view(), name='movie_update'), path('<int:pk>/delete/', views.MovieDeleteView.as_view(), name='movie_delete'), path('search/>', views.MovieSearchView.as_view(), name='movie_search'), ] <file_sep>/movie/migrations/0002_auto_20200412_0906.py # Generated by Django 3.0.5 on 2020-04-12 03:36 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('movie', '0001_initial'), ] operations = [ migrations.AddField( model_name='movie', name='IMDB_rating', field=models.IntegerField(default=0), ), migrations.AddField( model_name='movie', name='description', field=models.TextField(max_length=500, null=True), ), migrations.AddField( model_name='movie', name='genre', field=models.CharField(choices=[('ACTION', 'ACTION'), ('DRAMA', 'DRAMA'), ('CRIME', 'CRIME'), ('COMEDY', 'COMEDY'), ('ROMANCE', 'ROMANCE'), ('MYSTERY', 'MYSTERY')], max_length=7, null=True), ), migrations.AddField( model_name='movie', name='language', field=models.CharField(choices=[('EN', 'English'), ('HN', 'Hindi'), ('FR', 'French'), ('CH', 'Chineese'), ('KO', 'Korean')], max_length=7, null=True), ), migrations.AddField( model_name='movie', name='movie_name', field=models.CharField(max_length=200, null=True), ), migrations.AddField( model_name='movie', name='poster_image', field=models.ImageField(null=True, upload_to='movies'), ), migrations.AddField( model_name='movie', name='release_date', field=models.DateTimeField(null=True), ), ] <file_sep>/movie/templates/movie/movie_detail.html {% extends "movie/base.html" %} {% load static %} {% block content %} <div class="root"> <div class="container p-3"> <div class="row"> <div class="col-sm-12"> {% include "movie/movie-carousal.html" %} </div> <div class="col-sm-12 mt-4 p-2 d-flex" style="border:1px solid black; height:13rem"> <img src="{{movie.poster_image.url}}" alt="titleImage" style="width:20%;" class="mr-3"> <div> <h3>{{movie.movie_name}}</h3> <p>{{movie.description}}</p> <div class="d-flex"> <div> <h6>CAST : <em>{{movie.cast}}</em></h6> <h6><em>Category : </em>{{movie.genre}}</h6> <h6><em>IMDB rating : </em>{{movie.IMDB_rating}}</h6> </div> <div class="pl-5"> <a href="{% url 'movie_update' movie.id %}" class="btn btn-warning mr-4" title="movie-update">Update It</a> <a href="{% url 'movie_delete' movie.id %}" class="btn btn-danger" title="movie-delete">Delete It</a> </div> </div> </div> </div> <div class="col-sm-12 mt-4 p-2 d-flex justify-content-around align-items-center" style="border:1px solid black; height:12rem"> <h3>Download LINKS : </h3> <br> <a href="#" class="btn btn-info">DOWNLOAD LINK 1</a> <a href="#" class="btn btn-info">DOWNLOAD LINK 2</a> <a href="#" class="btn btn-info">DOWNLOAD LINK 3</a> <a href="#" class="btn btn-info">DOWNLOAD LINK 4</a> </div> <div class="col-sm-12 mt-4 p-2" style="border:1px solid black; "> <h3>Comments</h3> </div> </div> </div> </div> {% endblock content %}<file_sep>/movie/migrations/0006_auto_20200413_0650.py # Generated by Django 3.0.5 on 2020-04-13 01:20 from django.db import migrations, models import django.db.models.deletion import django.utils.timezone class Migration(migrations.Migration): dependencies = [ ('movie', '0005_auto_20200412_1942'), ] operations = [ migrations.AddField( model_name='download_link', name='link', field=models.URLField(default='#'), ), migrations.AddField( model_name='download_link', name='movie', field=models.ForeignKey(null=True, on_delete=django.db.models.deletion.CASCADE, related_name='links', to='movie.Movie'), ), migrations.AlterField( model_name='movie', name='release_date', field=models.DateTimeField(default=django.utils.timezone.now), ), ] <file_sep>/user/views.py from django.shortcuts import render, redirect from .forms import UserRegistrationForm # Create your views here. from django.contrib import messages # Registration view def register(req): form = UserRegistrationForm() if req.method == 'POST': form = UserRegistrationForm(req.POST) if form.is_valid(): username = form.cleaned_data.get('username') messages.success(req, f'Account created for {username}') form.save() return redirect('login') return render(req, 'user/register.html', {'form': form}) # for login and logout views I am using build-in LoginView and LogoutView
4952f8eca00b6e5455ae6dea4f0161a9699b222b
[ "Python", "HTML" ]
13
Python
PawanGulati/NITmdb
aee65d69c2d8178addaf4cedddde1cbe3f17f4ac
db96f04ab67e06b5d3b2c5b226031553282f4b19
refs/heads/master
<file_sep>package nmap import "net/http" // Mapper detects apps and checks if they are securely configured type Mapper interface { // App returns the app associated with the mapper App() string // KnownPorts returns the app known ports KnownPorts() []int // HasApp returns true if the response is associated with the targeted app HasApp(port int, header http.Header, body string) bool // Insecure returns whether the app is insecure and the reason for that Insecure(addr string) (bool, string) } <file_sep>package gcp import ( "encoding/json" "fmt" "github.com/twistlock/cloud-discovery/internal/shared" "google.golang.org/api/container/v1" "io/ioutil" "net/http" ) // DiscoverGKE retrieves a list of all GKE data func DiscoverGKE(opt Options, emitFn func(result shared.CloudDiscoveryResult)) error { client, projectID, err := client(opt.ServiceAccount) if err != nil { return err } var nextToken string // Get all available zones // https://cloud.google.com/kubernetes-engine/docs/reference/rest/ resp, err := client.Get(fmt.Sprintf("https://container.googleapis.com/v1beta1/projects/%s/locations", projectID)) if err != nil { return err } var locations struct { Locations []struct { Type string `json:"type"` Name string `json:"name"` } `json:"locations"` } data, err := ioutil.ReadAll(resp.Body) resp.Body.Close() if err != nil { return err } if err := json.Unmarshal(data, &locations); err != nil { return err } for _, location := range locations.Locations { if location.Type != "ZONE" { continue } // https://cloud.google.com/kubernetes-engine/docs/reference/rest/ url := fmt.Sprintf("https://container.googleapis.com/v1beta1/projects/%s/locations/%s/clusters", projectID, location.Name) req, err := http.NewRequest(http.MethodGet, url, nil) if err != nil { return err } // Set next page token in case there are more results to be queried if nextToken != "" { q := req.URL.Query() q.Add("pageToken", nextToken) } resp, err := client.Do(req) if err != nil { return err } defer resp.Body.Close() body, err := ioutil.ReadAll(resp.Body) if err != nil { return err } var clusters container.ListClustersResponse if err := json.Unmarshal(body, &clusters); err != nil { return err } res := shared.CloudDiscoveryResult{ Region: location.Name, Type: "GKE", } for _, f := range clusters.Clusters { res.Assets = append(res.Assets, shared.CloudAsset{ID: f.Name, Data: f}) } emitFn(res) } return nil } <file_sep>package shared import "time" // CloudDiscoveryResults contains the result of the cloud discovery type CloudDiscoveryResults struct { Modified time.Time Results []CloudDiscoveryResult } // CloudDiscoveryResult is the result of scanning a specific cloud provider region and type type CloudDiscoveryResult struct { Region string `json:"region"` // Region is the provider region/projects Type string `json:"type"` // Type is the provider result type Assets []CloudAsset `json:"assests"` // Assets are the list of assets discovered in the cloud scan } // CloudAsset represents an entity (cluster/container/etc...) for a specific cloud provider type CloudAsset struct { ID string `json:"id"` // ID is the assest ID Data interface{} `json:"data"` // Data is expanded customized asset data } type Discoverer interface { Discover() (*CloudDiscoveryResult, error) } // Provider is the cloud provider type Provider string const ( ProviderAWS Provider = "aws" ProviderGCP Provider = "gcp" ProviderAzure Provider = "azure" ) // Format is the output format type Format string const ( FormatJson Format = "json" FormatCSV Format = "csv" ) // Credentials holds authentication data for a specific provider type Credentials struct { Provider Provider `json:"provider"` // Provider is the authentication provider (AWS/Azure/GCP) ID string `json:"id"` // ID is the access key id used to access the provider data Secret string `json:"secret"` // Secret is the access key secret } // CloudDiscoveryRequest repsents a request to scan a cloud provider using a set of credentials type CloudDiscoveryRequest struct { Credentials []Credentials `json:"credentials"` } type CloudNmapRequest struct { Subnet string `json:"subnet"` // Subnet is the subnet to scan AutoDetect bool `json:"auto"` // AutoDetect indicates subnet should be auto-detected Verbose bool `json:"verbose"` // Verbose indicates whether to output debug data from nmap } // CloudNmapResult is a single host-port result of a cloud discovery nmap query type CloudNmapResult struct { Host string `json:"host"` // Host is the target host IP Port int `json:"port"` // Port is the target host port App string `json:"app"` // App is the name of the detected app Insecure bool `json:"insecure"` // Insecure indicates whether the app has secure Reason string `json:"reason"` // Reason provides detailed reasoning when the app is insecure } <file_sep>package aws import ( "fmt" "github.com/aws/aws-sdk-go/service/lambda" "github.com/twistlock/cloud-discovery/internal/shared" ) type lambdaClient struct { opt Options } // NewServerlessClientAWS create a new aws serverless client func NewLambdaClient(opt Options) *lambdaClient { return &lambdaClient{ opt: opt, } } // Discover retrieves a list of functions for the settings provided to the client func (s *lambdaClient) Discover() (*shared.CloudDiscoveryResult, error) { var res []shared.CloudAsset session, err := CreateAWSSession(&s.opt) if err != nil { return nil, err } client := lambda.New(session) if err != nil { return nil, err } var nextMarker string // A string returned by aws api if there are more functions to quiry after list functions is called truncated := true // A flag to indicate if the list result is partial and more quries are needed for truncated { functionVersion := "ALL" // Scan all versions of a function input := &lambda.ListFunctionsInput{FunctionVersion: &functionVersion} if nextMarker != "" { input.Marker = &nextMarker } functions, err := client.ListFunctions(input) if err != nil { return nil, err } if functions == nil { return nil, fmt.Errorf("received nil function list from AWS %s", s.opt.Region) } for _, f := range functions.Functions { res = append(res, shared.CloudAsset{ID: *f.FunctionName, Data: struct { CodeSha256 *string `json:"codeSha256"` CodeSize *int64 `json:"codeSize"` Description *string `json:"description"` FunctionArn *string `json:"functionARN"` FunctionName *string `json:"functionName"` Handler *string `json:"handler"` LastModified *string `json:"lastModified"` MasterArn *string `json:"masterArn"` MemorySize *int64 `json:"memorySize"` RevisionId *string `json:"revisionId"` Role *string `json:"role"` Runtime *string `json:"runtime"` Timeout *int64 ` json:"timeout"` Version *string ` json:"version"` }{ CodeSha256: f.CodeSha256, CodeSize: f.CodeSize, Description: f.Description, FunctionArn: f.FunctionArn, FunctionName: f.FunctionName, Handler: f.Handler, LastModified: f.LastModified, MasterArn: f.MasterArn, MemorySize: f.MemorySize, RevisionId: f.RevisionId, Role: f.Role, Runtime: f.Runtime, Timeout: f.Timeout, Version: f.Version, }}) } if functions.NextMarker == nil { truncated = false break } nextMarker = *functions.NextMarker } return &shared.CloudDiscoveryResult{Assets: res, Region: s.opt.Region, Type: "Lambda"}, nil } <file_sep>package nmap import ( "fmt" "github.com/globalsign/mgo" "net/http" "strings" "time" ) type mongoMapper struct{} func NewMongoMapper() *mongoMapper { return &mongoMapper{} } func (*mongoMapper) App() string { return "mongod" } func (m *mongoMapper) KnownPorts() []int { // https://docs.mongodb.com/manual/reference/default-mongodb-port/ return []int{27017, 27018, 27019} } func (*mongoMapper) HasApp(port int, respHeader http.Header, body string) bool { body = strings.ToLower(body) return strings.Contains(body, "mongo") } func (*mongoMapper) Insecure(addr string) (bool, string) { conn, err := mgo.DialWithTimeout(fmt.Sprintf("mongodb://%s", addr), time.Second*1) if err == nil { _, err := conn.DatabaseNames() conn.Close() if err == nil { return true, "missing authorization" } } return false, "" } <file_sep>package aws import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/eks" "github.com/twistlock/cloud-discovery/internal/shared" "time" ) type eksClient struct { options Options } // NewEKSClient creates a new EKS (Amazon Elastic Kubernetes Service) client func NewEKSClient(options Options) *eksClient { return &eksClient{options: options} } func (c *eksClient) Discover() (result *shared.CloudDiscoveryResult, err error) { sess, err := CreateAWSSession(&c.options) if err != nil { return nil, err } svc := eks.New(sess) var clusters []*string var nextToken *string for { out, err := svc.ListClusters(&eks.ListClustersInput{NextToken: nextToken}) if err != nil { return nil, err } clusters = append(clusters, out.Clusters...) nextToken = out.NextToken if nextToken == nil { break } } // For each cluster name, fetch its information var assets []shared.CloudAsset for _, cluster := range clusters { out, err := svc.DescribeCluster(&eks.DescribeClusterInput{Name: cluster}) if err != nil { return nil, err } assets = append(assets, shared.CloudAsset{ID: aws.StringValue(out.Cluster.Name), Data: struct { ARN *string `json:"arn"` CreatedAt *time.Time `json:"createdAt"` Endpoint *string `json:"endpoint"` RoleArn *string `json:"roleArn"` Status *string `json:"status"` Version *string `json:"version"` }{ ARN: out.Cluster.Arn, CreatedAt: out.Cluster.CreatedAt, RoleArn: out.Cluster.RoleArn, Status: out.Cluster.Status, Version: out.Cluster.Version, }, }) } return &shared.CloudDiscoveryResult{Assets: assets, Region: c.options.Region, Type: "EKS"}, nil } <file_sep>package nmap import ( "crypto/tls" "net/http" "time" ) // insecureClient retuns an HTTP client without TLS validations func insecureClient() *http.Client { return &http.Client{Timeout: time.Second * 2, Transport: &http.Transport{TLSClientConfig: &tls.Config{InsecureSkipVerify: true}}} } // portMapper is a generic port mapper for known apps type portMapper struct { app string ports []int } func NewPortMapper(app string, ports ...int) *portMapper { return &portMapper{app: app, ports: ports} } func (p *portMapper) App() string { return p.app } func (p *portMapper) HasApp(port int, respHeader http.Header, body string) bool { return false } func (p *portMapper) KnownPorts() []int { return p.ports } func (p *portMapper) Insecure(addr string) (bool, string) { return false, "" } <file_sep>package main import ( "encoding/json" "fmt" "github.com/twistlock/cloud-discovery/internal/nmap" "github.com/twistlock/cloud-discovery/internal/provider" "github.com/twistlock/cloud-discovery/internal/shared" "github.com/urfave/cli" "io/ioutil" "log" "os" ) func main() { app := cli.NewApp() app.Name = "cloud-discovery" app.Usage = " Cloud Discovery provides a point in time enumeration of all the cloud native platform services" app.Version = "1.0.0" var configPath, format, subnet string app.Commands = []cli.Command{ { Name: "discover", Usage: "Discover all cloud assets", Flags: []cli.Flag{cli.StringFlag{ Name: "config", Usage: "Path to credential configuration", Destination: &configPath, }, cli.StringFlag{ Name: "format", Usage: "Output Formatting (json or csv)", Value: "csv", Destination: &format, }, }, Action: func(c *cli.Context) error { if configPath == "" { return fmt.Errorf("missing config path") } data, err := ioutil.ReadFile(configPath) if err != nil { return err } var creds []shared.Credentials if err := json.Unmarshal(data, &creds); err != nil { return err } provider.Discover(creds, os.Stdout, shared.Format(format)) return nil }, }, { Name: "nmap", Usage: "Scan all exposed cloud assets", Flags: []cli.Flag{cli.StringFlag{ Name: "subnet", Usage: "The subnet to scan", Value: "127.0.0.1", Destination: &subnet, }, }, Action: func(c *cli.Context) error { nmap.Nmap(os.Stdout, subnet, true) return nil }, }, } err := app.Run(os.Args) if err != nil { log.Fatal(err) } } <file_sep>package nmap import ( "net/http" "strings" ) type mysqlMapper struct{} func NewMysqlMapper() *mysqlMapper { return &mysqlMapper{} } func (*mysqlMapper) App() string { return "mysql" } func (*mysqlMapper) HasApp(port int, header http.Header, body string) bool { body = strings.ToLower(body) return strings.Contains(body, "packets") && strings.Contains(body, "order") } func (m *mysqlMapper) KnownPorts() []int { // https://docs.mongodb.com/manual/reference/default-mongodb-port/ return []int{3306} } func (*mysqlMapper) Insecure(addr string) (bool, string) { return false, "" } <file_sep>package nmap import ( "fmt" "net/http" "strings" ) type registryMapper struct{} func NewRegistryMapper() *registryMapper { return &registryMapper{} } func (m *registryMapper) App() string { return "docker registry" } func (m *registryMapper) HasApp(port int, respHeader http.Header, body string) bool { for h, _ := range respHeader { if strings.Contains(strings.ToLower(h), "docker") { return true } } return false } func (m *registryMapper) KnownPorts() []int { // https://docs.mongodb.com/manual/reference/default-mongodb-port/ return []int{5000} } func (m *registryMapper) Insecure(addr string) (bool, string) { resp, err := insecureClient().Get(fmt.Sprintf("http://%s/v2/_catalog", addr)) if err == nil { resp.Body.Close() if resp.StatusCode == http.StatusOK { return true, "missing authorization" } } return false, "" } <file_sep>package gcp import ( "encoding/json" "fmt" "github.com/twistlock/cloud-discovery/internal/shared" "io/ioutil" "net/http" ) type gcrClient struct { opt Options } // NewGCRClient creates a new google container registry client func NewGCRClient(opt Options) *gcrClient { return &gcrClient{opt: opt} } // Discover retrieves all repositories for the settings provided to the client func (s *gcrClient) Discover() (*shared.CloudDiscoveryResult, error) { client, _, err := client(s.opt.ServiceAccount) if err != nil { return nil, err } // Use catalog API // https://docs.docker.com/registry/spec/api/#catalog catalogUrl := fmt.Sprintf("https://%s/v2/_catalog", s.opt.Region) result := &shared.CloudDiscoveryResult{ Region: s.opt.Region, Type: "GCR", } b, err := client.Get(catalogUrl) if err != nil { return nil, err } body, err := ioutil.ReadAll(b.Body) b.Body.Close() if err != nil { return nil, err } if b.StatusCode != http.StatusOK { return nil, fmt.Errorf("failed to to query %s %s %s", catalogUrl, b.Status, string(body)) } var response struct { Repositories []string `json:"repositories"` } err = json.Unmarshal(body, &response) if err != nil { return nil, err } result.Assets = append(result.Assets) for _, repo := range response.Repositories { result.Assets = append(result.Assets, shared.CloudAsset{ ID: repo, }) } return result, nil } <file_sep>FROM golang:1.11.1 WORKDIR /go/src/github.com/twistlock/cloud-discovery/ COPY . . RUN go fmt ./... RUN go vet ./... RUN CGO_ENABLED=0 GOOS=linux go build -a -installsuffix cgo -o app cmd/server/main.go FROM alpine:3.8 RUN apk --no-cache add ca-certificates nmap WORKDIR /licenses COPY /licenses/* ./ WORKDIR /root/ COPY --from=0 /go/src/github.com/twistlock/cloud-discovery/app . CMD ["./app"] <file_sep>package aws import ( "fmt" "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/ecs" "github.com/twistlock/cloud-discovery/internal/shared" ) type ecsClient struct { opt Options } // NewECSClient creates a new ECS (Amazon Elastic Container Service) client func NewECSClient(opt Options) *ecsClient { return &ecsClient{opt: opt} } func (c *ecsClient) Discover() (*shared.CloudDiscoveryResult, error) { sess, err := CreateAWSSession(&c.opt) if err != nil { return nil, err } svc := ecs.New(sess) // List regional ECS cluster arns var nextToken *string var arns []*string for { out, err := svc.ListClusters(&ecs.ListClustersInput{NextToken: nextToken}) if err != nil { return nil, err } arns = append(arns, out.ClusterArns...) nextToken = out.NextToken if nextToken == nil { break } } // Fetch information for each resource identifier // 1. Cluster name // 2. Number of instances (EC2 hosts) var clusters []shared.CloudAsset for _, arn := range arns { name, err := c.fetchClusterName(svc, arn) if err != nil { return nil, fmt.Errorf("error fetching ECS cluster name: %v", err) } // Fetch list of hosts var hosts []string var nextToken *string for { out, err := svc.ListContainerInstances(&ecs.ListContainerInstancesInput{Cluster: arn, NextToken: nextToken}) if err != nil { return nil, fmt.Errorf("error listing ECS cluster instance. =%v instances: %v", arn, err) } for _, arn := range out.ContainerInstanceArns { hosts = append(hosts, *arn) } nextToken = out.NextToken if nextToken == nil { break } } clusters = append(clusters, shared.CloudAsset{ID: name, Data: struct { Hosts []string `json:"hosts"` }{Hosts: hosts}}) } return &shared.CloudDiscoveryResult{Assets: clusters, Region: c.opt.Region, Type: "ECS"}, nil } func (c *ecsClient) fetchClusterName(svc *ecs.ECS, arn *string) (string, error) { out, err := svc.DescribeClusters(&ecs.DescribeClustersInput{Clusters: []*string{arn}}) if err != nil { return "", err } if len(out.Clusters) < 1 || out.Clusters[0].ClusterName == nil { return "", fmt.Errorf("unknown ECS cluster: %s", *arn) } return aws.StringValue(out.Clusters[0].ClusterName), nil } <file_sep>package aws import ( "fmt" "github.com/aws/aws-sdk-go/aws/credentials" "github.com/aws/aws-sdk-go/aws/credentials/ec2rolecreds" "github.com/aws/aws-sdk-go/aws/defaults" "github.com/aws/aws-sdk-go/aws/ec2metadata" "github.com/aws/aws-sdk-go/aws/endpoints" "github.com/aws/aws-sdk-go/aws/session" log "github.com/sirupsen/logrus" "github.com/twistlock/cloud-discovery/internal/shared" "time" ) // AWSSession creates a session for AWS services handling func CreateAWSSession(opt *Options) (*session.Session, error) { var creds *credentials.Credentials cfg := defaults.Config() if opt.UseAWSRole { // Get Role credentials from EC2 metadata endpoint. EC2RoleProvider retrieves credentials from the EC2 service, and keeps track if // those credentials are expired. endpoint, err := endpoints.DefaultResolver().EndpointFor(ec2metadata.ServiceName, opt.Region) if err != nil { return nil, err } creds = credentials.NewCredentials(&ec2rolecreds.EC2RoleProvider{ Client: ec2metadata.NewClient(*cfg, defaults.Handlers(), endpoint.URL, endpoint.SigningRegion), ExpiryWindow: 5 * time.Minute, }) } else { if opt.SecretAccessKey == "" { return nil, fmt.Errorf("missing secret key in AWS settings") } creds = credentials.NewStaticCredentials(opt.AccessKeyID, opt.SecretAccessKey, "") } return session.NewSession(cfg.WithCredentials(creds).WithRegion(opt.Region)) } func Discover(username, password string, emitFn func(result shared.CloudDiscoveryResult)) { var discoverers []shared.Discoverer opt := Options{ AccessKeyID: username, SecretAccessKey: <PASSWORD>, } for _, region := range eksRegions { opt.Region = region discoverers = append(discoverers, NewEKSClient(opt)) } for _, region := range ecsRegions { opt.Region = region discoverers = append(discoverers, NewECSClient(opt)) } for _, region := range lambdaRegions { opt.Region = region discoverers = append(discoverers, NewLambdaClient(opt)) } for _, region := range lambdaRegions { opt.Region = region discoverers = append(discoverers, NewECRClient(opt)) } for _, discoverer := range discoverers { result, err := discoverer.Discover() if err != nil { log.Debugf(err.Error()) } else if len(result.Assets) > 0 { emitFn(*result) } } } // eksRegions - Amazon known EKS regions list // https://docs.aws.amazon.com/general/latest/gr/rande.html#eks_region var eksRegions = []string{ "us-east-1", // N. Virginia "us-west-2", // Oregon } var ecsRegions = []string{ "us-east-2", // US East (Ohio) "us-east-1", // US East (N. Virginia) "us-west-1", // US West (N. California) "us-west-2", // US West (Oregon) "ap-northeast-1", // Asia Pacific (Tokyo) "ap-northeast-2", // Asia Pacific (Seoul) "ap-south-1", // Asia Pacific (Mumbai) "ap-southeast-1", // Asia Pacific (Singapore) "ap-southeast-2", // Asia Pacific (Sydney) "ca-central-1", // Canada (Central) "cn-north-1", // China (Beijing) "cn-northwest-1", // China (Ningxia) "eu-central-1", // EU (Frankfurt) "eu-west-1", // EU (Ireland) "eu-west-2", // EU (London) "eu-west-3", // EU (Paris) "sa-east-1", // South America (São Paulo) } // awsRegions - Amazon known Lambda regions list // https://docs.aws.amazon.com/general/latest/gr/rande.html#lambda_region var lambdaRegions = []string{ "us-east-2", "us-east-1", "us-west-1", "us-west-2", "ap-northeast-2", "ap-south-1", "ap-southeast-1", "ap-southeast-2", "ap-northeast-1", "ca-central-1", "eu-central-1", "eu-west-1", "eu-west-2", "sa-east-1", } <file_sep>package nmap import ( "fmt" "net/http" ) type kubeletMapper struct{} func NewKubeletMapper() *kubeletMapper { return &kubeletMapper{} } func (m *kubeletMapper) App() string { return "kubelet" } func (m *kubeletMapper) HasApp(port int, respHeader http.Header, body string) bool { return false } func (m *kubeletMapper) KnownPorts() []int { return []int{10250} } func (m *kubeletMapper) Insecure(addr string) (bool, string) { resp, err := insecureClient().Get(fmt.Sprintf("https://%s", addr)) if err == nil { resp.Body.Close() if resp.StatusCode == http.StatusOK { return true, "missing authorization for metrics API" } } return false, "" } <file_sep>package provider import ( "fmt" "github.com/twistlock/cloud-discovery/internal/provider/aws" "github.com/twistlock/cloud-discovery/internal/provider/azure" "github.com/twistlock/cloud-discovery/internal/provider/gcp" "github.com/twistlock/cloud-discovery/internal/shared" "io" "text/tabwriter" ) func Discover(creds []shared.Credentials, wr io.Writer, format shared.Format) { var writer ResponseWriter if format == shared.FormatJson { writer = shared.NewJsonResponseWriter(wr) } else { writer = NewTabResponseWriter(wr) } for _, cred := range creds { switch cred.Provider { case shared.ProviderGCP: gcp.Discover(cred.Secret, writer.Write) case shared.ProviderAzure: azure.Discover(cred.Secret, writer.Write) default: aws.Discover(cred.ID, cred.Secret, writer.Write) } } } type ResponseWriter interface { Write(shared.CloudDiscoveryResult) } type csvResponseWriter struct { tw *tabwriter.Writer } func NewTabResponseWriter(writer io.Writer) *csvResponseWriter { tw := shared.NewTabWriter(writer) fmt.Fprintf(tw, "Type\tRegion\tID\n") return &csvResponseWriter{tw: tw} } func (w *csvResponseWriter) Write(result shared.CloudDiscoveryResult) { for _, asset := range result.Assets { fmt.Fprintf(w.tw, "%s\t%s\t%s\n", result.Type, result.Region, asset.ID) } w.tw.Flush() } <file_sep>package azure import ( "context" "github.com/Azure/azure-sdk-for-go/services/web/mgmt/2018-02-01/web" "github.com/Azure/go-autorest/autorest" "github.com/Azure/go-autorest/autorest/adal" "github.com/Azure/go-autorest/autorest/azure" "github.com/twistlock/cloud-discovery/internal/shared" "strings" ) // DiscoverFunctions retrieves all Azure functions func DiscoverFunctions(opt Options, emitFn func(result shared.CloudDiscoveryResult)) error { spt, err := spt(opt) if err != nil { return err } ac := web.NewAppsClient(opt.SubscriptionID) ac.Authorizer = autorest.NewBearerAuthorizer(spt) functionApps, err := ac.List(context.Background()) if err != nil { return err } var result shared.CloudDiscoveryResult result.Type = "Azure Functions" const azureFunctionKind = "functionapp" for { apps := functionApps.Values() if len(apps) == 0 { return err } for _, app := range apps { if !strings.HasPrefix(strings.ToLower(*app.Kind), azureFunctionKind) { continue } if app.Name == nil || app.Location == nil { continue } emitFn(shared.CloudDiscoveryResult{ Region: *app.Location, Type: "Azure Functions", Assets: []shared.CloudAsset{ {ID: *app.Name, Data: app}, }, }) } if err := functionApps.Next(); err != nil { return err } } } // spt returns an authenticated service principal token using provided credentials func spt(opt Options) (*adal.ServicePrincipalToken, error) { oauthConfig, err := adal.NewOAuthConfig(azure.PublicCloud.ActiveDirectoryEndpoint, opt.TenantID) if err != nil { return nil, err } spt, err := adal.NewServicePrincipalToken(*oauthConfig, opt.ClientID, opt.Secret, azure.PublicCloud.ResourceManagerEndpoint) if err != nil { return nil, err } return spt, nil } <file_sep>package azure import ( "encoding/base64" "encoding/json" log "github.com/sirupsen/logrus" "github.com/twistlock/cloud-discovery/internal/shared" ) // Discover discovers all ACR assets func Discover(serviceAccount string, emitFn func(result shared.CloudDiscoveryResult)) { sa, err := base64.RawStdEncoding.DecodeString(serviceAccount) if err != nil { log.Errorf(err.Error()) return } var opt Options if err := json.Unmarshal([]byte(sa), &opt); err != nil { log.Errorf(err.Error()) return } if err := DiscoverFunctions(opt, emitFn); err != nil { log.Debugf(err.Error()) } if err := DiscoverACR(opt, emitFn); err != nil { log.Debugf(err.Error()) } } <file_sep>package aws // Options are options for getting credentials for AWS services type Options struct { AccessKeyID string // AccessKeyID is the access key ID to aws services SecretAccessKey string // SecretAccessKey is the secret access key to aws services Region string // Region is the region in query UseAWSRole bool // UseAWSRole is a flag indicates if local IAM role should be used for authentication, than username and password would be ignored } <file_sep>package main import ( "crypto/rand" "crypto/rsa" "crypto/subtle" "crypto/tls" "crypto/x509" "crypto/x509/pkix" "encoding/json" "encoding/pem" "fmt" "github.com/gorilla/mux" log "github.com/sirupsen/logrus" "github.com/twistlock/cloud-discovery/internal/nmap" "github.com/twistlock/cloud-discovery/internal/provider" "github.com/twistlock/cloud-discovery/internal/shared" "io" "io/ioutil" "math/big" "net" "net/http" "os" "time" ) func main() { config := struct { username string password string tlsCertPath string tlsKeyPath string port string }{ username: os.Getenv("BASIC_AUTH_USERNAME"), password: os.Getenv("BASIC_AUTH_PASSWORD"), tlsCertPath: os.Getenv("TLS_CERT_KEY"), tlsKeyPath: os.Getenv("TLS_CERT_PATH"), port: os.Getenv("PORT"), } if config.username == "" { config.username = "admin" log.Warnf("Username is not set. Setting it to %q", config.username) } if config.password == "" { const n = 16 const letterBytes = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ" b := make([]byte, n) if _, err := rand.Read(b); err != nil { panic(err) } for i := range b { b[i] = letterBytes[int(b[i])%len(letterBytes)] } config.password = string(b) log.Warnf("Password is not set. Setting it to %q", config.password) } if config.tlsCertPath == "" || config.tlsKeyPath == "" { log.Warnf("Missing TLS path, creating self-signed certificates") config.tlsKeyPath = "cert.key" config.tlsCertPath = "cert.pem" if err := genCert(config.tlsCertPath, config.tlsKeyPath, "localhost"); err != nil { log.Fatalf("Failed to generate TLS certs %v", err) } } if config.port == "" { config.port = "9083" log.Debugf(`Using default port: %q`, config.port) } r := mux.NewRouter() r.Use(func(next http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { user, pass, ok := r.BasicAuth() if !ok || subtle.ConstantTimeCompare([]byte(user), []byte(config.username)) != 1 || subtle.ConstantTimeCompare([]byte(pass), []byte(config.password)) != 1 { w.Header().Set("WWW-Authenticate", `Basic realm="Please enter your username and password for this site"`) w.WriteHeader(401) w.Write([]byte("Unauthorized.\n")) return } next.ServeHTTP(w, r) }) }) close := func(v interface{}) { if closer, ok := v.(io.Closer); ok { closer.Close() } } handleConn := func(w http.ResponseWriter, r *http.Request, out interface{}, validateFN func() error) (conn io.Writer, stop bool) { conn, err := func() (io.Writer, error) { limitedReader := &io.LimitedReader{R: r.Body, N: 100000} defer r.Body.Close() body, err := ioutil.ReadAll(limitedReader) if err != nil { return nil, fmt.Errorf("failed reading body %v", err) } if err := json.Unmarshal(body, out); err != nil { if err != nil { return nil, badRequestErr(fmt.Sprintf("bad input format %v", err)) } } if err := validateFN(); err != nil { return nil, badRequestErr(err.Error()) } hj, ok := w.(http.Hijacker) if !ok { return nil, fmt.Errorf("failed upgrading connection") } conn, _, err := hj.Hijack() if err != nil { return nil, fmt.Errorf("failed upgrading connection %v", err) } return conn, nil }() if err != nil { close(conn) log.Errorf(err.Error()) if isBadRequestErr(err) { http.Error(w, err.Error(), http.StatusBadRequest) } else { http.Error(w, "", http.StatusInternalServerError) } return nil, true } return conn, false } r.HandleFunc("/nmap", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { var req shared.CloudNmapRequest wr, stop := handleConn(w, r, &req, func() error { if req.Subnet == "" && !req.AutoDetect { return badRequestErr("missing subnet") } if req.AutoDetect { resp, err := http.Get("http://169.254.169.254/latest/meta-data/mac") if err != nil { return err } defer resp.Body.Close() mac, err := ioutil.ReadAll(resp.Body) if err != nil { return err } resp, err = http.Get(fmt.Sprintf("http://169.254.169.254/latest/meta-data/network/interfaces/macs/%s/subnet-ipv4-cidr-block", string(mac))) if err != nil { return err } defer resp.Body.Close() subnet, err := ioutil.ReadAll(resp.Body) if err != nil { return err } req.Subnet = string(subnet) return err } return nil }) if stop { return } defer close(wr) nmap.Nmap(wr, req.Subnet, req.Verbose) })).Methods(http.MethodPost) r.HandleFunc("/discover", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { var req shared.CloudDiscoveryRequest wr, stop := handleConn(w, r, &req, func() error { for _, cred := range req.Credentials { if cred.Provider == shared.ProviderAWS && cred.ID == "" { return fmt.Errorf("missing credential ID") } if cred.Secret == "" { return fmt.Errorf("missing credential secret") } } return nil }) if stop { return } defer close(wr) provider.Discover(req.Credentials, wr, shared.Format(r.URL.Query().Get("format"))) })).Methods(http.MethodPost) s := &http.Server{ TLSNextProto: make(map[string]func(*http.Server, *tls.Conn, http.Handler)), // Disable http2 Addr: fmt.Sprintf(":%s", config.port), Handler: r, ReadTimeout: 10 * time.Second, WriteTimeout: 10 * time.Second, MaxHeaderBytes: 1 << 20, } log.Fatal(s.ListenAndServeTLS(config.tlsCertPath, config.tlsKeyPath)) } func genCert(certPath, keyPath, host string) error { const rsaBits = 2048 priv, err := rsa.GenerateKey(rand.Reader, rsaBits) if err != nil { return err } notBefore := time.Now() notAfter := notBefore.Add(time.Hour * 24 * 365) // 1 Year serialNumberLimit := new(big.Int).Lsh(big.NewInt(1), 128) serialNumber, err := rand.Int(rand.Reader, serialNumberLimit) if err != nil { return err } template := x509.Certificate{ SerialNumber: serialNumber, Subject: pkix.Name{ Organization: []string{"Cloud discovery"}, }, NotBefore: notBefore, NotAfter: notAfter, IsCA: true, KeyUsage: x509.KeyUsageKeyEncipherment | x509.KeyUsageDigitalSignature | x509.KeyUsageCertSign, ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth}, BasicConstraintsValid: true, } if ip := net.ParseIP(host); ip != nil { template.IPAddresses = append(template.IPAddresses, ip) } else { template.DNSNames = append(template.DNSNames, host) } der, err := x509.CreateCertificate(rand.Reader, &template, &template, &priv.PublicKey, priv) if err != nil { return err } certOut, err := os.Create(certPath) if err != nil { return err } if err := pem.Encode(certOut, &pem.Block{Type: "CERTIFICATE", Bytes: der}); err != nil { return err } if err := certOut.Close(); err != nil { return err } keyOut, err := os.OpenFile(keyPath, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0600) if err != nil { return err } if err := pem.Encode(keyOut, &pem.Block{Type: "RSA PRIVATE KEY", Bytes: x509.MarshalPKCS1PrivateKey(priv)}); err != nil { return err } if err := keyOut.Close(); err != nil { return err } return nil } type badRequestErr string func (e badRequestErr) Error() string { return string(e) } func isBadRequestErr(err error) bool { _, ok := err.(badRequestErr) return ok } <file_sep># Twistlock Cloud Discovery Cloud Discovery provides point in time enumeration of all the cloud native platform services, such as container registries, managed Kubernetes platforms, and serverless services used across your cloud providers, accounts, and regions. Its a powerful tool for audit and security practitioners that want a simple way to discover all the 'unknown unknowns' across environments without having to manually login to multiple provider consoles, click through many pages, and manually export the data. Cloud Discovery connects to cloud providers' native platform APIs to discover services and their metadata and requires only read permissions. Cloud Discovery also has a network discovery option that uses port scanning to sweep IP ranges and discover cloud native infrastructure and apps, such as Docker Registries and Kubernetes API servers, with weak settings or authentication. This is useful to discover 'self-installed' cloud native components not provided as a service by a cloud provider, such as a Docker Registry running on an EC2 instance. Cloud Discovery is provided as a simple Docker container image that can be run anywhere and works well for both interactive use and automation. Cloud Discovery is [another](https://github.com/docker/swarmkit/pull/2239) [open](https://github.com/moby/moby/pull/15365) [source](https://github.com/moby/moby/pull/20111) [contribution](https://github.com/moby/moby/pull/21556) [provided](https://github.com/docker/distribution/pull/2362 ) by [Twistlock](https://www.twistlock.com). <img src="http://www.twistlock.com/wp-content/uploads/2017/11/Twistlock_Logo-Lockup_RGB.png" width="400"> # Environment variables 1. BASIC_AUTH_USERNAME - This variable determines the username to use for basic authentication. 2. BASIC_AUTH_PASSWORD - This variable determines the password to use for basic authentication. 3. TLS_CERT_PATH - This variable determines the path to the TLS certificate inside the container. By default the service generates self-signed certificates for localhost usage. 4. TLS_CERT_KEY - This variable determines the path to the TLS certificate key inside the container. # Example usage ## Start the container ```sh docker run -d --name cloud-discovery --restart=always \ -e BASIC_AUTH_USERNAME=admin -e BASIC_AUTH_PASSWORD=<PASSWORD> -e PORT=9083 -p 9083:9083 twistlock/cloud-discovery ``` ## Scan and list all AWS assets ```sh curl -k -v -u admin:pass --raw --data \ '{"credentials": [{"id":"<AWS_ACCESS_KEY>","secret":"<AWS_ACCESS_PASSWORD>"}]}' \ https://localhost:9083/discover ``` Output ```sh Type Region ID EKS us-east-1 k8s-cluster-1 ECS us-east-1 cluster-1 ECS us-east-1 cluster-2 ECS us-east-1 cluster-3 ECR us-east-2 cluster-1 ``` ## Scan all AWS assets and show full metadata for each of them ```sh curl -k -v -u admin:pass --raw --data \ '{"credentials": [{"id":"<AWS_ACCESS_KEY>","secret":"<AWS_ACCESS_PASSWORD>"}]}' https://localhost:9083/discover?format=json ``` ## Scan and list all GCP assets ```sh SERVICE_ACCOUNT=$(cat <service_account_secret> | base64 | tr -d '\n') curl -k -v -u admin:pass --raw --data '{"credentials": [{"secret":"'${SERVICE_ACCOUNT}'", "provider":"gcp"}]}' https://localhost:9083/discover ``` Output ```sh Type Region ID GKE us-central1-a cluster-1 GKE us-central1-a cluster-2 GCR gcr.io registry-1 GCR gcr.io registry-2 Functions us-central1 function-1 ``` ## Scan all GCP assets and show full metadata for each of them ```sh SERVICE_ACCOUNT=$(cat <service_account_secret> | base64 | tr -d '\n') curl -k -v -u admin:pass --raw --data '{"credentials": [{"secret":"'${SERVICE_ACCOUNT}'", "provider":"gcp"}]}' https://localhost:9083/discover?format=json ``` ## Port scan a subnet to discover cloud native infrastructure and apps Scan all open ports and automatically detect insecure apps (native cloud apps configured without proper authorization) Remark: If the container runs in AWS cluster, the subnet can be automatically extracted from [AWS metadata API server](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-instance-metadata.html) ```sh curl -k -v -u admin:pass --raw --data '{"subnet":"172.17.0.1", "debug": true}' https://localhost:9083/nmap ``` Output ``` Host Port App Insecure 172.17.0.1 5000 docker registry true 172.17.0.1 5003 docker registry false 172.17.0.1 27017 mongod true ``` <file_sep>module github.com/twistlock/cloud-discovery require ( cloud.google.com/go v0.32.0 // indirect contrib.go.opencensus.io/exporter/ocagent v0.3.0 // indirect github.com/Azure/azure-sdk-for-go v22.1.1+incompatible github.com/Azure/go-autorest v11.2.6+incompatible github.com/aws/aws-sdk-go v1.15.18 github.com/dgrijalva/jwt-go v3.2.0+incompatible // indirect github.com/globalsign/mgo v0.0.0-20180615134936-113d3961e731 github.com/gorilla/context v1.1.1 // indirect github.com/gorilla/mux v1.6.2 github.com/lair-framework/go-nmap v0.0.0-20180506230210-84c21710ccc8 github.com/satori/go.uuid v1.2.0 // indirect github.com/sirupsen/logrus v1.1.0 github.com/spf13/cobra v0.0.4-0.20180915222204-8d114be902bc // indirect github.com/urfave/cli v1.20.0 go.opencensus.io v0.18.0 // indirect golang.org/x/net v0.0.0-20181102091132-c10e9556a7bc // indirect golang.org/x/oauth2 v0.0.0-20180821212333-d2e6202438be google.golang.org/api v0.0.0-20181003000758-f5c49d98d21c google.golang.org/appengine v1.3.0 // indirect ) <file_sep>package aws import ( "fmt" "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/ecr" "github.com/twistlock/cloud-discovery/internal/shared" "time" ) type ecrClient struct { opt Options } // NewECRClient creates a new ECR client (Amazon Elastic Container Registry) func NewECRClient(opt Options) *ecrClient { return &ecrClient{opt: opt} } func (r *ecrClient) Discover() (*shared.CloudDiscoveryResult, error) { session, err := CreateAWSSession(&r.opt) ecr.New(session) client := ecr.New(session) if err != nil { return nil, err } result := shared.CloudDiscoveryResult{ Region: r.opt.Region, Type: "ECR", } var nextToken *string for { out, err := client.DescribeRepositories(&ecr.DescribeRepositoriesInput{NextToken: nextToken}) if err != nil { return nil, err } else if out == nil { return nil, fmt.Errorf("failed to describe repositories") } for _, repo := range out.Repositories { result.Assets = append(result.Assets, shared.CloudAsset{ID: aws.StringValue(repo.RepositoryName), Data: struct { ARN *string `json:"arn"` CreatedAt *time.Time `json:"createdAt"` RegistryId *string `json:"registryId"` RepositoryArn *string `json:"repositoryArn"` RepositoryUri *string `json:"repositoryUri"` Version *string `json:"version"` }{ CreatedAt: repo.CreatedAt, RegistryId: repo.RegistryId, RepositoryArn: repo.RepositoryArn, RepositoryUri: repo.RepositoryUri, }}) } if out.NextToken == nil { break } nextToken = out.NextToken } return &result, nil } <file_sep>package azure import ( "context" "github.com/Azure/azure-sdk-for-go/services/containerregistry/mgmt/2017-10-01/containerregistry" "github.com/Azure/azure-sdk-for-go/services/web/mgmt/2018-02-01/web" "github.com/Azure/go-autorest/autorest" "github.com/twistlock/cloud-discovery/internal/shared" ) // DiscoverACR retrieves all container registry data func DiscoverACR(opt Options, emitFn func(result shared.CloudDiscoveryResult)) error { spt, err := spt(opt) if err != nil { return err } ac := web.NewAppsClient(opt.SubscriptionID) ac.Authorizer = autorest.NewBearerAuthorizer(spt) client := containerregistry.NewRegistriesClient(opt.SubscriptionID) client.Authorizer = autorest.NewBearerAuthorizer(spt) registryList, err := client.List(context.Background()) if err != nil { return err } for { registries := registryList.Values() if len(registries) == 0 { return nil } var result shared.CloudDiscoveryResult result.Type = "ECR" for _, registry := range registries { if registry.Location == nil || registry.Name == nil { continue } result.Region = *registry.Location emitFn(shared.CloudDiscoveryResult{ Region: *registry.Location, Type: "ECR", Assets: []shared.CloudAsset{ {ID: *registry.Name, Data: registry}, }, }) } if err := registryList.Next(); err != nil { return err } } } <file_sep>package nmap import ( "fmt" gonmap "github.com/lair-framework/go-nmap" log "github.com/sirupsen/logrus" "github.com/twistlock/cloud-discovery/internal/shared" "io" "io/ioutil" "net/http" "os" "os/exec" "path/filepath" "time" ) func Nmap(wr io.Writer, subnet string, verbose bool) { tw := shared.NewTabWriter(wr) var nmapWriter io.Writer if verbose { nmapWriter = wr } else { nmapWriter = os.Stdout } fmt.Fprintf(tw, "\nHost\tPort\tApp\tInsecure\tReason\t\n") if err := nmap(subnet, 30, 30000, nmapWriter, func(result shared.CloudNmapResult) { fmt.Fprintf(tw, "%s\t%d\t%s\t%t\t%s\t\n", result.Host, result.Port, result.App, result.Insecure, result.Reason) }); err != nil { log.Error(err) } tw.Flush() } func nmap(subnet string, minPort, maxPort int, nmapWriter io.Writer, emitFn func(result shared.CloudNmapResult)) error { log.Debugf("Scanning subnet %s", subnet) dir, err := ioutil.TempDir("", "nmap") if err != nil { return err } defer os.RemoveAll(dir) resultPath := filepath.Join(dir, "nmap") // https://nmap.org/book/nping-man-output-options.html cmd := exec.Command( "nmap", subnet, "-v", "1", "-sT", "--max-retries", "0", "-p", fmt.Sprintf("%d-%d", minPort, maxPort), "-oX", resultPath, "--max-scan-delay", "3") cmd.Stdout = nmapWriter cmd.Stderr = nmapWriter if err := cmd.Run(); err != nil { return err } out, err := ioutil.ReadFile(resultPath) if err != nil { return err } nmap, err := gonmap.Parse(out) if err != nil { return err } mappers := []Mapper{ NewMongoMapper(), NewMysqlMapper(), NewRegistryMapper(), NewPortMapper("kube-apiserver", 6443), NewPortMapper("kube-router", 20244), NewPortMapper("kube-proxy", 10256), NewPortMapper("kubelet", 10255), NewKubeletMapper()} client := http.Client{Timeout: time.Second * 2} for _, host := range nmap.Hosts { for _, targetPort := range host.Ports { if len(host.Addresses) == 0 { continue } if host.Addresses[0].Addr == "0.0.0.0" { continue } addr := fmt.Sprintf("%s:%d", host.Addresses[0].Addr, targetPort.PortId) app := targetPort.Service.Name log.Debugf("Checking target port %v %v %v", host.Addresses[0], targetPort.PortId, targetPort.Protocol) if app == "unknown" || app == "" || (targetPort.PortId >= 5000 && targetPort.PortId <= 30000 && targetPort.Protocol == "tcp") { resp, err := client.Get(fmt.Sprintf("http://%s/v2/_catalog", addr)) found := false if err == nil { out, _ := ioutil.ReadAll(resp.Body) resp.Body.Close() body := string(out) for _, mapper := range mappers { if mapper.HasApp(targetPort.PortId, resp.Header, body) { app = mapper.App() found = true break } } } if !found { // Fallback to known port for _, mapper := range mappers { for _, port := range mapper.KnownPorts() { if port == targetPort.PortId { app = mapper.App() break } } } } } result := shared.CloudNmapResult{ Host: host.Addresses[0].Addr, Port: targetPort.PortId, App: app, } for _, mapper := range mappers { if mapper.App() == app { insecure, reason := mapper.Insecure(addr) if insecure { // Multiple mappers can apply to the same app, take precedence based on insecure findings result.Insecure = insecure result.Reason = reason break } } } emitFn(result) } } return nil } <file_sep>package azure // Options are options for getting cloud data for Azure services type Options struct { TenantID string `json:"tenantId"` ClientID string `json:"clientId"` Secret string `json:"clientSecret"` SubscriptionID string `json:"subscriptionId"` } <file_sep>package gcp // Options are options for getting cloud data for GCP services type Options struct { ServiceAccount string // ServiceAccount is the secret key used for authentication (in JSON format) Region string // Region is the region to query } <file_sep>.PHONY: build build: # Find all of the open source LICENSE files in the source code and include them in a /licenses directory inside the container image. # Inclusion of the license files may be a requirement for some to distribute the cloud-discovery container image. rm -rf licenses; mkdir -p licenses; find . | grep LICENSE | while IFS= read -r pathname; do filename=$$(echo $$pathname | tr "\.\/" "_" | sed "s/^__//"); cp $$pathname licenses/$$filename; done docker build -t twistlock/cloud-discovery . <file_sep>package gcp import ( "context" "encoding/base64" "encoding/json" log "github.com/sirupsen/logrus" "github.com/twistlock/cloud-discovery/internal/shared" "golang.org/x/oauth2/google" "net/http" ) // Discover discovers all GCR assets func Discover(serviceAccount string, emitFn func(result shared.CloudDiscoveryResult)) { sa, err := base64.StdEncoding.DecodeString(serviceAccount) if err != nil { log.Errorf(err.Error()) return } var discoverers []shared.Discoverer opt := Options{ ServiceAccount: string(sa), } for _, region := range gcrRegions { opt.Region = region discoverers = append(discoverers, NewGCRClient(opt)) } for _, region := range functionRegions { opt.Region = region discoverers = append(discoverers, NewFunctionsClient(opt)) } if err := DiscoverGKE(opt, emitFn); err != nil { log.Debugf(err.Error()) } for _, discoverer := range discoverers { result, err := discoverer.Discover() if err != nil { log.Debugf(err.Error()) } else if len(result.Assets) > 0 { emitFn(*result) } } } // functionRegions are regions for GCP cloud functions // See https://cloud.google.com/functions/docs/locations var functionRegions = []string{ "europe-west1", "asia-northeast1", "us-central1", "us-east1", } var gcrRegions = []string{ "gcr.io", "us.gcr.io", "eu.gcr.io", "asia.gcr.io", } func client(sa string) (client *http.Client, projectID string, err error) { // Use service key to create an authentication token conf, err := google.JWTConfigFromJSON([]byte(sa), "https://www.googleapis.com/auth/cloud-platform") if err != nil { return nil, "", err } var serviceAccount struct { ProjectID string `json:"project_id"` } if err := json.Unmarshal([]byte(sa), &serviceAccount); err != nil { return nil, "", err } return conf.Client(context.Background()), serviceAccount.ProjectID, nil } <file_sep>package gcp import ( "encoding/json" "fmt" "github.com/twistlock/cloud-discovery/internal/shared" "google.golang.org/api/cloudfunctions/v1" "io/ioutil" "net/http" ) type functionsClient struct { opt Options } // NewFunctionsClient creates a new google functions client func NewFunctionsClient(opt Options) *functionsClient { return &functionsClient{opt: opt} } // Discover retrieves a list of functions for the settings provided to the client func (s *functionsClient) Discover() (*shared.CloudDiscoveryResult, error) { client, projectID, err := client(s.opt.ServiceAccount) if err != nil { return nil, err } var res []shared.CloudAsset var nextToken string truncated := true // https://cloud.google.com/functions/docs/reference/rest/v1/projects.locations.functions/list url := fmt.Sprintf("https://cloudfunctions.googleapis.com/v1/projects/%s/locations/%s/functions", projectID, s.opt.Region) for truncated { req, err := http.NewRequest(http.MethodGet, url, nil) if err != nil { return nil, err } // Set next page token in case there are more results to be queried if nextToken != "" { q := req.URL.Query() q.Add("pageToken", nextToken) } resp, err := client.Do(req) if err != nil { return nil, err } defer resp.Body.Close() body, err := ioutil.ReadAll(resp.Body) if err != nil { return nil, err } var functions cloudfunctions.ListFunctionsResponse if err := json.Unmarshal(body, &functions); err != nil { return nil, err } for _, f := range functions.Functions { res = append(res, shared.CloudAsset{ID: f.Name, Data: f}) } if functions.NextPageToken == "" { truncated = false } nextToken = functions.NextPageToken } return &shared.CloudDiscoveryResult{ Region: s.opt.Region, Type: "Functions", Assets: res, }, nil } <file_sep>package shared import ( "encoding/json" log "github.com/sirupsen/logrus" "io" "os" "text/tabwriter" ) func init() { log.SetFormatter(&log.JSONFormatter{}) // Output to stdout instead of the default stderr // Can be any io.Writer, see below for File example log.SetOutput(os.Stdout) // Only log the warning severity or above. log.SetLevel(log.DebugLevel) } func NewTabWriter(wr io.Writer) *tabwriter.Writer { return tabwriter.NewWriter(wr, 0, 0, 5, ' ', tabwriter.TabIndent) } type jsonResposeWriter struct { w io.Writer } func NewJsonResponseWriter(w io.Writer) *jsonResposeWriter { return &jsonResposeWriter{w: w} } func (w *jsonResposeWriter) Write(result CloudDiscoveryResult) { out, _ := json.Marshal(result) w.w.Write(out) w.w.Write([]byte("\n")) }
fa015d1a8f7ad8b728a9baa09533fee0b876ae2f
[ "Markdown", "Makefile", "Go", "Go Module", "Dockerfile" ]
31
Go
jpadams/cloud-discovery
8d875eb00beedfc508cf918bb02ea3d6be0ab6b8
d37b11e12d403239ad6215c097fca5a384a2b70b