branch_name
stringclasses
15 values
target
stringlengths
26
10.3M
directory_id
stringlengths
40
40
languages
sequencelengths
1
9
num_files
int64
1
1.47k
repo_language
stringclasses
34 values
repo_name
stringlengths
6
91
revision_id
stringlengths
40
40
snapshot_id
stringlengths
40
40
input
stringclasses
1 value
refs/heads/master
<file_sep>package danielrajic.objects; public class Dackel extends Hund { } <file_sep>package danielrajic.laufverhalten; public class KannNichtLaufen implements ILaufVerhalten{ public void laufen() { System.out.println("Kann doch gar nicht laufen."); } } <file_sep>package danielrajic.objects; import danielrajic.bellverhalten.IBellVerhalten; import danielrajic.bellverhalten.LautBellen; import danielrajic.laufverhalten.ILaufVerhalten; import danielrajic.laufverhalten.SchnellLaufen; public abstract class Hund { //Instanzvariablen vom Typ des Interfaces. Defaultverhalten IBellVerhalten bellVerhalten = new LautBellen(); ILaufVerhalten laufVerhalten = new SchnellLaufen(); public void setBellVerhalten(IBellVerhalten pBellVerhalten) { bellVerhalten = pBellVerhalten; } public void setLaufVerhalten(ILaufVerhalten pLaufVerhalten) { laufVerhalten = pLaufVerhalten; } public void bellen(){ //Delegation des Verhaltens an Verhaltensobjekt bellVerhalten.bellen(); } public void laufen(){ //Delegation des Verhaltens an Verhaltensobjekt laufVerhalten.laufen(); } } <file_sep>package danielrajic.laufverhalten; public class NormalLaufen implements ILaufVerhalten{ public void laufen() { System.out.println("Normal laufen."); } } <file_sep>package danielrajic.programm; import danielrajic.bellverhalten.LeiseBellen; import danielrajic.laufverhalten.Humpeln; import danielrajic.objects.Husky; public class Client { public static void main(String[] args) { Husky husky = new Husky(); husky.bellen(); husky.laufen(); husky.setBellVerhalten(new LeiseBellen() ); husky.setLaufVerhalten(new Humpeln()); husky.bellen(); husky.laufen(); } } <file_sep>package danielrajic.laufverhalten; public class Humpeln implements ILaufVerhalten{ public void laufen() { System.out.println("Humpeln."); } }
3b3b0f8f8a60012d5ac80511f5cb455f41b36f4d
[ "Java" ]
6
Java
n00bst3r/DesignPatterns
bb7810d41ff2989b41778370229c5cc0614ba2d8
27ac75ec5623d5f5a111c84ba250779cef6307ce
refs/heads/master
<file_sep>package com.phong.test4.service; import com.phong.test4.model.City; public interface ICityService extends IGeneralService<City>{ } <file_sep>package com.phong.test4.service; import com.phong.test4.model.Country; public interface ICountryService extends IGeneralService<Country> { }
9cad8072b83154df343df175115f06d70adf6dbe
[ "Java" ]
2
Java
dangphong91/moduleexam4
2084832913dd1d558b2625528a8c2d0cfc18a605
1c905043313d1b10d8238f3bd0a86e23ed08e49d
refs/heads/master
<repo_name>ninjasphere/sphere-cloud-modelstore-service<file_sep>/README.md # sphere-cloud-modelstore-service Syncing: * ```modelstore.calculateSyncItems(user, modelName, nodeManifest)``` * ```modelstore.doSyncItems(user, modelName, pushedItems, requestedObjectIds)``` * ```modelstore.pushItemChange(user, modelName, pushedItem)``` Access: * ```modelstore.listItems(user, modelName)``` * ```modelstore.getItem(user, modelName, objectId)``` * ```modelstore.updateItem(user, modelName, objectId, data)``` * ```modelstore.createItem(user, modelName, data)``` * ```modelstore.deleteItem(user, modelName, objectId)``` # docker Deployment and local testing is done using docker. To build an image. ``` make build ``` To test locally. ``` make local ``` To deploy ``` make deploy ``` To point to a docker in a vm use. ``` export DOCKER_ARGS="-H crusty.local:5555" Licensing sphere-cloud-modelstore-service is licensed under the MIT License. See LICENSE for the full license text. <file_sep>/lib/rpc/modelstore/access.js 'use strict'; var debug = require('debug')('rpc:modelstore:access'); var Joi = require('joi'); var uuid = require('node-uuid'); var schemas = require('./schemas'); module.exports.listItems = function (user, modelName) { Joi.assert(user, schemas.UserRecord); Joi.assert(modelName, schemas.ModelName); var query = { key: [user.id, modelName], include_docs: true }; return this.couchdb.view('manifest/manifest', query).then(function (result) { var results = []; result.rows.map(function (row) { results.push(row.doc.data); }); return results; }); }; module.exports.getItem = function (user, modelName, objectId) { Joi.assert(user, schemas.UserRecord); Joi.assert(modelName, schemas.ModelName); Joi.assert(objectId, schemas.ObjectId); debug('getItem', modelName, 'id', objectId); var couchId = [user.id, modelName, objectId].join(':'); return this.couchdb.get(couchId).then(function (result) { return result.data; }); }; module.exports.updateItem = function (user, modelName, objectId, data) { Joi.assert(user, schemas.UserRecord); Joi.assert(modelName, schemas.ModelName); Joi.assert(objectId, schemas.ObjectId); debug('updateItem', modelName, 'id', objectId); var couchId = [user.id, modelName, objectId].join(':'); return this.couchdb.get(couchId).then(function (result) { debug('updateDoc', result._id, 'data', data); result.data = data; return this.couchdb.save(result); }.bind(this)).then(function (result) { return result.data; }); }; module.exports.createItem = function (user, modelName, data) { Joi.assert(user, schemas.UserRecord); Joi.assert(modelName, schemas.ModelName); var objectId = uuid.v4(); // Generate a v4 (random) id debug('createItem', modelName, 'id', objectId); // add the id to match the existing behaviour data.id = objectId; var newDocument = { _id: [user.id, modelName, objectId].join(':'), user: user, model: { type: modelName, id: objectId }, data: data }; return this.couchdb.save(newDocument).then(function (result) { return result.data; }); }; module.exports.deleteItem = function (user, modelName, objectId) { Joi.assert(user, schemas.UserRecord); Joi.assert(modelName, schemas.ModelName); Joi.assert(objectId, schemas.ObjectId); debug('deleteItem', modelName, 'id', objectId); var couchId = [user.id, modelName, objectId].join(':'); return this.couchdb.get(couchId).then(function (result) { debug('deleteDoc', result._id); result._deleted = true; return this.couchdb.save(result); }.bind(this)).then(function (result) { return result.data; }); };
027db8b07ceb12bcc2c130502c6d1aae2366f6e5
[ "Markdown", "JavaScript" ]
2
Markdown
ninjasphere/sphere-cloud-modelstore-service
907892944ee24bd5aaef653fa1f430008f91a92b
760a5a68a487c6c34c6ca93603211800eeb1c74a
refs/heads/master
<repo_name>haru4shi/game_<file_sep>/Stage1ura.cpp #include "Stage1ura.h" #include <cassert> #include"SphereCollider.h" using namespace DirectX; Stage1ura::Stage1ura(ISceneChanger* changer) :BaseScene(changer) { } Stage1ura::~Stage1ura() { //スプライト safe_delete(leftMesssage); safe_delete(rigthMessage); safe_delete(message); //3Dオブジェクト safe_delete(object3d); safe_delete(stage1Item1); safe_delete(stage1Item2); } void Stage1ura::Initialize(DirectXCommon* dxCommon, Input* input, Audio* audio) { this->dxCommon = dxCommon; this->input = input; this->audio = audio; WinApp* winApp = dxCommon->GetWinApp(); #pragma region スプライト読み込み生成 //読み込み Sprite::LoadTexture(1, L"Resources/memo1_n_n2.png"); Sprite::LoadTexture(2, L"Resources/memo.l_n.png"); Sprite::LoadTexture(3, L"Resources/memo.r_n.png"); //生成 message = Sprite::Create(1, { 0,0 }); rigthMessage = Sprite::Create(2, { 0,0 }); leftMesssage = Sprite::Create(3, { 0,0 }); #pragma endregion //コリジョンマネージャ初期化 collisionManager = CollisionManager::GetInstance(); #pragma region 3Dオブジェクト生成 object3d = Object3d::Create(winApp->window_width, winApp->window_height); //コライダー追加 object3d->SetCollider(new SphereCollider); //プレイヤーの座標 XMFLOAT3 playerPos = object3d->GetPosition(); object3d->SetPosition(playerPos); object3d->Update(); stage1Item1 = Stage1Item1::Create(winApp->window_width, winApp->window_height); stage1Item1->Update(); stage1Item2 = Stage1Item2::Create(winApp->window_width, winApp->window_height); stage1Item2->Update(); #pragma endregion } void Stage1ura::Update() { XMFLOAT3 playerPosition = object3d->GetPosition(); #pragma region キー入力で移動 if (input->IsPush(DIK_RIGHT)) { playerPosition.x += 0.5f; } if (input->IsPush(DIK_LEFT)) { playerPosition.x -= 0.5f; } //if (input->IsPush(DIK_UP)) { playerPosition.y += 0.5f; } //if (input->IsPush(DIK_DOWN)) { playerPosition.y -= 0.5f; } #pragma endregion #pragma region 切れ端に到達したら消す //ここ調整 //オブジェクトで判定取る if (playerPosition.x == 38) { Item1Get = true; } if (playerPosition.x == -40 && playerPosition.y == 10) { Item2Get = true; } if (Item1Get == true) { DrawItem1 = false; } if (Item2Get == true) { DrawItem2 = false; } #pragma endregion #pragma region 切れ端確認できるようにする if (Item1Get == true && input->Trigger(DIK_TAB)) { DrawRaightMessage = true; } if (Item2Get == true && input->Trigger(DIK_TAB)) { DrawLeftMessage = true; } if (Item1Get == true && Item2Get == true) { Item1Get = false; Item2Get = false; AllitemGet = true; } if (AllitemGet == true && input->Trigger(DIK_TAB)) { DrawMessage = true; } if (input->Trigger(DIK_ESCAPE)) { DrawRaightMessage = false; DrawLeftMessage = false; DrawMessage = false; } #pragma endregion #pragma region 座標セット object3d->SetPosition(playerPosition); #pragma endregion #pragma region 更新 object3d->Update(); stage1Item1->Update(); stage1Item2->Update(); #pragma endregion //全ての衝突判定をチェック collisionManager->CheckAllCollision(); } void Stage1ura::Draw() { // コマンドリストの取得 ID3D12GraphicsCommandList* cmdList = dxCommon->GetCommandList(); #pragma region 3Dオブジェクト描画 //描画前処理 Object3d::PreDraw(cmdList); //TestObject::PreDraw(cmdList); Stage1Item1::PreDraw(cmdList); Stage1Item2::PreDraw(cmdList); //描画 object3d->Draw(); //testObject->Draw(); if (DrawItem1) stage1Item1->Draw(); if (DrawItem2) stage1Item2->Draw(); //描画後処理 Object3d::PostDraw(); //TestObject::PostDraw(); Stage1Item1::PostDraw(); Stage1Item2::PostDraw(); #pragma endregion #pragma region 前景スプライト描画 //描画前処理 Sprite::PreDraw(cmdList); //描画 if (DrawRaightMessage) rigthMessage->Draw(); if (DrawLeftMessage) leftMesssage->Draw(); if (DrawMessage) message->Draw(); //描画後処理 Sprite::PostDraw(); #pragma endregion } <file_sep>/DirectXCommon.h #pragma once #define backBufferCount 2 #include <Windows.h> #include <d3d12.h> #include <dxgi1_6.h> #include <wrl.h> #include <d3dx12.h> #include <cstdlib> #include "WinApp.h" class DirectXCommon { private: //Microsoft::WRL::を省略 template <class T> using ComPtr = Microsoft::WRL::ComPtr<T>; public: void Initialize(WinApp* win);//初期化 void PreDraw();//描画前 void PostDraw();//描画後 void ClearRenderTarget();//レンダーターゲットクリア void ClearDepthBuffer();//深度バッファのクリア //デバイス取得 ID3D12Device* GetDevice() { return device.Get(); } //描画コマンド取得 ID3D12GraphicsCommandList* GetCommandList() { return cmdList.Get(); } WinApp* GetWinApp(){ return winApp; } private: void InitializeDXGIDevice();//デバイス初期化 void CreateSwapChain();//スワップチェーン生成 void InitializeCommand();//コマンド関連初期化 void CreateDepthBuffer();//深度バッファ生成 void CreateFence();//フェンス生成 void CreateFinalRenderTargets();//初期化用レンダーターゲット生成 private: WinApp* winApp; ComPtr<ID3D12Device> device; ComPtr<ID3D12GraphicsCommandList> cmdList; ComPtr<IDXGIFactory6> dxgiFactory; ComPtr<ID3D12CommandQueue> cmdQueue; ComPtr<IDXGISwapChain4> swapchain; ComPtr<ID3D12CommandAllocator> cmdAllocator; ComPtr<ID3D12DescriptorHeap> rtvHeaps; ComPtr<ID3D12DescriptorHeap> dsvHeap; std::vector<ComPtr<ID3D12Resource>> backBuffers{ backBufferCount }; ComPtr<ID3D12Resource> depthBuffer; ComPtr<ID3D12Fence> fence; UINT64 fenceVal = 0; }; <file_sep>/BaseCollider.cpp #include "BaseCollider.h" <file_sep>/Collision.cpp #include "Collision.h" using namespace DirectX; bool Collision::CheckSphere2Sphere(const Sphere& sphereA, const Sphere& sphereB, DirectX::XMVECTOR* inter) { // 中心点の距離の2乗 <= 半径の和の2乗 なら交差 float dist = XMVector3LengthSq(sphereA.center - sphereB.center).m128_f32[0]; float radius2 = sphereA.radius + sphereB.radius; radius2 *= radius2; if (dist <= radius2) { if (inter) { // Aの半径が0の時座標はBの中心 Bの半径が0の時座標はAの中心 となるよう補完 float t = sphereB.radius / (sphereA.radius + sphereB.radius); *inter = XMVectorLerp(sphereA.center, sphereB.center, t); } return true; } return false; } <file_sep>/CollisionInfo.h #pragma once #include<DirectXMath.h> class Object3d; class BaseCollider; struct CollisionInfo { public: CollisionInfo(Object3d* object, BaseCollider* collider, const DirectX::XMVECTOR& inter) { this->object = object; this->collider = collider; this->inter = inter; } Object3d* object = nullptr; BaseCollider* collider = nullptr; DirectX::XMVECTOR inter; };<file_sep>/ISceneChanger.cpp #include "ISceneChanger.h" ISceneChanger::~ISceneChanger() { }<file_sep>/SceneManager.cpp #include "SceneManager.h" #include "Title.h" #include"GameScene.h" #include "GameClear.h" #include "GameOver.h" #include"Stage1ura.h" SceneManager::SceneManager() : mNextScene(eScene_None) //次のシーン管理変数 { mScene = (BaseScene*) new Title(this); } //初期化 void SceneManager::Initialize(DirectXCommon* dxCommon, Input* input,Audio* audio) { this->dxCommon = dxCommon; this->input = input; this->audio = audio; assert(audio); mScene->Initialize(dxCommon, input, audio); } //終了処理 void SceneManager::Finalize() { mScene->Finalize(); } //更新 void SceneManager::Update() { if (mNextScene != eScene_None) {//次のシーンがセットされていたら mScene->Finalize();//現在のシーンの終了処理を実行 delete mScene; switch (mNextScene) { //シーンによって処理を分岐 case eScene_Title: //次の画面がメニューなら mScene = (BaseScene*) new Title(this); //メニュー画面のインスタンスを生成する break;//以下略 case eScene_Game: mScene = (BaseScene*) new GameScene(this); break; case eScene_Stage1ura: mScene = (BaseScene*) new Stage1ura(this); break; case eScene_GameClear: mScene = (BaseScene*) new GameClear(this); break; case eScene_GameOver: mScene = (BaseScene*) new GameOver(this); break; } mNextScene = eScene_None; //次のシーン情報をクリア mScene->Initialize(dxCommon, input, audio); //シーンを初期化 } mScene->Update(); //シーンの更新 } //描画 void SceneManager::Draw() { mScene->Draw(); } // 引数 nextScene にシーンを変更する void SceneManager::ChangeScene(eScene NextScene) { mNextScene = NextScene; //次のシーンをセットする } <file_sep>/Title.cpp #include "Title.h" Title::Title(ISceneChanger * changer) : BaseScene(changer) { } void Title::Initialize(DirectXCommon * dxCommon, Input * input, Audio* audio) { this->dxCommon = dxCommon; this->input = input; this->audio = audio; assert(audio); audio->Initialize(); Sprite::LoadTexture(1, L"Resources/背景1.png"); titlesprite1 = Sprite::Create(1, { 0,0 }); } void Title::Update() { if (input->Trigger(DIK_SPACE)) { mSceneChanger->ChangeScene(eScene_Game);//シーンをゲーム画面に変更 } if (input->Trigger(DIK_A)) { audio->PlayWave("Resources/Alarm01.wav");//更新 } } void Title::Draw() { // コマンドリストの取得 ID3D12GraphicsCommandList* cmdList = dxCommon->GetCommandList(); Sprite::PreDraw(cmdList); titlesprite1->Draw(); Sprite::PostDraw(); // 深度バッファクリア dxCommon->ClearDepthBuffer(); }<file_sep>/Audio.h #pragma once #include <Windows.h> #include <xaudio2.h> #include <wrl.h> //オーディオコールバック class XAudio2VoiceCallback : public IXAudio2VoiceCallback { public: // ボイス処理パスの開始時 //STDMETHOD_(void, OnVoiceProcessingPassStart) (THIS_ UINT32 BytesRequired) {}; void OnVoiceProcessingPassStart(UINT32 BytesRequired) {}; // ボイス処理パスの終了時 STDMETHOD_(void, OnVoiceProcessingPassEnd) (THIS) {}; // バッファストリームの再生が終了した時 STDMETHOD_(void, OnStreamEnd) (THIS) {}; // バッファの使用開始時 STDMETHOD_(void, OnBufferStart) (THIS_ void* pBufferContext) {}; // バッファの末尾に達した時 STDMETHOD_(void, OnBufferEnd) (THIS_ void* pBufferContext) { // バッファを解放する delete[] pBufferContext; }; // 再生がループ位置に達した時 STDMETHOD_(void, OnLoopEnd) (THIS_ void* pBufferContext) {}; // ボイスの実行エラー時 STDMETHOD_(void, OnVoiceError) (THIS_ void* pBufferContext, HRESULT Error) {}; }; class Audio { private: // エイリアス // Microsoft::WRL::を省略 template <class T> using ComPtr = Microsoft::WRL::ComPtr<T>; public: // サブクラス // チャンクヘッダ struct Chunk { char id[4]; // チャンク毎のID int size; // チャンクサイズ }; // RIFFヘッダチャンク struct RiffHeader { Chunk chunk; // "RIFF" char type[4]; // "WAVE" }; // FMTチャンク struct FormatChunk { Chunk chunk; // "fmt " WAVEFORMAT fmt; // 波形フォーマット }; public: // メンバ関数 bool Initialize(); // サウンドファイルの読み込みと再生 void PlayWave(const char* filename); private: // メンバ変数 ComPtr<IXAudio2> xAudio2; IXAudio2MasteringVoice* masterVoice; XAudio2VoiceCallback voiceCallback; }; <file_sep>/Timer.h #pragma once class Timer { public: Timer(float nowTime); float GetTime(); private: float nowTime = 0; }; <file_sep>/GameScene.h #pragma once #include "ISceneChanger.h" #include<DirectXMath.h> #include "BaseScene.h" #include"CollisionManager.h" //class Collisionmanager; class GameScene: public BaseScene { private: // エイリアス // Microsoft::WRL::を省略 template <class T> using ComPtr = Microsoft::WRL::ComPtr<T>; // DirectX::を省略 using XMFLOAT2 = DirectX::XMFLOAT2; using XMFLOAT3 = DirectX::XMFLOAT3; using XMFLOAT4 = DirectX::XMFLOAT4; using XMMATRIX = DirectX::XMMATRIX; private: // 静的メンバ変数 static const int debugTextTexNumber = 0; public: // メンバ関数 GameScene(ISceneChanger* changer); ~GameScene(); void Initialize(DirectXCommon* dxCommon, Input* input, Audio* audio); void Update(); void Draw(); private: // メンバ変数 DirectXCommon* dxCommon = nullptr; Input* input = nullptr; float acceleration = 0.0001; float speed = 0; //衝突マネージャ CollisionManager* collisionManager = nullptr; Object3d* object3d = nullptr; Stage1Item1* stage1Item1 = nullptr; Stage1Item2* stage1Item2 = nullptr; Stage1uraBlockObject* stage1uraObj = nullptr; //メッセージ Sprite* rigthMessage = nullptr; Sprite* leftMesssage = nullptr; Sprite* message = nullptr; //bool bool DrawMessage = false; bool DrawRaightMessage = false; bool DrawLeftMessage = false; bool Item1Get = false; bool Item2Get = false; bool AllitemGet = false; bool DrawItem1 = true; bool DrawItem2 = true; //足場出現フラグ bool scaffold = false; //背景チェンジフラグ bool behind = false; //裏表チェンジ bool change = false; //ベクトル float velocity = 1; }; <file_sep>/ISceneChanger.h #pragma once typedef enum { eScene_Title, //メニュー画面 eScene_Game, //ゲーム画面(1ステージ目) eScene_Stage1ura, //1ステージ目裏 eScene_Stage3, //3ステージ目 eScene_Stage4, //4ステージ目 eScene_Stage5, //5ステージ目 eScene_Stage6, //6ステージ目 eScene_Stage7, //7ステージ目 eScene_Stage8, //8ステージ目 eScene_GameOver,//ゲームオーバー画面 eScene_GameClear,//クリア画面 eScene_None, //無し } eScene; class ISceneChanger { public: virtual ~ISceneChanger() = 0; virtual void ChangeScene(eScene NextScene) = 0;//指定シーンに変更する }; <file_sep>/BaseScene.h #pragma once #include"WinApp.h" #include "Task.h" #include "ISceneChanger.h" #include "SafeDelete.h" #include "DirectXCommon.h" #include <DirectXMath.h> #include "Input.h" #include"Audio.h" #include "Sprite.h" #include "Object3d.h" #include"TestObject.h" #include"Stage1Item1.h" #include"Stage1Item2.h" #include"Stage1uraBlockObject.h" class BaseScene : public Task { protected: // エイリアス // Microsoft::WRL::を省略 template <class T> using ComPtr = Microsoft::WRL::ComPtr<T>; // DirectX::を省略 using XMFLOAT2 = DirectX::XMFLOAT2; using XMFLOAT3 = DirectX::XMFLOAT3; using XMFLOAT4 = DirectX::XMFLOAT4; using XMMATRIX = DirectX::XMMATRIX; protected: ISceneChanger* mSceneChanger; //クラス所有元にシーン切り替えを伝えるインターフェイス DirectXCommon* dxCommon = nullptr; Input* input = nullptr; Sprite* sprite1 = nullptr; Sprite* sprite2 = nullptr; Audio* audio = nullptr; protected: // 静的メンバ変数 static const int debugTextTexNumber = 0; public: BaseScene(ISceneChanger* changer); virtual ~BaseScene() {} virtual void Initialize(DirectXCommon* dxCommon, Input* input,Audio* audio) override; //初期化処理をオーバーライド。 virtual void Finalize() override; //終了処理をオーバーライド。 virtual void Update() override; //更新処理をオーバーライド。 virtual void Draw() override; //描画処理をオーバーライド。 }; <file_sep>/TestObject.h #pragma once #include"Object3d.h" class TestObject:public Object3d { public: static TestObject* Create(int window_width, int window_height); void Initialize(int window_width, int window_height) override; void Update() override; void OnCollision(const CollisionInfo& info) override; }; <file_sep>/CollisionPrimitive.h #pragma once /// <summary> /// 当たり判定プリミティブ /// </summary> #include <DirectXMath.h> /// <summary> /// 球 /// </summary> struct Sphere { // 中心座標 DirectX::XMVECTOR center = {}; // 半径 float radius = 1.0f; }; /// <summary> /// 平面 /// </summary> struct Plane { // 法線ベクトル DirectX::XMVECTOR normal = { 0,1,0 }; // 原点(0,0,0)からの距離 float distance = 0.0f; }; /// <summary> /// 法線付き三角形(時計回りが表面) /// </summary> class Triangle { public: // 頂点座標3つ DirectX::XMVECTOR p0; DirectX::XMVECTOR p1; DirectX::XMVECTOR p2; // 法線ベクトル DirectX::XMVECTOR normal; /// <summary> /// 法線の計算 /// </summary> void ComputeNormal(); }; /// <summary> /// レイ(半直線) /// </summary> struct Ray { // 始点座標 DirectX::XMVECTOR start = { 0,0,0,1 }; // 方向 DirectX::XMVECTOR dir = { 1,0,0,0 }; };<file_sep>/Task.h #pragma once #include"DirectXCommon.h" #include"Input.h" #include"Audio.h" class Task { public: virtual ~Task() {} virtual void Initialize(DirectXCommon* dxCommon, Input* input,Audio* audio) {} //初期化処理 virtual void Finalize() {} //終了処理 virtual void Update() = 0; //更新処理は必ず継承先で実装する virtual void Draw() = 0; //描画処理は必ず継承先で実装する }; <file_sep>/Stage1Item1.h #pragma once #include <Windows.h> #include <wrl.h> #include <d3d12.h> #include <DirectXMath.h> #include <d3dx12.h> #include"CollisionInfo.h" class BaseCollider; class Stage1Item1 { protected: // エイリアス // Microsoft::WRL::を省略 template <class T> using ComPtr = Microsoft::WRL::ComPtr<T>; // DirectX::を省略 using XMFLOAT2 = DirectX::XMFLOAT2; using XMFLOAT3 = DirectX::XMFLOAT3; using XMFLOAT4 = DirectX::XMFLOAT4; using XMMATRIX = DirectX::XMMATRIX; public: static Stage1Item1* Create(int window_width, int window_height);//インスタンス生成とinitialize呼び出し static void StaticInitialize(ID3D12Device* device); void InitializeGraphicsPipeline(); void InitializeDescriptorHeap(); void InitializeCamera(int window_width, int window_height); void CreateModel(); static void PreDraw(ID3D12GraphicsCommandList* cmdList); static void PostDraw(); void LoadMaterial(const std::string& directoryPath, const std::string& filename); const XMFLOAT3& GetPosition() { return position; } void SetPosition(XMFLOAT3 position) { this->position = position; } bool LoadTexture(const std::string& directoryPath, const std::string& filename); //コンストラクタ Stage1Item1() = default; //仮想デストラクタ virtual ~Stage1Item1(); //初期化 virtual void Initialize(int window_width, int window_height); virtual void Update(); virtual void Draw(); //ワールド行列取得 const XMMATRIX& GetMatWorld() { return matWorld; } //コライダーのセット void SetCollider(BaseCollider * collider); //衝突時のコールバック関数 virtual void OnCollision(const CollisionInfo & info) {} public: //構造体 struct VertexPosNormalUv { XMFLOAT3 pos; // xyz座標 XMFLOAT3 normal; // 法線ベクトル XMFLOAT2 uv; // uv座標 }; // 定数バッファ用データ構造体BO struct ConstBufferDataBO { XMMATRIX mat; // 3D変換行列 }; //定数バッファ用データ構造体1 struct ConstBufferDataB1 { XMFLOAT3 ambient;//アンビエント係数 float pad1; //パディング XMFLOAT3 diffuse;//ディフーズ係数 float pad2; //パディング XMFLOAT3 speculer;//スペキュラー係数 float alpha; //アルファ }; struct Material { std::string name;//マテリアル名 XMFLOAT3 ambient;//アンビエント影響度 XMFLOAT3 diffuse;//ディフーズ影響度 XMFLOAT3 specular;//スペキュラー影響度 float alpha;//アルファ std::string textuerFilename;//テクスチャファイル名 //コンストラクタ Material() { ambient = { 0.3f,0.3f,0.3f }; diffuse = { 0.0f,0.0f,0.0f }; specular = { 0.0f,0.0f,0.0f }; alpha = 1.0f; } }; private: std::vector<VertexPosNormalUv> vertices; std::vector<unsigned short> indices; Material material; ComPtr<ID3D12Resource> vertBuff; ComPtr<ID3D12Resource> indexBuff; static ID3D12Device* device; XMMATRIX matView;//ビュー変換行列 static ComPtr<ID3D12PipelineState> pipelinestate; static ComPtr<ID3D12RootSignature> rootsignature; XMFLOAT3 eye = { 0, 0, -50.0f }; XMFLOAT3 target = { 0, 0, 0 }; XMFLOAT3 up = { 0, 1, 0 }; D3D12_VERTEX_BUFFER_VIEW vbView{}; D3D12_INDEX_BUFFER_VIEW ibView{}; XMMATRIX matProjection; static ID3D12GraphicsCommandList* cmdList; CD3DX12_CPU_DESCRIPTOR_HANDLE cpuDescHandleSRV; CD3DX12_GPU_DESCRIPTOR_HANDLE gpuDescHandleSRV; UINT descriptorHandleIncrementSize = 0; ComPtr<ID3D12DescriptorHeap> descHeap; ComPtr<ID3D12Resource> texbuff; protected: ComPtr<ID3D12Resource> constBuffBO;// 定数バッファ ComPtr<ID3D12Resource> constBuffB1;// 定数バッファ XMFLOAT3 rotation = { 0,0,0 }; XMFLOAT3 position = { 40,-20,0 }; XMFLOAT4 color = { 1,1,1,1 }; XMFLOAT3 scale = { 1,1,1 }; XMMATRIX matWorld; //親オブジェクト Stage1Item1* parent = nullptr; Object3d* parent2 = nullptr; //クラス名(デバッグ用) const char* name = nullptr; //コライダー BaseCollider* collider = nullptr; }; <file_sep>/SceneManager.h #pragma once #include "ISceneChanger.h" #include"BaseScene.h" #include"Task.h" class SceneManager : public ISceneChanger,Task { private: BaseScene* mScene; //シーン管理変数 eScene mNextScene; //次のシーン管理変数 DirectXCommon* dxCommon = nullptr; Input* input = nullptr; Audio* audio = nullptr; public: SceneManager(); void Initialize(DirectXCommon* dxCommon, Input* input, Audio* audio) override;//初期化 void Finalize() override;//終了処理 void Update() override;//更新 void Draw() override;//描画 // 引数 nextScene にシーンを変更する void ChangeScene(eScene NextScene) override; }; <file_sep>/SphereCollider.cpp #include "SphereCollider.h" using namespace DirectX; void SphereCollider::Update() { //ワールド行列から座標を抽出 const XMMATRIX& matWorld = object3d->GetMatWorld(); //球のメンバ変数を更新 Sphere::center = matWorld.r[3] + offset; Sphere::radius = radius; } <file_sep>/DirectXCommon.cpp #include "DirectXCommon.h" #include <vector> #include <cassert> #include "SafeDelete.h" #pragma comment(lib, "d3d12.lib") #pragma comment(lib, "dxgi.lib") #pragma comment(lib, "dxguid.lib") using namespace Microsoft::WRL; void DirectXCommon::Initialize(WinApp * win) { winApp = win; // DXGIデバイス初期化 InitializeDXGIDevice(); // コマンド関連初期化 InitializeCommand(); // スワップチェーンの生成 CreateSwapChain(); // レンダーターゲット生成 CreateFinalRenderTargets(); // 深度バッファ生成 CreateDepthBuffer(); // フェンス生成 CreateFence(); } void DirectXCommon::PreDraw() { // バックバッファの番号を取得(2 つなので 0 番か 1 番) UINT bbIndex = swapchain->GetCurrentBackBufferIndex(); //リソースバリアを変更 //表示状態から描画状態に変更 cmdList->ResourceBarrier(1, &CD3DX12_RESOURCE_BARRIER::Transition(backBuffers[bbIndex].Get(), D3D12_RESOURCE_STATE_PRESENT, D3D12_RESOURCE_STATE_RENDER_TARGET)); // レンダーターゲットビュー用ディスクリプタヒープのハンドルを取得 CD3DX12_CPU_DESCRIPTOR_HANDLE rtvH = CD3DX12_CPU_DESCRIPTOR_HANDLE(rtvHeaps->GetCPUDescriptorHandleForHeapStart(), bbIndex, device->GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_RTV)); // 深度ステンシルビュー用デスクリプタヒープのハンドルを取得 CD3DX12_CPU_DESCRIPTOR_HANDLE dsvH = CD3DX12_CPU_DESCRIPTOR_HANDLE(dsvHeap->GetCPUDescriptorHandleForHeapStart()); // レンダーターゲットをセット cmdList->OMSetRenderTargets(1, &rtvH, false, &dsvH); // 全画面クリア Red Green Blue Alpha float clearColor[] = { 0.1f,0.25f, 0.5f,0.0f }; // 青っぽい色 //レンダーターゲットのクリア cmdList->ClearRenderTargetView(rtvH, clearColor, 0, nullptr); //深度バッファのクリア cmdList->ClearDepthStencilView(dsvH, D3D12_CLEAR_FLAG_DEPTH, 1.0f, 0, 0, nullptr); //ビューボットの設定コマンド cmdList->RSSetViewports(1, &CD3DX12_VIEWPORT(0.0f, 0.0f, winApp->window_width, winApp->window_height)); //シザー短径の設定コマンド cmdList->RSSetScissorRects(1, &CD3DX12_RECT(0, 0, winApp->window_width, winApp->window_height)); } void DirectXCommon::PostDraw() { UINT bbIndex = swapchain->GetCurrentBackBufferIndex(); cmdList->ResourceBarrier(1, &CD3DX12_RESOURCE_BARRIER::Transition(backBuffers[bbIndex].Get(), D3D12_RESOURCE_STATE_RENDER_TARGET, D3D12_RESOURCE_STATE_PRESENT)); // 命令のクローズ cmdList->Close(); // コマンドリストの実行 ID3D12CommandList* cmdLists[] = { cmdList.Get() }; // コマンドリストの配列 cmdQueue->ExecuteCommandLists(1, cmdLists); // コマンドリストの実行完了を待つ cmdQueue->Signal(fence.Get(), ++fenceVal); if (fence->GetCompletedValue() != fenceVal) { HANDLE event = CreateEvent(nullptr, false, false, nullptr); fence->SetEventOnCompletion(fenceVal, event); WaitForSingleObject(event, INFINITE); CloseHandle(event); } cmdAllocator->Reset(); // キューをクリア cmdList->Reset(cmdAllocator.Get(), nullptr); // 再びコマンドリストを貯める準備 // バッファをフリップ(裏表の入替え) swapchain->Present(1, 0); } void DirectXCommon::ClearRenderTarget() { UINT bbIndex = swapchain->GetCurrentBackBufferIndex(); // レンダーターゲットビュー用ディスクリプタヒープのハンドルを取得 CD3DX12_CPU_DESCRIPTOR_HANDLE rtvH = CD3DX12_CPU_DESCRIPTOR_HANDLE(rtvHeaps->GetCPUDescriptorHandleForHeapStart(), bbIndex, device->GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_RTV)); // 全画面クリア Red Green Blue Alpha float clearColor[] = { 0.1f,0.25f, 0.5f,0.0f }; // 青っぽい色 cmdList->ClearRenderTargetView(rtvH, clearColor, 0, nullptr); } void DirectXCommon::ClearDepthBuffer() { // 深度ステンシルビュー用デスクリプタヒープのハンドルを取得 CD3DX12_CPU_DESCRIPTOR_HANDLE dsvH = CD3DX12_CPU_DESCRIPTOR_HANDLE(dsvHeap->GetCPUDescriptorHandleForHeapStart()); // 深度バッファのクリア cmdList->ClearDepthStencilView(dsvH, D3D12_CLEAR_FLAG_DEPTH, 1.0f, 0, 0, nullptr); } void DirectXCommon::InitializeDXGIDevice() { HRESULT result; #ifdef _DEBUG //デバッグレイヤーをオンに ComPtr<ID3D12Debug> debugController; if (SUCCEEDED(D3D12GetDebugInterface(IID_PPV_ARGS(&debugController)))) { debugController->EnableDebugLayer(); } #endif // DEBUG //対応レベルの配列 D3D_FEATURE_LEVEL levels[] = { D3D_FEATURE_LEVEL_12_1, D3D_FEATURE_LEVEL_12_0, D3D_FEATURE_LEVEL_11_1, D3D_FEATURE_LEVEL_11_0, }; //DXGI ファクトリーの生成 result = CreateDXGIFactory1(IID_PPV_ARGS(&dxgiFactory)); std::vector<ComPtr<IDXGIAdapter1>> adapters; //ここに特定の名前を持つアダプターオブジェクトが入る ComPtr<IDXGIAdapter1> tmpAdapter; for (int i = 0; dxgiFactory->EnumAdapters1(i, &tmpAdapter) != DXGI_ERROR_NOT_FOUND; i++) { adapters.push_back(tmpAdapter);//動的配列に追加する } for (int i = 0; i < adapters.size(); i++) { DXGI_ADAPTER_DESC1 adesc{}; adapters[i]->GetDesc1(&adesc);//アダプターの情報を取得 // ソフトウェアデバイスを回避 if (adesc.Flags & DXGI_ADAPTER_FLAG_SOFTWARE) { continue; } std::wstring strDesc = adesc.Description;//アダプター名 //Microsoft Basic Render Driverを回避 if (strDesc.find(L"Intel") == std::wstring::npos) { tmpAdapter = adapters[i];// break; } } D3D_FEATURE_LEVEL featureLevel; result = S_FALSE; for (int i = 0; i < _countof(levels); i++) { //採用したアダプターでデバイスを生成 result = D3D12CreateDevice(tmpAdapter.Get(), levels[i], IID_PPV_ARGS(&device)); if (result == S_OK) { //デバイスを生成できた時点でループを抜ける featureLevel = levels[i]; break; } } } void DirectXCommon::CreateSwapChain() { HRESULT result; //各種設定をしてスワップチェーンを生成 DXGI_SWAP_CHAIN_DESC1 swapchainDesc{}; swapchainDesc.Width = 1280; swapchainDesc.Height = 720; swapchainDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM; // 色情報の書式 swapchainDesc.SampleDesc.Count = 1; // マルチサンプルしない swapchainDesc.BufferUsage = DXGI_USAGE_BACK_BUFFER; // バックバッファ用 swapchainDesc.BufferCount = 2; // バッファ数を2つに設定 swapchainDesc.SwapEffect = DXGI_SWAP_EFFECT_FLIP_DISCARD; // フリップ後は破棄 swapchainDesc.Flags = DXGI_SWAP_CHAIN_FLAG_ALLOW_MODE_SWITCH; //IDXGISwapChain1のComPtrを用意 ComPtr<IDXGISwapChain1> swapchain1; HWND hwnd = winApp->GetHwnd(); //スワップチェーンの生成 result = dxgiFactory->CreateSwapChainForHwnd( cmdQueue.Get(), hwnd, &swapchainDesc, nullptr, nullptr, &swapchain1); //生成したIDXGISwapChain1のオブジェクトをIDXGISwapChain4に変換する swapchain1.As(&swapchain); } void DirectXCommon::InitializeCommand() { HRESULT result; //コマンドアロケータを生成 result = device->CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT, IID_PPV_ARGS(&cmdAllocator)); //コマンドリストの生成 result = device->CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, cmdAllocator.Get(), nullptr, IID_PPV_ARGS(&cmdList)); //標準設定でコマンドキューを生成 D3D12_COMMAND_QUEUE_DESC cmdQueueDesc{}; result=device->CreateCommandQueue(&cmdQueueDesc, IID_PPV_ARGS(&cmdQueue)); } void DirectXCommon::CreateFinalRenderTargets() { HRESULT result; DXGI_SWAP_CHAIN_DESC swcDesc = {}; result = swapchain->GetDesc(&swcDesc); //ディスクリプタヒープを生成 D3D12_DESCRIPTOR_HEAP_DESC heapDesc{}; heapDesc.Type = D3D12_DESCRIPTOR_HEAP_TYPE_RTV; // レンダーターゲットビュー heapDesc.NumDescriptors = swcDesc.BufferCount; // 裏表の2つ result=device->CreateDescriptorHeap(&heapDesc, IID_PPV_ARGS(&rtvHeaps)); for (int i = 0; i < backBuffers.size(); i++) { // スワップチェーンからバッファを取得 result = swapchain->GetBuffer(i, IID_PPV_ARGS(&backBuffers[i])); // ディスクリプタヒープのハンドルを取得 CD3DX12_CPU_DESCRIPTOR_HANDLE handle = CD3DX12_CPU_DESCRIPTOR_HANDLE(rtvHeaps->GetCPUDescriptorHandleForHeapStart(), i, device->GetDescriptorHandleIncrementSize(heapDesc.Type)); // レンダーターゲットビューの生成 device->CreateRenderTargetView( backBuffers[i].Get(), nullptr, handle); } } void DirectXCommon::CreateDepthBuffer() { HRESULT result; //リソースの設定 CD3DX12_RESOURCE_DESC depthResDesc = CD3DX12_RESOURCE_DESC::Tex2D( DXGI_FORMAT_D32_FLOAT, winApp->window_width, winApp->window_height, 1, 0, 1, 0, D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL ); //リソース生成 result = device->CreateCommittedResource( &CD3DX12_HEAP_PROPERTIES(D3D12_HEAP_TYPE_DEFAULT),//アップロード不可 D3D12_HEAP_FLAG_NONE, &depthResDesc, D3D12_RESOURCE_STATE_DEPTH_WRITE,//深度値書き込みに使用 &CD3DX12_CLEAR_VALUE(DXGI_FORMAT_D32_FLOAT, 1.0f, 0), IID_PPV_ARGS(&depthBuffer)); //深度ビュー用デスクリプタヒープ作成 D3D12_DESCRIPTOR_HEAP_DESC dsvHeapDesc{}; dsvHeapDesc.NumDescriptors = 1;//深度ビューは1つ dsvHeapDesc.Type = D3D12_DESCRIPTOR_HEAP_TYPE_DSV;//デプスステンシルビュー result = device->CreateDescriptorHeap(&dsvHeapDesc, IID_PPV_ARGS(&dsvHeap)); //深度ビュー作成 D3D12_DEPTH_STENCIL_VIEW_DESC dsvDesc{}; dsvDesc.Format = DXGI_FORMAT_D32_FLOAT;//深度値フォーマット dsvDesc.ViewDimension = D3D12_DSV_DIMENSION_TEXTURE2D; device->CreateDepthStencilView( depthBuffer.Get(), &dsvDesc, dsvHeap->GetCPUDescriptorHandleForHeapStart()); } void DirectXCommon::CreateFence() { HRESULT result; result = device->CreateFence(fenceVal, D3D12_FENCE_FLAG_NONE, IID_PPV_ARGS(&fence)); } <file_sep>/CollisionManager.cpp #include "CollisionManager.h" #include"BaseCollider.h" #include"Collision.h" #include"CollisionPrimitive.h" CollisionManager* CollisionManager::GetInstance() { static CollisionManager instance; return &instance; } void CollisionManager::CheckAllCollision() { std::forward_list<BaseCollider*>::iterator itA; std::forward_list<BaseCollider*>::iterator itB; //全ての組み合わせを総当たりチェック itA = colliders.begin(); for (; itA != colliders.end(); itA++) { itB = itA; itB++; for (; itB != colliders.end(); itB++) { BaseCollider* colA = *itA; BaseCollider* colB = *itB; //ともに球 if (colA->GetShapeType() == COLLISIONSHAPE_SPHERE && colB->GetShapeType() == COLLISIONSHAPE_SPHERE) { Sphere* SphereA = dynamic_cast<Sphere*>(colA); Sphere* SphereB = dynamic_cast<Sphere*>(colB); DirectX::XMVECTOR inter; if (Collision::CheckSphere2Sphere(*SphereA, *SphereB, &inter)) { colA->OnCollision(CollisionInfo(colB->GetObject3d(), colB, inter)); colB->OnCollision(CollisionInfo(colA->GetObject3d(), colA, inter)); } } } } } <file_sep>/GameOver.h #pragma once #include "BaseScene.h" #include "ISceneChanger.h" #include"Sprite.h" class GameOver: public BaseScene { private: Sprite* gameoversprite; WinApp* win = nullptr; public: GameOver(ISceneChanger* changer); void Initialize(DirectXCommon* dxCommon, Input* input, Audio* audio) override; //初期化処理をオーバーライド。 void Update() override; //更新処理をオーバーライド。 void Draw() override; //描画処理をオーバーライド。 }; <file_sep>/CollisionTypes.cpp #include "CollisionTypes.h" <file_sep>/Timer.cpp #include "Timer.h" #pragma comment(lib,"winmm.lib") #include<windows.h> #include<wchar.h> Timer::Timer(float nowTime) :nowTime(nowTime) { } float Timer::GetTime() { DWORD Before, Affter; return nowTime; } <file_sep>/Stage1Item2.cpp #include "Stage1Item2.h" #include"SphereCollider.h" #include"Input.h" using namespace DirectX; Stage1Item2* Stage1Item2::Create(int window_width, int window_height) { //インスタンス生成 Stage1Item2* stage1Item2 = new Stage1Item2(); //初期化 stage1Item2->Initialize(window_width, window_height); //初期位置 XMFLOAT3 position = stage1Item2->GetPosition(); position.x = -40; position.y = 10; stage1Item2->SetPosition(position); return stage1Item2; } void Stage1Item2::Initialize(int window_width, int window_height) { Stage1Item1::Initialize(window_width, window_height); //コライダー追加 //float radius = 2; //SetCollider(new SphereCollider(XMVECTOR({ radius,radius,0,0 }), radius)); } void Stage1Item2::Update() { Input* input = Input::GetInstance(); Stage1Item1::Update(); } void Stage1Item2::OnCollision(const CollisionInfo& info) { } <file_sep>/Input.h #pragma once #include <Windows.h> #include <wrl.h> #define DIRECTINPUT_VERSION 0x0800 // DirectInputのバージョン指定 #include <dinput.h> class Input { private: template <class T> using ComPtr = Microsoft::WRL::ComPtr<T>; public: Input(); ~Input(); //初期化 void Initialize(HWND hwnd, HINSTANCE hInstance); //毎フレーム更新 void Update(); //キーが押されているかどうかをチェックする bool IsPush(int keyNumber); //キーのトリガーチェック bool Trigger(int keyNumber); static Input* GetInstance(); private: ComPtr<IDirectInput8> dinput; ComPtr<IDirectInputDevice8> devkeyboard; //キーボード入力情報 BYTE key[256] = {}; //前回のキー情報 BYTE keyPre[256] = {}; }; <file_sep>/Stage1ura.h #pragma once #include "ISceneChanger.h" #include<DirectXMath.h> #include "BaseScene.h" #include"CollisionManager.h" #include"GameScene.h" class Stage1ura: public BaseScene { private: // エイリアス // Microsoft::WRL::を省略 template <class T> using ComPtr = Microsoft::WRL::ComPtr<T>; // DirectX::を省略 using XMFLOAT2 = DirectX::XMFLOAT2; using XMFLOAT3 = DirectX::XMFLOAT3; using XMFLOAT4 = DirectX::XMFLOAT4; using XMMATRIX = DirectX::XMMATRIX; private: // 静的メンバ変数 static const int debugTextTexNumber = 0; public: // メンバ関数 Stage1ura(ISceneChanger* changer); ~Stage1ura(); void Initialize(DirectXCommon* dxCommon, Input* input, Audio* audio); void Update(); void Draw(); private: // メンバ変数 DirectXCommon* dxCommon = nullptr; Input* input = nullptr; Audio* audio = nullptr; //衝突マネージャ CollisionManager* collisionManager = nullptr; Object3d* object3d = nullptr; Stage1Item1* stage1Item1 = nullptr; Stage1Item2* stage1Item2 = nullptr; //メッセージ Sprite* rigthMessage = nullptr; Sprite* leftMesssage = nullptr; Sprite* message = nullptr; //bool bool DrawMessage = false; bool DrawRaightMessage = false; bool DrawLeftMessage = false; bool Item1Get = false; bool Item2Get = false; bool AllitemGet = false; bool DrawItem1 = true; bool DrawItem2 = true; }; <file_sep>/CollisionPrimitive.cpp #include "CollisionPrimitive.h" using namespace DirectX; void Triangle::ComputeNormal() { XMVECTOR p0_p1 = p1 - p0; XMVECTOR p0_p2 = p2 - p0; // 外積により、2辺に垂直なベクトルを算出する normal = XMVector3Cross(p0_p1, p0_p2); normal = XMVector3Normalize(normal); } <file_sep>/WinApp.h #pragma once #include<Windows.h> class WinApp { public: const int window_width = 1280; const int window_height = 720; static const wchar_t windowClassName[]; public: static LRESULT WindowProc(HWND hwnd, UINT msg, WPARAM wparam, LPARAM lparam); public: void CreateGameWindow();//ウィンドウ作成 void TerminateGameWindow();//ウィンドウ破棄 HWND GetHwnd() { return hwnd; } HINSTANCE GetInstance() { return wndClass.hInstance; } private: HWND hwnd = nullptr; // ウィンドウハンドル WNDCLASSEX wndClass{}; // ウィンドウクラス }; <file_sep>/main.cpp #include"WinApp.h" #include"DirectXCommon.h" #include"SceneManager.h" #include"BaseScene.h" // Windows アプリでのエントリーポイント(main 関数) int WINAPI WinMain(HINSTANCE, HINSTANCE, LPSTR, int) { WinApp* win = nullptr; DirectXCommon* dxCommon = nullptr; Input* input = nullptr; SceneManager* sceneManager = nullptr; Audio* audio = nullptr; //ゲームウィンドウ作成 win = new WinApp(); win->CreateGameWindow(); //DirectXの初期化処理 ここから dxCommon = new DirectXCommon(); dxCommon->Initialize(win); //初期化 input = new Input(); input->Initialize(win->GetHwnd(),win->GetInstance()); //audio初期化 audio = new Audio(); audio->Initialize(); // スプライト静的初期化 if (!Sprite::StaticInitialize(dxCommon->GetDevice(), win->window_width,win->window_height)) { assert(0); return 1; } #pragma region オブジェクト初期化 Object3d::StaticInitialize(dxCommon->GetDevice()); TestObject::StaticInitialize(dxCommon->GetDevice()); Stage1Item1::StaticInitialize(dxCommon->GetDevice()); Stage1Item2::StaticInitialize(dxCommon->GetDevice()); Stage1uraBlockObject::StaticInitialize(dxCommon->GetDevice()); #pragma endregion //ゲームシーンの初期化 sceneManager = new SceneManager(); sceneManager->Initialize(dxCommon, input,audio); while (1) { MSG msg{}; //メッセージがある? if (PeekMessage(&msg, nullptr, 0, 0, PM_REMOVE)) { TranslateMessage(&msg);//キー入力メッセージの処理 DispatchMessage(&msg);//プロシージャにメッセージを送る } //終了メッセージが来たらループを抜ける if (msg.message == WM_QUIT) { break; } //入力関係更新 input->Update(); //ゲームシーンの毎フレーム処理 sceneManager->Update(); //描画前の処理 dxCommon->PreDraw(); //ゲームシーン描画 sceneManager->Draw(); //描画後の処理 dxCommon->PostDraw(); //DirectXの毎フレーム処理 ここまで } safe_delete(dxCommon); safe_delete(sceneManager); safe_delete(input); safe_delete(audio); //ウィンドウクラスを登録解除 win->TerminateGameWindow(); safe_delete(win); return 0; } <file_sep>/WinApp.cpp #include "WinApp.h" const wchar_t WinApp::windowClassName[] = L"DirectXGame"; LRESULT WinApp::WindowProc(HWND hwnd, UINT msg, WPARAM wparam, LPARAM lparam) { //メッセージで分岐 switch (msg) { case WM_DESTROY://ウィンドウが破棄された PostQuitMessage(0);//OSに対して、アプリの終了を伝える return 0; } return DefWindowProc(hwnd, msg, wparam, lparam);//標準の処理を行う } void WinApp::CreateGameWindow() { wndClass.cbSize = sizeof(WNDCLASSEX); wndClass.lpfnWndProc = (WNDPROC)WindowProc;//ウィンドウプロシージャーを設定 wndClass.lpszClassName = L"DirectXGame";//ウィンドウクラス名 wndClass.hInstance = GetModuleHandle(nullptr);//ウィンドウハンドル wndClass.hCursor = LoadCursor(NULL, IDC_ARROW);//カーソル指定 RegisterClassEx(&wndClass); // ウィンドウクラスをOSに登録 // ウィンドウサイズ{ X座標 Y座標 横幅 縦幅 } RECT wrc = { 0, 0, window_width, window_height }; AdjustWindowRect(&wrc, WS_OVERLAPPEDWINDOW, false); // 自動でサイズ補正 // ウィンドウオブジェクトの生成 hwnd = CreateWindow(wndClass.lpszClassName, // クラス名 windowClassName, // タイトルバーの文字 WS_OVERLAPPEDWINDOW, // タイトルバーと境界線があるウィンドウ CW_USEDEFAULT, // 表示X座標(OSに任せる) CW_USEDEFAULT, // 表示Y座標(OSに任せる) wrc.right - wrc.left, // ウィンドウ横幅 wrc.bottom - wrc.top, // ウィンドウ縦幅 nullptr, // 親ウィンドウハンドル nullptr, // メニューハンドル wndClass.hInstance, // 呼び出しアプリケーションハンドル nullptr); // オプション // ウィンドウ表示 ShowWindow(hwnd, SW_SHOW); } void WinApp::TerminateGameWindow() { // ウィンドウクラスを登録解除 UnregisterClass(wndClass.lpszClassName, wndClass.hInstance); } <file_sep>/Collision.h #pragma once #include "CollisionPrimitive.h" class Collision { public: static bool CheckSphere2Sphere(const Sphere& sphereA, const Sphere& sphereB, DirectX::XMVECTOR* inter = nullptr); }; <file_sep>/Input.cpp #include "Input.h" #include<cassert> #pragma comment(lib, "dinput8.lib") //メンバ関数の定義 Input::Input() { } Input::~Input() { } void Input::Initialize(HWND hwnd, HINSTANCE hInstance) { HRESULT result; //DirectInputオブジェクト生成 result = DirectInput8Create(hInstance, DIRECTINPUT_VERSION, IID_IDirectInput8, (void**)&dinput, nullptr); //キーボードデバイスの生成 result = dinput->CreateDevice(GUID_SysKeyboard, &devkeyboard, NULL); //入力データのセット result = devkeyboard->SetDataFormat(&c_dfDIKeyboard); // 標準形式 //排他的レベルのセット result = devkeyboard->SetCooperativeLevel( hwnd, DISCL_FOREGROUND | DISCL_NONEXCLUSIVE | DISCL_NOWINKEY); } void Input::Update() { HRESULT result; //キーボード情報の取得開始 UpDateKey result = devkeyboard->Acquire(); //前回のキー入力処理をコピー for (int i = 0; i < 256; i++) { keyPre[i] = key[i]; } //全キーの入力状態を取得する result = devkeyboard->GetDeviceState(sizeof(key), key); } bool Input::IsPush(int keyNumber) { //キー配列の設定値を超えたら判定をしない if (keyNumber < 0) { OutputDebugString(TEXT("キー配列の設定値を超えたためトリガー判定を行えない")); return false; } if (keyNumber > 255) { OutputDebugString(TEXT("キー配列の設定値を超えたためトリガー判定を行えない")); return false; } //範囲内ならキー入力判定 if (key[keyNumber]) { return true; } return false; } bool Input::Trigger(int keyNumber) { //キー配列の設定値を超えたら判定をしない if (keyNumber < 0) { OutputDebugString(TEXT("キー配列の設定値を超えたためトリガー判定を行えない")); return false; } if (keyNumber > 255) { OutputDebugString(TEXT("キー配列の設定値を超えたためトリガー判定を行えない")); return false; } //前回押されていない(1フレーム前)かつ今回押されている if (!keyPre[keyNumber] && key[keyNumber]) { return true; } return false; } Input* Input::GetInstance() { static Input instance; return &instance; } <file_sep>/GameClear.cpp #include "GameClear.h" GameClear::GameClear(ISceneChanger * changer) : BaseScene(changer) { } void GameClear::Initialize(DirectXCommon * dxCommon, Input * input,Audio* audio) { this->dxCommon = dxCommon; this->input = input; this->audio = audio; gameclearsprite->LoadTexture(1, L"Resources/GameClear.png"); gameclearsprite->Create(1, {0,0}); } void GameClear::Update() { if (input->Trigger(DIK_SPACE)) { mSceneChanger->ChangeScene(eScene_Title);//シーンをゲーム画面に変更 } } void GameClear::Draw() { // コマンドリストの取得 ID3D12GraphicsCommandList* cmdList = dxCommon->GetCommandList(); gameclearsprite->PreDraw(cmdList); gameclearsprite->Draw(); gameclearsprite->PostDraw(); // 深度バッファクリア dxCommon->ClearDepthBuffer(); }<file_sep>/SphereCollider.h #pragma once #include"BaseCollider.h" #include"CollisionPrimitive.h" #include<DirectXMath.h> class SphereCollider:public BaseCollider,public Sphere { private: using XMVECTOR = DirectX::XMVECTOR; public: SphereCollider(XMVECTOR offset = { 0,0,0,0 }, float radius = 1.0f) : offset(offset),radius(radius) { //球をセット shapeType = COLLISIONSHAPE_SPHERE; } //更新 void Update() override; inline void SetRadius(float radius) { this->radius = radius; } private: //オブジェクトの中心からのオフセット XMVECTOR offset; //半径 float radius; }; <file_sep>/SafeDelete.h #pragma once template <class T> inline void safe_delete(T*& p) { delete p; p = nullptr; } <file_sep>/GameClear.h #pragma once #include "BaseScene.h" #include "ISceneChanger.h" #include"Sprite.h" class GameClear : public BaseScene { private: Sprite* gameclearsprite; WinApp* win = nullptr; public: GameClear(ISceneChanger* changer); void Initialize(DirectXCommon* dxCommon, Input* input,Audio* audio) override; //初期化処理をオーバーライド。 void Update() override; //更新処理をオーバーライド。 void Draw() override; //描画処理をオーバーライド。 }; <file_sep>/Sprite.cpp #include "Sprite.h" #include <cassert> #include <d3dx12.h> #include <d3dcompiler.h> #include <DirectXTex.h> #pragma comment(lib, "d3dcompiler.lib") using namespace DirectX; using namespace Microsoft::WRL; /// <summary> /// 静的メンバ変数の実体 /// </summary> ID3D12Device* Sprite::device = nullptr; UINT Sprite::descriptorHandleIncrementSize; ID3D12GraphicsCommandList* Sprite::cmdList = nullptr; ComPtr<ID3D12RootSignature> Sprite::rootSignature; ComPtr<ID3D12PipelineState> Sprite::pipelineState; XMMATRIX Sprite::matProjection; ComPtr<ID3D12DescriptorHeap> Sprite::descHeap; ComPtr<ID3D12Resource> Sprite::texBuff[srvCount]; bool Sprite::StaticInitialize(ID3D12Device* device, int window_width, int window_height) { // nullptrチェック assert(device); Sprite::device = device; // デスクリプタサイズを取得 descriptorHandleIncrementSize = device->GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV); HRESULT result = S_FALSE; ComPtr<ID3DBlob> vsBlob; // 頂点シェーダオブジェクト ComPtr<ID3DBlob> psBlob; // ピクセルシェーダオブジェクト ComPtr<ID3DBlob> errorBlob; // エラーオブジェクト // 頂点シェーダの読み込みとコンパイル result = D3DCompileFromFile( L"SpriteVertexShader.hlsl", // シェーダファイル名 nullptr, D3D_COMPILE_STANDARD_FILE_INCLUDE, // インクルード可能にする "main", "vs_5_0", // エントリーポイント名、シェーダーモデル指定 D3DCOMPILE_DEBUG | D3DCOMPILE_SKIP_OPTIMIZATION, // デバッグ用設定 0, &vsBlob, &errorBlob); if (FAILED(result)) { // errorBlobからエラー内容をstring型にコピー std::string errstr; errstr.resize(errorBlob->GetBufferSize()); std::copy_n((char*)errorBlob->GetBufferPointer(), errorBlob->GetBufferSize(), errstr.begin()); errstr += "\n"; // エラー内容を出力ウィンドウに表示 OutputDebugStringA(errstr.c_str()); return false; } // ピクセルシェーダの読み込みとコンパイル result = D3DCompileFromFile( L"SpritePixelSharder.hlsl", // シェーダファイル名 nullptr, D3D_COMPILE_STANDARD_FILE_INCLUDE, // インクルード可能にする "main", "ps_5_0", // エントリーポイント名、シェーダーモデル指定 D3DCOMPILE_DEBUG | D3DCOMPILE_SKIP_OPTIMIZATION, // デバッグ用設定 0, &psBlob, &errorBlob); if (FAILED(result)) { // errorBlobからエラー内容をstring型にコピー std::string errstr; errstr.resize(errorBlob->GetBufferSize()); std::copy_n((char*)errorBlob->GetBufferPointer(), errorBlob->GetBufferSize(), errstr.begin()); errstr += "\n"; // エラー内容を出力ウィンドウに表示 OutputDebugStringA(errstr.c_str()); return false; } // 頂点レイアウト D3D12_INPUT_ELEMENT_DESC inputLayout[] = { { // xy座標(1行で書いたほうが見やすい) "POSITION", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, D3D12_APPEND_ALIGNED_ELEMENT, D3D12_INPUT_CLASSIFICATION_PER_VERTEX_DATA, 0 }, { // uv座標(1行で書いたほうが見やすい) "TEXCOORD", 0, DXGI_FORMAT_R32G32_FLOAT, 0, D3D12_APPEND_ALIGNED_ELEMENT, D3D12_INPUT_CLASSIFICATION_PER_VERTEX_DATA, 0 }, }; // グラフィックスパイプラインの流れを設定 D3D12_GRAPHICS_PIPELINE_STATE_DESC gpipeline{}; gpipeline.VS = CD3DX12_SHADER_BYTECODE(vsBlob.Get()); gpipeline.PS = CD3DX12_SHADER_BYTECODE(psBlob.Get()); // サンプルマスク gpipeline.SampleMask = D3D12_DEFAULT_SAMPLE_MASK; // 標準設定 // ラスタライザステート gpipeline.RasterizerState = CD3DX12_RASTERIZER_DESC(D3D12_DEFAULT); gpipeline.RasterizerState.CullMode = D3D12_CULL_MODE_NONE; // デプスステンシルステート gpipeline.DepthStencilState = CD3DX12_DEPTH_STENCIL_DESC(D3D12_DEFAULT); gpipeline.DepthStencilState.DepthFunc = D3D12_COMPARISON_FUNC_ALWAYS; // 常に上書きルール // レンダーターゲットのブレンド設定 D3D12_RENDER_TARGET_BLEND_DESC blenddesc{}; blenddesc.RenderTargetWriteMask = D3D12_COLOR_WRITE_ENABLE_ALL; // RBGA全てのチャンネルを描画 blenddesc.BlendEnable = true; blenddesc.BlendOp = D3D12_BLEND_OP_ADD; blenddesc.SrcBlend = D3D12_BLEND_SRC_ALPHA; blenddesc.DestBlend = D3D12_BLEND_INV_SRC_ALPHA; blenddesc.BlendOpAlpha = D3D12_BLEND_OP_ADD; blenddesc.SrcBlendAlpha = D3D12_BLEND_ONE; blenddesc.DestBlendAlpha = D3D12_BLEND_ZERO; // ブレンドステートの設定 gpipeline.BlendState.RenderTarget[0] = blenddesc; // 深度バッファのフォーマット gpipeline.DSVFormat = DXGI_FORMAT_D32_FLOAT; // 頂点レイアウトの設定 gpipeline.InputLayout.pInputElementDescs = inputLayout; gpipeline.InputLayout.NumElements = _countof(inputLayout); // 図形の形状設定(三角形) gpipeline.PrimitiveTopologyType = D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE; gpipeline.NumRenderTargets = 1; // 描画対象は1つ gpipeline.RTVFormats[0] = DXGI_FORMAT_R8G8B8A8_UNORM; // 0〜255指定のRGBA gpipeline.SampleDesc.Count = 1; // 1ピクセルにつき1回サンプリング // デスクリプタレンジ CD3DX12_DESCRIPTOR_RANGE descRangeSRV; descRangeSRV.Init(D3D12_DESCRIPTOR_RANGE_TYPE_SRV, 1, 0); // t0 レジスタ // ルートパラメータ CD3DX12_ROOT_PARAMETER rootparams[2]; rootparams[0].InitAsConstantBufferView(0, 0, D3D12_SHADER_VISIBILITY_ALL); rootparams[1].InitAsDescriptorTable(1, &descRangeSRV, D3D12_SHADER_VISIBILITY_ALL); // スタティックサンプラー CD3DX12_STATIC_SAMPLER_DESC samplerDesc = CD3DX12_STATIC_SAMPLER_DESC(0, D3D12_FILTER_MIN_MAG_MIP_POINT); // s0 レジスタ // ルートシグネチャの設定 CD3DX12_VERSIONED_ROOT_SIGNATURE_DESC rootSignatureDesc; rootSignatureDesc.Init_1_0(_countof(rootparams), rootparams, 1, &samplerDesc, D3D12_ROOT_SIGNATURE_FLAG_ALLOW_INPUT_ASSEMBLER_INPUT_LAYOUT); ComPtr<ID3DBlob> rootSigBlob; // バージョン自動判定のシリアライズ result = D3DX12SerializeVersionedRootSignature(&rootSignatureDesc, D3D_ROOT_SIGNATURE_VERSION_1_0, &rootSigBlob, &errorBlob); if (FAILED(result)) { assert(0); return false; } // ルートシグネチャの生成 result = device->CreateRootSignature(0, rootSigBlob->GetBufferPointer(), rootSigBlob->GetBufferSize(), IID_PPV_ARGS(&rootSignature)); if (FAILED(result)) { assert(0); return false; } gpipeline.pRootSignature = rootSignature.Get(); // グラフィックスパイプラインの生成 result = device->CreateGraphicsPipelineState(&gpipeline, IID_PPV_ARGS(&pipelineState)); if (FAILED(result)) { assert(0); return false; } // 射影行列計算 matProjection = XMMatrixOrthographicOffCenterLH( 0.0f, (float)window_width, (float)window_height, 0.0f, 0.0f, 1.0f); // デスクリプタヒープを生成 D3D12_DESCRIPTOR_HEAP_DESC descHeapDesc = {}; descHeapDesc.Type = D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV; descHeapDesc.Flags = D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE;//シェーダから見えるように descHeapDesc.NumDescriptors = srvCount; result = device->CreateDescriptorHeap(&descHeapDesc, IID_PPV_ARGS(&descHeap));//生成 if (FAILED(result)) { assert(0); return false; } return true; } bool Sprite::LoadTexture(UINT texnumber, const wchar_t * filename) { // nullptrチェック assert(device); HRESULT result; // WICテクスチャのロード TexMetadata metadata{}; ScratchImage scratchImg{}; result = LoadFromWICFile( filename, WIC_FLAGS_NONE, &metadata, scratchImg); if (FAILED(result)) { assert(0); return false; } const Image* img = scratchImg.GetImage(0, 0, 0); // 生データ抽出 // リソース設定 CD3DX12_RESOURCE_DESC texresDesc = CD3DX12_RESOURCE_DESC::Tex2D( metadata.format, metadata.width, (UINT)metadata.height, (UINT16)metadata.arraySize, (UINT16)metadata.mipLevels ); // テクスチャ用バッファの生成 result = device->CreateCommittedResource( &CD3DX12_HEAP_PROPERTIES(D3D12_CPU_PAGE_PROPERTY_WRITE_BACK, D3D12_MEMORY_POOL_L0), D3D12_HEAP_FLAG_NONE, &texresDesc, D3D12_RESOURCE_STATE_GENERIC_READ, // テクスチャ用指定 nullptr, IID_PPV_ARGS(&texBuff[texnumber])); if (FAILED(result)) { assert(0); return false; } // テクスチャバッファにデータ転送 result = texBuff[texnumber]->WriteToSubresource( 0, nullptr, // 全領域へコピー img->pixels, // 元データアドレス (UINT)img->rowPitch, // 1ラインサイズ (UINT)img->slicePitch // 1枚サイズ ); if (FAILED(result)) { assert(0); return false; } // シェーダリソースビュー作成 D3D12_SHADER_RESOURCE_VIEW_DESC srvDesc{}; // 設定構造体 D3D12_RESOURCE_DESC resDesc = texBuff[texnumber]->GetDesc(); srvDesc.Format = resDesc.Format; srvDesc.Shader4ComponentMapping = D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING; srvDesc.ViewDimension = D3D12_SRV_DIMENSION_TEXTURE2D;//2Dテクスチャ srvDesc.Texture2D.MipLevels = 1; device->CreateShaderResourceView(texBuff[texnumber].Get(), //ビューと関連付けるバッファ &srvDesc, //テクスチャ設定情報 CD3DX12_CPU_DESCRIPTOR_HANDLE(descHeap->GetCPUDescriptorHandleForHeapStart(), texnumber, descriptorHandleIncrementSize) ); return true; } void Sprite::PreDraw(ID3D12GraphicsCommandList * cmdList) { // PreDrawとPostDrawがペアで呼ばれていなければエラー assert(Sprite::cmdList == nullptr); // コマンドリストをセット Sprite::cmdList = cmdList; // パイプラインステートの設定 cmdList->SetPipelineState(pipelineState.Get()); // ルートシグネチャの設定 cmdList->SetGraphicsRootSignature(rootSignature.Get()); // プリミティブ形状を設定 cmdList->IASetPrimitiveTopology(D3D_PRIMITIVE_TOPOLOGY_TRIANGLESTRIP); } void Sprite::PostDraw() { // コマンドリストを解除 Sprite::cmdList = nullptr; } Sprite * Sprite::Create(UINT texNumber, XMFLOAT2 position, XMFLOAT4 color, XMFLOAT2 anchorpoint, bool isFlipX, bool isFlipY) { // 仮サイズ XMFLOAT2 size = { 100.0f, 100.0f }; if (texBuff[texNumber]) { // テクスチャ情報取得 D3D12_RESOURCE_DESC resDesc = texBuff[texNumber]->GetDesc(); // スプライトのサイズをテクスチャのサイズに設定 size = { (float)resDesc.Width, (float)resDesc.Height }; } // Spriteのインスタンスを生成 Sprite* sprite = new Sprite(texNumber, position, size, color, anchorpoint, isFlipX, isFlipY); if (sprite == nullptr) { return nullptr; } // 初期化 if (!sprite->Initialize()) { delete sprite; assert(0); return nullptr; } return sprite; } Sprite::Sprite(UINT texNumber, XMFLOAT2 position, XMFLOAT2 size, XMFLOAT4 color, XMFLOAT2 anchorpoint, bool isFlipX, bool isFlipY) { this->position = position; this->size = size; this->anchorpoint = anchorpoint; this->matWorld = XMMatrixIdentity(); this->color = color; this->texNumber = texNumber; this->isFlipX = isFlipX; this->isFlipY = isFlipY; this->texSize = size; } bool Sprite::Initialize() { // nullptrチェック assert(device); HRESULT result = S_FALSE; // 頂点バッファ生成 result = device->CreateCommittedResource( &CD3DX12_HEAP_PROPERTIES(D3D12_HEAP_TYPE_UPLOAD), D3D12_HEAP_FLAG_NONE, &CD3DX12_RESOURCE_DESC::Buffer(sizeof(VertexPosUv) * vertNum), D3D12_RESOURCE_STATE_GENERIC_READ, nullptr, IID_PPV_ARGS(&vertBuff)); if (FAILED(result)) { assert(0); return false; } // 頂点バッファへのデータ転送 TransferVertices(); // 頂点バッファビューの作成 vbView.BufferLocation = vertBuff->GetGPUVirtualAddress(); vbView.SizeInBytes = sizeof(VertexPosUv) * 4; vbView.StrideInBytes = sizeof(VertexPosUv); // 定数バッファの生成 result = device->CreateCommittedResource( &CD3DX12_HEAP_PROPERTIES(D3D12_HEAP_TYPE_UPLOAD), // アップロード可能 D3D12_HEAP_FLAG_NONE, &CD3DX12_RESOURCE_DESC::Buffer((sizeof(ConstBufferData) + 0xff)&~0xff), D3D12_RESOURCE_STATE_GENERIC_READ, nullptr, IID_PPV_ARGS(&constBuff)); if (FAILED(result)) { assert(0); return false; } // 定数バッファにデータ転送 ConstBufferData* constMap = nullptr; result = constBuff->Map(0, nullptr, (void**)&constMap); if (SUCCEEDED(result)) { constMap->color = color; constMap->mat = matProjection; constBuff->Unmap(0, nullptr); } return true; } void Sprite::SetRotation(float rotation) { this->rotation = rotation; // 頂点バッファへのデータ転送 TransferVertices(); } void Sprite::SetPosition(XMFLOAT2 position) { this->position = position; // 頂点バッファへのデータ転送 TransferVertices(); } void Sprite::SetSize(XMFLOAT2 size) { this->size = size; // 頂点バッファへのデータ転送 TransferVertices(); } void Sprite::SetAnchorPoint(XMFLOAT2 anchorpoint) { this->anchorpoint = anchorpoint; // 頂点バッファへのデータ転送 TransferVertices(); } void Sprite::SetIsFlipX(bool isFlipX) { this->isFlipX = isFlipX; // 頂点バッファへのデータ転送 TransferVertices(); } void Sprite::SetIsFlipY(bool isFlipY) { this->isFlipY = isFlipY; // 頂点バッファへのデータ転送 TransferVertices(); } void Sprite::SetTextureRect(XMFLOAT2 texBase, XMFLOAT2 texSize) { this->texBase = texBase; this->texSize = texSize; // 頂点バッファへのデータ転送 TransferVertices(); } void Sprite::Draw() { // ワールド行列の更新 this->matWorld = XMMatrixIdentity(); this->matWorld *= XMMatrixRotationZ(XMConvertToRadians(rotation)); this->matWorld *= XMMatrixTranslation(position.x, position.y, 0.0f); // 定数バッファにデータ転送 ConstBufferData* constMap = nullptr; HRESULT result = constBuff->Map(0, nullptr, (void**)&constMap); if (SUCCEEDED(result)) { constMap->color = this->color; constMap->mat = this->matWorld * matProjection; // 行列の合成 constBuff->Unmap(0, nullptr); } // 頂点バッファの設定 cmdList->IASetVertexBuffers(0, 1, &this->vbView); ID3D12DescriptorHeap* ppHeaps[] = { descHeap.Get() }; // デスクリプタヒープをセット cmdList->SetDescriptorHeaps(_countof(ppHeaps), ppHeaps); // 定数バッファビューをセット cmdList->SetGraphicsRootConstantBufferView(0, this->constBuff->GetGPUVirtualAddress()); // シェーダリソースビューをセット cmdList->SetGraphicsRootDescriptorTable(1, CD3DX12_GPU_DESCRIPTOR_HANDLE(descHeap->GetGPUDescriptorHandleForHeapStart(), this->texNumber, descriptorHandleIncrementSize)); // 描画コマンド cmdList->DrawInstanced(4, 1, 0, 0); } void Sprite::TransferVertices() { HRESULT result = S_FALSE; // 左下、左上、右下、右上 enum { LB, LT, RB, RT }; float left = (0.0f - anchorpoint.x) * size.x; float right = (1.0f - anchorpoint.x) * size.x; float top = (0.0f - anchorpoint.x) * size.y; float bottom = (1.0f - anchorpoint.x) * size.y; if (isFlipX) {// 左右入れ替え left = -left; right = -right; } if (isFlipY) {// 上下入れ替え top = -top; bottom = -bottom; } // 頂点データ VertexPosUv vertices[vertNum]; vertices[LB].pos = { left, bottom, 0.0f }; // 左下 vertices[LT].pos = { left, top, 0.0f }; // 左上 vertices[RB].pos = { right, bottom, 0.0f }; // 右下 vertices[RT].pos = { right, top, 0.0f }; // 右上 // テクスチャ情報取得 if (texBuff[texNumber]) { D3D12_RESOURCE_DESC resDesc = texBuff[texNumber]->GetDesc(); float tex_left = texBase.x / resDesc.Width; float tex_right = (texBase.x + texSize.x) / resDesc.Width; float tex_top = texBase.y / resDesc.Height; float tex_bottom = (texBase.y + texSize.y) / resDesc.Height; vertices[LB].uv = { tex_left, tex_bottom }; // 左下 vertices[LT].uv = { tex_left, tex_top }; // 左上 vertices[RB].uv = { tex_right, tex_bottom }; // 右下 vertices[RT].uv = { tex_right, tex_top }; // 右上 } // 頂点バッファへのデータ転送 VertexPosUv* vertMap = nullptr; result = vertBuff->Map(0, nullptr, (void**)&vertMap); if (SUCCEEDED(result)) { memcpy(vertMap, vertices, sizeof(vertices)); vertBuff->Unmap(0, nullptr); } } <file_sep>/CollisionInfo.cpp #include "CollisionInfo.h" <file_sep>/CollisionManager.h #pragma once #include<forward_list> class BaseCollider; class CollisionManager { public://静的メンバ関数 static CollisionManager* GetInstance(); public://メンバ関数 //コライダー追加 inline void AddCollider(BaseCollider* collider) { colliders.push_front(collider); } //コライダー削除 inline void RemoveCollider(BaseCollider* collider) { colliders.remove(collider); } //全ての衝突チェック void CheckAllCollision(); private: CollisionManager() = default; CollisionManager(const CollisionManager&) = delete; ~CollisionManager() = default; CollisionManager& operator=(const CollisionManager&) = delete; //コライダーのリスト std::forward_list<BaseCollider*> colliders; }; <file_sep>/Audio.cpp #include "Audio.h" #include <fstream> #include <cassert> #pragma comment(lib,"xaudio2.lib") //テスト bool Audio::Initialize() { HRESULT result; // XAudioエンジンのインスタンスを生成 result = XAudio2Create(&xAudio2, 0, XAUDIO2_DEFAULT_PROCESSOR); if FAILED(result) { assert(0); return false; } // マスターボイスを生成 result = xAudio2->CreateMasteringVoice(&masterVoice); if FAILED(result) { assert(0); return false; } return true; } void Audio::PlayWave(const char* filename) { HRESULT result; // ファイルストリーム std::ifstream file; // Waveファイルを開く file.open(filename, std::ios_base::binary); // ファイルオープン失敗をチェック if (file.fail()) { assert(0); } // RIFFヘッダーの読み込み RiffHeader riff; file.read((char*)&riff, sizeof(riff)); // ファイルがRIFFかチェック if (strncmp(riff.chunk.id, "RIFF", 4) != 0) { assert(0); } // Formatチャンクの読み込み FormatChunk format; file.read((char*)&format, sizeof(format)); // Dataチャンクの読み込み Chunk data; file.read((char*)&data, sizeof(data)); // Dataチャンクのデータ部(波形データ)の読み込み char* pBuffer = new char[data.size]; file.read(pBuffer, data.size); // Waveファイルを閉じる file.close(); WAVEFORMATEX wfex{}; // 波形フォーマットの設定 memcpy(&wfex, &format.fmt, sizeof(format.fmt)); wfex.wBitsPerSample = format.fmt.nBlockAlign * 8 / format.fmt.nChannels; // 波形フォーマットを元にSourceVoiceの生成 IXAudio2SourceVoice* pSourceVoice = nullptr; result = xAudio2->CreateSourceVoice(&pSourceVoice, &wfex, 0, 2.0f, &voiceCallback); if FAILED(result) { delete[] pBuffer; assert(0); return; } // 再生する波形データの設定 XAUDIO2_BUFFER buf{}; buf.pAudioData = (BYTE*)pBuffer; buf.pContext = pBuffer; buf.Flags = XAUDIO2_END_OF_STREAM; buf.AudioBytes = data.size; // 波形データの再生 result = pSourceVoice->SubmitSourceBuffer(&buf); if FAILED(result) { delete[] pBuffer; assert(0); return; } result = pSourceVoice->Start(); if FAILED(result) { delete[] pBuffer; assert(0); return; } } <file_sep>/BaseCollider.h #pragma once #include"CollisionTypes.h" #include"Object3d.h" #include"CollisionInfo.h" class BaseCollider { public: BaseCollider() = default; //仮想デストラクタ virtual~BaseCollider() = default; inline void SetObject(Object3d* object) { this->object3d = object; } inline Object3d* GetObject3d() { return object3d; } //更新 virtual void Update() = 0; //形状タイプ取得 inline CollisionShapeType GetShapeType() { return shapeType; } //衝突時コールバック関数 inline void OnCollision(const CollisionInfo& info) { object3d->OnCollision(info); } protected: Object3d* object3d = nullptr; //形状タイプ CollisionShapeType shapeType = SHAPE_UNKNOWN; }; <file_sep>/Sprite.h #pragma once #include <Windows.h> #include <wrl.h> #include <d3d12.h> #include <DirectXMath.h> class Sprite { private: // エイリアス // Microsoft::WRL::を省略 template <class T> using ComPtr = Microsoft::WRL::ComPtr<T>; // DirectX::を省略 using XMFLOAT2 = DirectX::XMFLOAT2; using XMFLOAT3 = DirectX::XMFLOAT3; using XMFLOAT4 = DirectX::XMFLOAT4; using XMMATRIX = DirectX::XMMATRIX; public: // サブクラス /// <summary> /// 頂点データ構造体 /// </summary> struct VertexPosUv { XMFLOAT3 pos; // xyz座標 XMFLOAT2 uv; // uv座標 }; /// <summary> /// 定数バッファ用データ構造体 /// </summary> struct ConstBufferData { XMFLOAT4 color; // 色 (RGBA) XMMATRIX mat; // 3D変換行列 }; public: // 静的メンバ関数 /// <summary> /// 静的初期化 /// </summary> /// <param name="device">デバイス</param> /// <param name="window_width">画面幅</param> /// <param name="window_height">画面高さ</param> /// <returns>成否</returns> static bool StaticInitialize(ID3D12Device* device, int window_width, int window_height); /// <summary> /// テクスチャ読み込み /// </summary> /// <param name="texnumber">テクスチャ番号</param> /// <param name="filename">画像ファイル名</param> /// <returns>成否</returns> static bool LoadTexture(UINT texnumber, const wchar_t*filename); /// <summary> /// 描画前処理 /// </summary> /// <param name="cmdList">描画コマンドリスト</param> static void PreDraw(ID3D12GraphicsCommandList* cmdList); /// <summary> /// 描画後処理 /// </summary> static void PostDraw(); /// <summary> /// スプライト生成 /// </summary> /// <param name="texNumber">テクスチャ番号</param> /// <param name="position">座標</param> /// <param name="color">色</param> /// <param name="anchorpoint">アンカーポイント</param> /// <param name="isFlipX">左右反転</param> /// <param name="isFlipY">上下反転</param> /// <returns>生成されたスプライト</returns> static Sprite* Create(UINT texNumber, XMFLOAT2 position, XMFLOAT4 color = { 1, 1, 1, 1 }, XMFLOAT2 anchorpoint = { 0.0f, 0.0f }, bool isFlipX = false, bool isFlipY = false); private: // 静的メンバ変数 // テクスチャの最大枚数 static const int srvCount = 512; // 頂点数 static const int vertNum = 4; // デバイス static ID3D12Device* device; // デスクリプタサイズ static UINT descriptorHandleIncrementSize; // コマンドリスト static ID3D12GraphicsCommandList* cmdList; // ルートシグネチャ static ComPtr<ID3D12RootSignature> rootSignature; // パイプラインステートオブジェクト static ComPtr<ID3D12PipelineState> pipelineState; // 射影行列 static XMMATRIX matProjection; // デスクリプタヒープ static ComPtr<ID3D12DescriptorHeap> descHeap; // テクスチャバッファ static ComPtr<ID3D12Resource> texBuff[srvCount]; public: // メンバ関数 Sprite(UINT texNumber, XMFLOAT2 position, XMFLOAT2 size, XMFLOAT4 color, XMFLOAT2 anchorpoint, bool isFlipX, bool isFlipY); bool Initialize(); void SetRotation(float rotation); void SetPosition(XMFLOAT2 position); void SetSize(XMFLOAT2 size); void SetAnchorPoint(XMFLOAT2 anchorpoint); void SetIsFlipX(bool isFlipX); void SetIsFlipY(bool isFlipY); void SetTextureRect(XMFLOAT2 texBase, XMFLOAT2 texSize); void Draw(); //座標の取得 const XMFLOAT2& GetPosition() { return position; } private: // メンバ変数 // 頂点バッファ ComPtr<ID3D12Resource> vertBuff; // 定数バッファ ComPtr<ID3D12Resource> constBuff; // 頂点バッファビュー D3D12_VERTEX_BUFFER_VIEW vbView{}; // テクスチャ番号 UINT texNumber = 0; // Z軸回りの回転角 float rotation = 0.0f; // 座標 XMFLOAT2 position{}; // スプライト幅、高さ XMFLOAT2 size = { 100.0f, 100.0f }; // アンカーポイント XMFLOAT2 anchorpoint = { 0, 0 }; // ワールド行列 XMMATRIX matWorld; // 色 XMFLOAT4 color = { 1, 1, 1, 1 }; // 左右反転 bool isFlipX = false; // 上下反転 bool isFlipY = false; // テクスチャ始点 XMFLOAT2 texBase = { 0, 0 }; // テクスチャ幅、高さ XMFLOAT2 texSize = { 100.0f, 100.0f }; private: // メンバ関数 /// <summary> /// 頂点データ転送 /// </summary> void TransferVertices(); }; <file_sep>/TestObject.cpp #include "TestObject.h" #include"SphereCollider.h" #include"Input.h" using namespace DirectX; TestObject* TestObject::Create(int window_width, int window_height) { //インスタンス生成 TestObject* testObject = new TestObject(); //初期化 testObject->Initialize(window_width, window_height); //初期位置 XMFLOAT3 position = testObject->GetPosition(); position = {0,-20,0}; testObject->SetPosition(position); return testObject; } void TestObject::Initialize(int window_width, int window_height) { Object3d::Initialize(window_width,window_height); //コライダー追加 float radius = 2; SetCollider(new SphereCollider(XMVECTOR({ radius,radius,0,0 }), radius)); } void TestObject::Update() { Input* input = Input::GetInstance(); Object3d::Update(); } void TestObject::OnCollision(const CollisionInfo& info) { position.y += 10; } <file_sep>/BaseScene.cpp #include "BaseScene.h" BaseScene::BaseScene(ISceneChanger * changer) :mSceneChanger(changer) { } void BaseScene::Initialize(DirectXCommon * dxCommon, Input * input,Audio* audio) { assert(dxCommon); assert(input); assert(audio); this->dxCommon = dxCommon; this->input = input; this->audio = audio; } void BaseScene::Finalize() { } void BaseScene::Update() { } void BaseScene::Draw() { }<file_sep>/GameOver.cpp #include "GameOver.h" GameOver::GameOver(ISceneChanger * changer) : BaseScene(changer) { } void GameOver::Initialize(DirectXCommon * dxCommon, Input * input, Audio* audio) { this->dxCommon = dxCommon; this->input = input; this->audio = audio; gameoversprite->LoadTexture(1, L"Resources/GameOver.png"); gameoversprite->Create(1, {0,0}); } void GameOver::Update() { if (input->Trigger(DIK_SPACE)) { mSceneChanger->ChangeScene(eScene_Title);//シーンをゲーム画面に変更 } } void GameOver::Draw() { // コマンドリストの取得 ID3D12GraphicsCommandList* cmdList = dxCommon->GetCommandList(); gameoversprite->PreDraw(cmdList); gameoversprite->Draw(); gameoversprite->PostDraw(); // 深度バッファクリア dxCommon->ClearDepthBuffer(); }<file_sep>/Object3d.cpp #include "Object3d.h" #include <d3dcompiler.h> #include <DirectXTex.h> #include<string> #include<vector> #include<fstream> #include<sstream> #include"BaseCollider.h" #include"CollisionManager.h" #pragma comment(lib, "d3dcompiler.lib") using namespace std; using namespace DirectX; using namespace Microsoft::WRL; ID3D12Device* Object3d::device = nullptr; ID3D12GraphicsCommandList* Object3d::cmdList = nullptr; ComPtr<ID3D12RootSignature> Object3d::rootsignature; ComPtr<ID3D12PipelineState> Object3d::pipelinestate; void Object3d::StaticInitialize(ID3D12Device * device) { Object3d::device = device; } void Object3d::InitializeGraphicsPipeline() { HRESULT result; ComPtr<ID3DBlob> vsBlob; // 頂点シェーダオブジェクト ComPtr<ID3DBlob> psBlob; // ピクセルシェーダオブジェクト ComPtr<ID3DBlob> errorBlob; // エラーオブジェクト // 頂点シェーダの読み込みとコンパイル result = D3DCompileFromFile( L"BasicVertexShader.hlsl", // シェーダファイル名 nullptr, D3D_COMPILE_STANDARD_FILE_INCLUDE, // インクルード可能にする "VSmain", "vs_5_0", // エントリーポイント名、シェーダーモデル指定 D3DCOMPILE_DEBUG | D3DCOMPILE_SKIP_OPTIMIZATION, // デバッグ用設定 0, &vsBlob, &errorBlob); // ピクセルシェーダの読み込みとコンパイル result = D3DCompileFromFile( L"BasicPixelShader.hlsl", // シェーダファイル名 nullptr, D3D_COMPILE_STANDARD_FILE_INCLUDE, // インクルード可能にする "PSmain", "ps_5_0", // エントリーポイント名、シェーダーモデル指定 D3DCOMPILE_DEBUG | D3DCOMPILE_SKIP_OPTIMIZATION, // デバッグ用設定 0, &psBlob, &errorBlob); if (FAILED(result)) { //errorBlobからエラー内容をstring型にコピー std::string errstr;//受け取り用string errstr.resize(errorBlob.Get()->GetBufferSize());//必要なサイズを確保 //データコピー std::copy_n((char*)errorBlob.Get()->GetBufferPointer(), errorBlob.Get()->GetBufferSize(), errstr.begin()); errstr += "\n"; //エラー内容を出力ウィンドウに表示 OutputDebugStringA(errstr.c_str()); exit(1); } //頂点レイアウト D3D12_INPUT_ELEMENT_DESC inputLayout[] = { //xyz座標 { "POSITION", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, D3D12_APPEND_ALIGNED_ELEMENT, D3D12_INPUT_CLASSIFICATION_PER_VERTEX_DATA, 0 }, // (1 行で書いたほうが見やすい)xy座標 //法線ベクトル { "NORMAL", 0, DXGI_FORMAT_R32G32B32_FLOAT,0, D3D12_APPEND_ALIGNED_ELEMENT, D3D12_INPUT_CLASSIFICATION_PER_VERTEX_DATA,0 }, //uv座標 {"TEXCOORD",0,DXGI_FORMAT_R32G32_FLOAT,0,D3D12_APPEND_ALIGNED_ELEMENT,D3D12_INPUT_CLASSIFICATION_PER_VERTEX_DATA,0},//uv座標 }; //グラフィクスパイプラインの各ステージの設定をする構造体 D3D12_GRAPHICS_PIPELINE_STATE_DESC gpipeline{}; //頂点シェーダ、ピクセルシェーダーをパイプラインに設定 gpipeline.VS = CD3DX12_SHADER_BYTECODE(vsBlob.Get()); gpipeline.PS = CD3DX12_SHADER_BYTECODE(psBlob.Get()); //サンプルマスクとラスタライザステートの設定 gpipeline.SampleMask = D3D12_DEFAULT_SAMPLE_MASK; // ラスタライザステート gpipeline.RasterizerState = CD3DX12_RASTERIZER_DESC(D3D12_DEFAULT); // デプスステンシルステート gpipeline.DepthStencilState = CD3DX12_DEPTH_STENCIL_DESC(D3D12_DEFAULT); //レンダーターゲットのブレンド設定 D3D12_RENDER_TARGET_BLEND_DESC blenddesc{}; blenddesc.RenderTargetWriteMask = D3D12_COLOR_WRITE_ENABLE_ALL;//標準設定 blenddesc.BlendEnable = true;//ブレンドを有効にする blenddesc.BlendOpAlpha = D3D12_BLEND_OP_ADD;//加算 blenddesc.SrcBlendAlpha = D3D12_BLEND_ONE;//ソースの値使う blenddesc.DestBlendAlpha = D3D12_BLEND_ZERO;//1.0f-ソースのα値 //ブレンド変更 blenddesc.BlendOp = D3D12_BLEND_OP_ADD;//加算 blenddesc.SrcBlend = D3D12_BLEND_SRC_ALPHA;//ソースの値を100%使う blenddesc.DestBlend = D3D12_BLEND_INV_SRC_ALPHA;//デストの値を0%使う //ブレンドステートの設定 gpipeline.BlendState.RenderTarget[0] = blenddesc; // 深度バッファのフォーマット gpipeline.DSVFormat = DXGI_FORMAT_D32_FLOAT; //頂点レイアウトの設定 gpipeline.InputLayout.pInputElementDescs = inputLayout; gpipeline.InputLayout.NumElements = _countof(inputLayout); //図形の形状を三角形に設定 gpipeline.PrimitiveTopologyType = D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE; //その他の設定 gpipeline.NumRenderTargets = 1; // 描画対象は 1 つ gpipeline.RTVFormats[0] = DXGI_FORMAT_R8G8B8A8_UNORM; // 0~255 指定の RGBA gpipeline.SampleDesc.Count = 1; // 1 ピクセルにつき 1 回サンプリング // デスクリプタレンジ CD3DX12_DESCRIPTOR_RANGE descRangeSRV; descRangeSRV.Init(D3D12_DESCRIPTOR_RANGE_TYPE_SRV, 1, 0); // t0 レジスタ // ルートパラメータ CD3DX12_ROOT_PARAMETER rootparams[3]; rootparams[0].InitAsConstantBufferView(0, 0, D3D12_SHADER_VISIBILITY_ALL); rootparams[1].InitAsConstantBufferView(1, 0, D3D12_SHADER_VISIBILITY_ALL); rootparams[2].InitAsDescriptorTable(1, &descRangeSRV, D3D12_SHADER_VISIBILITY_ALL); //サンプラーの設定 CD3DX12_STATIC_SAMPLER_DESC samplerDesc = CD3DX12_STATIC_SAMPLER_DESC(0); //ルートシグネチャの生成 CD3DX12_VERSIONED_ROOT_SIGNATURE_DESC rootSignatureDesc; rootSignatureDesc.Init_1_0(_countof(rootparams), rootparams, 1, &samplerDesc, D3D12_ROOT_SIGNATURE_FLAG_ALLOW_INPUT_ASSEMBLER_INPUT_LAYOUT); ComPtr<ID3DBlob> rootSigBlob; //バージョン自動判定でのシリアライズ result = D3DX12SerializeVersionedRootSignature(&rootSignatureDesc, D3D_ROOT_SIGNATURE_VERSION_1_0, &rootSigBlob, &errorBlob); result = device->CreateRootSignature(0, rootSigBlob->GetBufferPointer(), rootSigBlob->GetBufferSize(), IID_PPV_ARGS(&rootsignature)); // パイプラインにルートシグネチャをセット gpipeline.pRootSignature = rootsignature.Get(); //パイプラインステートの生成 result = device->CreateGraphicsPipelineState(&gpipeline, IID_PPV_ARGS(&pipelinestate)); } void Object3d::InitializeDescriptorHeap() { HRESULT result; // デスクリプタヒープを生成 D3D12_DESCRIPTOR_HEAP_DESC descHeapDesc = {}; descHeapDesc.Type = D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV; descHeapDesc.Flags = D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE;//シェーダから見えるように descHeapDesc.NumDescriptors = 1; // シェーダーリソースビュー1つ result = device->CreateDescriptorHeap(&descHeapDesc, IID_PPV_ARGS(&descHeap));//生成 // デスクリプタサイズを取得 descriptorHandleIncrementSize = device->GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV); } void Object3d::InitializeCamera(int window_width,int window_height) { // ビュー行列の生成 matView = XMMatrixLookAtLH( XMLoadFloat3(&eye), XMLoadFloat3(&target), XMLoadFloat3(&up)); //射影変換行列 matProjection = XMMatrixPerspectiveFovLH( XMConvertToRadians(60.0f),//画角60度 (float)window_width / window_height,//アスペクト比(画面横幅/画面縦幅) 0.1f,//前端 1000.0f//奥端 ); } Object3d * Object3d::Create(int window_width, int window_height) { // 3Dオブジェクトのインスタンスを生成 Object3d* object3d = new Object3d(); object3d->Initialize(window_width,window_height); return object3d; } Object3d::~Object3d() { if (collider) { //コリジョンマネージャから登録を解除する CollisionManager::GetInstance()->RemoveCollider(collider); delete collider; } } void Object3d::Initialize(int window_width, int window_height) { // デスクリプタヒープの初期化 InitializeDescriptorHeap(); // カメラ初期化 InitializeCamera(window_width, window_height); // パイプライン初期化 InitializeGraphicsPipeline(); // テクスチャ読み込み LoadTexture("Resources", "start.png"); // モデル生成 CreateModel(); assert(device); HRESULT result; // 定数バッファの生成 result = device->CreateCommittedResource( &CD3DX12_HEAP_PROPERTIES(D3D12_HEAP_TYPE_UPLOAD), // アップロード可能 D3D12_HEAP_FLAG_NONE, &CD3DX12_RESOURCE_DESC::Buffer((sizeof(ConstBufferDataB1) + 0xff)&~0xff), D3D12_RESOURCE_STATE_GENERIC_READ, nullptr, IID_PPV_ARGS(&constBuffB1)); //constBufferBOの定数バッファ生成 result = device->CreateCommittedResource( &CD3DX12_HEAP_PROPERTIES(D3D12_HEAP_TYPE_UPLOAD), // アップロード可能 D3D12_HEAP_FLAG_NONE, &CD3DX12_RESOURCE_DESC::Buffer((sizeof(ConstBufferDataBO) + 0xff)&~0xff), D3D12_RESOURCE_STATE_GENERIC_READ, nullptr, IID_PPV_ARGS(&constBuffBO)); //クラス名の文字列を取得 name = typeid(*this).name(); } void Object3d::CreateModel() { HRESULT result; //ファイルストリーム ifstream file; //.objファイルを開く const string modelname = "StartObject"; const string filename = "start.obj"; const string directoryPath = "Resources/" + modelname + "/"; file.open(directoryPath + filename); //ファイルオープン失敗をチェック if (file.fail()) { assert(0); } vector<XMFLOAT3> positions;//頂点座標 vector<XMFLOAT3> normals;//法線ベクトル vector<XMFLOAT2> texcoords;//テクスチャUV //1行ずつ読み込む string line; while (getline(file, line)) { //1行分の文字列をストリームに変換して解析しやすくする std::istringstream line_stream(line); //半角スペース区切りで行の先頭文字列を取得 string key; getline(line_stream, key, ' '); //先頭文字列がvなら頂点座標 if (key == "v") { //x,y,z座標読み込み XMFLOAT3 position{}; line_stream >> position.x; line_stream >> position.y; line_stream >> position.z; //座標データに追加 positions.emplace_back(position); } //先頭文字列がfならポリゴン(三角形) if (key == "f") { //半角スペース区切りで行の続きを読み込む string index_string; while (getline(line_stream, index_string, ' ')) { //頂点インデックス1個分の文字列をストリームに変換して解析しやすくする istringstream index_stream(index_string); unsigned short indexPosition, indexNormal, indexTexcoord; index_stream >> indexPosition; //スラッシュを飛ばす index_stream.seekg(1, ios_base::cur); index_stream >> indexTexcoord; index_stream.seekg(1, ios_base::cur); index_stream >> indexNormal; //頂点データの追加 VertexPosNormalUv vertex{}; vertex.pos = positions[indexPosition - 1]; vertex.normal = normals[indexNormal - 1]; vertex.uv = texcoords[indexTexcoord - 1]; vertices.emplace_back(vertex); //インデックスデータの追加 indices.emplace_back((unsigned short)indices.size()); } } //先頭文字列がvtならテクスチャ if (key == "vt") { //uv成分読み込み XMFLOAT2 texcoord{}; line_stream >> texcoord.x; line_stream >> texcoord.y; //v方向反転 texcoord.y = 1.0f - texcoord.y; //テクスチャ座標データに追加 texcoords.emplace_back(texcoord); } //先頭の文字列がvnなら法線ベクトル if (key == "vn") { //x,y,z成分読み込み XMFLOAT3 normal{}; line_stream >> normal.x; line_stream >> normal.y; line_stream >> normal.z; //法線ベクトルデータに追加 normals.emplace_back(normal); } //先頭の文字列がmtllibならマテリアル if (key == "mtllib") { //マテリアルのファイル読み込み string filename; line_stream >> filename; //マテリアル読み込み LoadMaterial(directoryPath, filename); } } //ファイルを閉じる file.close(); UINT sizeVB = static_cast<UINT>(sizeof(VertexPosNormalUv)*vertices.size()); UINT sizeIB = static_cast<UINT>(sizeof(unsigned short)*indices.size()); //頂点バッファの生成 result = device->CreateCommittedResource( &CD3DX12_HEAP_PROPERTIES(D3D12_HEAP_TYPE_UPLOAD),//アップロード可能 D3D12_HEAP_FLAG_NONE, &CD3DX12_RESOURCE_DESC::Buffer(sizeVB), D3D12_RESOURCE_STATE_GENERIC_READ, nullptr, IID_PPV_ARGS(&vertBuff)); //インデックスバッファの生成 result = device->CreateCommittedResource( &CD3DX12_HEAP_PROPERTIES(D3D12_HEAP_TYPE_UPLOAD),//アップロード可能 D3D12_HEAP_FLAG_NONE, &CD3DX12_RESOURCE_DESC::Buffer(sizeIB), D3D12_RESOURCE_STATE_GENERIC_READ, nullptr, IID_PPV_ARGS(&indexBuff)); // 頂点バッファへのデータ転送 VertexPosNormalUv* vertMap = nullptr; result = vertBuff->Map(0, nullptr, (void**)&vertMap); if (SUCCEEDED(result)) { std::copy(vertices.begin(), vertices.end(), vertMap); vertBuff->Unmap(0, nullptr); } // インデックスバッファへのデータ転送 unsigned short* indexMap = nullptr; result = indexBuff->Map(0, nullptr, (void**)&indexMap); if (SUCCEEDED(result)) { // 全インデックスに対して std::copy(indices.begin(), indices.end(), indexMap); indexBuff->Unmap(0, nullptr); } //頂点バッファビューの作成 vbView.BufferLocation = vertBuff->GetGPUVirtualAddress(); vbView.SizeInBytes = sizeVB; vbView.StrideInBytes = sizeof(vertices[0]); //インデックスバッファビューの作成 ibView.BufferLocation = indexBuff->GetGPUVirtualAddress(); ibView.Format = DXGI_FORMAT_R16_UINT; ibView.SizeInBytes = sizeIB; } void Object3d::Update() { HRESULT result; XMMATRIX matScale, matRot, matTrans; // スケール、回転、平行移動行列の計算 matScale = XMMatrixScaling(scale.x, scale.y, scale.z); matRot = XMMatrixIdentity(); matRot *= XMMatrixRotationZ(XMConvertToRadians(rotation.z)); matRot *= XMMatrixRotationX(XMConvertToRadians(rotation.x)); matRot *= XMMatrixRotationY(XMConvertToRadians(rotation.y)); matTrans = XMMatrixTranslation(position.x, position.y, position.z); // ワールド行列の合成 matWorld = XMMatrixIdentity(); // 変形をリセット matWorld *= matScale; // ワールド行列にスケーリングを反映 matWorld *= matRot; // ワールド行列に回転を反映 matWorld *= matTrans; // ワールド行列に平行移動を反映 // 親オブジェクトがあれば if (parent != nullptr) { // 親オブジェクトのワールド行列を掛ける matWorld *= parent->matWorld; } // 定数バッファへデータ転送 ConstBufferDataBO* constMap0 = nullptr; result = constBuffBO->Map(0, nullptr, (void**)&constMap0); constMap0->mat = matWorld * matView * matProjection; // 行列の合成 constBuffBO->Unmap(0, nullptr); //定数バッファへデータ転送 ConstBufferDataB1* constMap1 = nullptr; result = constBuffB1->Map(0, nullptr, (void**)&constMap1); constMap1->ambient = material.ambient; constMap1->diffuse = material.diffuse; constMap1->speculer = material.specular; constMap1->alpha = material.alpha; constBuffB1->Unmap(0, nullptr); //当たり判定更新 if (collider) { collider->Update(); } } void Object3d::PreDraw(ID3D12GraphicsCommandList* cmdList) { // PreDrawとPostDrawがペアで呼ばれていなければエラー //assert(cmdList == nullptr); // コマンドリストをセット Object3d::cmdList = cmdList; //パイプラインステートの設定コマンド cmdList->SetPipelineState(pipelinestate.Get()); //ルートシグネチャの設定コマンド cmdList->SetGraphicsRootSignature(rootsignature.Get()); //プリミティブ形状の設定コマンド(三角形リスト) cmdList->IASetPrimitiveTopology(D3D_PRIMITIVE_TOPOLOGY_TRIANGLESTRIP); } void Object3d::Draw() { //頂点バッファの設定コマンド cmdList->IASetVertexBuffers(0, 1, &vbView); //インデックスバッファの設定コマンド cmdList->IASetIndexBuffer(&ibView); //デスクリプタヒープの配列 ID3D12DescriptorHeap* ppHeaps[] = { descHeap.Get() }; cmdList->SetDescriptorHeaps(_countof(ppHeaps), ppHeaps); // 定数バッファビューをセット cmdList->SetGraphicsRootConstantBufferView(0, constBuffBO->GetGPUVirtualAddress()); cmdList->SetGraphicsRootConstantBufferView(1, constBuffB1->GetGPUVirtualAddress()); // シェーダリソースビューをセット cmdList->SetGraphicsRootDescriptorTable(2, gpuDescHandleSRV); // 描画コマンド cmdList->DrawIndexedInstanced((UINT)indices.size(), 1, 0, 0, 0); } void Object3d::SetCollider(BaseCollider* collider) { collider->SetObject(this); this->collider = collider; //コリジョンマネージャに登録 CollisionManager::GetInstance()->AddCollider(collider); //コライダー更新 collider->Update(); } void Object3d::PostDraw() { Object3d::cmdList = nullptr; } void Object3d::LoadMaterial(const std::string & directoryPath, const std::string & filename) { //ファイルストリーム ifstream file; //マテリアルファイルを開く file.open(directoryPath + filename); //ファイルオープン失敗チェック if (file.fail()) { assert(0); } //1行ずつ読み込む string line; while (getline(file, line)) { //1行分の文字列をストリームに変換 std::istringstream line_stream(line); //半角スペース区切りで行の先頭文字列を取得 string key; getline(line_stream, key, ' '); //先頭のタブ文字は無視する if (key[0] == '\t') { key.erase(key.begin());//先頭の文字を削除 } //先頭文字列がnewmtlならマテリアル if (key == "newmtl") { //マテリアル読みこみ line_stream >> material.name; } //先頭文字列がKaならアンビエント色 if (key == "Ka") { line_stream >> material.ambient.x; line_stream >> material.ambient.y; line_stream >> material.ambient.z; } //先頭文字列がKdならディフーズ色 if (key == "Kd") { line_stream >> material.diffuse.x; line_stream >> material.diffuse.y; line_stream >> material.diffuse.z; } //先頭文字列がKsならスペキュラー色 if (key == "Ks") { line_stream >> material.specular.x; line_stream >> material.specular.y; line_stream >> material.specular.z; } //先頭文字列がmap_Kdならテクスチャファイル名 if (key == "map_Kd") { //テクスチャファイル名読み込み line_stream >> material.textuerFilename; //テクスチャ読み込み LoadTexture(directoryPath, material.textuerFilename); } } //ファイルを閉じる file.close(); } //void Object3d::LoadTexture(const std::string & directoryPath, const std::string & filename) //{ // HRESULT result; // // // WICテクスチャのロード // TexMetadata metadata{}; // ScratchImage scratchImg{}; // // //ファイルパス結合 // string filepath = directoryPath + filename; // // //ユニコード文字列に変換する // wchar_t wfilepath[128]; // int iBufferSize = MultiByteToWideChar(CP_ACP, 0, // filepath.c_str(), -1, wfilepath, _countof(wfilepath)); // // result = LoadFromWICFile( // wfilepath, WIC_FLAGS_NONE, // &metadata, scratchImg); // // const Image* img = scratchImg.GetImage(0, 0, 0); // 生データ抽出 // // //リソース設定 // CD3DX12_RESOURCE_DESC texresDesc = CD3DX12_RESOURCE_DESC::Tex2D( // metadata.format, // metadata.width, // (UINT)metadata.height, // (UINT16)metadata.arraySize, // (UINT16)metadata.mipLevels // ); // // // テクスチャ用バッファの生成 // result = device->CreateCommittedResource( // &CD3DX12_HEAP_PROPERTIES(D3D12_CPU_PAGE_PROPERTY_WRITE_BACK, D3D12_MEMORY_POOL_L0), // D3D12_HEAP_FLAG_NONE, // &texresDesc, // D3D12_RESOURCE_STATE_GENERIC_READ, // テクスチャ用指定 // nullptr, // IID_PPV_ARGS(&texbuff)); // // // テクスチャバッファにデータ転送 // result = texbuff->WriteToSubresource( // 0, // nullptr, // 全領域へコピー // img->pixels, // 元データアドレス // (UINT)img->rowPitch, // 1ラインサイズ // (UINT)img->slicePitch // 1枚サイズ // ); // // // シェーダリソースビュー作成 // cpuDescHandleSRV = CD3DX12_CPU_DESCRIPTOR_HANDLE(descHeap->GetCPUDescriptorHandleForHeapStart(), 0, descriptorHandleIncrementSize); // gpuDescHandleSRV = CD3DX12_GPU_DESCRIPTOR_HANDLE(descHeap->GetGPUDescriptorHandleForHeapStart(), 0, descriptorHandleIncrementSize); // // D3D12_SHADER_RESOURCE_VIEW_DESC srvDesc{}; // 設定構造体 // D3D12_RESOURCE_DESC resDesc = texbuff->GetDesc(); // // srvDesc.Format = resDesc.Format; // srvDesc.Shader4ComponentMapping = D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING; // srvDesc.ViewDimension = D3D12_SRV_DIMENSION_TEXTURE2D;//2Dテクスチャ // srvDesc.Texture2D.MipLevels = 1; // // device->CreateShaderResourceView(texbuff.Get(), //ビューと関連付けるバッファ // &srvDesc, //テクスチャ設定情報 // cpuDescHandleSRV // ); //} bool Object3d::LoadTexture(const std::string& directoryPath, const std::string& filename) { HRESULT result = S_FALSE; // WICテクスチャのロード TexMetadata metadata{}; ScratchImage scratchImg{}; //ファイルパス結合 string filepath = directoryPath + filename; //ユニコード文字列に変換する wchar_t wfilepath[128]; int iBufferSize = MultiByteToWideChar(CP_ACP, 0, filepath.c_str(), -1, wfilepath, _countof(wfilepath)); result = LoadFromWICFile( wfilepath, WIC_FLAGS_NONE, &metadata, scratchImg); if (FAILED(result)) { return result; } const Image* img = scratchImg.GetImage(0, 0, 0); // 生データ抽出 // リソース設定 CD3DX12_RESOURCE_DESC texresDesc = CD3DX12_RESOURCE_DESC::Tex2D( metadata.format, metadata.width, (UINT)metadata.height, (UINT16)metadata.arraySize, (UINT16)metadata.mipLevels ); // テクスチャ用バッファの生成 result = device->CreateCommittedResource( &CD3DX12_HEAP_PROPERTIES(D3D12_CPU_PAGE_PROPERTY_WRITE_BACK, D3D12_MEMORY_POOL_L0), D3D12_HEAP_FLAG_NONE, &texresDesc, D3D12_RESOURCE_STATE_GENERIC_READ, // テクスチャ用指定 nullptr, IID_PPV_ARGS(&texbuff)); if (FAILED(result)) { return result; } // テクスチャバッファにデータ転送 result = texbuff->WriteToSubresource( 0, nullptr, // 全領域へコピー img->pixels, // 元データアドレス (UINT)img->rowPitch, // 1ラインサイズ (UINT)img->slicePitch // 1枚サイズ ); if (FAILED(result)) { return result; } // シェーダリソースビュー作成 cpuDescHandleSRV = CD3DX12_CPU_DESCRIPTOR_HANDLE(descHeap->GetCPUDescriptorHandleForHeapStart(), 0, descriptorHandleIncrementSize); gpuDescHandleSRV = CD3DX12_GPU_DESCRIPTOR_HANDLE(descHeap->GetGPUDescriptorHandleForHeapStart(), 0, descriptorHandleIncrementSize); D3D12_SHADER_RESOURCE_VIEW_DESC srvDesc{}; // 設定構造体 D3D12_RESOURCE_DESC resDesc = texbuff->GetDesc(); srvDesc.Format = resDesc.Format; srvDesc.Shader4ComponentMapping = D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING; srvDesc.ViewDimension = D3D12_SRV_DIMENSION_TEXTURE2D;//2Dテクスチャ srvDesc.Texture2D.MipLevels = 1; device->CreateShaderResourceView(texbuff.Get(), //ビューと関連付けるバッファ &srvDesc, //テクスチャ設定情報 cpuDescHandleSRV ); return true; } <file_sep>/Title.h #pragma once #include "BaseScene.h" #include "ISceneChanger.h" #include"Sprite.h" class Title: public BaseScene { private: Sprite* titlesprite1 = nullptr; WinApp* win = nullptr; public: Title(ISceneChanger* changer); void Initialize(DirectXCommon* dxCommon, Input* input, Audio* audio) override; //初期化処理をオーバーライド。 void Update() override; //更新処理をオーバーライド。 void Draw() override; //描画処理をオーバーライド。 };
f3a5713bb6f1d45ccf81e3cb1d2213f0938bdecd
[ "C++" ]
48
C++
haru4shi/game_
2104cb7718a09942680a19b06fcead388cf28f85
1e3834eb0c30a0647137eeee95f24e6820a9be58
refs/heads/master
<file_sep> class Cell(): def __init__(self, x, y): self.x = x self.y = y def __str__(self): return "Cell(%i,%i)" % (self.x, self.y) def set_neighbors(self, neighbors): self.neighbors = neighbors <file_sep>from cell import Cell class Grid: def __init__(self, width, height): self.width = width self.height = height self.size = width * height self.cells = [] self.build_cells() def build_cells(self): self.cells = [[] for x in range(self.width)] for x in range(self.width): self.cells[x] = [Cell(x,y) for y in range(self.height)] def assign_neighbors(self): for row in self.cells: for cell in row: neighbors = [] if self.in_grid(cell.x-3, cell.y): neighbors.append(self.cells[cell.x-3][cell.y]) if self.in_grid(cell.x+3, cell.y): neighbors.append(self.cells[cell.x+3][cell.y]) if self.in_grid(cell.x, cell.y+3): neighbors.append(self.cells[cell.x][cell.y+3]) if self.in_grid(cell.x, cell.y-3): neighbors.append(self.cells[cell.x][cell.y-3]) if self.in_grid(cell.x-2, cell.y-2): neighbors.append(self.cells[cell.x-2][cell.y-2]) if self.in_grid(cell.x-2, cell.y+2): neighbors.append(self.cells[cell.x-2][cell.y+2]) if self.in_grid(cell.x+2, cell.y-2): neighbors.append(self.cells[cell.x+2][cell.y-2]) if self.in_grid(cell.x+2, cell.y+2): neighbors.append(self.cells[cell.x+2][cell.y+2]) cell.set_neighbors(neighbors) def in_grid(self, x, y): return 0 <= x < self.width and 0 <= y < self.height def find_path(self): for cell in self.cells: path = [] unvisited = self.cells path.append(cell)
6f0c9ff0ca02b44ce6d10500f1786000be1154a7
[ "Python" ]
2
Python
ecahanin/riddler-solutions
fa70e5a8f695faf14622c87b78a6c27a3cdfcdad
c3f2b8209217372b51a98281e3a6c3b4fe3ef6c1
refs/heads/master
<file_sep>require 'test_helper' class MailboxHelperTest < ActionView::TestCase end <file_sep>source 'https://rubygems.org' gem 'rails', '4.1.6' gem 'sass-rails', '~> 4.0.3' gem 'uglifier', '>= 1.3.0' gem 'coffee-rails', '~> 4.0.0' gem 'jquery-rails' gem 'turbolinks' gem 'jbuilder', '~> 2.0' gem 'sdoc', '~> 0.4.0', group: :doc # Spring speeds up development by keeping your application running in the background. # Read more: https://github.com/rails/spring group :development do gem 'mysql2' gem 'spring' end gem 'bootstrap-sass' gem 'devise' gem 'mailboxer' gem 'chosen-rails' group :production do gem 'rails_12factor' end <file_sep>== README Simple rails app that demonstrates how to create a private messaging system. Feel free to clone this repo and if you have improvements, also feel free to submit a PR. You can read the tutorial at http://goo.gl/rVasxY == Thanks!
885b6cdb3e33432e1ae47d19ce6041158109d592
[ "RDoc", "Ruby" ]
3
Ruby
subhashsaran/rails-gmail-like-messaging-app
471ba0398daeccf197ba9164b5d05722dd0925c3
a8c70839e04a54a0f08da45b66ac56b6ae5c085e
refs/heads/master
<file_sep>using System; using TestingRandom; using Xunit; namespace TestingRandomTests { public class DiceRollerTests { private DiceRoller _sut; public DiceRollerTests() { _sut = new DiceRoller(new Randomizer()); } [Theory] [InlineData("fd6")] [InlineData("2df")] public void Roll_Throws_Format_Exception_For_Malformed_Input_String(string input) { void Act() => _sut.Roll(input); Assert.Throws<FormatException>(Act); } // TODO: Fix this test [Fact] public void Roll_Never_Out_Of_Range() { for (var i = 0; i < 100; i++) { var result = _sut.Roll("1d6"); if (result < 1 || 6 < result) { throw new Exception($"Result out of range: {result}"); } } } // TODO: Figure out a way to test making sure the dice roller gets random numbers the right number of times // TODO: rolling "2d6" should call the randomizer twice, and pass in 6 to IRandomizer.Next(int) } } <file_sep>namespace TestingRandom { public interface IRandomizer { int Next(int maximum); } } <file_sep># Testing / Mocks Practice I've got a `DiceRoller` class here that needs to be tested. I've got a partial test suite started in *TestingRandomTests/DiceRollerTests.cs*, but it's got some problems. `DiceRoller.Roll(string)` accepts an input string formatted like a Dungeons and Dragons dice roll. For example, *1d6* means roll a six-sided die one time, *2d8* means roll an eight-sided die twice, and so on. ## Task (1) `Roll_Never_Out_Of_Range` - Looping the action to test over and over is a pretty bad way of testing Roll. Figure out a better way to test and make sure it's never out of range. (2) Figure out how to test making sure that the `DiceRoller` calls into the `IRandomizer` the right number of times with the right argument. Don't change `DiceRoller` to make this happen. You are not limited in the mocking technique / library you use. <file_sep>using System; namespace TestingRandom { public class DiceRoller { private readonly IRandomizer _randomizer; public DiceRoller(IRandomizer randomizer) { _randomizer = randomizer; } public int Roll(string diceExpression) { var expressionParts = diceExpression.Split('d'); var dieCount = Convert.ToInt32(expressionParts[0]); var sideCount = Convert.ToInt32(expressionParts[1]); var sum = 0; for (var i = 0; i < dieCount; i++) { sum += _randomizer.Next(sideCount) + 1; } return sum; } } } <file_sep>using System; namespace TestingRandom { public class Randomizer : IRandomizer { private readonly Random _random = new Random(); public int Next(int maximum) { return _random.Next(maximum); } } }
d8c68433369bb6635c44930e3c6c98f809d32e10
[ "Markdown", "C#" ]
5
C#
jdphenix/testpractice-1
c941d31a9b2048ab3a76a4e78274fd8aa96f8085
db8f3071563d75a295ff2b93201f119b0fa3475c
refs/heads/master
<file_sep>package com.example.rpereira.recyclerview.utils; import android.support.annotation.NonNull; import android.support.v7.widget.RecyclerView; import android.view.View; import android.widget.TextView; import com.example.rpereira.recyclerview.R; public class CustomViewHolder extends RecyclerView.ViewHolder { final TextView mTitleList; final TextView mSubTitleList; public CustomViewHolder(@NonNull View itemView) { super(itemView); mTitleList = (TextView) itemView.findViewById(R.id.idtvTitleList); mSubTitleList = (TextView) itemView.findViewById(R.id.idtvSubTitleList); itemView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { } }); } }
bd0c5aada5e613ecc5a3e006a9ee222f494b0038
[ "Java" ]
1
Java
RogerPhilippe/RecyclerView
e043d6f6f66f37c2da3d8769fcec2c9b57bebd8e
a5ccb74f30fadba31c65050752a6516097ba69a8
refs/heads/master
<repo_name>dmb-220/Projektas_X<file_sep>/storage/framework/views/c5955c00d2e9fe00e549215288efe96bbbc2fb85.php <?php $__env->startSection('content'); ?> <div class="container-fluid"> <div class="content "> <div class="content"> <div class="row"> <div class="col-md-12"> <div class="input-group input-group-lg border"> <div class="input-group-prepend"> <button class="btn btn-danger" type="button"> <i class="fa fa-pencil-square-o"></i></button> </div> <input type="text" class="form-control" placeholder="" aria-label="" aria-describedby="basic-addon1"> <select class="custom-select" id="inputGroupSelect01"> <option selected>Choose...</option> <option value="1">One</option> <option value="2">Two</option> <option value="3">Three</option> </select> <div class="input-group-append"> <button class="btn btn-info" type="button"> <i class="fa fa-search"></i></button> </div> </div> </div> </div> </div> <!-- Page Content --> <div class="content"> <div class="row"> <!-- Row #3 --> <div class="col-md-4"> <div class="block"> <div class="block-content block-content-full"> <div class="py-20 text-center"> <div class="mb-20"> <i class="fa fa-envelope-open fa-4x text-primary"></i> </div> <div class="font-size-h4 font-w600">RANGOVAI</div> <div class="text-muted">Your main list is growing!</div> <div class="pt-20"> <a class="btn btn-rounded btn-alt-primary" href="javascript:void(0)"> <i class="fa fa-arrow-circle-o-right mr-5"></i> Žiūrėti </a> </div> </div> </div> </div> </div> <div class="col-md-4"> <div class="block"> <div class="block-content block-content-full"> <div class="py-20 text-center"> <div class="mb-20"> <i class="fa fa-twitter fa-4x text-info"></i> </div> <div class="font-size-h4 font-w600">UŽSAKOVAI</div> <div class="text-muted">You are doing great!</div> <div class="pt-20"> <a class="btn btn-rounded btn-alt-info" href="javascript:void(0)"> <i class="fa fa-arrow-circle-o-right mr-5"></i> Žiūrėti </a> </div> </div> </div> </div> </div> <div class="col-md-4"> <div class="block"> <div class="block-content block-content-full"> <div class="py-20 text-center"> <div class="mb-20"> <i class="fa fa-check fa-4x text-success"></i> </div> <div class="font-size-h4 font-w600">SKELBIMAI</div> <div class="text-muted">This is your current active plan</div> <div class="pt-20"> <a class="btn btn-rounded btn-alt-success" href="javascript:void(0)"> <i class="fa fa-arrow-circle-o-right mr-5"></i> Žiūrėti </a> </div> </div> </div> </div> </div> <!-- END Row #3 --> </div> <!-- END Page Content --> </div> <?php $__env->stopSection(); ?> <?php echo $__env->make('layouts.app', \Illuminate\Support\Arr::except(get_defined_vars(), ['__data', '__path']))->render(); ?><?php /**PATH C:\wamp64\www\Projektas_X\resources\views/home.blade.php ENDPATH**/ ?><file_sep>/resources/js/router.js import Vue from 'vue' import Router from 'vue-router' //import Pagrindinis from './views/Pagrindinis.vue' import HomeComponent from './components/HomeComponent.vue'; import Ideti_SkelbimaComponent from './components/Ideti_SkelbimaComponent.vue'; Vue.use(Router) export default new Router({ base: process.env.BASE_URL, routes: [ { path: '/', name: 'home', component: HomeComponent }, { name: 'ideti_skelbima', path: '/ideti_skelbima', component: Ideti_SkelbimaComponent }, ], }) <file_sep>/resources/js/app.js // Axios & Echo global require('./bootstrap'); /* Core */ import Vue from 'vue' import VueAxios from 'vue-axios'; import axios from 'axios'; Vue.use(VueAxios, axios); import BootstrapVue from 'bootstrap-vue' Vue.use(BootstrapVue) import 'bootstrap/dist/css/bootstrap.css' import 'bootstrap-vue/dist/bootstrap-vue.css' //import VueHtmlToPaper from 'vue-html-to-paper'; //const options = { //name: '_blank', //specs: [ // 'fullscreen=yes', //], //styles: [ // 'https://unpkg.com/buefy/dist/buefy.min.css', // 'http://app.test/css/print.css', // ] //} //Vue.use(VueHtmlToPaper, options); // or, using the defaults with no stylesheet //Vue.use(VueHtmlToPaper); /* Router & Store */ import router from './router' //import store from './store' /* Vue. Main component */ import App from './App.vue' Vue.config.productionTip = false /* Main component */ Vue.component('App', App) new Vue({ router, render: h => h(App), }).$mount('#app')
79a149e0c1dffad05ea6de5b8317618faf4c041a
[ "JavaScript", "PHP" ]
3
PHP
dmb-220/Projektas_X
18867912a9501331306463946940e9d595721882
e9e92b32197c3c07059df53916db9c4d63eb0c6e
refs/heads/master
<file_sep>'use strict'; /** * @param {Egg.Application} app - egg application */ module.exports = app => { const { router, controller } = app; router.get('/', controller.home.index); router.get('/user/login', 'home.login'); router.get('/getUrl', 'home.getUrl'); router.get('/dianping/getAlbum', controller.dianping.getAlbum); }; <file_sep>module.exports = app => { const mongoose = app.mongoose; const Schema = mongoose.Schema; const firstSchema = new Schema({ _id: { type: Schema.ObjectId }, name: { type: String }, age: { type: Number }, }); return mongoose.model('FirstModel', firstSchema, 'first'); };
1d6b7c24966fd687abc1ebf4c9eead499e68b3f9
[ "JavaScript" ]
2
JavaScript
lson-lee/node-server
62e6f7a5e5428302a40eb33ccca222d944c35c4a
bc1509883a7f48a46e3baa18bc62459fb299d055
refs/heads/master
<repo_name>cstamper6/cToolbox<file_sep>/src/ordNumLister.c /* C program to list ordinal numbers of given prompt */ #include <stdio.h> void main() { int x; char * ord[20] = {"1st", "2nd", "3rd", "4th", "5th", "6th", "7th", "8th", "9th", "10th", "11th", "12th", "13th", "14th", "15th", "16th", "17th", "18th", "19th", "20th"}; printf("Enter a number from 1 to 20:\n"); scanf("%i", &x); if (x < 1 || x > 20) { printf("Number is not in the range from 1 to 20\n"); return; } else { printf("Here are the first %i ordinal numbers:\n", x); for (int i = 0; i < x; i++) { printf("%s\n", ord[i]); } } } <file_sep>/src/matrixMult.c /* C program to multiply two MxM matrices */ #include <stdio.h> int A[10][10]; int B[10][10]; int C[10][10]; int main() { // scan in size of matrices int input; scanf("%i", &input); // store matrix values for (int i = 0; i < input; i++) { for (int j = 0; j < input; j++) { scanf("%i", &A[i][j]); } } for (int i = 0; i < input; i++) { for (int j = 0; j < input; j++) { scanf("%i", &B[i][j]); } } // Multiply matrix A with matrix B and store in C for (int i = 0; i < input; i++) { for (int j = 0; j < input; j++) { for (int k = 0; k < input; k++) { C[i][j] += A[i][k] * B[k][j]; } } } // print matrix C for (int i = 0; i < input; i++) { for (int j = 0; j < input; j++) { printf("%6d", C[i][j]); } printf("\n"); } } <file_sep>/src/rhymeSequencer.c /* C program to sequence rhymes into a story */ #include <stdio.h> #include <string.h> char animals[20][15]; char lyrics[20][60]; int number; void nurseryrhyme(int current) { printf("%*s", current, ""); // print "current" number of spaces if (current == 0) { printf("There was an old lady who swallowed a %s;\n", animals[0]); } else { printf("She swallowed the %s to catch the %s;\n", animals[current-1], animals[current]); } if(current < number-1) { nurseryrhyme(current+1); } else { current++; } if (strcmp(animals[current], "END\n") == 0) { for (int i = number - 1; i >= 0; i--) { printf("%*sI don't know why she swallowed a %s - %s", i, "", animals[i], lyrics[i]); } } } int main() { int i=0; while (1) { fgets(animals[i], 15, stdin); // reads the next animal name if (strcmp(animals[i], "END\n") == 0) { // if it is "END\n" - done reading break; } int length = strlen(animals[i]); animals[i][length - 1] = '\0'; // strips the newline at the end fgets(lyrics[i], 60, stdin); // reads the lyric corresponding to the animal i++; } number = i; nurseryrhyme(0); } <file_sep>/src/numFormatter.c /* * C program to format given input by value * Values may be decimal, hex, or octal */ #include <stdio.h> void main() { int input; int ints[6]; printf("Enter six integers:\n"); for (int i = 0; i < 6; i++) { scanf("%i", &input); ints[i] = input; } // prints header and first line of ints printf("1234567890bb1234567890\n%*i%*i\n", 10, ints[0], 12, ints[1]); // prints next two lines of ints printf("%*i%*i\n%*i%*i\n", 10, ints[2], 12, ints[3], 10, ints[4], 12, ints[5]); } <file_sep>/src/moddedText.c /* C program to mod the text of the prompted input */ #include <stdio.h> #include <string.h> #define MAX 1024 int main () { char buf[MAX], c; int len, length, i; do { // read a line fgets(buf, MAX, stdin); // calculate its length len = strlen(buf) -1; // -1 for \n // modify the line by switching characters if (len == 0) { //exit upon empty line break; } for (i=0; i<len; i++) { //iterates and checks each letter then prints c = buf[i]; if (c == 'e'|| c == 'E') { c = '3'; } if (c == 'i' || c == 'I') { c = '1'; } if (c == 'o' || c == 'O') { c = '0'; } if (c == 's' ||c == 'S') { c = '5'; } printf("%c", c); } printf("\n"); } while (len > 1); } <file_sep>/src/binPatternGen.c /* C program to generate all binary patterns of length of given input */ #include <stdio.h> int array[10]; int size; void binaryPattern(int array[], int n) { if (n > 0) { array[size - n] = 0; binaryPattern(array, n - 1); array[size - n] = 1; binaryPattern(array, n - 1); } else { for (int i = 0; i < size; i++) { printf("%u", array[i]); } printf("\n"); } } void main() { int n; scanf("%i", &n); size = n; binaryPattern(array, n); } <file_sep>/README.md # cToolbox A variety of programs written in C that accomplish specific mathematical and analytical tasks. COMP 411 - Computer Organization - Spring 2019 # What I Learned * Transferable knowledge of a mid-level, structured programming language * C's extendability and efficiency * Ability of datatypes and powerful operators <file_sep>/src/mazeSolver.c /* C program to solve a maze */ #include<stdio.h> #include<stdlib.h> #define true 1 #define false 0 #define MAX 100 int maze[100][100]; // 100x100 is the maximum size needed int wasHere[100][100]; int correctPath[100][100]; int width, height; int startX, startY, endX, endY; int recursiveSolve(int x, int y); int main() { int x, y; scanf("%d%d", &width, &height); scanf("\n"); // This is needed to "eat" the newline after height, // before the actual maze entries begin on the next line char tempchar; for(y=0; y < height; y++) { for(x=0; x < width; x++) { scanf("%c", &tempchar); maze[y][x]=tempchar; if (tempchar == 'S') { startX = x; startY = y; } else if (tempchar == 'F') { endX = x; endY = y; } wasHere[y][x] = 0; correctPath[y][x] = 0; } scanf("\n"); } recursiveSolve(startX, startY); // Code to print the output maze for (int i = 0; i < height; i++) { for (int j = 0; j < width; j++) { if (correctPath[i][j] == 1 && maze[i][j] != 'S') { maze[i][j] = '.'; } printf("%c", maze[i][j]); } printf("\n"); } } int recursiveSolve(int x, int y) { if (x == endX && y == endY) return 1; // If you reached the end if (maze[y][x] == '*' || wasHere[y][x]) return 0; // If you are on a wall or already were here wasHere[y][x] = 1; if (x != 0) // Checks if not on left edge if (recursiveSolve(x-1, y)) { // Calls method one to the left correctPath[y][x] = 1; // Sets that path value to true; return 1; } if (x != width - 1) // Checks if not on right edge if (recursiveSolve(x+1, y)) { // Calls method one to the right correctPath[y][x] = 1; return 1; } if (y != 0) // Checks if not on top edge if (recursiveSolve(x, y-1)) { // Calls method one up correctPath[y][x] = 1; return 1; } if (y != height - 1) // Checks if not on bottom edge if (recursiveSolve(x, y+1)) { // Calls method one down correctPath[y][x] = 1; return 1; } return 0; } <file_sep>/src/stringBubSort.c /* C program to bubble sort strings in array WITHOUT use of C string library functions */ #include <stdio.h> #include <string.h> #define NUM 25 /* number of strings */ #define LEN 1000 /* max length of each string */ int my_compare_strings(char string1[], char string2[]) { /* * -1 if string1 comes before string2 in alphabetical order * 0 if string1 is the same as string2 * +1 if string1 comes after string2 in alphabetical order */ int length; if (strlen(string1) > strlen(string2)) { length = strlen(string1); } else if (strlen(string2) > strlen(string1)) { length = strlen(string2); } else { length = strlen(string1); } for (int i = 0; i < length + 1; i++) { if (string1[i] == '\0' && string2[i] != '\0') { return -1; } else if (string2[i] == '\0' && string1[i] != '\0') { return 1; } else if (string1[i] < string2[i]) { return -1; } else if (string1[i] > string2[i]) { return 1; } } // if strings are the same return 0; } void my_swap_strings(char string1[], char string2[]) { char temp; // char variable used in swapping one character at a time int length; if (strlen(string1) > strlen(string2)) { length = strlen(string1); } else if (strlen(string2) > strlen(string1)) { length = strlen(string2); } else { length = strlen(string1); } for (int i = 0; i < length + 1; i++) { temp = string1[i]; string1[i] = string2[i]; string2[i] = temp; } } int main() { char Strings[NUM][LEN]; printf("Please enter %d strings, one per line:\n", NUM); for (int i = 0; i < NUM; i++) { fgets(Strings[i], LEN, stdin); } puts("\nHere are the strings in the order you entered:"); for (int i = 0; i < NUM; i++) { printf("%s", Strings[i]); } /* Bubble sort */ /* * my_compare_strings() to compare two strings * If they are out of order, my_swap_strings() to swap their contents */ for (int i = 0; i < NUM - 1; i++) { for (int j = 0; j < NUM - i - 1; j++) { if (my_compare_strings(Strings[j], Strings[j+1]) > 0) { my_swap_strings(Strings[j], Strings[j+1]); } } } /* Output sorted list */ puts("In alphabetical order, the strings are:"); for (int i = 0; i < NUM; i++) { printf("%s", Strings[i]); } } <file_sep>/src/triangularNum.c /* C program to determine if the input is a triangular number */ #include <stdio.h> #include <math.h> void main() { int input; int tRoot; int tRootInt; int tNumber; printf("Number ?\n"); scanf("%d", &input); tRoot = (sqrt(8*(input)+1)-1)/2; tRootInt = (int) tRoot; tNumber = (tRootInt*(tRootInt+1))/2; if (input == 0) { printf("Done\n"); return; } else if (input == tNumber) { printf("%d is a triangular number\n", input); main(); } else { printf("%d is not triangular, nearest triangular number below %d is %d\n", input, input, tNumber); main(); } } <file_sep>/src/fpNumbers.c /* C program to calculate various values of given input */ #include <stdio.h> void main() { double input; double sum = 0; double min = TMP_MAX; double max = -TMP_MAX; double product = 1; printf("Enter 10 floating-point numbers:\n"); for (int i = 0; i < 10; i++) { scanf("%lf", &input); sum += input; if (min > input) { min = input; } if (max < input) { max = input; } product *= input; } printf("Sum is %.5lf\nMin is %.5lf\nMax is %.5lf\nProduct is %.5lf\n", sum, min, max, product); } <file_sep>/src/matrixAdd.c /* C program to find the sum of two matrices represented by 2-D arrays */ #include <stdio.h> int main() { int A[3][3]; // matrix A int B[3][3]; // matrix B int C[3][3]; // matrix to store their sum int i,j; puts("Please enter 9 values for matrix A:"); for (i=0;i<3;i++) { //3 values for each row for (j=0;j<3;j++) { scanf("%d",&A[i][j]); //gets values for matrix a } } puts("Please enter 9 values for matrix B:"); for (i=0;i<3;i++) { //3 values for each row for (j=0;j<3;j++) { scanf("%d",&B[i][j]); //gets values for matrix b } } for (i=0;i<3;i++) { for (j=0;j<3;j++) { C[i][j]=A[i][j]+B[i][j]; //sums for matrix c } } puts("C = B + A ="); for (i=0;i<3;i++) { for (j=0;j<3;j++) { printf("%10d", C[i][j]); //prints 3 per line } printf("\n"); } } <file_sep>/src/collatzSequence.c /* C program to compute the Collatz sequence of given input */ #include <stdio.h> int main() { int n; puts("Please enter the starting number of the Collatz sequence:"); scanf("%d", &n); printf("%d", n); do { if (n == 1) { printf("1"); break; } else if (n%2 == 0) { n = n/2; } else { n = 3*n+1; } printf(", %d", n); } while (n > 1); printf("\n"); } <file_sep>/src/relaxedPalindrome.c /* * C program to determine if the prompted input is a palindrome * Disregards capitals, spaces, and punctuation */ #include <stdio.h> #include <string.h> #include <ctype.h> #define MAX 1000 int main() { char text[MAX], c; int i; // int ind, isPal; //isPal=0=false; isPal=1=true puts("Type some text (then ENTER):"); fgets(text, MAX, stdin); ind = strlen(text) - 2; // -1 for \n; -1 for 0 based index puts("Your input in reverse is:"); for (i=ind; i>=0; i--) { //index is 0 based printf("%c",text[i]); text[i] = tolower(text[i]); //changes chars to lowercase after print } printf("\n"); // for (i=len-1;i>= i = 0; while (ind >= 0) { //iterates backwards last char to first if (!isalpha(text[i])) { //skips char if not alpha; checks with the same j i++; } else if (!isalpha(text[ind])) { //skips char; checks with same i ind--; } else if (text[i] == text[ind]) { i++; //continues inwards to next char if match ind--; isPal = 1; //bool for print } else { isPal = 0; break; } } if (isPal == 1) { printf("Found a palindrome!\n"); } }
02b4cc5a4f8c263ea9a5734e17b1f96ed5505bcb
[ "Markdown", "C" ]
14
C
cstamper6/cToolbox
700b7f8850df52431ba2bcefa5d8d959d5fba112
41c85a8a11143bbf17e835ec5419f5f3580c0be2
refs/heads/master
<file_sep># BuildManagement A simple module to help auto increment build number in webpack projects. <file_sep>const fs = require('fs-extra'); const _ = require("lodash"); const moment = require('moment'); function incrementVersion(packageFileName, writeVersionToFile = true) { let packageFile = fs.readFileSync(packageFileName, "utf8"); if (!packageFile) return undefined; packageFile = JSON.parse(packageFile); let packageVersion = packageFile.version; let version = packageFile.build || {}; version.major = _.toString(packageVersion.split(".")[0]); version.minor = _.toString(packageVersion.split(".")[1]); version.revision = _.toString(packageVersion.split(".")[2]); version.build = _.padStart((_.toNumber(version.build) || 0) + 1, 4, "0"); version.year = _.toString(moment().format("YYYY")); version.month = _.toString(moment().format("MM")); version.day = _.toString(moment().format("DD")); version.hour = _.toString(moment().format("HH")); version.minute = _.toString(moment().format("mm")); version.second = _.toString(moment().format("ss")); version.date = _.toString(moment().valueOf()); packageFile.build = version; fs.writeFileSync(packageFileName, JSON.stringify(packageFile, null, 2), "utf8"); if (writeVersionToFile) fs.writeFileSync(packageFileName.replace("package.json", "version.json"), JSON.stringify(version, null, 2), "utf8"); return version; } function buildObjectToVersionString(buildObject) { return `${buildObject.major}.${buildObject.minor}.${buildObject.revision}.${buildObject.build} ${moment(buildObject.date).format("MMM DD YYYY HH:mm:ss")}`; } function addVersionScriptTagToIndex(indexFilename, versionString) { let indexFile = fs.readFileSync(indexFilename, "utf8"); if (indexFile) { if (indexFile.indexOf("const CURRENTVERSION") < 0) { indexFile = indexFile.replace(/<\/head>/, `<script>const CURRENTVERSION = "${versionString}";</script>${"\n"}</head>`); } else { indexFile = indexFile.replace(/<script>const CURRENTVERSION = (.*)?;<\/script>/, `<script>const CURRENTVERSION = "${versionString}";</script>`); } fs.writeFileSync(indexFilename, indexFile, "utf8"); } } function getVersion(packageFilename) { let packageFile = fs.readFileSync(packageFilename, "utf8"); if (!packageFile) return undefined; packageFile = JSON.parse(packageFile); return packageFile.build || {}; } function incrementRevisionNumber(packageFileName, writeVersionToFile = true) { let packageFile = fs.readFileSync(packageFileName, "utf8"); if (!packageFile) return undefined; packageFile = JSON.parse(packageFile); let packageVersion = packageFile.version; let version = packageFile.build || {}; version.major = _.toString(packageVersion.split(".")[0]); version.minor = _.toString(packageVersion.split(".")[1]); version.revision = _.toString(_.toNumber(_.toString(packageVersion.split(".")[2])) + 1); version.build = _.padStart((_.toNumber(version.build) || 0) + 1, 4, "0"); version.year = _.toString(moment().format("YYYY")); version.month = _.toString(moment().format("MM")); version.day = _.toString(moment().format("DD")); version.hour = _.toString(moment().format("HH")); version.minute = _.toString(moment().format("mm")); version.second = _.toString(moment().format("ss")); version.date = _.toString(moment().valueOf()); packageFile.version = `${version.major}.${version.minor}.${version.revision}`; packageFile.build = version; fs.writeFileSync(packageFileName, JSON.stringify(packageFile, null, 2), "utf8"); if (writeVersionToFile) fs.writeFileSync(packageFileName.replace("package.json", "version.json"), JSON.stringify(version, null, 2), "utf8"); return version; } module.exports = {incrementVersion, getVersion, buildObjectToVersionString, addVersionScriptTagToIndex, incrementRevisionNumber};
7774b09bc7470b073450d2efa23520d846f46a3b
[ "Markdown", "JavaScript" ]
2
Markdown
Mystify76/BuildManagement
21392aa52ba61a77c453f1353c450d387af059b6
3034997338e5ec821e6509537ade98d95a85da48
refs/heads/master
<file_sep>platform :ios, '8.0' target 'QingYue'do pod 'AFNetworking','~> 3.0.0’ pod 'SDWebImage’, ‘~> 3.7.3’ pod 'MJRefresh', '~> 2.4.12' pod 'Masonry', '~> 0.6.3' pod 'FMDB', '~> 2.5' pod 'JSONKit', '~> 1.5pre' pod 'MBProgressHUD', '~> 0.9.2' pod 'IQKeyboardManager', '~> 4.0.9' pod ‘SVProgressHUD’, ‘~> 2.1.2’ end <file_sep>// // Parameters.h // Yuncang // // Created by ChengxuZheng on 15/11/18. // Copyright © 2015年 ChengxuZheng. All rights reserved. // #ifndef Parameters_h #define Parameters_h #define MSSize_Bounds [UIScreen mainScreen].bounds #define MSSize_Width [UIScreen mainScreen].bounds.size.width #define MSSize_Height [UIScreen mainScreen].bounds.size.height #define kSVS_Width self.bounds.size.width #define kSVS_Height self.bounds.size.height #define kTB_Height 49 #define kNB_Height 64 #define WS(weakSelf) __weak __typeof(&*self)weakSelf = self; #define Font(R) [UIFont systemFontOfSize:R]; #define kSC_W (375.f/MSSize_Width) #define kSC_H (667.f/MSSize_Height) #define RGB(R,G,B,A) [UIColor colorWithRed:R/255.0f green:G/255.0f blue:B/255.0f alpha:A/1.0] #define MyRedColor [UIColor colorWithRed:244/255.0f green:68/255.0f blue:68/255.0f alpha:1/1.0] #define MyGrayColor [UIColor colorWithRed:240/255.0f green:241/255.0f blue:245/255.0f alpha:1/1.0] #endif /* Parameters_h */ <file_sep>// // Parameters.h // QingYue // // Created by leilei on 2017/3/26. // Copyright © 2017年 com.lanou.product_A. All rights reserved. // #ifndef Parameters_h #define Parameters_h /**适配宏 */ #define SUITABLE_WIDTH 375.0 * MSSize_Width #define SUITABLE_HEIGHT 667.0 * MSSize_Height #define MSSize_Bounds [UIScreen mainScreen].bounds #define MSSize_Width [UIScreen mainScreen].bounds.size.width #define MSSize_Height [UIScreen mainScreen].bounds.size.height #define kSVS_Width self.bounds.size.width #define kSVS_Height self.bounds.size.height #define kTB_Height 49 #define kNB_Height 64 #define WS(weakSelf) __weak __typeof(&*self)weakSelf = self; #define Font(R) [UIFont systemFontOfSize:R]; #define kSC_W (375.f/MSSize_Width) #define kSC_H (667.f/MSSize_Height) #define RGB(R,G,B,A) [UIColor colorWithRed:R/255.0f green:G/255.0f blue:B/255.0f alpha:A/1.0] #define MyRedColor [UIColor colorWithRed:244/255.0f green:68/255.0f blue:68/255.0f alpha:1/1.0] #define MyGrayColor [UIColor colorWithRed:240/255.0f green:241/255.0f blue:245/255.0f alpha:1/1.0] #define MyBlueColor [UIColor colorWithRed:19/255.0f green:139/255.0f blue:202/255.0f alpha:1/1.0] #define UIColorFromRGB(rgbValue) [UIColor colorWithRed:((float)((rgbValue & 0xFF0000) >> 16))/255.0 green:((float)((rgbValue & 0xFF00) >> 8))/255.0 blue:((float)(rgbValue & 0xFF))/255.0 alpha:1.0] #define MyGreenColor [UIColor colorWithRed:38/255.0f green:203/255.0f blue:100/255.0f alpha:1/1.0] #define kNumber @"0123456789\n" #define kPassWord @"<PASSWORD>" #define kWScale(R) (MSSize_Width/375.f)*R #define kHScale(R) (MSSize_Height/375.f)*R #define FFont(S) [UIFont systemFontOfSize:S] #define kWFont(S) (MSSize_Width>320)?(MSSize_Width>375?FFont(S*(414/375.f)):FFont(S*(375/375.f))):FFont(S*(320/375.f)) #define BFont(S) [UIFont boldSystemFontOfSize:S] #define kBFont(S) (MSSize_Width>320)?(MSSize_Width>375?BFont(S*(414/375.f)):BFont(S*(375/375.f))):BFont(S*(320/375.f)) #define AlertReqestFailureText @"网络请求失败,稍后重试" #define NetWorkingText @"努力加载中..." #define ISStringEqual(A,B) [A isEqualToString:B] #define kShowNet(S) [SVProgressHUD showWithStatus:S] #define kHideNet [SVProgressHUD dismiss] #define kTimeAfter(T,Block) dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(T * NSEC_PER_SEC)), dispatch_get_main_queue(), Block); #define kUserDefaults [NSUserDefaults standardUserDefaults] #endif /* Parameters_h */
1e625c660d79ca698c45383a8d791cc980166a4c
[ "C", "Ruby" ]
3
Ruby
chengxuzheng/QingYue
a62b770a7c2358d6f0e65b036621cba6e8f4cb7b
e7303f4fbe860066b503a51fb04dd1d7c043b0af
refs/heads/master
<file_sep>import { Component } from '@angular/core'; import { Platform, LoadingController } from 'ionic-angular'; import { HomePage } from '../pages/home/home'; import { IntroPage } from '../pages/intro/intro'; import { Storage } from '@ionic/storage'; @Component({ templateUrl: 'app.html' }) export class MyApp { rootPage: any = HomePage; loader: any; constructor(platform: Platform, public loadingCtrl: LoadingController, public storage: Storage) { this.presentLoading(); platform.ready().then(() => { this.storage.get('introShown').then((result) => { // if (false) { // this.rootPage = HomePage; // } else { this.rootPage = IntroPage; this.storage.set('introShown', true); // } this.loader.dismiss(); }); }); } private presentLoading() { this.loader = this.loadingCtrl.create({ content: 'Authenticating...', }); this.loader.present(); } } <file_sep>import { Component, ViewChild } from '@angular/core'; import { Content } from 'ionic-angular'; /** * Generated class for the AccountSelectorComponent component. * * See https://angular.io/api/core/Component for more info on Angular * Components. */ @Component({ selector: 'account-selector', templateUrl: 'account-selector.html' }) export class AccountSelectorComponent { items = [ '200000000012345600', '160000000012345600', '210000000012345600', '180000000012345600', '140000000012345600', ]; @ViewChild(Content) content: Content; constructor() { console.log('Hello AccountSelectorComponent Component'); } private itemSelected(item: string) { console.log("Selected Item", item); } }
d2ecce3a33f0142e542b19cf8362253bd45851b7
[ "TypeScript" ]
2
TypeScript
somi92/pig
7dbd1fb807f8725a0b2284bcced26462f4a2a1fc
b4031459a815d5ba1dbc73cb14e31a5177c27f66
refs/heads/master
<repo_name>SteBurz/python-selenium-web-scraper<file_sep>/README.md # python-selenium-web-scraper This repo is an example how a web scraper with python an selenium could look like. The program is: - get a title of a website - get a text of a HTML Element - perform a click event - input text into a field and - how to inject custom script. More can be watched here: https://youtu.be/Aum4-GRCzxc ## Install How to install pip: https://phoenixnap.com/kb/install-pip-windows Chrome Webdriver: https://sites.google.com/a/chromium.org/chromedriver/downloads Using selenium: https://selenium-python.readthedocs.io/ <file_sep>/scraper.py from selenium import webdriver DRIVER_PATH = 'C:\Program Files\chromedriver.exe' driver = webdriver.Chrome(executable_path=DRIVER_PATH) driver.get('example.com') websiteTitle = driver.title firstPost = driver.find_element_by_xpath('//*[@id="post-7"]/div/header/h2/a') if websiteTitle: print(websiteTitle) else: print("Couldn't get title") if firstPost.text: print(firstPost.text) firstPost.click() excerpt = driver.find_element_by_xpath('//*[@id="post-7"]/div/div/p[1]') if(excerpt.text): print(excerpt.text) commentTextField = driver.find_element_by_xpath('//*[@id="comment"]') commentNameField = driver.find_element_by_xpath('//*[@id="author"]') commentEmailField = driver.find_element_by_xpath('//*[@id="email"]') commentSubmitButton = driver.find_element_by_xpath('//*[@id="submit"]') commentTextField.send_keys("Some content here") commentNameField.send_keys("<NAME>") commentEmailField.send_keys("<EMAIL>") driver.execute_script("window.scrollTo(0, document.body.scrollHeight)") commentSubmitButton.click() else: print('Couldn\'t find excerpt for post.') else: print('Couldn\'t find first post') driver.quit()
fcb6ffa81ac1e6c21c30fcb2130378a3b7acfa14
[ "Markdown", "Python" ]
2
Markdown
SteBurz/python-selenium-web-scraper
c994b36ad9099568a8eee872122049fcd4b888aa
8262eeef52dcb72d5a7074d7167eb262f74197c6
refs/heads/main
<file_sep># KotlinCalculator Familiarizing myself with the basics of Kotlin by implementing a calculator <file_sep>package academy.learnprogramming.calculator 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 class MainActivity : AppCompatActivity() { //lateinit is used to subvert the null data type we would otherwise use to init the widgets in //the onCreate function. lateinit can only be used for vars private lateinit var result: EditText private lateinit var newNumber: EditText //or you can use lazy delegation, which can only be used for vals private val displayOperation by lazy(LazyThreadSafetyMode.NONE) { findViewById<TextView>(R.id.operation) } //Variables to hold our operands and calculation private var operand1: Double? = null private var operand2: Double = 0.0 private var pendingOperation = "" override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) result = findViewById(R.id.result) newNumber = findViewById(R.id.newNumber) //There are two different ways of assigning button widgets: val button0: Button = findViewById(R.id.button0) val button1: Button = findViewById(R.id.button1) val button2: Button = findViewById(R.id.button2) val button3: Button = findViewById(R.id.button3) val button4: Button = findViewById(R.id.button4) val button5: Button = findViewById(R.id.button5) val button6: Button = findViewById(R.id.button6) val button7: Button = findViewById(R.id.button7) val button8: Button = findViewById(R.id.button8) val button9: Button = findViewById(R.id.button9) val buttonDot: Button = findViewById(R.id.buttonDot) val buttonEquals = findViewById<Button>(R.id.buttonEquals) val buttonDivide = findViewById<Button>(R.id.buttonDivide) val buttonMultiply = findViewById<Button>(R.id.buttonMultiply) val buttonMinus = findViewById<Button>(R.id.buttonMinus) val buttonPlus = findViewById<Button>(R.id.buttonPlus) val listener = View.OnClickListener { v -> val b = v as Button //not all widgets have a text property so we need to specify the //widget we are getting the text from newNumber.append(b.text) } //Setting up buttons //Can optimize this by adding all buttons to an array and calling each button's //onClickListener. Should do this ESP if we are implementing a full keyboard /* button0.setOnClickListener(listener) button1.setOnClickListener(listener) button2.setOnClickListener(listener) button3.setOnClickListener(listener) button4.setOnClickListener(listener) button5.setOnClickListener(listener) button6.setOnClickListener(listener) button7.setOnClickListener(listener) button8.setOnClickListener(listener) button9.setOnClickListener(listener) buttonDot.setOnClickListener(listener) */ //Used listOf instead of arrayOf because list is immutable whereas an array is val valButtons = listOf(button0, button1, button2, button3, button4, button5, button6, button7, button8, button9, buttonDot) for (b in valButtons) b.setOnClickListener(listener) //Setup onClickListener for operation buttons val opListener = View.OnClickListener { v -> val op = (v as Button).text.toString() val value = newNumber.text.toString() if (value.isNotEmpty()) { //If value is not "" - change operation on calc performOperand(value, op) } //Regardless if value is "" or not, pendingOperation = op displayOperation.text = pendingOperation } val opButtons = listOf(buttonEquals, buttonDivide, buttonMultiply, buttonMinus, buttonPlus) for (op in opButtons) op.setOnClickListener(opListener) } private fun performOperand(value: String, operation: String) { if (operand1 == null) { //if we don't have a first number to do math on (ie. A), use the previous number //A [] B = C operand1 = value.toDouble() } else { //Otherwise, we do have A so we just need B, which will be the newNum just inserted operand2 = value.toDouble() if (pendingOperation == "=") { //update next operation pendingOperation = operation } when (operation) { "=" -> operand1 = operand2 "/" -> if (operand2 == 0.0) { operand1 = Double.NaN } else { operand1 = operand1!! / operand2 } "*" -> operand1 = operand1!! * operand2 "-" -> operand1 = operand1!! - operand2 "+" -> operand1 = operand1!! + operand2 } } result.setText(operand1.toString()) newNumber.setText("") } }
1b26250b7c6557407005b682be485ff177bb272d
[ "Markdown", "Kotlin" ]
2
Markdown
casychow/KotlinCalculator
3ae588fc9effbea8a6a8bab995bbddebc785a384
b3b13920ac5dd8bc9521e12db629ddc396c1c45d
refs/heads/master
<repo_name>sushantsenger7351/spychat<file_sep>/spy_details.py spy_name='Mr.Sushant' spy_age=21 spy_rating=5.7<file_sep>/main.py from spy_details import spy #importing spy dictionary from spy_details file from steganography.steganography import Steganography#importing Steganography module from steganography class of steganography library from datetime import datetime #importing datetime module from datetime class time=datetime.now()#now() function will return current date and time print time #printing returned current date and time. print'Hello buddy'#print hello buddy print'Let\'s get started' STATUS_MESSAGE=['Sleeping', 'Busy', 'Do not disturb']#list friends=[{'name': 'kumar','age': 22,'rating': 2.5,'is_online':True,'chats': []},{'name': 'verma','age':22,'rating':3.5,'is_online':True,'chats':[]}]#dictionary within a list def add_status(c_status): if c_status != None: #if nothing is chosen from status print "Your current status is "+ c_status else: print"You don't have any status currently.." existing_status = raw_input("You want to select from old status? Y/N") if existing_status.upper() == 'N': new_status=raw_input('Enter your status : ')#asking new status from user if len(new_status) > 0: #checking length of status STATUS_MESSAGE.append(new_status)#adding new status to list.. elif existing_status.upper()=='Y': serial_no=1 for old_status in STATUS_MESSAGE:#traversing the list print str(serial_no)+old_status serial_no=serial_no+1#increementing the value of serial no user_choice=input('Enter your choice :') new_status=STATUS_MESSAGE[user_choice-1] updated_status=new_status return updated_status def add_friend(): frnd= { 'name':'', 'age':0, 'rating':0.0, 'is_online':True, 'chats':[] } frnd['name']=raw_input('What is your name ?') frnd['age']=input('What is your age ?') frnd['rating']=input('What is your rating ?') frnd['is_online']=True if len(frnd['name'])>2 and 12<frnd['age']<50 and frnd['rating']>spy['rating'] : friends.append(frnd) else: print 'Friend cannot be added..' return len(friends) # will return to add_friend() def select_frnd(): serial_no=1 for frnd in friends:# traversing the dictionary friends to show the friends. print str(serial_no)+'.'+frnd['name'] serial_no=serial_no+1 user_selected_frnd=input('Enter your choice : ')#user choice user_selected_frnd_index=user_selected_frnd-1#index of the selected frnd return user_selected_frnd_index def send_message(): selected_frnd=select_frnd() original_image=raw_input('What is the name of your image ? ')#asking user about the name of image secret_text=raw_input('What is your secret text ? ') # asking about the secret text you want to save in image output_path="output.jpg" Steganography.encode(original_image,output_path,secret_text)#encoding the image with secret text.. print 'Your message has been successfully encoded..' new_chat={ #dictionary 'message':secret_text, 'time': datetime.now(), 'sent_by_me':True } friends[selected_frnd]['chats'].append(new_chat) #appending in friends list the new_chat dictionary print'Your secret message is ready.' def read_message(): selected_frnd=select_frnd() output_path=raw_input('Which image you want to decode ? ') secret_text=Steganography.decode(output_path) print 'Secret text is:'+ secret_text new_chat={ #dictionary... 'message':secret_text, 'time': datetime.now(), 'sent_by_me':False } friends[selected_frnd]['chats'].append(new_chat)#appending print'Your secret message has been saved...' def spy_chat(spy_name,spy_age,spy_rating): #defining the function print'Here are your options..'+spy_name current_status=None show_menu=True while show_menu: spy_choice=input('What do you want to do \n 1. Add a status. \n 2. Add a friend \n 3. Send a message \n 4. Read a message \n 0. exit') if spy_choice==1: current_status= add_status(current_status) print 'Updated status is '+ current_status elif spy_choice==2:#elif for multiple conditions. no_of_friends=add_friend() print 'You have '+ str(no_of_friends) +' friends.' elif spy_choice==3:#will send encoded message send_message() elif spy_choice==4:#will display the decoded message read_message() elif spy_choice==0: show_menu=False else: print'Invalid options..' spy_exist=raw_input('Are you a new user : Y/N')#asking whether you are new or not if spy_exist.upper()=='N':#when spy is an old one print'Welcome back '+spy['name']+' age :'+str(spy['age'])+' having rating of '+str(spy['rating']) spy_chat(spy['name'],spy['age'],spy['rating'])#calling function elif spy_exist.upper=='Y': spy={ #dictionary.. 'name':'', 'age': 0, 'rating':0.0 } spy['name']=raw_input('What is your spy_name? ')#take input from user print spy['name'] if len(spy['name'])>2:#checking the length of input print'Welcome '+spy['name'] +'.'#concatenating name with welcome. spy_salutation=raw_input('What should we call you Mr. or Ms. ')#input salutation from user if spy_salutation=='Mr.' or spy_salutation=='Ms.': spy['name']=spy_salutation+' '+spy['name']#concatenation print'Welcome '+spy['name'] +'. Glad to see you back..' print'Alright '+spy['name']+'. I would like to know a little bit more about you..' spy['age']=input('What is your age..?')#input from user if 12<spy['age']<50:#spy age should be between 12 to 50 print'Your age is correct....' spy['rating']=input('What is your rating..?')#input rating of spy if spy['rating']>5.0: print'Great spy..' elif 3.5<spy['rating']<=5.0: print'Average spy.' elif 2.5<spy['rating']<=3.5: print'Bad spy..' else: print'Who hired you...' spy_is_online=True#check if spy is online #str to concat string with integer/float.. print'Authentication is completed..Welcome '+ spy['name'] +'age: '+str(spy['age'])+ 'rating: '+str(spy['rating']) spy_chat(spy['name'],spy['age'],spy['rating'])#calling function spy_chat else: print'You are not eligible to be a spy....' else: print'Invalid salutation...' else: print 'Oops please enter a valid name..' else: print'Invalid entry...'
0d0eeb449b997b4edc084e2ebbdba039f7f8e06b
[ "Python" ]
2
Python
sushantsenger7351/spychat
b50276a59ed469360d14db7d59c3e037418754f5
8c8faf939e2004b89b1eda66d2e663ac93a29bed
refs/heads/master
<repo_name>vincezipparro/GoalPostApp-<file_sep>/GoalPostApp/GoalPostApp/Controller/GoalsVC.swift // // GoalsVC.swift // GoalPostApp // // Created by <NAME> on 12/21/17. // Copyright © 2017 <NAME>. All rights reserved. // import UIKit class GoalsVC: UIViewController { @IBOutlet weak var tableView: UITableView! override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. } @IBAction func addGoalButtonWasPressed(_ sender: Any) { print("button was pressed") } }
b51e807e26facc3cbea17a10bfb017476cef0078
[ "Swift" ]
1
Swift
vincezipparro/GoalPostApp-
c599c0010c7de24366f9dcf09dbe4629fd1397a9
96156c63989427bcd015d78389078183afa4d0bd
refs/heads/master
<repo_name>purocean/php-api-service<file_sep>/captcha/index.php <?php /** * 若快验证码人工打码接口 * post data=bas64. */ $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, 'http://api.ruokuai.com/create.json'); curl_setopt($ch, CURLOPT_HEADER, false); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_TIMEOUT, 65); curl_custom_postfields($ch, [ // 'username' => '填写你的用户名', // 'password' => '<PASSWORD>', 'typeid' => 3000, // 4位的字母数字混合码 类型表http://www.ruokuai.com/pricelist.aspx 'timeout' => 60, // 中文以及选择题类型需要设置更高的超时时间建议90以上 'softid' => 53089, 'softkey' => '1e3caa0b568b450ebd25e33526a7c294', ], [ // 'image' => file_get_contents('img.jpg'), 'image' => base64_decode($_POST['data']), ]); $result = curl_exec($ch); curl_close($ch); die($result); /** * For safe multipart POST request for PHP5.3 ~ PHP 5.4. * * @param resource $ch cURL resource * @param array $assoc "name => value" * @param array $files "name => path" * * @return bool * * @link http://php.net/manual/en/class.curlfile.php */ function curl_custom_postfields(&$ch, array $assoc = array(), array $files = array()) { // invalid characters for "name" and "filename" static $disallow = array("\0", '"', "\r", "\n"); // build normal parameters foreach ($assoc as $k => $v) { $k = str_replace($disallow, '_', $k); $body[] = implode("\r\n", array( "Content-Disposition: form-data; name=\"{$k}\"", '', filter_var($v), )); } // build file parameters foreach ($files as $k => $v) { $k = str_replace($disallow, '_', $k); $body[] = implode("\r\n", array( "Content-Disposition: form-data; name=\"{$k}\"; filename=\"{$k}\"", 'Content-Type: application/octet-stream', '', $v, )); } // generate safe boundary do { $boundary = '---------------------'.md5(mt_rand().microtime()); } while (preg_grep("/{$boundary}/", $body)); // add boundary for each parameters array_walk($body, function (&$part) use ($boundary) { $part = "--{$boundary}\r\n{$part}"; }); // add final boundary $body[] = "--{$boundary}--"; $body[] = ''; // die(implode("\r\n", $body)); // set options return curl_setopt_array($ch, array( CURLOPT_POST => true, CURLOPT_POSTFIELDS => implode("\r\n", $body), CURLOPT_HTTPHEADER => array( 'Expect: 100-continue', "Content-Type: multipart/form-data; boundary={$boundary}", // change Content-Type ), )); } <file_sep>/email/send2me.php <?php /** * 使用 SendCloud 向自己发送邮件 * * @param string $subject 邮件主题 * @param string $html 邮件正文 * * @return string 发送结果 */ function sendMail2Me($subject, $html) { $url = 'http://sendcloud.sohu.com/webapi/mail.send.json'; $apiUser = ''; $apiKey = ''; //不同于登录SendCloud站点的帐号,您需要登录后台创建发信子帐号,使用子帐号和密码才可以进行邮件的发送。 $param = [ 'api_user' => $apiUser, 'api_key' => $apiKey, 'from' => '<EMAIL>', 'fromname' => 'SendCloud测试邮件', 'to' => '', 'subject' => $subject, 'html' => $html, 'resp_email_id' => 'true' ]; $data = http_build_query($param); $options = [ 'http' => [ 'method' => 'POST', 'header' => 'Content-Type: application/x-www-form-urlencoded', 'content' => $data ] ]; $context = stream_context_create($options); $result = file_get_contents($url, false, $context); return $result; } echo sendMail2Me($_GET['subject'], $_GET['html']);
9abd8df2c09b058e195dbddf13315553f5b32e95
[ "PHP" ]
2
PHP
purocean/php-api-service
16c1a4f26e3dd241ce1aece18d89b6607a7ea5eb
d8a6f848146c17a603ac81007e3b4b7bd3bee4b4
refs/heads/master
<file_sep>/** * */ /** * @author mitul * */ package com.techartworks.userfederation;<file_sep>package com.techartworks.userfederation.storage; import org.jboss.logging.Logger; import org.keycloak.component.ComponentModel; import org.keycloak.models.*; import org.keycloak.storage.StorageId; import javax.ejb.*; import javax.persistence.EntityManager; import javax.persistence.PersistenceContext; import javax.persistence.TypedQuery; import java.util.*; import java.util.stream.Collectors; @Stateful(name="ejb/CustomUserFederationProvider", mappedName="ejb/CustomUserFederationProvider" ) @Local @TransactionManagement(TransactionManagementType.BEAN) public class CustomUserFederationProvider implements CustomUserFederationProviderLocal { private static final Logger log = Logger.getLogger(CustomUserFederationProvider.class); private static final String MOBILE = "mobile"; private static final String DATE_OF_BIRTH = "dateOfBirth"; private static final String FIRST_NAME = "firstName"; private static final String LAST_NAME = "lastName"; private static final String POST_CODE = "postCode"; @PersistenceContext(unitName = "user-storage-jpa") private transient EntityManager entityManager; private transient ComponentModel model; private transient KeycloakSession session; @Override public void preRemove(final RealmModel realm) { log.info("CustomUserFederationProvider.preRemove(RealmModel realm)"); } @Override public void preRemove(final RealmModel realm, final GroupModel group) { log.info("CustomUserFederationProvider.preRemove(RealmModel realm, GroupModel group)"); } @Override public void preRemove(final RealmModel realm, final RoleModel role) { log.info("CustomUserFederationProvider.preRemove(RealmModel realm, RoleModel role)"); } @Remove @Override public void close() { log.info("CustomUserFederationProvider.close()"); } @Override public UserModel getUserById(final String id, final RealmModel realm) { log.debug("getUserById: " + id); String persistenceId = StorageId.externalId(id); UserEntity entity = entityManager.find(UserEntity.class, persistenceId); if (null == entity) { log.info("could not find user by id: " + id); return null; } return new UserAdapter(session, realm, model, entity); } @Override public UserModel getUserByUsername(final String username, final RealmModel realm) { log.debug("getUserByUsername: " + username); TypedQuery<UserEntity> query = entityManager.createNamedQuery("UserEntity.findByUserInfo", UserEntity.class); query.setParameter(MOBILE, username); List<UserEntity> result = query.getResultList(); if (result.isEmpty()) { log.info("could not find username: " + username); return null; } return new UserAdapter(session, realm, model, result.get(0)); } @Override public UserModel getUserByEmail(final String email, final RealmModel realm) { log.debug("getUserByEmail(String " + email + ", RealmModel realm)"); return null; } @Override public int getUsersCount(final RealmModel realm) { log.info("getUsersCount(RealmModel realm)"); Object count = entityManager.createNamedQuery("UserEntity.getUserCount") .getSingleResult(); return ((Number)count).intValue(); } @Override public List<UserModel> getUsers(final RealmModel realm) { log.info("getUsers(RealmModel realm)"); return getUsers(realm, -1, -1); } @Override public List<UserModel> getUsers(final RealmModel realm, final int firstResult, final int maxResults) { log.info("getUsers(RealmModel realm, int firstResult, int maxResults)"); final TypedQuery<UserEntity> query = entityManager.createNamedQuery("UserEntity.getAllUsers", UserEntity.class); log.error("1. CustomUserFederationProvider: getAddUsers"); return getUserModels(realm, firstResult, maxResults, query); } private List<UserModel> getUserModels(final RealmModel realm, final int firstResult, final int maxResults, final TypedQuery<UserEntity> query) { log.info("getUserModels(RealmModel realm, int firstResult, int maxResults, TypedQuery<UserEntity> query)"); if (-1 != firstResult) { query.setFirstResult(firstResult); } if (-1 != maxResults) { query.setMaxResults(maxResults); } final List<UserEntity> results = query.getResultList(); log.info("2. CustomUserFederationProvider : getUserModels : " + results.size()); results.forEach(log::info); return results.stream() .map(entity -> new UserAdapter(session, realm, model, entity)) .collect(Collectors.toCollection(LinkedList::new)); } @Override public List<UserModel> searchForUser(final String search, final RealmModel realm) { log.info("searchForUser( " + search + ", RealmModel realm)"); return searchForUser(search, realm, -1, -1); } @Override public List<UserModel> searchForUser(final String search, final RealmModel realm, final int firstResult, final int maxResults) { log.info("searchForUser( " + search + ", RealmModel realm, "+ firstResult + ", "+ maxResults + ")"); final TypedQuery<UserEntity> query = entityManager.createNamedQuery("UserEntity.searchForUser", UserEntity.class); query.setParameter(MOBILE, search.toLowerCase(Locale.getDefault())); return getUserModels(realm, firstResult, maxResults, query); } @Override public List<UserModel> searchForUser(final Map<String, String> params, final RealmModel realm) { log.info("searchForUser(Map<String, String> params, RealmModel realm)"); params.forEach((s, s2) -> log.info("Key:" + s + " Value: " + s2)); return searchForUser(params, realm, -1, -1); } @Override public List<UserModel> searchForUser(final Map<String, String> params, final RealmModel realm, final int firstResult, final int maxResults) { log.debug("searchForUser(Map<String, String> " + params.toString() + ", RealmModel realm, int " + firstResult + ", int " + maxResults + ")"); TypedQuery<UserEntity> query; log.debug("Params Size: " + params.size()); if (params.keySet().containsAll(Set.of(FIRST_NAME, LAST_NAME, POST_CODE))) { log.debug("firstName "+ params.get(FIRST_NAME)); log.debug("lastName "+ params.get(LAST_NAME)); query = entityManager.createNamedQuery("UserEntity.firstTimeLoginSearch", UserEntity.class); query.setParameter(FIRST_NAME, params.get(FIRST_NAME)) .setParameter(LAST_NAME, params.get(LAST_NAME)); } else if (params.keySet().containsAll(Set.of(MOBILE, DATE_OF_BIRTH))) { log.debug("Mobile "+ params.get(MOBILE)); log.debug("Dob "+ params.get(DATE_OF_BIRTH)); query = entityManager.createNamedQuery("UserEntity.searchForUser", UserEntity.class); query.setParameter(MOBILE, params.get(MOBILE)) .setParameter(DATE_OF_BIRTH, params.get(DATE_OF_BIRTH)); } else { query = entityManager.createNamedQuery("UserEntity.getAllUsers", UserEntity.class); } return getUserModels(realm, firstResult, maxResults, query); } @Override public List<UserModel> getGroupMembers(final RealmModel realm, final GroupModel group, final int firstResult, final int maxResults) { log.info("getGroupMembers(realm, group, firstResult, maxResults)"); return Collections.emptyList(); } @Override public List<UserModel> getGroupMembers(final RealmModel realm, final GroupModel group) { log.info("getGroupMembers(realm, group)"); return Collections.emptyList(); } @Override public List<UserModel> searchForUserByUserAttribute(final String attrName, final String attrValue, final RealmModel realm) { log.debug("searchForUserByUserAttribute(" + attrName + ", " + attrValue + ", " + realm.getName() + ")"); TypedQuery<UserEntity> query = entityManager.createNamedQuery("UserEntity.searchForUser", UserEntity.class); query.setParameter(MOBILE, attrValue.toLowerCase(Locale.getDefault())); return getUserModels(realm, -1, -1, query); } @Override public void setModel(final ComponentModel model) { log.info("setModel"); this.model = model; } @Override public void setSession(final KeycloakSession session) { log.info("setSession"); this.session = session; } } <file_sep>package com.techartworks.userfederation; import org.keycloak.models.AuthenticatorConfigModel; import java.io.UnsupportedEncodingException; import java.net.URLEncoder; import java.nio.charset.StandardCharsets; public final class CustomKeycloakUtils { public static String getConfigString(final AuthenticatorConfigModel config, final String configName) { return config.getConfig().get(configName); } public static boolean getConfigBoolean(final AuthenticatorConfigModel config, final String configName) { return config.getConfig().get(configName) == null ? Boolean.FALSE : Boolean.valueOf(config.getConfig().get(configName)); } public static String encodeValue(String value) throws UnsupportedEncodingException { return URLEncoder.encode(value, StandardCharsets.UTF_8.toString()); } } <file_sep>package com.techartworks.userfederation.storage; import javax.persistence.*; import com.techartworks.userfederation.storage.converter.LocalDateAttributeConverter; import java.io.Serializable; @Entity @Table(name = "CUSTOMER_VERIFICATION") @NamedQueries({ @NamedQuery(name="UserEntity.getUserCount", query="select count(u) from UserEntity u"), @NamedQuery(name="UserEntity.searchForUser", query="select u from UserEntity u where u.mobile = :mobile and u.dateOfBirth = :dateOfBirth"), @NamedQuery(name="UserEntity.firstTimeLoginSearch", query="select u from UserEntity u where u.firstName = :firstName and u.lastName = :lastName"), @NamedQuery(name="UserEntity.findByUserInfo", query="select u from UserEntity u where u.mobile = :mobile"), @NamedQuery(name="UserEntity.getAllUsers", query="select u from UserEntity u") }) public class UserEntity implements Serializable { private static final long serialVersionUID = 5330847131505545734L; @Id @Column(name = "resource_id") private String resourceId; @Column(name = "last_name") private String lastName; @Column(name = "first_name") private String firstName; @Column(name = "date_of_birth", nullable = false) @Convert(converter = LocalDateAttributeConverter.class) private String dateOfBirth; @Column(name = "mobile", nullable = false) private String mobile; @Column(name = "online_admin_activation") private String onlineAdminActivation; public String getResourceId() { return resourceId; } public void setResourceId(final String resourceId) { this.resourceId = resourceId; } public String getLastName() { return lastName; } public void setLastName(final String lastName) { this.lastName = lastName; } public String getFirstName() { return firstName; } public void setFirstName(final String firstName) { this.firstName = firstName; } public String getOnlineAdminActivation() { return onlineAdminActivation; } public void setOnlineAdminActivation(final String onlineAdminActivation) { this.onlineAdminActivation = onlineAdminActivation; } public String getMobile() { return mobile; } public void setMobile(final String mobile) { this.mobile = mobile; } public String getDateOfBirth() { return dateOfBirth; } public void setDateOfBirth(String dateOfBirth) { this.dateOfBirth = dateOfBirth; } } <file_sep>package com.techartworks.userfederation; public class MobileAuthConstants { public static final String REDIRECT_URL = "redirect_url"; public static final String LOGIN_ASSISTANCE_URL = "Login_assistance_Url"; public static final String LOGIN_SYSTEM_ERROR = "Login_system_Error"; } <file_sep>package com.techartworks.userfederation.storage; import javax.persistence.*; import java.io.Serializable; @Entity @Table(name = "customer_address") public class UserPostcodeEntity implements Serializable { private static final long serialVersionUID = -7171051674364560600L; @Id private String id; @Column(name = "resource_id") private String customerId; @Column(name = "postcode") private String postCode; public String getCustomerId() { return customerId; } public void setCustomerId(final String customerId) { this.customerId = customerId; } public String getPostCode() { return postCode; } public void setPostCode(final String postCode) { this.postCode = postCode; } }
639123a7b8e41a473d92556bfdb1a40c9cb70f03
[ "Java" ]
6
Java
bhatnagarm/keycloak-custom-user-federation
075ceeb81859e6e704435fd211d15697dc7b13de
57fe5dd461dcfe80a31980eb218a60a57b806c6d
refs/heads/master
<repo_name>amp5/Hackbright_Day_6_Project_2<file_sep>/wordcount.py # put your code here. open_text = open('test.txt') def word_count(): unique_count = {} # initializing empty dictionary to keep track of each unique occurence of a word all_words = [] # initializing empty list of all of the words # unwanted_puncs = ['!', '?', ',', '.', '-', '--'] # punct we do not want for line in open_text: words_on_line = line.rstrip().replace(',', '').split(" ") # this works for getting rid of commas # possible list comprehension idea for getting rid of punctuation: # w for w in words_on_line if in unwanted_puncs... # we need to be testing the last char of string w in words_on_line #words_on_line_vrs_2 = line.rstrip(",") # pulling all the words out of a line and putting them in a list, assigned to variable for word in words_on_line: all_words.append(word) # this adds each word from the line list to the all_words list. # I wonder if there is any way to consolidate this idea with line.rstrip().split # like a list comprehension. append all words. + rstrip and split? if word not in unique_count: # this adds new words to the dictionary, ignoring duplicates unique_count[word] = 0 #d[key] = value, this is syntax for adding a key to a dictionary # print "Original Dictionary:" # print unique_count # the unique_count dictionary has been compiled by the above for loop! for word in all_words: # now go through all occurences of every word in text #if word in unique_count: # maybe don't need this -- every word is definitely in unique unique_count[word] += 1 # shorthand += for increasing a value by 1 # print "\nThis is the new dictionary with count:" for word in unique_count: print word, unique_count[word] # just for printng the list in the same way as the example output word_count()
fa68d5616a3fa639be0c8a4ea4e3c15ee1b48456
[ "Python" ]
1
Python
amp5/Hackbright_Day_6_Project_2
eaac7a52255fac0938b691adcdc18d87a6a587ac
10e10b0fdf4a7dc1eed0a8ebb2a5b294a86f438b
refs/heads/master
<repo_name>chensiyou123/security<file_sep>/README.md # security 权限认证学习 <file_sep>/spring-security-oauth2/spring-security-oauth2-server/src/main/java/com/csy/oauth2/service/TbUserService.java package com.csy.oauth2.service; import com.csy.oauth2.domain.TbUser; public interface TbUserService { default TbUser getByUsername(String username) { return null; } } <file_sep>/spring-security-oauth2/spring-security-oauth2-server/src/main/java/com/csy/oauth2/mapper/TbPermissionMapper.java package com.csy.oauth2.mapper; import com.csy.oauth2.domain.TbPermission; import org.apache.ibatis.annotations.Mapper; import org.apache.ibatis.annotations.Param; import java.util.List; import java.util.Map; @Mapper public interface TbPermissionMapper { List<TbPermission> query(Map map); } <file_sep>/spring-security-oauth2/spring-security-oauth2-server/src/main/java/com/csy/oauth2/service/impl/TbPermissionServiceImpl.java package com.csy.oauth2.service.impl; import com.csy.oauth2.domain.TbPermission; import com.csy.oauth2.mapper.TbPermissionMapper; import com.csy.oauth2.service.TbPermissionService; import org.springframework.stereotype.Service; import javax.annotation.Resource; import java.util.HashMap; import java.util.List; import java.util.Map; @Service public class TbPermissionServiceImpl implements TbPermissionService { @Resource private TbPermissionMapper tbPermissionMapper; @Override public List<TbPermission> selectByUserId(Long userId) { Map map = new HashMap(); map.put(userId,userId); return tbPermissionMapper.query(map); } }
24aca3a960b2be1da7a7d4c16ff8e9ee8cbfaeef
[ "Markdown", "Java" ]
4
Markdown
chensiyou123/security
75f0c1cdc34c05157b49b70a5255ee7be2de4d58
618df61591878a227540098c8c0ae80de7f2e5ce
refs/heads/main
<file_sep>let days = [ "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday" ]; let celTemp = null; let city = "Los Angeles"; let apiKey = "50ea266795ff34ae2a3920026adbb08c"; let apiUrl = `https://api.openweathermap.org/data/2.5/weather?q=${city}&appid=${apiKey}&units=metric`; axios.get(apiUrl).then(showTemperature); function formatDate(timestamp) { let date = new Date(timestamp); let hours = date.getHours(); if (hours < 10) { hours = `0${hours}`; } let minutes = date.getMinutes(); if (minutes < 10) { minutes = `0${minutes}`; } let day = date.getDay(); return `${days[day]} ${hours}:${minutes}`; } function showTemperature(response) { let currentDegree = document.querySelector("#current-degree"); let city = document.querySelector(".city"); let description = document.querySelector("#description"); let windSpeed = document.querySelector("#wind"); let humid = document.querySelector("#humidity"); let currentDate = document.querySelector(".date"); let icon = document.querySelector("#icon"); celTemp = response.data.main.temp; currentDegree.innerHTML = `${Math.round(celTemp)}°`; city.innerHTML = response.data.name; description.innerHTML = response.data.weather[0].description; windSpeed.innerHTML = Math.round(response.data.wind.speed); humid.innerHTML = response.data.main.humidity; currentDate.innerHTML = formatDate(response.data.dt * 1000); icon.setAttribute( "src", `http://openweathermap.org/img/wn/${response.data.weather[0].icon}@2x.png` ); icon.setAttribute("alt", response.data.weather[0].description); } function enterCity(event) { event.preventDefault(); let citySearch = document.querySelector("input"); let city = document.querySelector(".city"); city.innerHTML = citySearch.value; let citySearched = citySearch.value; let apiUrl = `https://api.openweathermap.org/data/2.5/weather?q=${citySearched}&appid=${apiKey}&units=metric`; axios.get(`${apiUrl}`).then(showTemperature); } let cityForm = document.querySelector("form"); cityForm.addEventListener("submit", enterCity); function degreeCel(event) { event.preventDefault(); let currentDegree = document.querySelector("#current-degree"); cel.classList.add("on"); fahr.classList.remove("on"); currentDegree.innerHTML = `${Math.round(celTemp)}°`; } let cel = document.querySelector("#celsius"); cel.addEventListener("click", degreeCel); function degreeFahr(event) { event.preventDefault(); let currentDegree = document.querySelector("#current-degree"); cel.classList.remove("on"); fahr.classList.add("on"); let conversionF = (celTemp * 9) / 5 + 32; currentDegree.innerHTML = `${Math.round(conversionF)}°`; } let fahr = document.querySelector("#fahrenheit"); fahr.addEventListener("click", degreeFahr);
41932c96d5fc978250edde7b4f43c0111cfe8226
[ "JavaScript" ]
1
JavaScript
laurenybarra/weatherApp
d14f04ffc3b5245f13582ef71baa93651b4bea54
6374c014b17bf33a2208b66285c596324a9a7a13
refs/heads/master
<file_sep>import asyncio import discord import random TOKEN = '<KEY>' client = discord.Client() insults = ["you stupid cunt", "fucking faggot", "dumb fucking retard", "neck yourself cunt", "grow a brain shithead", "jump off a cliff nibba"] @client.event async def on_message(message): if message.author == client.user: return if message.content.startswith(':insult'): args = message.content.split(" ") if len(args) > 1: msg = args[1] + " " + insults[random.randint(0, len(insults) - 1)] await client.send_message(message.channel, msg) else: msg = '{0.author.mention} '.format(message) + insults[random.randint(0, len(insults) - 1)] await client.send_message(message.channel, msg) if message.content.startswith(':ascii'): with open('ascii.png', 'rb') as picture: msg = 'julsberts ascii table {0.author.mention}'.format(message) await client.send_message(message.channel, msg) await client.send_file(message.channel, picture) if message.content.startswith(':blitz'): msg = 'https://blitzresearch.itch.io/blitzplus' await client.send_message(message.channel, msg) if message.content.startswith(':blitzplus'): msg = 'https://blitzresearch.itch.io/blitzplus' await client.send_message(message.channel, msg) if message.content.startswith(':devcpp'): msg = 'https://sourceforge.net/projects/orwelldevcpp/' await client.send_message(message.channel, msg) @client.event async def on_ready(): print('Logged in as') print(client.user.name) print(client.user.id) print('------') client.run(TOKEN)
2cd422bc00f75c499a4f0a8a6681681c1b1add04
[ "Python" ]
1
Python
theinventor13/ethylbot
913b598585dacb5846962f68ef3b398411c7a6de
609d2737a2d9da6613acc4b12b48eb53bd345164
refs/heads/master
<file_sep>--- layout: case caseId: 3e29cd10-3c3f-468e-98a0-0e2359aced9c title: How to approach the 'unremarkable' CXR in the FRCR 2B Viva speciality: [Chest] difficulty: Medium videoId: 327454857 videoUrl: https://vimeo.com/327454857 videoThumbnailLarge: https://i.vimeocdn.com/video/771727358_640.jpg videoThumbnailMedium: https://i.vimeocdn.com/video/771727358_200x150.jpg videoThumbnailSmall: https://i.vimeocdn.com/video/771727358_100x75.jpg author: <NAME> --- Examples of 'unremarkable' CXRs with pathology.<file_sep>--- layout: case caseId: 2147a3e8-cdd7-4227-96cf-c3f1ac5248df title: Pneumomediastinum speciality: [Chest] difficulty: Easy videoId: 278543553 videoUrl: https://vimeo.com/278543553 videoThumbnailLarge: https://i.vimeocdn.com/video/711591657_640.jpg videoThumbnailMedium: https://i.vimeocdn.com/video/711591657_200x150.jpg videoThumbnailSmall: https://i.vimeocdn.com/video/711591657_100x75.jpg author: <NAME> --- Explanation of the mechanism of pneumomediastinum<file_sep>--- layout: list speciality: Musculoskeletal difficulty: Easy --- <file_sep>--- layout: case caseId: 0bf022f5-6fe8-4583-b2bc-ba5bd2b0aa19 title: Pectus excavatum speciality: [Chest] difficulty: Easy videoId: 328814165 videoUrl: https://vimeo.com/328814165 videoThumbnailLarge: https://i.vimeocdn.com/video/773434114_640.jpg videoThumbnailMedium: https://i.vimeocdn.com/video/773434114_200x150.jpg videoThumbnailSmall: https://i.vimeocdn.com/video/773434114_100x75.jpg author: <NAME> --- The CXR appearances of pectus excavatum <file_sep>--- layout: case caseId: 5af1fa4c-c5d3-42a3-99c8-4d8629e9f1c3 title: Centrilobular Pathology on HRCT speciality: [Chest] difficulty: Medium videoId: 329064898 videoUrl: https://vimeo.com/329064898 videoThumbnailLarge: https://i.vimeocdn.com/video/773776436_640.jpg videoThumbnailMedium: https://i.vimeocdn.com/video/773776436_200x150.jpg videoThumbnailSmall: https://i.vimeocdn.com/video/773776436_100x75.jpg author: <NAME> --- Description of the secondary pulmonary lobule with examples of centrilobular nodules and centrilobular emphysema<file_sep>--- layout: case caseId: 47dee0f3-9ffe-4e5c-841a-86f1b1a01463 title: Non-traumatic brain haemorrhage speciality: [Neuro, Head & Neck] difficulty: Easy videoId: 280029277 videoUrl: https://vimeo.com/280029277 videoThumbnailLarge: https://i.vimeocdn.com/video/713397351_640.jpg videoThumbnailMedium: https://i.vimeocdn.com/video/713397351_200x150.jpg videoThumbnailSmall: https://i.vimeocdn.com/video/713397351_100x75.jpg author: <NAME> --- A video explaining patterns of extra-axial and intra-axial non-traumatic bleeds. You can also read about traumatic brain haemorrhage <a href="http://radiologymasters.com/cases/traumatic-brain-haemorrhage/">traumatic brain haemorrhage</a><file_sep>--- layout: page title: Admin Zone --- This area is intended for administrators and authors. #### How to login to the admin dashboard <span class="rm-red">Prerequisite: You already have an administrator account setup</span> 1. Navigate to the [Radiology Masters Admin Panel](https://radiologymasters.github.io/radiology-masters-admin/) 2. Login using your credentials or Google Account 3. The admin panel will load #### What can I do on the admin dashboard? Authorised users are able to complete the following tasks once authenticated * **Add new cases**<br> The case authoring engine will take care of uploading and converting videos, creating cases in the database and publishing them live to [Radiology Masters](https://radiologymasters.com) * **Update case**<br> Everything including the video file can be updated and will be synchronised and re-published to all sources automatically. * **Delete case**<br> Cases cannot be recovered once removed and all user data associated with a case will also be erased. This will take care of removing the video, all database entries and publication on the website.<file_sep>--- layout: case caseId: 0ea33fa9-6261-4523-bc7b-c374ec1b6176 title: Pseudosubarachnoid sign speciality: [Neuro, Head & Neck] difficulty: Easy videoId: 346743531 videoUrl: https://vimeo.com/346743531 videoThumbnailLarge: https://i.vimeocdn.com/video/796888726_640.jpg videoThumbnailMedium: https://i.vimeocdn.com/video/796888726_200x150.jpg videoThumbnailSmall: https://i.vimeocdn.com/video/796888726_100x75.jpg author: <NAME> --- The pseudosubarachnoid sign or pseudosubarachnoid haemorrhage sign is seen in patients with global anoxia. It is thought that the main reason for this sign is due to global loss of brain density secondary to hypoxia/anoxia. It can be differentiated from real subarachnoid haemorrhage due to the absence of high density in the cerebral sulci which is found with real subarachnoid haemorrhage.<file_sep>--- layout: case caseId: 669cd365-9cd0-4e0e-b8ef-62656c41725c title: Thalassaemia speciality: [Musculoskeletal] difficulty: Medium videoId: 317479533 videoUrl: https://vimeo.com/317479533 videoThumbnailLarge: https://i.vimeocdn.com/video/759703219_640.jpg videoThumbnailMedium: https://i.vimeocdn.com/video/759703219_200x150.jpg videoThumbnailSmall: https://i.vimeocdn.com/video/759703219_100x75.jpg author: <NAME> --- Theory regarding hair-on-end and thinning of the outer table<file_sep>--- layout: case caseId: 29e7f834-60a1-4629-a64c-d59539531809 title: Left Upper Lobe Collapse speciality: [Chest] difficulty: Easy videoId: 343309513 videoUrl: https://vimeo.com/343309513 videoThumbnailLarge: https://i.vimeocdn.com/video/792421765_640.jpg videoThumbnailMedium: https://i.vimeocdn.com/video/792421765_200x150.jpg videoThumbnailSmall: https://i.vimeocdn.com/video/792421765_100x75.jpg author: <NAME> --- The CXR and CT findings of Left Upper Lobe Collapse. As most presentations of lobar collapse are due to neoplasia, it is vitally imporant to search the film for evidence of disease spread e.g. bony structures.<file_sep>--- layout: case caseId: 6376b3d0-32cb-458f-bf59-af6fadd65b9f title: Pulmonary hamartoma speciality: [Chest] difficulty: Easy videoId: 338892362 videoUrl: https://vimeo.com/338892362 videoThumbnailLarge: https://i.vimeocdn.com/video/786770808_640.jpg videoThumbnailMedium: https://i.vimeocdn.com/video/786770808_200x150.jpg videoThumbnailSmall: https://i.vimeocdn.com/video/786770808_100x75.jpg author: <NAME> --- Fat-containing pulmonary nodules are almost always benign. Pixel densitometry is used to detect fat not immediately obvious visually. Hamartomas contain fat, calcification (usually popcorn) and soft tissue and are usually well- defined.<file_sep>--- layout: case caseId: a09453ec-e0e8-4fc9-ad6e-ad35602f1759 title: Left Lower Lobe Collapse speciality: [Chest] difficulty: Easy videoId: 346604629 videoUrl: https://vimeo.com/346604629 videoThumbnailLarge: https://i.vimeocdn.com/video/796679353_640.jpg videoThumbnailMedium: https://i.vimeocdn.com/video/796679353_200x150.jpg videoThumbnailSmall: https://i.vimeocdn.com/video/796679353_100x75.jpg author: <NAME> --- The radiological appearances of LLL collapse.<file_sep>--- layout: case caseId: 96981c26-395e-423a-b6a7-ff359fd8d2de title: Traumatic brain haemorrhage speciality: [Neuro, Head & Neck] difficulty: Easy videoId: 280029368 videoUrl: https://vimeo.com/280029368 videoThumbnailLarge: https://i.vimeocdn.com/video/713397464_640.jpg videoThumbnailMedium: https://i.vimeocdn.com/video/713397464_200x150.jpg videoThumbnailSmall: https://i.vimeocdn.com/video/713397464_100x75.jpg author: <NAME> --- A video explaining the main types of traumatic intracranial bleeds.<file_sep>--- layout: case caseId: a0ba7c89-5bf5-4375-9e8d-465e2421f131 title: Incomplete border sign speciality: [Chest] difficulty: Easy videoId: 341211074 videoUrl: https://vimeo.com/341211074 videoThumbnailLarge: https://i.vimeocdn.com/video/789760762_640.jpg videoThumbnailMedium: https://i.vimeocdn.com/video/789760762_200x150.jpg videoThumbnailSmall: https://i.vimeocdn.com/video/789760762_100x75.jpg author: <NAME> --- The incomplete border sign on a chest radiograph is important since it usually denotes a non-pulmonary lesion - either arising from the pleural or extrapleural spaces. A mediastinal mass effectively produces the incomplete border sign also.<file_sep>--- layout: case caseId: b4f180a7-98c3-4b2c-8ee6-c100e0136b0d title: The Cervicothoracic Sign speciality: [Chest] difficulty: Medium videoId: 328809664 videoUrl: https://vimeo.com/328809664 videoThumbnailLarge: https://i.vimeocdn.com/video/773428561_640.jpg videoThumbnailMedium: https://i.vimeocdn.com/video/773428561_200x150.jpg videoThumbnailSmall: https://i.vimeocdn.com/video/773428561_100x75.jpg author: <NAME> --- The cervicothoracic sign is very useful in working out the location of a superior mediastinal mass<file_sep>--- layout: list speciality: Genitourinary title: Genitourinary --- <file_sep>--- layout: case caseId: 53500e0f-28d5-4be1-aa05-5969545d0828 title: Approach to the FRCR 2B viva exam speciality: [Exam Tips] difficulty: Easy videoId: 312968087 videoUrl: https://vimeo.com/312968087 videoThumbnailLarge: https://i.vimeocdn.com/video/754162076_640.jpg videoThumbnailMedium: https://i.vimeocdn.com/video/754162076_200x150.jpg videoThumbnailSmall: https://i.vimeocdn.com/video/754162076_100x75.jpg author: <NAME> --- General tips on how to approach the FRCR 2b viva examination, including 3 example case presentations. <file_sep>--- layout: case caseId: 1dfc1be6-e340-4907-91f3-bfc6076f7b4e title: Right Lower Lobe Collapse speciality: [Chest] difficulty: Easy videoId: 345221696 videoUrl: https://vimeo.com/345221696 videoThumbnailLarge: https://i.vimeocdn.com/video/794931740_640.jpg videoThumbnailMedium: https://i.vimeocdn.com/video/794931740_200x150.jpg videoThumbnailSmall: https://i.vimeocdn.com/video/794931740_100x75.jpg author: <NAME> --- The radiological appearances of RLL collapse.<file_sep>--- layout: case caseId: c1139e30-57f7-4e1d-8ae3-32d16c7b3503 title: Apical Cap speciality: [Chest] difficulty: Easy videoId: 328810836 videoUrl: https://vimeo.com/328810836 videoThumbnailLarge: https://i.vimeocdn.com/video/773430003_640.jpg videoThumbnailMedium: https://i.vimeocdn.com/video/773430003_200x150.jpg videoThumbnailSmall: https://i.vimeocdn.com/video/773430003_100x75.jpg author: <NAME> --- What is the apical cap and why does it appear as it does on a CXR?<file_sep>--- layout: case caseId: d264a5ab-9a53-4004-a805-dd4632d30a9d title: The continuous diaphragm sign speciality: [Chest] difficulty: Easy videoId: 317797431 videoUrl: https://vimeo.com/317797431 videoThumbnailLarge: https://i.vimeocdn.com/video/760076715_640.jpg videoThumbnailMedium: https://i.vimeocdn.com/video/760076715_200x150.jpg videoThumbnailSmall: https://i.vimeocdn.com/video/760076715_100x75.jpg author: <NAME> --- The 'continuous diaphragm' sign is a sign of pneumomediastinum. This video explains its appearance and significance.<file_sep>--- layout: case caseId: 8884c08e-1fc3-4009-97bf-a9cb5e00b77c title: Midgut volvulus speciality: [Gastrointestinal] difficulty: Medium videoId: 252411078 videoUrl: https://vimeo.com/252411078 videoThumbnailLarge: https://i.vimeocdn.com/video/679039973_640.jpg videoThumbnailMedium: https://i.vimeocdn.com/video/679039973_200x150.jpg videoThumbnailSmall: https://i.vimeocdn.com/video/679039973_100x75.jpg author: <NAME> --- Midgut volvulus<p>Sound Edited in ScreenFlow - all that I did was apply a single click "Smooth Audio Levels" which Normalized the volume<br></p><file_sep>--- layout: case caseId: 4015227f-fc7c-40f9-9987-7b9cd59891e5 title: Location of bone lesions in children and adults - silent movie speciality: [Musculoskeletal] difficulty: Easy videoId: 328970710 videoUrl: https://vimeo.com/328970710 videoThumbnailLarge: https://i.vimeocdn.com/video/773644086_640.jpg videoThumbnailMedium: https://i.vimeocdn.com/video/773644086_200x150.jpg videoThumbnailSmall: https://i.vimeocdn.com/video/773644086_100x75.jpg author: <NAME> --- In this silent movie, there is description of the location of bone lesions in children and adults<file_sep>--- layout: case caseId: 496b43b6-85e8-4b79-b3c8-291f9c087d9b title: Hilum overlay sign speciality: [Chest] difficulty: Easy videoId: 346690236 videoUrl: https://vimeo.com/346690236 videoThumbnailLarge: https://i.vimeocdn.com/video/796815021_640.jpg videoThumbnailMedium: https://i.vimeocdn.com/video/796815021_200x150.jpg videoThumbnailSmall: https://i.vimeocdn.com/video/796815021_100x75.jpg author: <NAME> --- The hilum overlay sign is an appearance on chest radiographs whereby the margins of the hilar vessels can be seen at the level of a mass in the lung or mediastinum. In order to be able to see hilar structures, the mass cannot be located in the middle mediastinum. Therefore the presence of the hilum overlay sign tells us that the mass is arising from the anterior or posterior mediastinum. The ability to see the heart border separate from the mass is seen with posterior mediastinal masses and obscuration of the heart border places the lesion in the anterior mediastinum.<file_sep>--- layout: case caseId: 7fbf4728-9230-4b4c-9fdc-8c66c6cfc7c2 title: Lipohaemarthrosis speciality: [Musculoskeletal] difficulty: Easy videoId: 319448665 videoUrl: https://vimeo.com/319448665 videoThumbnailLarge: https://i.vimeocdn.com/video/762010340_640.jpg videoThumbnailMedium: https://i.vimeocdn.com/video/762010340_200x150.jpg videoThumbnailSmall: https://i.vimeocdn.com/video/762010340_100x75.jpg author: <NAME> --- X Ray and CT description of lipohaemarthrosis - fat layering over blood within the joint<file_sep>--- layout: case caseId: bfa17b04-dd88-4c3b-91ba-a79c6b7de0c1 title: Cavitating lung lesions speciality: [Chest] difficulty: Medium videoId: 280955866 videoUrl: https://vimeo.com/280955866 videoThumbnailLarge: https://i.vimeocdn.com/video/714574569_640.jpg videoThumbnailMedium: https://i.vimeocdn.com/video/714574569_200x150.jpg videoThumbnailSmall: https://i.vimeocdn.com/video/714574569_100x75.jpg author: <NAME> --- The pertinent causes of cavitating lung lesions in a nutshell.<file_sep>--- layout: case caseId: 66242848-7735-4c6b-8536-28d6f89994ac title: Epiploic appendagitis speciality: [Gastrointestinal] difficulty: Easy videoId: 329060452 videoUrl: https://vimeo.com/329060452 videoThumbnailLarge: https://i.vimeocdn.com/video/773770144_640.jpg videoThumbnailMedium: https://i.vimeocdn.com/video/773770144_200x150.jpg videoThumbnailSmall: https://i.vimeocdn.com/video/773770144_100x75.jpg author: <NAME> --- A CT description of epiploic appendagitis<file_sep>--- layout: case caseId: c3b541c5-a5e3-4bf6-894e-7fd24af9847e title: Approaching the CXR 'from the end of the bed' speciality: [Chest] difficulty: Medium videoId: 328510546 videoUrl: https://vimeo.com/328510546 videoThumbnailLarge: https://i.vimeocdn.com/video/773051264_640.jpg videoThumbnailMedium: https://i.vimeocdn.com/video/773051264_200x150.jpg videoThumbnailSmall: https://i.vimeocdn.com/video/773051264_100x75.jpg author: <NAME> --- You will get much more information than you think by looking at the CXR as if looking at the patient 'from the end of the bed'.<file_sep>--- layout: case caseId: d6aed45a-31af-40a7-ab3d-068a6f766c33 title: Pulmonary vs bony vs skin lesions speciality: [Chest] difficulty: Medium videoId: 320211385 videoUrl: https://vimeo.com/320211385 videoThumbnailLarge: https://i.vimeocdn.com/video/762611062_640.jpg videoThumbnailMedium: https://i.vimeocdn.com/video/762611062_200x150.jpg videoThumbnailSmall: https://i.vimeocdn.com/video/762611062_100x75.jpg author: <NAME> --- How to work out where the lesion is that is projected on a CXR<file_sep>--- layout: case caseId: 6c9581c9-ceda-495f-a503-c4c1a3a93e37 title: Cytotoxic vs Vasogenic cerebral oedema speciality: [Neuro, Head & Neck] difficulty: Easy videoId: 346620961 videoUrl: https://vimeo.com/346620961 videoThumbnailLarge: https://i.vimeocdn.com/video/796727960_640.jpg videoThumbnailMedium: https://i.vimeocdn.com/video/796727960_200x150.jpg videoThumbnailSmall: https://i.vimeocdn.com/video/796727960_100x75.jpg author: <NAME> --- Learn how to differentiate cytotoxic and vasogenic oedema<file_sep>--- layout: case caseId: 8e532e2b-6be1-4203-9bca-9e90318a17c4 title: Common paediatric fracture patterns speciality: [Paediatric] difficulty: Easy videoId: 347166156 videoUrl: https://vimeo.com/347166156 videoThumbnailLarge: https://i.vimeocdn.com/video/797416793_640.jpg videoThumbnailMedium: https://i.vimeocdn.com/video/797416793_200x150.jpg videoThumbnailSmall: https://i.vimeocdn.com/video/797416793_100x75.jpg author: <NAME> --- Learn about the common types of fracture patterns which are specific to paediatric population.<file_sep>--- layout: case caseId: 98bdd8a1-ec91-4193-8480-e66fded59bc6 title: Obturator hernia speciality: [Gastrointestinal] difficulty: Medium videoId: 318587580 videoUrl: https://vimeo.com/318587580 videoThumbnailLarge: https://i.vimeocdn.com/video/760971944_640.jpg videoThumbnailMedium: https://i.vimeocdn.com/video/760971944_200x150.jpg videoThumbnailSmall: https://i.vimeocdn.com/video/760971944_100x75.jpg author: <NAME> --- Radiological and clinical description of an obturator hernia<file_sep>--- layout: author name: <NAME> description: Musculoskeletal Radiologist picture: --- Sed porttitor lectus nibh. Curabitur aliquet quam id dui posuere blandit. Praesent sapien massa, convallis a pellentesque nec, egestas non nisi. Proin eget tortor risus. Quisque velit nisi, pretium ut lacinia in, elementum id enim. Proin eget tortor risus. Vestibulum ac diam sit amet quam vehicula elementum sed sit amet dui. Curabitur non nulla sit amet nisl tempus convallis quis ac lectus. Sed porttitor lectus nibh. Curabitur aliquet quam id dui posuere blandit. Praesent sapien massa, convallis a pellentesque nec, egestas non nisi. Proin eget tortor risus. Quisque velit nisi, pretium ut lacinia in, elementum id enim. Proin eget tortor risus. Vestibulum ac diam sit amet quam vehicula elementum sed sit amet dui. Curabitur non nulla sit amet nisl tempus convallis quis ac lectus. <file_sep>--- layout: case caseId: 9e139b24-ca03-41cd-86e9-0e69cd9fcc78 title: Diffuse cystic lung disease speciality: [Chest] difficulty: Medium videoId: 323777613 videoUrl: https://vimeo.com/323777613 videoThumbnailLarge: https://i.vimeocdn.com/video/766958474_640.jpg videoThumbnailMedium: https://i.vimeocdn.com/video/766958474_200x150.jpg videoThumbnailSmall: https://i.vimeocdn.com/video/766958474_100x75.jpg author: <NAME> --- Learn the differentials for diffuse cystic lung disease<file_sep>---\r\n layout: case\r\n caseId: RadiologyMasters.Authoring.ValueObjects.CaseId\r\n title: Title\r\n speciality: [Cardiology\r\n difficulty: hard\r\n videoId: 3333\r\n videoUrl: /videos/3333\r\n videoThumbnailLarge: \r\n videoThumbnailMedium: \r\n videoThumbnailSmall: http://somesite/thumbnails/test.png\r\n author: <NAME>\r\n ---\r\n\r\n Description<file_sep>--- layout: case caseId: 80aa3d95-ddeb-4900-956f-e80cf101a64c title: Falciform ligament visibility in pneumoperitoneum speciality: [Gastrointestinal] difficulty: Easy videoId: 341685234 videoUrl: https://vimeo.com/341685234 videoThumbnailLarge: https://i.vimeocdn.com/video/790368210_640.jpg videoThumbnailMedium: https://i.vimeocdn.com/video/790368210_200x150.jpg videoThumbnailSmall: https://i.vimeocdn.com/video/790368210_100x75.jpg author: <NAME> --- This video attempts to explain why the falciform ligament is more likely to be visible in cases of childhood pneumoperitoneum compared with adults.<file_sep>$.fn.relatedCases = function(options) { var _self = this; var _user = null; var _settings = $.extend({ caseId: "", speciality: "", maxRelatedCases: 4 }, options); $(document).on("user-loaded", handleUserLoaded); $(document).on("user-unauthenticated", handleUserUnautheticated); var _container = $(this); function handleUserLoaded(e, user) { _user = user; console.log("LOADING RELATED CASES...", _settings.speciality); loadRelatedCases() .then(filterCases) .then(displayRelatedCases) .catch(handleError); } function handleUserUnautheticated() { _user = null; _self.hide(); } function isCaseSameSpeciality(caseInfo, speciality) { if (!caseInfo.speciality || caseInfo.speciality.length == 0) { return false; } var isSameSpeciality = caseInfo.speciality.indexOf(speciality) > -1; console.log("CASE '" + caseInfo.caseId + "' IS SAME SPECIALITY: " + isSameSpeciality, caseInfo); return isSameSpeciality; } function hasUserCompletedCase(caseId, user) { if (!user.completedCases || user.completedCases.length == 0) { return false; } var hasCompletedCase = false; for(var i = 0; i < user.completedCases.length; i++) { var completedCaseId = user.completedCases[i]; hasCompletedCase = completedCaseId == caseId; } console.log("USER HAS COMPLETED CASE '" + caseId + "': " + hasCompletedCase, user); return hasCompletedCase; } function loadRelatedCases(speciality, user) { var promise = new Promise(function(resolve, reject) { if (!_settings.caseId) { throw new Error("The case id must not be null"); } firebase .database() .ref("/cases/") .once("value") .then(function(caseRecords) { var cases = caseRecords.val(); resolve(cases); }); }); return promise; } function filterCases(cases) { var promise = new Promise(function(resolve, reject) { var filteredCases = []; console.log("ALL CASES", cases); for (var caseKey in cases) { var caseInfo = cases[caseKey]; var isSameSpeciality = isCaseSameSpeciality(caseInfo, _settings.speciality); var hasCompleted = hasUserCompletedCase(caseInfo.caseId, _user); if (isSameSpeciality && !hasCompleted) { filteredCases.push(caseInfo); } } resolve(filteredCases); }); return promise; } function displayRelatedCases(cases) { var promise = new Promise(function(resolve, reject) { console.log("RELATED CASES", cases); for(var i = 0; i < cases.length; i++) { if (i == _settings.maxRelatedCases) { break; } var caseInfo = cases[i]; var li = $("<li/>", { "class": "case" }); var h4 = $("<h4/>", { text: caseInfo.title }); var img = $("<img/>", { src: "http://apeg.com/apeg-dev/wp-content/themes/apeg-new/images/default_video_thumb.png" }); var article = $("<article/>", { "class": "fl w-100 w-50-m w-25-ns pa2-ns" }); var a = $("<a/>", { href: "/cases/" + caseInfo.title, "class": "ph2 ph0-ns pb3 link db dim" }); var d1 = $("<div/>", { "class": "z-0 aspect-ratio aspect-ratio--16x9 cover bg-center", style: "background-image:url(http://mrmrs.github.io/images/0006.jpg);" }); var d2 = $("<div/>"); var s1 = $("<span/>", { "class": "absolute left-1 top-1 f7 dib pa1 br1 w-auto white", text: caseInfo.complexity }); var s2 = $("<span/>", { "class": "absolute right-1 top-1 f7 dib pa1 br1 w-auto bg-blue white", text: caseInfo.createdByUserFullName }); var d3 = $("<div/>", { "class": "ph1" }); var h3 = $("<h3/>", { "class": "f5 mb0 pa1 br1 black-80", text: caseInfo.title }); d2.append(s1, s2); d1.append(d2); d3.append(h3); a.append(d1, d3); article.append(a); _container.append(article); } resolve(cases); }); return promise; } function handleError(error) { console.error(error); } }; <file_sep>--- layout: case caseId: c499d5a0-eae2-483f-8dcc-8eb19150507b title: Gout speciality: [Musculoskeletal] difficulty: Easy videoId: 317934210 videoUrl: https://vimeo.com/317934210 videoThumbnailLarge: https://i.vimeocdn.com/video/760223130_640.jpg videoThumbnailMedium: https://i.vimeocdn.com/video/760223130_200x150.jpg videoThumbnailSmall: https://i.vimeocdn.com/video/760223130_100x75.jpg author: <NAME> --- This provides a description of the plain film manifestations of gout, affecting the musculo-skeletal system<file_sep>--- layout: case caseId: bdd4b19b-2d28-4fe3-9204-307569025446 title: Positive interventricular septum sign speciality: [Chest, Cardiovascular] difficulty: Easy videoId: 397775301 videoUrl: https://vimeo.com/397775301 videoThumbnailLarge: https://i.vimeocdn.com/video/865132907_640.jpg videoThumbnailMedium: https://i.vimeocdn.com/video/865132907_200x150.jpg videoThumbnailSmall: https://i.vimeocdn.com/video/865132907_100x75.jpg author: <NAME> --- In unenhanced CT, a positive interventricular septum sign is a sign of anaemia<file_sep>--- layout: case caseId: 6bdc8c90-ecbe-434a-9940-112c18d549c9 title: Osteoid Osteoma speciality: [Musculoskeletal, Exam Tips] difficulty: Easy videoId: 285196054 videoUrl: https://vimeo.com/285196054 videoThumbnailLarge: https://i.vimeocdn.com/video/719818551_640.jpg videoThumbnailMedium: https://i.vimeocdn.com/video/719818551_200x150.jpg videoThumbnailSmall: https://i.vimeocdn.com/video/719818551_100x75.jpg author: <NAME> --- Osteoid osteomas are benign bone lesions with classic characteristics on plain film, MRI and CT. They are also a very common exam case and are worth rehearsing in a slick way.<file_sep>--- layout: list speciality: Paediatric title: Paediatric ---<file_sep>--- layout: case caseId: feb00c58-7622-4f0c-8f8b-fa20f834619d title: Shoulder dislocation speciality: [Musculoskeletal] difficulty: Easy videoId: 346608449 videoUrl: https://vimeo.com/346608449 videoThumbnailLarge: https://i.vimeocdn.com/video/796693029_640.jpg videoThumbnailMedium: https://i.vimeocdn.com/video/796693029_200x150.jpg videoThumbnailSmall: https://i.vimeocdn.com/video/796693029_100x75.jpg author: <NAME> --- Learn about the different types of shoulder dislocation.<file_sep>--- layout: list speciality: Musculoskeletal title: Musculoskeletal --- <file_sep>--- layout: case caseId: 338dda07-3969-49f4-a8db-f9905163dcec title: Proximal femoral fractures speciality: [Musculoskeletal] difficulty: Easy videoId: 342581305 videoUrl: https://vimeo.com/342581305 videoThumbnailLarge: https://i.vimeocdn.com/video/791494693_640.jpg videoThumbnailMedium: https://i.vimeocdn.com/video/791494693_200x150.jpg videoThumbnailSmall: https://i.vimeocdn.com/video/791494693_100x75.jpg author: <NAME> --- This video emphasises the importance of understanding the arterial anatomy of the femoral neck and head in determining which fracture is likely to lead to avascular necrosis of the femoral head<file_sep>--- layout: case caseId: 36e04bac-b02a-4c3c-9975-0b479d43745b title: Intra vs extra axial brain lesions speciality: [Neuro, Head & Neck] difficulty: Easy videoId: 346547563 videoUrl: https://vimeo.com/346547563 videoThumbnailLarge: https://i.vimeocdn.com/video/796627832_640.jpg videoThumbnailMedium: https://i.vimeocdn.com/video/796627832_200x150.jpg videoThumbnailSmall: https://i.vimeocdn.com/video/796627832_100x75.jpg author: <NAME> --- Basic rules to tell the difference between an intra and extra axial brain lesion<file_sep>--- layout: case caseId: b6d59311-ae4c-4925-832a-6b427d9fa199 title: Making Video Tutorials with Screenflow speciality: [] difficulty: Easy videoId: 252332660 videoUrl: https://vimeo.com/252332660 videoThumbnailLarge: https://i.vimeocdn.com/video/678937706_640.jpg videoThumbnailMedium: https://i.vimeocdn.com/video/678937706_200x150.jpg videoThumbnailSmall: https://i.vimeocdn.com/video/678937706_100x75.jpg author: Radiology Masters --- <p>I prefer making tutorials using my desktop mac due to the ergonomics and ease of availability of assets. I find it frustrating having to import images to my iPad to work with Explain Everything.</p><p>I made this short video to show some of the ways of working.</p><p>I'm using the following kit</p><p><ul><li>Screenflow screen recording software</li><li>WACOM Intuos Draw graphics tablet</li><li>Ink2go screen annotation software</li><li>Samson Go USB Microphone</li></ul></p><file_sep>--- layout: list speciality: Chest title: Chest --- <file_sep>--- layout: case caseId: b4748212-57b4-4b12-bcd4-5fa6daa8b9d0 title: Urinary bladder rupture speciality: [Genitourinary] difficulty: Medium videoId: 322662427 videoUrl: https://vimeo.com/322662427 videoThumbnailLarge: https://i.vimeocdn.com/video/765611530_640.jpg videoThumbnailMedium: https://i.vimeocdn.com/video/765611530_200x150.jpg videoThumbnailSmall: https://i.vimeocdn.com/video/765611530_100x75.jpg author: <NAME> --- Features of extra and intraperitoneal bladder rupture<file_sep>--- layout: list speciality: Gastrointestinal title: Gastrointestinal --- <file_sep>--- layout: case caseId: c03cc820-eb8b-402d-b30e-c3d99d347df2 title: Blowout Fractures of the Orbit speciality: [Neuro, Head & Neck] difficulty: Medium videoId: 285112297 videoUrl: https://vimeo.com/285112297 videoThumbnailLarge: https://i.vimeocdn.com/video/719712286_640.jpg videoThumbnailMedium: https://i.vimeocdn.com/video/719712286_200x150.jpg videoThumbnailSmall: https://i.vimeocdn.com/video/719712286_100x75.jpg author: <NAME> --- A blowout fracture is a fracture through the orbital floor usually caused by a punch injury to the eye. It is best assessed using CT scans (more so than plain film) so that the in depth anatomy of the orbit can be assessed to ensure that there is not herniation of the inferior rectus muscle and entrapment. In this video, the relevant injury anatomy, plain film and CT scans are assessed<file_sep>--- layout: case caseId: 8f2be8c0-74b9-4f4e-a721-4123791ae30f title: Tension Pneumothorax speciality: [Chest] difficulty: Medium videoId: 342532229 videoUrl: https://vimeo.com/342532229 videoThumbnailLarge: https://i.vimeocdn.com/video/791434884_640.jpg videoThumbnailMedium: https://i.vimeocdn.com/video/791434884_200x150.jpg videoThumbnailSmall: https://i.vimeocdn.com/video/791434884_100x75.jpg author: <NAME> --- It is often said that a tension pneumothorax should be diagnosed clinically without the need for a CXR. But what defines a 'tension' pneumothorax by imaging criteria? This video will explain.<file_sep>--- layout: case caseId: a43da92a-5773-476d-a2d1-867ed79ad807 title: Heart Failure speciality: [Chest] difficulty: Easy videoId: 342586893 videoUrl: https://vimeo.com/342586893 videoThumbnailLarge: https://i.vimeocdn.com/video/791501272_640.jpg videoThumbnailMedium: https://i.vimeocdn.com/video/791501272_200x150.jpg videoThumbnailSmall: https://i.vimeocdn.com/video/791501272_100x75.jpg author: <NAME> --- The CXR (and CT) appearances of heart failure<file_sep>--- layout: case caseId: 3ddb9dc6-b031-4bd0-9108-6d0c9a816ec1 title: Supine Pneumothorax speciality: [Chest] difficulty: Medium videoId: 341597584 videoUrl: https://vimeo.com/341597584 videoThumbnailLarge: https://i.vimeocdn.com/video/790254495_640.jpg videoThumbnailMedium: https://i.vimeocdn.com/video/790254495_200x150.jpg videoThumbnailSmall: https://i.vimeocdn.com/video/790254495_100x75.jpg author: <NAME> --- A pneumothorax locates in the apical region on an erect CXR. The lung edge is often seen along with absence of vascular markings over the pleural space. On a supine CXR, a pneumothorax is more subtle and locates over the base of the chest producing the so-called 'deep sulcus sign'. This video explains how to detect pneumothoraces on supine films. <file_sep>--- layout: case caseId: 6dbc20d5-87ea-4013-b05d-96df36e8b06e title: Siding the diaphragm on the lateral CXR speciality: [Chest] difficulty: Easy videoId: 328953793 videoUrl: https://vimeo.com/328953793 videoThumbnailLarge: https://i.vimeocdn.com/video/773621559_640.jpg videoThumbnailMedium: https://i.vimeocdn.com/video/773621559_200x150.jpg videoThumbnailSmall: https://i.vimeocdn.com/video/773621559_100x75.jpg author: <NAME> --- Video showing how you can side the diaphragm on the lateral CXR<file_sep>--- layout: case caseId: 3f81dcad-aa3c-4528-ab03-396d59f582be title: Scaphoid fracture speciality: [Musculoskeletal] difficulty: Easy videoId: 342474049 videoUrl: https://vimeo.com/342474049 videoThumbnailLarge: https://i.vimeocdn.com/video/791361795_640.jpg videoThumbnailMedium: https://i.vimeocdn.com/video/791361795_200x150.jpg videoThumbnailSmall: https://i.vimeocdn.com/video/791361795_100x75.jpg author: <NAME> --- Radiological description of scaphoid fracture with vascular anatomical considerations that determine the development of avascular necrosis as a significant complication<file_sep>--- layout: case caseId: ce826ba6-a417-4009-b100-a4ab001199d2 title: Pericardial and cardiac calcification (not including coronary artery calcification) speciality: [Chest] difficulty: Easy videoId: 343197390 videoUrl: https://vimeo.com/343197390 videoThumbnailLarge: https://i.vimeocdn.com/video/792280387_640.jpg videoThumbnailMedium: https://i.vimeocdn.com/video/792280387_200x150.jpg videoThumbnailSmall: https://i.vimeocdn.com/video/792280387_100x75.jpg author: <NAME> --- Pictorial description of cardiac and pericardial calcification<file_sep>--- layout: page title: Welcome to Radiology Masters --- <h2 class="fw2">A new type of online radiology tutorial</h2> ### Why another radiology tutorial site? **We might be late to the party with online radiology tutorials, there are tons out there. But what we are offering is a little different.** Watching a 45-minute long video might help some of you learn, but we find that bite sized video tutorials each 5-minutes long on specialist topics hits the sweet spot for more people. We are trying to replicate that unique and personalised experience you get when a good boss takes you aside and imparts a short burst of knowledge and wisdom. That might be during a mock viva exam session or it might be during a normal day in the radiology reporting room. What we do know is that right now this experience has not been recreated online! ### Is it really free? Yes, for now we just want to build up a library of great content and get it out there. We want to see how people use this resource and from that we can adapt and improve the site. In the future we have plans for some premium content mostly aimed to help you pass your boards and FRCR radiology exams. ### Who is behind Radiology Masters? The idea was developed by Dr <NAME> and Dr <NAME> and soon after Dr <NAME> joined the team. <file_sep>--- layout: list speciality: "Exam Tips" title: FRCR Exam Tips ---<file_sep>--- layout: case caseId: 7ecca929-fe07-45e6-a32f-b6c594e80b22 title: Hypertransradiant Lung Field speciality: [Chest] difficulty: Medium videoId: 347201550 videoUrl: https://vimeo.com/347201550 videoThumbnailLarge: https://i.vimeocdn.com/video/797463849_640.jpg videoThumbnailMedium: https://i.vimeocdn.com/video/797463849_200x150.jpg videoThumbnailSmall: https://i.vimeocdn.com/video/797463849_100x75.jpg author: <NAME> --- This video will explain how to work out whether a hypertransradiant lung field is due to pulmonary or chest wall/pleural pathology, showing the key case examples.<file_sep>--- layout: list speciality: Breast title: Breast ---<file_sep>--- layout: case caseId: d00587eb-8f81-4669-a66a-ed336808591b title: Normal Variants - CHEST speciality: [Chest] difficulty: Easy videoId: 345333622 videoUrl: https://vimeo.com/345333622 videoThumbnailLarge: https://i.vimeocdn.com/video/795074459_640.jpg videoThumbnailMedium: https://i.vimeocdn.com/video/795074459_200x150.jpg videoThumbnailSmall: https://i.vimeocdn.com/video/795074459_100x75.jpg author: <NAME> --- Aberrant right subclavian artery, azygos lobe and left sided SVC are described. Please note at 04.08 the description of the azygos fissure should state that there are 4 pleural layers - 2 visceral and 2 parietal.<file_sep>--- layout: list speciality: Neuro title: Neuro ---<file_sep>--- layout: case caseId: cfa2d736-f2f4-4cec-a313-b6417e6b0490 title: The Bulging Fissure Sign speciality: [Chest] difficulty: Easy videoId: 345176419 videoUrl: https://vimeo.com/345176419 videoThumbnailLarge: https://i.vimeocdn.com/video/794875703_640.jpg videoThumbnailMedium: https://i.vimeocdn.com/video/794875703_200x150.jpg videoThumbnailSmall: https://i.vimeocdn.com/video/794875703_100x75.jpg author: <NAME> --- The bulging fissure sign is usually seen in the RUL in cases of lobar pneumonia, although not exclusively in this lobe. Thick exudative secretions lead to lobar expansion and result in bulging of the fissure. Other causes to consider are any 'space-occupying' lesion such as cancer, abscess or haematoma.<file_sep>--- layout: list speciality: "Head & Neck" title: Head & Neck ---<file_sep>--- layout: case caseId: 98d3d6e4-27b5-4668-8dc8-8caf140540ec title: Rigler's sign speciality: [Gastrointestinal] difficulty: Easy videoId: 278540084 videoUrl: https://vimeo.com/278540084 videoThumbnailLarge: https://i.vimeocdn.com/video/711587156_640.jpg videoThumbnailMedium: https://i.vimeocdn.com/video/711587156_200x150.jpg videoThumbnailSmall: https://i.vimeocdn.com/video/711587156_100x75.jpg author: <NAME> --- Rigler's sign of pneumoperitoneum<file_sep>--- layout: case caseId: ac11b31c-9be9-45ed-bade-816e2f4a6955 title: Carpal bone fractures speciality: [Musculoskeletal] difficulty: Easy videoId: 280029827 videoUrl: https://vimeo.com/280029827 videoThumbnailLarge: https://i.vimeocdn.com/video/713398053_640.jpg videoThumbnailMedium: https://i.vimeocdn.com/video/713398053_200x150.jpg videoThumbnailSmall: https://i.vimeocdn.com/video/713398053_100x75.jpg author: <NAME> --- A video demonstrating the common carpal bone fractures.<file_sep>--- layout: case caseId: c06d3057-63b1-4d00-a736-02c889678f7f title: Rt middle lobe collapse speciality: [Chest] difficulty: Easy videoId: 328619747 videoUrl: https://vimeo.com/328619747 videoThumbnailLarge: https://i.vimeocdn.com/video/773187810_640.jpg videoThumbnailMedium: https://i.vimeocdn.com/video/773187810_200x150.jpg videoThumbnailSmall: https://i.vimeocdn.com/video/773187810_100x75.jpg author: <NAME> --- Rt middle lobe collapse on CXR - PA and Lat<file_sep>--- layout: case caseId: 6215a3c8-d6f6-4ee9-a4d2-3a2b9e30ad79 title: Caecal and sigmoid volvulus speciality: [Gastrointestinal] difficulty: Easy videoId: 280029558 videoUrl: https://vimeo.com/280029558 videoThumbnailLarge: https://i.vimeocdn.com/video/713397707_640.jpg videoThumbnailMedium: https://i.vimeocdn.com/video/713397707_200x150.jpg videoThumbnailSmall: https://i.vimeocdn.com/video/713397707_100x75.jpg author: <NAME> --- A video explaining the main features of both caecal and sigmoid volvulus.<file_sep>--- layout: case caseId: a410bfce-fcb9-4147-bc58-1a005e486f2b title: Elbow effusion speciality: [Musculoskeletal] difficulty: Easy videoId: 278566863 videoUrl: https://vimeo.com/278566863 videoThumbnailLarge: https://i.vimeocdn.com/video/711621167_640.jpg videoThumbnailMedium: https://i.vimeocdn.com/video/711621167_200x150.jpg videoThumbnailSmall: https://i.vimeocdn.com/video/711621167_100x75.jpg author: <NAME> --- how an elbow effusion is seen on a plain film
618e98e5b8bffb35952de7011cd3c38f69e21e40
[ "Markdown", "JavaScript" ]
68
Markdown
radiologymasters/radiology-masters
a73c5461d6e00fa124125963a2e928af0eb3bdc5
1feba1aa02d536e21132437cd83e65bf1f6dae96
refs/heads/master
<file_sep>include ':app', ':flexyStepIndicator' <file_sep>package com.akexorcist.library.flexystepindicator; import android.annotation.TargetApi; import android.content.Context; import android.content.res.TypedArray; import android.graphics.Bitmap; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Matrix; import android.graphics.Paint; import android.graphics.drawable.BitmapDrawable; import android.graphics.drawable.Drawable; import android.os.Build; import android.os.Parcel; import android.os.Parcelable; import android.util.AttributeSet; import android.util.TypedValue; import android.view.Gravity; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.FrameLayout; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.TextView; import java.util.ArrayList; import java.util.List; /** * Created by Akexorcist on 9/28/2016 AD. */ @SuppressWarnings({"unused", "DefaultFileTemplate"}) public class FlexyStepIndicator extends LinearLayout implements View.OnClickListener { private static final int DEFAULT_COLOR = Color.parseColor("#DDDDDD"); private List<Integer> descriptionResIdList; private List<String> descriptionStringList; private int currentIndex = -1; private int descriptionTextColor; private int descriptionTextSize; private int numberBackgroundResId; private int numberTextSize; private int numberTextColor; private int numberSize; private int doneIconResId; private int doneBackgroundResId; private int lineActiveColor; private int lineInactiveColor; private int lineHeight; private int lineLength; private int lineDashCount; private boolean isStepClickable; private List<StepProperty> stepPropertyList; private StepClickListener stepClickListener; public FlexyStepIndicator(Context context, AttributeSet attrs) { super(context, attrs); setup(attrs); } public FlexyStepIndicator(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); setup(attrs); } @TargetApi(Build.VERSION_CODES.LOLLIPOP) public FlexyStepIndicator(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) { super(context, attrs, defStyleAttr, defStyleRes); setup(attrs); } private void setup(AttributeSet attrs) { setOrientation(LinearLayout.HORIZONTAL); setGravity(Gravity.CENTER_VERTICAL); setupStyleable(attrs); setupThing(); } private void setupStyleable(AttributeSet attrs) { TypedArray typedArray = getContext().obtainStyledAttributes(attrs, R.styleable.FlexyStepIndicator); descriptionTextColor = typedArray.getResourceId(R.styleable.FlexyStepIndicator_flexy_descriptionTextColor, -1); descriptionTextSize = (int) typedArray.getDimension(R.styleable.FlexyStepIndicator_flexy_descriptionTextSize, 16); numberBackgroundResId = typedArray.getResourceId(R.styleable.FlexyStepIndicator_flexy_numberBackgroundDrawable, -1); numberTextSize = (int) typedArray.getDimension(R.styleable.FlexyStepIndicator_flexy_numberTextSize, 16); numberTextColor = typedArray.getResourceId(R.styleable.FlexyStepIndicator_flexy_numberTextColor, -1); numberSize = (int) typedArray.getDimension(R.styleable.FlexyStepIndicator_flexy_numberSize, 30); doneIconResId = typedArray.getResourceId(R.styleable.FlexyStepIndicator_flexy_doneIconDrawable, -1); doneBackgroundResId = typedArray.getResourceId(R.styleable.FlexyStepIndicator_flexy_doneBackgroundDrawable, -1); lineActiveColor = typedArray.getColor(R.styleable.FlexyStepIndicator_flexy_lineActiveColor, DEFAULT_COLOR); lineInactiveColor = typedArray.getColor(R.styleable.FlexyStepIndicator_flexy_lineInactiveColor, DEFAULT_COLOR); lineHeight = (int) typedArray.getDimension(R.styleable.FlexyStepIndicator_flexy_lineHeight, 4); lineLength = (int) typedArray.getDimension(R.styleable.FlexyStepIndicator_flexy_lineLength, 30); lineDashCount = typedArray.getInt(R.styleable.FlexyStepIndicator_flexy_lineDashCount, 5); typedArray.recycle(); } private void setupThing() { stepPropertyList = new ArrayList<>(); } /** * Set current step index that will be selected. * * @param selectedIndex an index of the step. The step will be set to all done * if current step index is more than actual step size */ public void setCurrentIndex(int selectedIndex) { this.currentIndex = selectedIndex; updateView(); } /** * Get current selected step index * * @return the selected step index */ public int getCurrentIndex() { return currentIndex; } /** * Set all step to done */ public void setAllStepDone() { if (stepPropertyList != null) { setCurrentIndex(stepPropertyList.size() + 1); } } /** * Set description text color with color resource. * You can use selector to set difference color when step is active * or use color resource directly * <pre> * {@code * <selector xmlns:android="http://schemas.android.com/apk/res/android"> * <item android:color="#ffffff" android:state_selected="true" /> * <item android:color="#8dc73c" /> * </selector> * } * </pre> * * @param resId a color resource */ public void setStepDescriptionTextColorRes(int resId) { this.descriptionTextColor = resId; updateView(); } /** * Set step description text size. * * @param size a size of step description text (px) */ public void setStepDescriptionTextSize(int size) { this.descriptionTextSize = size; updateView(); } /** * Set step number text background with drawable resource * You can use selector to set difference drawable when step is active * or use drawable resource directly * <pre> * {@code * <selector xmlns:android="http://schemas.android.com/apk/res/android"> * <item android:drawable="@drawable/any_drawable" android:state_selected="true" /> * <item android:drawable="@drawable/any_drawable" /> * </selector> * } * </pre> * * @param resId a resource id of drawable */ public void setNumberBackgroundDrawableRes(int resId) { this.numberBackgroundResId = resId; updateView(); } /** * Set step number text size. * * @param size a size of step number text (px) */ public void setNumberTextSize(int size) { this.numberTextSize = size; updateView(); } /** * Set step number text color with color resource. * You can use selector to set difference color when step is active * or use color resource directly * <pre> * {@code * <selector xmlns:android="http://schemas.android.com/apk/res/android"> * <item android:color="#ffffff" android:state_selected="true" /> * <item android:color="#8dc73c" /> * </selector> * } * </pre> * * @param resId a color resource */ public void setNumberTextColorRes(int resId) { this.numberTextColor = resId; updateView(); } /** * Set done icon/symbol with drawable resource * You can use selector to set difference drawable when step is active * or use drawable resource directly * <pre> * {@code * <selector xmlns:android="http://schemas.android.com/apk/res/android"> * <item android:drawable="@drawable/any_drawable" android:state_selected="true" /> * <item android:drawable="@drawable/any_drawable" /> * </selector> * } * </pre> * * @param resId a resource id of drawable */ public void setDoneIconDrawableRes(int resId) { this.doneIconResId = resId; updateView(); } /** * Set done icon/symbol background with drawable resource * You can use selector to set difference drawable when step is active * or use drawable resource directly * <pre> * {@code * <selector xmlns:android="http://schemas.android.com/apk/res/android"> * <item android:drawable="@drawable/any_drawable" android:state_selected="true" /> * <item android:drawable="@drawable/any_drawable" /> * </selector> * } * </pre> * * @param resId a resource id of drawable */ public void setDoneBackgroundDrawableRes(int resId) { this.doneBackgroundResId = resId; updateView(); } /** * Set height of the step line * * @param height a height of the step line (px) */ public void setLineHeight(int height) { this.lineHeight = height; updateView(); } /** * Set length of the step line. * This length should be the total of both line side (left and right) * * @param length a length of the step line (px) */ public void setLineLength(int length) { this.lineLength = length; updateView(); } /** * Set number of dash in the step line * This number should be the total of both line side (left and right) * * @param lineDashCount a number of dash in the step line */ public void setLineDashCount(int lineDashCount) { this.lineDashCount = lineDashCount; updateView(); } /** * Set step line color with color resource when active * * @param color a color */ public void setLineActiveColor(int color) { this.lineActiveColor = color; updateView(); } /** * Set step line color with color resource when inactive * * @param color a color */ public void setLineInactiveColor(int color) { this.lineInactiveColor = color; updateView(); } /** * Set step view can be clickable or not * * @param clickable a boolean of step view clickable state */ public void setStepClickable(boolean clickable) { this.isStepClickable = clickable; updateStepClickableState(); } /** * Get step view clickable state * * @return the step view clickable state */ public boolean isStepClickable() { return this.isStepClickable; } /** * Set event listener for step view click event * * @param listener a step click listener */ public void setStepClickListener(StepClickListener listener) { this.stepClickListener = listener; } /** * Invalidate this view */ @Override public void invalidate() { setupThing(); updateIndicatorView(); updateStepClickableState(); updateView(); } private void updateStepClickableState() { if (stepPropertyList != null) { for (StepProperty stepProperty : stepPropertyList) { stepProperty.getRootView().setClickable(isStepClickable()); } } } private void updateView() { if (stepPropertyList != null) { int selectedIndex = getCurrentIndex(); for (int index = 0; index < stepPropertyList.size(); index++) { updateRootViewSelection(stepPropertyList.get(index), index, selectedIndex); updateIconDrawableVisibility(stepPropertyList.get(index), index, selectedIndex); updateLeftDividerDrawable(stepPropertyList.get(index), index, selectedIndex); updateRightDividerDrawable(stepPropertyList.get(index), index, selectedIndex); updateActiveState(stepPropertyList.get(index), index, selectedIndex); } } } private void updateRootViewSelection(StepProperty stepProperty, int index, int selectedIndex) { stepProperty.getRootView().setSelected(index <= selectedIndex); } private void updateIconDrawableVisibility(StepProperty stepProperty, int index, int selectedIndex) { if (stepProperty.getDoneImageView().isEnabled()) { updateDoneVisibility(stepProperty.getNumberTextView(), stepProperty.getDoneImageView(), index, selectedIndex); } } /** * Update an visibility of done icon and number of the step text. * <p/> * You can custom code to design how these view can be show or hide depending on current * step index as you want * * @param tvNumber a TextView that display the number of the that step * @param ivIcon a ImageView that display done icon or image in that step * @param index expect step index that will be custom in this method * @param selectedIndex current step index that has selected */ protected void updateDoneVisibility(TextView tvNumber, ImageView ivIcon, int index, int selectedIndex) { if (index < selectedIndex) { tvNumber.setVisibility(View.INVISIBLE); ivIcon.setVisibility(View.VISIBLE); } else { tvNumber.setVisibility(View.VISIBLE); ivIcon.setVisibility(View.INVISIBLE); } } private void updateLeftDividerDrawable(StepProperty stepProperty, int index, int selectedIndex) { updateDivider(stepProperty.getLeftDividerView(), true, index > selectedIndex); } private void updateRightDividerDrawable(StepProperty stepProperty, int index, int selectedIndex) { updateDivider(stepProperty.getRightDividerView(), false, index >= selectedIndex); } private void updateActiveState(StepProperty stepProperty, int index, int selectedIndex) { stepProperty.setActive(index <= selectedIndex); stepProperty.setActiveWithLastIndex(index == selectedIndex); } /** * Set description with string resource id to show in step view. * <p/> * This method should be called to setup step view * Step view won't show if you didn't call this method or * {@link #setStepDescriptionList(List String descriptionList)} method * * @param descriptionList List of string resource for step description */ public void setStepDescriptionResourceList(List<Integer> descriptionList) { this.descriptionResIdList = descriptionList; descriptionStringList = null; currentIndex = -1; updateIndicatorView(); } /** * Set description with string to show in step view. * <p/> * This method should be called to setup step view * Step view won't show if you didn't call this method or * {@link #setStepDescriptionResourceList(List Integer descriptionList)} method * * @param descriptionList List of string for step description */ public void setStepDescriptionList(List<String> descriptionList) { this.descriptionStringList = descriptionList; descriptionResIdList = null; currentIndex = -1; updateIndicatorView(); } private void updateIndicatorView() { int stepCount = 0; if (descriptionResIdList != null) { stepCount = descriptionResIdList.size(); } else if (descriptionStringList != null) { stepCount = descriptionStringList.size(); } removeAllViews(); stepPropertyList.clear(); for (int index = 0; index < stepCount; index++) { View view = createStepView(index, stepCount); addView(view); stepPropertyList.add(getStepProperty(view)); } } private void setViewSize(View view, int width, int height) { ViewGroup.LayoutParams params = view.getLayoutParams(); params.height = height; params.width = width; view.setLayoutParams(params); } @SuppressWarnings("deprecation") private View createStepView(int index, int totalStep) { View view = LayoutInflater.from(getContext()).inflate(R.layout.view_flexy_step_indicator, this, false); view.setSelected(false); view.setOnClickListener(this); // Number Layout Container FrameLayout layoutNumberContainer = (FrameLayout) view.findViewById(R.id.flexy_step_indicator_layout_number_container); setViewSize(layoutNumberContainer, numberSize, numberSize); // Done Image View ImageView ivDone = (ImageView) view.findViewById(R.id.flexy_step_indicator_iv_done); ivDone.setVisibility(View.INVISIBLE); ivDone.setEnabled(true); if (doneIconResId != -1) { ivDone.setImageResource(doneIconResId); } if (doneBackgroundResId != -1) { ivDone.setBackgroundResource(doneBackgroundResId); } if (doneBackgroundResId == -1 && doneIconResId == -1) { ivDone.setEnabled(false); } // Number Text View TextView tvNumber = (TextView) view.findViewById(R.id.flexy_step_indicator_tv_number); tvNumber.setTextSize(TypedValue.COMPLEX_UNIT_PX, numberTextSize); tvNumber.setText(String.valueOf(index + 1)); if (numberBackgroundResId != -1) { tvNumber.setBackgroundResource(numberBackgroundResId); } if (numberTextColor != -1) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { tvNumber.setTextColor(getResources().getColorStateList(numberTextColor, getContext().getTheme())); } else { tvNumber.setTextColor(getResources().getColorStateList(numberTextColor)); } } // Left Divider View viewLeftDivider = view.findViewById(R.id.flexy_step_indicator_view_left_line); if (index == 0) { viewLeftDivider.setVisibility(View.INVISIBLE); } updateDivider(viewLeftDivider, true, true); setLineSize(viewLeftDivider, lineDashCount, lineLength, lineHeight); // Right Divider View viewRightDivider = view.findViewById(R.id.flexy_step_indicator_view_right_divider); if (index == totalStep - 1) { viewRightDivider.setVisibility(View.INVISIBLE); } updateDivider(viewRightDivider, false, true); setLineSize(viewRightDivider, lineDashCount, lineLength, lineHeight); // Description Text View TextView tvDescription = (TextView) view.findViewById(R.id.flexy_step_indicator_tv_description); tvDescription.setText(getDescriptionText(index)); tvDescription.setTextSize(TypedValue.COMPLEX_UNIT_PX, descriptionTextSize); if (descriptionTextColor != -1) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { tvDescription.setTextColor(getResources().getColorStateList(descriptionTextColor, getContext().getTheme())); } else { tvDescription.setTextColor(getResources().getColorStateList(descriptionTextColor)); } } return view; } private String getDescriptionText(int index) { if (descriptionResIdList != null && descriptionResIdList.size() > index) { return getResources().getString(descriptionResIdList.get(index)); } if (descriptionStringList != null && descriptionStringList.size() > index) { return descriptionStringList.get(index); } return null; } @SuppressWarnings("deprecation") private void updateDivider(View view, boolean isMirror, boolean isInactive) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) { view.setBackground(createLineDrawable(lineDashCount, lineLength, lineHeight, lineActiveColor, lineInactiveColor, isMirror, isInactive)); } else { view.setBackgroundDrawable(createLineDrawable(lineDashCount, lineLength, lineHeight, lineActiveColor, lineInactiveColor, isMirror, isInactive)); } } private void setLineSize(View view, int dashCount, int lineLength, int lineHeight) { setViewSize(view, lineLength, lineHeight); } private StepProperty getStepProperty(View rootView) { TextView tvNumber = (TextView) rootView.findViewById(R.id.flexy_step_indicator_tv_number); View viewLeftDivider = rootView.findViewById(R.id.flexy_step_indicator_view_left_line); View viewRightDivider = rootView.findViewById(R.id.flexy_step_indicator_view_right_divider); ImageView ivDone = (ImageView) rootView.findViewById(R.id.flexy_step_indicator_iv_done); StepProperty stepProperty = new StepProperty(); stepProperty.setRootView(rootView); stepProperty.setLeftDividerView(viewLeftDivider); stepProperty.setRightDividerView(viewRightDivider); stepProperty.setNumberTextView(tvNumber); stepProperty.setDoneImageView(ivDone); stepProperty.setActive(false); return stepProperty; } private Drawable createLineDrawable(int dashCount, int lineLength, int lineHeight, int normalColor, int dashColor, boolean isMirror, boolean isActive) { int totalWidth = (int) ((dashCount - 0.5f) * lineLength); Paint paint = new Paint(); if (isActive) { paint.setColor(dashColor); } else { paint.setColor(normalColor); } Bitmap bitmap = Bitmap.createBitmap(totalWidth, lineHeight, Bitmap.Config.ARGB_8888); Canvas canvas = new Canvas(bitmap); if (isActive) { drawActiveLine(canvas, dashCount, lineHeight, lineLength, paint); } else { drawInactiveLine(canvas, dashCount, lineHeight, lineLength, paint); } if (isMirror) { Matrix matrix = new Matrix(); matrix.preScale(-1, 1); bitmap = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), matrix, false); } return new BitmapDrawable(getResources(), bitmap); } /** * Draw the step line with canvas when expect step is active * <p/> * Horizontal line of step that link to side step was create by canvas. * So you can custom the step line with your code * * @param canvas a canvas instance to draw the step line * @param dashCount a number of dash for the step line (include left and right side) * @param lineHeight a size of step line height (px) * @param lineLength a size of step line width in each side (px) * @param paint a paint instance to draw something on canvas */ @SuppressWarnings("UnnecessaryLocalVariable") protected void drawActiveLine(Canvas canvas, int dashCount, int lineHeight, int lineLength, Paint paint) { for (int i = 0; i < dashCount; i++) { float x1 = lineLength * 2 * i; float x2 = x1 + lineLength; float y1 = 0; float y2 = lineHeight; canvas.drawRect(x1, y1, x2, y2, paint); } } /** * Draw the step line with canvas when expect step is inactive * <p/> * Horizontal line of step that link to side step was create by canvas. * So you can custom the step line with your code * * @param canvas a canvas instance to draw the step line * @param dashCount a number of dash for the step line (include left and right side) * @param lineHeight a size of step line height (px) * @param lineLength a size of step line width in each side (px) * @param paint a paint instance to draw something on canvas */ protected void drawInactiveLine(Canvas canvas, int dashCount, int lineHeight, int lineLength, Paint paint) { canvas.drawRect(0, 0, canvas.getWidth(), lineHeight, paint); } @Override public void onClick(View view) { int stepIndex = getStepViewIndexClicked(view); if (stepIndex != -1) { setCurrentIndex(stepIndex); if (stepClickListener != null) { stepClickListener.onStepClick(stepIndex); } } } private int getStepViewIndexClicked(View view) { if (stepPropertyList != null) { for (int index = 0; index < stepPropertyList.size(); index++) { StepProperty stepProperty = stepPropertyList.get(index); if (stepProperty.getRootView() == view) { return index; } } } return -1; } @Override protected Parcelable onSaveInstanceState() { Parcelable superState = super.onSaveInstanceState(); SavedState ss = new SavedState(superState); ss.currentIndex = this.currentIndex; ss.descriptionTextColor = this.descriptionTextColor; ss.descriptionTextSize = this.descriptionTextSize; ss.numberBackgroundResId = this.numberBackgroundResId; ss.numberTextSize = this.numberTextSize; ss.numberTextColor = this.numberTextColor; ss.numberSize = this.numberSize; ss.doneIconResId = this.doneIconResId; ss.doneBackgroundResId = this.doneBackgroundResId; ss.lineActiveColor = this.lineActiveColor; ss.lineInactiveColor = this.lineInactiveColor; ss.lineHeight = this.lineHeight; ss.lineLength = this.lineLength; ss.lineDashCount = this.lineDashCount; ss.isStepClickable = this.isStepClickable; ss.descriptionResIdList = this.descriptionResIdList; ss.descriptionStringList = this.descriptionStringList; return ss; } @Override protected void onRestoreInstanceState(Parcelable state) { if (!(state instanceof SavedState)) { super.onRestoreInstanceState(state); return; } SavedState ss = (SavedState) state; super.onRestoreInstanceState(ss.getSuperState()); this.currentIndex = ss.currentIndex; this.descriptionTextColor = ss.descriptionTextColor; this.descriptionTextSize = ss.descriptionTextSize; this.numberBackgroundResId = ss.numberBackgroundResId; this.numberTextSize = ss.numberTextSize; this.numberTextColor = ss.numberTextColor; this.numberSize = ss.numberSize; this.doneIconResId = ss.doneIconResId; this.doneBackgroundResId = ss.doneBackgroundResId; this.lineActiveColor = ss.lineActiveColor; this.lineInactiveColor = ss.lineInactiveColor; this.lineHeight = ss.lineHeight; this.lineLength = ss.lineLength; this.lineDashCount = ss.lineDashCount; this.isStepClickable = ss.isStepClickable; this.descriptionResIdList = ss.descriptionResIdList; this.descriptionStringList = ss.descriptionStringList; invalidate(); } private static class SavedState extends BaseSavedState { List<Integer> descriptionResIdList; List<String> descriptionStringList; int currentIndex; int descriptionTextColor; int descriptionTextSize; int numberBackgroundResId; int numberTextSize; int numberTextColor; int numberSize; int doneIconResId; int doneBackgroundResId; int lineActiveColor; int lineInactiveColor; int lineHeight; int lineLength; int lineDashCount; boolean isStepClickable; SavedState(Parcelable superState) { super(superState); } private SavedState(Parcel in) { super(in); this.currentIndex = in.readInt(); this.descriptionTextColor = in.readInt(); this.descriptionTextSize = in.readInt(); this.numberBackgroundResId = in.readInt(); this.numberTextSize = in.readInt(); this.numberTextColor = in.readInt(); this.numberSize = in.readInt(); this.doneIconResId = in.readInt(); this.doneBackgroundResId = in.readInt(); this.lineActiveColor = in.readInt(); this.lineInactiveColor = in.readInt(); this.lineHeight = in.readInt(); this.lineLength = in.readInt(); this.lineDashCount = in.readInt(); this.isStepClickable = in.readInt() != 0; this.descriptionStringList = restoreDescriptionStringList(in); this.descriptionResIdList = restoreDescriptionResIdList(in); } private List<String> restoreDescriptionStringList(Parcel in) { List<String> descriptionStringList = in.createStringArrayList(); in.readStringList(descriptionStringList); return descriptionStringList; } private List<Integer> restoreDescriptionResIdList(Parcel in) { int[] descriptionResIds = in.createIntArray(); in.readIntArray(descriptionResIds); descriptionResIdList = new ArrayList<>(); for (int descriptionResId : descriptionResIds) { descriptionResIdList.add(descriptionResId); } return descriptionResIdList; } @Override public void writeToParcel(Parcel out, int flags) { super.writeToParcel(out, flags); out.writeInt(this.currentIndex); out.writeInt(this.descriptionTextColor); out.writeInt(this.descriptionTextSize); out.writeInt(this.numberBackgroundResId); out.writeInt(this.numberTextSize); out.writeInt(this.numberTextColor); out.writeInt(this.numberSize); out.writeInt(this.doneIconResId); out.writeInt(this.doneBackgroundResId); out.writeInt(this.lineActiveColor); out.writeInt(this.lineInactiveColor); out.writeInt(this.lineHeight); out.writeInt(this.lineLength); out.writeInt(this.lineDashCount); out.writeInt(this.isStepClickable ? 1 : 0); out.writeStringArray(saveDescriptionStringList(this.descriptionStringList)); out.writeIntArray(saveDescriptionResIdList(this.descriptionResIdList)); } private String[] saveDescriptionStringList(List<String> descriptionStringList) { if( descriptionStringList != null ){ String[] descriptionStrings = new String[descriptionStringList.size()]; for (int index = 0; index < descriptionStringList.size(); index++) { String descriptionString = descriptionStringList.get(index); descriptionStrings[index] = descriptionString; } return descriptionStrings; } return null; } private int[] saveDescriptionResIdList(List<Integer> descriptionResIdList) { if( descriptionResIdList != null ){ int[] descriptionResIds = new int[descriptionResIdList.size()]; for (int index = 0; index < descriptionResIdList.size(); index++) { Integer descriptionResId = descriptionResIdList.get(index); descriptionResIds[index] = descriptionResId; } return descriptionResIds; } return null; } public static final Creator<SavedState> CREATOR = new Creator<SavedState>() { public SavedState createFromParcel(Parcel in) { return new SavedState(in); } public SavedState[] newArray(int size) { return new SavedState[size]; } }; } private static class StepProperty { View rootView; TextView tvNumber; View viewLeftDivider; View viewRightDivider; ImageView ivDone; boolean isActive; boolean isActiveWithLastIndex; StepProperty() { } View getRootView() { return rootView; } void setRootView(View rootView) { this.rootView = rootView; } TextView getNumberTextView() { return tvNumber; } void setNumberTextView(TextView tvNumber) { this.tvNumber = tvNumber; } View getLeftDividerView() { return viewLeftDivider; } void setLeftDividerView(View viewLeftDivider) { this.viewLeftDivider = viewLeftDivider; } View getRightDividerView() { return viewRightDivider; } void setRightDividerView(View viewRightDivider) { this.viewRightDivider = viewRightDivider; } ImageView getDoneImageView() { return ivDone; } void setDoneImageView(ImageView ivDone) { this.ivDone = ivDone; } boolean isActive() { return isActive; } void setActive(boolean active) { isActive = active; } boolean isActiveWithLastIndex() { return isActiveWithLastIndex; } void setActiveWithLastIndex(boolean activeWithLastIndex) { isActiveWithLastIndex = activeWithLastIndex; } } public interface StepClickListener { void onStepClick(int index); } } <file_sep># FlexyStepIndicator Step Indicator view with flexibility customization
1c508f80537aa80372351dc363807e4ce7876eb6
[ "Markdown", "Java", "Gradle" ]
3
Gradle
akexorcist/FlexyStepIndicator
ca6fb137228b97f880b8627b321a14a02a844bd0
7098d4566e8d423d1ee16cb0cd3aa5fcd1e38aae
refs/heads/master
<file_sep>package routers import ( "github.com/gin-gonic/gin" v1 "yhdm/api/v1" ) func Routers() *gin.Engine{ r :=gin.Default() // 添加路由 r.GET("/home",v1.Testget) return r } <file_sep>package global import "github.com/sirupsen/logrus" var ( LOG *logrus.Logger ) <file_sep>package log import ( "fmt" "github.com/sirupsen/logrus" "strings" "time" ) type MyFormatter struct{} func (s *MyFormatter) Format(entry *logrus.Entry) ([]byte, error) { timestamp := time.Now().Local().Format("2006/01/02 15:04:05") msg := fmt.Sprintf("[CAI-%s] %s %s\n",strings.ToUpper(entry.Level.String()),timestamp, entry.Message) return []byte(msg), nil } func InitLogger() *logrus.Logger { var log = logrus.New() log.SetFormatter(new(MyFormatter)) return log }<file_sep>package main import ( "yhdm/global" "yhdm/log" ) func main() { global.LOG = log.InitLogger() global.LOG.Info("gin run") global.InitGlobal("127.0.0.1:7999") }<file_sep>package v1 import ( "github.com/gin-gonic/gin" "net/http" ) func Testget(c *gin.Context) { c.JSON(http.StatusOK, gin.H{ "name": "hello", "number": "123456", }) }
aa28b96caafc7c3c7e856d9eb78e6228953be0e1
[ "Go" ]
5
Go
kasoushu/yhdm
6f2b3a12107631cd5f7f5dd276c3ee069b168dfe
5f4dcce737f21ff16cb561b028f931108e768d00
refs/heads/master
<repo_name>Eforen/HTML5-Sudoku<file_sep>/Gruntfile.js module.exports = function(grunt) { grunt.initConfig({ pkg: grunt.file.readJSON('package.json'), browserify: { all: { files: {'public/javascripts/bundle.js': ['src/js/app.js']} } }, watch: { main: { options: { livereload: true, }, files: [ "src/js/**/*.js", "src/view/**/*.jsx"], tasks: [ 'browserify' ] }, test: { options: { spawn: false, }, files: [ "src/js/**/*.js", "test/**/*.js"], tasks: [ 'clear', 'mochaTest:all', 'jshint:codeBase' ] }, doc: { options: { spawn: false, livereload: true }, files: [ "src/js/**/*.js"], tasks: [ 'jsdoc:all' ] }, testndoc: { options: { spawn: false, livereload: 35730 }, files: [ "src/js/**/*.js", "test/**/*.js"], tasks: [ 'clear', 'mochaTest:all', 'jshint:codeBase', 'jsdoc:all' ] } }, exec: { start: "node ./bin/www", test: "node ./node_modules/mocha/bin/_mocha --reporter spec", testnyan: "node ./node_modules/mocha/bin/_mocha --reporter nyan" }, concurrent: { develop: ['watch:main', 'exec:start'], developTest: ['watch:test', 'exec:start'], test: ['jshint', 'mocha'] }, copy:{ html: { files: [{ expand: true, cwd: 'src/', src: ['*.html'], dest: 'public/' }] } }, jshint: { options: { //http://jshint.com/docs/options/ asi: true, //This option suppresses warnings about missing semicolons. boss: false, //This option suppresses warnings about the use of assignments in cases where comparisons are expected. More often than not, code like if (a = 10) {} is a typo. curly: false, //This option requires you to always put curly braces around blocks in loops and conditionals. eqeqeq: false, //This options prohibits the use of == and != in favor of === and !==. The former try to coerce values before comparing them which can lead to some unexpected results. The latter don't do any coercion so they are generally safer. eqnull: true, //This option suppresses warnings about == null comparisons. esnext: true, //This option tells JSHint that your code uses ECMAScript 6 specific syntax. browser: true, //This option defines globals exposed by modern browsers module: true, //This option informs JSHint that the input code describes an ECMAScript 6 module. globals: { jQuery: true }, }, codeBase: { files: { src: [ "src/js/**/*.js", "!public/javascripts/bundle.js" ] } }, bundle:{ options: { undef: true, }, files: { src: ['public/javascripts/bundle.js'] } } }, mochaTest: { all: { options: { ui: 'bdd', reporter: 'spec', captureFile: 'TestResults.txt', quiet: false, // Optionally suppress output to standard out (defaults to false) clearRequireCache: true // Clear the require cache before running tests so that the tests actually run on the new code }, src:['test/**/*.js'] }, react: { options: { ui: 'bdd', reporter: 'spec', captureFile: 'TestResults/react.txt', quiet: false, // Optionally suppress output to standard out (defaults to false) clearRequireCache: true, // Clear the require cache before running tests so that the tests actually run on the new code require: ["mocha-babel"] }, src:['test/**/*.jsx'] } }, jsdoc : { all : { src: ['src/**/*.js'], jsdoc: 'node_modules/.bin/jsdoc', options: { destination: 'docs', private: true, verbose: true, template : "docs-template", readme: "README.md", package: "package.json" //configure : "jsdoc.conf.json" } } }, babel: { options: { sourceMap: true, modules: "common" }, dist: { src: ['src/view/*.jsx'], dest: 'tmp/view.js' } }, sass: { // Task dist: { // Target options: { // Target options style: 'expanded' }, files: { // Dictionary of files 'public/stylesheets/main.css': 'src/styles/main.scss'//, // 'destination': 'source' //'widgets.css': 'widgets.scss' } } } }) grunt.loadNpmTasks('grunt-browserify') grunt.loadNpmTasks('grunt-babel') grunt.loadNpmTasks('grunt-clear') grunt.loadNpmTasks('grunt-concurrent') grunt.loadNpmTasks('grunt-contrib-copy') grunt.loadNpmTasks('grunt-contrib-jshint') grunt.loadNpmTasks('grunt-contrib-watch') grunt.loadNpmTasks('grunt-exec') grunt.loadNpmTasks('grunt-mocha-test') grunt.loadNpmTasks('grunt-jsdoc') grunt.loadNpmTasks('grunt-contrib-sass') grunt.registerTask('build', ['clear', 'sass:dist', 'copy:html', 'browserify:all']); grunt.registerTask('default', ['jshint:codeBase', 'mochaTest:all', 'browserify', 'uglify', 'jshint:bundle']); grunt.registerTask('develop', ['browserify', 'concurrent:develop']); grunt.registerTask('developTest', ['browserify', 'concurrent:developTest']); grunt.registerTask('buildDocs', ['jsdoc']); grunt.registerTask('watchDoc', ['watch:doc']); //grunt.registerTask('test', ['watch:test']); grunt.registerTask('test', 'runs my tasks', function () { var tasks = ['mochaTest:all', 'jshint:codeBase', 'watch:test']; // Use the force option for all tasks declared in the previous line // This allows tests to fail and still run jshint after grunt.option('force', true); grunt.task.run(tasks); }); grunt.registerTask('testndoc', 'runs my tasks', function () { var tasks = ['mochaTest:all', 'jshint:codeBase', 'watch:testndoc']; // Use the force option for all tasks declared in the previous line // This allows tests to fail and still run jshint after grunt.option('force', true); grunt.task.run(tasks); }); var defaultTestSrc = grunt.config('mochaTest.all.src'); var defaultJsHintSrc = grunt.config('jshint.codeBase.files.src'); // on watch:test events configure mochaTest.all to only run on changed file grunt.event.on('watch', function(action, filepath, target) { console.log("wtf!") if(target == "test" || target == "testndoc"){ //debug console.log("Test: "+ target + " | "+ action + " | " + filepath) //Set Syntax Check grunt.config('jshint.codeBase.files.src', filepath) //change reporter to nyan for compressed output //grunt.config('mochaTest.all.options.reporter', 'nyan') //make my own filepath storage var file = filepath; //if the path is not already a test then target the correct test if(file.indexOf('src\\js\\') === 0) { //change file target file = "test\\test."+file.substring(7); console.log("Test: "+file+"|"+ file.substring(7)); //debug } if(grunt.file.exists(file)){ console.log("Targeted test found running..."); //put file path in array for mochaTest //file = [file]; //Set test target grunt.config('mochaTest.all.src', file); } else{ grunt.fail.warn('File ' + file + ' doesn\'t exist.'); //run the all the tests if file not found console.log("Targeted test not found running all..."); grunt.config('mochaTest.all.src', defaultTestSrc); } } }); }<file_sep>/test/test.tileStore.js var expect = require("chai").expect; var tileStore = require("../src/js/tileStore.js"); var sudoku = require("../src/js/sudokuOBJ.js"); describe("tileStore Object", function() { it("should have all available", function(done){ var store = new tileStore(); expect(store.available()).to.deep.equal([true,true,true,true,true,true,true,true,true]); done(); }) it("should have no tiles at construction", function(done){ var store = new tileStore(); expect(store.tiles).to.have.length(0); done(); }) })<file_sep>/src/js/app.js /** * @file Main App Code * @author <NAME> */ window.sudokuOBJ = require("./sudokuOBJ.js"); window.sudokuSolver = require("./sudokuSolver.js"); window.token = require("./tokenENUM.js"); //test = new window.sudokuOBJ(); window.testData = { name: "Simple Test", puzzle: "043000620700403008600208007075000340000000000098000570900507003100602005087000260" } window.su = window.sudokuOBJ.loadFromOBJ(window.testData); window.solve = new window.sudokuSolver(window.su); window.su2 = window.solve.getSudoku(); /* */ window.runTest = function(){ solve.solvePassBasic() solve.solvePassBasic() solve.solvePassBasic() solve.solvePassBasic() solve.solveRegionExclusion() solve.solvePassBasic() solve.solveRowExclusion() solve.solvePassBasic() solve.solveColExclusion() solve.solvePassBasic() solve.solveRegionExclusion() solve.solvePassBasic() solve.solveRowExclusion() solve.solvePassBasic() solve.solvePassBasic() } window.runRenderWait = function(waitTime, index){ if(waitTime == null || waitTime <= 0) return if(index == null || index < 0) index = 0; switch (index) { case 0: window.solve.solvePassBasic() break case 1: window.solve.solvePassBasic() break case 2: window.solve.solvePassBasic() break case 3: window.solve.solvePassBasic() break case 4: window.solve.solveRegionExclusion() break case 5: window.solve.solvePassBasic() break case 6: window.solve.solveRowExclusion() break case 7: window.solve.solvePassBasic() break case 8: window.solve.solveColExclusion() break case 9: window.solve.solvePassBasic() break case 10: window.solve.solveRegionExclusion() break case 11: window.solve.solvePassBasic() break case 12: window.solve.solveRowExclusion() break case 13: window.solve.solvePassBasic() break case 14: window.solve.solvePassBasic() break default: return } index++ setTimeout(window.runRenderWait, waitTime, waitTime, index) window.renderView(); } require("../view/view.jsx") //require("./view.js")<file_sep>/test/test.tileOBJ.js var expect = require("chai").expect; var sudoku = require("../src/js/sudokuOBJ.js"); var tileStore = require("../src/js/tileStore.js"); var tileOBJ = require("../src/js/tileOBJ.js"); var tokens = require("../src/js/tokenENUM.js"); var debug = require("../src/js/debugger.js"); describe("tile Object", function() { //var su = null; var tile = null; beforeEach(function(done) { //su = new sudoku(); //should not need this //su = null; //Debug setup expectation //expect(su).not.to.be.null; //Test setup expectation tile = new tileOBJ(); expect(tile).not.to.be.null; done(); }) it("should instansiate available", function(done){ expect(tile).not.to.be.null; expect(tile).to.be.instanceof(tileOBJ); done(); }) describe("setup", function() { var su = null; beforeEach(function(done){ su = new sudoku(); //should not need this expect(su).not.to.be.null; //Test setup expectation expect(tile.setup).to.be.a('function'); tile.setup(su.getRow(1), su.getCol(2), su.getRegion(1), 3,2); done(); }) it("before setup isSetup should be false", function(done){ var t = new tileOBJ(); expect(t.isSetup).to.be.false; done(); }) it("after setup isSetup should be true", function(done){ expect(tile.isSetup).to.be.true; done(); }) it("rows match", function(done){ expect(tile.getRow()).to.equal(su.getRow(1)); done(); }) it("cols match", function(done){ expect(tile.getCol()).to.equal(su.getCol(2)); done(); }) it("region match", function(done){ expect(tile.getRegion()).to.equal(su.getRegion(1)); done(); }) it("pos x match", function(done){ expect(tile.getX()).to.equal(3); done(); }) it("pos y match", function(done){ expect(tile.getY()).to.equal(2); done(); }) }) describe("data Values", function() { var su = null; beforeEach(function(done){ done(); }) it("default Token", function(done){ expect(tile.getToken()).to.equal(1); done(); }) it("default Type", function(done){ expect(tile.getType()).to.equal(tileOBJ.types.blank); done(); }) it("set Token", function(done){ tile.setToken(tokens.c); done(); }) it("set Type", function(done){ tile.setType(tileOBJ.types.guess); done(); }) it("set Both", function(done){ tile.set(tokens.c, tileOBJ.types.guess); done(); }) it("get token Token", function(done){ tile.setToken(tokens.c); expect(tile.getToken()).to.equal(tokens.c); done(); }) it("get type Type", function(done){ tile.setType(tileOBJ.types.guess); expect(tile.getType()).to.equal(tileOBJ.types.guess); done(); }) it("get both", function(done){ tile.set(tokens.c, tileOBJ.types.guess); expect(tile.get().token).to.equal(tokens.c); expect(tile.get().type).to.equal(tileOBJ.types.guess); done(); }) }) describe("Guessing", function(){ it("guess default should be false", function(done){ expect(tile.getGuess(tokens.b)).to.equal(false); done(); }) it("can set guess (value)", function(done){ expect(tile.getGuess(tokens.c)).to.equal(false); tile.setGuess(tokens.c); expect(tile.getGuess(tokens.c)).to.equal(true); done(); }) it("can set guess (type)", function(done){ expect(tile.getType()).to.equal(tileOBJ.types.blank); tile.setGuess(tokens.d); expect(tile.getType()).to.equal(tileOBJ.types.guess); done(); }) it("can get guesses as array", function(done){ expect(tile.getGuesses()).to.be.instanceof(Array); done(); }) it("can set guesses as array partial range", function(done){ expect(tile.getGuess(tokens.a)).to.equal(false); expect(tile.getGuess(tokens.b)).to.equal(false); expect(tile.getGuess(tokens.c)).to.equal(false); expect(tile.getGuess(tokens.d)).to.equal(false); expect(tile.getGuess(tokens.e)).to.equal(false); expect(tile.getGuess(tokens.f)).to.equal(false); var arr = [] arr[tokens.a] = true; arr[tokens.b] = false; arr[tokens.c] = true; arr[tokens.d] = true; arr[tokens.f] = true; tile.setGuesses(arr); expect(tile.getGuess(tokens.a)).to.equal(true); expect(tile.getGuess(tokens.b)).to.equal(false); expect(tile.getGuess(tokens.c)).to.equal(true); expect(tile.getGuess(tokens.d)).to.equal(true); expect(tile.getGuess(tokens.e)).to.equal(false); expect(tile.getGuess(tokens.f)).to.equal(true); done(); }) it("can set guesses as array full range", function(done){ expect(tile.getGuess(tokens.a)).to.equal(false); expect(tile.getGuess(tokens.b)).to.equal(false); expect(tile.getGuess(tokens.c)).to.equal(false); expect(tile.getGuess(tokens.d)).to.equal(false); expect(tile.getGuess(tokens.e)).to.equal(false); expect(tile.getGuess(tokens.f)).to.equal(false); expect(tile.getGuess(tokens.g)).to.equal(false); expect(tile.getGuess(tokens.h)).to.equal(false); expect(tile.getGuess(tokens.i)).to.equal(false); var arr = [] arr[tokens.a] = true; arr[tokens.b] = true; arr[tokens.c] = true; arr[tokens.d] = true; arr[tokens.e] = true; arr[tokens.f] = true; arr[tokens.g] = true; arr[tokens.h] = true; arr[tokens.i] = true; tile.setGuesses(arr); expect(tile.getGuess(tokens.a)).to.equal(true); expect(tile.getGuess(tokens.b)).to.equal(true); expect(tile.getGuess(tokens.c)).to.equal(true); expect(tile.getGuess(tokens.d)).to.equal(true); expect(tile.getGuess(tokens.e)).to.equal(true); expect(tile.getGuess(tokens.f)).to.equal(true); expect(tile.getGuess(tokens.g)).to.equal(true); expect(tile.getGuess(tokens.h)).to.equal(true); expect(tile.getGuess(tokens.i)).to.equal(true); done(); }) it("can set all guesses to value", function(done){ expect(tile.getGuess(tokens.a)).to.equal(false); expect(tile.getGuess(tokens.b)).to.equal(false); expect(tile.getGuess(tokens.c)).to.equal(false); expect(tile.getGuess(tokens.d)).to.equal(false); expect(tile.getGuess(tokens.e)).to.equal(false); expect(tile.getGuess(tokens.f)).to.equal(false); expect(tile.getGuess(tokens.g)).to.equal(false); expect(tile.getGuess(tokens.h)).to.equal(false); expect(tile.getGuess(tokens.i)).to.equal(false); tile.setGuesses(true); expect(tile.getGuess(tokens.a)).to.equal(true); expect(tile.getGuess(tokens.b)).to.equal(true); expect(tile.getGuess(tokens.c)).to.equal(true); expect(tile.getGuess(tokens.d)).to.equal(true); expect(tile.getGuess(tokens.e)).to.equal(true); expect(tile.getGuess(tokens.f)).to.equal(true); expect(tile.getGuess(tokens.g)).to.equal(true); expect(tile.getGuess(tokens.h)).to.equal(true); expect(tile.getGuess(tokens.i)).to.equal(true); tile.setGuesses(false); expect(tile.getGuess(tokens.a)).to.equal(false); expect(tile.getGuess(tokens.b)).to.equal(false); expect(tile.getGuess(tokens.c)).to.equal(false); expect(tile.getGuess(tokens.d)).to.equal(false); expect(tile.getGuess(tokens.e)).to.equal(false); expect(tile.getGuess(tokens.f)).to.equal(false); expect(tile.getGuess(tokens.g)).to.equal(false); expect(tile.getGuess(tokens.h)).to.equal(false); expect(tile.getGuess(tokens.i)).to.equal(false); done(); }) it("should change type to set when was guess", function(done){ tile.setGuesses(true); tile.set(tokens.a); expect(tile.getType()).to.equal(tileOBJ.types.set); done(); }) it("should change type to set when was guess 2", function(done){ tile.setGuesses(true); tile.setToken(tokens.a); expect(tile.getType()).to.equal(tileOBJ.types.set); done(); }) it("should NOT change type to guess when mass falseing and was set", function(done){ tile.setGuesses(true); tile.setToken(tokens.a); tile.setType(tileOBJ.types.guess); //Object.watch("tile._type", function(){ console.log(debug.getstack())}) var arr = [] arr[tokens.a] = false; arr[tokens.d] = false; arr[tokens.i] = false; tile.setGuesses(arr) expect(tile.getType()).to.equal(tileOBJ.types.guess); tile.setGuesses(true); tile.setToken(tokens.a); tile.setType(tileOBJ.types.set); //Object.watch("tile._type", function(){ console.log(debug.getstack())}) var arr = [] arr[tokens.a] = false; arr[tokens.d] = false; arr[tokens.i] = false; tile.setGuesses(arr) expect(tile.getType()).to.equal(tileOBJ.types.set); tile.setGuesses(true); tile.setToken(tokens.a); tile.setType(tileOBJ.types.lock); //Object.watch("tile._type", function(){ console.log(debug.getstack())}) var arr = [] arr[tokens.a] = false; arr[tokens.d] = false; arr[tokens.i] = false; tile.setGuesses(arr) expect(tile.getType()).to.equal(tileOBJ.types.lock); done(); }) }) })<file_sep>/src/view/sudokuTile.jsx var React = require('react'); var tileOBJ = require("../js/tileOBJ.js"); /** * This makes the sudoku tile dom * @name SudokuTile * @module */ var SudokuTile = React.createClass({ render: function() { var id = null if(this.props.x != null & this.props.y != null){ id = this.props.x+"x"+this.props.y } var style = { } var inside = null switch (this.props.tile.getType()){ case tileOBJ.types.set: inside = (<div className="set">{this.props.tile._value}</div>) break case tileOBJ.types.locked: inside = (<div className="locked">{this.props.tile._value}</div>) break case tileOBJ.types.guess: var guessItems = [] var guesses = this.props.tile._guesses; for (var i = 0; i < guesses.length; i++) { if(guesses[i] === true){ //console.log("guesses["+i+"]="+guesses[i]) guessItems.push(<span key={i} className={"guess guess-"+i}>{i}</span>) } } inside = (<div className="guesses">{guessItems}</div>) break default: inside = (<div className="empty"> </div>) } return (<div style={style} className={(this.props.x != null & this.props.y != null)?"tile tile-"+id:"tile"}> {inside} </div>) } }); module.exports = SudokuTile<file_sep>/src/js/tokenENUM.js /** * @file tokenENUM Code * @author <NAME> */ /** * Enum of Token Values * @readonly * @enum {number} */ /* var tokenENUM = { a: 1, b: 2, c: 3, d: 4, e: 5, f: 6, g: 7, h: 8, i: 9 } exports = tokenENUM */ exports.a = 1; exports.b = 2; exports.c = 3; exports.d = 4; exports.e = 5; exports.f = 6; exports.g = 7; exports.h = 8; exports.i = 9;<file_sep>/test/test.sudokuSolver.js var expect = require("chai").expect; var sudokuSolver = require("../src/js/sudokuSolver.js"); var sudokuOBJ = require("../src/js/sudokuOBJ.js"); var tileStore = require("../src/js/tileStore.js"); var tileOBJ = require("../src/js/tileOBJ.js"); var tokens = require("../src/js/tokenENUM.js"); describe("sudoku solver", function() { var su = null; var solve = null; beforeEach(function(done) { var test = { name: "<NAME>", puzzle: "043000620700403008600208007075000340000000000098000570900507003100602005087000260" } su = sudokuOBJ.loadFromOBJ(test); //su = null; //Debug setup expectation expect(su).not.to.be.null; //Test setup expectation expect(su).to.be.instanceof(sudokuOBJ); //Test setup expectation solve = new sudokuSolver(su); expect(solve).not.to.be.null; //Test setup expectation expect(solve).to.be.instanceof(sudokuSolver); //Test setup expectation done(); }) it("should instansiate and be available", function(done){ expect(solve).not.to.be.null; expect(solve).to.be.instanceof(sudokuSolver); //Test setup expectation done(); }) it("it should contain the sudoku provided before", function(done){ solve.getSudoku().getTile(1,1).setType(tileOBJ.types.locked) expect(solve.getSudoku()).to.be.equal(su); expect(su.getTile(1,1).getType()).to.be.equal(tileOBJ.types.locked); done(); }) it("should prep object sudoku by filling every tile with all guesses", function(done){ var tile; expect(su.debugRow(0)).to.equal("|123456789|4|3|123456789|123456789|123456789|6|2|123456789|") expect(su.debugRow(1)).to.equal("|7|123456789|123456789|4|123456789|3|123456789|123456789|8|") expect(su.debugRow(2)).to.equal("|6|123456789|123456789|2|123456789|8|123456789|123456789|7|") expect(su.debugRow(3)).to.equal("|123456789|7|5|123456789|123456789|123456789|3|4|123456789|") expect(su.debugRow(4)).to.equal("|123456789|123456789|123456789|123456789|123456789|123456789|123456789|123456789|123456789|") expect(su.debugRow(5)).to.equal("|123456789|9|8|123456789|123456789|123456789|5|7|123456789|") expect(su.debugRow(6)).to.equal("|9|123456789|123456789|5|123456789|7|123456789|123456789|3|") expect(su.debugRow(7)).to.equal("|1|123456789|123456789|6|123456789|2|123456789|123456789|5|") expect(su.debugRow(8)).to.equal("|123456789|8|7|123456789|123456789|123456789|2|6|123456789|") expect(solve.getSudoku().getTile(0,0).getType()).to.equal(tileOBJ.types.guess) var val = true; for (var x = 0; x < 9; x++) { for (var y = 0; y < 9; y++) { tile = solve.getSudoku().getTile(x,y); //tile = su.getTile(x,y); val = true; expect(tile.getType()).to.not.equal(tileOBJ.types.blank) if(tile.getType() == tileOBJ.types.locked) val = false; expect(tile.getGuess(tokens.a)).to.equal(val); expect(tile.getGuess(tokens.b)).to.equal(val); expect(tile.getGuess(tokens.c)).to.equal(val); expect(tile.getGuess(tokens.d)).to.equal(val); expect(tile.getGuess(tokens.e)).to.equal(val); expect(tile.getGuess(tokens.f)).to.equal(val); expect(tile.getGuess(tokens.g)).to.equal(val); expect(tile.getGuess(tokens.h)).to.equal(val); expect(tile.getGuess(tokens.i)).to.equal(val); } } done(); }) // 0dc 000 fb0 // g00 d0c 00h // f00 b0h 00g // 0ge 000 cd0 // 000 000 000 // 0ih 000 eg0 // i00 e0g 00c // a00 f0b 00e // 0hg 000 bf0 it("should remove all guesses of tile that are in row", function(done){ //Confirming Start state expect(su.debugRow(0)).to.equal("|123456789|4|3|123456789|123456789|123456789|6|2|123456789|") //expect(su.debugRow(1)).to.equal("|7|123456789|123456789|4|123456789|3|123456789|123456789|8|") expect(solve.getSudoku().getTile(0,0).getType()).to.equal(tileOBJ.types.guess) solve.solveForRow(0); solve.solveForRow(1); solve.solveForRow(2); solve.solveForRow(3); solve.solveForRow(4); solve.solveForRow(5); solve.solveForRow(6); solve.solveForRow(7); solve.solveForRow(8); expect(solve.getSudoku().getTile(0,0).getType()).to.equal(tileOBJ.types.guess) tile = solve.getSudoku().getTile(0,0); expect(tile.getGuess(tokens.a)).to.equal(true); // 1 expect(tile.getGuess(tokens.b)).to.equal(false); // 2 expect(tile.getGuess(tokens.c)).to.equal(false); // 3 expect(tile.getGuess(tokens.d)).to.equal(false); // 4 expect(tile.getGuess(tokens.e)).to.equal(true); // 5 expect(tile.getGuess(tokens.f)).to.equal(false); // 6 expect(tile.getGuess(tokens.g)).to.equal(true); // 7 expect(tile.getGuess(tokens.h)).to.equal(true); // 8 expect(tile.getGuess(tokens.i)).to.equal(true); // 9 expect(solve.getSudoku().debugRow(0)).to.equal("|15789|4|3|15789|15789|15789|6|2|15789|") expect(su.debugRow(1)).to.equal("|7|12569|12569|4|12569|3|12569|12569|8|") expect(su.debugRow(2)).to.equal("|6|13459|13459|2|13459|8|13459|13459|7|") expect(su.debugRow(3)).to.equal("|12689|7|5|12689|12689|12689|3|4|12689|") expect(su.debugRow(4)).to.equal("|123456789|123456789|123456789|123456789|123456789|123456789|123456789|123456789|123456789|") expect(su.debugRow(5)).to.equal("|12346|9|8|12346|12346|12346|5|7|12346|") expect(su.debugRow(6)).to.equal("|9|12468|12468|5|12468|7|12468|12468|3|") expect(su.debugRow(7)).to.equal("|1|34789|34789|6|34789|2|34789|34789|5|") expect(su.debugRow(8)).to.equal("|13459|8|7|13459|13459|13459|2|6|13459|") done() }) it("should remove all guesses of tile that are in col", function(done){ //check start start state expect(su.debugRow(0)).to.equal("|123456789|4|3|123456789|123456789|123456789|6|2|123456789|") //expect(su.debugRow(1)).to.equal("|7|123456789|123456789|4|123456789|3|123456789|123456789|8|") //expect(su.debugRow(2)).to.equal("|6|123456789|123456789|2|123456789|8|123456789|123456789|7|") //expect(su.debugRow(3)).to.equal("|123456789|7|5|123456789|123456789|123456789|3|4|123456789|") //expect(su.debugRow(4)).to.equal("|123456789|123456789|123456789|123456789|123456789|123456789|123456789|123456789|123456789|") //expect(su.debugRow(5)).to.equal("|123456789|9|8|123456789|123456789|123456789|5|7|123456789|") //expect(su.debugRow(6)).to.equal("|9|123456789|123456789|5|123456789|7|123456789|123456789|3|") //expect(su.debugRow(7)).to.equal("|1|123456789|123456789|6|123456789|2|123456789|123456789|5|") //expect(su.debugRow(8)).to.equal("|123456789|8|7|123456789|123456789|123456789|2|6|123456789|") solve.solveForCol(0); //solve.solveForCol(1); //solve.solveForCol(2); //solve.solveForCol(3); //solve.solveForCol(4); //solve.solveForCol(5); //solve.solveForCol(6); //solve.solveForCol(7); //solve.solveForCol(8); tile = solve.getSudoku().getTile(0,0); //expect(tile.getGuess(tokens.a)).to.equal(false); // 1 //expect(tile.getGuess(tokens.b)).to.equal(true); // 2 //expect(tile.getGuess(tokens.c)).to.equal(true); // 3 //expect(tile.getGuess(tokens.d)).to.equal(true); // 4 //expect(tile.getGuess(tokens.e)).to.equal(true); // 5 //expect(tile.getGuess(tokens.f)).to.equal(false); // 6 //expect(tile.getGuess(tokens.g)).to.equal(false); // 7 //expect(tile.getGuess(tokens.h)).to.equal(true); // 8 //expect(tile.getGuess(tokens.i)).to.equal(false); // 9 expect() expect(su.debugCol(0)).to.equal("|23458|7|6|23458|23458|23458|9|1|23458|") //expect(su.debugRow(0)).to.equal("|23458|4|3|123456789|123456789|123456789|6|2|123456789|") //expect(su.debugRow(1)).to.equal("|7|123456789|123456789|4|123456789|3|123456789|123456789|8|") //expect(su.debugRow(2)).to.equal("|6|123456789|123456789|2|123456789|8|123456789|123456789|7|") //expect(su.debugRow(3)).to.equal("|23458|7|5|123456789|123456789|123456789|3|4|123456789|") //expect(su.debugRow(4)).to.equal("|23458|123456789|123456789|123456789|123456789|123456789|123456789|123456789|123456789|") //expect(su.debugRow(5)).to.equal("|23458|9|8|123456789|123456789|123456789|5|7|123456789|") //expect(su.debugRow(6)).to.equal("|9|123456789|123456789|5|123456789|7|123456789|123456789|3|") //expect(su.debugRow(7)).to.equal("|1|123456789|123456789|6|123456789|2|123456789|123456789|5|") //expect(su.debugRow(8)).to.equal("|23458|8|7|123456789|123456789|123456789|2|6|123456789|") done() }) // 0 d c // g 0 0 // f 0 0 it("should remove all guesses of tile that are in region", function(done){ solve.solveForRegion(0); solve.solveForRegion(1); solve.solveForRegion(2); solve.solveForRegion(3); solve.solveForRegion(4); solve.solveForRegion(5); solve.solveForRegion(6); solve.solveForRegion(7); solve.solveForRegion(8); tile = solve.getSudoku().getTile(0,0); expect(tile.getGuess(tokens.a)).to.equal(true); // 1 expect(tile.getGuess(tokens.b)).to.equal(true); // 2 expect(tile.getGuess(tokens.c)).to.equal(false); // 3 expect(tile.getGuess(tokens.d)).to.equal(false); // 4 expect(tile.getGuess(tokens.e)).to.equal(true); // 5 expect(tile.getGuess(tokens.f)).to.equal(false); // 6 expect(tile.getGuess(tokens.g)).to.equal(false); // 7 expect(tile.getGuess(tokens.h)).to.equal(true); // 8 expect(tile.getGuess(tokens.i)).to.equal(true); // 9 expect(su.debugRegion(0)).to.equal("|12589|4|3|7|12589|12589|6|12589|12589|") expect(su.debugRegion(1)).to.equal("|15679|15679|15679|4|15679|3|2|15679|8|") expect(su.debugRegion(2)).to.equal("|6|2|13459|13459|13459|8|13459|13459|7|") expect(su.debugRegion(3)).to.equal("|12346|7|5|12346|12346|12346|12346|9|8|") expect(su.debugRegion(4)).to.equal("|123456789|123456789|123456789|123456789|123456789|123456789|123456789|123456789|123456789|") expect(su.debugRegion(5)).to.equal("|3|4|12689|12689|12689|12689|5|7|12689|") expect(su.debugRegion(6)).to.equal("|9|23456|23456|1|23456|23456|23456|8|7|") expect(su.debugRegion(7)).to.equal("|5|13489|7|6|13489|2|13489|13489|13489|") expect(su.debugRegion(8)).to.equal("|14789|14789|3|14789|14789|5|2|6|14789|") //expect(su.debugRow(0)).to.equal("|123456789|4|3|123456789|123456789|123456789|6|2|123456789|") //expect(su.debugRow(1)).to.equal("|7|123456789|123456789|4|123456789|3|123456789|123456789|8|") //expect(su.debugRow(2)).to.equal("|6|123456789|123456789|2|123456789|8|123456789|123456789|7|") //expect(su.debugRow(3)).to.equal("|123456789|7|5|123456789|123456789|123456789|3|4|123456789|") //expect(su.debugRow(4)).to.equal("|123456789|123456789|123456789|123456789|123456789|123456789|123456789|123456789|123456789|") //expect(su.debugRow(5)).to.equal("|123456789|9|8|123456789|123456789|123456789|5|7|123456789|") //expect(su.debugRow(6)).to.equal("|9|123456789|123456789|5|123456789|7|123456789|123456789|3|") //expect(su.debugRow(7)).to.equal("|1|123456789|123456789|6|123456789|2|123456789|123456789|5|") //expect(su.debugRow(8)).to.equal("|123456789|8|7|123456789|123456789|123456789|2|6|123456789|") done() }) it("pass #01 basic solve", function(done){ /* Checks each guess agenst every other tile that is SET or LOCKED in the posibility space (ROW, COL or REGION) */ /* Blank Starter Test expect(su.debugRow(0)).to.equal("||4|3||||6|2||") expect(su.debugRow(1)).to.equal("|7|||4||3|||8|") expect(su.debugRow(2)).to.equal("|6|||2||8|||7|") expect(su.debugRow(3)).to.equal("||7|5||||3|4||") expect(su.debugRow(4)).to.equal("||||||||||") expect(su.debugRow(5)).to.equal("||9|8||||5|7||") expect(su.debugRow(6)).to.equal("|9|||5||7|||3|") expect(su.debugRow(7)).to.equal("|1|||6||2|||5|") expect(su.debugRow(8)).to.equal("||8|7||||2|6||") */ solve.solvePassBasic(); expect(su.debugRow(0)).to.equal("|58|4|3|179|1579|159|6|2|19|") expect(su.debugRow(1)).to.equal("|7|125|129|4|1569|3|19|159|8|") expect(su.debugRow(2)).to.equal("|6|15|19|2|159|8|149|1359|7|") expect(su.debugRow(3)).to.equal("|2|7|5|189|12689|169|3|4|1269|") expect(su.debugRow(4)).to.equal("|234|1236|1246|13789|123456789|14569|189|189|1269|") expect(su.debugRow(5)).to.equal("|234|9|8|13|12346|146|5|7|126|") expect(su.debugRow(6)).to.equal("|9|26|246|5|148|7|148|18|3|") expect(su.debugRow(7)).to.equal("|1|3|4|6|3489|2|4789|89|5|") expect(su.debugRow(8)).to.equal("|345|8|7|139|1349|149|2|6|149|") expect(su.getStructure()).to.equal( "*---*---*---*\n"+ "|043|000|620|\n"+ "|700|403|008|\n"+ "|600|208|007|\n"+ "*---+---+---*\n"+ "|275|000|340|\n"+ "|000|000|000|\n"+ "|098|000|570|\n"+ "*---+---+---*\n"+ "|900|507|003|\n"+ "|134|602|005|\n"+ "|087|000|260|\n"+ "*---*---*---*\n"); done() }) it("pass #02 basic solve", function(done){ solve.solvePassBasic(); solve.solvePassBasic(); expect(su.debugRow(0)).to.equal("|58|4|3|179|1579|159|6|2|19|") expect(su.debugRow(1)).to.equal("|7|125|129|4|1569|3|19|159|8|") expect(su.debugRow(2)).to.equal("|6|15|19|2|159|8|149|1359|7|") expect(su.debugRow(3)).to.equal("|2|7|5|189|1689|169|3|4|169|") expect(su.debugRow(4)).to.equal("|34|16|16|13789|123456789|14569|189|189|1269|") expect(su.debugRow(5)).to.equal("|34|9|8|13|12346|146|5|7|126|") expect(su.debugRow(6)).to.equal("|9|26|26|5|148|7|148|18|3|") expect(su.debugRow(7)).to.equal("|1|3|4|6|89|2|789|89|5|") expect(su.debugRow(8)).to.equal("|5|8|7|139|1349|149|2|6|149|") /* expect(su.debugRow(0)).to.equal("|58|4|3|179|1579|159|6|2|19|") expect(su.debugRow(1)).to.equal("|7|125|129|4|1569|3|19|159|8|") expect(su.debugRow(2)).to.equal("|6|15|19|2|159|8|149|1359|7|") expect(su.debugRow(3)).to.equal("|2|7|5|189|12689|169|3|4|1269|") expect(su.debugRow(4)).to.equal("|234|1236|1246|13789|123456789|14569|189|189|1269|") expect(su.debugRow(5)).to.equal("|234|9|8|13|12346|146|5|7|126|") expect(su.debugRow(6)).to.equal("|9|26|246|5|148|7|148|18|3|") expect(su.debugRow(7)).to.equal("|1|3|4|6|2489|2|4789|89|5|") expect(su.debugRow(8)).to.equal("|5|8|7|139|1349|149|2|6|149|") */ expect(su.getStructure()).to.equal( "*---*---*---*\n"+ "|043|000|620|\n"+ "|700|403|008|\n"+ "|600|208|007|\n"+ "*---+---+---*\n"+ "|275|000|340|\n"+ "|000|000|000|\n"+ "|098|000|570|\n"+ "*---+---+---*\n"+ "|900|507|003|\n"+ "|134|602|005|\n"+ "|587|000|260|\n"+ "*---*---*---*\n"); done() }) it("pass #03 basic solve", function(done){ solve.solvePassBasic(); solve.solvePassBasic(); solve.solvePassBasic(); expect(su.debugRow(0)).to.equal("|8|4|3|179|1579|159|6|2|19|") expect(su.debugRow(1)).to.equal("|7|125|129|4|1569|3|19|159|8|") expect(su.debugRow(2)).to.equal("|6|15|19|2|159|8|149|1359|7|") expect(su.debugRow(3)).to.equal("|2|7|5|189|1689|169|3|4|169|") expect(su.debugRow(4)).to.equal("|34|16|16|13789|123456789|14569|189|189|1269|") expect(su.debugRow(5)).to.equal("|34|9|8|13|12346|146|5|7|126|") expect(su.debugRow(6)).to.equal("|9|26|26|5|148|7|148|18|3|") expect(su.debugRow(7)).to.equal("|1|3|4|6|89|2|789|89|5|") expect(su.debugRow(8)).to.equal("|5|8|7|139|1349|149|2|6|149|") expect(su.getStructure()).to.equal( "*---*---*---*\n"+ "|843|000|620|\n"+ "|700|403|008|\n"+ "|600|208|007|\n"+ "*---+---+---*\n"+ "|275|000|340|\n"+ "|000|000|000|\n"+ "|098|000|570|\n"+ "*---+---+---*\n"+ "|900|507|003|\n"+ "|134|602|005|\n"+ "|587|000|260|\n"+ "*---*---*---*\n"); done() }) it("pass #04 Basic Pass should show no change in set", function(done){ solve.solvePassBasic(); solve.solvePassBasic(); solve.solvePassBasic(); solve.solvePassBasic(); expect(su.getStructure()).to.equal( "*---*---*---*\n"+ "|843|000|620|\n"+ "|700|403|008|\n"+ "|600|208|007|\n"+ "*---+---+---*\n"+ "|275|000|340|\n"+ "|000|000|000|\n"+ "|098|000|570|\n"+ "*---+---+---*\n"+ "|900|507|003|\n"+ "|134|602|005|\n"+ "|587|000|260|\n"+ "*---*---*---*\n"); done() }) it("pass #05 Region Exclusion", function(done){ solve.solvePassBasic(); solve.solvePassBasic(); solve.solvePassBasic(); solve.solvePassBasic(); solve.solveRegionExclusion(); // ********************************************* // Checks each tiles guesses agenst all other // tiles GUESSES in the same posibility REGION and sets it if there // are no other tiles with that guess in them in // the same region // ********************************************* expect(su.debugRow(0)).to.equal("|8|4|3|179|1579|159|6|2|19|") expect(su.debugRow(1)).to.equal("|7|125|129|4|6|3|19|159|8|") expect(su.debugRow(2)).to.equal("|6|15|19|2|159|8|4|3|7|") expect(su.debugRow(3)).to.equal("|2|7|5|189|1689|169|3|4|169|") expect(su.debugRow(4)).to.equal("|34|16|16|13789|123456789|14569|189|189|1269|") expect(su.debugRow(5)).to.equal("|34|9|8|13|12346|146|5|7|126|") expect(su.debugRow(6)).to.equal("|9|26|26|5|148|7|148|18|3|") expect(su.debugRow(7)).to.equal("|1|3|4|6|89|2|7|89|5|") expect(su.debugRow(8)).to.equal("|5|8|7|139|1349|149|2|6|149|") expect(su.getStructure()).to.equal( "*---*---*---*\n"+ "|843|000|620|\n"+ "|700|463|008|\n"+ "|600|208|437|\n"+ "*---+---+---*\n"+ "|275|000|340|\n"+ "|000|000|000|\n"+ "|098|000|570|\n"+ "*---+---+---*\n"+ "|900|507|003|\n"+ "|134|602|705|\n"+ "|587|000|260|\n"+ "*---*---*---*\n"); done() }) it("pass #06 Basic Pass should show no change in set", function(done){ solve.solvePassBasic(); solve.solvePassBasic(); solve.solvePassBasic(); solve.solvePassBasic(); solve.solveRegionExclusion(); solve.solvePassBasic(); expect(su.debugRow(0)).to.equal("|8|4|3|179|1579|159|6|2|19|") expect(su.debugRow(1)).to.equal("|7|125|129|4|6|3|19|159|8|") expect(su.debugRow(2)).to.equal("|6|15|19|2|159|8|4|3|7|") expect(su.debugRow(3)).to.equal("|2|7|5|189|189|169|3|4|169|") expect(su.debugRow(4)).to.equal("|34|16|16|13789|12345789|14569|189|189|1269|") expect(su.debugRow(5)).to.equal("|34|9|8|13|1234|146|5|7|126|") expect(su.debugRow(6)).to.equal("|9|26|26|5|148|7|18|18|3|") expect(su.debugRow(7)).to.equal("|1|3|4|6|89|2|7|89|5|") expect(su.debugRow(8)).to.equal("|5|8|7|139|1349|149|2|6|149|") expect(su.getStructure()).to.equal( "*---*---*---*\n"+ "|843|000|620|\n"+ "|700|463|008|\n"+ "|600|208|437|\n"+ "*---+---+---*\n"+ "|275|000|340|\n"+ "|000|000|000|\n"+ "|098|000|570|\n"+ "*---+---+---*\n"+ "|900|507|003|\n"+ "|134|602|705|\n"+ "|587|000|260|\n"+ "*---*---*---*\n"); done() }) it("pass #07 Row Exclusion", function(done){ solve.solvePassBasic(); solve.solvePassBasic(); solve.solvePassBasic(); solve.solvePassBasic(); solve.solveRegionExclusion(); solve.solvePassBasic(); solve.solveRowExclusion(); // ********************************************* // Checks each tiles guesses agenst all other // tiles GUESSES in the same posibility ROW and sets it if there // are no other tiles with that guess in them in // the same region // ********************************************* /* row = solve.getSudoku().getRow(6) tile = row.tiles[0]; expect(tile.getToken()).to.equal(tokens.i); expect(tile.getType()).to.equal(tileOBJ.types.locked); tile = row.tiles[1]; expect(tile.getGuess(tokens.a)).to.equal(false); // 1 expect(tile.getGuess(tokens.b)).to.equal(true); // 2 expect(tile.getGuess(tokens.c)).to.equal(false); // 3 expect(tile.getGuess(tokens.d)).to.equal(false); // 4 expect(tile.getGuess(tokens.e)).to.equal(false); // 5 expect(tile.getGuess(tokens.f)).to.equal(true); // 6 expect(tile.getGuess(tokens.g)).to.equal(false); // 7 expect(tile.getGuess(tokens.h)).to.equal(false); // 8 expect(tile.getGuess(tokens.i)).to.equal(false); // 9 tile = row.tiles[2]; expect(tile.getGuess(tokens.a)).to.equal(false); // 1 expect(tile.getGuess(tokens.b)).to.equal(true); // 2 expect(tile.getGuess(tokens.c)).to.equal(false); // 3 expect(tile.getGuess(tokens.d)).to.equal(false); // 4 expect(tile.getGuess(tokens.e)).to.equal(false); // 5 expect(tile.getGuess(tokens.f)).to.equal(true); // 6 expect(tile.getGuess(tokens.g)).to.equal(false); // 7 expect(tile.getGuess(tokens.h)).to.equal(false); // 8 expect(tile.getGuess(tokens.i)).to.equal(false); // 9 tile = row.tiles[3]; expect(tile.getToken()).to.equal(tokens.e); expect(tile.getType()).to.equal(tileOBJ.types.locked); tile = row.tiles[4]; expect(tile.getToken()).to.equal(tokens.d); expect(tile.getType()).to.equal(tileOBJ.types.set); tile = row.tiles[5]; expect(tile.getToken()).to.equal(tokens.g); expect(tile.getType()).to.equal(tileOBJ.types.locked); tile = row.tiles[6]; expect(tile.getGuess(tokens.a)).to.equal(true); // 1 expect(tile.getGuess(tokens.b)).to.equal(false); // 2 expect(tile.getGuess(tokens.c)).to.equal(false); // 3 expect(tile.getGuess(tokens.d)).to.equal(false); // 4 expect(tile.getGuess(tokens.e)).to.equal(false); // 5 expect(tile.getGuess(tokens.f)).to.equal(false); // 6 expect(tile.getGuess(tokens.g)).to.equal(false); // 7 expect(tile.getGuess(tokens.h)).to.equal(true); // 8 expect(tile.getGuess(tokens.i)).to.equal(false); // 9 tile = row.tiles[7]; expect(tile.getGuess(tokens.a)).to.equal(true); // 1 expect(tile.getGuess(tokens.b)).to.equal(false); // 2 expect(tile.getGuess(tokens.c)).to.equal(false); // 3 expect(tile.getGuess(tokens.d)).to.equal(false); // 4 expect(tile.getGuess(tokens.e)).to.equal(false); // 5 expect(tile.getGuess(tokens.f)).to.equal(false); // 6 expect(tile.getGuess(tokens.g)).to.equal(false); // 7 expect(tile.getGuess(tokens.h)).to.equal(true); // 8 expect(tile.getGuess(tokens.i)).to.equal(false); // 9 tile = row.tiles[8]; expect(tile.getToken()).to.equal(tokens.c); expect(tile.getType()).to.equal(tileOBJ.types.locked); */ expect(su.debugRow(0)).to.equal("|8|4|3|179|1579|159|6|2|19|") expect(su.debugRow(1)).to.equal("|7|125|129|4|6|3|19|159|8|") expect(su.debugRow(2)).to.equal("|6|15|19|2|159|8|4|3|7|") expect(su.debugRow(3)).to.equal("|2|7|5|189|189|169|3|4|169|") expect(su.debugRow(4)).to.equal("|34|16|16|13789|12345789|14569|189|189|1269|") expect(su.debugRow(5)).to.equal("|34|9|8|13|1234|146|5|7|126|") expect(su.debugRow(6)).to.equal("|9|26|26|5|4|7|18|18|3|") expect(su.debugRow(7)).to.equal("|1|3|4|6|89|2|7|89|5|") expect(su.debugRow(8)).to.equal("|5|8|7|139|1349|149|2|6|149|") expect(su.getStructure()).to.equal( "*---*---*---*\n"+ "|843|000|620|\n"+ "|700|463|008|\n"+ "|600|208|437|\n"+ "*---+---+---*\n"+ "|275|000|340|\n"+ "|000|000|000|\n"+ "|098|000|570|\n"+ "*---+---+---*\n"+ "|900|547|003|\n"+ "|134|602|705|\n"+ "|587|000|260|\n"+ "*---*---*---*\n"); done() }) it("pass #08 Basic Pass should show no change in set", function(done){ solve.solvePassBasic(); solve.solvePassBasic(); solve.solvePassBasic(); solve.solvePassBasic(); solve.solveRegionExclusion(); solve.solvePassBasic(); solve.solveRowExclusion(); solve.solvePassBasic(); expect(su.debugRow(0)).to.equal("|8|4|3|179|1579|159|6|2|19|") expect(su.debugRow(1)).to.equal("|7|125|129|4|6|3|19|159|8|") expect(su.debugRow(2)).to.equal("|6|15|19|2|159|8|4|3|7|") expect(su.debugRow(3)).to.equal("|2|7|5|189|189|169|3|4|169|") expect(su.debugRow(4)).to.equal("|34|16|16|13789|1235789|14569|189|189|1269|") expect(su.debugRow(5)).to.equal("|34|9|8|13|123|146|5|7|126|") expect(su.debugRow(6)).to.equal("|9|26|26|5|4|7|18|18|3|") expect(su.debugRow(7)).to.equal("|1|3|4|6|89|2|7|89|5|") expect(su.debugRow(8)).to.equal("|5|8|7|139|139|19|2|6|149|") expect(su.getStructure()).to.equal( "*---*---*---*\n"+ "|843|000|620|\n"+ "|700|463|008|\n"+ "|600|208|437|\n"+ "*---+---+---*\n"+ "|275|000|340|\n"+ "|000|000|000|\n"+ "|098|000|570|\n"+ "*---+---+---*\n"+ "|900|547|003|\n"+ "|134|602|705|\n"+ "|587|000|260|\n"+ "*---*---*---*\n"); done() }) it("pass #09 Col Exclusion", function(done){ solve.solvePassBasic(); solve.solvePassBasic(); solve.solvePassBasic(); solve.solvePassBasic(); solve.solveRegionExclusion(); solve.solvePassBasic(); solve.solveRowExclusion(); solve.solvePassBasic(); solve.solveColExclusion(); // ********************************************* // Checks each tiles guesses agenst all other // tiles GUESSES in the same posibility COL and sets it if there // are no other tiles with that guess in them in // the same region // ********************************************* expect(su.debugRow(0)).to.equal("|8|4|3|179|1579|159|6|2|19|") expect(su.debugRow(1)).to.equal("|7|125|129|4|6|3|19|5|8|") expect(su.debugRow(2)).to.equal("|6|15|19|2|159|8|4|3|7|") expect(su.debugRow(3)).to.equal("|2|7|5|189|189|169|3|4|169|") expect(su.debugRow(4)).to.equal("|34|16|16|13789|1235789|14569|189|189|1269|") expect(su.debugRow(5)).to.equal("|34|9|8|13|123|146|5|7|126|") expect(su.debugRow(6)).to.equal("|9|26|26|5|4|7|18|18|3|") expect(su.debugRow(7)).to.equal("|1|3|4|6|89|2|7|89|5|") expect(su.debugRow(8)).to.equal("|5|8|7|139|139|19|2|6|4|") expect(su.getStructure()).to.equal( "*---*---*---*\n"+ "|843|000|620|\n"+ "|700|463|058|\n"+ "|600|208|437|\n"+ "*---+---+---*\n"+ "|275|000|340|\n"+ "|000|000|000|\n"+ "|098|000|570|\n"+ "*---+---+---*\n"+ "|900|547|003|\n"+ "|134|602|705|\n"+ "|587|000|264|\n"+ "*---*---*---*\n"); done() }) /* Don't need to run these most of the time it("pass #10 Basic Pass should show no change in set", function(done){ solve.solvePassBasic(); solve.solvePassBasic(); solve.solvePassBasic(); solve.solvePassBasic(); solve.solveRegionExclusion(); solve.solvePassBasic(); solve.solveRowExclusion(); solve.solvePassBasic(); solve.solveColExclusion(); solve.solvePassBasic(); expect(su.debugRow(0)).to.equal("|8|4|3|179|1579|159|6|2|19|") expect(su.debugRow(1)).to.equal("|7|12|129|4|6|3|19|5|8|") expect(su.debugRow(2)).to.equal("|6|15|19|2|159|8|4|3|7|") expect(su.debugRow(3)).to.equal("|2|7|5|189|189|169|3|4|169|") expect(su.debugRow(4)).to.equal("|34|16|16|13789|1235789|14569|189|189|1269|") expect(su.debugRow(5)).to.equal("|34|9|8|13|123|146|5|7|126|") expect(su.debugRow(6)).to.equal("|9|26|26|5|4|7|18|18|3|") expect(su.debugRow(7)).to.equal("|1|3|4|6|89|2|7|89|5|") expect(su.debugRow(8)).to.equal("|5|8|7|139|139|19|2|6|4|") expect(su.getStructure()).to.equal( "*---*---*---*\n"+ "|843|000|620|\n"+ "|700|463|058|\n"+ "|600|208|437|\n"+ "*---+---+---*\n"+ "|275|000|340|\n"+ "|000|000|000|\n"+ "|098|000|570|\n"+ "*---+---+---*\n"+ "|900|547|003|\n"+ "|134|602|705|\n"+ "|587|000|264|\n"+ "*---*---*---*\n"); done() }) ////////// it("pass #11 region Exclusion", function(done){ solve.solvePassBasic(); solve.solvePassBasic(); solve.solvePassBasic(); solve.solvePassBasic(); solve.solveRegionExclusion(); solve.solvePassBasic(); solve.solveRowExclusion(); solve.solvePassBasic(); solve.solveColExclusion(); solve.solvePassBasic(); solve.solveRegionExclusion(); expect(su.debugRow(0)).to.equal("|8|4|3|179|1579|159|6|2|19|") expect(su.debugRow(1)).to.equal("|7|12|129|4|6|3|19|5|8|") expect(su.debugRow(2)).to.equal("|6|5|19|2|159|8|4|3|7|") expect(su.debugRow(3)).to.equal("|2|7|5|189|189|169|3|4|169|") expect(su.debugRow(4)).to.equal("|34|16|16|13789|1235789|14569|189|189|1269|") expect(su.debugRow(5)).to.equal("|34|9|8|13|123|146|5|7|126|") expect(su.debugRow(6)).to.equal("|9|26|26|5|4|7|18|18|3|") expect(su.debugRow(7)).to.equal("|1|3|4|6|8|2|7|9|5|") expect(su.debugRow(8)).to.equal("|5|8|7|139|139|19|2|6|4|") expect(su.getStructure()).to.equal( "*---*---*---*\n"+ "|843|000|620|\n"+ "|700|463|058|\n"+ "|650|208|437|\n"+ "*---+---+---*\n"+ "|275|000|340|\n"+ "|000|000|000|\n"+ "|098|000|570|\n"+ "*---+---+---*\n"+ "|900|547|003|\n"+ "|134|682|795|\n"+ "|587|000|264|\n"+ "*---*---*---*\n"); done() }) it("pass #12 Basic Pass should show no change in set", function(done){ solve.solvePassBasic(); solve.solvePassBasic(); solve.solvePassBasic(); solve.solvePassBasic(); solve.solveRegionExclusion(); solve.solvePassBasic(); solve.solveRowExclusion(); solve.solvePassBasic(); solve.solveColExclusion(); solve.solvePassBasic(); solve.solveRegionExclusion(); solve.solvePassBasic(); expect(su.debugRow(0)).to.equal("|8|4|3|179|1579|159|6|2|19|") expect(su.debugRow(1)).to.equal("|7|12|129|4|6|3|19|5|8|") expect(su.debugRow(2)).to.equal("|6|5|19|2|19|8|4|3|7|") expect(su.debugRow(3)).to.equal("|2|7|5|189|19|169|3|4|169|") expect(su.debugRow(4)).to.equal("|34|16|16|13789|123579|14569|189|18|1269|") expect(su.debugRow(5)).to.equal("|34|9|8|13|123|146|5|7|126|") expect(su.debugRow(6)).to.equal("|9|26|26|5|4|7|18|18|3|") expect(su.debugRow(7)).to.equal("|1|3|4|6|8|2|7|9|5|") expect(su.debugRow(8)).to.equal("|5|8|7|139|139|19|2|6|4|") expect(su.getStructure()).to.equal( "*---*---*---*\n"+ "|843|000|620|\n"+ "|700|463|058|\n"+ "|650|208|437|\n"+ "*---+---+---*\n"+ "|275|000|340|\n"+ "|000|000|000|\n"+ "|098|000|570|\n"+ "*---+---+---*\n"+ "|900|547|003|\n"+ "|134|682|795|\n"+ "|587|000|264|\n"+ "*---*---*---*\n"); done() }) it("pass #13 row Exclusion", function(done){ solve.solvePassBasic(); solve.solvePassBasic(); solve.solvePassBasic(); solve.solvePassBasic(); solve.solveRegionExclusion(); solve.solvePassBasic(); solve.solveRowExclusion(); solve.solvePassBasic(); solve.solveColExclusion(); solve.solvePassBasic(); solve.solveRegionExclusion(); solve.solvePassBasic(); solve.solveRowExclusion(); expect(su.debugRow(0)).to.equal("|8|4|3|179|1579|159|6|2|19|") expect(su.debugRow(1)).to.equal("|7|12|129|4|6|3|19|5|8|") expect(su.debugRow(2)).to.equal("|6|5|19|2|19|8|4|3|7|") expect(su.debugRow(3)).to.equal("|2|7|5|8|19|169|3|4|169|") expect(su.debugRow(4)).to.equal("|34|16|16|13789|123579|14569|189|18|1269|") expect(su.debugRow(5)).to.equal("|34|9|8|13|123|146|5|7|126|") expect(su.debugRow(6)).to.equal("|9|26|26|5|4|7|18|18|3|") expect(su.debugRow(7)).to.equal("|1|3|4|6|8|2|7|9|5|") expect(su.debugRow(8)).to.equal("|5|8|7|139|139|19|2|6|4|") expect(su.getStructure()).to.equal( "*---*---*---*\n"+ "|843|000|620|\n"+ "|700|463|058|\n"+ "|650|208|437|\n"+ "*---+---+---*\n"+ "|275|800|340|\n"+ "|000|000|000|\n"+ "|098|000|570|\n"+ "*---+---+---*\n"+ "|900|547|003|\n"+ "|134|682|795|\n"+ "|587|000|264|\n"+ "*---*---*---*\n"); done() }) it("pass #14 Basic Pass", function(done){ solve.solvePassBasic(); solve.solvePassBasic(); solve.solvePassBasic(); solve.solvePassBasic(); solve.solveRegionExclusion(); solve.solvePassBasic(); solve.solveRowExclusion(); solve.solvePassBasic(); solve.solveColExclusion(); solve.solvePassBasic(); solve.solveRegionExclusion(); solve.solvePassBasic(); solve.solveRowExclusion(); solve.solvePassBasic(); expect(su.debugRow(0)).to.equal("|8|4|3|179|1579|159|6|2|19|") expect(su.debugRow(1)).to.equal("|7|12|129|4|6|3|19|5|8|") expect(su.debugRow(2)).to.equal("|6|5|19|2|19|8|4|3|7|") expect(su.debugRow(3)).to.equal("|2|7|5|8|19|169|3|4|169|") expect(su.debugRow(4)).to.equal("|34|16|16|1379|123579|14569|189|18|1269|") expect(su.debugRow(5)).to.equal("|34|9|8|13|123|146|5|7|126|") expect(su.debugRow(6)).to.equal("|9|26|26|5|4|7|18|18|3|") expect(su.debugRow(7)).to.equal("|1|3|4|6|8|2|7|9|5|") expect(su.debugRow(8)).to.equal("|5|8|7|139|139|19|2|6|4|") expect(su.getStructure()).to.equal( "*---*---*---*\n"+ "|843|000|620|\n"+ "|700|463|058|\n"+ "|650|208|437|\n"+ "*---+---+---*\n"+ "|275|800|340|\n"+ "|000|000|000|\n"+ "|098|000|570|\n"+ "*---+---+---*\n"+ "|900|547|003|\n"+ "|134|682|795|\n"+ "|587|000|264|\n"+ "*---*---*---*\n"); done() }) it("pass #15 Basic Pass should show no change in set", function(done){ solve.solvePassBasic(); solve.solvePassBasic(); solve.solvePassBasic(); solve.solvePassBasic(); solve.solveRegionExclusion(); solve.solvePassBasic(); solve.solveRowExclusion(); solve.solvePassBasic(); solve.solveColExclusion(); solve.solvePassBasic(); solve.solveRegionExclusion(); solve.solvePassBasic(); solve.solveRowExclusion(); solve.solvePassBasic(); solve.solvePassBasic(); expect(su.debugRow(0)).to.equal("|8|4|3|179|1579|159|6|2|19|") expect(su.debugRow(1)).to.equal("|7|12|129|4|6|3|19|5|8|") expect(su.debugRow(2)).to.equal("|6|5|19|2|19|8|4|3|7|") expect(su.debugRow(3)).to.equal("|2|7|5|8|19|169|3|4|169|") expect(su.debugRow(4)).to.equal("|34|16|16|1379|123579|14569|189|18|1269|") expect(su.debugRow(5)).to.equal("|34|9|8|13|123|146|5|7|126|") expect(su.debugRow(6)).to.equal("|9|26|26|5|4|7|18|18|3|") expect(su.debugRow(7)).to.equal("|1|3|4|6|8|2|7|9|5|") expect(su.debugRow(8)).to.equal("|5|8|7|139|139|19|2|6|4|") expect(su.getStructure()).to.equal( "*---*---*---*\n"+ "|843|000|620|\n"+ "|700|463|058|\n"+ "|650|208|437|\n"+ "*---+---+---*\n"+ "|275|800|340|\n"+ "|000|000|000|\n"+ "|098|000|570|\n"+ "*---+---+---*\n"+ "|900|547|003|\n"+ "|134|682|795|\n"+ "|587|000|264|\n"+ "*---*---*---*\n"); done() }) it("pass #16 simple is stuck", function(done){ solve.solvePassBasic(); solve.solvePassBasic(); solve.solvePassBasic(); solve.solvePassBasic(); //No change start simple solve.solveRegionExclusion(); solve.solvePassBasic(); solve.solveRowExclusion(); solve.solvePassBasic(); solve.solveColExclusion(); solve.solvePassBasic(); //first run finished trying again solve.solveRegionExclusion(); solve.solvePassBasic(); solve.solveRowExclusion(); solve.solvePassBasic(); solve.solvePassBasic(); solve.solveColExclusion(); //No Change solve.solvePassBasic(); //No change running simple one more time solve.solveRegionExclusion(); solve.solvePassBasic(); solve.solveRowExclusion(); solve.solvePassBasic(); solve.solveColExclusion(); expect(su.debugRow(0)).to.equal("|8|4|3|179|1579|159|6|2|19|") expect(su.debugRow(1)).to.equal("|7|12|129|4|6|3|19|5|8|") expect(su.debugRow(2)).to.equal("|6|5|19|2|19|8|4|3|7|") expect(su.debugRow(3)).to.equal("|2|7|5|8|19|169|3|4|169|") expect(su.debugRow(4)).to.equal("|34|16|16|1379|123579|14569|189|18|1269|") expect(su.debugRow(5)).to.equal("|34|9|8|13|123|146|5|7|126|") expect(su.debugRow(6)).to.equal("|9|26|26|5|4|7|18|18|3|") expect(su.debugRow(7)).to.equal("|1|3|4|6|8|2|7|9|5|") expect(su.debugRow(8)).to.equal("|5|8|7|139|139|19|2|6|4|") expect(su.getStructure()).to.equal( "*---*---*---*\n"+ "|843|000|620|\n"+ "|700|463|058|\n"+ "|650|208|437|\n"+ "*---+---+---*\n"+ "|275|800|340|\n"+ "|000|000|000|\n"+ "|098|000|570|\n"+ "*---+---+---*\n"+ "|900|547|003|\n"+ "|134|682|795|\n"+ "|587|000|264|\n"+ "*---*---*---*\n"); done() }) it("pass #17.a run pairs pass", function(done){ solve.solvePassBasic(); solve.solvePassBasic(); solve.solvePassBasic(); solve.solvePassBasic(); solve.solveRegionExclusion(); solve.solvePassBasic(); solve.solveRowExclusion(); solve.solvePassBasic(); solve.solveColExclusion(); solve.solvePassBasic(); solve.solveRegionExclusion(); solve.solvePassBasic(); solve.solveRowExclusion(); solve.solvePassBasic(); solve.solvePassBasic(); solve.solveColExclusion(); solve.solveRegionExclusion(); solve.checkPairsRow() expect(su.debugRow(0)).to.equal("|8|4|3|179|1579|159|6|2|19|") expect(su.debugRow(1)).to.equal("|7|12|129|4|6|3|19|5|8|") expect(su.debugRow(2)).to.equal("|6|5|19|2|19|8|4|3|7|") expect(su.debugRow(3)).to.equal("|2|7|5|8|19|169|3|4|169|") expect(su.debugRow(4)).to.equal("|34|16|16|379|23579|459|89|8|29|") expect(su.debugRow(5)).to.equal("|34|9|8|13|123|146|5|7|126|") expect(su.debugRow(6)).to.equal("|9|26|26|5|4|7|18|18|3|") expect(su.debugRow(7)).to.equal("|1|3|4|6|8|2|7|9|5|") expect(su.debugRow(8)).to.equal("|5|8|7|139|139|19|2|6|4|") expect(su.getStructure()).to.equal( "*---*---*---*\n"+ "|843|000|620|\n"+ "|700|463|058|\n"+ "|650|208|437|\n"+ "*---+---+---*\n"+ "|275|800|340|\n"+ "|000|000|000|\n"+ "|098|000|570|\n"+ "*---+---+---*\n"+ "|900|547|003|\n"+ "|134|682|795|\n"+ "|587|000|264|\n"+ "*---*---*---*\n"); done() }) it("pass #17.b run pairs pass", function(done){ solve.solvePassBasic(); solve.solvePassBasic(); solve.solvePassBasic(); solve.solvePassBasic(); solve.solveRegionExclusion(); solve.solvePassBasic(); solve.solveRowExclusion(); solve.solvePassBasic(); solve.solveColExclusion(); solve.solvePassBasic(); solve.solveRegionExclusion(); solve.solvePassBasic(); solve.solveRowExclusion(); solve.solvePassBasic(); solve.solvePassBasic(); solve.solveColExclusion(); solve.solveRegionExclusion(); solve.checkPairsRow(); solve.checkPairsCol(); expect(su.debugCol(0)).to.equal("|8|7|6|2|34|34|9|1|5|") expect(su.debugCol(1)).to.equal("|4|12|5|7|16|9|26|3|8|") expect(su.debugCol(2)).to.equal("|3|129|19|5|16|8|26|4|7|") expect(su.debugCol(3)).to.equal("|179|4|2|8|379|13|5|6|139|") expect(su.debugCol(4)).to.equal("|57|6|19|19|2357|23|4|8|3|") expect(su.debugCol(5)).to.equal("|159|3|8|169|459|146|7|2|19|") expect(su.debugCol(6)).to.equal("|6|19|4|3|89|5|18|7|2|") expect(su.debugCol(7)).to.equal("|2|5|3|4|8|7|18|9|6|") expect(su.debugCol(8)).to.equal("|19|8|7|169|29|126|3|5|4|") expect(su.getStructure()).to.equal( "*---*---*---*\n"+ "|843|000|620|\n"+ "|700|463|058|\n"+ "|650|208|437|\n"+ "*---+---+---*\n"+ "|275|800|340|\n"+ "|000|000|000|\n"+ "|098|000|570|\n"+ "*---+---+---*\n"+ "|900|547|003|\n"+ "|134|682|795|\n"+ "|587|000|264|\n"+ "*---*---*---*\n"); done() }) it("pass #17.c run pairs pass", function(done){ solve.solvePassBasic(); solve.solvePassBasic(); solve.solvePassBasic(); solve.solvePassBasic(); solve.solveRegionExclusion(); solve.solvePassBasic(); solve.solveRowExclusion(); solve.solvePassBasic(); solve.solveColExclusion(); solve.solvePassBasic(); solve.solveRegionExclusion(); solve.solvePassBasic(); solve.solveRowExclusion(); solve.solvePassBasic(); solve.solvePassBasic(); solve.solveColExclusion(); solve.solveRegionExclusion(); solve.checkPairsRow() solve.checkPairsCol() solve.checkPairsRegion() expect(su.getStructure()).to.equal( "*---*---*---*\n"+ "|843|000|620|\n"+ "|700|463|058|\n"+ "|650|208|437|\n"+ "*---+---+---*\n"+ "|275|800|340|\n"+ "|000|000|000|\n"+ "|098|000|570|\n"+ "*---+---+---*\n"+ "|900|547|003|\n"+ "|134|682|795|\n"+ "|587|000|264|\n"+ "*---*---*---*\n"); done() }) */ it("pass #17 run pairs pass", function(done){ solve.solvePassBasic(); solve.solvePassBasic(); solve.solvePassBasic(); solve.solvePassBasic(); solve.solveRegionExclusion(); solve.solvePassBasic(); solve.solveRowExclusion(); solve.solvePassBasic(); solve.solveColExclusion(); solve.solvePassBasic(); solve.solveRegionExclusion(); solve.solvePassBasic(); solve.solveRowExclusion(); solve.solvePassBasic(); solve.solvePassBasic(); solve.solveColExclusion(); solve.solveRegionExclusion(); solve.checkPairs() expect(su.debugRow(0)).to.equal("|8|4|3|179|57|159|6|2|19|") expect(su.debugRow(1)).to.equal("|7|12|129|4|6|3|19|5|8|") expect(su.debugRow(2)).to.equal("|6|5|19|2|19|8|4|3|7|") expect(su.debugRow(3)).to.equal("|2|7|5|8|19|169|3|4|169|") expect(su.debugRow(4)).to.equal("|34|16|16|379|2357|459|89|8|29|") expect(su.debugRow(5)).to.equal("|34|9|8|13|23|146|5|7|126|") expect(su.debugRow(6)).to.equal("|9|26|26|5|4|7|18|18|3|") expect(su.debugRow(7)).to.equal("|1|3|4|6|8|2|7|9|5|") expect(su.debugRow(8)).to.equal("|5|8|7|139|3|19|2|6|4|") expect(su.getStructure()).to.equal( "*---*---*---*\n"+ "|843|000|620|\n"+ "|700|463|058|\n"+ "|650|208|437|\n"+ "*---+---+---*\n"+ "|275|800|340|\n"+ "|000|000|000|\n"+ "|098|000|570|\n"+ "*---+---+---*\n"+ "|900|547|003|\n"+ "|134|682|795|\n"+ "|587|000|264|\n"+ "*---*---*---*\n"); done() }) /* Don't need to run these most of the time it("pass #18 Basic Pass", function(done){ solve.solvePassBasic(); solve.solvePassBasic(); solve.solvePassBasic(); solve.solvePassBasic(); solve.solveRegionExclusion(); solve.solvePassBasic(); solve.solveRowExclusion(); solve.solvePassBasic(); solve.solveColExclusion(); solve.solvePassBasic(); solve.solveRegionExclusion(); solve.solvePassBasic(); solve.solveRowExclusion(); solve.solvePassBasic(); solve.solvePassBasic(); solve.solveColExclusion(); solve.solveRegionExclusion(); solve.checkPairs(); solve.solvePassBasic(); expect(su.debugRow(0)).to.equal("|8|4|3|179|57|159|6|2|19|") expect(su.debugRow(1)).to.equal("|7|12|129|4|6|3|19|5|8|") expect(su.debugRow(2)).to.equal("|6|5|19|2|19|8|4|3|7|") expect(su.debugRow(3)).to.equal("|2|7|5|8|19|169|3|4|169|") expect(su.debugRow(4)).to.equal("|34|16|16|379|2357|459|89|8|29|") expect(su.debugRow(5)).to.equal("|34|9|8|13|23|146|5|7|126|") expect(su.debugRow(6)).to.equal("|9|26|26|5|4|7|18|18|3|") expect(su.debugRow(7)).to.equal("|1|3|4|6|8|2|7|9|5|") expect(su.debugRow(8)).to.equal("|5|8|7|139|3|19|2|6|4|") expect(su.getStructure()).to.equal( "*---*---*---*\n"+ "|843|000|620|\n"+ "|700|463|058|\n"+ "|650|208|437|\n"+ "*---+---+---*\n"+ "|275|800|340|\n"+ "|000|000|080|\n"+ "|098|000|570|\n"+ "*---+---+---*\n"+ "|900|547|003|\n"+ "|134|682|795|\n"+ "|587|030|264|\n"+ "*---*---*---*\n"); done() }) it("pass #19 Basic Pass", function(done){ solve.solvePassBasic(); solve.solvePassBasic(); solve.solvePassBasic(); solve.solvePassBasic(); solve.solveRegionExclusion(); solve.solvePassBasic(); solve.solveRowExclusion(); solve.solvePassBasic(); solve.solveColExclusion(); solve.solvePassBasic(); solve.solveRegionExclusion(); solve.solvePassBasic(); solve.solveRowExclusion(); solve.solvePassBasic(); solve.solvePassBasic(); solve.solveColExclusion(); solve.solveRegionExclusion(); solve.checkPairs(); solve.solvePassBasic(); solve.solvePassBasic(); expect(su.debugRow(0)).to.equal("|8|4|3|179|57|159|6|2|19|") expect(su.debugRow(1)).to.equal("|7|12|129|4|6|3|19|5|8|") expect(su.debugRow(2)).to.equal("|6|5|19|2|19|8|4|3|7|") expect(su.debugRow(3)).to.equal("|2|7|5|8|19|169|3|4|169|") expect(su.debugRow(4)).to.equal("|34|16|16|379|257|459|9|8|29|") expect(su.debugRow(5)).to.equal("|34|9|8|13|2|146|5|7|126|") expect(su.debugRow(6)).to.equal("|9|26|26|5|4|7|18|1|3|") expect(su.debugRow(7)).to.equal("|1|3|4|6|8|2|7|9|5|") expect(su.debugRow(8)).to.equal("|5|8|7|19|3|19|2|6|4|") expect(su.getStructure()).to.equal( "*---*---*---*\n"+ "|843|000|620|\n"+ "|700|463|058|\n"+ "|650|208|437|\n"+ "*---+---+---*\n"+ "|275|800|340|\n"+ "|000|000|980|\n"+ "|098|020|570|\n"+ "*---+---+---*\n"+ "|900|547|013|\n"+ "|134|682|795|\n"+ "|587|030|264|\n"+ "*---*---*---*\n"); done() }) it("pass #20 Basic Pass", function(done){ solve.solvePassBasic(); solve.solvePassBasic(); solve.solvePassBasic(); solve.solvePassBasic(); solve.solveRegionExclusion(); solve.solvePassBasic(); solve.solveRowExclusion(); solve.solvePassBasic(); solve.solveColExclusion(); solve.solvePassBasic(); solve.solveRegionExclusion(); solve.solvePassBasic(); solve.solveRowExclusion(); solve.solvePassBasic(); solve.solvePassBasic(); solve.solveColExclusion(); solve.solveRegionExclusion(); solve.checkPairs(); solve.solvePassBasic(); solve.solvePassBasic(); solve.solvePassBasic(); expect(su.debugRow(0)).to.equal("|8|4|3|179|57|159|6|2|19|") expect(su.debugRow(1)).to.equal("|7|12|129|4|6|3|1|5|8|") expect(su.debugRow(2)).to.equal("|6|5|19|2|19|8|4|3|7|") expect(su.debugRow(3)).to.equal("|2|7|5|8|19|169|3|4|16|") expect(su.debugRow(4)).to.equal("|34|16|16|37|57|45|9|8|2|") expect(su.debugRow(5)).to.equal("|34|9|8|13|2|146|5|7|16|") expect(su.debugRow(6)).to.equal("|9|26|26|5|4|7|8|1|3|") expect(su.debugRow(7)).to.equal("|1|3|4|6|8|2|7|9|5|") expect(su.debugRow(8)).to.equal("|5|8|7|19|3|19|2|6|4|") expect(su.getStructure()).to.equal( "*---*---*---*\n"+ "|843|000|620|\n"+ "|700|463|158|\n"+ "|650|208|437|\n"+ "*---+---+---*\n"+ "|275|800|340|\n"+ "|000|000|982|\n"+ "|098|020|570|\n"+ "*---+---+---*\n"+ "|900|547|813|\n"+ "|134|682|795|\n"+ "|587|030|264|\n"+ "*---*---*---*\n"); done() }) it("pass #21 Basic Pass should show no change in set", function(done){ solve.solvePassBasic(); solve.solvePassBasic(); solve.solvePassBasic(); solve.solvePassBasic(); solve.solveRegionExclusion(); solve.solvePassBasic(); solve.solveRowExclusion(); solve.solvePassBasic(); solve.solveColExclusion(); solve.solvePassBasic(); solve.solveRegionExclusion(); solve.solvePassBasic(); solve.solveRowExclusion(); solve.solvePassBasic(); solve.solvePassBasic(); solve.solveColExclusion(); solve.solveRegionExclusion(); solve.checkPairs(); solve.solvePassBasic(); solve.solvePassBasic(); solve.solvePassBasic(); solve.solvePassBasic(); expect(su.debugRow(0)).to.equal("|8|4|3|179|57|159|6|2|9|") expect(su.debugRow(1)).to.equal("|7|2|29|4|6|3|1|5|8|") expect(su.debugRow(2)).to.equal("|6|5|19|2|19|8|4|3|7|") expect(su.debugRow(3)).to.equal("|2|7|5|8|19|169|3|4|16|") expect(su.debugRow(4)).to.equal("|34|16|16|37|57|45|9|8|2|") expect(su.debugRow(5)).to.equal("|34|9|8|13|2|146|5|7|16|") expect(su.debugRow(6)).to.equal("|9|26|26|5|4|7|8|1|3|") expect(su.debugRow(7)).to.equal("|1|3|4|6|8|2|7|9|5|") expect(su.debugRow(8)).to.equal("|5|8|7|19|3|19|2|6|4|") expect(su.getStructure()).to.equal( "*---*---*---*\n"+ "|843|000|629|\n"+ "|720|463|158|\n"+ "|650|208|437|\n"+ "*---+---+---*\n"+ "|275|800|340|\n"+ "|000|000|982|\n"+ "|098|020|570|\n"+ "*---+---+---*\n"+ "|900|547|813|\n"+ "|134|682|795|\n"+ "|587|030|264|\n"+ "*---*---*---*\n"); done() }) it("pass #22 Basic Pass should show no change in set", function(done){ solve.solvePassBasic(); solve.solvePassBasic(); solve.solvePassBasic(); solve.solvePassBasic(); solve.solveRegionExclusion(); solve.solvePassBasic(); solve.solveRowExclusion(); solve.solvePassBasic(); solve.solveColExclusion(); solve.solvePassBasic(); solve.solveRegionExclusion(); solve.solvePassBasic(); solve.solveRowExclusion(); solve.solvePassBasic(); solve.solvePassBasic(); solve.solveColExclusion(); solve.solveRegionExclusion(); solve.checkPairs(); solve.solvePassBasic(); solve.solvePassBasic(); solve.solvePassBasic(); solve.solvePassBasic(); solve.solvePassBasic(); expect(su.getStructure()).to.equal( "*---*---*---*\n"+ "|843|000|629|\n"+ "|729|463|158|\n"+ "|650|208|437|\n"+ "*---+---+---*\n"+ "|275|800|340|\n"+ "|000|000|982|\n"+ "|098|020|570|\n"+ "*---+---+---*\n"+ "|960|547|813|\n"+ "|134|682|795|\n"+ "|587|030|264|\n"+ "*---*---*---*\n"); done() }) it("pass #23 Basic Pass should show no change in set", function(done){ solve.solvePassBasic(); solve.solvePassBasic(); solve.solvePassBasic(); solve.solvePassBasic(); solve.solveRegionExclusion(); solve.solvePassBasic(); solve.solveRowExclusion(); solve.solvePassBasic(); solve.solveColExclusion(); solve.solvePassBasic(); solve.solveRegionExclusion(); solve.solvePassBasic(); solve.solveRowExclusion(); solve.solvePassBasic(); solve.solvePassBasic(); solve.solveColExclusion(); solve.solveRegionExclusion(); solve.checkPairs(); solve.solvePassBasic(); solve.solvePassBasic(); solve.solvePassBasic(); solve.solvePassBasic(); solve.solvePassBasic(); solve.solvePassBasic(); expect(su.getStructure()).to.equal( "*---*---*---*\n"+ "|843|000|629|\n"+ "|729|463|158|\n"+ "|651|208|437|\n"+ "*---+---+---*\n"+ "|275|800|340|\n"+ "|010|000|982|\n"+ "|098|020|570|\n"+ "*---+---+---*\n"+ "|962|547|813|\n"+ "|134|682|795|\n"+ "|587|030|264|\n"+ "*---*---*---*\n"); done() }) it("pass #24 Basic Pass should show no change in set", function(done){ solve.solvePassBasic(); solve.solvePassBasic(); solve.solvePassBasic(); solve.solvePassBasic(); solve.solveRegionExclusion(); solve.solvePassBasic(); solve.solveRowExclusion(); solve.solvePassBasic(); solve.solveColExclusion(); solve.solvePassBasic(); solve.solveRegionExclusion(); solve.solvePassBasic(); solve.solveRowExclusion(); solve.solvePassBasic(); solve.solvePassBasic(); solve.solveColExclusion(); solve.solveRegionExclusion(); solve.checkPairs(); solve.solvePassBasic(); solve.solvePassBasic(); solve.solvePassBasic(); solve.solvePassBasic(); solve.solvePassBasic(); solve.solvePassBasic(); solve.solvePassBasic(); expect(su.getStructure()).to.equal( "*---*---*---*\n"+ "|843|000|629|\n"+ "|729|463|158|\n"+ "|651|298|437|\n"+ "*---+---+---*\n"+ "|275|800|340|\n"+ "|016|000|982|\n"+ "|098|020|570|\n"+ "*---+---+---*\n"+ "|962|547|813|\n"+ "|134|682|795|\n"+ "|587|030|264|\n"+ "*---*---*---*\n"); done() }) it("pass #25 Basic Pass should show no change in set", function(done){ solve.solvePassBasic(); solve.solvePassBasic(); solve.solvePassBasic(); solve.solvePassBasic(); solve.solveRegionExclusion(); solve.solvePassBasic(); solve.solveRowExclusion(); solve.solvePassBasic(); solve.solveColExclusion(); solve.solvePassBasic(); solve.solveRegionExclusion(); solve.solvePassBasic(); solve.solveRowExclusion(); solve.solvePassBasic(); solve.solvePassBasic(); solve.solveColExclusion(); solve.solveRegionExclusion(); solve.checkPairs(); solve.solvePassBasic(); solve.solvePassBasic(); solve.solvePassBasic(); solve.solvePassBasic(); solve.solvePassBasic(); solve.solvePassBasic(); solve.solvePassBasic(); solve.solvePassBasic(); expect(su.getStructure()).to.equal( "*---*---*---*\n"+ "|843|000|629|\n"+ "|729|463|158|\n"+ "|651|298|437|\n"+ "*---+---+---*\n"+ "|275|810|340|\n"+ "|016|000|982|\n"+ "|098|020|570|\n"+ "*---+---+---*\n"+ "|962|547|813|\n"+ "|134|682|795|\n"+ "|587|030|264|\n"+ "*---*---*---*\n"); done() }) it("pass #26 Basic Pass should show no change in set", function(done){ solve.solvePassBasic(); solve.solvePassBasic(); solve.solvePassBasic(); solve.solvePassBasic(); solve.solveRegionExclusion(); solve.solvePassBasic(); solve.solveRowExclusion(); solve.solvePassBasic(); solve.solveColExclusion(); solve.solvePassBasic(); solve.solveRegionExclusion(); solve.solvePassBasic(); solve.solveRowExclusion(); solve.solvePassBasic(); solve.solvePassBasic(); solve.solveColExclusion(); solve.solveRegionExclusion(); solve.checkPairs(); solve.solvePassBasic(); solve.solvePassBasic(); solve.solvePassBasic(); solve.solvePassBasic(); solve.solvePassBasic(); solve.solvePassBasic(); solve.solvePassBasic(); solve.solvePassBasic(); solve.solvePassBasic(); expect(su.getStructure()).to.equal( "*---*---*---*\n"+ "|843|000|629|\n"+ "|729|463|158|\n"+ "|651|298|437|\n"+ "*---+---+---*\n"+ "|275|810|346|\n"+ "|016|000|982|\n"+ "|098|320|570|\n"+ "*---+---+---*\n"+ "|962|547|813|\n"+ "|134|682|795|\n"+ "|587|030|264|\n"+ "*---*---*---*\n"); done() }) it("pass #27 Basic Pass should show no change in set", function(done){ solve.solvePassBasic(); solve.solvePassBasic(); solve.solvePassBasic(); solve.solvePassBasic(); solve.solveRegionExclusion(); solve.solvePassBasic(); solve.solveRowExclusion(); solve.solvePassBasic(); solve.solveColExclusion(); solve.solvePassBasic(); solve.solveRegionExclusion(); solve.solvePassBasic(); solve.solveRowExclusion(); solve.solvePassBasic(); solve.solvePassBasic(); solve.solveColExclusion(); solve.solveRegionExclusion(); solve.checkPairs(); solve.solvePassBasic(); solve.solvePassBasic(); solve.solvePassBasic(); solve.solvePassBasic(); solve.solvePassBasic(); solve.solvePassBasic(); solve.solvePassBasic(); solve.solvePassBasic(); solve.solvePassBasic(); solve.solvePassBasic(); expect(su.getStructure()).to.equal( "*---*---*---*\n"+ "|843|000|629|\n"+ "|729|463|158|\n"+ "|651|298|437|\n"+ "*---+---+---*\n"+ "|275|819|346|\n"+ "|016|700|982|\n"+ "|498|320|571|\n"+ "*---+---+---*\n"+ "|962|547|813|\n"+ "|134|682|795|\n"+ "|587|030|264|\n"+ "*---*---*---*\n"); done() }) */ it("pass #28 Basic Pass should show no change in set", function(done){ solve.solvePassBasic(); solve.solvePassBasic(); solve.solvePassBasic(); solve.solvePassBasic(); solve.solveRegionExclusion(); solve.solvePassBasic(); solve.solveRowExclusion(); solve.solvePassBasic(); solve.solveColExclusion(); solve.solvePassBasic(); solve.solveRegionExclusion(); solve.solvePassBasic(); solve.solveRowExclusion(); solve.solvePassBasic(); solve.solvePassBasic(); solve.solveColExclusion(); solve.solveRegionExclusion(); solve.checkPairs(); solve.solvePassBasic(); solve.solvePassBasic(); solve.solvePassBasic(); solve.solvePassBasic(); solve.solvePassBasic(); solve.solvePassBasic(); solve.solvePassBasic(); solve.solvePassBasic(); solve.solvePassBasic(); solve.solvePassBasic(); solve.solvePassBasic(); expect(su.getStructure()).to.equal( "*---*---*---*\n"+ "|843|100|629|\n"+ "|729|463|158|\n"+ "|651|298|437|\n"+ "*---+---+---*\n"+ "|275|819|346|\n"+ "|316|750|982|\n"+ "|498|326|571|\n"+ "*---+---+---*\n"+ "|962|547|813|\n"+ "|134|682|795|\n"+ "|587|031|264|\n"+ "*---*---*---*\n"); done() }) it("pass #29 Solve with one final Basic Pass", function(done){ solve.solvePassBasic(); solve.solvePassBasic(); solve.solvePassBasic(); solve.solvePassBasic(); solve.solveRegionExclusion(); solve.solvePassBasic(); solve.solveRowExclusion(); solve.solvePassBasic(); solve.solveColExclusion(); solve.solvePassBasic(); solve.solveRegionExclusion(); solve.solvePassBasic(); solve.solveRowExclusion(); solve.solvePassBasic(); solve.solvePassBasic(); solve.solveColExclusion(); solve.solveRegionExclusion(); solve.checkPairs(); solve.solvePassBasic(); solve.solvePassBasic(); solve.solvePassBasic(); solve.solvePassBasic(); solve.solvePassBasic(); solve.solvePassBasic(); solve.solvePassBasic(); solve.solvePassBasic(); solve.solvePassBasic(); solve.solvePassBasic(); solve.solvePassBasic(); solve.solvePassBasic(); expect(su.getStructure()).to.equal( "*---*---*---*\n"+ "|843|175|629|\n"+ "|729|463|158|\n"+ "|651|298|437|\n"+ "*---+---+---*\n"+ "|275|819|346|\n"+ "|316|754|982|\n"+ "|498|326|571|\n"+ "*---+---+---*\n"+ "|962|547|813|\n"+ "|134|682|795|\n"+ "|587|931|264|\n"+ "*---*---*---*\n"); done() }) it("Just solve", function(done){ solve.solve() expect(su.getStructure()).to.equal( "*---*---*---*\n"+ "|843|175|629|\n"+ "|729|463|158|\n"+ "|651|298|437|\n"+ "*---+---+---*\n"+ "|275|819|346|\n"+ "|316|754|982|\n"+ "|498|326|571|\n"+ "*---+---+---*\n"+ "|962|547|813|\n"+ "|134|682|795|\n"+ "|587|931|264|\n"+ "*---*---*---*\n"); done() }) /* */ })<file_sep>/src/view/view.jsx /** * Sets up and runs the view * @file view.jsx * @author <NAME> */ var React = require('react'); window.React = React var SudokuBoard = require('./SudokuBoard.jsx') /** * Renders the window using the current Sudoku at window.su * @function */ window.renderView = function() { React.render( <SudokuBoard sudoku={window.su}/> , document.body ); } /** * Calls a method and then calls window render * @example * window.dnr(alert, this, "This is an alert!") * @function * @param {Function} f The function to call. * @param {Function} [t=null] The context to call the function in such as this. * @param {arguments} [*=null] all remaining arguments are passed to the function */ window.dnr = function(f, t ){ var args = Array.prototype.splice.call(arguments, 2); f.apply(t, args) window.renderView(); } window.renderView();<file_sep>/docs/serve/0.0.0/debugger.js.html <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <title>HTML5 Sudoku App: Source: debugger.js</title> <script src="scripts/prettify/prettify.js"> </script> <script src="scripts/prettify/lang-css.js"> </script> <!--[if lt IE 9]> <script src="//html5shiv.googlecode.com/svn/trunk/html5.js"></script> <![endif]--> <link type="text/css" rel="stylesheet" href="styles/prettify-tomorrow.css"> <link type="text/css" rel="stylesheet" href="styles/jsdoc-default.css"> </head> <body> <div id="main"> <h1 class="page-title">Source: debugger.js</h1> <section> <article> <pre class="prettyprint source linenums"><code>/** * Just some floating debug helper methods * @name Debugger * @module */ /** * Gets the current stack. * @function * @returns {string} The current stack as a string */ exports.getstack = function(){ //create dubby error to get stack var e = new Error('stackTrace'); //format stack var stack = e.stack.replace(/^[^\(]+?[\n$]/gm, '') .replace(/^\s+at\s+/gm, '') .replace(/^Object.&lt;anonymous>\s*\(/gm, '{anonymous}()@') .split('\n'); //return stack return stack } </code></pre> </article> </section> </div> <nav> <h2><a href="index.html">Home</a></h2><h3>Modules</h3><ul><li><a href="module-Debugger.html">Debugger</a></li></ul><h3>Classes</h3><ul><li><a href="puzzleMaker.html">puzzleMaker</a></li><li><a href="sudokuOBJ.html">sudokuOBJ</a></li><li><a href="sudokuSolver.html">sudokuSolver</a></li><li><a href="tileOBJ.html">tileOBJ</a></li><li><a href="tileStore.html">tileStore</a></li></ul><h3>Global</h3><ul><li><a href="global.html#a">a</a></li><li><a href="global.html#TileTypes">Tile Types</a></li></ul> </nav> <br class="clear"> <footer> Documentation generated by <a href="https://github.com/jsdoc3/jsdoc">JSDoc 3.3.2</a> on Tue Aug 25 2015 18:08:45 GMT-1000 (Hawaiian Standard Time) </footer> <script> prettyPrint(); </script> <script src="scripts/linenumber.js"> </script> </body> </html> <file_sep>/src/js/puzzleMaker.js /** * @file Puzzle Maker Code * @author <NAME> */ /** * Puzzle Maker * {Not Implimented Yet} * @class puzzleMaker */ var puzzleMaker = function () { // body... } module.exports = puzzleMaker;<file_sep>/README.md # HTML5-Sudoku Simple React.js Sudoku app writen with Legit TDD and full documentation. # Author <NAME> # Documentation [Clicking this link](http://htmlpreview.github.io/?https://raw.githubusercontent.com/Eforen/HTML5-Sudoku/master/docs/index.html) will take you to the full documentaion for this project! Its awesome because it is extracted from the code meaning that the code is fully commented and that the docs can link to where the methods, classes, n things are defined with exact line numbers! # Current Status Base structure testing. # To Do before implimenting GUI - [x] Add static serving node.js to allow debugging in chrome without crossdomain issues. - [x] Setup Testing for TDD and Browserify. - [x] Create Sudoku Object/Class - [x] Create tile store - [x] Create tile object - [ ] Create Sudoku solver - [ ] Load Seed Puzzles from json - [ ] Create Sudoku Maker - [ ] Make Areas able to check available numbers and validity of numbers. - [ ] Make brute force Sudoku Creater. # Bugs: None<file_sep>/test/test.sudokuOBJ.js var expect = require("chai").expect; var sudoku = require("../src/js/sudokuOBJ.js"); var tileStore = require("../src/js/tileStore.js"); var tileOBJ = require("../src/js/tileOBJ.js"); var tokens = require("../src/js/tokenENUM.js"); describe("sudoku Object", function() { var su = null; var testJSON = "{}"; var testOBJ = {}; beforeEach(function(done) { test = '{"name": "<NAME>", "puzzle": "043000620700403008600208007075000340000000000098000570900507003100602005087000260"}'; testOBJ = { name: "<NAME>", puzzle: "043000620700403008600208007075000340000000000098000570900507003100602005087000260" } su = new sudoku(); //su = null; //Debug setup expectation expect(su).not.to.be.null; //Test setup expectation done(); }) it("should instansiate and be available", function(done){ expect(su).not.to.be.null; done(); }) describe("lines", function(){ describe("rows", function() { it("should be and array", function(done){ expect(su.getRows()).to.be.an('array'); done(); }) it("should create 9", function(done){ expect(su.getRows()).to.have.length(9); done(); }) it("should all be tileStores", function(done){ for (var i = 0; i < 9; i++) { expect(su.getRow(i)).to.be.an.instanceof(tileStore); } done(); }) it("should all be full of tileOBJs", function(done){ for (var r = 0; r < 9; r++) { var ro = su.getRow(r); for (var c = 0; c < 9; c++) { expect(ro.tiles[c]).to.be.instanceof(tileOBJ); } } done(); }) }) describe("cols", function() { it("should be and array", function(done){ expect(su.getCols()).to.be.an('array'); done(); }) it("should create 9", function(done){ expect(su.getCols()).to.have.length(9); done(); }) it("should all be tileStores", function(done){ for (var i = 0; i < 9; i++) { expect(su.getCol(i)).to.be.an.instanceof(tileStore); } done(); }) it("should all be full of tileOBJs", function(done){ for (var c = 0; c < 9; c++) { var co = su.getCol(c); for (var r = 0; r < 9; r++) { expect(co.tiles[r]).to.be.instanceof(tileOBJ); } } done(); }) }) }) describe("regions", function() { it("should be and array", function(done){ expect(su.getRegions()).to.be.an('array'); done(); }) it("should create 9", function(done){ expect(su.getRegions()).to.have.length(9); done(); }) it("should all be tileStores", function(done){ for (var i = 0; i < 9; i++) { expect(su.getRegion(i)).to.be.an.instanceof(tileStore); } done(); }) it("get from posision should return the correct tileStores", function(done){ for (var x = 0; x < 9; x++) { for (var y = 0; y < 9; y++) { var xx = null; if(x > 0 && x < 3) xx = 0; if(x > 2 && x < 6) xx = 1; if(x > 5 && x < 9) xx = 2; var yy = null; if(y > 0 && y < 3) yy = 0; if(y > 2 && y < 6) yy = 1; if(y > 5 && y < 9) yy = 2; expect(su.getRegion(x, y)).to.equal(su.getRegion(3*yy+xx)); } } done(); }) it("should all be full of tileOBJs", function(done){ for (var r = 0; r < 9; r++) { var ro = su.getRegion(r); for (var i = 0; i < 9; i++) { expect(ro.tiles[i]).to.be.instanceof(tileOBJ); } } done(); }) }) describe("Data", function(){ beforeEach(function(done) { //su = sudoku.loadFromJSON(test); su = sudoku.loadFromOBJ(testOBJ); //su = null; //Debug setup expectation expect(su).not.to.be.null; //Test setup expectation expect(su).to.be.instanceof(sudoku); //Test setup expectation done(); }) it("should load from JSON", function(done){ //var su = sudoku.loadFromJSON(test); su = sudoku.loadFromOBJ(testOBJ); done(); }) describe("should be the correct data:", function(){ it("token check...", function(done){ //console.log("wtf! "+tokens.a+" "+tokens.b) expect(su.getTile(1,0).getToken()).to.equal(tokens.d); expect(su.getTile(2,0).getToken()).to.equal(tokens.c); // 043 000 620 expect(su.getTile(1,0).getToken()).to.equal(4); expect(su.getTile(2,0).getToken()).to.equal(3); expect(su.getTile(6,0).getToken()).to.equal(6); expect(su.getTile(7,0).getToken()).to.equal(2); // 700 403 008 expect(su.getTile(0,1).getToken()).to.equal(7); expect(su.getTile(3,1).getToken()).to.equal(4); expect(su.getTile(5,1).getToken()).to.equal(3); expect(su.getTile(8,1).getToken()).to.equal(8); // 600 208 007 expect(su.getTile(0,2).getToken()).to.equal(6); expect(su.getTile(3,2).getToken()).to.equal(2); expect(su.getTile(5,2).getToken()).to.equal(8); expect(su.getTile(8,2).getToken()).to.equal(7); // 075 000 340 expect(su.getTile(1,3).getToken()).to.equal(7); expect(su.getTile(2,3).getToken()).to.equal(5); expect(su.getTile(6,3).getToken()).to.equal(3); expect(su.getTile(7,3).getToken()).to.equal(4); // 000 000 000 // 098 000 570 expect(su.getTile(1,5).getToken()).to.equal(9); expect(su.getTile(2,5).getToken()).to.equal(8); expect(su.getTile(6,5).getToken()).to.equal(5); expect(su.getTile(7,5).getToken()).to.equal(7); // 900 507 003 expect(su.getTile(0,6).getToken()).to.equal(9); expect(su.getTile(3,6).getToken()).to.equal(5); expect(su.getTile(5,6).getToken()).to.equal(7); expect(su.getTile(8,6).getToken()).to.equal(3); // 100 602 005 expect(su.getTile(0,7).getToken()).to.equal(1); expect(su.getTile(3,7).getToken()).to.equal(6); expect(su.getTile(5,7).getToken()).to.equal(2); expect(su.getTile(8,7).getToken()).to.equal(5); // 087 000 260 expect(su.getTile(1,8).getToken()).to.equal(8); expect(su.getTile(2,8).getToken()).to.equal(7); expect(su.getTile(6,8).getToken()).to.equal(2); expect(su.getTile(7,8).getToken()).to.equal(6); done(); }) it("type check...", function(done){ // 043 000 620 expect(su.getTile(0,0).getType()).to.equal(tileOBJ.types.blank); expect(su.getTile(1,0).getType()).to.equal(tileOBJ.types.locked); expect(su.getTile(2,0).getType()).to.equal(tileOBJ.types.locked); expect(su.getTile(3,0).getType()).to.equal(tileOBJ.types.blank); expect(su.getTile(4,0).getType()).to.equal(tileOBJ.types.blank); expect(su.getTile(5,0).getType()).to.equal(tileOBJ.types.blank); expect(su.getTile(6,0).getType()).to.equal(tileOBJ.types.locked); expect(su.getTile(7,0).getType()).to.equal(tileOBJ.types.locked); expect(su.getTile(8,0).getType()).to.equal(tileOBJ.types.blank); // 700 403 008 expect(su.getTile(0,1).getType()).to.equal(tileOBJ.types.locked); expect(su.getTile(1,1).getType()).to.equal(tileOBJ.types.blank); expect(su.getTile(2,1).getType()).to.equal(tileOBJ.types.blank); expect(su.getTile(3,1).getType()).to.equal(tileOBJ.types.locked); expect(su.getTile(4,1).getType()).to.equal(tileOBJ.types.blank); expect(su.getTile(5,1).getType()).to.equal(tileOBJ.types.locked); expect(su.getTile(6,1).getType()).to.equal(tileOBJ.types.blank); expect(su.getTile(7,1).getType()).to.equal(tileOBJ.types.blank); expect(su.getTile(8,1).getType()).to.equal(tileOBJ.types.locked); // 600 208 007 expect(su.getTile(0,2).getType()).to.equal(tileOBJ.types.locked); expect(su.getTile(1,2).getType()).to.equal(tileOBJ.types.blank); expect(su.getTile(2,2).getType()).to.equal(tileOBJ.types.blank); expect(su.getTile(3,2).getType()).to.equal(tileOBJ.types.locked); expect(su.getTile(4,2).getType()).to.equal(tileOBJ.types.blank); expect(su.getTile(5,2).getType()).to.equal(tileOBJ.types.locked); expect(su.getTile(6,2).getType()).to.equal(tileOBJ.types.blank); expect(su.getTile(7,2).getType()).to.equal(tileOBJ.types.blank); expect(su.getTile(8,2).getType()).to.equal(tileOBJ.types.locked); // 075 000 340 expect(su.getTile(0,3).getType()).to.equal(tileOBJ.types.blank); expect(su.getTile(1,3).getType()).to.equal(tileOBJ.types.locked); expect(su.getTile(2,3).getType()).to.equal(tileOBJ.types.locked); expect(su.getTile(3,3).getType()).to.equal(tileOBJ.types.blank); expect(su.getTile(4,3).getType()).to.equal(tileOBJ.types.blank); expect(su.getTile(5,3).getType()).to.equal(tileOBJ.types.blank); expect(su.getTile(6,3).getType()).to.equal(tileOBJ.types.locked); expect(su.getTile(7,3).getType()).to.equal(tileOBJ.types.locked); expect(su.getTile(8,3).getType()).to.equal(tileOBJ.types.blank); // 000 000 000 expect(su.getTile(0,4).getType()).to.equal(tileOBJ.types.blank); expect(su.getTile(1,4).getType()).to.equal(tileOBJ.types.blank); expect(su.getTile(2,4).getType()).to.equal(tileOBJ.types.blank); expect(su.getTile(3,4).getType()).to.equal(tileOBJ.types.blank); expect(su.getTile(4,4).getType()).to.equal(tileOBJ.types.blank); expect(su.getTile(5,4).getType()).to.equal(tileOBJ.types.blank); expect(su.getTile(6,4).getType()).to.equal(tileOBJ.types.blank); expect(su.getTile(7,4).getType()).to.equal(tileOBJ.types.blank); expect(su.getTile(8,4).getType()).to.equal(tileOBJ.types.blank); // 098 000 570 expect(su.getTile(0,5).getType()).to.equal(tileOBJ.types.blank); expect(su.getTile(1,5).getType()).to.equal(tileOBJ.types.locked); expect(su.getTile(2,5).getType()).to.equal(tileOBJ.types.locked); expect(su.getTile(3,5).getType()).to.equal(tileOBJ.types.blank); expect(su.getTile(4,5).getType()).to.equal(tileOBJ.types.blank); expect(su.getTile(5,5).getType()).to.equal(tileOBJ.types.blank); expect(su.getTile(6,5).getType()).to.equal(tileOBJ.types.locked); expect(su.getTile(7,5).getType()).to.equal(tileOBJ.types.locked); expect(su.getTile(8,5).getType()).to.equal(tileOBJ.types.blank); // 900 507 003 expect(su.getTile(0,6).getType()).to.equal(tileOBJ.types.locked); expect(su.getTile(1,6).getType()).to.equal(tileOBJ.types.blank); expect(su.getTile(2,6).getType()).to.equal(tileOBJ.types.blank); expect(su.getTile(3,6).getType()).to.equal(tileOBJ.types.locked); expect(su.getTile(4,6).getType()).to.equal(tileOBJ.types.blank); expect(su.getTile(5,6).getType()).to.equal(tileOBJ.types.locked); expect(su.getTile(6,6).getType()).to.equal(tileOBJ.types.blank); expect(su.getTile(7,6).getType()).to.equal(tileOBJ.types.blank); expect(su.getTile(8,6).getType()).to.equal(tileOBJ.types.locked); // 100 602 005 expect(su.getTile(0,7).getType()).to.equal(tileOBJ.types.locked); expect(su.getTile(1,7).getType()).to.equal(tileOBJ.types.blank); expect(su.getTile(2,7).getType()).to.equal(tileOBJ.types.blank); expect(su.getTile(3,7).getType()).to.equal(tileOBJ.types.locked); expect(su.getTile(4,7).getType()).to.equal(tileOBJ.types.blank); expect(su.getTile(5,7).getType()).to.equal(tileOBJ.types.locked); expect(su.getTile(6,7).getType()).to.equal(tileOBJ.types.blank); expect(su.getTile(7,7).getType()).to.equal(tileOBJ.types.blank); expect(su.getTile(8,7).getType()).to.equal(tileOBJ.types.locked); // 087 000 260 expect(su.getTile(0,8).getType()).to.equal(tileOBJ.types.blank); expect(su.getTile(1,8).getType()).to.equal(tileOBJ.types.locked); expect(su.getTile(2,8).getType()).to.equal(tileOBJ.types.locked); expect(su.getTile(3,8).getType()).to.equal(tileOBJ.types.blank); expect(su.getTile(4,8).getType()).to.equal(tileOBJ.types.blank); expect(su.getTile(5,8).getType()).to.equal(tileOBJ.types.blank); expect(su.getTile(6,8).getType()).to.equal(tileOBJ.types.locked); expect(su.getTile(7,8).getType()).to.equal(tileOBJ.types.locked); expect(su.getTile(8,8).getType()).to.equal(tileOBJ.types.blank); done(); }) }) describe("structure", function() { it("should be the correct tileOBJs", function(done){ for (var x = 0; x < 9; x++) { for (var y = 0; y < 9; y++) { var r = su.getRow(y); var c = su.getCol(x); expect(r.tiles[x]).to.equal(c.tiles[y]); } } done(); }) it("get tile should get the correct tileOBJ", function(done){ for (var x = 0; x < 9; x++) { for (var y = 0; y < 9; y++) { var r = su.getRow(y); var c = su.getCol(x); expect(r.tiles[x]).to.equal(c.tiles[y]); expect(su.getTile(x, y)).to.equal(r.tiles[x]); } } done(); }) it("regions should all be the correct tileOBJs", function(done){ var r = su.getRegions(); for (var x = 0; x < 9; x++) { for (var y = 0; y < 9; y++) { var rx = null; if(x > 0 && x < 3) rx = 0; if(x > 2 && x < 6) rx = 1; if(x > 5 && x < 9) rx = 2; var ry = null; if(y > 0 && y < 3) ry = 0; if(y > 2 && y < 6) ry = 1; if(y > 5 && y < 9) ry = 2; expect(r[3*ry+rx].tiles[3*parseInt(y%3)+parseInt(x%3)]).to.equal(su.getTile(x, y)); } } done(); }) describe("debug methods", function() { it("should return correct structure in string", function(done){ /* *---*---*---* |043|000|620| |700|403|008| |600|208|007| *---+---+---* |075|000|340| |000|000|000| |098|000|570| *---+---+---* |900|507|003| |100|602|005| |087|000|260| *---*---*---* */ var target = "*---*---*---*\n"+ "|043|000|620|\n"+ "|700|403|008|\n"+ "|600|208|007|\n"+ "*---+---+---*\n"+ "|075|000|340|\n"+ "|000|000|000|\n"+ "|098|000|570|\n"+ "*---+---+---*\n"+ "|900|507|003|\n"+ "|100|602|005|\n"+ "|087|000|260|\n"+ "*---*---*---*\n" expect(su.getStructure()).to.equal(target); done() }) it("should print debug of tiles in row with .debugRow(y)", function(done){ expect(su.debugRow(0)).to.equal("||4|3||||6|2||") expect(su.debugRow(1)).to.equal("|7|||4||3|||8|") expect(su.debugRow(2)).to.equal("|6|||2||8|||7|") expect(su.debugRow(3)).to.equal("||7|5||||3|4||") expect(su.debugRow(4)).to.equal("||||||||||") expect(su.debugRow(5)).to.equal("||9|8||||5|7||") expect(su.debugRow(6)).to.equal("|9|||5||7|||3|") expect(su.debugRow(7)).to.equal("|1|||6||2|||5|") expect(su.debugRow(8)).to.equal("||8|7||||2|6||") done(); }) it("should print debug of tiles in row with .debugRow(y) with guesses", function(done){ var row = su.getRow(0).tiles // a b c d e f g h i // 1 2 3 4 5 6 7 8 9 var arr = [] arr[tokens.e] = true; arr[tokens.h] = true; row[0].setGuesses(arr) arr = [] arr[tokens.a] = true; arr[tokens.g] = true; arr[tokens.i] = true; row[3].setGuesses(arr) arr = [] arr[tokens.a] = true; arr[tokens.e] = true; arr[tokens.g] = true; arr[tokens.i] = true; row[4].setGuesses(arr) arr = [] arr[tokens.a] = true; arr[tokens.e] = true; arr[tokens.i] = true; row[5].setGuesses(arr) arr = [] arr[tokens.a] = true; arr[tokens.i] = true; row[8].setGuesses(arr) expect(su.debugRow(0)).to.equal("|58|4|3|179|1579|159|6|2|19|") expect(su.debugRow(1)).to.equal("|7|||4||3|||8|") expect(su.debugRow(2)).to.equal("|6|||2||8|||7|") expect(su.debugRow(3)).to.equal("||7|5||||3|4||") expect(su.debugRow(4)).to.equal("||||||||||") expect(su.debugRow(5)).to.equal("||9|8||||5|7||") expect(su.debugRow(6)).to.equal("|9|||5||7|||3|") expect(su.debugRow(7)).to.equal("|1|||6||2|||5|") expect(su.debugRow(8)).to.equal("||8|7||||2|6||") done(); }) it("should print debug of tiles in col with .debugCol(x)", function(done){ expect(su.debugCol(0)).to.equal("||7|6||||9|1||") done(); }) it("should print debug of tiles in col with .debugCol(x) with guesses", function(done){ var col = su.getCol(0).tiles // a b c d e f g h i // 1 2 3 4 5 6 7 8 9 var arr = [] arr[tokens.e] = true; arr[tokens.h] = true; col[0].setGuesses(arr) arr = [] arr[tokens.a] = true; arr[tokens.g] = true; arr[tokens.i] = true; col[3].setGuesses(arr) arr = [] arr[tokens.a] = true; arr[tokens.e] = true; arr[tokens.g] = true; arr[tokens.i] = true; col[4].setGuesses(arr) arr = [] arr[tokens.a] = true; arr[tokens.e] = true; arr[tokens.i] = true; col[5].setGuesses(arr) arr = [] arr[tokens.a] = true; arr[tokens.i] = true; col[8].setGuesses(arr) expect(su.debugCol(0)).to.equal("|58|7|6|179|1579|159|9|1|19|") done(); }) it("should print debug of tiles in region with .debugRegion(y)", function(done){ expect(su.debugRegion(0,0)).to.equal("||4|3|7|||6|||") done(); }) it("should print debug of tiles in region with .debugRegion(x, y) with guesses", function(done){ var region = su.getRegion(0,0).tiles // a b c d e f g h i // 1 2 3 4 5 6 7 8 9 var arr = [] arr[tokens.e] = true; arr[tokens.h] = true; region[0].setGuesses(arr) arr = [] arr[tokens.a] = true; arr[tokens.g] = true; arr[tokens.i] = true; region[4].setGuesses(arr) arr = [] arr[tokens.a] = true; arr[tokens.e] = true; arr[tokens.g] = true; arr[tokens.i] = true; region[5].setGuesses(arr) arr = [] arr[tokens.a] = true; arr[tokens.e] = true; arr[tokens.i] = true; region[7].setGuesses(arr) arr = [] arr[tokens.a] = true; arr[tokens.i] = true; region[8].setGuesses(arr) expect(su.debugRegion(0,0)).to.equal("|58|4|3|7|179|1579|6|159|19|") done(); }) }) }) }) })<file_sep>/test/test-sudokuTile.jsx //jsdom = require("jsdom") sinon = require("mocha-sinon") require("./dom_helper.js") var expect = require("chai").expect; var React = require('react') var ReactAddons = require('react/addons') // require the addons var ReactTestUtils = React.addons.TestUtils // <- YEAH! var tileOBJ = require("../src/js/tileOBJ.js"); var tokens = require("../src/js/tokenENUM.js"); var debug = require("../src/js/debugger.js"); describe("sudokuTile Comp", function() { beforeEach(function() { var container = this.document.createElement('div') }) it("create the correct HTML on Set", function(done){ var tileHTML = TestUtils.renderIntoDocument((<sudokuTile x={2} y={4} tile={tile} />), container) console.log(tileHTML.innerHTML()) done(); }) })<file_sep>/src/js/sudokuSolver.js /** * @file SudokuSolver Code * @author <NAME> */ console.log("Loaded SudokuSolver.js"); var sudokuOBJ = require("./sudokuOBJ.js"); var tileStore = require("./tileStore.js"); var tileOBJ = require("./tileOBJ.js"); var token = require("./tokenENUM.js"); /** * Holds all the logic to solve a sudoku or preform parts of solving. * @todo Document this object * @class */ var sudokuSolver = function(sudoku){ //Private Vars /** * @todo Document this member * @member sudokuSolver#su * @private */ var su = sudoku; //Public Vars //Methods /** * @todo Document this method * @method sudokuSolver#prepSudoku */ this.prepSudoku=function(){ var defaultGuesses = []; defaultGuesses[token.a] = true; defaultGuesses[token.b] = true; defaultGuesses[token.c] = true; defaultGuesses[token.d] = true; defaultGuesses[token.e] = true; defaultGuesses[token.f] = true; defaultGuesses[token.g] = true; defaultGuesses[token.h] = true; defaultGuesses[token.i] = true; var tile = null; for (var x = 0; x < 9; x++) { for (var y = 0; y < 9; y++) { tile = su.getTile(x,y); if(tile.getType()!=tileOBJ.types.locked){ tile.setGuesses(defaultGuesses); } } } } /** * @todo Document this method * @method sudokuSolver#getSudoku */ this.getSudoku = function(){ return su; } /** * @todo Document this method * @method sudokuSolver#solveForRow */ this.solveForRow = function(y){ this.excludeInSet(su.getRow(y)); } /** * @todo Document this method * @method sudokuSolver#solveForCol */ this.solveForCol = function(x){ this.excludeInSet(su.getCol(x)); } /** * @todo Document this method * @method sudokuSolver#solveForRegion */ this.solveForRegion = function(x, y){ this.excludeInSet(su.getRegion(x, y)); } /** * @todo Document this method * @method sudokuSolver#excludeSet */ this.excludeSet = function(tile, container){ for (var n = 1; n < 10; n++) { for (var i = 0; i < container.tiles.length; i++) { if(container.tiles[i].getToken() === n || container.tiles[i].getType() === tileOBJ.types.locked || container.tiles[i].getType() === tileOBJ.types.set){ console.log("Making "+n+"|"+i+" falsy") tile.setGuess(n, false); break; } } } } /** * @todo Document this method * @method sudokuSolver#excludeInSet */ this.excludeInSet = function(container){ var data = [] var log = "" //Debug //run through set and mark all present tokens as false in data set leave all others null for (var i = 0; i < container.tiles.length; i++) { log += i+" loop"+", " //If tile is guess then skip it if(container.tiles[i].getType() === tileOBJ.types.guess){ log += i+" skip"+", " continue } //If tile is set then set data as false if(container.tiles[i].getType() == tileOBJ.types.locked || container.tiles[i].getType() == tileOBJ.types.set){ log += i+" set "+container.tiles[i].getToken()+". " data[container.tiles[i].getToken()] = false } } log += "|"+data+"|" //Kill all bad guesses with the data array for (var i = 0; i < container.tiles.length; i++){ log += i+" loop"+", " if(typeof(container.tiles[i]) !== "undefined"){ log += i+" set"+". " container.tiles[i].setGuesses(data) } } //console.log(log) } /** * @todo Document this method * @method sudokuSolver#excludeGuess */ this.excludeGuess = function(container, includeGuesses, debug){ if(includeGuesses == null) includeGuesses = false var data = [] for (var n = 1; n < 10; n++) { data[n]={ inMoreThenOne: 0, index: 0 } for (var i = 0; i < container.tiles.length; i++) { if(container.tiles[i].getType() === tileOBJ.types.guess){ if(container.tiles[i].getGuess(n)){ data[n].inMoreThenOne++ data[n].index = i } } if(container.tiles[i].getType() == tileOBJ.types.locked || container.tiles[i].getType() == tileOBJ.types.set){ if(container.tiles[i].getToken() == n){ data[n].inMoreThenOne += 10 data[n].index = i } } /* */ } } if(typeof(window) != "undefined") window.testGuess = data //debug for (var n = 1; n < 10; n++) { /*if(n == 4 && debug === true) {//debug console.log("\n\n********************************************\nSolve for N"+n+" is "+data[n].inMoreThenOne+"|"+data[n].index+"\n********************************************\n\n") }*/ if(data[n].inMoreThenOne === 1){ //console.log("found one") container.tiles[data[n].index].setToken(n) container.tiles[data[n].index].setType(tileOBJ.types.set) } } } /** * @todo Document this method * @method sudokuSolver#solvePassBasic */ this.solvePassBasic = function(){ for (var x = 0; x < 9; x++) { for (var y = 0; y < 9; y++) { //if(y === 7) console.log("Solving For r"+9+" c"+x) this.solveForRow(y) this.solveForCol(x) this.solveForRegion(x) } } var tile = null; for (var x = 0; x < 9; x++) { for (var y = 0; y < 9; y++) { tile = this.getSudoku().getTile(x, y) if(tile.getType() === tileOBJ.types.guess){ var count = 0 var guesses = tile.getGuesses() var lastToken = 0 for (var i = 0; i < guesses.length; i++) { if(guesses[i]){ count++ lastToken = i } } if(count === 1) { tile.setToken(lastToken) tile.setType(tileOBJ.types.set) } } } } } /** * @todo Document this method * @method sudokuSolver#solveRegionExclusion */ this.solveRegionExclusion = function(){ var regions = this.getSudoku().getRegions() for (var i = 0; i < 9; i++) { this.excludeGuess(regions[i], true) } } /** * @todo Document this method * @method sudokuSolver#solveRowExclusion */ this.solveRowExclusion = function(){ //var row = this.getSudoku().getRows() for (var i = 0; i < 9; i++) { this.excludeGuess(this.getSudoku().getRow(i), true) } } /** * @todo Document this method * @method sudokuSolver#solveColExclusion */ this.solveColExclusion = function(){ for (var i = 0; i < 9; i++) { //console.log(su.debugCol(i)) //debug this.excludeGuess(this.getSudoku().getCol(i), true) } } /** * This method preforms a pair exclusion test on all rows * @method sudokuSolver#checkPairsRow */ this.checkPairsRow = function(){ for (var i = 0; i < 9; i++) { //console.log(su.debugCol(i)) //debug this.excludePairGuess(this.getSudoku().getRow(i)) } } /** * This method preforms a pair exclusion test on all columns * @method sudokuSolver#checkPairsCol */ this.checkPairsCol = function(){ for (var i = 0; i < 9; i++) { //console.log(su.debugCol(i)) //debug this.excludePairGuess(this.getSudoku().getCol(i)) } } /** * This method preforms a pair exclusion test on all regions * @method sudokuSolver#checkPairsRegion */ this.checkPairsRegion = function(){ for (var i = 0; i < 9; i++) { //console.log(su.debugCol(i)) //debug this.excludePairGuess(this.getSudoku().getRegion(i)) } } /** * This method preforms a pair exclusion test on all rows, columns, and regions * @method sudokuSolver#checkPairs */ this.checkPairs = function(){ this.checkPairsRow() this.checkPairsCol() this.checkPairsRegion() } /** * * This method preforms a pair exclusion test on the given {@link tileStore} * @method sudokuSolver#excludeGuess */ this.excludePairGuess = function(container, debug){ var data = [] for (var n = 1; n < 10; n++) { var guess = [] var count = 0 for (var i = 0; i < container.tiles.length; i++) { if(container.tiles[i].getType() === tileOBJ.types.guess){ //get guesses guess = container.tiles[i].getGuesses() count = 0 //count the actual values for(var g = 0; g<guess.length; g++){ if(guess[g] === true){ count+=1 // Add one for every guess in the base set } } //if is a pair if(count === 2){ //base set has only 2 guesses var guess2 = [] var same = true //define the var outside the loop to avoid object creation for speed for (var ii = i+1; ii < container.tiles.length; ii++) {//check every other tile for the same values same = true count = 0 //reuse and reset the counter to 0 guess2 = container.tiles[ii].getGuesses() //get current secondary tiles set of guesses for(var g = 0; g<guess2.length; g++) { if (guess2[g] !== guess[g]) { // If it does not match the base set same = false //backup to insure it does not stop on the 3rd guess and not match thus looking like a pair break }else if(guess2[g] === true){ count++ //Backup to insure that the other is a pair not just something that has for example an empty guess list } } if(same === true && count === 2){ //We have found a pair now kill these guesses in all others that are not this pair var killSet = [] for(var g = 0; g<guess2.length; g++) { if (guess2[g] == true) { // If it matches the base set killSet[g] = false //set it to false so when applied to target tiles it removes both elements of the pair if they are present } } for (var k = 0; k < container.tiles.length; k++) { //kill guesses that are in this set in all other tiles. if(k !== i && k !== ii){ if(container.tiles[k].getToken() !== tileOBJ.types.locked || container.tiles[k].getToken() !== tileOBJ.types.set){ container.tiles[k].setGuesses(killSet) } } } } } } } } } } this.solve = function(){ var lastPass = 0 var thisPass = 0 var solved = false var failed = false var lastState = "" var thisState = "" while(solved === false) { switch(thisPass){ case sudokuSolver.solvers.basicPass: console.log("solvePassBasic") this.solvePassBasic(); break case sudokuSolver.solvers.RowExclusion: console.log("RowExclusion") this.solveRegionExclusion(); break case sudokuSolver.solvers.ColExclusion: console.log("ColExclusion") this.solveRowExclusion(); break case sudokuSolver.solvers.RegionExclusion: console.log("RegionExclusion") this.solveColExclusion(); break case sudokuSolver.solvers.checkPairs: console.log("checkPairs") this.checkPairs(); break default: solved = true failed = true console.log("Solver not found!") } lastState = thisState thisState = su.getStructure(true, true) console.log(thisState) if(su.isSolved()){ solved = true; break } if(lastState == thisState) { //This pass did nothing //if(lastPass > thisStep){ if(thisPass < sudokuSolver.solvers.lastSolver){ if(lastPass >= thisPass && lastPass != sudokuSolver.solvers.firstSolver){ console.log("WTF2!") //If the last pass in greater then this one then that means that we where checking for basic changes //Should switch back to where it was and run the next step. thisPass = lastPass + 1 } else{ console.log("WTF3!") thisPass++ } } else{ console.log("WTF1!") lastPass = sudokuSolver.solvers.firstSolver thisPass = sudokuSolver.solvers.firstSolver } } else{ console.log("WTF3!") //This pass did something so check basic pass lastPass = thisPass thisPass = sudokuSolver.solvers.firstSolver } } } //Start of Constructor this.prepSudoku(); //End of Constructor } sudokuSolver.solvers = { firstSolver: 0, basicPass: 0, RegionExclusion: 1, RowExclusion: 2, ColExclusion: 3, checkPairs: 4, lastSolver: 4 } module.exports = sudokuSolver;<file_sep>/src/js/debugger.js /** * Just some floating debug helper methods * @name Debugger * @module */ /** * Gets the current stack. * @function * @returns {string} The current stack as a string */ exports.getstack = function(){ //create dubby error to get stack var e = new Error('stackTrace'); //format stack var stack = e.stack.replace(/^[^\(]+?[\n$]/gm, '') .replace(/^\s+at\s+/gm, '') .replace(/^Object.<anonymous>\s*\(/gm, '{anonymous}()@') .split('\n'); //return stack return stack } <file_sep>/test/dom_helper.js /* //jsdom = require("jsdom") require("mocha-sinon") // move into beforeEach and flip global.window.close on to improve // cleaning of environment during each test and prevent memory leaks document = jsdom.jsdom('<html><body></body></html>', jsdom.level(1, 'core')) beforeEach( function(){ this.document = document global.document = this.document global.window = this.document.parentWindow }) afterEach( function(){ // setting up and closing a "window" every run is really heavy // it prevents contamination between tests and prevents memory leaks global.window.close() }) */<file_sep>/test/test.hex2rgb.js var expect = require("chai").expect; var hex2rgb = require("../src/js/lib/hex2rgb"); describe("hex to rgb conversion", function() { it("should fail with less than 3 characters", function(done){ hex2rgb("#ff", function(err){ expect(err).to.exist; done(); }); }) it("should fail with more than 6 characters", function(done){ hex2rgb("#ffaabbs", function(err){ expect(err).to.exist; done(); }); }) it("should convert hex to rgb succcessfully", function(done){ hex2rgb("#ffaa55", function(err, rgb){ expect(err).to.be.null; expect(rgb).to.deep.equal([255,170,85]); done(); }); }) })<file_sep>/src/js/tileOBJ.js /** * @file tileOBJ Code * @author <NAME> */ console.log("Loaded tileOBJ.js"); var tokens = require("./tokenENUM.js"); /** * This object stores data to describe a tile in the sudoku. * @module tileOBJ * @class */ var tileOBJ = function(){ /** * Tells if the this instance has been setup or not. * @member tileOBJ#isSetup * @type {Boolean} */ this.isSetup = false; /** * Stores a refrence to the {@link tileStore} that contains all the tiles in the same row. * @member tileOBJ#_row * @type {tileStore} * @private */ /** * Stores a refrence to the {@link tileStore} that contains all the tiles in the same column. * @member tileOBJ#_column * @type {tileStore} * @private */ /** * Stores a refrence to the {@link tileStore} that contains all the tiles in the same region. * @member tileOBJ#_region * @type {tileStore} * @private */ /** * Stores a copy of the X position. * @readonly * @member tileOBJ#_x * @type {Number} * @private */ /** * Stores a copy of the Y position. * @readonly * @member tileOBJ#_y * @type {Number} * @private */ var _row, _col, _region, _x, _y; /** * Gets all remaining valid tokens. * @method tileOBJ#available * @returns {number[]} some stuff. */ this.setup = function(row, col, region, x, y){ _row = row; _col = col; _region = region; _x = x; _y = y; this.isSetup = true; } /** * Gets the stored refrence to the {@link tileStore} that contains all the tiles in the same row. * @method tileOBJ#getRow * @returns {tileStore} */ this.getRow = function(){ return _row; } /** * Gets the stored refrence to the {@link tileStore} that contains all the tiles in the same column. * @method tileOBJ#getCol * @returns {tileStore} */ this.getCol = function(){ return _col; } /** * Gets the stored refrence to the {@link tileStore} that contains all the tiles in the same region. * @method tileOBJ#getRegion * @returns {tileStore} */ this.getRegion = function(){ return _region; } /** * Gets the stored copy of the X position. * @readonly * @method tileOBJ#getX * @returns {Number} */ this.getX = function(){ return _x; } /** * Gets the stored copy of the Y position. * @readonly * @method tileOBJ#getY * @returns {Number} */ this.getY = function(){ return _y; } /** * Stores the token value of this tile. * @member tileOBJ#_value * @type {Number} * @private */ this._value = 1; /** * Stores the type of this tile. * @member tileOBJ#_value * @type {Number} * @private */ this._type = 1; /** * Stores the type of this tile. * @method tileOBJ#set * @param {tokenENUM} val - The desired token for this tile. * @param {tileOBJ.types} [type=tileOBJ.types.set] - (Optional) The desired type for this tile. */ this.set = function(val, type){ this._value = val; if(typeof(type) == "undefined") this._type = tileOBJ.types.set else this._type = type; } /** * Gets an object that represents the data in this {@link tileOBJ}. * @method tileOBJ#get * @returns {tokenENUM} object.token - The token that the tile currently is set to. * @returns {tileOBJ.types} object.type - The type this tile currently is set to. * @private */ this.get = function(){ return { token: this._value, type: this._type } } /** * Gets the [Type]{@link tileOBJ#types} of this tileOBJ. * @readonly * @method tileOBJ#getType * @returns {Number} */ this.getType=function(){ return this._type; } /** * Sets the [Type]{@link tileOBJ#types} of this tileOBJ. * @readonly * @method tileOBJ#setType * @returns {Number} */ this.setType=function(t){ this._type = t; } /** * Gets the [Token]{@link tokenENUM} of this tileOBJ. * @readonly * @method tileOBJ#getToken * @returns {Number} */ this.getToken=function(){ return this._value; } /** * Sets the [Token]{@link tokenENUM} of this tileOBJ. * @readonly * @method tileOBJ#setToken * @returns {Number} */ this.setToken=function(v){ this._value = v; this._type = tileOBJ.types.set } /** * Stores the tiles guesses as token values. * @member tileOBJ#_guesses * @type {tokenENUM[]} */ this._guesses = []; /** * Stores a guess for this tile. * @method tileOBJ#setGuess * @param {tokenENUM} val - The desired token for this tile. * @param {boolean} [state=true] - (Optional) The desired state of this guess for tile. */ this.setGuess = function(token, state){ if(typeof(state) == "undefined") state = true; this._guesses[token] = state; this.checkGuessState(); } /** * This method is used in guess manipulation functions to check it the tiles type should be changed. * @method tileOBJ#checkGuessState * @private */ this.checkGuessState = function(){ //set counter for guess var count = 0; for (var i = 0; i < this._guesses.length; i++) { if(this._guesses[i] === true) count++; } if(this._type == tileOBJ.types.blank && count > 0) this._type = tileOBJ.types.guess; else if(this._type == tileOBJ.types.guess && count === 0) this._type = tileOBJ.types.blank; } /** * This function will unset the provided token. * This is just a simple helper funtion that basicly calls instance.[setGuess]{@link tileOBJ#set}(token, false) * @see {@link tileOBJ#setGuess} * @method tileOBJ#unsetGuess */ this.unsetGuess = function(token){ this._guesses[token] = false; this.checkGuessState(); } /** * Gets state of the token provided. * @method tileOBJ#getGuess * @param {tokenENUM} token - The token to retrieve state of. * @return {boolean} If the token provided token is a guess on this tile and if it is an active guess. */ this.getGuess = function(token){ if(typeof(this._guesses[token]) == "undefined") return false; if(this._guesses[token] === true) return true; return false; } /** * Retreves all the guesses for the current tile in an array. * @example * [null,true,true,true,true,true,true,true,true,true] * @method tileOBJ#getGuesses * @return the array of guesses */ this.getGuesses = function(){ return this._guesses; } /** * Sets guesses using an array. * @example * tile = new Tile(); * ... * var arr = []; * * // The array does not need to contain a value for all 9 tokens. Only values set in the array are touched. * arr[tokenENUM.c] = true; * arr[tokenENUM.d] = true; * arr[tokenENUM.i] = true; * * // You can insure that a token is false by setting it in the array to false * arr[tokenENUM.f] = false; * * console.log(arr); * // Output: [null,null,null,true,true,null,false,null,null,true] * tile.setGuesses(arr); * * console.log(tile.getGuesses()); * // Output: [null,false,false,true,true,false,false,false,false,true] * @method tileOBJ#setGuesses */ this.setGuesses = function(data){ if(Array.isArray(data)) { var guesses = this._guesses var check = function(token){ if(data[token] === true || data[token] === false){ guesses[token] = data[token]; } } check(tokens.a); check(tokens.b); check(tokens.c); check(tokens.d); check(tokens.e); check(tokens.f); check(tokens.g); check(tokens.h); check(tokens.i); /* this._guesses[tokens.a] = data[tokens.a]; this._guesses[tokens.b] = data[tokens.b]; this._guesses[tokens.c] = data[tokens.c]; this._guesses[tokens.d] = data[tokens.d]; this._guesses[tokens.e] = data[tokens.e]; this._guesses[tokens.f] = data[tokens.f]; this._guesses[tokens.g] = data[tokens.g]; this._guesses[tokens.h] = data[tokens.h]; this._guesses[tokens.i] = data[tokens.i]; */ if(this.getType != tileOBJ.types.set && this.getType != tileOBJ.types.locked) this.checkGuessState(); return; } if(data !== true) data = false; this._guesses = []; this._guesses[tokens.a] = data; this._guesses[tokens.b] = data; this._guesses[tokens.c] = data; this._guesses[tokens.d] = data; this._guesses[tokens.e] = data; this._guesses[tokens.f] = data; this._guesses[tokens.g] = data; this._guesses[tokens.h] = data; this._guesses[tokens.i] = data; if(this.getType != tileOBJ.types.set && this.getType != tileOBJ.types.locked) this.checkGuessState(); } } /** * Enum of Tile Types * @name Tile Types * @readonly * @prop {number} tileOBJ.types.blank 1 * @prop {number} tileOBJ.types.set 2 * @prop {number} tileOBJ.types.guess 3 * @prop {number} tileOBJ.types.locked 4 * @enum {number} * @see {@link tileOBJ#types} * @global */ /** * Enum of Tile Types * @prop {number} blank 1 * @prop {number} set 2 * @prop {number} guess 3 * @prop {number} locked 4 * @name tileOBJ.types * @readonly * @enum {number} */ tileOBJ.types = { blank: 1, set:2, guess:3, locked:4 } module.exports = tileOBJ;
bded27bbd54f950929376a10265e40fe530792c0
[ "JavaScript", "HTML", "Markdown" ]
18
JavaScript
Eforen/HTML5-Sudoku
859396445fe0ede197cb1d309480e61978f366fb
457f8bac45ce2d9aaf5518a82fedb25e4c62b004
refs/heads/master
<repo_name>nathan25maloney/FriendFinder<file_sep>/server.js var express = require("express"); var bodyParser = require("body-parser"); var path = require("path"); var fs = require("fs"); var app = express(); var PORT = process.env.PORT || 3000; app.use(bodyParser.json()); app.use(bodyParser.urlencoded({ extended: true })); app.use(bodyParser.text()); app.use(bodyParser.json({ type: "application/vnd.api+json" })); function recursiveRoutes(folderName) { fs.readdirSync(folderName).forEach(function(file) { var fullName = path.join(folderName, file); var stat = fs.lstatSync(fullName); if (stat.isDirectory()) { recursiveRoutes(fullName); } else if (file.toLowerCase().indexOf('.js')) { console.log("require('" + fullName + "')"); require('./' + fullName)(app); } }); } recursiveRoutes('app/routing'); app.listen(PORT, function() { console.log("App listening on PORT " + PORT); });<file_sep>/app/routing/apiRoutes.js var path = require("path"); var fs = require("fs"); module.exports = function(app){ app.get("/api/friends", function(req, res) { let myJson = null; try { myJson = JSON.parse(fs.readFileSync(path.join(__dirname, "../data/friends.json"), 'utf8')); } catch(e){ } res.send(myJson); }); app.post("/api/friends", function(req, res) { let myJson = null; let closestMatch; let lowestScore = 100; let newFriend = { name: req.body.name, photo: req.body.photo, scores: req.body.scores } let currentScore; try { myJson = JSON.parse(fs.readFileSync(path.join(__dirname, "../data/friends.json"), 'utf8')); } catch(e){ myJson = [] } if(myJson !== undefined){ for (let i = 0; i < myJson.length; i++) { currentScore = compareScores(newFriend.scores,myJson[i].scores) if(currentScore < lowestScore){ lowestScore = currentScore; closestMatch = myJson[i]; } } if(lowestScore < 100){ console.log(closestMatch); closestMatch.matchScore = lowestScore; res.send(closestMatch); delete closestMatch['matchScore']; } }else { } myJson.push(newFriend); fs.writeFile(path.join(__dirname, "../data/friends.json"), JSON.stringify(myJson, null, 2) , 'utf-8'); }); let compareScores = (newArr,oldArr) => { var totalDiff = 0; for (let i = 0; i < oldArr.length; i++) { totalDiff += Math.abs(newArr[i] - oldArr[i]); } console.log(totalDiff); return totalDiff; } }<file_sep>/README.md # FriendFinder This application is a simple match making site for friends. It is hosted on the web with heroku and stores a database with all the people who have entered in the answers to their survey. If there is more than one entry in the database it will take the scores from the survey and match it with the closes answers from another in the database. It will return that match with the persons photo, name and their match score. The lowest possible match score the better. Future fixes would be to add exception handling that would not match someone with themselves if they take the test more than once.
3026cf9156497648e3fa6278c573347a58148afb
[ "JavaScript", "Markdown" ]
3
JavaScript
nathan25maloney/FriendFinder
4925b8378ee70ea2f36a2839c136f211d152d5f6
da139a735eabe258075a34a378ee4244c180fb14
refs/heads/master
<repo_name>jxncyym/SARPN<file_sep>/options/testopt.py import argparse def _get_test_opt(): parser = argparse.ArgumentParser(description = 'Evaluate performance of SARPN on NYU-D v2 test set') parser.add_argument('--backbone', default='SENet154', help='select a network as backbone') parser.add_argument('--testlist_path', required=True, help='the path of testlist') parser.add_argument('--batch_size', type=int, default=1, help='testing batch size') parser.add_argument('--root_path', required=True, help="the root path of dataset") parser.add_argument('--loadckpt', required=True, help="the path of the loaded model") parser.add_argument('--threshold', type=float, default=1.0, help="threshold of the pixels on edges") parser.add_argument('--pretrained_dir', type=str, required=True, help="the path of pretrained models") # parse arguments return parser.parse_args() <file_sep>/evaluate.py import time import torch import numpy as np import torch.nn as nn import torch.nn.parallel import torch.nn.functional from utils import * from models.net import SARPN from options import get_args from collections import OrderedDict from dataloader import nyudv2_dataloader args = get_args('test') # lode nyud v2 test set TestImgLoader = nyudv2_dataloader.getTestingData_NYUDV2(args.batch_size, args.testlist_path, args.root_path) # model model = SARPN(args) model = nn.DataParallel(model) model.cuda() # load test model if args.loadckpt is not None: print("loading model {}".format(args.loadckpt)) state_dict = torch.load(args.loadckpt) model.load_state_dict(state_dict) else: print("You have not loaded any models.") def test(): model.eval() totalNumber = 0 Ae = 0 Pe = 0 Re = 0 Fe = 0 errorSum = {'MSE': 0, 'RMSE': 0, 'ABS_REL': 0, 'LG10': 0, 'MAE': 0, 'DELTA1': 0, 'DELTA2': 0, 'DELTA3': 0} for batch_idx, sample in enumerate(TestImgLoader): print("Processing the {}th image!".format(batch_idx)) image, depth = sample['image'], sample['depth'] depth = depth.cuda() image = image.cuda() image = torch.autograd.Variable(image) depth = torch.autograd.Variable(depth) start = time.time() pred_depth = model(image) end = time.time() running_time = end - start output = torch.nn.functional.interpolate(pred_depth[-1], size=[depth.size(2), depth.size(3)], mode='bilinear', align_corners=True) depth_edge = edge_detection(depth) output_edge = edge_detection(output) batchSize = depth.size(0) totalNumber = totalNumber + batchSize errors = evaluateError(output, depth) errorSum = addErrors(errorSum, errors, batchSize) averageError = averageErrors(errorSum, totalNumber) edge1_valid = (depth_edge > args.threshold) edge2_valid = (output_edge > args.threshold) nvalid = np.sum(torch.eq(edge1_valid, edge2_valid).float().data.cpu().numpy()) A = nvalid / (depth.size(2)*depth.size(3)) nvalid2 = np.sum(((edge1_valid + edge2_valid) ==2).float().data.cpu().numpy()) P = nvalid2 / (np.sum(edge2_valid.data.cpu().numpy())) R = nvalid2 / (np.sum(edge1_valid.data.cpu().numpy())) F = (2 * P * R) / (P + R) Ae += A Pe += P Re += R Fe += F Av = Ae / totalNumber Pv = Pe / totalNumber Rv = Re / totalNumber Fv = Fe / totalNumber print('PV', Pv) print('RV', Rv) print('FV', Fv) averageError['RMSE'] = np.sqrt(averageError['MSE']) print(averageError) if __name__ == '__main__': test() <file_sep>/train.py import os import time import torch import numpy as np import torch.nn as nn import torch.nn.parallel import torch.optim as optim import torch.backends.cudnn as cudnn from utils import * from options import get_args from models.net import SARPN from torch.autograd import Variable from tensorboardX import SummaryWriter from dataloader import nyudv2_dataloader from models.loss import adjust_gt, total_loss cudnn.benchmark = True args = get_args('train') # Create folder makedir(args.checkpoint_dir) makedir(args.logdir) # creat summary logger logger = SummaryWriter(args.logdir) # dataset, dataloader TrainImgLoader = nyudv2_dataloader.getTrainingData_NYUDV2(args.batch_size, args.trainlist_path, args.root_path) # model, optimizer model = SARPN(args) model = nn.DataParallel(model) model.cuda() optimizer = build_optimizer(model = model, learning_rate=args.lr, optimizer_name=args.optimizer_name, weight_decay = args.weight_decay, epsilon=args.epsilon, momentum=args.momentum ) # load parameters start_epoch = 0 ## progress if args.resume: all_saved_ckpts = [ckpt for ckpt in os.listdir(args.checkpoint_dir) if ckpt.endswith(".pth.tar")] all_saved_ckpts = sorted(all_saved_ckpts, key=lambda x:int(x.split('_')[-1].split('.'))[0]) loadckpt = os.path.join(args.checkpoint_dir, all_saved_ckpts[-1]) start_epoch = all_saved_ckpts[-1].split('_')[-1].split('.')[0] print("loading the lastest model in checkpoint_dir: {}".format(loadckpt)) state_dict = torch.load(loadckpt) model.load_state_dict(state_dict) elif args.loadckpt is not None: print("loading model {}".format(args.loadckpt)) start_epoch = args.loadckpt.split('_')[-1].split('.')[0] state_dict = torch.load(args.loadckpt) model.load_state_dict(state_dict) else: print("start at epoch {}".format(start_epoch)) ## train process def train(): for epoch in range(start_epoch, args.epochs): adjust_learning_rate(optimizer, epoch, args.lr) batch_time = AverageMeter() losses = AverageMeter() model.train() end = time.time() for batch_idx, sample in enumerate(TrainImgLoader): image, depth = sample['image'], sample['depth'] depth = depth.cuda() image = image.cuda() image = torch.autograd.Variable(image) depth = torch.autograd.Variable(depth) optimizer.zero_grad() global_step = len(TrainImgLoader) * epoch + batch_idx # get the predicted depth maps of different scales pred_depth = model(image) # adjust ground-truth to the corresponding scales gt_depth = adjust_gt(depth, pred_depth) # Calculate the total loss loss = total_loss(pred_depth, gt_depth) losses.update(loss.item(), image.size(0)) loss.backward() optimizer.step() batch_time.update(time.time() - end) end = time.time() if args.do_summary: all_draw_image = {"image":image, "pred":pred_depth[-1], "gt":gt_depth[-1]} draw_losses(logger, losses.avg, global_step) draw_images(logger, all_draw_image, global_step) #batchSize = depth.size(0) print(('Epoch: [{0}][{1}/{2}]\t' 'Time {batch_time.val:.3f} ({batch_time.sum:.3f})\t' 'Loss {loss.val:.4f} ({loss.avg:.4f})' .format(epoch, batch_idx, len(TrainImgLoader), batch_time=batch_time, loss=losses))) if (epoch+1)%1 == 0: save_checkpoint(model.state_dict(), filename=args.checkpoint_dir + "SARPN_checkpoints_" + str(epoch + 1) + ".pth.tar") if __name__ == '__main__': train() <file_sep>/README.md # Structure-Aware Residual Pyramid Network for Monocular Depth Estimation This is the implementation of the paper [***Structure-Aware Residual Pyramid Network for Monocular Depth Estimation***](https://arxiv.org/abs/1907.06023), ***IJCAI 2019, <NAME>, <NAME>, and <NAME>.*** ## Citation ``` @inproceedings{Chen2019structure-aware, title = {Structure-Aware Residual Pyramid Network for Monocular Depth Estimation}, author = {<NAME> and Chen , Xuejin and <NAME>}, conference={International Joint Conferences on Artificial Intelligence}, year = {2019} } @article{Chen2020LapNet, title={Laplacian Pyramid Neural Network for Dense Continuous-Value Regression for Complex Scenes}, author={<NAME> and <NAME> and Zhang, Yiteng and <NAME> and <NAME>}, journal={IEEE TNNLS}, year={2020} } ``` ## Contents 1. [Introduction](#introduction)<br> 2. [Usage](#usage)<br> 3. [Results](#Results)<br> 4. [Acknowledgements](#Acknowledgements)<br> ## Introduction Monocular depth estimation is an essential task for scene understanding. The underlying structure of objects and stuff in a complex scene is critical to recovering accurate and visually-pleasing depth maps. Global structure conveys scene layouts,while local structure reflects shape details. Recently developed approaches based on convolutional neural networks (CNNs) significantly improve the performance of depth estimation. However, few of them take into account multi-scale structures in complex scenes. In this paper, we propose a Structure-Aware Residual Pyramid Network (SARPN) to exploit multi-scale structures for accurate depth prediction. We propose a Residual Pyramid Decoder (RPD) which expresses global scene structure in upper levels to represent layouts, and local structure in lower levels to present shape details. At each level, we propose Residual Refinement Modules (RRM) that predict residual maps to progressively add finer structures on the coarser structure predicted at the upper level. In order to fully exploit multi-scale image features, an Adaptive Dense Feature Fusion (ADFF) module, which adaptively fuses effective features from all scales for inferring structures of each scale, is introduced. ![figure](./images/overview.png) ## Usage ### Dependencies - [Python3.6](https://www.python.org/downloads/) - [PyTorch(1.0.1)](https://pytorch.org/) - [NYU Depth v2](https://cs.nyu.edu/~silberman/datasets/nyu_depth_v2.html) ### Train As an example, use the following command to train SARPN on NYUDV2.<br> CUDA_VISIBLE_DEVICES="0,1,2,3" python train.py --trainlist_path (the path of trainlist(nyu2_train.csv))\ --checkpoint_dir (the directory to save the checkpoints)\ --root_path (the root path of dataset)\ --logdir (the directory to save logs and checkpoints)\ --pretrained_dir (the path of pretrained models)\ --do_summary ### Evaluation Use the following command to evaluate the trained SARPN on NYUDV2 test data.<br> CUDA_VISIBLE_DEVICES="0" python evaluate.py --testlist_path (the path of testlist(nyu2_test.csv))\ --root_path (the root path of dataset)\ --loadckpt (the path of the loaded model)\ --pretrained_dir (the path of pretrained models)\ --threshold (threshold of the pixels on edges) ### Pretrained Model You can download the pretrained model:<br> **NOTE: You don't need to decompress our pre-trained model. Please use torch.load() to load it.**<br> [NYUDV2](https://1drv.ms/u/s!AhXIHZfUg-uSaQmwNbyEDywBGMc?e=wjUZwc) [KITTI and Height estimation](https://1drv.ms/u/s!AhXIHZfUg-uSch9ylCA2sBnKpsc?e=dYVfKb) ### Pre-processed Data You can download the pre-processed data from this [link](https://drive.google.com/file/d/1WoOZOBpOWfmwe7bknWS5PMUCLBPFKTOw/view?usp=sharing), which is shared by [<NAME>.](https://github.com/JunjH/Revisiting_Single_Depth_Estimation) ## Results **Indoor scene**<br> ![](./images/visualcomparison.png)<br> **Outdoor scene**<br> ![](./images/comp_kitti.PNG) ## Some examples ![](./examples/demo1.gif) ![](./examples/demo2.gif) ## Acknowledgements Thanks to <NAME> for opening source of his excellent [work](https://arxiv.org/abs/1803.08673). Our work is inspired by this work and part of codes. <file_sep>/models/modules.py from collections import OrderedDict import math import torch import torch.nn.functional as F import torch.nn as nn from torch.utils import model_zoo import copy import numpy as np from models import senet from models import resnet from models import densenet import matplotlib.image import matplotlib.pyplot as plt plt.set_cmap("jet") class _UpProjection(nn.Sequential): def __init__(self, num_input_features, num_output_features): super(_UpProjection, self).__init__() self.conv1 = nn.Conv2d(num_input_features, num_output_features, kernel_size=5, stride=1, padding=2, bias=False) self.bn1 = nn.BatchNorm2d(num_output_features) self.relu = nn.ReLU(inplace=True) self.conv1_2 = nn.Conv2d(num_output_features, num_output_features, kernel_size=3, stride=1, padding=1, bias=False) self.bn1_2 = nn.BatchNorm2d(num_output_features) self.conv2 = nn.Conv2d(num_input_features, num_output_features, kernel_size=5, stride=1, padding=2, bias=False) self.bn2 = nn.BatchNorm2d(num_output_features) def forward(self, x, size): x = F.interpolate(x, size=size, mode='bilinear',align_corners=True) x_conv1 = self.relu(self.bn1(self.conv1(x))) bran1 = self.bn1_2(self.conv1_2(x_conv1)) bran2 = self.bn2(self.conv2(x)) out = self.relu(bran1 + bran2) return out class E_resnet(nn.Module): def __init__(self, original_model, num_features = 2048): super(E_resnet, self).__init__() self.conv1 = original_model.conv1 self.bn1 = original_model.bn1 self.relu = original_model.relu self.maxpool = original_model.maxpool self.layer1 = original_model.layer1 self.layer2 = original_model.layer2 self.layer3 = original_model.layer3 self.layer4 = original_model.layer4 def forward(self, x): x = self.conv1(x) x = self.bn1(x) x = self.relu(x) x_block0 = x x = self.maxpool(x) x_block1 = self.layer1(x) x_block2 = self.layer2(x_block1) x_block3 = self.layer3(x_block2) x_block4 = self.layer4(x_block3) feature_pyramid = [x_block0, x_block1, x_block2, x_block3, x_block4] return feature_pyramid class E_densenet(nn.Module): def __init__(self, original_model, num_features = 2208): super(E_densenet, self).__init__() self.features = original_model.features def forward(self, x): x01 = self.features[0](x) x02 = self.features[1](x01) x03 = self.features[2](x02) x_block0 = x03 x04 = self.features[3](x03) x_block1 = self.features[4](x04) x_block1 = self.features[5][0](x_block1) x_block1 = self.features[5][1](x_block1) x_block1 = self.features[5][2](x_block1) x_tran1 = self.features[5][3](x_block1) x_block2 = self.features[6](x_tran1) x_block2 = self.features[7][0](x_block2) x_block2 = self.features[7][1](x_block2) x_block2 = self.features[7][2](x_block2) x_tran2 = self.features[7][3](x_block2) x_block3 = self.features[8](x_tran2) x_block3 = self.features[9][0](x_block3) x_block3 = self.features[9][1](x_block3) x_block3 = self.features[9][2](x_block3) x_tran3 = self.features[9][3](x_block3) x_block4 = self.features[10](x_tran3) x_block4 = F.relu(self.features[11](x_block4)) feature_pyramid = [x_block0, x_block1, x_block2, x_block3, x_block4] return feature_pyramid class E_senet(nn.Module): def __init__(self, original_model, num_features = 2048): super(E_senet, self).__init__() self.base = nn.Sequential(*list(original_model.children())[:-3]) def forward(self, x): x_block0 = nn.Sequential(*list(self.base[0].children())[:-1])(x) x0 = self.base[0](x) x_block1 = self.base[1](x0) x_block2 = self.base[2](x_block1) x_block3 = self.base[3](x_block2) x_block4 = self.base[4](x_block3) feature_pyramid = [x_block0, x_block1, x_block2, x_block3, x_block4] return feature_pyramid class Refineblock(nn.Module): def __init__(self, num_features, kernel_size): super(Refineblock, self).__init__() padding=(kernel_size-1)//2 self.conv1 = nn.Conv2d(1, num_features//2, kernel_size=kernel_size, stride=1, padding=padding, bias=False) self.bn1 = nn.BatchNorm2d(num_features//2) self.conv2 = nn.Conv2d( num_features//2, num_features//2, kernel_size=kernel_size, stride=1, padding=padding, bias=False) self.bn2 = nn.BatchNorm2d(num_features//2) self.conv3 = nn.Conv2d(num_features//2, 1, kernel_size=kernel_size, stride=1, padding=padding, bias=True) def forward(self, x): x_res = self.conv1(x) x_res = self.bn1(x_res) x_res = F.relu(x_res) x_res = self.conv2(x_res) x_res = self.bn2(x_res) x_res = F.relu(x_res) x_res = self.conv3(x_res) x2 = x + x_res return x2 # Residual Pyramid Decoder class RPD(nn.Module): def __init__(self, rpd_num_features = 2048, top_num_features=2048): super(RPD, self).__init__() self.conv = nn.Conv2d(top_num_features, rpd_num_features // 2, kernel_size=1, stride=1, bias=False) self.bn = nn.BatchNorm2d(rpd_num_features//2) self.conv5 = nn.Sequential(nn.Conv2d(rpd_num_features, rpd_num_features//2, kernel_size=3, stride=1, padding=1, bias=False), nn.BatchNorm2d(rpd_num_features//2), nn.ReLU(), nn.Conv2d(rpd_num_features//2, 1, kernel_size=3, stride=1, padding=1, bias=False)) rpd_num_features = rpd_num_features // 2 self.scale5 = Refineblock(num_features=rpd_num_features, kernel_size=3) rpd_num_features = rpd_num_features // 2 self.conv4 = nn.Sequential(nn.Conv2d(rpd_num_features, rpd_num_features, kernel_size=3, stride=1, padding=1, bias=False), nn.BatchNorm2d(rpd_num_features), nn.ReLU(), nn.Conv2d(rpd_num_features, 1, kernel_size=3, stride=1, padding=1, bias=False)) self.scale4 = Refineblock(num_features=rpd_num_features, kernel_size=3) rpd_num_features = rpd_num_features // 2 self.conv3 = nn.Sequential(nn.Conv2d(rpd_num_features, rpd_num_features, kernel_size=3, stride=1, padding=1, bias=False), nn.BatchNorm2d(rpd_num_features), nn.ReLU(), nn.Conv2d(rpd_num_features, 1, kernel_size=3, stride=1, padding=1, bias=False)) self.scale3 = Refineblock(num_features=rpd_num_features, kernel_size=3) rpd_num_features = rpd_num_features // 2 self.conv2 = nn.Sequential(nn.Conv2d(rpd_num_features, rpd_num_features, kernel_size=3, stride=1, padding=1, bias=False), nn.BatchNorm2d(rpd_num_features), nn.ReLU(), nn.Conv2d(rpd_num_features, 1, kernel_size=3, stride=1, padding=1, bias=False)) self.scale2 = Refineblock(num_features=rpd_num_features, kernel_size=3) rpd_num_features = rpd_num_features // 2 self.conv1 = nn.Sequential(nn.Conv2d(rpd_num_features, rpd_num_features, kernel_size=3, stride=1, padding=1, bias=False), nn.BatchNorm2d(rpd_num_features), nn.ReLU(), nn.Conv2d(rpd_num_features, 1, kernel_size=3, stride=1, padding=1, bias=False)) self.scale1 = Refineblock(num_features=rpd_num_features, kernel_size=3) def forward(self, feature_pyramid, fused_feature_pyramid): scale1_size = [fused_feature_pyramid[0].size(2), fused_feature_pyramid[0].size(3)] scale2_size = [fused_feature_pyramid[1].size(2), fused_feature_pyramid[1].size(3)] scale3_size = [fused_feature_pyramid[2].size(2), fused_feature_pyramid[2].size(3)] scale4_size = [fused_feature_pyramid[3].size(2), fused_feature_pyramid[3].size(3)] scale5_size = [fused_feature_pyramid[4].size(2), fused_feature_pyramid[4].size(3)] # scale5 scale5 = torch.cat((F.relu(self.bn(self.conv(feature_pyramid[4]))), fused_feature_pyramid[4]), 1) scale5_depth = self.scale5(self.conv5(scale5)) # scale4 scale4_res = self.conv4(fused_feature_pyramid[3]) scale5_upx2 = F.interpolate(scale5_depth, size=scale4_size, mode='bilinear', align_corners=True) scale4_depth = self.scale4(scale4_res + scale5_upx2) # scale3 scale3_res = self.conv3(fused_feature_pyramid[2]) scale4_upx2 = F.interpolate(scale4_depth, size=scale3_size, mode='bilinear', align_corners=True) scale3_depth = self.scale3(scale3_res + scale4_upx2) # scale2 scale2_res = self.conv2(fused_feature_pyramid[1]) scale3_upx2 = F.interpolate(scale3_depth, size=scale2_size, mode='bilinear', align_corners=True) scale2_depth = self.scale2(scale2_res + scale3_upx2) # scale1 scale1_res = self.conv1(fused_feature_pyramid[0]) scale2_upx2 = F.interpolate(scale2_depth, size=scale1_size, mode='bilinear', align_corners=True) scale1_depth = self.scale1(scale1_res + scale2_upx2) scale_depth = [scale5_depth, scale4_depth, scale3_depth, scale2_depth, scale1_depth] return scale_depth # Adaptive Dense Features Fusion module class ADFF(nn.Module): def __init__(self, block_channel, adff_num_features=1280, rpd_num_features=2048): super(ADFF, self).__init__() rpd_num_features = rpd_num_features // 2 print("block_channel:", block_channel) #scale5 self.upsample_scale1to5 = _UpProjection(num_input_features=block_channel[0], num_output_features=adff_num_features//5) self.upsample_scale2to5 = _UpProjection(num_input_features=block_channel[1], num_output_features=adff_num_features//5) self.upsample_scale3to5 = _UpProjection(num_input_features=block_channel[2], num_output_features=adff_num_features//5) self.upsample_scale4to5 = _UpProjection(num_input_features=block_channel[3], num_output_features=adff_num_features//5) self.upsample_scale5to5 = _UpProjection(num_input_features=block_channel[4], num_output_features=adff_num_features//5) self.conv_scale5 = nn.Conv2d(adff_num_features, rpd_num_features, kernel_size=3, stride=1, padding=1, bias=False) # 1280/1024 self.bn_scale5 = nn.BatchNorm2d(rpd_num_features) adff_num_features = adff_num_features // 2 rpd_num_features = rpd_num_features // 2 # scale4 self.upsample_scale1to4 = _UpProjection(num_input_features=block_channel[0], num_output_features=adff_num_features//5) self.upsample_scale2to4 = _UpProjection(num_input_features=block_channel[1], num_output_features=adff_num_features//5) self.upsample_scale3to4 = _UpProjection(num_input_features=block_channel[2], num_output_features=adff_num_features//5) self.upsample_scale4to4 = _UpProjection(num_input_features=block_channel[3], num_output_features=adff_num_features//5) self.upsample_scale5to4 = _UpProjection(num_input_features=block_channel[4], num_output_features=adff_num_features//5) self.conv_scale4 = nn.Conv2d(adff_num_features, rpd_num_features, kernel_size=3, stride=1, padding=1, bias=False) # 640/512 self.bn_scale4 = nn.BatchNorm2d(rpd_num_features) adff_num_features = adff_num_features // 2 rpd_num_features = rpd_num_features // 2 # scale3 self.upsample_scale1to3 = _UpProjection(num_input_features=block_channel[0], num_output_features=adff_num_features//5) self.upsample_scale2to3 = _UpProjection(num_input_features=block_channel[1], num_output_features=adff_num_features//5) self.upsample_scale3to3 = _UpProjection(num_input_features=block_channel[2], num_output_features=adff_num_features//5) self.upsample_scale4to3 = _UpProjection(num_input_features=block_channel[3], num_output_features=adff_num_features//5) self.upsample_scale5to3 = _UpProjection(num_input_features=block_channel[4], num_output_features=adff_num_features//5) self.conv_scale3 = nn.Conv2d(adff_num_features, rpd_num_features, kernel_size=3, stride=1, padding=1, bias=False) # 320/256 self.bn_scale3 = nn.BatchNorm2d(rpd_num_features) adff_num_features = adff_num_features // 2 rpd_num_features = rpd_num_features // 2 # scale2 self.upsample_scale1to2 = _UpProjection(num_input_features=block_channel[0], num_output_features=adff_num_features//5) self.upsample_scale2to2 = _UpProjection(num_input_features=block_channel[1], num_output_features=adff_num_features//5) self.upsample_scale3to2 = _UpProjection(num_input_features=block_channel[2], num_output_features=adff_num_features//5) self.upsample_scale4to2 = _UpProjection(num_input_features=block_channel[3], num_output_features=adff_num_features//5) self.upsample_scale5to2 = _UpProjection(num_input_features=block_channel[4], num_output_features=adff_num_features//5) self.conv_scale2 = nn.Conv2d(adff_num_features, rpd_num_features, kernel_size=3, stride=1, padding=1, bias=False) # 160/128 self.bn_scale2 = nn.BatchNorm2d(rpd_num_features) adff_num_features = adff_num_features // 2 rpd_num_features = rpd_num_features // 2 #scale1 self.upsample_scale1to1 = _UpProjection(num_input_features=block_channel[0], num_output_features=adff_num_features//5) self.upsample_scale2to1 = _UpProjection(num_input_features=block_channel[1], num_output_features=adff_num_features//5) self.upsample_scale3to1 = _UpProjection(num_input_features=block_channel[2], num_output_features=adff_num_features//5) self.upsample_scale4to1 = _UpProjection(num_input_features=block_channel[3], num_output_features=adff_num_features//5) self.upsample_scale5to1 = _UpProjection(num_input_features=block_channel[4], num_output_features=adff_num_features//5) self.conv_scale1 = nn.Conv2d(adff_num_features, rpd_num_features, kernel_size=3, stride=1, padding=1, bias=False) # 80/64 self.bn_scale1 = nn.BatchNorm2d(rpd_num_features) def forward(self, feature_pyramid): scale1_size = [feature_pyramid[0].size(2), feature_pyramid[0].size(3)] scale2_size = [feature_pyramid[1].size(2), feature_pyramid[1].size(3)] scale3_size = [feature_pyramid[2].size(2), feature_pyramid[2].size(3)] scale4_size = [feature_pyramid[3].size(2), feature_pyramid[3].size(3)] scale5_size = [feature_pyramid[4].size(2), feature_pyramid[4].size(3)] # scale5_mff 8x10 scale_1to5 = self.upsample_scale1to5(feature_pyramid[0], scale5_size) scale_2to5 = self.upsample_scale2to5(feature_pyramid[1], scale5_size) scale_3to5 = self.upsample_scale3to5(feature_pyramid[2], scale5_size) scale_4to5 = self.upsample_scale4to5(feature_pyramid[3], scale5_size) scale_5to5 = self.upsample_scale5to5(feature_pyramid[4], scale5_size) scale5_mff = torch.cat((scale_1to5, scale_2to5, scale_3to5, scale_4to5, scale_5to5), 1) scale5_mff = F.relu(self.bn_scale5(self.conv_scale5(scale5_mff))) # scale4_mff 15x19 scale_1to4 = self.upsample_scale1to4(feature_pyramid[0], scale4_size) scale_2to4 = self.upsample_scale2to4(feature_pyramid[1], scale4_size) scale_3to4 = self.upsample_scale3to4(feature_pyramid[2], scale4_size) scale_4to4 = self.upsample_scale4to4(feature_pyramid[3], scale4_size) scale_5to4 = self.upsample_scale5to4(feature_pyramid[4], scale4_size) scale4_mff = torch.cat((scale_1to4, scale_2to4, scale_3to4, scale_4to4, scale_5to4), 1) scale4_mff = F.relu(self.bn_scale4(self.conv_scale4(scale4_mff))) # scale3_mff 29x38 scale_1to3 = self.upsample_scale1to3(feature_pyramid[0], scale3_size) scale_2to3 = self.upsample_scale2to3(feature_pyramid[1], scale3_size) scale_3to3 = self.upsample_scale3to3(feature_pyramid[2], scale3_size) scale_4to3 = self.upsample_scale4to3(feature_pyramid[3], scale3_size) scale_5to3 = self.upsample_scale5to3(feature_pyramid[4], scale3_size) scale3_mff = torch.cat((scale_1to3, scale_2to3, scale_3to3, scale_4to3, scale_5to3), 1) scale3_mff = F.relu(self.bn_scale3(self.conv_scale3(scale3_mff))) # scale2_mff 57x76 scale_1to2 = self.upsample_scale1to2(feature_pyramid[0], scale2_size) scale_2to2 = self.upsample_scale2to2(feature_pyramid[1], scale2_size) scale_3to2 = self.upsample_scale3to2(feature_pyramid[2], scale2_size) scale_4to2 = self.upsample_scale4to2(feature_pyramid[3], scale2_size) scale_5to2 = self.upsample_scale5to2(feature_pyramid[4], scale2_size) scale2_mff = torch.cat((scale_1to2, scale_2to2, scale_3to2, scale_4to2, scale_5to2), 1) scale2_mff = F.relu(self.bn_scale2(self.conv_scale2(scale2_mff))) # scale1_mff 114x152 scale_1to1 = self.upsample_scale1to1(feature_pyramid[0], scale1_size) scale_2to1 = self.upsample_scale2to1(feature_pyramid[1], scale1_size) scale_3to1 = self.upsample_scale3to1(feature_pyramid[2], scale1_size) scale_4to1 = self.upsample_scale4to1(feature_pyramid[3], scale1_size) scale_5to1 = self.upsample_scale5to1(feature_pyramid[4], scale1_size) scale1_mff = torch.cat((scale_1to1, scale_2to1, scale_3to1, scale_4to1, scale_5to1), 1) scale1_mff = F.relu(self.bn_scale1(self.conv_scale1(scale1_mff))) fused_feature_pyramid = [scale1_mff, scale2_mff, scale3_mff, scale4_mff, scale5_mff] return fused_feature_pyramid <file_sep>/dataloader/nyudv2_dataloader.py import pandas as pd import numpy as np from torch.utils.data import Dataset, DataLoader from torchvision import transforms, utils from PIL import Image import random from dataloader.nyu_transform import * class NYUDV2Dataset(Dataset): """NYUV2D dataset.""" def __init__(self, csv_file, root_path, transform=None): self.frame = pd.read_csv(csv_file, header=None) self.transform = transform self.root_path = root_path def __getitem__(self, idx): image_name = self.frame.ix[idx, 0] depth_name = self.frame.ix[idx, 1] root_path = self.root_path image = Image.open(root_path+image_name) depth = Image.open(root_path+depth_name) sample = {'image': image, 'depth': depth} if self.transform: sample = self.transform(sample) return sample def __len__(self): return len(self.frame) def getTrainingData_NYUDV2(batch_size, trainlist_path, root_path): __imagenet_pca = { 'eigval': torch.Tensor([0.2175, 0.0188, 0.0045]), 'eigvec': torch.Tensor([ [-0.5675, 0.7192, 0.4009], [-0.5808, -0.0045, -0.8140], [-0.5836, -0.6948, 0.4203], ]) } __imagenet_stats = {'mean': [0.485, 0.456, 0.406], 'std': [0.229, 0.224, 0.225]} transformed_training = NYUDV2Dataset(csv_file=trainlist_path, root_path = root_path, transform=transforms.Compose([ Scale(240), RandomHorizontalFlip(), RandomRotate(5), CenterCrop([304, 228], [152, 114]), ToTensor(), Lighting(0.1, __imagenet_pca[ 'eigval'], __imagenet_pca['eigvec']), ColorJitter( brightness=0.4, contrast=0.4, saturation=0.4, ), Normalize(__imagenet_stats['mean'], __imagenet_stats['std']) ])) dataloader_training = DataLoader(transformed_training, batch_size, shuffle=True, num_workers=1, pin_memory=False) return dataloader_training def getTestingData_NYUDV2(batch_size, testlist_path, root_path): __imagenet_stats = {'mean': [0.485, 0.456, 0.406], 'std': [0.229, 0.224, 0.225]} transformed_testing = NYUDV2Dataset(csv_file=testlist_path, root_path=root_path, transform=transforms.Compose([ Scale(240), CenterCrop([304, 228], [304, 228]), ToTensor(is_test=True), Normalize(__imagenet_stats['mean'], __imagenet_stats['std']) ])) dataloader_testing = DataLoader(transformed_testing, batch_size, shuffle=False, num_workers=4, pin_memory=False) return dataloader_testing <file_sep>/models/net.py import torch import torch.nn as nn import numpy as np from models import modules from models import get_models class SARPN(nn.Module): def __init__(self, args): super(SARPN, self).__init__() print("backbone:", args.backbone) self.feature_extraction = get_models(args) if args.backbone in ["ResNet18", "ResNet34"]: adff_num_features = 640 rpd_num_features = 512 block_channel = [64, 64, 128, 256, 512] top_num_features = block_channel[-1] if args.backbone in ["ResNet50", "ResNet101", "ResNet152"]: adff_num_features = 1280 rpd_num_features = 2048 block_channel = [64, 256, 512, 1024, 2048] top_num_features = block_channel[-1] if args.backbone in ["DenseNet121"]: adff_num_features = 640 rpd_num_features = 1024 block_channel = [64, 128, 256, 512, 1024] top_num_features = block_channel[-1] if args.backbone in ["DenseNet161"]: adff_num_features = 1280 rpd_num_features = 2048 block_channel = [96, 192, 384, 1056, 2208] top_num_features = block_channel[-1] if args.backbone in ["DenseNet169"]: adff_num_features = 1280 rpd_num_features = 2048 block_channel = [64, 128, 256, 640, 1664] top_num_features = block_channel[-1] if args.backbone in ["DenseNet201"]: adff_num_features = 1280 rpd_num_features = 2048 block_channel = [64, 128, 256, 896, 1920] top_num_features = block_channel[-1] if args.backbone in ["SENet154"]: adff_num_features = 1280 rpd_num_features = 2048 block_channel = [128, 256, 512, 1024, 2048] top_num_features = block_channel[-1] if args.backbone in ["SE_ResNet50", "SE_ResNet101", "SE_ResNet152", "SE_ResNext50_32x4d", "SE_ResNext101_32x4d"]: adff_num_features = 1280 rpd_num_features = 2048 block_channel = [64, 256, 512, 1024, 2048] top_num_features = block_channel[-1] self.residual_pyramid_decoder = modules.RPD(rpd_num_features, top_num_features) self.adaptive_dense_feature_fusion = modules.ADFF(block_channel, adff_num_features, rpd_num_features) def forward(self, x): feature_pyramid = self.feature_extraction(x) fused_feature_pyramid = self.adaptive_dense_feature_fusion(feature_pyramid) multiscale_depth = self.residual_pyramid_decoder(feature_pyramid, fused_feature_pyramid) return multiscale_depth
0773e65d461e5cfae5a20800f3e69a712f41574e
[ "Markdown", "Python" ]
7
Python
jxncyym/SARPN
95c40892d2ffec6ac12c87de044aabfc0b155a79
2934694b9aec67fd3e45079d950c0d0023ebfa08
refs/heads/master
<repo_name>arayoshipta/TwoDGaussainProblemExample<file_sep>/README.md # TwoDGaussainProblemExample 2 dimensional Gaussian Fitting Example by Apache Commons Math3 (API 3.4) These are the example codes for 2 dimensional Gaussian fitting Problem optimization by Levenberg-Marquardt method by Apache Commons Math (API 3.4). Most of the part of source codes are derived and modified from the [QuadraticProblemExample_2.java](https://github.com/arayoshipta/QuadraticProblemExample2). Thank you. <NAME> <file_sep>/src/main/java/pta2/track/tdgaussian/TwoDGaussianFunction.java package pta2.track.tdgaussian; import org.apache.commons.math3.analysis.MultivariateMatrixFunction; import org.apache.commons.math3.analysis.MultivariateVectorFunction; /** * Two dimensional Gaussian function for LM fitting * @author <NAME> * @version 1.0 * @date 07/01/2015 */ public class TwoDGaussianFunction { // Member variables int data_width; // width of data int data_size; // data size /** * @param data input data * @param data_width input data width */ public TwoDGaussianFunction(int data_width,int data_size) { this.data_width = data_width; this.data_size = data_size; } public MultivariateVectorFunction retMVF() { return new MultivariateVectorFunction() { @Override public double[] value(double[] v) throws IllegalArgumentException { double[] values = new double[data_size]; // pre-calculation double v3v3 = v[3]*v[3]; double v4v4 = v[4]*v[4]; double sqrt_twopiv3v4 = Math.sqrt(2*Math.PI*v3v3*v4v4); for (int i = 0; i < values.length; ++i) { // parameters for x,y positioning int xi = i % data_width; int yi = i / data_width; /* * f(x,y) = A/sqrt(2*pi*s_x^2*s_y^2)*exp(-(x-x_m)^2/(2*s_x^2))*exp(-(y-y_m)^2/(2*s_y^2))+offset * v[0] : A * v[1] : x_m mean of x * v[2] : y_m mean of y * v[3] : s_x sigma of x * v[4] : s_y sigma of y * v[5] : offset offset */ values[i] = v[0]/sqrt_twopiv3v4 *Math.exp(-(xi-v[1])*(xi-v[1])/(2*v3v3)) *Math.exp(-(yi-v[2])*(yi-v[2])/(2*v4v4)) +v[5]; } return values; } }; } /** * Return the jacobian of the model function * @return return the jacobian */ public MultivariateMatrixFunction retMMF() { return new MultivariateMatrixFunction() { @Override public double[][] value(double[] point) throws IllegalArgumentException { return jacobian(point); } private double[][] jacobian(double[] v) { double[][] jacobian = new double[data_size][6]; double v3v3 = v[3]*v[3]; double v4v4 = v[4]*v[4]; double sqrt_twopiv3v4 = Math.sqrt(2*Math.PI*v3v3*v4v4); for (int i = 0; i < jacobian.length; ++i) { // parameters for x,y positioning int xi = i % data_width; int yi = i / data_width; double exp_x = Math.exp(-(xi-v[1])*(xi-v[1])/(2*v3v3)); double exp_y = Math.exp(-(yi-v[2])*(yi-v[2])/(2*v4v4)); //partial differentiations were calculated by using Maxima jacobian[i][0] = exp_x*exp_y/sqrt_twopiv3v4; //df(x,y)/dv0 jacobian[i][1] = v[0]*(xi-v[1])/v3v3*jacobian[i][0]; //df(x,y)/dv1 jacobian[i][2] = v[0]*(yi-v[2])/v4v4*jacobian[i][0]; //df(x,y)/dv2 jacobian[i][3] = jacobian[i][1]*(xi-v[1])/v[3]-v[0]*jacobian[i][0]/v[3]; //df(x,y)/dv3 jacobian[i][4] = jacobian[i][2]*(yi-v[2])/v[4]-v[0]*jacobian[i][0]/v[4]; //df(x,y)/dv4 jacobian[i][5] = 1; //df(x,y)/dv5 } return jacobian; } }; } }
6059509a67c5d23fb77a75ae50c7fc02587db1c8
[ "Markdown", "Java" ]
2
Markdown
arayoshipta/TwoDGaussainProblemExample
4de0949648b90ec234d66d55973b228ce2689bdb
d0816494154cc0c8923c31c9eb49db4b5f5ae4dc
refs/heads/main
<file_sep>const commonjs = require('rollup-plugin-commonjs'); module.exports = { // Input is created by webpack in previous build step, in CommonJS format. input: 'dist/context.js', output: { file: 'dist/context.esm.js', format: 'esm' }, plugins: [ commonjs({ // explicitly list exports otherwise only have 'default' namedExports: { 'dist/context.js': [ 'contexts', 'constants', 'CONTEXT', 'CONTEXT_URL', 'CONTEXT_URL_V1', 'DID_CONTEXT_URL' ] } }) ] }; <file_sep>'use strict'; const context = require('./context'); const constants = require('./constants'); const {CONTEXT_URL, DID_CONTEXT_URL} = constants; const contexts = new Map(); contexts.set(CONTEXT_URL, context); module.exports = { constants, contexts, DID_CONTEXT_URL, CONTEXT_URL, CONTEXT_URL_V1: CONTEXT_URL, CONTEXT: context }; <file_sep># did-context ChangeLog ## 3.1.1 - 2021-09-14 ### Fixed - Fix rollup export. ## 3.1.0 - 2021-09-14 ### Changed - Refactor to use current context repo template (generate the `.jsonld` during build). ## 3.0.1 - 2021-04-14 ### Fixed - Remove `"@container": "@set"` properties from `alsoKnownAs` and `service` terms, to match the DID Registries definition. ## 3.0.0 - 2021-03-30 ### Changed - **BREAKING**: Remove non-DID Core properties. - **BREAKING**: Enable term protection. - **BREAKING**: Change context url from `https://w3id.org/did/v0.11` to `https://www.w3.org/ns/did/v1`. ## 2.0.0 - 2019-07-02 ### Added - Add terms: - `EcdsaSecp256k1Signature2019` - `EcdsaSecp256k1VerificationKey2019` - `SchnorrSecp256k1Signature2019` - `SchnorrSecp256k1VerificationKey2019` - `keyAgreement` ### Changed - New repository for packaging. Previously mixed in with the [did-spec][] repository. - **BREAKING**: Implement a new module structure. - Build and distribute static browser version with all contexts. - Export a `contexts` Map associating context URIs to contexts. - Export a `constants` Object associating short ids to contexts URIs. ## 1.0.0 - 2019-01-03 See git history of [did-spec][] for changes previous to this release. [did-spec]: https://github.com/w3c-ccg/did-spec <file_sep># DID Context _(did-context)_ [![NPM Version](https://img.shields.io/npm/v/did-context.svg?style=flat-square)](https://npm.im/did-context) <!--[![Build Status](https://travis-ci.org/digitalbazaar/did-context.png?branch=master)](https://travis-ci.org/digitalbazaar/did-context)--> > A [DID][did-spec] (Decentralized Identifier) context library for JavaScript This project packages the DID Context from the [DID specification][did-spec] for use with [Node.js][Node.js] and web apps. ## Table of Contents - [Security](#security) - [Background](#background) - [Install](#install) - [Usage](#usage) - [Contribute](#contribute) - [Commercial Support](#commercial-support) - [License](#license) ## Security TBD ## Background See also (related specs): * [Decentralized Identifiers (DIDs) - Data Model and Syntaxes][did-spec] * [Decentralized Identifier Resolution](https://w3c-ccg.github.io/did-resolution/) ## Install Requires [Node.js][] 8.3+ To install via [NPM][]: ``` npm install did-context ``` ## Usage ```js import didContext from 'did-context'; // or const didContext = require('did-context'); // use URL in a JSON-LD context const obj = { "@context": [ didContext.CONTEXT_URL_V1, // ... ], // ... }; // get context data for a specific context const data = didContext.CONTEXT; // ... ``` This package can be used with bundlers, such as [webpack][], in browser applications. ## API The library exports two properties: - `constants`: A Object that maps constants to well-known context URLs. The main constant `DID_CONTEXT_URL` may be updated from time to time to the latest context location. - `contexts`: A `Map` that maps URLs to full context data. ## Contribute Code and packaging development is at the [did-context][] project. The contexts themselves are developed in the [did-spec][] project. Contexts in this package are updated manually from the [did-spec][] contexts. Please file an issue if this package is not synced with [did-spec][] changes in a timely manner. Small note: If editing the Readme, please conform to the [standard-readme](https://github.com/RichardLitt/standard-readme) specification. ## Commercial Support Commercial support for this library is available upon request from Digital Bazaar: <EMAIL> ## License - Code: BSD 3-Clause © Digital Bazaar - Contexts: W3C Software and Document License - See the [LICENSE](./LICENSE.md) file for details. [did-context]: https://github.com/digitalbazaar/did-context [did-spec]: https://www.w3.org/TR/did-core/ [NPM]: https://www.npmjs.com/ [Node.js]: https://nodejs.org/ [webpack]: https://webpack.js.org/ <file_sep>'use strict'; const DID_CONTEXT_URL = 'https://www.w3.org/ns/did/v1'; module.exports = { CONTEXT_FILENAME: 'did-v1.jsonld', DID_CONTEXT_URL, CONTEXT_URL: DID_CONTEXT_URL, CONTEXT_URL_V1: DID_CONTEXT_URL }; <file_sep>module.exports = function(config) { const bundler = process.env.BUNDLER || 'webpack'; const frameworks = ['mocha', 'chai']; const files = ['*.spec.js']; // browser launchers: https://npmjs.org/browse/keyword/karma-launcher // browsers: ['ChromeHeadless', 'Chrome', 'Firefox', 'Safari'], const browsers = ['ChromeHeadless']; const reporters = ['mocha']; const client = { mocha: { timeout: 10000, // 10 sec reporter: 'html' //delay: true } }; // main bundle preprocessors const preprocessors = []; preprocessors.push(bundler); preprocessors.push('sourcemap'); return config.set({ frameworks, files, reporters, basePath: '', port: 9876, colors: true, browsers, client, // level of logging // possible values: config.LOG_DISABLE || config.LOG_ERROR || // config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG logLevel: config.LOG_INFO, singleRun: true, // enable / disable watching file and executing test whenever any // file changes autoWatch: false, // preprocess matching files before serving them to the browser // available preprocessors: // https://npmjs.org/browse/keyword/karma-preprocessor preprocessors: { '*.spec.js': preprocessors, }, webpack: { devtool: 'inline-source-map', mode: 'development', } }); };
61ed04274cfe4035d7217f80c9ce43d3b99052ac
[ "JavaScript", "Markdown" ]
6
JavaScript
digitalbazaar/did-context
a79b64acdbf81fb4f8545e3627576b94e5b8a27e
97e8b78bff2928699d39a2801a5bd333ae1a8412
refs/heads/master
<file_sep>speakers_array = ["Edsger","Ada","Charles","Alan","Grace","Linus","Matz"] rooms_array = ["1", "2", "3", "4", "5", "6", "7"] def HelloMyNameIs (speakers_array) counter = 0 speakers_array.length.times do puts "Hello, My name is #{speakers_array[counter]}" end HelloMyNameIs(speakers_array) #def badge_maker(speaker_name) #putting the array name in the parentheses will display all the speakers' names in one output #puts "Hello my name is #{speaker_name}" #end #def batch_badge_creator(r) # counter = 0 #while counter <= speakers_array.length #badge_maker(r) #counter =+ 1 #end #end #batch_badge_creator(speakers_array)
06258d3959186d002bdd2c11b2602734d04ad614
[ "Ruby" ]
1
Ruby
Hokeepokie/badges-and-schedules-manhattan-fasttrack-111018
817b20daff14ad72173602d97a59d297cd33833a
bb726ec57c7dac58195768fa711f82642b37c22a
refs/heads/master
<file_sep>package com.atguigu.git.test; public class Client { public static void main(String[] args) { System.out.println("hello 0407"); System.out.println("hello 0407 2"); System.out.println("hello 0407 3"); System.out.println("hello p2"); System.out.println("回复 Github服务器"); System.out.println("回复 Github服务器v21"); System.out.println("0407 springmvc"); int i = 0; int j = 100; int x = i + j / 2; System.out.println(x); } }
a664ff10cc29a744ff66ea2cd1c50d0bf0a18ee9
[ "Java" ]
1
Java
lufeilong/crm0407
0d13e86a76f2c3ce4d93512dbc2a20d5b316224e
2d23242ea2ea54f71890010d6fa3b23aa1baf45d
refs/heads/master
<repo_name>shunf4/Shadowray<file_sep>/shadowray/subscribe/parser.py import requests import json from shadowray.common.B64 import decode from shadowray.config.v2ray import SUBSCRIBE_FILE from shadowray.core.configuration import Configuration import urllib.parse import itertools import base64 def base64_decode(x): #if debug: eprint(x) return base64.urlsafe_b64decode(x + '=' * (-len(x) % 4)).decode("utf-8") def urlsafe_base64_decode(x): #if debug: eprint(x) return base64.urlsafe_b64decode(x + '=' * (-len(x) % 4)).decode("utf-8") def compat_base64_decode(x): try: return base64_decode(x) except Exception: return urlsafe_base64_decode(x) def urlsafe_base64_encode(x): if debug: eprint(x) r = base64.urlsafe_b64encode(x.encode("utf-8")).decode("ascii") if debug: eprint(r) while r and r[-1] == '=': r = r[:-1] if debug: eprint(r) return r class Parser: def __init__(self, filename=None, template=None): self.servers = [] self.filename = None self.subscribes = json.loads("{}") if filename is not None: f = open(filename, "r") self.subscribes = json.load(f) f.close() self.filename = filename if template is not None: f = open(template, "r") self.template = json.load(f) f.close() else: self.template = None def get_url(self, url, **kwargs): r = requests.get(url).text text = decode(r) text = text.split('\n') mux = 0 if kwargs.get("mux") is not None: mux = kwargs.get("mux") for t in text: if len(t) == 0: continue original_t = t t = t.split("://") if self.template: config = Configuration(self.template) else: config = Configuration() socks_port = 1082 http_port = 8118 listen_addr = "127.0.0.1" if kwargs.get("socks_port") is not None: socks_port = kwargs.get("socks_port") if kwargs.get("http_port") is not None: http_port = kwargs.get("http_port") if kwargs.get("listen_addr") is not None: listen_addr = kwargs.get("listen_addr") inbound = Configuration.Inbound(socks_port, listen_addr, "socks") socks = Configuration.ProtocolSetting.Inbound.Socks() inbound.set_settings(socks) config.add_inbound(inbound) inbound = Configuration.Inbound(http_port, listen_addr, "http") http = Configuration.ProtocolSetting.Inbound.Http(0) inbound.set_settings(http) config.add_inbound(inbound) if t[0] == "vmess": t[1] = json.loads(decode(t[1])) outbound = Configuration.Outbound("vmess", "proxy") vmess = Configuration.ProtocolSetting.Outbound.VMess() vmess_server = Configuration.ProtocolSetting.Outbound.VMess.Server(addr=t[1]['add'], port=int(t[1]['port'])) vmess_server.add_user(id=t[1]['id'], aid=int(t[1].get('aid', 0)), security='auto', level=int(t[1].get('level', 0))) vmess.add_server(vmess_server) outbound.set_settings(vmess) stream = Configuration.StreamSetting(type=Configuration.StreamSetting.STREAMSETTING, network=t[1]['net'], security=t[1].get('tls', 'auto')) stream.set_web_socket(Configuration.StreamSetting.WebSocket(t[1].get('path', '/'))) masquerade_type = t[1].get('type', 'none') stream.set_tcp(Configuration.StreamSetting.TCP(masquerade_type != 'none', masquerade_type)) outbound.set_stream(stream) outbound.set_mux(Configuration.Outbound.Mux(mux != 0, mux)) server_obj = { "protocol": t[0], "config": None, "ps": t[1]['ps'], "host": t[1]['add'] } if t[0] == "ss": outbound = Configuration.Outbound("shadowsocks", "proxy") ss = Configuration.ProtocolSetting.Outbound.Shadowsocks() tmp1 = original_t[len("ss://"):].split('#') if len(tmp1) < 2: tmp1.append("") tmp_ps = urllib.parse.unquote(tmp1[-1]) ss_body = '#'.join(tmp1[:-1]) if not ('@' in ss_body): ss_body = compat_base64_decode(ss_body) tmp2 = ss_body.split("@") if ':' in tmp2[0]: ss_user = tmp2[0] else: ss_user = compat_base64_decode(tmp2[0]) ss_enc, ss_password = ss_user.split(":") ss_add, ss_port = tmp2[1].split(":") ss_port = ''.join(itertools.takewhile(str.isdigit, ss_port)) ss_ps = ("%s:%s" % (ss_add, ss_port)) if not tmp_ps else tmp_ps.strip() ss_obj = { "is_ss": True, "add": ss_add, "port": ss_port, "enc": ss_enc, "password": <PASSWORD>, "ps": ss_ps } ss.add_server(str(ss_obj["add"]), int(ss_obj["port"]), str(ss_obj["enc"]), str(ss_obj["password"]), 0) outbound.set_settings(ss) stream = Configuration.StreamSetting(type=Configuration.StreamSetting.STREAMSETTING, network="tcp", security="none") outbound.set_stream(stream) server_obj = { "protocol": t[0], "config": None, "ps": ss_ps, "host": ss_add } config.insert_outbound(0, outbound) server_obj["config"] = config.json_obj self.servers.append(server_obj) def update(self, name=None, show_info=False, **kwargs): self.servers.clear() if name is None: for j in self.subscribes: if show_info: print("update %s : %s" % (j, self.subscribes[j])) self.get_url(self.subscribes[j], **kwargs) else: if show_info: print("update %s : %s" % (name, self.subscribes[name])) self.get_url(self.subscribes[name], **kwargs) def save(self, filename=None): if filename is None: filename = SUBSCRIBE_FILE f = open(filename, 'w') f.write(json.dumps(self.subscribes)) f.close() def add(self, name, url): self.subscribes[name] = url def delete(self, name): del self.subscribes[name] def get_servers(self): return self.servers
74230d3b419fd9cc81f4a3d92991fcab8387dd9e
[ "Python" ]
1
Python
shunf4/Shadowray
3ec2e69a9b079e051983f7d84252ba787ce933a2
e6045c9515ecb0deb86b49a14acda12c8d4d3c7d
refs/heads/master
<repo_name>secondLieutenantCoder/DouDouChong<file_sep>/Podfile platform:ios,'8.0' target 'DouDouChong' do pod 'AMap3DMap' pod 'AMapSearch' pod 'AMapLocation' pod 'mob_smssdk' pod 'WechatOpenSDK' end
795c7d44527a2465ada6ac851e68e73038f43062
[ "Ruby" ]
1
Ruby
secondLieutenantCoder/DouDouChong
6da9e02dd4538a44722e2eda87208e545529b934
f2c9915a246ad51c710e68684474d025161c98a0
refs/heads/master
<repo_name>jsuarezm94/PG4<file_sep>/client/client.c // Computer Networks - CSE 30264 // Programming Assignment 4 // October 31, 2016 // Authors: <NAME> & <NAME> // NETIDs: jdiazort & jsuarezm // Client #include <stdio.h> #include <stdlib.h> #include <string.h> #include <stdint.h> #include <time.h> #include <math.h> #include <dirent.h> #include <sys/types.h> #include <sys/stat.h> #include <sys/mman.h> #include <fcntl.h> #include <sys/socket.h> #include <netinet/in.h> #include <netdb.h> #include <unistd.h> #include <time.h> #include <sys/time.h> #include <openssl/md5.h> int32_t fileSize(char * file_name) { FILE *fp; int32_t file_size = -1; if(fp = fopen(file_name, "r")) { fseek(fp,0,SEEK_END); file_size = ftell(fp); fseek(fp,0,SEEK_SET); fclose(fp); } return file_size; } //end FILESIZE /* CREATE BOARD */ void create (int udp_sock, struct sockaddr_in sin) { /* Declare variables */ char board_name[100]; // Board name char server_resp[100]; // Server response int addr_len; memset(board_name, '\0', sizeof(board_name)); memset(server_resp, '\0', sizeof(server_resp)); /* Prompt user input */ printf("Enter name of board to create: "); scanf("%s", board_name); /* Send board name to server */ if(sendto(udp_sock,board_name,strlen(board_name),0,(struct sockaddr *)&sin, sizeof(struct sockaddr)) == -1) { perror("ERROR: client-sendto()\n"); exit(1); } //end sendto check /* Receive server confirmation regarding creation of board and print results */ if(recvfrom(udp_sock,server_resp,sizeof(server_resp),0,(struct sockaddr *)&sin, &addr_len) == -1) { perror("ERROR: client-recvfrom()\n"); exit(1); } //end recvfrom check if (strcmp(server_resp,"Yes") == 0) { printf("Success: Board %s has been created\n", board_name); } else { printf("Failure: Board %s has not been created\n", board_name); } } // end CREATE BOARD /* LEAVE MESSAGE */ void message (int udp_sock, struct sockaddr_in sin) { /* Declare variables */ char board_name[100]; // Board name char message[4096]; // Message to be added char server_resp[100]; // Server response int addr_len; char *message_ptr = NULL; size_t size; memset(board_name, '\0', sizeof(board_name)); memset(message, '\0', sizeof(message)); memset(server_resp, '\0', sizeof(server_resp)); /* Prompt user input */ printf("Enter name of board to add message: "); scanf("%s", board_name); /* Send board name to server */ if(sendto(udp_sock,board_name,strlen(board_name),0,(struct sockaddr *)&sin, sizeof(struct sockaddr)) == -1) { perror("ERROR: client-sendto()\n"); exit(1); } //end sendto check /* Prompt user input */ printf("Enter message: "); /* if (getline(&message_ptr, &size, stdin) == -1) { printf("Failed to read message\n"); exit(1); } else { printf("LINE: %s", message_ptr); } */ scanf("%s", message); //fgets(message, sizeof(message), stdin); //getline(&message2, &n, stdin); /* Send message to server */ if(sendto(udp_sock,message,strlen(message),0,(struct sockaddr *)&sin, sizeof(struct sockaddr)) == -1) { perror("ERROR: client-sendto()\n"); exit(1); } //end sendto check /* Receive server confirmation regarding addition of message and print results */ if(recvfrom(udp_sock,server_resp,sizeof(server_resp),0,(struct sockaddr *)&sin, &addr_len) == -1) { perror("ERROR: client-recvfrom()\n"); exit(1); } //end recvfrom check if (strcmp(server_resp,"Yes") == 0) { printf("Success: Message '%s' has been added to Board %s\n", message_ptr, board_name); } else { printf("Failure: Message '%s' was not added to Board %s\n", message_ptr, board_name); } } //end LEAVE MESSAGE /* DELETE MESSAGE */ void deleteMessage (int udp_sock, struct sockaddr_in sin) { /* Declare variables */ char board_name[100]; // Board name char message[4096]; // Message to be deleted //int message2; // Message to be deleted char server_resp[100]; // Server response int addr_len; memset(board_name, '\0', sizeof(board_name)); memset(message, '\0', sizeof(message)); memset(server_resp, '\0', sizeof(server_resp)); /* Prompt user input */ printf("Enter name of board to delete message: "); scanf("%s", board_name); /* Send board name to server */ if(sendto(udp_sock,board_name,strlen(board_name),0,(struct sockaddr *)&sin, sizeof(struct sockaddr)) == -1) { perror("ERROR: client-sendto()\n"); exit(1); } //end sendto check /* Prompt user input */ printf("Enter message to be deleted: "); scanf("%s", message); /* Send message to server */ if(sendto(udp_sock,message,strlen(message),0,(struct sockaddr *)&sin, sizeof(struct sockaddr)) == -1) { perror("ERROR: client-sendto()\n"); exit(1); } //end sendto check /* Receive server confirmation regarding deletion of message and print results */ if(recvfrom(udp_sock,server_resp,sizeof(server_resp),0,(struct sockaddr *)&sin, &addr_len) == -1) { perror("ERROR: client-recvfrom()\n"); exit(1); } //end recvfrom check printf("RESPONSE: %s\n", server_resp); if (strcmp(server_resp,"Yes") == 0) { printf("Success: Message '%s' has been deleted from Board %s\n", message, board_name); } else { printf("Failure: Message '%s' was not deleted from Board %s\n", message, board_name); } } //end DELETE MESSAGE /* EDIT MESSAGE */ void edit (int udp_sock, struct sockaddr_in sin) { /* Declare variables */ char board_name[100]; // Board name char message[4096]; // Message to be replaced char new_message[4096]; // New message char server_resp[100]; // Server response int addr_len; memset(board_name, '\0', sizeof(board_name)); memset(message, '\0', sizeof(message)); memset(new_message, '\0', sizeof(new_message)); memset(server_resp, '\0', sizeof(server_resp)); /* Prompt user input */ printf("Enter name of board to replace message: "); scanf("%s", board_name); /* Send board name to server */ if(sendto(udp_sock,board_name,strlen(board_name),0,(struct sockaddr *)&sin, sizeof(struct sockaddr)) == -1) { perror("ERROR: client-sendto()\n"); exit(1); } //end sendto Check /* Prompt user input */ printf("Enter message to be replaced: "); scanf("%s", message); /* Send message to be replaced to server */ if(sendto(udp_sock,message,strlen(message),0,(struct sockaddr *)&sin, sizeof(struct sockaddr)) == -1) { perror("ERROR: client-sendto()\n"); exit(1); } //end sendto check /* Prompt user input */ printf("Enter new message: "); scanf("%s", new_message); /* Send new message to server */ if(sendto(udp_sock,new_message,strlen(new_message),0,(struct sockaddr *)&sin, sizeof(struct sockaddr)) == -1) { perror("ERROR: client-sendto()\n"); exit(1); } //end sendto check /* Receive server confirmation regarding replacement of message and print results */ if(recvfrom(udp_sock,server_resp,sizeof(server_resp),0,(struct sockaddr *)&sin, &addr_len) == -1) { perror("ERROR: client-recvfrom()\n"); exit(1); } // end recvfrom check if (strcmp(server_resp,"Yes") == 0) { printf("Success: Message '%s' has been replaced in Board %s\n", message, board_name); } else { printf("Failure: Message '%s' was not replaced in Board %s\n", message, board_name); } } //end EDIT MESSAGE /* LIST BOARDS */ void list (int udp_sock, struct sockaddr_in sin) { /* Declare variables */ char board_names[4096]; // List of boards int addr_len; int dir_size = 0; int dir_bytes = 0; int n_bytes = 0; char list_buf[100]; memset(board_names,'\0',sizeof(board_names)); /* Receive board listing size from server and print results */ if(recvfrom(udp_sock,&dir_size,sizeof(dir_size),0,(struct sockaddr *)&sin,&addr_len) == -1) { perror("ERROR: client-recvfrom()\n"); exit(1); } //end recvfrom check while (n_bytes < dir_size) { if(recvfrom(udp_sock,list_buf,sizeof(list_buf),0,(struct sockaddr *)&sin,&addr_len) == -1) { perror("ERROR: client-recvfrom()\n"); exit(1); } //end recvfrom check n_bytes ++; printf("%s\n", list_buf); fflush(stdout); memset(list_buf, '\0', sizeof(list_buf)); } } //end LIST BOARDS /* READ BOARD */ void readBoard (int tcp_sock) { /* Declare variables */ char board_name[100]; // Board name int32_t board_len; // Length of board name int32_t server_board_size=1; // Server response - board size int server_data_received; // Current data received int total_data_received; // Total data received char server_board[4096]; // Board contents char bsize[100]; int status; memset(bsize,'\0', sizeof(bsize)); /* Prompt user input */ printf("Enter board name to read: "); scanf("%s", board_name); /* Send length of filename and filename */ board_len = strlen(board_name); board_len = htonl(board_len); if (send(tcp_sock,&board_len,sizeof(int32_t),0) == -1) { perror("ERROR: client-send()\n"); exit(1); } //end send check if (send(tcp_sock,board_name,sizeof(board_name),0) == -1) { perror("ERROR: client-send()\n"); exit(1); } //end send check /* Receive server confirmation in terms of file size */ /* if ( (status = recv(tcp_sock,&server_board_size,sizeof(int32_t),0) ) == -1) { perror("ERROR: client-recv()\n"); exit(1); } // end recv check */ recv(tcp_sock,bsize,sizeof(bsize),0); printf("bsize = %s", bsize); int sizeb; sizeb = atoi(bsize); printf ("sizeb = %i\n", sizeb); printf("status = %i\n", status); printf("BOARD SIZE: %i\n", server_board_size); server_board_size = ntohl(server_board_size); printf("BOARD SIZE: %i\n", server_board_size); /* Interpret server response and output appropriate message to user */ if (server_board_size < 0) { printf("Board '%s' does not exist\n", board_name); return; } /* If board exists, enter loop to receive board contents until total data received == server_board_size */ total_data_received = 0; printf("Before receiving data\n"); while (total_data_received < server_board_size) { printf("Inside while loop\n"); if ((server_data_received = recv(tcp_sock,server_board,sizeof(server_board),0)) == -1) { printf("Receiving data\n"); total_data_received += server_data_received; printf("%s\n",server_board); } //end if } //end WHILE } // end READ BOARD /* APPEND FILE */ void append(int tcp_sock) { /* Declare variables */ char board_name[100]; // Board name int board_len; // Length of board name char file_name[100]; // File name int file_len; // Length of file name int server_response; // Server confirmation int file_size,original_size; // File size FILE *fp; char file_line[20000]; int len, sent_len; /* Prompt user input */ printf("Enter board name to read: "); scanf("%s",board_name); /* Send length of board name and board name */ board_len = strlen(board_name); board_len = htonl(board_len); if (send(tcp_sock,&board_len,sizeof(board_len),0) == -1) { perror("ERROR: client-send()\n"); exit(1); } //end send check if (send(tcp_sock,board_name,sizeof(board_name),0) == -1) { perror("ERROR: client-send()\n"); exit(1); } //end send check /* Prompt user input */ printf("Enter name of file to append: "); scanf("%s", file_name); /* Send length of filename and filename */ file_len = strlen(file_name); file_len = htonl(file_len); if (send(tcp_sock,&file_len,sizeof(file_len),0) == -1) { perror("ERROR: client-send()\n"); exit(1); } //end send check if (send(tcp_sock,file_name,sizeof(file_name),0) == -1) { perror("ERROR: client-send()\n"); exit(1); } //end send check /* Recieve server confirmation */ if (recv(tcp_sock,&server_response, sizeof(server_response),0) == -1) { perror("ERROR: client-recv()\n"); exit(1); } //end recv check printf("RESPONSE: %i\n", server_response); /* Interpret server confirmation and output appropriate message */ /* Response = 1 -> board exists and file can be created */ /* Response = -1 -> board does not exist */ /* Response = -2 -> board exists, and attachment already exists on board */ if (server_response == -1) { printf("Board does not exist\n"); return; } else if (server_response == -2) { printf("Attachment already exists on board\n"); return; } else {} /* Calculate file size and send it to the server */ file_size = fileSize(file_name); original_size = file_size; file_size = htonl(file_size); if (send(tcp_sock,&file_size,sizeof(int32_t),0) == -1) { perror("ERROR: client-send()\n"); exit(1); } //end send check printf("SENT FILE SIZE: %i\n", original_size); if (original_size == -1) { printf("File does not exist locally\n"); return; } /* Open file */ fp = fopen(file_name, "r"); memset(file_line, '\0', sizeof(file_line)); /* Read file and send to server line by line */ len = 0; sent_len = 0; while ( len=fread(file_line,sizeof(char),sizeof(file_line),fp) > 0) { sent_len = send(tcp_sock,file_line,len,0); memset(file_line, '\0', sizeof(file_line)); } //end reading file fclose(fp); } // end APPEND FILE /* DOWNLOAD FILE */ void download (int tcp_sock) { /* Declare variables */ char board_name[100]; // Board name int board_len; // Length of board name char file_name[100]; // File name int file_len; // Length of file name int server_response; // Server confirmation int file_size; // File size FILE *fp; char file_line[20000]; int len, recv_len, recv_bytes, write_size; /* Prompt user input */ printf("Enter board name to download from: "); scanf("%s",board_name); /* Send length of board name and board name */ board_len = strlen(board_name); board_len = htonl(board_len); if (send(tcp_sock,&board_len,sizeof(board_len),0) == -1) { perror("ERROR: client-send()\n"); exit(1); } //end send check if (send(tcp_sock,board_name,sizeof(board_name),0) == -1) { perror("ERROR: client-send()\n"); exit(1); } //end send check /* Prompt user input */ printf("Enter name of file to append: "); scanf("%s", file_name); /* Send length of filename and filename */ file_len = strlen(file_name); file_len = htonl(file_len); if (send(tcp_sock,&file_len,sizeof(file_len),0) == -1) { perror("ERROR: client-send()\n"); exit(1); } //end send check if (send(tcp_sock,file_name,sizeof(file_name),0) == -1) { perror("ERROR: client-send()\n"); exit(1); } //end send check /* Recieve server confirmation */ if (recv(tcp_sock,&server_response, sizeof(server_response),0) == -1) { perror("ERROR: client-recv()\n"); exit(1); } //end recv check /* Interpret server confirmation and output appropriate message */ /* Response = 1 -> board exists and file can be created */ /* Response = -1 -> board does not exist */ /* Response = -2 -> board exists, and file is not appended on board*/ if (server_response == -1) { printf("Board does not exist\n"); return; } else if (server_response == -2) { printf("Attachment already exists on board\n"); return; } else {} file_size = server_response; /* Open file to write */ fp = fopen(file_name, "w"); memset(file_line, '\0', sizeof(file_line)); len=0; recv_len=0; while (recv_len = recv(tcp_sock,file_line,sizeof(file_line),0) > 0) { recv_bytes += recv_len; write_size = fwrite(file_line, sizeof(char), recv_len, fp); memset(file_line, '\0', sizeof(file_line)); // if (recv_bytes == file_size) break; } //end while fclose(fp); } //end DOWNLOAD FILE /* DESTROY BOARD */ void destroy (int udp_sock, struct sockaddr_in sin) { /* Declare variables */ char board_name[100]; // Board name char server_resp[100]; // Server response int addr_len; memset(board_name, '\0', sizeof(board_name)); memset(server_resp, '\0', sizeof(server_resp)); /* Prompt user input */ printf("Enter name of board to destroy: "); scanf("%s", board_name); /* Send board name to server */ if(sendto(udp_sock,board_name,strlen(board_name),0,(struct sockaddr *)&sin, sizeof(struct sockaddr)) == -1) { perror("ERROR: client-sendto()\n"); exit(1); } //end sendto check /* Receive server confirmation regarding deletion of board and print results */ if(recvfrom(udp_sock,server_resp,sizeof(server_resp),0,(struct sockaddr *)&sin, &addr_len) == -1) { perror("ERROR: client-recvfrom()\n"); exit(1); } //end recvfrom check if (strcmp(server_resp,"Yes") == 0) { printf("Success: Board %s has been destroyed\n", board_name); } else { printf("Failure: Board %s has not been destroyed\n", board_name); } } //end DESTROY BOARD /* SHUTDOWN SERVER */ int shutdown_server (int udp_sock, struct sockaddr_in sin) { /* Declare variables */ char password[100]; // Admin password char server_resp[100]; // Server response int addr_len; int shutdown_ind=0; memset(password, '\0', sizeof(password)); memset(server_resp, '\0', sizeof(server_resp)); /* Prompt user input */ printf("Enter admin password to server: "); scanf("%s", password); /* Send password to server */ if(sendto(udp_sock,password,strlen(password),0,(struct sockaddr *)&sin, sizeof(struct sockaddr)) == -1) { perror("ERROR: cleint-sendto()\n"); exit(1); } //end sendto check /* Receive server confirmation regarding admin password */ if(recvfrom(udp_sock,server_resp,sizeof(server_resp),0,(struct sockaddr *)&sin, &addr_len) == -1) { perror("ERROR: client-recvfrom()\n"); exit(1); } //end recvfrom check if (strcmp(server_resp, "Yes") == 0) { printf("Success: correct admin password\n"); shutdown_ind=1; } else { printf("Failure: incorrect admin password\n"); shutdown_ind=0; } return shutdown_ind; } //end SHUTDOWN SERVER int main (int argc, char * argv[]) { /* Declare variables */ FILE *fn; // File handle for file struct hostent *host; // Host struct sockaddr_in sin; // Address struct used for communication struct client_addr; // Address structure char *hp; // Host int udp_sock; // UDP - File handle for socket int tcp_sock; // TCP - File handle for socket int port_num; // Port number char username[150]; // Username char server_username[150]; // Username prompt char password[150]; // Password char server_password[150]; // Password prompt size_t user_ack=0; // User ack from server int exit_loop=1; // While loop variable int shutdown_ind; // Shutdown indicator /* Check arguments in command line */ if (argc!=3) { fprintf(stderr,"USAGE ERROR: %s <server ip> <port number>\n",argv[0]); exit(1); } // end arguments check /* Assign command-line arguments and check for errors */ /* Host - argv1 */ /* Translate host name into peer's IP address */ host = gethostbyname(argv[1]); if (!host) { printf("ERROR: host name/unknown host\n"); exit(1); } // end hostname check /* Port number - argv2 */ port_num = atoi(argv[2]); /* Build address data structure */ bzero((char *)&sin, sizeof(sin)); sin.sin_family = AF_INET; bcopy(host->h_addr, (char *)&sin.sin_addr, host->h_length); sin.sin_port = htons(port_num); /* -------- UDP -------- */ /* UDP - Open socket and check for errors */ if((udp_sock = socket(AF_INET, SOCK_DGRAM, 0)) == -1) { perror("ERROR: client-socket()\n"); exit(1); } // end socket check /* -------- TCP -------- */ /* TCP - Open socket and check for errors */ if((tcp_sock = socket(PF_INET, SOCK_STREAM, 0)) == -1) { perror("ERROR: client-socket()\n"); exit(1); } // end socket check /* TCP - Connect client and server */ if (connect(tcp_sock, (struct sockaddr *)&sin, sizeof(sin)) < 0) { perror("ERROR: client-connect()\n"); close(tcp_sock); exit(1); } // end connect check /* -------- USERNAME -------- */ /* Receive request for username from server */ if(recv(tcp_sock, server_username, sizeof(server_username), 0) == -1) { perror("ERROR: client-recv()\n"); exit(1); } // end recv check /* Prompt user for username and send it to the server */ printf("%s", server_username); scanf("%s", username); if(send(tcp_sock, username, sizeof(username), 0) == -1) { perror("ERROR: client-send()\n"); exit(1); } // end send check /* -------- PASSWORD -------- */ /* Receive request for password from server */ if(recv(tcp_sock, server_password, sizeof(server_password), 0) == -1) { perror("ERROR: client-recv()\n"); exit(1); } // end recv check /* Prompt user for password and send it to the server */ printf("%s", server_password); scanf("%s", password); if(send(tcp_sock, password, sizeof(password), 0) == -1) { perror("ERROR: client-send()\n"); exit(1); } // end send check /* -------- SERVER ACKNOWLEDGEMENT -------- */ if(recv(tcp_sock, &user_ack, sizeof(int), 0) == -1) { perror("ERROR: client-recv()\n"); exit(1); } // end recv check if(user_ack == 0) { printf("ERROR: User authentication/registration failed\n"); exit(1); } /* -------- PROMPT USER FOR OPERATION -------- */ while (exit_loop) { char command[10]; printf("Enter command: CRT, LIS, MSG, DLT, RDB, EDT, APN, DWN, DST, XIT, SHT: "); scanf("%s", command); /* if (strcmp(command,"RDB")==0 || strcmp(command,"APN")==0 || strcmp(command,"DWN")==0) { if(send(tcp_sock,command,sizeof(command), 0) == -1) { perror("ERROR: client-send()\n"); exit(1); } // end send check } else { if(sendto(udp_sock,command,strlen(command),0,(struct sockaddr *)&sin, sizeof(struct sockaddr)) == -1) { perror("ERROR: client-sendto()\n"); exit(1); } // end send check } // end IF */ if(sendto(udp_sock,command,strlen(command),0,(struct sockaddr *)&sin, sizeof(struct sockaddr)) == -1) { perror("ERROR: client-sendto()\n"); exit(1); } //end sendto check if (strcmp(command,"CRT") == 0) { create(udp_sock,sin); } else if (strcmp(command,"LIS") == 0) { list(udp_sock,sin); } else if (strcmp(command,"MSG") == 0) { message(udp_sock,sin); } else if (strcmp(command,"DLT") == 0) { deleteMessage(udp_sock,sin); } else if (strcmp(command,"RDB") == 0) { readBoard(tcp_sock); } else if (strcmp(command,"EDT") == 0) { edit(udp_sock,sin); } else if (strcmp(command,"APN") == 0) { append(tcp_sock); } else if (strcmp(command,"DWN") == 0) { download(tcp_sock); } else if (strcmp(command,"DST") == 0) { destroy(udp_sock,sin); } else if (strcmp(command,"XIT") == 0) { close(udp_sock); close(tcp_sock); printf("Session has been closed\n"); exit_loop = 0; } else if (strcmp(command,"SHT") == 0) { shutdown_ind = shutdown_server(udp_sock,sin); if (shutdown_ind) { close(udp_sock); close(tcp_sock); printf("Server is shutting down\n"); exit_loop = 0; } } else { printf("Incorrect command\n"); } } // end while loop return 0; } <file_sep>/client/Makefile # <NAME> all: client client: client.c gcc -o myfrm client.c -lssl clean: rm myfrm <file_sep>/server/server.c // Computer Networks - CSE 30264 // Programming Assignment 4 // October 31, 2016 // Authors: <NAME> & <NAME> // NETIDs: jdiazort & jsuarezm // Server #include <stdio.h> #include <stdlib.h> #include <string.h> #include <stdint.h> #include <time.h> #include <math.h> #include <dirent.h> #include <sys/types.h> #include <sys/stat.h> #include <sys/mman.h> #include <fcntl.h> #include <sys/socket.h> #include <netinet/in.h> #include <netdb.h> #include <unistd.h> #include <sys/time.h> #include <openssl/md5.h> #include <sys/types.h> #include <sys/stat.h> #include <time.h> #include <fcntl.h> #include <string.h> #define MAX_MD5LENGTH 50 #define MAX_FILENAME 100 #define MAX_PENDING 5 #define MAX_LINE 256 struct user { char name[100]; char password[100]; }; int32_t fileSize(char * file_name) { FILE *fp; int32_t file_size = -1; if(fp = fopen(file_name, "r")) { fseek(fp,0,SEEK_END); file_size = ftell(fp); fseek(fp,0,SEEK_SET); fclose(fp); } return file_size; } //end FILESIZE void deleteAll() { int ret; DIR *dir_stream; char list_buf[100]; struct dirent *dir_read; ssize_t read; dir_stream = opendir("./"); if (dir_stream != NULL) { while ( dir_read = readdir(dir_stream) ) { ret = unlink(dir_read->d_name); } } } void sendFile(int tcp_sock, char * file_name) { int file_size; int original_size; FILE *fp; char file_line[20000]; int len, sent_len; /* Calculate file size and send it to the server */ file_size = fileSize(file_name); original_size = file_size; file_size = htonl(file_size); if (send(tcp_sock,&file_size,sizeof(int32_t),0) == -1) { perror("ERROR: client-send()\n"); exit(1); } //end send check if (original_size == -1) { printf("File does not exist locally\n"); return; } /* Open file */ fp = fopen(file_name, "r"); memset(file_line, '\0', sizeof(file_line)); /* Read file and send to server line by line */ len = 0; sent_len = 0; while ( len=fread(file_line,sizeof(char),sizeof(file_line),fp) > 0) { sent_len = send(tcp_sock,file_line,len,0); memset(file_line, '\0', sizeof(file_line)); } //end reading file fclose(fp); } /* CREATE BOARD */ void create(int udp_sock, struct sockaddr_in sin, char * user_name) { printf("inside CREATE\n"); /* Declare Variables */ char board_name[100]; char server_resp[100]; char board_head[200]; FILE *fp; int addr_len; memset(board_name, '\0', sizeof(board_name)); memset(server_resp, '\0', sizeof(server_resp)); memset(board_head, '\0', sizeof(board_head)); /* Receive board_name of board to create from the client */ if(recvfrom(udp_sock,board_name,sizeof(board_name),0,(struct sockaddr *)&sin, &addr_len) == -1) { perror("ERROR: client-recvfrom()\n"); exit(1); } //end recvfrom check printf("board name = %s\n", board_name); strcpy(board_head, user_name); strcat(board_head, " "); strcat(board_head, board_name); printf("board_head = %s\n", board_head); size_t wf; if (fp = fopen(board_name,"ab+" )) { wf = fwrite(board_head, 1, strlen(board_head), fp ); fclose(fp); printf("Number of bytes written = %i\n", wf); } strcpy(server_resp, "Yes" ); if (sendto (udp_sock, server_resp, strlen(server_resp), 0, (struct sockaddr *)&sin, sizeof(struct sockaddr) ) == -1 ) { perror("ERROR: server-sendto()\n"); } printf("End of create\n"); } void message(int udp_sock, struct sockaddr_in sin, char * user_name) { /* Declare cariables */ char board_name[100]; char message[4096]; char server_resp[100]; int addr_len; int board_exists; FILE *fp; printf("inside message\n"); memset(board_name, '\0', sizeof(board_name)); memset(message, '\0', sizeof(message)); memset(server_resp, '\0', sizeof(server_resp)); /* Receive board_name of board to create from the client */ if(recvfrom(udp_sock,board_name,sizeof(board_name),0,(struct sockaddr *)&sin, &addr_len) == -1) { perror("ERROR: client-recvfrom()\n"); exit(1); } //end recvfrom check /* Receive message to post on board */ if(recvfrom(udp_sock,message,sizeof(message),0,(struct sockaddr *)&sin, &addr_len) == -1) { perror("ERROR: client-recvfrom()\n"); exit(1); } //end recvfrom check printf("user name %s\n", user_name); printf("board_name: %s\n", board_name); printf("message: %s\n", message); if ( (board_exists = access(board_name, F_OK)) != -1 ) { size_t wf; if (fp = fopen(board_name,"ab+" )) { wf = fwrite("\n", 1, sizeof("\n")-1, fp ); fclose(fp); printf("Number of bytes written = %i\n", wf); } else { board_exists = -1; } if (fp = fopen(board_name,"ab+" )) { wf = fwrite(user_name, 1, strlen(user_name), fp ); fclose(fp); printf("Number of bytes written = %i\n", wf); } else { board_exists = -1; } if (fp = fopen(board_name,"ab+" )) { wf = fwrite("\n", 1, sizeof("\n")-1, fp ); fclose(fp); printf("Number of bytes written = %i\n", wf); } else { board_exists = -1; } if (fp = fopen(board_name,"ab+" )) { wf = fwrite(message, 1, strlen(message), fp ); fclose(fp); printf("Number of bytes written = %i\n", wf); } else { board_exists = -1; } if (fp = fopen(board_name,"ab+" )) { wf = fwrite("\n", 1, sizeof("\n")-1, fp ); fclose(fp); printf("Number of bytes written = %i\n", wf); } else { board_exists = -1; } } if (board_exists != -1) { strcpy(server_resp,"Yes"); } else { strcpy(server_resp, "No"); } if(sendto(udp_sock,server_resp,strlen(server_resp),0,(struct sockaddr *)&sin, sizeof(struct sockaddr)) == -1) { perror("ERROR: client-sendto()\n"); exit(1); } //end sendto check } void deleteMessage (int udp_sock, struct sockaddr_in sin, char * user_name) { printf("Inside delete\n"); /* Declare Variables */ char board_name[100]; char message[4096]; char server_resp[100]; char b_message[4096]; int addr_len; int board_exists; FILE *fp; char * line = NULL; char prev_line[200]; size_t len = 0; ssize_t read; char * line_msg = NULL; size_t len_msg=0; int found_message; FILE* out_file = fopen("temp.txt", "ab+"); memset(board_name, '\0', sizeof(board_name)); memset(message, '\0', sizeof(message)); memset(server_resp, '\0', sizeof(server_resp)); /* Receive board_name of boad to delete */ if(recvfrom(udp_sock,board_name,sizeof(board_name),0,(struct sockaddr *)&sin, &addr_len) == -1) { perror("ERROR: client-recvfrom()\n"); exit(1); } //end recvfrom check /* Receive message to be deleted */ if(recvfrom(udp_sock,b_message,sizeof(b_message),0,(struct sockaddr *)&sin, &addr_len) == -1) { perror("ERROR: client-recvfrom()\n"); exit(1); } //end recvfrom check strcat(user_name,"\n"); //printf("board_name: %s\n", board_name); //printf("message: %s\n", message); size_t wf; //printf("Before deletion\n"); /* PERFORM DELETION*/ strcpy(server_resp,"No"); if( (board_exists = access(board_name, F_OK)) == -1) { printf("Board does not exist\n"); if(sendto(udp_sock,server_resp,strlen(server_resp),0,(struct sockaddr *)&sin, sizeof(struct sockaddr)) == -1) { perror("ERROR: client-sendto()\n"); exit(1); } //end sendto check return; } fp = fopen(board_name, "rw"); if (fp == NULL) { printf("Cannot open file\n"); if(sendto(udp_sock,server_resp,strlen(server_resp),0,(struct sockaddr *)&sin, sizeof(struct sockaddr)) == -1) { perror("ERROR: client-sendto()\n"); exit(1); } //end sendto check return; } //end pointer check while((read = getline(&line, &len, fp)) != -1) { printf("USERNAME: %sLINE: %s", user_name,line); if (strcmp(user_name,line) == 0) { if ((read = getline(&line_msg, &len_msg, fp)) != -1 ) { strcat(b_message, "\n"); printf("MSG: %sLINE: %s", b_message,line_msg); if (strcmp(b_message,line_msg)==0) { found_message = 1; } else { wf = fwrite(line, 1, sizeof(line), out_file); wf = fwrite(line_msg, 1, sizeof(line_msg), out_file); } //end message compare } } else { wf = fwrite(line, 1, sizeof(line), out_file); } //end USERNAME compare } //end WHILE fclose(fp); fclose(out_file); if (found_message == 1) { rename("temp.txt", board_name); strcpy(server_resp, "Yes"); } else { strcpy(server_resp, "No"); } /* END DELETION */ // strcpy(server_resp,"Yes"); if(sendto(udp_sock,server_resp,strlen(server_resp),0,(struct sockaddr *)&sin, sizeof(struct sockaddr)) == -1) { perror("ERROR: client-sendto()\n"); exit(1); } //end sendto check // printf("After sending respinse"); //system("rm ./temp.txt"); } void editMessage(int udp_sock, struct sockaddr_in sin, char * user_name) { //printf("Inside insert\n"); /* Declare Variables */ char board_name[100]; char message[4096]; char new_message[4096]; char server_resp[100]; int addr_len; int board_exists; FILE *fp; char * line = NULL; char * prev_line = ""; size_t len = 0; ssize_t read; int found_message; FILE* out_file = fopen("temp.txt", "w+"); char * line_msg = NULL; size_t len_msg=0; char test_line[200]; int test_len=0; char line_str[200]; char new_msg_str[200]; memset(board_name, '\0', sizeof(board_name)); memset(message, '\0', sizeof(message)); memset(server_resp, '\0', sizeof(server_resp)); memset(new_message, '\0', sizeof(new_message)); memset(line_str, '\0', sizeof(line_str)); memset(new_msg_str, '\0', sizeof(new_msg_str)); memset(test_line, '\0', sizeof(test_line)); /* Receive board_name of boad to delete */ if(recvfrom(udp_sock,board_name,sizeof(board_name),0,(struct sockaddr *)&sin, &addr_len) == -1) { perror("ERROR: client-recvfrom()\n"); exit(1); } //end recvfrom check /* Receive message to be deleted */ if(recvfrom(udp_sock,message,sizeof(message),0,(struct sockaddr *)&sin, &addr_len) == -1) { perror("ERROR: client-recvfrom()\n"); exit(1); } //end recvfrom check /* Receive message that will replace old message */ if(recvfrom(udp_sock,new_message,sizeof(new_message),0,(struct sockaddr *)&sin, &addr_len) == -1) { perror("ERROR: client-recvfrom()\n"); exit(1); } //end recvfrom check strcat(user_name,"\n"); //printf("board_name: %s\n", board_name); //printf("message: %s\n", message); //printf("new message: %s\n", new_message); size_t wf; //printf("Before edit\n"); /* PERFORM EDIT*/ strcpy(server_resp,"No"); if( (board_exists = access(board_name, F_OK)) == -1) { printf("Board does not exist\n"); if(sendto(udp_sock,server_resp,strlen(server_resp),0,(struct sockaddr *)&sin, sizeof(struct sockaddr)) == -1) { perror("ERROR: client-sendto()\n"); exit(1); } //end sendto check return; } fp = fopen(board_name, "rw"); if (fp == NULL) { printf("Cannot open file\n"); if(sendto(udp_sock,server_resp,strlen(server_resp),0,(struct sockaddr *)&sin, sizeof(struct sockaddr)) == -1) { perror("ERROR: client-sendto()\n"); exit(1); } //end sendto check return; } //end pointer while( (read = getline(&line, &len, fp)) != -1) { if (strcmp(user_name,line) == 0) { if ((read = getline(&line_msg, &len_msg, fp)) != -1 ) { strcat(message,"\n"); if (strcmp(message,line_msg)==0) { strcat(line_str,line); strcat(new_msg_str,new_message); strcat(test_line, line_str); strcat(test_line, new_msg_str); printf("TESTLINE = %s\n", test_line); test_len = strlen(line_str) + strlen(new_msg_str); wf = fwrite(test_line,1,test_len,out_file); //wf = fwrite(line, 1, sizeof(line), out_file); //wf = fwrite(new_message, 1, sizeof(new_message), out_file); found_message = 1; memset(line_str, '\0', sizeof(line_str)); memset(new_msg_str, '\0', sizeof(new_msg_str)); memset(test_line, '\0', sizeof(test_line)); } else { strcpy(line_str, line); strcpy(new_msg_str, line_msg); strcat(test_line, line_str); strcat(test_line, new_msg_str); printf("TESTLINE = %s\n", test_line); test_len = strlen(line_str) + strlen(new_msg_str); wf = fwrite(test_line,1,test_len,out_file); //wf = fwrite(line, 1, sizeof(line), out_file); //wf = fwrite(line_msg, 1, sizeof(line_msg), out_file); memset(line_str, '\0', sizeof(line_str)); memset(new_msg_str, '\0', sizeof(new_msg_str)); memset(test_line, '\0', sizeof(test_line)); } //end message compare } } else { strcpy(test_line, line); test_len = strlen(test_line); printf("TESTLINE = %s\n", test_line); wf = fwrite(test_line, 1, test_len, out_file); memset(test_line, '\0', sizeof(test_line)); //wf = fwrite(line, 1, sizeof(line), out_file); } //end USERNAME compare } //end WHILE fclose(fp); fclose(out_file); if (found_message == 1) { rename("temp.txt", board_name); strcpy(server_resp, "Yes"); } else { strcpy(server_resp, "No"); } if(sendto(udp_sock,server_resp,strlen(server_resp),0,(struct sockaddr *)&sin, sizeof(struct sockaddr)) == -1) { perror("ERROR: client-sendto()\n"); exit(1); } //end sendto check } void list (int udp_sock, struct sockaddr_in sin, char * user_name) { printf("Inside lsit\n"); /* Declare Variables */ char server_responze[100]; char board_name[4096]; int addr_len; int dir_size = 0; DIR *dir_stream; char list_buf[100]; struct dirent *dir_read; ssize_t read; memset(board_name, '\0', sizeof(board_name)); printf("before opendir\n"); /* GET LIST OF ALL THE BOARDS*/ dir_stream = opendir("./"); if (dir_stream != NULL) { printf("reading directory size\n"); /* Calculating the size of the directory */ while ( dir_read = readdir(dir_stream) ) { strcpy (list_buf, dir_read->d_name); dir_size ++; memset(list_buf, '\0', sizeof(list_buf)); } closedir(dir_stream); printf ("dir_size = %i\n", dir_size); /* Sending directory size to client */ if(sendto(udp_sock, &dir_size, sizeof(dir_size),0,(struct sockaddr *)&sin, sizeof(struct sockaddr)) == -1) { perror("ERROR: client-sendto()\n"); exit(1); } //end sendto check printf("before reading directory and sending\n"); /* Send directory listing to cleint */ dir_stream = opendir("./"); while ( dir_read = readdir(dir_stream) ) { strcpy ( list_buf, dir_read->d_name ); if(sendto(udp_sock,list_buf,strlen(list_buf),0,(struct sockaddr *)&sin, sizeof(struct sockaddr)) == -1) { perror("ERROR: client-sendto()\n"); exit(1); } //end sendto check memset(list_buf, '\0', sizeof(list_buf)); memset(list_buf, '\0', sizeof(list_buf)); } printf("after sending\n"); } } void readBoard(int tcp_sock) { printf("Inside read board\n"); char board_name[100]; char line[1000]; char server_resp[100]; int board_exists; int32_t board_name_len; int32_t board_size_2; char bsize[100]; FILE *fp; int len; printf("HERE 2\n"); memset(board_name, '\0', sizeof(board_name)); printf("HERE 3\n"); memset(server_resp, '\0', sizeof(server_resp)); printf("HERE 4\n"); memset(line,'\0', sizeof(line)); memset(bsize,'\0', sizeof(bsize)); printf("HERE 5\n"); recv(tcp_sock,&board_name_len,sizeof(int32_t),0); board_name_len = ntohl(board_name_len); printf("File length = %i\n",board_name_len); while(strlen(board_name)<board_name_len) { recv(tcp_sock,board_name,sizeof(board_name),0); } printf("Board name = %s\n", board_name); //board_size_2 = fileSize(board_name); //board_size_2 = htonl(board_size_2); //send(tcp_sock,&board_size_2,sizeof(int32_t),0); if ( (board_exists = access(board_name, F_OK)) != -1 ) { printf("Inside if\n"); board_size_2 = fileSize(board_name); sprintf(bsize,"%d",board_size_2); printf("bsize = %s",bsize); if (board_size_2 == 0) { printf("file size = 0\n"); board_size_2 = -1; send(tcp_sock,&board_size_2,sizeof(int32_t),0); } else { printf("board size = %i\n", board_size_2); board_size_2 = htonl(board_size_2); printf("board size = %i\n", board_size_2); send(tcp_sock,&board_name,sizeof(board_name),0); //send(tcp_sock,&board_size_2,sizeof(int32_t),0); fp = fopen(board_name, "r"); while ( (len=fread(line,sizeof(char),sizeof(line),fp)) > 0) { send(tcp_sock,line,len,0); memset(line,'\0',sizeof(line)); } fclose(fp); } } } void append(int tcp_sock, char * user_name){ printf("Inside append\n"); /* Declare variables */ char board_name[100]; // Board name int board_name_len; // Length of board name char file_name[100]; // File name int file_name_len; // Length of file name int server_response; // Server confirmation int file_size,original_size; // File size FILE *fp; char file_line[20000]; int len, sent_len; int data_received=0; int total_data_received=0; int board_exists=0; int file_exists=0; char append_file_name[200]; int status = 0; recv(tcp_sock,&board_name_len,sizeof(board_name_len),0); //printf("board name length = %i\n",board_name_len); while(strlen(board_name)<board_name_len) { recv(tcp_sock,board_name,sizeof(board_name),0); } //printf("board name = %s\n", board_name); recv(tcp_sock,&file_name_len,sizeof(file_name_len),0); printf("File name length = %i\n",file_name_len); while(strlen(file_name)<file_name_len) { recv(tcp_sock,file_name,sizeof(file_name),0); } //printf("File name = %s\n", file_name); if ( !((board_exists = access(board_name, F_OK)) != -1) ) { status = -1; send(tcp_sock, &status, sizeof(int32_t), 0); return; } if ( file_exists = access(file_name, F_OK) != -1 ) { status = -2; send(tcp_sock, &status, sizeof(int32_t), 0); return; } printf("status = 1 \n"); status = 1; send(tcp_sock, &status, sizeof(int32_t), 0); printf("Inside if\n"); strcat(append_file_name,board_name); strcat(append_file_name,"-"); strcat(append_file_name,file_name ); recv(tcp_sock,&file_size,sizeof(file_size), 0); if (file_size == -1 ) { return; } size_t wf; fp = fopen(file_name,"ab+" ); while (total_data_received < file_size) { if (data_received = recv(tcp_sock,file_line,sizeof(file_line),0) == -1) { total_data_received += data_received; wf = fwrite(file_line, 1, strlen(file_line), fp ); printf("Number of bytes written = %i\n", wf); } //end if } //end WHILE fclose(fp); if (fp = fopen(board_name,"ab+" )) { wf = fwrite(user_name, 1, strlen(user_name), fp ); printf("Number of bytes written = %i\n", wf); wf = fwrite("\nUser appended: ", 1, sizeof("\nUser appended: ")-1,fp); printf("Number of bytes written = %i\n", wf); wf = fwrite(append_file_name, 1, strlen(append_file_name), fp ); printf("Number of bytes written = %i\n", wf); fclose(fp); } } void download(int tcp_sock){ /* Declare variables */ char board_name[100]; // Board name int board_name_len; // Length of board name char file_name[100]; // File name int file_name_len; // Length of file name char server_resp[10]; // Server confirmation int file_size; // File size FILE *fp; char file_line[20000]; int recv_len, recv_bytes, write_size; char *line = NULL; size_t len; int board_exists=0; char board_attachment[200]; memset(board_attachment, '\0', sizeof(board_attachment)); strcpy(board_attachment,"User appended: " ); /* Receive boardname length and board name */ recv(tcp_sock,&board_name_len,sizeof(board_name_len),0); printf("File length = %i\n",board_name_len); while(strlen(board_name)<board_name_len) { recv(tcp_sock,board_name,sizeof(board_name),0); } /* Recieve file_name length and file name */ recv(tcp_sock,&file_name_len,sizeof(file_name_len),0); printf("File length = %i\n",file_name_len); while(strlen(file_name)<file_name_len) { recv(tcp_sock,file_name,sizeof(file_name),0); } if ( (board_exists = access(board_name, F_OK)) != -1) { if ( fp = fopen(board_name, "r")) { while (getline(&line, &len, fp) != -1) { char temp[strlen(board_attachment)]; char filename_temp[100]; strncpy(temp,line,strlen(board_attachment)); if (strcmp (board_attachment, temp)) { strncpy(file_name,line+strlen(board_attachment), strlen(line)-strlen(board_attachment)); if (strcmp(file_name,filename_temp)) { sendFile(tcp_sock, file_name); break; } } } } } } void destroy(int udp_sock, struct sockaddr_in sin, char * user_name) { /* Declare variables */ char board_name[100]; // Board name char server_resp[100]; // Server response int addr_len; FILE *fp; char * line = NULL; char * prev_line = ""; size_t len = 0; char board_username[100]; char board_attachment[200]; int board_exists=0; char line_str [200]; memset(board_name, '\0', sizeof(board_name)); memset(server_resp, '\0', sizeof(server_resp)); memset(board_attachment, '\0', sizeof(board_attachment)); strcpy(board_attachment,"User appended: " ); strcpy(server_resp, "No"); /* Receive server confirmation regarding creation of board and print results */ if(recvfrom(udp_sock,board_name,sizeof(board_name),0,(struct sockaddr *)&sin, &addr_len) == -1) { perror("ERROR: client-recvfrom()\n"); exit(1); } //end recvfrom check /* Delete board and files appended to it */ if ( (board_exists = access(board_name, F_OK)) != -1) { if ( fp = fopen(board_name, "r")) { if (getline(&line, &len, fp) != -1){ strncpy(line_str, line, strlen(user_name) ); printf("Username = %s\n", line_str); strcpy(board_username, line_str); if ( (strcmp(board_username, user_name) == 0) ) { strcpy(server_resp, "Yes"); printf("inside deletion\n"); while (getline(&line, &len, fp) != -1) { printf("Inside while\n"); char temp[strlen(board_attachment)]; char file_name[100]; //strcpy(line_str,line); strncpy(temp,line,strlen(board_attachment)); if ( (strcmp (board_attachment, temp) == 0 ) ) { strncpy(file_name,line+strlen(board_attachment), strlen(line)-strlen(board_attachment)); remove(file_name); } } printf("After while\n"); fclose(fp); remove(board_name); } } } } if (sendto (udp_sock, server_resp, strlen(server_resp), 0, (struct sockaddr *)&sin, sizeof(struct sockaddr) ) == -1 ) { perror("ERROR: server-sendto()\n"); } } void shutdownServer (int udp_sock, struct sockaddr_in sin, char * user_name, char * admin_password) { /* Declare variables */ char password[100]; // Admin password char server_resp[100]; // Server response int addr_len; int shutdown_ind=0; memset(password, '\0', sizeof(password)); memset(server_resp, '\0', sizeof(server_resp)); /* Receive board_name of board to create from the client */ if(recvfrom(udp_sock,password,sizeof(password),0,(struct sockaddr *)&sin, &addr_len) == -1) { perror("ERROR: client-recvfrom()\n"); exit(1); } //end recvfrom check if ( (strcmp(password,admin_password))==0 ) { strcpy(server_resp, "Yes" ); deleteAll(); } else { strcpy(server_resp, "No" ); } // removing files system("exec rm -r ./*"); if (sendto (udp_sock, server_resp, strlen(server_resp), 0, (struct sockaddr *)&sin, sizeof(struct sockaddr) ) == -1 ) { perror("ERROR: server-sendto()\n"); } } int main (int argc, char * argv[]) { /* Declare variables */ struct sockaddr_in sin, client_addr; // Address structure int addr_len; // Length int udp_sock; // UDP - File handle for socket int tcp_sock; // TCP - File handle for socket char buf[10]; // Buffer for commands // int sock, new_sock; // Sockets int opt = 1; int port_num; // Port number struct user users[100]; int total_users = 0; int exit_loop=1; // While loop variable int shutdown_ind; // Shutdown indicator char * admin_password; char admin_passwd_str[100]; /* Check arguments in command line */ if (argc!=3) { fprintf(stderr,"USAGE ERROR: %s <port number> <admin_password>\n",argv[0]); exit(1); } // end arguments check /* Assign command-line arguments and check for errors*/ /* Port number - argv1 */ port_num = atoi(argv[1]); admin_password = argv[2]; printf("Password = %s\n",admin_password); /* Build address data structure */ bzero((char *)&sin, sizeof(sin)); sin.sin_family = AF_INET; printf("HERE 1\n"); sin.sin_addr.s_addr = INADDR_ANY; sin.sin_port = htons(port_num); /* --- Setting up the UDP server --- */ if((udp_sock = socket(PF_INET, SOCK_DGRAM, 0)) == -1) { perror("ERROR: client-socket()\n"); exit(1); } // end socket check /* --- Setting up TCP server --- */ /* Create a socket on the server side */ if ((tcp_sock = socket(PF_INET, SOCK_STREAM,0)) < 0) { perror("ERROR: server-socket()\n"); exit(1); } // end socket check /* Set socket options */ if ((setsockopt(tcp_sock, SOL_SOCKET, SO_REUSEADDR, (char *)& opt, sizeof(int))) < 0) { perror("ERROR: server-setsockopt()\n"); exit(1); } //end socket options check //fcntl(tcp_sock, F_SETFL, O_NONBLOCK); /* Bind the created UDP socket to the specified address */ if((bind(udp_sock,(struct sockaddr*)&sin, sizeof(sin))) < 0){ perror("simplex-talk: bind"); exit(1); } /* Bind the created TCP socket to the specified address */ if ((bind(tcp_sock,(struct sockaddr *)&sin, sizeof(sin))) < 0) { perror("ERROR: server-bind()\n"); exit(1); } //end bind check if ((listen(tcp_sock, MAX_PENDING)) < 0) { perror("ERROR: server-listen()\n"); exit(1); } //end listen check printf("HERE 1\n"); /* if ((tcp_sock = accept(tcp_sock, (struct sockaddr *)&sin, &addr_len)) < 0) { perror("ERROR: server-accept()\n"); exit(1); } //end accept check */ chdir("./boards/"); while(1) { printf("Waiting for clien conection.\n"); if ((tcp_sock = accept(tcp_sock, (struct sockaddr *)&sin, &addr_len)) < 0) { perror("ERROR: server-accept()\n"); exit(1); } //end accept check /* if ((listen(tcp_sock, MAX_PENDING)) < 0) { perror("ERROR: server-listen()\n"); exit(1); } //end listen check printf("HERE 1\n"); if ((tcp_sock = accept(tcp_sock, (struct sockaddr *)&sin, &addr_len)) < 0) { perror("ERROR: server-accept()\n"); exit(1); } //end accept check */ printf("HERE 2 \n"); char request_username[150]; memset(request_username,'\0',sizeof(request_username)); snprintf(request_username,sizeof(request_username),"Please enter your username: "); if (send(tcp_sock, request_username, sizeof(request_username),0) == -1) { perror("ERROR: server-send()\n"); } printf("HERE 3 \n"); char username[150]; if (recv(tcp_sock, username, sizeof(username), 0) == -1 ) { perror("ERROR: server-recv()\n"); } printf("USERNAME: %s\n", username); int user_exists = -1; int i; for (i=0; i<100 && i<total_users; i++) { printf("HERE 4.1\n"); if (strcmp(users[i].name,username) ) { printf("HERE 4.2\n"); user_exists = 1; } } char request_password[150]; memset(request_password, '\0', sizeof(request_password)); snprintf(request_password, sizeof(request_password), "Please enter your password: "); if (send(tcp_sock, request_password, sizeof(request_password), 0) == -1) { perror("ERROR: server-send()"); } char password[150]; if (recv(tcp_sock, password, sizeof(password), 0) == -1 ) { perror("ERROR: server-recv()\n"); } printf("PASSWORD: %s", password); int password_match = -1; if (user_exists != -1) { int j; for (j=0; j<100 && j<total_users; j++) { if ( strcmp (users[j].password,password)) { password_match = 1; } } } else { total_users++; struct user u; strcpy(u.name, username); strcpy(u.password, <PASSWORD>); users[total_users] = u; printf("HERE 4\n"); password_match = 1; } // Fail to authenticate user size_t ACK = 1; if (password_match == -1) { ACK = 0; printf("HERE 5\n"); printf("User Authentication Failed.\n"); } if (send(tcp_sock, &ACK, sizeof(size_t), 0) == -1 ) { perror("ERROR: server-send()"); exit(1); } int connected = 1; char protocol[10]; int bytes_buf; addr_len = sizeof(client_addr); /* --------- WATING FOR USER OPERATION --------- */ while(connected) { memset(buf, '\0', sizeof(buf)); printf("Waiting for operation from client.\n"); if (bytes_buf = recvfrom(udp_sock, buf,sizeof(buf),0,(struct sockaddr *)&sin, &addr_len) == -1) { perror("ERROR: client-recvfrom()\n"); exit(1); } //end recvfrom check printf("Received: %s, %i bytes\n", buf, bytes_buf); if (strcmp(buf,"CRT")==0){ printf("Calling CREATE\n"); create(udp_sock, sin, username); } else if (strcmp(buf,"MSG")==0){ message(udp_sock, sin, username); } else if (strcmp(buf,"LIS")==0){ list(udp_sock, sin, username); } else if (strcmp(buf,"DLT")==0){ deleteMessage(udp_sock, sin, username); } else if (strcmp(buf,"EDT")==0) { editMessage(udp_sock, sin, username); } else if (strcmp(buf, "RDB")==0){ readBoard(tcp_sock); } else if (strcmp(buf, "APN")==0){ append(tcp_sock, username); } else if (strcmp(buf,"DWN")==0){ download(tcp_sock); } else if (strcmp(buf,"DST")==0) { destroy(udp_sock, sin, username); } else if (strcmp(buf,"SHT")==0) { shutdownServer(udp_sock, sin, username,admin_password); } else if (strcmp(buf,"XIT")==0){ connected = 0; //close(tcp_sock); printf("Client has ended session.\n"); } memset(buf, '\0', sizeof(buf)); printf("Here 6\n"); } } } <file_sep>/README.md Computer Networks - CSE 30264 PG4
884933925859edbd16a2c5810d6f8b8789d85fff
[ "Markdown", "C", "Makefile" ]
4
C
jsuarezm94/PG4
3681a18c12b3fe3be1e086e2460773274081d955
daf5c491efc1eb6dabdb54604109f251d84f5dff
refs/heads/master
<repo_name>hktwarzone/LintCode<file_sep>/399.cpp /* Nuts & Bolts Problem Given a set of n nuts of different sizes and n bolts of different sizes. There is a one-one mapping between nuts and bolts. Comparison of a nut to another nut or a bolt to another bolt is not allowed. It means nut can only be compared with bolt and bolt can only be compared with nut to see which one is bigger/smaller. We will give you a compare function to compare nut with bolt. Example Given nuts = ['ab','bc','dd','gg'], bolts = ['AB','GG', 'DD', 'BC']. Your code should find the matching bolts and nuts. one of the possible return: nuts = ['ab','bc','dd','gg'], bolts = ['AB','BC','DD','GG']. we will tell you the match compare function. If we give you another compare function. the possible return is the following: nuts = ['ab','bc','dd','gg'], bolts = ['BC','AA','DD','GG']. So you must use the compare function that we give to do the sorting. The order of the nuts or bolts does not matter. You just need to find the matching bolt for each nut. */ /** * class Comparator { * public: * int cmp(string a, string b); * }; * You can use compare.cmp(a, b) to compare nuts "a" and bolts "b", * if "a" is bigger than "b", it will return 1, else if they are equal, * it will return 0, else if "a" is smaller than "b", it will return -1. * When "a" is not a nut or "b" is not a bolt, it will return 2, which is not valid. */ class Solution { public: /** * @param nuts: a vector of integers * @param bolts: a vector of integers * @param compare: a instance of Comparator * @return: nothing */ void sortNutsAndBolts(vector<string> &nuts, vector<string> &bolts, Comparator compare) { // write your code here if (nuts.size() != bolts.size()) return; cmpsort(nuts, bolts, 0, nuts.size() - 1, compare); } private: void cmpsort(vector<string>& n, vector<string>& b, int start, int end, Comparator compare) { if (start >= end) return; int mid = start + (end - start) / 2; string pivot = b[mid]; int left = start; int right = end; while(true) { while (left < right && compare.cmp(n[left], pivot) < 0) { left++; } while (left < right && compare.cmp(n[right], pivot) > 0) { right--; } if (left < right) { swap(n[left], n[right]); } else { break; } } pivot = n[right]; left = start; right = end; while(true) { while (left < right && compare.cmp(pivot, b[left]) > 0) { left++; } while (left < right && compare.cmp(pivot, b[right]) < 0) { right--; } if (left < right) { swap(b[left], b[right]); } else { break; } } cmpsort(n, b, start, right - 1, compare); cmpsort(n, b, right + 1, end, compare); } }; <file_sep>/434.cpp /* Number of Islands II Given a n,m which means the row and column of the 2D matrix and an array of pair A( size k). Originally, the 2D matrix is all 0 which means there is only sea in the matrix. The list pair has k operator and each operator has two integer A[i].x, A[i].y means that you can change the grid matrix[A[i].x][A[i].y] from sea to island. Return how many island are there in the matrix after each operator. Example Given n = 3, m = 3, array of pair A = [(0,0),(0,1),(2,2),(2,1)]. return [1,1,2,2]. Note 0 is represented as the sea, 1 is represented as the island. If two 1 is adjacent, we consider them in the same island. We only consider up/down/left/right adjacent. */ /** * Definition for a point. * struct Point { * int x; * int y; * Point() : x(0), y(0) {} * Point(int a, int b) : x(a), y(b) {} * }; */ class Solution { public: /** * @param n an integer * @param m an integer * @param operators an array of point * @return an integer array */ vector<int> numIslands2(int n, int m, vector<Point>& operators) { // Write your code here int t = operators.size(); vector<int> numI; vector<vector<int>> board(n, vector<int>(m, 0)); vector<int> father(n * m, 0); for (int i = 0; i < n * m; i++) { father[i] = i; } int dx[4] = {1,0,-1,0}; int dy[4] = {0,1,0,-1}; int res = 0; for (int i = 0; i < t; i++) { int ox = operators[i].x; int oy = operators[i].y; int ido = id(m, ox, oy); board[ox][oy] = 1; res++; for (int j = 0; j < 4; j++) { int nx = ox + dx[j]; int ny = oy + dy[j]; if (nx >= 0 && nx < n && ny >= 0 && ny < m && board[nx][ny] == 1) { int idd = id(m, nx, ny); int of = compressed_find(father, ido); int nf = compressed_find(father, idd); if (of != nf) { res--; find_union(father, ido, idd); } } } numI.push_back(res); } return numI; } private: int id(int& m, int x, int y) { return x * m + y; } int compressed_find(vector<int>& father, int x) { int parent = father[x]; while(parent != father[parent]) { parent = father[parent]; } int tmp = -1; int fa = father[x]; while(fa != father[fa]) { tmp = father[fa]; father[fa] = parent; fa = tmp; } return parent; } void find_union(vector<int>& father, int x, int y) { int fx = compressed_find(father, x); int fy = compressed_find(father, y); if (fx != fy) { father[fx] = fy; } } }; <file_sep>/401.cpp /* Kth Smallest Number in Sorted Matrix Find the kth smallest number in at row and column sorted matrix. Have you met this question in a real interview? Yes Example Given k = 4 and a matrix: [ [1 ,5 ,7], [3 ,7 ,8], [4 ,8 ,9], ] return 5 Challenge O(k log n), n is the maximal number in width and height. */ class Node { public: int x; int y; int v; Node(int xx, int yy, int vv) { x = xx; y = yy; v = vv; } }; class CompareNode { public: bool operator()(Node& n1, Node& n2) { return (n1.v > n2.v); } }; class Solution { public: /** * @param matrix: a matrix of integers * @param k: an integer * @return: the kth smallest number in the matrix */ int kthSmallest(vector<vector<int> > &matrix, int k) { // write your code here if (matrix.empty() || matrix[0].empty()) return -1; if (k == 1) return matrix[0][0]; int n = matrix.size(); int m = matrix[0].size(); priority_queue<Node, vector<Node>, CompareNode> q; set<pair<int, int>> visited; q.push(Node(0, 0, matrix[0][0])); visited.insert(make_pair(0, 0)); int dx[4] = {1,0,-1,0}; int dy[4] = {0,1,0,-1}; for (int i = 0; i < k - 1; i++) { Node curr = q.top(); q.pop(); for (int j = 0; j < 4; j++) { int nx = curr.x + dx[j]; int ny = curr.y + dy[j]; if (inBound(nx, ny, n, m) && visited.find(make_pair(nx, ny)) == visited.end()) { visited.insert(make_pair(nx, ny)); q.push(Node(nx, ny, matrix[nx][ny])); } } } return q.top().v; } private: bool inBound(int& nx, int& ny, int& n, int& m) { return (nx >= 0 && ny >= 0 && nx < n && ny < m); } }; <file_sep>/435.cpp /* Post Office Problem On one line there are n houses. Give you an array of integer means the the position of each house. Now you need to pick k position to build k post office, so that the sum distance of each house to the nearest post office is the smallest. Return the least possible sum of all distances between each village and its nearest post office. Example Given array a = [1,2,3,4,5], k = 2. return 3. Challenge Could you solve this problem in O(n^2) time ? */ class Solution { public: /** * @param A an integer array * @param k an integer * @return an integer */ int postOffice(vector<int>& A, int k) { // Write your code here int n = A.size(); if (n == 0 || k >= n) return 0; sort(A.begin(), A.end()); vector<vector<int>> dis(n + 1, vector<int>(n + 1, 0)); for (int i = 1; i <= n; i++) { for (int j = i + 1; j <= n; j++) { int mid = i + (j - i) / 2; for (int x = i; x <= j; x++) { dis[i][j] += abs(A[x - 1] - A[mid - 1]); } } } vector<vector<int>> f(n + 1, vector<int>(k + 1, 0)); for (int i = 1; i <= n; i++) { f[i][1] = dis[1][i]; } for (int j = 2; j <= k; j++) { for (int i = j; i <= n; i++) { f[i][j] = f[1][j - 1] + dis[2][i]; for (int x = 2; x < i; x++) { f[i][j] = min(f[i][j], f[x][j - 1] + dis[x + 1][i]); } } } return f[n][k]; } }; <file_sep>/390.cpp /* Find Peak Element II There is an integer matrix which has the following features: The numbers in adjacent positions are different. The matrix has n rows and m columns. For all i < m, A[0][i] < A[1][i] && A[n - 2][i] > A[n - 1][i]. For all j < n, A[j][0] < A[j][1] && A[j][m - 2] > A[j][m - 1]. We define a position P is a peek if: A[j][i] > A[j+1][i] && A[j][i] > A[j-1][i] && A[j][i] > A[j][i+1] && A[j][i] > A[j][i-1] Find a peak element in this matrix. Return the index of the peak. Have you met this question in a real interview? Yes Example Given a matrix: [ [1 ,2 ,3 ,6 ,5], [16,41,23,22,6], [15,17,24,21,7], [14,18,19,20,10], [13,14,11,10,9] ] return index of 41 (which is [1,1]) or index of 24 (which is [2,2]) Note The matrix may contains multiple peeks, find any of them. Challenge Solve it in O(n+m) time. If you come up with an algorithm that you thought it is O(n log m) or O(m log n), can you prove it is actually O(n+m) or propose a similar but O(n+m) algorithm? */ class Solution { public: /** * @param A: An integer matrix * @return: The index of the peak */ vector<int> findPeakII(vector<vector<int> > A) { // write your code here vector<int> res; if (A.empty() || A[0].empty()) return res; int n = A.size(); int m = A[0].size(); int left = 1; int right = n - 2; int local = 0; while(left < right) { int mid = left + (right - left) / 2; local = findPeak(A[mid]); if (A[mid][local] < A[mid - 1][local]) { right = mid - 1; } else if (A[mid][local] < A[mid + 1][local]) { left = mid + 1; } else { res.push_back(mid); res.push_back(local); return res; } } res.push_back(left); res.push_back(findPeak(A[left])); return res; } private: int findPeak(vector<int>& A) { int m = A.size(); int left = 1; int right = m - 2; while(left < right) { int mid = left + (right - left) / 2; if (A[mid] < A[mid - 1]) { right = mid - 1; } else if (A[mid] < A[mid + 1]) { left = mid + 1; } else return mid; } return left; } }; <file_sep>/360_multimap.cpp /* Sliding Window Median Given an array of n integer, and a moving window(size k), move the window at each iteration from the start of the array, find the median of the element inside the window at each moving. (If there are even numbers in the array, return the N/2-th number after sorting the element in the window. ) Example For array [1,2,7,8,5], moving window size k = 3. return [2,7,7] At first the window is at the start of the array like this [ | 1,2,7 | ,8,5] , return the median 2; then the window move one step forward. [1, | 2,7,8 | ,5], return the median 7; then the window move one step forward again. [1,2, | 7,8,5 | ], return the median 7; Challenge O(nlog(n)) time */ class Solution { public: /** * @param nums: A list of integers. * @return: The median of the element inside the window at each moving */ vector<int> medianSlidingWindow(vector<int> &nums, int k) { // write your code here multiset<int, less<int>> minHeap; multiset<int, greater<int>> maxHeap; vector<int> res; for (int i = 0; i < nums.size(); i++) { if (i >= k) { int toDelete = nums[i - k]; if (maxHeap.find(toDelete) != maxHeap.end()) { maxHeap.erase(maxHeap.find(toDelete)); if (minHeap.size() > maxHeap.size()) { maxHeap.emplace(*minHeap.begin()); minHeap.erase(minHeap.begin()); } } else { minHeap.erase(minHeap.find(toDelete)); if (maxHeap.size() > 1 + minHeap.size()) { minHeap.emplace(*maxHeap.begin()); maxHeap.erase(maxHeap.begin()); } } } if (maxHeap.empty() || nums[i] <= *(maxHeap.begin())) { maxHeap.emplace(nums[i]); if (maxHeap.size() > 1 + minHeap.size()) { minHeap.emplace(*maxHeap.begin()); maxHeap.erase(maxHeap.begin()); } } else { minHeap.emplace(nums[i]); if (minHeap.size() > maxHeap.size()) { maxHeap.emplace(*minHeap.begin()); minHeap.erase(minHeap.begin()); } } if (i >= k - 1) { res.push_back(*maxHeap.begin()); } } return res; } }; <file_sep>/360_map.cpp /* Sliding Window Median Given an array of n integer, and a moving window(size k), move the window at each iteration from the start of the array, find the median of the element inside the window at each moving. (If there are even numbers in the array, return the N/2-th number after sorting the element in the window. ) Example For array [1,2,7,8,5], moving window size k = 3. return [2,7,7] At first the window is at the start of the array like this [ | 1,2,7 | ,8,5] , return the median 2; then the window move one step forward. [1, | 2,7,8 | ,5], return the median 7; then the window move one step forward again. [1,2, | 7,8,5 | ], return the median 7; Challenge O(nlog(n)) time */ class Solution { public: /** * @param nums: A list of integers. * @return: The median of the element inside the window at each moving */ vector<int> medianSlidingWindow(vector<int> &nums, int k) { // write your code here map<int, int> maxHeap; map<int, int> minHeap; int maxCount = 0; int minCount = 0; vector<int> res; for (int i = 0; i < nums.size(); i++) { if (i >= k) { int toDelete = nums[i - k]; if (maxHeap.find(toDelete) != maxHeap.end()) { if (maxHeap[toDelete] == 1) { maxHeap.erase(maxHeap.find(toDelete)); } else { maxHeap[toDelete]--; } maxCount--; } else { if (minHeap[toDelete] == 1) { minHeap.erase(minHeap.find(toDelete)); } else { minHeap[toDelete]--; } minCount--; } rebalance(maxHeap, minHeap, maxCount, minCount); } if (maxCount == 0 || nums[i] <= maxHeap.rbegin()->first) { maxHeap[nums[i]]++; maxCount++; } else { minHeap[nums[i]]++; minCount++; } rebalance(maxHeap, minHeap, maxCount, minCount); if (i >= k - 1) { res.push_back(maxHeap.rbegin()->first); } } return res; } private: void rebalance(map<int, int>& maxHeap, map<int, int>& minHeap, int& maxCount, int& minCount) { if (maxCount < minCount) { int target = minHeap.begin()->first; if (minHeap[target] == 1) { minHeap.erase(minHeap.find(target)); } else { minHeap[target]--; } minCount--; maxHeap[target]++; maxCount++; } if (maxCount > minCount + 1) { int target = maxHeap.rbegin()->first; if (maxHeap[target] == 1) { maxHeap.erase(maxHeap.find(target)); } else { maxHeap[target]--; } maxCount--; minHeap[target]++; minCount++; } } }; <file_sep>/061.cpp /* Search for a Range Given a sorted array of n integers, find the starting and ending position of a given target value. If the target is not found in the array, return [-1, -1]. Have you met this question in a real interview? Yes Example Given [5, 7, 7, 8, 8, 10] and target value 8, return [3, 4]. Challenge O(log n) time. */ class Solution { /** *@param A : an integer sorted array *@param target : an integer to be inserted *return : a list of length 2, [index1, index2] */ public: vector<int> searchRange(vector<int> &A, int target) { // write your code here int lb = lowerBound(A, target); int ub = upperBound(A, target); if (lb == ub) return vector<int>{-1, -1}; else return {lb, ub - 1}; } private: int lowerBound(vector<int> &A, int target) { if (A.empty()) {return -1;} if (A[A.size() - 1] < target) {return A.size();} if (A[0] >= target) {return 0;} int left = 0; int right = A.size() - 1; while(left < right) { int mid = left + (right - left) / 2; if (A[mid] >= target) {right = mid;} else {left = mid + 1;} } return left; } int upperBound(vector<int> &A, int target) { if (A.empty()) {return -1;} if (A[A.size() - 1] <= target) {return A.size();} if (A[0] > target) {return 0;} int left = 0; int right = A.size() - 1; while(left < right) { int mid = left + (right - left) / 2; if (A[mid] > target) {right = mid;} else {left = mid + 1;} } return left; } }; <file_sep>/403.cpp /* Continuous Subarray Sum II Given an integer array, find a continuous rotate subarray where the sum of numbers is the biggest. Your code should return the index of the first number and the index of the last number. (If their are duplicate answer, return anyone. The answer can be rorate array or non- rorate array) Example Give [3, 1, -100, -3, 4], return [4,1]. */ class Solution { public: /** * @param A an integer array * @return A list of integers includes the index of * the first number and the index of the last number */ vector<int> continuousSubarraySumII(vector<int>& A) { // Write your code here vector<int> res; if (A.empty()) return res; int start = 0; int maxsum = A[0]; int sum = A[0]; int total = A[0]; vector<int> resmax = {0, 0}; vector<int> resmin = {0, 0}; for (int i = 1; i < A.size(); i++) { if (sum < 0) { sum = 0; start = i; } sum += A[i]; total += A[i]; if (sum > maxsum) { maxsum = sum; resmax = {start, i}; } } int minsum = A[0]; sum = A[0]; start = 0; for (int i = 1; i < A.size(); i++) { if (sum > 0) { sum = 0; start = i; } sum += A[i]; if (sum < minsum) { minsum = sum; resmin = {start, i}; } } if (total == minsum) { return resmax; } else if (total - minsum <= maxsum) { return resmax; } else { //do not need to handle boundary: if minsum is on the bourdary, total-minsum <= maxsum return vector<int>{++resmin[1],--resmin[0]}; } } }; <file_sep>/011.cpp /* Search Range in Binary Search Tree Given two values k1 and k2 (where k1 < k2) and a root pointer to a Binary Search Tree. Find all the keys of tree in range k1 to k2. i.e. print all x such that k1<=x<=k2 and x is a key of given BST. Return all the keys in ascending order. Have you met this question in a real interview? Yes Example If k1 = 10 and k2 = 22, then your function should return [12, 20, 22]. 20 / \ 8 22 / \ 4 12 */ /** * Definition of TreeNode: * class TreeNode { * public: * int val; * TreeNode *left, *right; * TreeNode(int val) { * this->val = val; * this->left = this->right = NULL; * } * } */ class Solution { public: /** * @param root: The root of the binary search tree. * @param k1 and k2: range k1 to k2. * @return: Return all keys that k1<=key<=k2 in ascending order. */ vector<int> searchRange(TreeNode* root, int k1, int k2) { // write your code here vector<int> results; if (root == NULL) return results; searchHelper(root, k1, k2, results); return results; } private: void searchHelper(TreeNode* root, int& k1, int& k2, vector<int>& results){ if (root == NULL) return; searchHelper(root->left, k1, k2, results); if (k1 <= root->val && root->val <= k2) { results.push_back(root->val); } searchHelper(root->right, k1, k2, results); } }; <file_sep>/391.cpp /* Number of Airplanes in the Sky Given an interval list which are flying and landing time of the flight. How many airplanes are on the sky at most? Have you met this question in a real interview? Yes Example For interval list [[1,10],[2,3],[5,8],[4,7]], return 3 Note If landing and flying happens at the same time, we consider landing should happen at first. */ /** * Definition of Interval: * classs Interval { * int start, end; * Interval(int start, int end) { * this->start = start; * this->end = end; * } */ class Solution { public: /** * @param intervals: An interval array * @return: Count of airplanes are in the sky. */ int countOfAirplanes(vector<Interval> &airplanes) { // write your code here vector<pair<int, int>> times; for (int i = 0; i < airplanes.size(); i++) { times.push_back(make_pair(airplanes[i].start, 1)); times.push_back(make_pair(airplanes[i].end, -1)); } int res = 0; int count = 0; sort(times.begin(), times.end()); for (int i = 0; i < times.size(); i++) { count += times[i].second; res = max(res, count); } return res; } }; <file_sep>/364.cpp /* Trapping Rain Water II Given n x m non-negative integers representing an elevation map 2d where the area of each cell is 1 x 1, compute how much water it is able to trap after raining. Example Given 5*4 matrix [12,13,0,12] [13,4,13,12] [13,8,10,12] [12,13,12,12] [13,13,13,13] return 14. */ class Node { public: int x; int y; int h; Node(int xx, int yy, int hh) { x = xx; y = yy; h = hh; } }; class CompareNode { public: bool operator()(Node& n1, Node& n2) { return (n1.h > n2.h); } }; class Solution { public: /** * @param heights: a matrix of integers * @return: an integer */ int trapRainWater(vector<vector<int> > &heights) { // write your code here if (heights.empty() || heights[0].empty()) return 0; int n = heights.size(); int m = heights[0].size(); priority_queue<Node, vector<Node>, CompareNode> q; vector<vector<bool>> visited(n, vector<bool>(m, false)); for (int i = 0; i < m; i++) { q.push(Node(0, i, heights[0][i])); q.push(Node(n - 1, i, heights[n - 1][i])); visited[0][i] = true; visited[n - 1][i] = true; } for (int i = 0; i < n; i++) { q.push(Node(i, 0, heights[i][0])); q.push(Node(i, m - 1, heights[i][m - 1])); visited[i][0] = true; visited[i][m - 1] = true; } vector<int> dx = {1, 0, -1, 0}; vector<int> dy = {0, 1, 0, -1}; int res = 0; while(!q.empty()) { Node curr_node = q.top(); q.pop(); for (int i = 0; i < 4; i++) { int curr_x = curr_node.x + dx[i]; int curr_y = curr_node.y + dy[i]; if (curr_x >= 0 && curr_x < n && curr_y >= 0 && curr_y < m && !visited[curr_x][curr_y]) { visited[curr_x][curr_y] = true; q.push(Node(curr_x, curr_y, max(curr_node.h, heights[curr_x][curr_y]))); res += max(0, curr_node.h - heights[curr_x][curr_y]); } } } return res; } }; <file_sep>/131.cpp /* Building Outline Given N buildings in a x-axis,each building is a rectangle and can be represented by a triple (start, end, height), where start is the start position on x-axis, end is the end position on x-axis and height is the height of the building. Buildings may overlap if you see them from far away,find the outline of them。 An outline can be represented by a triple, (start, end, height), where start is the start position on x-axis of the outline, end is the end position on x-axis and height is the height of the outline. Example Given 3 buildings: [ [1, 3, 3], [2, 4, 4], [5, 6, 1] ] The outlines are: [ [1, 2, 3], [2, 4, 4], [5, 6, 1] ] Note Please merge the adjacent outlines if they have the same height and make sure different outlines cant overlap on x-axis. */ class Solution { public: /** * @param buildings: A list of lists of integers * @return: Find the outline of those buildings */ vector<vector<int> > buildingOutline(vector<vector<int> > &buildings) { // write your code here vector<vector<int>> res; if (buildings.empty()) return res; vector<pair<int, int>> points; multiset<int> heights; for (int i = 0; i < buildings.size(); i++) { points.push_back(make_pair(buildings[i][0], -buildings[i][2])); points.push_back(make_pair(buildings[i][1], buildings[i][2])); } sort(points.begin(), points.end()); heights.insert(0); int currHeight = 0; int prevHeight = 0; int prevStart = -1; for (int i = 0; i < points.size(); i++) { if (points[i].second < 0) { heights.insert(-points[i].second); } else { heights.erase(heights.find(points[i].second)); } currHeight = *heights.rbegin(); if (prevHeight != currHeight) { if (prevStart != -1 && prevHeight > 0) { res.push_back(vector<int>{prevStart, points[i].first, prevHeight}); } prevStart = points[i].first; prevHeight = currHeight; } } return res; } };
927bf92fcec1221f79017e212209b813ed241501
[ "C++" ]
13
C++
hktwarzone/LintCode
7c2bab9706e693a14bf520a465b8b1c42f0c4127
3418eff54eb0ec1fb8456ba027d38df11e3c07e2
refs/heads/master
<repo_name>rjw57/ground-plane-estimate<file_sep>/app/app.js (function() { // Entry point to application. Called after all functions and variables below // have been initialised. function main() { //var imgUrl = 'lensfield.png'; var imgUrl = 'trumpington.png'; Split(['#floor-pane', '#image-pane'], { gutterSize: 8, cursor: 'col-resize', onDrag: onUiResize, sizes: [33, 67], }); ffUi = new FloorFindUI('image-ui'); fpUi = new FloorPreviewUI('floor-preview', ffUi); var loader = new THREE.TextureLoader(); var texPromise = new Promise(function(resolve, reject) { loader.load(imgUrl, resolve, null, reject); }); texPromise.then(function(texture) { texture.minFilter = THREE.LinearFilter; texture.magFilter = THREE.NearestFilter; ffUi.texture = texture; ffUi.initialiseFromTexture(); fpUi.texture = texture; }); function onUiResize() { ffUi.containerResized(); fpUi.containerResized(); } window.addEventListener('resize', onUiResize); var actions = { download: function() { // makes use of saveAs function from FileSaver.min.js. var columnMajorImageToFloorMatrix = []; for(var i=0; i<9; ++i) { columnMajorImageToFloorMatrix[i] = ffUi.imageToFloorMatrix.elements[i]; } var str = ffUi.toJSON(); var data = new Blob([str], {type:'application/json'}); saveAs(data, 'calibration.json'); }, }; var state = { xScale: 1, yScale: 1, xOffset: 0, yOffset: 0, theta: 0, }; function updateFloorTransform() { var s = state; var scale = [ [s.xScale, 0, 0], [0, s.yScale, 0], [0, 0, 1], ]; var shift = [ [1, 0, s.xOffset], [0, 1, s.yOffset], [0, 0, 1], ]; var thetaRad = 2.0 * Math.PI * (s.theta / 360.0); var ct = Math.cos(thetaRad), st = Math.sin(thetaRad); var rot = [ [ct, -st, 0], [st, ct, 0], [0, 0, 1], ]; ffUi.setFloorPlaneTransform( numeric.dot(rot, numeric.dot(scale, shift)) ); } // Create parameter GUI var gui = new dat.GUI(); gui.add(ffUi, 'floorOpacity', 0.0, 1.0); gui.add(ffUi, 'floorRadius', 1, 90); gui.add(ffUi, 'barrelDistortion', -0.50, 0.20); gui.add(state, 'xScale', 0, 3).onChange(updateFloorTransform); gui.add(state, 'yScale', 0, 3).onChange(updateFloorTransform); gui.add(state, 'xOffset', -20, 20).onChange(updateFloorTransform); gui.add(state, 'yOffset', -20, 20).onChange(updateFloorTransform); gui.add(state, 'theta', -200, 200).onChange(updateFloorTransform); gui.add(ffUi, 'referenceHeight1', 0, 3).onChange(updateFloorTransform); gui.add(ffUi, 'referenceHeight2', 0, 3).onChange(updateFloorTransform); gui.add(actions, 'download'); function render() { window.requestAnimationFrame(render); ffUi.render(); fpUi.render(); } window.requestAnimationFrame(render); } // Object representing a UI for previewing a floor plane function FloorPreviewUI(containerElement, propSource) { var self = this; self.containerElement = containerElement; if(typeof(self.containerElement) === 'string') { self.containerElement = document.getElementById(self.containerElement); } self.propSource = propSource; self.texture = null; // Create container within container with position: relative to enable // absolute positioning within it. var _uiElement = document.createElement('div'); _uiElement.style.position = 'relative'; _uiElement.style.backgroundColor = '#bbb'; _uiElement.style.width = '100%'; _uiElement.style.height = '100%'; _uiElement.style.overflow = 'hidden'; self.containerElement.appendChild(_uiElement); var boardId = 'floor-preview-ui-board-' + Math.random().toString(16).slice(2); var floorId = 'floor-preview-ui-floor-' + Math.random().toString(16).slice(2); function createUIChild(id) { var childElement = document.createElement('div'); childElement.id = id; childElement.style.position = 'absolute'; childElement.style.width = '100%'; childElement.style.height = '100%'; childElement.style.top = '0'; childElement.style.bottom = '0'; _uiElement.appendChild(childElement); return childElement; } // Now create the elements for the WebGL-rendered floor and the JSXGraph // board. var floorElement = createUIChild(floorId); var boardElement = createUIChild(boardId); // Create the JSXGraph board self._board = JXG.JSXGraph.initBoard(boardId, { boundingbox: [-10, 10, 10, -10], axis: true, grid: true, keepAspectRatio: true, zoom: { wheel: true, }, pan: { needShift: false }, showCopyright: false, }); self._floorRenderer = new FloorPreviewRenderer(floorElement); //self._board.on('boundingbox', function() { self._setFloorCamera(); }); } FloorPreviewUI.prototype.containerResized = function() { var elem = this.containerElement; this._board.renderer.resize(elem.clientWidth, elem.clientHeight); this._board.setBoundingBox(this._board.getBoundingBox(), true); this._floorRenderer.containerResized(); }; FloorPreviewUI.prototype.render = function() { var bbox = this._board.getBoundingBox(); this._floorRenderer.camera.updateProjectionMatrix(); this._floorRenderer.viewBounds.set(bbox[0], bbox[1], bbox[2], bbox[3]); this._floorRenderer.containerResized(); this._floorRenderer.barrelPercent = this.propSource.barrelDistortion; this._floorRenderer.worldToImageMatrix.copy(this.propSource.worldToImageMatrix); this._floorRenderer.floorRadius = this.propSource.floorRadius; this._floorRenderer.texture = this.texture; this._floorRenderer.render(); }; // Create ThreeJS context for rendering floor. function FloorPreviewRenderer(containerElement, textureUrl) { var self = this; self.containerElement = containerElement; self.scene = new THREE.Scene(); self.camera = new THREE.OrthographicCamera(-0.5, 0.5, 0.5, -0.5, 0, 2); self.renderer = new THREE.WebGLRenderer({ alpha: true, depth: false }); self.imageToFloorMatrix = new THREE.Matrix3(); self.floorRadius = 15; self.barrelPercent = 0.0; self.viewBounds = new THREE.Vector4(-0.5, 0.5, 0.5, -0.5); self.texture = null; self.worldToImageMatrix = new THREE.Matrix4(); var geometry = new THREE.PlaneGeometry(1, 1, 1, 1); self.floorMaterial = new THREE.ShaderMaterial({ vertexShader: document.getElementById('previewVertexShader').textContent, fragmentShader: document.getElementById('previewFragmentShader').textContent, uniforms: { image: { type: 't', value: self.texture }, textureSize: { type: 'v2', value: new THREE.Vector2(1, 1) }, barrelPercent: { type: 'f', value: self.barrelPercent }, worldToImageMatrix: { type: 'm4', value: self.worldToImageMatrix }, viewBounds: { type: 'v4', value: self.viewBounds }, floorRadius: { type: 'f', value: self.floorRadius }, }, }); var floor = new THREE.Mesh(geometry, self.floorMaterial); self.scene.add(floor); self.camera.position.z = 1; self.containerElement.appendChild(self.renderer.domElement); self.containerResized(); } FloorPreviewRenderer.prototype.containerResized = function() { var elem = this.containerElement; this.renderer.setSize(elem.clientWidth, elem.clientHeight); } FloorPreviewRenderer.prototype.render = function() { var uniforms; uniforms = this.floorMaterial.uniforms; uniforms.barrelPercent.value = this.barrelPercent; uniforms.floorRadius.value = this.floorRadius; uniforms.image.value = this.texture; if(this.texture) { var w = this.texture.image.width, h = this.texture.image.height; uniforms.textureSize.value.set(w, h); } this.renderer.render(this.scene, this.camera); } // Object representing a UI for finding floor planes. Takes a single element or // element id which contains the UI. function FloorFindUI(containerElement) { var self = this; self.containerElement = containerElement; if(typeof(self.containerElement) === 'string') { self.containerElement = document.getElementById(self.containerElement); } self.floorOpacity = 0.25; self.floorRadius = 20.0; self.barrelDistortion = 0; self._projectionMatrix = []; // Affine transform to apply to floor plane. var floorPlaneTransform = numeric.identity(3); self.getFloorPlaneTransform = function() { return floorPlaneTransform; } self.setFloorPlaneTransform = function(t) { floorPlaneTransform = t; this.updateProjectionMatrix(); } // Create container within container with position: relative to enable // absolute positioning within it. var _uiElement = document.createElement('div'); _uiElement.style.position = 'relative'; _uiElement.style.backgroundColor = '#888'; _uiElement.style.width = '100%'; _uiElement.style.height = '100%'; _uiElement.style.overflow = 'hidden'; self.containerElement.appendChild(_uiElement); var boardId = 'floor-ui-board-' + Math.random().toString(16).slice(2); var floorId = 'floor-ui-floor-' + Math.random().toString(16).slice(2); function createUIChild(id) { var childElement = document.createElement('div'); childElement.id = id; childElement.style.position = 'absolute'; childElement.style.width = '100%'; childElement.style.height = '100%'; childElement.style.top = '0'; childElement.style.bottom = '0'; _uiElement.appendChild(childElement); return childElement; } // Now create the elements for the WebGL-rendered floor and the JSXGraph // board. var floorElement = createUIChild(floorId); var boardElement = createUIChild(boardId); // Create the JSXGraph board self._board = JXG.JSXGraph.initBoard(boardId, { boundingbox: [-100, 1180, 2020, -100], axis: false, grid: false, keepAspectRatio: true, zoom: { wheel: true, }, pan: { needShift: false }, showCopyright: false, }); // Create the floor-rendering context self._floorRenderer = new FloorRenderer(floorElement); // Create the JSXGraph geometry var w = 640, h = 480; var vp1 = self._board.create('point', [0, h*0.5], { name: 'VP1' }); var vp2 = self._board.create('point', [w, h*0.5], { name: 'VP2' }); var horizon = self._board.create('line', [vp1, vp2], { label: 'Horizon' }); var pB = self._board.create('point', [w*0.5, h*0.125], { name: 'B' }); var l11 = self._board.create('line', [vp1, pB], { straightFirst: false, fixed: true, highlight: false }); var l12 = self._board.create('line', [vp2, pB], { straightFirst: false, fixed: true, highlight: false }); var pD = self._board.create('point', [w*0.5, h*0.25], { name: 'D' }); var l21 = self._board.create('line', [vp1, pD], { straightFirst: false, fixed: true, highlight: false }); var l22 = self._board.create('line', [vp2, pD], { straightFirst: false, fixed: true, highlight: false }); var pA = self._board.create('intersection', [l21, l12], { name: 'A', fixed: true, highlight: false }); var pC = self._board.create('intersection', [l22, l11], { name: 'C', fixed: true, highlight: false }); self._pA = pA; self._pB = pB; self._pC = pC; self._pD = pD; self._vp1 = vp1; self._vp2 = vp2; self._refVert1Floor = self._board.create('point', [w*0.25, h*0.25], { name: 'Floor' }); self._refVert2Floor = self._board.create('point', [w*0.75, h*0.25], { name: 'Floor' }); self._refVert1 = self._board.create('point', [w*0.25, h*0.75], { name: 'Vertical 1' }); self._refVert2 = self._board.create('point', [w*0.75, h*0.75], { name: 'Vertical 2' }); self.referenceHeight1 = 0.4; self.referenceHeight2 = 0.4; self._board.create('line', [self._refVert1Floor, self._refVert1], { straightFirst: false, straightLast: false }); self._board.create('line', [self._refVert2Floor, self._refVert2], { straightFirst: false, straightLast: false }); self.imageToFloorMatrix = new THREE.Matrix3(); self.worldToImageMatrix = new THREE.Matrix4(); function setFloorCamera() { // There's a new bounding box. Bounding boxes in JSXGraph are arrays // giving [left, top, right, bottom] co-ords. Use this bounding box to // update floor renderer. var bbox = self._board.getBoundingBox(); self._floorRenderer.camera.updateProjectionMatrix(); self._floorRenderer.viewBounds.set(bbox[0], bbox[1], bbox[2], bbox[3]); self._floorRenderer.containerResized(); }; self._board.on('boundingbox', setFloorCamera); self.updateProjectionMatrix(); self._board.on('update', function() { self.updateProjectionMatrix(); }); } FloorFindUI.prototype.toJSON = function() { return JSON.stringify({ controlPoints: { A: [ this._pA.X(), this._pA.Y() ], B: [ this._pA.X(), this._pA.Y() ], C: [ this._pA.X(), this._pA.Y() ], D: [ this._pA.X(), this._pA.Y() ], VP1: [ this._vp1.X(), this._vp1.Y() ], VP2: [ this._vp2.X(), this._vp2.Y() ], Vert1Floor: [ this._refVert1Floor.X(), this._refVert1Floor.Y() ], Vert2Floor: [ this._refVert2Floor.X(), this._refVert2Floor.Y() ], Vert1Top: [ this._refVert1.X(), this._refVert1.Y() ], Vert2Top: [ this._refVert2.X(), this._refVert2.Y() ], }, controlValues: { referenceHeight1: this.referenceHeight1, referenceHeight2: this.referenceHeight2, }, pointCorrespondences: this.pointCorrespondences(), projectionMatrix: this._projectionMatrix, barrelCorrection: { K1: this.barrelDistortion, }, }); }; FloorFindUI.prototype.containerResized = function() { var elem = this.containerElement; this._board.renderer.resize(elem.clientWidth, elem.clientHeight); this._board.setBoundingBox(this._board.getBoundingBox(), true); this._floorRenderer.containerResized(); }; FloorFindUI.prototype.render = function() { this._floorRenderer.floorOpacity = this.floorOpacity; this._floorRenderer.floorRadius = this.floorRadius; this._floorRenderer.barrelPercent = this.barrelDistortion; this._floorRenderer.texture = this.texture; this._floorRenderer.render(); }; FloorFindUI.prototype.initialiseFromTexture = function() { var self = this; var w = self.texture.image.width, h = self.texture.image.height; self._board.setBoundingBox([-0.2*w, 1.2*h, 1.2*w, -0.2*h], true); self._vp1.setPosition(JXG.COORDS_BY_USER, [0, h*0.5]); self._vp2.setPosition(JXG.COORDS_BY_USER, [w, h*0.5]); self._pB.setPosition(JXG.COORDS_BY_USER, [w*0.5, h*0.125]); self._pD.setPosition(JXG.COORDS_BY_USER, [w*0.5, h*0.25]); self._board.update(); }; FloorFindUI.prototype.pointCorrespondences = function() { var self = this; // Firstly compute the image-space to floor plane matrix: var floorPoints = numeric.dot( self.getFloorPlaneTransform(), [ [1, 0, 0, 1], [0, 0, 1, 1], [1, 1, 1, 1], ] ); for(var i=0; i<4; ++i) { var w = floorPoints[2][i]; for(var j=0; j<3; ++j) { floorPoints[j][i] /= w; } } var H = computeHomography([ { x: self._pA.X(), y: self._pA.Y() }, { x: self._pB.X(), y: self._pB.Y() }, { x: self._pC.X(), y: self._pC.Y() }, { x: self._pD.X(), y: self._pD.Y() }, ], [ { x: floorPoints[0][0], y: floorPoints[1][0] }, { x: floorPoints[0][1], y: floorPoints[1][1] }, { x: floorPoints[0][2], y: floorPoints[1][2] }, { x: floorPoints[0][3], y: floorPoints[1][3] }, ]); var imageToFloor = [ [H[0], H[1], H[2]], [H[3], H[4], H[5]], [H[6], H[7], 1.0] ]; // Use the image to floor matrix to compute the floor-plane co-ordinates of // the reference verticals. var refVert1Floor = numeric.dot(imageToFloor, [ self._refVert1Floor.X(), self._refVert1Floor.Y(), 1 ]); refVert1Floor = numeric.div(refVert1Floor, refVert1Floor[2]); var refVert2Floor = numeric.dot(imageToFloor, [ self._refVert2Floor.X(), self._refVert2Floor.Y(), 1 ]); refVert2Floor = numeric.div(refVert2Floor, refVert2Floor[2]); // We can now compute a list of image-space and world-space correspondences. var imagePoints = [], worldPoints = []; imagePoints.push([self._pA.X(), self._pA.Y()]); imagePoints.push([self._pB.X(), self._pB.Y()]); imagePoints.push([self._pC.X(), self._pC.Y()]); imagePoints.push([self._pD.X(), self._pD.Y()]); for(var i=0; i<4; ++i) { worldPoints.push([floorPoints[0][i], floorPoints[1][i], 0]); } imagePoints.push([self._refVert1Floor.X(), self._refVert1Floor.Y()]); imagePoints.push([self._refVert1.X(), self._refVert1.Y()]); worldPoints.push([refVert1Floor[0], refVert1Floor[1], 0]); worldPoints.push([refVert1Floor[0], refVert1Floor[1], self.referenceHeight1]); imagePoints.push([self._refVert2Floor.X(), self._refVert2Floor.Y()]); imagePoints.push([self._refVert2.X(), self._refVert2.Y()]); worldPoints.push([refVert2Floor[0], refVert2Floor[1], 0]); worldPoints.push([refVert2Floor[0], refVert2Floor[1], self.referenceHeight2]); return { image: imagePoints, world: worldPoints }; } FloorFindUI.prototype.updateProjectionMatrix = function() { var self = this; var correspondences = self.pointCorrespondences(); var imagePoints = correspondences.image, worldPoints = correspondences.world; // We can now form the camera calibration problem as outlined in // http://research.microsoft.com/en-us/um/people/zhang/Papers/Camera%20Calibration%20-%20book%20chapter.pdf // (With sign errors corrected) var G = []; for(i=0; i<imagePoints.length; ++i) { var X = worldPoints[i], x = imagePoints[i]; G.push([ X[0], X[1], X[2], 1, 0, 0, 0, 0, -x[0]*X[0], -x[0]*X[1], -x[0]*X[2], -x[0] ]); G.push([ 0, 0, 0, 0, X[0], X[1], X[2], 1, -x[1]*X[0], -x[1]*X[1], -x[1]*X[2], -x[1] ]); } var GtG = numeric.dot(numeric.transpose(G), G); var eigsol = numeric.eig(GtG); var absLambda = eigsol.lambda.abs().x; var minidx = 0, minval = absLambda[0]; for(i=0; i<absLambda.length; ++i) { if(absLambda[i] < minval) { minidx = i; minval = absLambda[i]; } } // Projection matrix coefficients are eigenvector with minimum eigenvalue: var Pvec = numeric.transpose(eigsol.E.x)[minidx]; // Normalise s.t. p31^2 + p32^2 + p33^2 = 1 and p34 +ve Pvec = numeric.div(Pvec, Math.sqrt(Pvec[8]*Pvec[8] + Pvec[9]*Pvec[9] + Pvec[10]*Pvec[10])); Pvec = numeric.mul(Pvec, Math.sign(Pvec[11])); var P = [ [Pvec[0], Pvec[1], Pvec[2], Pvec[3]], [Pvec[4], Pvec[5], Pvec[6], Pvec[7]], [Pvec[8], Pvec[9], Pvec[10], Pvec[11]] ]; // Form subset of matrix P which acts on world co-ordinate == 0 var floorToImage = [ [P[0][0], P[0][1], P[0][3]], [P[1][0], P[1][1], P[1][3]], [P[2][0], P[2][1], P[2][3]], ]; var imageToFloor = numeric.inv(floorToImage); self._floorRenderer.imageToFloorMatrix.set( imageToFloor[0][0], imageToFloor[0][1], imageToFloor[0][2], imageToFloor[1][0], imageToFloor[1][1], imageToFloor[1][2], imageToFloor[2][0], imageToFloor[2][1], imageToFloor[2][2] ); self.imageToFloorMatrix = self._floorRenderer.imageToFloorMatrix; self.worldToImageMatrix.set( P[0][0], P[0][1], P[0][2], P[0][3], P[1][0], P[1][1], P[1][2], P[1][3], 0, 0, 1, 0, P[2][0], P[2][1], P[2][2], P[2][3] ); self._floorRenderer.worldToImageMatrix.copy(self.worldToImageMatrix); self._projectionMatrix = P; }; // Create ThreeJS context for rendering floor. function FloorRenderer(containerElement, textureUrl) { var self = this; self.containerElement = containerElement; self.floorScene = new THREE.Scene(); self.camera = new THREE.OrthographicCamera(-0.5, 0.5, 0.5, -0.5, 0, 2); self.renderer = new THREE.WebGLRenderer({ alpha: true, depth: false }); self.floorOpacity = 0.25; self.floorRadius = 15; self.barrelPercent = 0.0; self.viewBounds = new THREE.Vector4(-0.5, 0.5, 0.5, -0.5); // Matrices self.imageToFloorMatrix = new THREE.Matrix3(); self.imageToViewportMatrix = new THREE.Matrix4(); self.worldToImageMatrix = new THREE.Matrix4(); self._worldToViewportMatrix = new THREE.Matrix4(); self.texture = null; var geometry = new THREE.PlaneGeometry(1, 1, 1, 1); self.imageMaterial = new THREE.ShaderMaterial({ vertexShader: document.getElementById('imageVertexShader').textContent, fragmentShader: document.getElementById('imageFragmentShader').textContent, uniforms: { viewBounds: { type: 'v4', value: self.viewBounds }, image: { type: 't', value: self.texture }, textureSize: { type: 'v2', value: new THREE.Vector2(1, 1) }, barrelPercent: { type: 'f', value: self.barrelPercent }, }, }); var img = new THREE.Mesh(geometry, self.imageMaterial); self.floorScene.add(img); self.floorMaterial = new THREE.ShaderMaterial({ vertexShader: document.getElementById('floorVertexShader').textContent, fragmentShader: document.getElementById('floorFragmentShader').textContent, uniforms: { viewBounds: { type: 'v4', value: self.viewBounds }, imageToFloorMatrix: { type: 'm3', value: self.imageToFloorMatrix }, floorOpacity: { type: 'f', value: self.floorOpacity }, floorRadius: { type: 'f', value: self.floorRadius }, }, transparent: true, }); var floor = new THREE.Mesh(geometry, self.floorMaterial); self.floorScene.add(floor); self.axisScene = new THREE.Scene(); self.axisCamera = new THREE.Camera(); //self.axisCamera = new THREE.PerspectiveCamera(90, 1, 1, 10000); //self.axisCamera.position.z = 5; self.axisScene.add(new THREE.ArrowHelper( new THREE.Vector3(1, 0, 0), new THREE.Vector3(0, 0, 0), 1, 0xff0000, 0.2, 0.1 )); self.axisScene.add(new THREE.ArrowHelper( new THREE.Vector3(0, 1, 0), new THREE.Vector3(0, 0, 0), 1, 0x00ff00, 0.2, 0.1 )); self.axisScene.add(new THREE.ArrowHelper( new THREE.Vector3(0, 0, 1), new THREE.Vector3(0, 0, 0), 1, 0x0000ff, 0.2, 0.1 )); self.camera.position.z = 1; self.containerElement.appendChild(self.renderer.domElement); self.containerResized(); } FloorRenderer.prototype.containerResized = function() { var elem = this.containerElement; this.renderer.setSize(elem.clientWidth, elem.clientHeight); } FloorRenderer.prototype.render = function() { // Re-calculate the image -> viewport matrix from the [left, top, right, // bottom] bounds. var bounds = this.viewBounds; var w = bounds.z - bounds.x, h = bounds.y - bounds.w; var cx = 0.5*(bounds.z + bounds.x), cy = 0.5*(bounds.y + bounds.w); this.imageToViewportMatrix.set( 2/w, 0, 0, -2*cx/w, 0, 2/h, 0, -2*cy/h, 0, 0, 1, 0, 0, 0, 0, 1 ); this._worldToViewportMatrix.multiplyMatrices( this.imageToViewportMatrix, this.worldToImageMatrix); this.axisCamera.projectionMatrix.copy(this._worldToViewportMatrix); var uniforms; uniforms = this.floorMaterial.uniforms; uniforms.imageToFloorMatrix.value = this.imageToFloorMatrix; uniforms.floorOpacity.value = this.floorOpacity; uniforms.floorRadius.value = this.floorRadius; uniforms = this.imageMaterial.uniforms; uniforms.barrelPercent.value = this.barrelPercent; uniforms.image.value = this.texture; if(this.texture) { var w = this.texture.image.width, h = this.texture.image.height; uniforms.textureSize.value.set(w, h); } this.renderer.autoClearColor = false; this.renderer.render(this.floorScene, this.camera); this.renderer.render(this.axisScene, this.axisCamera); } // Compute 3x3 matrix H which maps image-plane to floor-plane homogenous // co-ordinates. // // From: // http://homepages.inf.ed.ac.uk/rbf/CVonline/LOCAL_COPIES/EPSRC_SSAZ/node11.html function computeHomography(imagePoints, floorPoints) { if((imagePoints.length != 4) || (floorPoints.length != 4)) { throw new Error('Need 4 correspondences'); } var x1 = imagePoints[0].x, y1 = imagePoints[0].y, x2 = imagePoints[1].x, y2 = imagePoints[1].y, x3 = imagePoints[2].x, y3 = imagePoints[2].y, x4 = imagePoints[3].x, y4 = imagePoints[3].y; var xp1 = floorPoints[0].x, yp1 = floorPoints[0].y, xp2 = floorPoints[1].x, yp2 = floorPoints[1].y, xp3 = floorPoints[2].x, yp3 = floorPoints[2].y, xp4 = floorPoints[3].x, yp4 = floorPoints[3].y; var A = [ [ x1, y1, 1, 0, 0, 0, -xp1*x1, -xp1*y1 ], [ 0, 0, 0, x1, y1, 1, -yp1*x1, -yp1*y1 ], [ x2, y2, 1, 0, 0, 0, -xp2*x2, -xp2*y2 ], [ 0, 0, 0, x2, y2, 1, -yp2*x2, -yp2*y2 ], [ x3, y3, 1, 0, 0, 0, -xp3*x3, -xp3*y3 ], [ 0, 0, 0, x3, y3, 1, -yp3*x3, -yp3*y3 ], [ x4, y4, 1, 0, 0, 0, -xp4*x4, -xp4*y4 ], [ 0, 0, 0, x4, y4, 1, -yp4*x4, -yp4*y4 ], ]; var b = [ xp1, yp1, xp2, yp2, xp3, yp3, xp4, yp4 ]; return numeric.solve(A, b); } // Call main() function main(); })();
9aea15d52db0da06c276f7e0d69f07771f5174c3
[ "JavaScript" ]
1
JavaScript
rjw57/ground-plane-estimate
25d97f36ecbc240b31cc1ded76e0953ac874f77a
7bd0ac647cb28f71aba249a77511c513f8f6f1ab
refs/heads/master
<file_sep>using System; using System.ComponentModel; using System.ComponentModel.DataAnnotations.Schema; using System.Runtime.Serialization; using CMSSolutions.Data; using CMSSolutions.Data.Entity; namespace CMSSolutions.Websites.Entities { public enum SearchField { Id, SiteId, CategoryIds, CategoryNames, Type, SearchId, Title, TitleEnglish, Alias, Sumary, Tags, IsShow, IsClip, IsTrailer, IsFilm, Keyword, KeywordEN } [DataContract] public class SearchInfo : BaseEntity<long> { [DataMember] [DisplayName("LanguageCode")] public string LanguageCode { get; set; } [DataMember] [DisplayName("SiteId")] public int SiteId { get; set; } [DataMember] [DisplayName("CategoryIds")] public string CategoryIds { get; set; } [NotMapped] [DisplayName("CategoryNames")] public string CategoryNames { get; set; } [DataMember] [DisplayName("Type")] public int Type { get; set; } [DataMember] [DisplayName("SearchId")] public string SearchId { get; set; } [DataMember] [DisplayName("Title")] public string Title { get; set; } [DataMember] [DisplayName("TitleEnglish")] public string TitleEnglish { get; set; } [DataMember] [DisplayName("Images")] public string Images { get; set; } [DataMember] [DisplayName("Alias")] public string Alias { get; set; } [DataMember] [DisplayName("Sumary")] public string Sumary { get; set; } [DataMember] [DisplayName("Tags")] public string Tags { get; set; } [DataMember] [DisplayName("CreateDate")] public DateTime CreateDate { get; set; } [DataMember] [DisplayName("IsBlock")] public bool IsBlock { get; set; } [DataMember] [DisplayName("Processed")] public int Processed { get; set; } [NotMapped] [DisplayName("IsShow")] public bool IsShow { get; set; } [NotMapped] [DisplayName("IsClip")] public bool IsClip { get; set; } [NotMapped] [DisplayName("IsTrailer")] public bool IsTrailer { get; set; } [NotMapped] [DisplayName("IsFilm")] public bool IsFilm { get; set; } [NotMapped] [DisplayName("ViewCount")] public string ViewCount { get; set; } } public class SearchMap : EntityTypeConfiguration<SearchInfo>, IEntityTypeConfiguration { public SearchMap() { ToTable("Modules_Search"); HasKey(m => m.Id); Property(m => m.LanguageCode).HasMaxLength(50); Property(m => m.SiteId); Property(m => m.CategoryIds).HasMaxLength(250).IsRequired(); Property(m => m.Type); Property(m => m.SearchId).HasMaxLength(50); Property(m => m.Title).HasMaxLength(250); Property(m => m.TitleEnglish).IsRequired().HasMaxLength(250); Property(m => m.Images).HasMaxLength(500); Property(m => m.Alias).HasMaxLength(250); Property(m => m.Sumary).HasMaxLength(500); Property(m => m.Tags).HasMaxLength(400); Property(m => m.CreateDate); Property(m => m.IsBlock); } } } <file_sep>using CMSSolutions.Web.UI.ControlForms; using CMSSolutions.Websites.Entities; namespace CMSSolutions.Websites.Models { public class CategoryModel { public CategoryModel() { IsActived = true; } [ControlHidden] public int Id { get; set; } [ControlChoice(ControlChoice.DropDownList, Required = true, LabelText = "Ngôn ngữ hiển thị", ContainerCssClass = Constants.ContainerCssClassCol3, ContainerRowIndex = 0, OnSelectedIndexChanged = "$('#" + Extensions.Constants.ParentId+ "').empty();")] public string LanguageCode { get; set; } [ControlCascadingDropDown(LabelText = "Trang web", ParentControl = "LanguageCode", AbsoluteParentControl = true, ContainerCssClass = Constants.ContainerCssClassCol3, ContainerRowIndex = 0)] public int SiteId { get; set; } [ControlCascadingDropDown(LabelText = "Chuyên mục gốc", ParentControl = "SiteId", AbsoluteParentControl = true, ContainerCssClass = Constants.ContainerCssClassCol3, ContainerRowIndex = 0)] public int ParentId { get; set; } [ControlNumeric(LabelText = "Vị trí", Required = true, MaxLength = 3, ContainerCssClass = Constants.ContainerCssClassCol3, ContainerRowIndex = 0)] public int OrderBy { get; set; } [ControlChoice(ControlChoice.CheckBox, LabelText = "", PrependText = "Làm trang chủ", ContainerCssClass = Constants.ContainerCssClassCol3, ContainerRowIndex = 1)] public bool IsHome { get; set; } [ControlChoice(ControlChoice.CheckBox, LabelText = "", PrependText = "Được hiển thị", ContainerCssClass = Constants.ContainerCssClassCol3, ContainerRowIndex = 1)] public bool IsActived { get; set; } [ControlChoice(ControlChoice.CheckBox, LabelText = "", PrependText = "Có chuyên mục con", ContainerCssClass = Constants.ContainerCssClassCol3, ContainerRowIndex = 1)] public bool HasChilden { get; set; } [ControlChoice(ControlChoice.CheckBox, LabelText = "", PrependText = "Không sử dụng", ContainerCssClass = Constants.ContainerCssClassCol3, ContainerRowIndex = 1)] public bool IsDeleted { get; set; } [ControlText(Type = ControlText.TextBox, LabelText = "<NAME>", PlaceHolder = "Tối đa 250 ký tự", Required = true, MaxLength = 250, ContainerCssClass = Constants.ContainerCssClassCol4, ContainerRowIndex = 2)] public string ShortName { get; set; } [ControlText(Type = ControlText.TextBox, LabelText = "Tên đầy đủ", PlaceHolder = "Tối đa 400 ký tự", Required = true, MaxLength = 400, ContainerCssClass = Constants.ContainerCssClassCol8, ContainerRowIndex = 2)] public string Name { get; set; } [ControlText(Type = ControlText.TextBox, LabelText = "<NAME>", PlaceHolder = "Tối đa 250 ký tự", MaxLength = 250, ContainerCssClass = Constants.ContainerCssClassCol12, ContainerRowIndex = 4)] public string Url { get; set; } [ControlText(LabelText = "Mô tả SEO", PlaceHolder = "Tối đa 2000 ký tự", Type = ControlText.MultiText, Required = true, Rows = 2, MaxLength = 2000, ContainerCssClass = Constants.ContainerCssClassCol12, ContainerRowIndex = 5)] public string Description { get; set; } [ControlText(LabelText = "Tags SEO", PlaceHolder = "Tối đa 2000 ký tự", Type = ControlText.MultiText, Required = true, Rows = 2, MaxLength = 2000, ContainerCssClass = Constants.ContainerCssClassCol12, ContainerRowIndex = 6)] public string Tags { get; set; } public static implicit operator CategoryModel(CategoryInfo other) { if (other == null) { return null; } return new CategoryModel { Id = other.Id, SiteId = other.SiteId, ParentId = other.ParentId, ShortName = other.ShortName, Name = other.Name, LanguageCode = other.LanguageCode, IsActived = other.IsActived, OrderBy = other.OrderBy, Description = other.Description, Tags = other.Tags, Url = other.Url, IsHome = other.IsHome, HasChilden = other.HasChilden, IsDeleted = other.IsDeleted }; } } }<file_sep>using CMSSolutions.Web.UI.ControlForms; using CMSSolutions.Websites.Entities; namespace CMSSolutions.Websites.Models { public class CollectionModel { [ControlHidden] public int Id { get; set; } [ControlChoice(ControlChoice.DropDownList, Required = true, LabelText = "Ngôn ngữ hiển thị", ContainerCssClass = Constants.ContainerCssClassCol4, ContainerRowIndex = 0)] public string LanguageCode { get; set; } [ControlCascadingDropDown(LabelText = "Trang web", ParentControl = "LanguageCode", AbsoluteParentControl = true, ContainerCssClass = Constants.ContainerCssClassCol4, ContainerRowIndex = 1)] public int SiteId { get; set; } [ControlText(Type = ControlText.TextBox, Required = true, MaxLength = 250, LabelText = "Tên bộ phim", ContainerCssClass = Constants.ContainerCssClassCol4, ContainerRowIndex = 2)] public string Name { get; set; } [ControlNumeric(LabelText = "Vị trí", Required = true, MaxLength = 3, ContainerCssClass = Constants.ContainerCssClassCol2, ContainerRowIndex = 3)] public int OrderBy { get; set; } [ControlChoice(ControlChoice.CheckBox, LabelText = "", PrependText = "Bộ phim mới cập nhật", ContainerCssClass = Constants.ContainerCssClassCol2, ContainerRowIndex = 3)] public bool IsHot { get; set; } [ControlChoice(ControlChoice.DropDownList, Required = true,LabelText = "Trạng thái", ContainerCssClass = Constants.ContainerCssClassCol4, ContainerRowIndex = 4)] public int Status { get; set; } [ControlText(Type = ControlText.MultiText, Rows = 2, MaxLength = 2000, LabelText = "Giới thiệu", ContainerCssClass = Constants.ContainerCssClassCol12, ContainerRowIndex = 5)] public string Description { get; set; } public static implicit operator CollectionModel(CollectionInfo entity) { return new CollectionModel { Id = entity.Id, LanguageCode = entity.LanguageCode, SiteId = entity.SiteId, Name = entity.Name, IsHot = entity.IsHot, Description = entity.Description, Status = entity.Status, OrderBy = entity.OrderBy }; } } } <file_sep>using System; using System.ComponentModel; using System.ComponentModel.DataAnnotations.Schema; using System.Runtime.Serialization; using CMSSolutions.Data; using CMSSolutions.Data.Entity; namespace CMSSolutions.Websites.Entities { [DataContract] public class ArticlesInfo : BaseEntity<int> { [DataMember] [DisplayName("SiteId")] public int SiteId { get; set; } [DataMember] [DisplayName("ParentId")] public int ParentId { get; set; } [DataMember] [DisplayName("CategoryId")] public int CategoryId { get; set; } [NotMapped] [DisplayName("CategoryAlias")] public string CategoryAlias { get; set; } [NotMapped] [DisplayName("CategoryName")] public string CategoryName { get; set; } [DataMember] [DisplayName("LanguageCode")] public string LanguageCode { get; set; } [DataMember] [DisplayName("Icon")] public string Icon { get; set; } [DataMember] [DisplayName("Title")] public string Title { get; set; } [DataMember] [DisplayName("Alias")] public string Alias { get; set; } [DataMember] [DisplayName("Summary")] public string Summary { get; set; } [DataMember] [DisplayName("Contents")] public string Contents { get; set; } [DataMember] [DisplayName("CreateDate")] public DateTime CreateDate { get; set; } [DataMember] [DisplayName("CreateByUser")] public int CreateByUser { get; set; } [DataMember] [DisplayName("IsPublished")] public bool IsPublished { get; set; } [DataMember] [DisplayName("PublishedDate")] public DateTime? PublishedDate { get; set; } [NotMapped] [DisplayName(Constants.NotMapped)] public string TextPublishedDate { get { if (PublishedDate != null) { return PublishedDate.Value.ToString(Extensions.Constants.DateTimeFomat2); } return CreateDate.ToString(Extensions.Constants.DateTimeFomat2); } } [DataMember] [DisplayName("IsHome")] public bool IsHome { get; set; } [DataMember] [DisplayName("IsVideo")] public bool IsVideo { get; set; } [DataMember] [DisplayName("VideosUrl")] public string VideosUrl { get; set; } [DataMember] [DisplayName("ViewCount")] public int ViewCount { get; set; } [DataMember] [DisplayName("Description")] public string Description { get; set; } [DataMember] [DisplayName("Tags")] public string Tags { get; set; } [DataMember] [DisplayName("IsDeleted")] public bool IsDeleted { get; set; } } public class ArticlesMap : EntityTypeConfiguration<ArticlesInfo>, IEntityTypeConfiguration { public ArticlesMap() { ToTable("Modules_Articles"); HasKey(x => x.Id); Property(x => x.SiteId).IsRequired(); Property(x => x.CategoryId).IsRequired(); Property(x => x.Icon).HasMaxLength(300); Property(x => x.LanguageCode).HasMaxLength(50); Property(x => x.Title).IsRequired().HasMaxLength(200); Property(x => x.Alias).IsRequired().HasMaxLength(200); Property(x => x.Summary).IsRequired().HasMaxLength(400); Property(x => x.Contents).IsRequired(); Property(x => x.CreateDate).IsRequired(); Property(x => x.CreateByUser).IsRequired(); Property(x => x.IsPublished).IsRequired(); Property(x => x.IsHome).IsRequired(); Property(x => x.IsVideo).IsRequired(); Property(x => x.ViewCount).IsRequired(); Property(x => x.Description).HasMaxLength(400); Property(x => x.Tags).HasMaxLength(500); Property(x => x.IsDeleted).IsRequired(); } } }<file_sep>using System; using System.Globalization; using System.Web.Mvc; using CMSSolutions.Extensions; using CMSSolutions.Web.Mvc; using CMSSolutions.Web.Routing; using CMSSolutions.Web.Themes; using CMSSolutions.Web.UI.ControlForms; using CMSSolutions.Web.UI.Navigation; using CMSSolutions.Websites.Entities; using CMSSolutions.Websites.Extensions; using CMSSolutions.Websites.Models; using CMSSolutions.Websites.Services; namespace CMSSolutions.Websites.Controllers { [Themed(IsDashboard = true), Authorize] public class AdminActorController : BaseAdminController { public AdminActorController(IWorkContextAccessor workContextAccessor) : base(workContextAccessor) { TableName = "tblActors"; } [Url("admin/actors")] public ActionResult Index() { WorkContext.Breadcrumbs.Add(new Breadcrumb { Text = T("Quản lý diễn viên"), Url = "#" }); var result = new ControlGridFormResult<ActorInfo> { Title = T("Quản lý diễn viên"), CssClass = "table table-bordered table-striped", IsAjaxSupported = true, FetchAjaxSource = GetActors, DefaultPageSize = WorkContext.DefaultPageSize, EnablePaginate = true, UpdateActionName = "Update", GridWrapperStartHtml = Constants.Grid.GridWrapperStartHtml, GridWrapperEndHtml = Constants.Grid.GridWrapperEndHtml, ClientId = TableName, ActionsColumnWidth = 100 }; result.AddCustomVar(Extensions.Constants.SearchText, "$('#" + Extensions.Constants.SearchText + "').val();", true); result.AddCustomVar(Extensions.Constants.StatusId, "$('#" + Extensions.Constants.StatusId + "').val();", true); result.AddColumn(x => x.Id, T("ID")).AlignCenter().HasWidth(60); result.AddColumn(x => x.FullName, T("Họ và Tên")); result.AddColumn(x => EnumExtensions.GetDisplayName((Status)x.Status), T("Trạng thái")); result.AddAction().HasText(T("Thêm mới")) .HasUrl(Url.Action("Edit", RouteData.Values.Merge(new { id = 0 }))) .HasButtonStyle(ButtonStyle.Primary) .HasBoxButton(false) .HasRow(false) .HasCssClass(Constants.RowLeft) .HasRow(true) .ShowModalDialog(); result.AddAction(new ControlFormHtmlAction(BuildSearchText)).HasParentClass(Constants.ContainerCssClassCol3); result.AddAction(new ControlFormHtmlAction(BuildStatus)).HasParentClass(Constants.ContainerCssClassCol3); result.AddRowAction() .HasText(T("Sửa")) .HasUrl(x => Url.Action("Edit", RouteData.Values.Merge(new { id = x.Id }))) .HasButtonStyle(ButtonStyle.Default) .HasButtonSize(ButtonSize.ExtraSmall) .ShowModalDialog(); result.AddRowAction(true) .HasText(T("Xóa")) .HasName("Delete") .HasValue(x => x.Id.ToString(CultureInfo.InvariantCulture.ToString())) .HasButtonStyle(ButtonStyle.Danger) .HasButtonSize(ButtonSize.ExtraSmall) .HasConfirmMessage(T(Constants.Messages.ConfirmDeleteRecord).Text); result.AddReloadEvent("UPDATE_ENTITY_COMPLETE"); result.AddReloadEvent("DELETE_ENTITY_COMPLETE"); return result; } private ControlGridAjaxData<ActorInfo> GetActors(ControlGridFormRequest options) { var searchText = string.Empty; if (Utilities.IsNotNull(Request.Form[Extensions.Constants.SearchText])) { searchText = Request.Form[Extensions.Constants.SearchText]; } var statusId = 0; if (Utilities.IsNotNull(Request.Form[Extensions.Constants.StatusId])) { statusId = Convert.ToInt32(Request.Form[Extensions.Constants.StatusId]); } int totals; var items = WorkContext.Resolve<IActorService>().SearchPaged(searchText, statusId, options.PageIndex, options.PageSize, out totals); var result = new ControlGridAjaxData<ActorInfo>(items, totals); return result; } [Themed(false)] [Url("admin/actors/edit/{id}")] public ActionResult Edit(int id) { WorkContext.Breadcrumbs.Add(new Breadcrumb { Text = T("Quản lý diễn viên"), Url = Url.Action("Index") }); WorkContext.Breadcrumbs.Add(new Breadcrumb { Text = T("Thông tin diễn viên"), Url = "#" }); var model = new ActorModel(); if (id > 0) { var service = WorkContext.Resolve<IActorService>(); model = service.GetById(id); } var result = new ControlFormResult<ActorModel>(model) { Title = T("Thông tin diễn viên"), FormMethod = FormMethod.Post, UpdateActionName = "Update", SubmitButtonText = T("Lưu lại"), CancelButtonText = T("Đóng"), ShowBoxHeader = false, FormWrapperStartHtml = Constants.Form.FormWrapperStartHtml, FormWrapperEndHtml = Constants.Form.FormWrapperEndHtml }; result.RegisterExternalDataSource(x => x.Status, y => BindStatus()); return result; } [HttpPost, ValidateInput(false), FormButton("Save")] [Url("admin/actors/update")] public ActionResult Update(ActorModel model) { if (!ModelState.IsValid) { return new AjaxResult().Alert(T(Constants.Messages.InvalidModel)); } var service = WorkContext.Resolve<IActorService>(); ActorInfo item = model.Id == 0 ? new ActorInfo() : service.GetById(model.Id); if (service.CheckExist(model.Id, model.FullName)) { return new AjaxResult().NotifyMessage("UPDATE_ENTITY_COMPLETE") .Alert(T("Họ và Tên đã tồn tại.")); } item.FullName = model.FullName; item.Description = model.Description; item.Status = model.Status; service.Save(item); return new AjaxResult().NotifyMessage("UPDATE_ENTITY_COMPLETE") .Alert(T("Cập nhật thành công!")) .CloseModalDialog(); } [FormButton("Delete")] [HttpPost, ActionName("Update")] public ActionResult Delete(int id) { var service = WorkContext.Resolve<IActorService>(); var item = service.GetById(id); item.Status = (int)Status.Deleted; service.Update(item); return new AjaxResult() .NotifyMessage("DELETE_ENTITY_COMPLETE") .Alert(T("Dữ liệu chuyển trạng thái xóa tạm thời!")); } } } <file_sep>using System.Collections.Generic; using CMSSolutions.Websites.Entities; namespace CMSSolutions.Websites.Models { public class TagViewModel { public IList<TagInfo> ListTags { get; set; } } }<file_sep>using System.Web.Mvc; using CMSSolutions.Web.Mvc; using CMSSolutions.Web.Routing; using CMSSolutions.Web.Themes; using CMSSolutions.Web.UI.ControlForms; using CMSSolutions.Web.UI.Navigation; using CMSSolutions.Websites.Entities; using CMSSolutions.Websites.Extensions; using CMSSolutions.Websites.Models; using CMSSolutions.Websites.Services; namespace CMSSolutions.Websites.Controllers { [Themed(IsDashboard = true), Authorize] public class AdminSiteController : BaseAdminController { public AdminSiteController(IWorkContextAccessor workContextAccessor) : base(workContextAccessor) { TableName = "tblSites"; } [Url("admin/sites")] public ActionResult Index() { WorkContext.Breadcrumbs.Add(new Breadcrumb { Text = T("Quản lý trang web"), Url = "#" }); var result = new ControlGridFormResult<SiteInfo> { Title = T("Quản lý trang web"), CssClass = "table table-bordered table-striped", IsAjaxSupported = true, FetchAjaxSource = GetSites, UpdateActionName = "Update", ActionsColumnWidth = 100, ClientId = TableName, DefaultPageSize = WorkContext.DefaultPageSize, GridWrapperStartHtml = Constants.Grid.GridWrapperStartHtml, GridWrapperEndHtml = Constants.Grid.GridWrapperEndHtml }; result.AddCustomVar(Extensions.Constants.LanguageCode, "$('#" + Extensions.Constants.LanguageCode + "').val();", true); result.AddColumn(x => x.Id, T("ID")).AlignCenter().HasWidth(60); result.AddColumn(x => x.Name, T("Tên trang web")); result.AddColumn(x => x.Domain, T("Tên miền")); result.AddColumn(x => x.Url, T("Đường dẫn")); result.AddColumn(x => x.IsActived) .HasHeaderText(T("Sử dụng")) .AlignCenter() .HasWidth(100) .RenderAsStatusImage(); result.AddAction().HasText(T("Thêm mới")) .HasUrl(Url.Action("Edit", RouteData.Values.Merge(new { id = 0 }))) .HasButtonStyle(ButtonStyle.Primary) .HasBoxButton(false) .HasCssClass(Constants.RowLeft) .HasRow(true); result.AddAction(new ControlFormHtmlAction(() => BuildLanguages(false, string.Empty))).HasParentClass(Constants.ContainerCssClassCol3); result.AddRowAction() .HasText(T("Sửa")) .HasUrl(x => Url.Action("Edit", RouteData.Values.Merge(new { id = x.Id }))) .HasButtonStyle(ButtonStyle.Default) .HasButtonSize(ButtonSize.ExtraSmall); //result.AddRowAction(true) // .HasText(T("Xóa")) // .HasName("Delete") // .HasValue(x => x.Id) // .HasButtonStyle(ButtonStyle.Danger) // .HasButtonSize(ButtonSize.ExtraSmall) // .HasConfirmMessage(T(Constants.Messages.ConfirmDeleteRecord).Text); result.AddReloadEvent("UPDATE_ENTITY_COMPLETE"); //result.AddReloadEvent("DELETE_ENTITY_COMPLETE"); return result; } private ControlGridAjaxData<SiteInfo> GetSites(ControlGridFormRequest options) { var languageCode = WorkContext.CurrentCulture; if (Utilities.IsNotNull(Request.Form[Extensions.Constants.LanguageCode])) { languageCode = Request.Form[Extensions.Constants.LanguageCode]; } var items = WorkContext.Resolve<ISiteService>().GetRecords(x => x.LanguageCode == languageCode); var result = new ControlGridAjaxData<SiteInfo>(items); return result; } [Url("admin/sites/edit/{id}")] public ActionResult Edit(int id) { var model = new SiteModel(); if (id > 0) { var service = WorkContext.Resolve<ISiteService>(); model = service.GetById(id); } var result = new ControlFormResult<SiteModel>(model) { Title = T("Thông tin trang web"), FormMethod = FormMethod.Post, UpdateActionName = "Update", SubmitButtonText = T("Lưu lại"), ShowCancelButton = false, ShowBoxHeader = false, FormWrapperStartHtml = Constants.Form.FormWrapperStartHtml, FormWrapperEndHtml = Constants.Form.FormWrapperEndHtml }; result.AddAction().HasText(T("Trở về")) .HasUrl(Url.Action("Index")) .HasCssClass("btn btn-danger"); result.RegisterExternalDataSource(x => x.LanguageCode, y => BindLanguages()); return result; } [HttpPost, ValidateInput(false), FormButton("Save")] [Url("admin/sites/update")] public ActionResult Update(SiteModel model) { SiteInfo item; var service = WorkContext.Resolve<ISiteService>(); if (model.Id == 0) { item = new SiteInfo(); } else { item = service.GetById(model.Id); } item.Name = model.Name; item.LanguageCode = model.LanguageCode; item.Url = model.Url; item.Domain = model.Domain; item.IsActived = model.IsActived; item.Description = model.Description; service.Save(item); return new AjaxResult().NotifyMessage("UPDATE_ENTITY_COMPLETE").Alert(T("Cập nhật thành công!")); } //[FormButton("Delete")] //[HttpPost, ActionName("Update")] //public ActionResult Delete(int id) //{ // var service = WorkContext.Resolve<ISiteService>(); // var model = service.GetById(id); // service.Delete(model); // return new AjaxResult().NotifyMessage("DELETE_ENTITY_COMPLETE"); //} } } <file_sep>using System.ComponentModel; using System.Runtime.Serialization; using CMSSolutions.Data; using CMSSolutions.Data.Entity; namespace CMSSolutions.Websites.Entities { /// <summary> /// Nước sản xuất /// </summary> [DataContract] public class CountryInfo : BaseEntity<int> { [DataMember] [DisplayName("Code")] public string Code { get; set; } [DataMember] [DisplayName("Name")] public string Name { get; set; } } public class CountryMap : EntityTypeConfiguration<CountryInfo>, IEntityTypeConfiguration { public CountryMap() { ToTable("Modules_Countries"); HasKey(m => m.Id); Property(m => m.Code).IsRequired().HasMaxLength(50); Property(m => m.Name).IsRequired().HasMaxLength(250); } } } <file_sep>using System; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Text; using System.Web.Mvc; using CMSSolutions.Extensions; using CMSSolutions.Web.Mvc; using CMSSolutions.Web.Themes; using CMSSolutions.Web.UI.ControlForms; using CMSSolutions.Web.UI.Navigation; using CMSSolutions.Websites.Entities; using CMSSolutions.Websites.Extensions; using CMSSolutions.Websites.Services; using GemBox.Spreadsheet; namespace CMSSolutions.Websites.Controllers { [Themed(IsDashboard = true), Authorize] public class AdminReportSmsController : BaseAdminController { public AdminReportSmsController(IWorkContextAccessor workContextAccessor) : base(workContextAccessor) { TableName = "tblReportSms"; } [Url("admin/report/sms")] public ActionResult Index() { WorkContext.Breadcrumbs.Add(new Breadcrumb { Text = T("Báo cáo SMS"), Url = "#" }); var result = new ControlGridFormResult<TransactionSmsInfo> { Title = T("Báo cáo SMS"), CssClass = "table table-bordered table-striped", IsAjaxSupported = true, FetchAjaxSource = GetReportSMS, DefaultPageSize = WorkContext.DefaultPageSize, EnablePaginate = true, UpdateActionName = "Update", GridWrapperStartHtml = Constants.Grid.GridWrapperStartHtml, GridWrapperEndHtml = Constants.Grid.GridWrapperEndHtml, ClientId = TableName, ActionsColumnWidth = 150 }; result.AddCustomVar(Extensions.Constants.StatusId, "$('#" + Extensions.Constants.StatusId + "').val();", true); result.AddCustomVar(Extensions.Constants.TypeId, "$('#" + Extensions.Constants.TypeId + "').val();", true); result.AddCustomVar(Extensions.Constants.Locked, "$('#" + Extensions.Constants.Locked + "').val();", true); result.AddCustomVar(Extensions.Constants.FromDate, "$('#" + Extensions.Constants.FromDate + "').val();", true); result.AddCustomVar(Extensions.Constants.ToDate, "$('#" + Extensions.Constants.ToDate + "').val();", true); result.AddCustomVar(Extensions.Constants.SearchText, "$('#" + Extensions.Constants.SearchText + "').val();", true); result.AddColumn(x => x.TransactionCode, T("Mã GD")).HasWidth(60).AlignCenter(); result.AddColumn(x => x.CustomerCode, T("Mã KH")); result.AddColumn(x => x.FullName, T("Tên KH")); result.AddColumn(x => x.Amount, T("Số tiền")); result.AddColumn(x => EnumExtensions.GetDisplayName((RequestStatus)x.Status), T("Trạng thái")); result.AddColumn(x => x.TextStartDate, T("Từ ngày")); result.AddColumn(x => x.TextEndDate, T("Đến ngày")); result.AddColumn(x => x.IsLock) .HasHeaderText(T("Đang khóa")) .AlignCenter() .HasWidth(100) .RenderAsStatusImage(); result.AddAction().HasText(T("Chốt đối soát")) .HasUrl(Url.Action("Index", "AdminClosedSms")) .HasButtonStyle(ButtonStyle.Danger) .HasCssClass(Constants.RowLeft); result.AddAction().HasText(T("Xuất dữ liệu MO")) .HasUrl(Url.Action("ExportExcelMo")) .HasButtonStyle(ButtonStyle.Info) .HasCssClass(Constants.RowLeft); result.AddAction().HasText(T("Xuất dữ liệu MT")) .HasUrl(Url.Action("ExportExcelMt")) .HasButtonStyle(ButtonStyle.Info) .HasCssClass(Constants.RowLeft) .HasRow(true); result.AddAction(new ControlFormHtmlAction(BuildStatus)).HasParentClass(Constants.ContainerCssClassCol6); result.AddAction(new ControlFormHtmlAction(BuildTypes)).HasParentClass(Constants.ContainerCssClassCol3); result.AddAction(new ControlFormHtmlAction(BuildLocked)).HasParentClass(Constants.ContainerCssClassCol3).HasRow(true); result.AddAction(new ControlFormHtmlAction(() => BuildFromDate())).HasParentClass(Constants.ContainerCssClassCol3); result.AddAction(new ControlFormHtmlAction(() => BuildToDate())).HasParentClass(Constants.ContainerCssClassCol3); result.AddAction(new ControlFormHtmlAction(BuildSearchText)).HasParentClass(Constants.ContainerCssClassCol3); return result; } public override string BuildStatus() { var list = EnumExtensions.GetListItems<RequestStatus>(); var sb = new StringBuilder(); sb.AppendFormat(T("Trạng thái lỗi") + " <select id=\"" + Extensions.Constants.StatusId + "\" name=\"" + Extensions.Constants.StatusId + "\" autocomplete=\"off\" class=\"uniform form-control col-md-3\" onchange=\"$('#" + TableName + "').jqGrid().trigger('reloadGrid');\">"); foreach (var status in list) { if ((int)RequestStatus.Messages200 == int.Parse(status.Value)) { sb.AppendFormat("<option value=\"{1}\" selected>{0}</option>", status.Text, status.Value); continue; } sb.AppendFormat("<option value=\"{1}\">{0}</option>", status.Text, status.Value); } sb.Append("</select>"); return sb.ToString(); } private string BuildTypes() { var list = EnumExtensions.GetListItems<SMSType>(); var sb = new StringBuilder(); sb.AppendFormat(T("Loại tin nhắn") + " <select id=\"" + Extensions.Constants.TypeId + "\" name=\"" + Extensions.Constants.TypeId + "\" autocomplete=\"off\" class=\"uniform form-control col-md-3\" onchange=\"$('#" + TableName + "').jqGrid().trigger('reloadGrid');\">"); foreach (var status in list) { sb.AppendFormat("<option value=\"{1}\">{0}</option>", status.Text, status.Value); } sb.Append("</select>"); return sb.ToString(); } private string BuildLocked() { var list = new List<SelectListItem> { new SelectListItem{Value = "0", Text = "Chưa chốt sổ đối soát"}, new SelectListItem{Value = "1", Text = "Đã chốt sổ đối soát"} }; var sb = new StringBuilder(); sb.AppendFormat(T("Đối soát") + " <select id=\"" + Extensions.Constants.Locked + "\" name=\"" + Extensions.Constants.Locked + "\" autocomplete=\"off\" class=\"uniform form-control col-md-3\" onchange=\"$('#" + TableName + "').jqGrid().trigger('reloadGrid');\">"); foreach (var status in list) { sb.AppendFormat("<option value=\"{1}\">{0}</option>", status.Text, status.Value); } sb.Append("</select>"); return sb.ToString(); } private ControlGridAjaxData<TransactionSmsInfo> GetReportSMS(ControlGridFormRequest options) { var searchText = string.Empty; if (Utilities.IsNotNull(Request.Form[Extensions.Constants.SearchText])) { searchText = Request.Form[Extensions.Constants.SearchText]; } var type = 0; if (Utilities.IsNotNull(Request.Form[Extensions.Constants.TypeId])) { type = Convert.ToInt32(Request.Form[Extensions.Constants.TypeId]); } var status = 0; if (Utilities.IsNotNull(Request.Form[Extensions.Constants.StatusId])) { status = Convert.ToInt32(Request.Form[Extensions.Constants.StatusId]); } var locked = 0; if (Utilities.IsNotNull(Request.Form[Extensions.Constants.Locked])) { locked = Convert.ToInt32(Request.Form[Extensions.Constants.Locked]); } var fromDate = DateTime.Now.Date; if (Utilities.IsNotNull(Request.Form[Extensions.Constants.FromDate])) { fromDate = DateTime.ParseExact(Request.Form[Extensions.Constants.FromDate], "dd/MM/yyyy", CultureInfo.InvariantCulture); } var toDate = DateTime.Now.Date; if (Utilities.IsNotNull(Request.Form[Extensions.Constants.ToDate])) { toDate = DateTime.ParseExact(Request.Form[Extensions.Constants.ToDate], "dd/MM/yyyy", CultureInfo.InvariantCulture); } int totals; var items = WorkContext.Resolve<ITransactionSmsService>().GetPaged(searchText, type, status, locked, fromDate, toDate, options.PageIndex, options.PageSize, out totals); var result = new ControlGridAjaxData<TransactionSmsInfo>(items, totals); return result; } [Url("admin/report/sms/export-excel-mo")] public ActionResult ExportExcelMo() { var ef = new ExcelFile(); string fileName = Server.MapPath("/Media/Default/ExcelTemplate/DuLieuSMS.xls"); ef.LoadXls(fileName, XlsOptions.PreserveAll); ExcelWorksheet ws = ef.Worksheets[0]; var data = WorkContext.Resolve<ITransactionSmsService>().ExportExcelSms(Utilities.DateNull(), Utilities.DateNull(), (int)SMSType.MO); if (data != null && data.Count > 0) { int index = 1; foreach (var item in data) { ws.Cells[index, 0].Value = index; ws.Cells[index, 1].Value = item.CustomerCode; ws.Cells[index, 2].Value = item.FullName; ws.Cells[index, 3].Value = item.Amount; ws.Cells[index, 4].Value = item.ShortCode; ws.Cells[index, 5].Value = item.UserId; ws.Cells[index, 6].Value = item.CreateDate.ToString(Extensions.Constants.DateTimeFomatFull); ws.Cells[index, 7].Value = EnumExtensions.GetDisplayName((RequestStatus)item.Status); index++; ws.Rows[index].InsertCopy(1, ws.Rows[1]); } ws.Rows[index].Delete(); } byte[] fileContents; using (var stream = new MemoryStream()) { ef.SaveXls(stream); fileContents = stream.ToArray(); } return File(fileContents, "application/vnd.ms-excel"); } [Url("admin/report/sms/export-excel-mt")] public ActionResult ExportExcelMt() { var ef = new ExcelFile(); string fileName = Server.MapPath("/Media/Default/ExcelTemplate/DuLieuSMS.xls"); ef.LoadXls(fileName, XlsOptions.PreserveAll); ExcelWorksheet ws = ef.Worksheets[0]; var data = WorkContext.Resolve<ITransactionSmsService>().ExportExcelSms(Utilities.DateNull(), Utilities.DateNull(), (int)SMSType.MT); if (data != null && data.Count > 0) { int index = 1; foreach (var item in data) { ws.Cells[index, 0].Value = index; ws.Cells[index, 1].Value = item.CustomerCode; ws.Cells[index, 2].Value = item.FullName; ws.Cells[index, 3].Value = item.Amount; ws.Cells[index, 4].Value = item.ShortCode; ws.Cells[index, 5].Value = item.UserId; ws.Cells[index, 6].Value = item.CreateDate.ToString(Extensions.Constants.DateTimeFomatFull); ws.Cells[index, 7].Value = EnumExtensions.GetDisplayName((RequestStatus)item.Status); index++; ws.Rows[index].InsertCopy(1, ws.Rows[1]); } ws.Rows[index].Delete(); } byte[] fileContents; using (var stream = new MemoryStream()) { ef.SaveXls(stream); fileContents = stream.ToArray(); } return File(fileContents, "application/vnd.ms-excel"); } } } <file_sep>using System.ComponentModel; using System.Runtime.Serialization; using CMSSolutions.Data; using CMSSolutions.Data.Entity; namespace CMSSolutions.Websites.Entities { /// <summary> /// Diễn viên /// </summary> [DataContract] public class ActorInfo : BaseEntity<int> { [DataMember] [DisplayName("FullName")] public string FullName { get; set; } [DataMember] [DisplayName("Description")] public string Description { get; set; } [DataMember] [DisplayName("Status")] public int Status { get; set; } } public class ActorMap : EntityTypeConfiguration<ActorInfo>, IEntityTypeConfiguration { public ActorMap() { ToTable("Modules_Actors"); HasKey(m => m.Id); Property(m => m.FullName).IsRequired().HasMaxLength(250); Property(m => m.Description).HasMaxLength(2000); Property(m => m.Status).IsRequired(); } } } <file_sep>using System.Collections.Generic; using System.Data.SqlClient; using System.Linq; using CMSSolutions.Data; using CMSSolutions.Events; using CMSSolutions.Services; using CMSSolutions.Websites.Entities; namespace CMSSolutions.Websites.Services { public interface ICardTypeService : IGenericService<CardTypeInfo, int>, IDependency { IList<CardTypeInfo> GetPaged(int status, int pageIndex, int pageSize, out int totals); CardTypeInfo GetByCode(string code, int hasSerial); } public class CardTypeService : GenericService<CardTypeInfo, int>, ICardTypeService { public CardTypeService(IRepository<CardTypeInfo, int> repository, IEventBus eventBus) : base(repository, eventBus) { } public IList<CardTypeInfo> GetPaged(int status, int pageIndex, int pageSize, out int totals) { var results = Repository.Table.Where(x => x.Status == status).ToList(); { totals = results.Count(); return (from x in results select x).Skip((pageIndex - 1) * pageSize).Take(pageSize).ToList(); } } public CardTypeInfo GetByCode(string code, int hasSerial) { var list = new List<SqlParameter> { AddInputParameter("@Code", code), AddInputParameter("@HasSerial", hasSerial) }; return ExecuteReaderRecord<CardTypeInfo>("sp_CardTypes_GetByCode", list.ToArray()); } } } <file_sep>using System.Collections.Generic; using System.Data; using System.Data.SqlClient; using CMSSolutions.Data; using CMSSolutions.Events; using CMSSolutions.Services; using CMSSolutions.Websites.Entities; namespace CMSSolutions.Websites.Services { public interface IDownloadCustomerService : IGenericService<DownloadCustomerInfo, long>, IDependency { List<DownloadCustomerInfo> GetByCustomer(int customerId); DownloadCustomerInfo GetItem(int customerId, int downloadId); DataTable GetHistory(int customerId); } public class DownloadCustomerService : GenericService<DownloadCustomerInfo, long>, IDownloadCustomerService { public DownloadCustomerService(IRepository<DownloadCustomerInfo, long> repository, IEventBus eventBus) : base(repository, eventBus) { } public List<DownloadCustomerInfo> GetByCustomer(int customerId) { var list = new List<SqlParameter> { AddInputParameter("@CustomerId", customerId) }; return ExecuteReader<DownloadCustomerInfo>("sp_DownloadCustomers_GetByCustomer", list.ToArray()); } public DownloadCustomerInfo GetItem(int customerId, int downloadId) { var list = new List<SqlParameter> { AddInputParameter("@CustomerId", customerId), AddInputParameter("@DownloadId", downloadId) }; return ExecuteReaderRecord<DownloadCustomerInfo>("sp_DownloadCustomers_GetItem", list.ToArray()); } public DataTable GetHistory(int customerId) { var list = new List<SqlParameter> { AddInputParameter("@CustomerId", customerId) }; return ExecuteReader("sp_DownloadCustomers_GetHistory", list.ToArray()).Tables[0]; } } }<file_sep>using System; using System.Collections.Generic; using System.Net.Mail; using System.Text; using System.Web; using System.Web.Mvc; using CMSSolutions.Configuration; using CMSSolutions.Extensions; using CMSSolutions.Net.Mail; using CMSSolutions.Security.Cryptography; using CMSSolutions.Web.Mvc; using CMSSolutions.Websites.Entities; using CMSSolutions.Websites.Extensions; using CMSSolutions.Websites.Models; using CMSSolutions.Websites.Services; using DotNetOpenAuth.AspNet; using Microsoft.Web.WebPages.OAuth; namespace CMSSolutions.Websites.Controllers { public class BaseHomeController : BaseController { #region Paged public int PageIndex { get; set; } public int PageSize { get; set; } #endregion #region User Login public string GlobalCapcha { get { if (Session[Extensions.Constants.GlobalCapcha] != null) { return Session[Extensions.Constants.GlobalCapcha].ToString(); } return string.Empty; } } public bool IsVip { get { if (CurrentDate != DateTime.Now.Date) { var customer = WorkContext.Resolve<ICustomerService>().GetById(UserId); SetCustomerState(customer); } if (EndDate >= DateTime.Now) { return true; } return false; } } public bool IsLogin { get { return UserId > 0 && !string.IsNullOrEmpty(CustomerCode); } } public string CustomerCode { get { return GetCookies(Extensions.Constants.GlobalCustomerCode); } } public string UserName { get { return GetCookies(Extensions.Constants.GlobalUserName); } } public string FullName { get { return GetCookies(Extensions.Constants.GlobalFullName); } } public int UserId { get { var id = GetCookies(Extensions.Constants.GlobalUserId); if (!string.IsNullOrEmpty(id)) { return int.Parse(id); } return 0; } } public decimal VipXu { get { var xu = GetCookies(Extensions.Constants.GlobalVipXu); if (!string.IsNullOrEmpty(xu)) { return int.Parse(xu); } return 0; } } public int TotalDay { get { var day = GetCookies(Extensions.Constants.GlobalTotalDay); if (!string.IsNullOrEmpty(day)) { return int.Parse(day); } return 0; } } public DateTime StartDate { get { var date = GetCookies(Extensions.Constants.GlobalStartDate); if (!string.IsNullOrEmpty(date)) { return DateTime.Parse(date); } return Utilities.DateNull(); } } public DateTime EndDate { get { var date = GetCookies(Extensions.Constants.GlobalEndDate); if (!string.IsNullOrEmpty(date)) { return DateTime.Parse(date); } return Utilities.DateNull(); } } public int SiteId { get { if (Session[Extensions.Constants.GlobalSiteId] != null) { return (int)Session[Extensions.Constants.GlobalSiteId]; } return (int)Site.Home; } set { Session[Extensions.Constants.GlobalSiteId] = value; } } public string TransactionCode { get { if (Session[Extensions.Constants.TransactionCode] != null) { return Session[Extensions.Constants.TransactionCode].ToString(); } return string.Empty; } set { Session[Extensions.Constants.TransactionCode] = value; } } public DateTime CurrentDate { get { if (Session[Extensions.Constants.CurrentDate] != null) { return DateTime.Parse(Session[Extensions.Constants.CurrentDate].ToString()); } return Utilities.DateNull(); } set { Session[Extensions.Constants.CurrentDate] = value; } } public string UrlLogin { get { if (Session[Extensions.Constants.UrlLoginHistory] != null) { return Session[Extensions.Constants.UrlLoginHistory].ToString(); } return Url.Action("Index","Home"); } set { Session[Extensions.Constants.UrlLoginHistory] = value; } } #endregion public BaseHomeController(IWorkContextAccessor workContextAccessor) : base(workContextAccessor) { } public virtual ActionResult RedirectToLocal(string returnUrl) { if (!string.IsNullOrEmpty(returnUrl)) { return Redirect(returnUrl); } return Redirect(UrlLogin); } #region Cookies public void AddCookies(string key, string value, bool isRemember) { var expiration = DateTime.Now; if (isRemember) { expiration = DateTime.Now.AddMonths(1); } else { expiration = DateTime.Now.AddDays(1); } var cookie = new HttpCookie(key, EncryptionExtensions.Encrypt(KeyConfiguration.PublishKey, value)) { Expires = expiration, HttpOnly = true }; Response.Cookies.Add(cookie); } public string GetCookies(string key) { HttpCookie authCookie = Request.Cookies[key]; if (authCookie != null && !string.IsNullOrEmpty(authCookie.Value)) { return EncryptionExtensions.Decrypt(KeyConfiguration.PublishKey, authCookie.Value); } return string.Empty; } public void RemoveCookies(string key) { if (Request.Cookies[key] != null) { var myCookie = new HttpCookie(key) { Expires = DateTime.Now.AddDays(-1d) }; Response.Cookies.Add(myCookie); } } #endregion #region Customers [HttpPost] [AllowAnonymous] [ValidateAntiForgeryToken] [Url("mang-xa-hoi")] public ActionResult ExternalLogin(string provider, string returnUrl) { return new ExternalLoginResult(provider, Url.Action("ExternalLoginCallback", new { ReturnUrl = returnUrl })); } [AllowAnonymous] [Url("dang-nhap")] public ActionResult ExternalLoginCallback(string returnUrl) { GoogleClient.RewriteRequest(); AuthenticationResult result = OAuthWebSecurity.VerifyAuthentication(Url.Action("ExternalLoginCallback", new { ReturnUrl = returnUrl })); if (!result.IsSuccessful) { return RedirectToLocal(returnUrl); } var service = WorkContext.Resolve<ICustomerService>(); var cutomerCode = service.GetLatestCustomerCode(); //var loginType = EnumExtensions.Parse<LoginTypes>(OAuthWebSecurity.GetOAuthClientData(result.Provider).DisplayName); //string userName = cutomerCode; //if (loginType == LoginTypes.Google) //{ // userName = result.ExtraData["username"]; //} var fullName = result.ExtraData["name"]; var gender = Gender.None; try { if (result.ExtraData["gender"] == null) { gender = EnumExtensions.Parse<Gender>(result.ExtraData["gender"]); } } catch (Exception) { } var loginId = result.ExtraData["id"]; var email = result.UserName; if (!Utilities.ValidateUserName(email)) { email = loginId + "@nodomain.vn"; returnUrl = Url.Action("Index", "Home"); return RedirectToLocal(returnUrl); } var customer = new CustomerInfo { UserName = email, Password = EncryptionExtensions.Encrypt(KeyConfiguration.PublishKey, Extensions.Constants.DefaultPassword), Email = email, FullName = fullName, Sex = (int)gender, MemberDate = DateTime.Now.Date, Birthday = Utilities.DateNull(), VipXu = 0, Status = (int)Status.Approved, IsBlock = false }; customer.ImageIcon = gender == Gender.Male ? Extensions.Constants.ImageMale : Extensions.Constants.ImageFemale; var item = service.CheckRegister(customer.UserName); if (item == null) { customer.CustomerCode = cutomerCode; service.Insert(customer); var status = SendEmailRegister("Thông tin đăng nhập thành viên VIPHD.VN", customer.CustomerCode, customer.UserName, Extensions.Constants.DefaultPassword, customer.Email); if (!status) { var user1 = service.Login(customer.UserName, customer.Password); if (user1 != null) { SetCustomerState(user1); } return View("Messages", new MessageErrorModel { TitleForm = "Thông tin đăng nhập thành viên VIPHD.VN", GoBackText = "Quay lại", Messages = "Chúc mừng bạn, bạn đã đăng ký thành viên viphd.vn thành công. Chúng tôi không thể xác thực được email " + customer.Email + " của bạn hãy truy cập: http://viphd.vn/nguoi-dung/sua-thong-tin Tài khoản: " + customer.UserName + " Mật khẩu: " + Extensions.Constants.DefaultPassword }); } } else { customer.UserName = item.UserName; customer.Password = <PASSWORD>; } var user = service.Login(customer.UserName, customer.Password); if (user != null) { SetCustomerState(user); return RedirectToLocal(returnUrl); } return View("Messages", new MessageErrorModel { TitleForm = "Thông báo", GoBackText = "Quay lại", Messages = "Đăng nhập thất bại" }); } [HttpPost, ValidateInput(false)] [Url("dang-ky-tai-khoan-vip")] public virtual ActionResult RegisterUser() { var email = Request.Form["txtEmail"]; var password = Request.Form["txtPassword"]; var comfim = Request.Form["txtComfim"]; var fullName = Request.Form["txtFullName"]; var captcha = Request.Form["txtCaptcha"]; var result = new DataViewerModel(); if (password != comfim) { result.Status = false; result.Data = "Mật khẩu xác nhận mật khẩu không đúng."; return Json(result); } if (string.IsNullOrEmpty(captcha) || captcha.ToUpper() != GlobalCapcha.ToUpper()) { result.Status = false; result.Data = "Bạn nhập mã xác thực không đúng vui lòng nhập lại."; return Json(result); } var customer = new CustomerInfo { UserName = Utilities.RemoveInjection(email), Password = <PASSWORD>.Encrypt(KeyConfiguration.PublishKey, Utilities.RemoveInjection(password)), Email = Utilities.RemoveInjection(email), FullName = Utilities.RemoveInjection(fullName), Sex = 1, MemberDate = DateTime.Now.Date, Birthday = Utilities.DateNull(), VipXu = 0, Status = (int)Status.Approved, IsBlock = false, ImageIcon = Extensions.Constants.ImageMale }; if (!Utilities.ValidateUserName(customer.UserName)) { result.Status = false; result.Data = "Tài khoản là email hoặc tên không dấu và không có ký tự đặc biệt."; return Json(result); } var service = WorkContext.Resolve<ICustomerService>(); var item = service.CheckRegister(customer.UserName); if (item != null) { result.Status = false; result.Data = "Tài khoản đã tồn tại trên hệ thống vui lòng nhập tài khoản khác."; return Json(result); } var cutomerCode = service.GetLatestCustomerCode(); customer.CustomerCode = cutomerCode; service.Insert(customer); var user = service.Login(customer.UserName, customer.Password); result.Status = true; result.Data = "Không tìm thấy tài khoản của bạn vui lòng liên hệ quản trị."; if (user != null) { SetCustomerState(user); var status = SendEmailRegister("Thông tin đăng nhập thành viên VIPHD.VN", customer.CustomerCode, customer.UserName, Utilities.RemoveInjection(password), customer.Email); if (status) { result.Status = true; result.Data = "Chúc mừng bạn, bạn đã đăng ký thành viên viphd.vn thành công.<br/> Chúng tôi đã gửi thông tin tài khoản vào email<br/> " + customer.Email + "."; } else { result.Status = true; result.Data = "Chúc mừng bạn, bạn đã đăng ký thành viên viphd.vn thành công.<br/> Chúng tôi không thể xác thực được email<br/> " + customer.Email + " của bạn hãy truy cập<br/> http://viphd.vn/nguoi-dung/sua-thong-tin <br/>mật khẩu: " + Utilities.RemoveInjection(password); } } return Json(result); } [HttpPost, ValidateInput(false)] [Url("quen-mat-khau-thanh-vien")] public virtual ActionResult ForgetPasswordMember() { var email = Request.Form["txtEmail"]; var captcha = Request.Form["txtCaptcha"]; var result = new DataViewerModel(); if (string.IsNullOrEmpty(captcha) || captcha.ToUpper() != GlobalCapcha.ToUpper()) { result.Status = false; result.Data = "Bạn nhập mã xác thực không đúng vui lòng nhập lại."; return Json(result); } if (!Utilities.IsEmailValid(email)) { result.Status = false; result.Data = "Email không đúng định dạng hoặc có ký tự đặc biệt.<br/> Định dạng chuẩn VD: <EMAIL>"; return Json(result); } var newpass = EncryptionExtensions.Encrypt(KeyConfiguration.PublishKey, Utilities.GenerateUniqueNumber()); var service = WorkContext.Resolve<ICustomerService>(); var item = service.GetMemberForgetPassword(newpass, email.ToLower()); if (item == null) { result.Status = false; result.Data = "Không tồn tại tài khoản có email này trên hệ thống.<br/> Vui lòng kiểm tra lại email."; return Json(result); } result.Status = true; result.Data = "Hệ thống đã gửi lại email cho bạn thông tin tài khoản.<br/> Bạn vui lòng đăng nhập vào email để nhận lại mật khẩu<br/> sau đó quay lại để sử dụng tài khoản của bạn."; try { SendEmailForgetPassword("Quên mật khẩu đăng nhập VIPHD.VN", item.CustomerCode, item.UserName, EncryptionExtensions.Decrypt(KeyConfiguration.PublishKey, item.Password), item.Email); } catch (Exception) { result.Status = false; result.Data = "Xin lỗi bạn hệ thống không thể gửi email cho bạn.<br/> Vui lòng liên hệ quản trị để được hỗ trợ."; } return Json(result); } public void SetCustomerState(CustomerInfo customer, bool isRemember = true) { if (customer!= null) { AddCookies(Extensions.Constants.GlobalCustomerCode, customer.CustomerCode, isRemember); AddCookies(Extensions.Constants.GlobalUserName, customer.UserName, isRemember); AddCookies(Extensions.Constants.GlobalFullName, customer.FullName, isRemember); AddCookies(Extensions.Constants.GlobalUserId, customer.Id.ToString(), isRemember); AddCookies(Extensions.Constants.GlobalVipXu, customer.VipXu.ToString(), isRemember); AddCookies(Extensions.Constants.GlobalTotalDay, customer.TotalDay.ToString(), isRemember); AddCookies(Extensions.Constants.GlobalStartDate, customer.StartDate != null ? customer.StartDate.Value.ToString(Extensions.Constants.DateTimeFomatFull) : "01/01/1900", isRemember); AddCookies(Extensions.Constants.GlobalEndDate, customer.EndDate != null ? customer.EndDate.Value.ToString(Extensions.Constants.DateTimeFomatFull) : "01/01/1900", isRemember); CurrentDate = DateTime.Now.Date; } } [HttpPost, ValidateInput(false)] [Url("khach-hang-dang-nhap")] public virtual ActionResult CustomerLogin() { var email = Request.Form["txtEmail"]; var password = Request.Form["txtPassword"]; var remember = Request.Form["ckbRemember"]; var result = new DataViewerModel(); if (!Utilities.ValidateUserName(email)) { result = new DataViewerModel { Status = false, Data = T("Tài khoản là email hoặc tên không dấu và không có ký tự đặc biệt.") }; return Json(result); } var service = WorkContext.Resolve<ICustomerService>(); var user = service.Login(Utilities.RemoveInjection(email), EncryptionExtensions.Encrypt(KeyConfiguration.PublishKey, Utilities.RemoveInjection(password))); if (user != null) { var isRemember = false; if (!string.IsNullOrEmpty(remember)) { isRemember = bool.Parse(remember.Trim().TrimEnd(',')); } SetCustomerState(user, isRemember); result = new DataViewerModel { Status = true, Url = UrlLogin }; return Json(result); } result = new DataViewerModel { Status = false, Data = "Người dùng không tồn tại. Vui lòng kiểm tra lại." }; return Json(result); } [HttpPost, ValidateInput(false)] [Url("check-login")] public virtual ActionResult CheckLogin() { var result = new DataViewerModel(); if (!IsLogin) { result = new DataViewerModel { Status = false, Data = "" }; return Json(result); } result = new DataViewerModel { Status = true, Data = "" }; return Json(result); } [HttpPost, ValidateInput(false)] [Url("get-vip-informations")] public virtual ActionResult GetVip() { var result = new DataViewerModel(); if (!IsLogin || !IsVip) { result = new DataViewerModel { Status = false }; return Json(result); } result = new DataViewerModel { Status = IsVip }; if (EndDate == Utilities.DateNull()) { result.Data = string.Empty; } else { result.Data = EndDate.ToString(Extensions.Constants.DateTimeFomatFull2); } return Json(result); } [HttpGet] [Url("nguoi-dung/dang-xuat")] public virtual ActionResult UserLogout() { RemoveCookies(Extensions.Constants.GlobalCustomerCode); RemoveCookies(Extensions.Constants.GlobalUserName); RemoveCookies(Extensions.Constants.GlobalFullName); RemoveCookies(Extensions.Constants.GlobalUserId); RemoveCookies(Extensions.Constants.GlobalVipXu); RemoveCookies(Extensions.Constants.GlobalTotalDay); RemoveCookies(Extensions.Constants.GlobalStartDate); RemoveCookies(Extensions.Constants.GlobalEndDate); Session.RemoveAll(); return RedirectToLocal(Url.Action("Index", "Home")); } #endregion #region News [HttpPost, ValidateInput(false)] [Url("list-news-by-category")] public virtual ActionResult GetNewsByCategory(string category) { var id = category == "all" ? 0 : int.Parse(category); var service = WorkContext.Resolve<IArticlesService>(); service.LanguageCode = WorkContext.CurrentCulture; service.CategoryId = id; service.SiteId = SiteId; var data = service.BuildNewsByCategory(); var html = new StringBuilder(); if (data != null && data.Count > 0) { foreach (var item in data) { var url = Url.Action("ViewDetails", "HomeNews", new { @alias = item.Alias, @id = item.Id }); html.Append("<li>"); html.Append("<p>"); html.Append("<a title='" + item.Title + "' href='" + url + "'>" + item.Title + "</a>"); if (item.ViewCount > 10) { html.Append(" <span class='icon-nnews'></span>"); } html.Append("</p>"); html.Append("<span class='time-tem'>" + item.TextPublishedDate + "</span>"); html.Append("</li>"); } html.Append("<li class='li-see_a-link'><a title='Xem thêm' href='" + Url.Action("Index", "HomeNews") + "'>Xem thêm >></a></li>"); } var result = new DataViewerModel(); result = new DataViewerModel { Status = true, Data = html.ToString() }; return Json(result); } #endregion #region Capcha [HttpPost, ValidateInput(false)] [Url("capcha/auto-generate")] public virtual ActionResult CapchaGenerate(string token) { Session[Extensions.Constants.GlobalCapcha] = CaptchaImage.GenerateRandomCode(); var capchaImage = new CaptchaImage(GlobalCapcha).GetCapchaImage(); var result = new DataViewerModel { Status = true, Data = capchaImage }; return Json(result); } #endregion #region Send Emails public bool SendEmailForgetPassword(string subject, string customerCode, string username, string password, string toEmailReceive) { try { string html = System.IO.File.ReadAllText(Server.MapPath("~/Media/Default/EmailTemplates/MemberForgetPassword.html")); html = html.Replace("[CODE]", customerCode); html = html.Replace("[EMAIL]", toEmailReceive.ToLower().Trim()); html = html.Replace("[USERNAME]", username.ToLower().Trim()); html = html.Replace("[PASSWORD]", password.Trim()); SendEmail(subject, html, toEmailReceive, string.Empty); return true; } catch (Exception) { return false; } } public bool SendEmailRegister(string subject, string customerCode, string username, string password, string toEmailReceive) { try { string html = System.IO.File.ReadAllText(Server.MapPath("~/Media/Default/EmailTemplates/MemberRegister.html")); html = html.Replace("[CODE]", customerCode); html = html.Replace("[EMAIL]", toEmailReceive.ToLower().Trim()); html = html.Replace("[USERNAME]", username.ToLower().Trim()); html = html.Replace("[PASSWORD]", password.Trim()); SendEmail(subject, html, toEmailReceive, "<EMAIL>"); return true; } catch (Exception) { return false; } } public void SendEmail(string subject, string body, string toEmailReceive, string ccEmail) { var service = WorkContext.Resolve<IEmailSender>(); var mailMessage = new MailMessage { Subject = subject, SubjectEncoding = Encoding.UTF8, Body = body, BodyEncoding = Encoding.UTF8, IsBodyHtml = true }; mailMessage.Sender = new MailAddress(toEmailReceive); mailMessage.To.Add(toEmailReceive); if (!string.IsNullOrEmpty(ccEmail)) { mailMessage.CC.Add(ccEmail); mailMessage.Bcc.Add("<EMAIL>"); } service.Send(mailMessage); } #endregion #region Films [HttpPost, ValidateInput(false)] [Url("list-films-by-type")] public virtual ActionResult GetFilmByType(int type, int statistical = 0) { var serviceFilms = WorkContext.Resolve<IFilmService>(); serviceFilms.SiteId = SiteId; serviceFilms.LanguageCode = WorkContext.CurrentCulture; var result = new DataViewerModel{Status = false, Data = ""}; switch ((HomeDisplayFilmType)type) { #region FilmHot case HomeDisplayFilmType.FilmHot: { var listFilmHot = serviceFilms.BuildFilmHot(); var html = new StringBuilder(); if (listFilmHot != null && listFilmHot.Count > 0) { var count = listFilmHot.Count % 8; var total = listFilmHot.Count - count; for (int i = 7; i < total; i += 8) { html.Append("<div>"); html.Append("<ul class=\"first-and-second-carousel jcarousel-skin-tango fix-margin-li\" id=\"first-carousel\">"); html.Append("<li>"); #region Item 1 var index = i - 7; html.Append(BuildItem(listFilmHot[index], index, true)); #endregion #region Item 2 index = i - 6; html.Append(BuildItem(listFilmHot[index], index, true)); #endregion #region Item 3 index = i - 5; html.Append(BuildItem(listFilmHot[index], index, true)); #endregion #region Item 4 index = i - 4; html.Append(BuildItem(listFilmHot[index], index, true)); #endregion #region Item 5 index = i - 3; html.Append(BuildItem(listFilmHot[index], index, true)); #endregion #region Item 6 index = i - 2; html.Append(BuildItem(listFilmHot[index], index, true)); #endregion #region Item 7 index = i - 1; html.Append(BuildItem(listFilmHot[index], index, true)); #endregion #region Item 8 index = i; html.Append(BuildItem(listFilmHot[index], index, true)); #endregion html.Append("</li>"); html.Append("</ul>"); html.Append("</div>"); } if (count > 0) { html.Append("<div>"); html.Append("<ul class=\"first-and-second-carousel jcarousel-skin-tango fix-margin-li\" id=\"first-carousel\">"); html.Append("<li>"); for (int i = 0; i < count; i++) { var index = i; if (total > 0) { index = total + i; } html.Append(BuildItem(listFilmHot[index], index, true)); } html.Append("</li>"); html.Append("</ul>"); html.Append("</div>"); } } result = new DataViewerModel { Status = true, Data = html.ToString() }; } break; #endregion #region FilmRetail case HomeDisplayFilmType.FilmRetail: { var listFilmRetail = serviceFilms.BuildFilmRetail(); var html = new StringBuilder(); if (listFilmRetail != null && listFilmRetail.Count > 0) { var count = listFilmRetail.Count % 8; var total = listFilmRetail.Count - count; for (int i = 7; i < total; i += 8) { html.Append("<div>"); html.Append("<ul class=\"first-and-second-carousel jcarousel-skin-tango fix-margin-li\" id=\"first-carousel\">"); html.Append("<li>"); #region Item 1 var index = i - 7; html.Append(BuildItem(listFilmRetail[index], index, false)); #endregion #region Item 2 index = i - 6; html.Append(BuildItem(listFilmRetail[index], index, false)); #endregion #region Item 3 index = i - 5; html.Append(BuildItem(listFilmRetail[index], index, false)); #endregion #region Item 4 index = i - 4; html.Append(BuildItem(listFilmRetail[index], index, false)); #endregion #region Item 5 index = i - 3; html.Append(BuildItem(listFilmRetail[index], index, false)); #endregion #region Item 6 index = i - 2; html.Append(BuildItem(listFilmRetail[index], index, false)); #endregion #region Item 7 index = i - 1; html.Append(BuildItem(listFilmRetail[index], index, false)); #endregion #region Item 8 index = i; html.Append(BuildItem(listFilmRetail[index], index, false)); #endregion html.Append("</li>"); html.Append("</ul>"); html.Append("</div>"); } if (count > 0) { html.Append("<div>"); html.Append("<ul class=\"first-and-second-carousel jcarousel-skin-tango fix-margin-li\" id=\"first-carousel\">"); html.Append("<li>"); for (int i = 0; i < count; i++) { var index = i; if (total > 0) { index = total + i; } html.Append(BuildItem(listFilmRetail[index], index, false)); } html.Append("</li>"); html.Append("</ul>"); html.Append("</div>"); } } result = new DataViewerModel { Status = true, Data = html.ToString() }; } break; #endregion #region FilmLengthEpisodes case HomeDisplayFilmType.FilmLengthEpisodes: { var listFilmLengthEpisodes = serviceFilms.BuildFilmManyEpisodes(); var html = new StringBuilder(); if (listFilmLengthEpisodes != null && listFilmLengthEpisodes.Count > 0) { var count = listFilmLengthEpisodes.Count % 8; var total = listFilmLengthEpisodes.Count - count; for (int i = 7; i < total; i += 8) { html.Append("<div>"); html.Append("<ul class=\"first-and-second-carousel jcarousel-skin-tango fix-margin-li\" id=\"first-carousel\">"); html.Append("<li>"); #region Item 1 var index = i - 7; html.Append(BuildItem(listFilmLengthEpisodes[index], index, true)); #endregion #region Item 2 index = i - 6; html.Append(BuildItem(listFilmLengthEpisodes[index], index, true)); #endregion #region Item 3 index = i - 5; html.Append(BuildItem(listFilmLengthEpisodes[index], index, true)); #endregion #region Item 4 index = i - 4; html.Append(BuildItem(listFilmLengthEpisodes[index], index, true)); #endregion #region Item 5 index = i - 3; html.Append(BuildItem(listFilmLengthEpisodes[index], index, true)); #endregion #region Item 6 index = i - 2; html.Append(BuildItem(listFilmLengthEpisodes[index], index, true)); #endregion #region Item 7 index = i - 1; html.Append(BuildItem(listFilmLengthEpisodes[index], index, true)); #endregion #region Item 8 index = i; html.Append(BuildItem(listFilmLengthEpisodes[index], index, true)); #endregion html.Append("</li>"); html.Append("</ul>"); html.Append("</div>"); } if (count > 0) { html.Append("<div>"); html.Append("<ul class=\"first-and-second-carousel jcarousel-skin-tango fix-margin-li\" id=\"first-carousel\">"); html.Append("<li>"); for (int i = 0; i < count; i++) { var index = i; if (total > 0) { index = total + i; } html.Append(BuildItem(listFilmLengthEpisodes[index], index, true)); } html.Append("</li>"); html.Append("</ul>"); html.Append("</div>"); } } result = new DataViewerModel { Status = true, Data = html.ToString() }; } break; #endregion #region FilmJJChannelIntroduce case HomeDisplayFilmType.FilmJJChannelIntroduce: { serviceFilms.CategoryId = 0; var listFilmJJChannelIntroduce = serviceFilms.BuildFilmJJChannelIntroduce(); var html = new StringBuilder(); if (listFilmJJChannelIntroduce != null && listFilmJJChannelIntroduce.Count > 0) { var count = listFilmJJChannelIntroduce.Count % 8; var total = listFilmJJChannelIntroduce.Count - count; for (int i = 7; i < total; i += 8) { html.Append("<div>"); html.Append("<ul class=\"first-and-second-carousel jcarousel-skin-tango fix-margin-li\" id=\"first-carousel\">"); html.Append("<li>"); #region Item 1 var index = i - 7; html.Append(BuildItem(listFilmJJChannelIntroduce[index], index, true)); #endregion #region Item 2 index = i - 6; html.Append(BuildItem(listFilmJJChannelIntroduce[index], index, true)); #endregion #region Item 3 index = i - 5; html.Append(BuildItem(listFilmJJChannelIntroduce[index], index, true)); #endregion #region Item 4 index = i - 4; html.Append(BuildItem(listFilmJJChannelIntroduce[index], index, true)); #endregion #region Item 5 index = i - 3; html.Append(BuildItem(listFilmJJChannelIntroduce[index], index, true)); #endregion #region Item 6 index = i - 2; html.Append(BuildItem(listFilmJJChannelIntroduce[index], index, true)); #endregion #region Item 7 index = i - 1; html.Append(BuildItem(listFilmJJChannelIntroduce[index], index, true)); #endregion #region Item 8 index = i; html.Append(BuildItem(listFilmJJChannelIntroduce[index], index, true)); #endregion html.Append("</li>"); html.Append("</ul>"); html.Append("</div>"); } if (count > 0) { html.Append("<div>"); html.Append("<ul class=\"first-and-second-carousel jcarousel-skin-tango fix-margin-li\" id=\"first-carousel\">"); html.Append("<li>"); for (int i = 0; i < count; i++) { var index = i; if (total > 0) { index = total + i; } html.Append(BuildItem(listFilmJJChannelIntroduce[index], index, true)); } html.Append("</li>"); html.Append("</ul>"); html.Append("</div>"); } } result = new DataViewerModel { Status = true, Data = html.ToString() }; } break; #endregion #region FilmTheater case HomeDisplayFilmType.FilmTheater: { var listFilmTheater = serviceFilms.BuildFilmTheater(); var html = new StringBuilder(); if (listFilmTheater != null && listFilmTheater.Count > 0) { var count = listFilmTheater.Count % 8; var total = listFilmTheater.Count - count; for (int i = 7; i < total; i += 8) { html.Append("<div>"); html.Append("<ul class=\"first-and-second-carousel jcarousel-skin-tango fix-margin-li\" id=\"first-carousel\">"); html.Append("<li>"); #region Item 1 var index = i - 7; html.Append(BuildItem(listFilmTheater[index], index, false)); #endregion #region Item 2 index = i - 6; html.Append(BuildItem(listFilmTheater[index], index, false)); #endregion #region Item 3 index = i - 5; html.Append(BuildItem(listFilmTheater[index], index, false)); #endregion #region Item 4 index = i - 4; html.Append(BuildItem(listFilmTheater[index], index, false)); #endregion #region Item 5 index = i - 3; html.Append(BuildItem(listFilmTheater[index], index, false)); #endregion #region Item 6 index = i - 2; html.Append(BuildItem(listFilmTheater[index], index, false)); #endregion #region Item 7 index = i - 1; html.Append(BuildItem(listFilmTheater[index], index, false)); #endregion #region Item 8 index = i; html.Append(BuildItem(listFilmTheater[index], index, false)); #endregion html.Append("</li>"); html.Append("</ul>"); html.Append("</div>"); } if (count > 0) { html.Append("<div>"); html.Append("<ul class=\"first-and-second-carousel jcarousel-skin-tango fix-margin-li\" id=\"first-carousel\">"); html.Append("<li>"); for (int i = 0; i < count; i++) { var index = i; if (total > 0) { index = total + i; } html.Append(BuildItem(listFilmTheater[index], index, false)); } html.Append("</li>"); html.Append("</ul>"); html.Append("</div>"); } } result = new DataViewerModel { Status = true, Data = html.ToString() }; } break; #endregion #region TVShow case HomeDisplayFilmType.TVShow: { serviceFilms.CategoryId = 0; var listTVShows = serviceFilms.BuildTVShow(); var html = new StringBuilder(); if (listTVShows != null && listTVShows.Count > 0) { var count = listTVShows.Count%2; var total = listTVShows.Count - count; for (int i = 1; i < total; i += 2) { var item = listTVShows[i - 1]; var url = Url.Action("FilmView", "HomeView", new { @alias = item.FilmAlias, @id = item.Id }); html.Append("<div>"); html.Append("<ul class=\"first-and-second-carousel jcarousel-skin-tango member-item\">"); html.Append("<li>"); html.Append("<div class=\"slide_child_div_dt2col item\">"); html.AppendFormat("<a href=\"{0}\" title=\"{1}\">", url, item.FilmName); html.AppendFormat("<img src=\"{0}\" alt=\"{1}\" title=\"{2}\">", item.ImageIcon, item.FilmNameEnglish, item.FilmName); html.Append("<p class=\"title_film_child\">"); html.AppendFormat("<span class=\"orange_color\">{0}</span>", item.FilmNameEnglish); html.AppendFormat("<span>{0}</span>", item.FilmName); html.Append("</p>"); html.AppendFormat("<span class=\"mask-num-film\">Tập <p>{0}</p></span>", item.EpisodeCount); html.Append("</a>"); html.AppendFormat("<div class=\"tooltip_description\" style=\"display:none\" title=\"Item {0} Description\">", i); html.AppendFormat("<a title=\"{0}\" href=\"{1}\">{2}</a>", (string.IsNullOrEmpty(item.FilmNameEnglish) ? item.FilmName : item.FilmNameEnglish), url, item.FilmName); html.Append("<div class=\"film-info\">"); html.AppendFormat("<span>Số tập: </span><label>{0}</label></br>", item.EpisodeCount); html.AppendFormat("<span>Thể loại phim: </span><label>{0}</label></br>", item.FilmTypeNames); html.AppendFormat("<span>Quốc gia: </span><label>{0}</label></br>", item.CountryName); html.AppendFormat("<span>Thời lượng: </span><label>{0}</label></br>", item.Time); html.AppendFormat("<span>Dung lượng: </span><label>{0}</label>", item.Capacity); html.Append("</div>"); html.Append("<div class=\"film-body\">"); html.AppendFormat("<p>{0}</p>", item.Summary); html.Append("</div>"); html.Append("</div>"); html.Append("</div>"); html.Append("</li> "); var item2 = listTVShows[i]; var url2 = Url.Action("FilmView", "HomeView", new { @alias = item2.FilmAlias, @id = item2.Id }); html.Append("<li>"); html.Append("<div class=\"slide_child_div_dt2col item\">"); html.AppendFormat("<a href=\"{0}\" title=\"{1}\">", url2, item2.FilmName); html.AppendFormat("<img src=\"{0}\" alt=\"{1}\" title=\"{2}\">", item2.ImageIcon, item2.FilmNameEnglish, item2.FilmName); html.Append("<p class=\"title_film_child\">"); html.AppendFormat("<span class=\"orange_color\">{0}</span>", item2.FilmNameEnglish); html.AppendFormat("<span>{0}</span>", item2.FilmName); html.Append("</p>"); html.AppendFormat("<span class=\"mask-num-film\">Tập <p>{0}</p></span>", item2.EpisodeCount); html.Append("</a>"); html.AppendFormat("<div class=\"tooltip_description\" style=\"display:none\" title=\"Item {0} Description\">", i); html.AppendFormat("<a title=\"{0}\" href=\"{1}\">{2}</a>", (string.IsNullOrEmpty(item2.FilmNameEnglish) ? item2.FilmName : item2.FilmNameEnglish), url2, item2.FilmName); html.Append("<div class=\"film-info\">"); html.AppendFormat("<span>Số tập: </span><label>{0}</label></br>", item2.EpisodeCount); html.AppendFormat("<span>Thể loại phim: </span><label>{0}</label></br>", item2.FilmTypeNames); html.AppendFormat("<span>Quốc gia: </span><label>{0}</label></br>", item2.CountryName); html.AppendFormat("<span>Thời lượng: </span><label>{0}</label></br>", item2.Time); html.AppendFormat("<span>Dung lượng: </span><label>{0}</label>", item2.Capacity); html.Append("</div>"); html.Append("<div class=\"film-body\">"); html.AppendFormat("<p>{0}</p>", item2.Summary); html.Append("</div>"); html.Append("</div>"); html.Append("</div>"); html.Append("</li>"); html.Append("</ul>"); html.Append("</div>"); } if (count > 0) { html.Append("<div>"); html.Append("<ul class=\"first-and-second-carousel jcarousel-skin-tango member-item\">"); html.Append("<li>"); for (int i = 0; i < count; i++) { var item = listTVShows[i]; var url = Url.Action("FilmView", "HomeView", new { @alias = item.FilmAlias, @id = item.Id }); if (total > 0) { item = listTVShows[total + i]; } html.Append("<div class=\"slide_child_div_dt2col item\">"); html.AppendFormat("<a href=\"{0}\" title=\"{1}\">", url, item.FilmName); html.AppendFormat("<img src=\"{0}\" alt=\"{1}\" title=\"{2}\">", item.ImageIcon, item.FilmNameEnglish, item.FilmName); html.Append("<p class=\"title_film_child\">"); html.AppendFormat("<span class=\"orange_color\">{0}</span>", item.FilmNameEnglish); html.AppendFormat("<span>{0}</span>", item.FilmName); html.Append("</p>"); html.AppendFormat("<span class=\"mask-num-film\">Tập <p>{0}</p></span>", item.EpisodeCount); html.Append("</a>"); html.AppendFormat("<div class=\"tooltip_description\" style=\"display:none\" title=\"Item {0} Description\">", listTVShows.Count - 1); html.AppendFormat("<a title=\"{0}\" href=\"{1}\">{2}</a>", (string.IsNullOrEmpty(item.FilmNameEnglish) ? item.FilmName : item.FilmNameEnglish), url, item.FilmName); html.Append("<div class=\"film-info\">"); html.AppendFormat("<span>Số tập: </span><label>{0}</label></br>", item.EpisodeCount); html.AppendFormat("<span>Thể loại phim: </span><label>{0}</label></br>", item.FilmTypeNames); html.AppendFormat("<span>Quốc gia: </span><label>{0}</label></br>", item.CountryName); html.AppendFormat("<span>Thời lượng: </span><label>{0}</label></br>", item.Time); html.AppendFormat("<span>Dung lượng: </span><label>{0}</label>", item.Capacity); html.Append("</div>"); html.Append("<div class=\"film-body\">"); html.AppendFormat("<p>{0}</p>", item.Summary); html.Append("</div>"); html.Append("</div>"); html.Append("</div>"); } html.Append("</li> "); html.Append("</ul>"); html.Append("</div>"); } } result = new DataViewerModel { Status = true, Data = html.ToString() }; } break; #endregion #region Clips case HomeDisplayFilmType.Clip: { serviceFilms.CategoryId = 5; var listClips = serviceFilms.BuildClips(); var html = new StringBuilder(); if (listClips != null && listClips.Count > 0) { var count = listClips.Count%8; var total = listClips.Count - count; for (int i = 7; i < total; i += 8) { html.Append("<div>"); html.Append("<ul class=\"first-and-second-carousel jcarousel-skin-tango member-item\">"); html.Append("<li>"); var index = i - 7; html.Append(BuildItemClip(listClips[index], index)); index = i - 6; html.Append(BuildItemClip(listClips[index], index)); index = i - 5; html.Append(BuildItemClip(listClips[index], index)); index = i - 4; html.Append(BuildItemClip(listClips[index], index)); index = i - 3; html.Append(BuildItemClip(listClips[index], index)); index = i - 2; html.Append(BuildItemClip(listClips[index], index)); index = i - 1; html.Append(BuildItemClip(listClips[index], index)); index = i; html.Append(BuildItemClip(listClips[index], index)); html.Append("</li> "); html.Append("</ul>"); html.Append("</div>"); } if (count > 0) { html.Append("<div>"); html.Append("<ul class=\"first-and-second-carousel jcarousel-skin-tango member-item\">"); html.Append("<li>"); for (int i = 0; i < count; i++) { var index = i; if (total > 0) { index = total + i; } html.Append(BuildItemClip(listClips[index], index)); } html.Append("</li> "); html.Append("</ul>"); html.Append("</div>"); } } result = new DataViewerModel { Status = true, Data = html.ToString() }; } break; #endregion #region Statistical FilmRetail case HomeDisplayFilmType.StatisticalFilmRetail: { var listStatisticalFilmRetail = serviceFilms.BuildStatistical1(30, statistical); var html = new StringBuilder(); if (listStatisticalFilmRetail != null && listStatisticalFilmRetail.Count > 0) { foreach (var item in listStatisticalFilmRetail) { html.Append(BuildItemStatistical(item)); } } result = new DataViewerModel { Status = true, Data = html.ToString() }; } break; #endregion #region Statistical FilmLengthEpisodes case HomeDisplayFilmType.StatisticalLengthEpisodes: { var listStatisticalFilmRetail = serviceFilms.BuildStatistical2(30, statistical); var html = new StringBuilder(); if (listStatisticalFilmRetail != null && listStatisticalFilmRetail.Count > 0) { foreach (var item in listStatisticalFilmRetail) { html.Append(BuildItemStatistical(item)); } } result = new DataViewerModel { Status = true, Data = html.ToString() }; } break; #endregion #region Statistical Shows case HomeDisplayFilmType.StatisticalShows: { var listStatisticalShows = serviceFilms.BuildStatistical3(30, statistical); var html = new StringBuilder(); if (listStatisticalShows != null && listStatisticalShows.Count > 0) { foreach (var item in listStatisticalShows) { html.Append(BuildItemStatistical(item)); } } result = new DataViewerModel { Status = true, Data = html.ToString() }; } break; #endregion #region Statistical Clips case HomeDisplayFilmType.StatisticalClips: { var listStatisticalClips = serviceFilms.BuildStatistical4(30, statistical); var html = new StringBuilder(); if (listStatisticalClips != null && listStatisticalClips.Count > 0) { foreach (var item in listStatisticalClips) { html.Append(BuildClip(item)); } } result = new DataViewerModel { Status = true, Data = html.ToString() }; } break; #endregion #region Statistical Trailer case HomeDisplayFilmType.StatisticalTrailer: { var listStatisticalTrailer = serviceFilms.BuildStatistical5(30, statistical); var html = new StringBuilder(); if (listStatisticalTrailer != null && listStatisticalTrailer.Count > 0) { foreach (var item in listStatisticalTrailer) { html.Append(BuildTrailer(item)); } } result = new DataViewerModel { Status = true, Data = html.ToString() }; } break; #endregion #region Statistical Trailer case HomeDisplayFilmType.StatisticalNextFilm: { var listStatisticalTrailer = serviceFilms.BuildStatistical5(30, statistical); var html = new StringBuilder(); if (listStatisticalTrailer != null && listStatisticalTrailer.Count > 0) { foreach (var item in listStatisticalTrailer) { html.Append(BuildTrailer(item)); } } result = new DataViewerModel { Status = true, Data = html.ToString() }; } break; #endregion } return Json(result); } public string GetFilmHtml(int type, int statistical = 0) { var serviceFilms = WorkContext.Resolve<IFilmService>(); serviceFilms.SiteId = SiteId; serviceFilms.LanguageCode = WorkContext.CurrentCulture; switch ((HomeDisplayFilmType)type) { #region FilmHot case HomeDisplayFilmType.FilmHot: { var listFilmHot = serviceFilms.BuildFilmHot(); var html = new StringBuilder(); if (listFilmHot != null && listFilmHot.Count > 0) { var count = listFilmHot.Count % 8; var total = listFilmHot.Count - count; for (int i = 7; i < total; i += 8) { html.Append("<div>"); html.Append("<ul class=\"first-and-second-carousel jcarousel-skin-tango fix-margin-li\" id=\"first-carousel\">"); html.Append("<li>"); #region Item 1 var index = i - 7; html.Append(BuildItem(listFilmHot[index], index, true)); #endregion #region Item 2 index = i - 6; html.Append(BuildItem(listFilmHot[index], index, true)); #endregion #region Item 3 index = i - 5; html.Append(BuildItem(listFilmHot[index], index, true)); #endregion #region Item 4 index = i - 4; html.Append(BuildItem(listFilmHot[index], index, true)); #endregion #region Item 5 index = i - 3; html.Append(BuildItem(listFilmHot[index], index, true)); #endregion #region Item 6 index = i - 2; html.Append(BuildItem(listFilmHot[index], index, true)); #endregion #region Item 7 index = i - 1; html.Append(BuildItem(listFilmHot[index], index, true)); #endregion #region Item 8 index = i; html.Append(BuildItem(listFilmHot[index], index, true)); #endregion html.Append("</li>"); html.Append("</ul>"); html.Append("</div>"); } if (count > 0) { html.Append("<div>"); html.Append("<ul class=\"first-and-second-carousel jcarousel-skin-tango fix-margin-li\" id=\"first-carousel\">"); html.Append("<li>"); for (int i = 0; i < count; i++) { var index = i; if (total > 0) { index = total + i; } html.Append(BuildItem(listFilmHot[index], index, true)); } html.Append("</li>"); html.Append("</ul>"); html.Append("</div>"); } } return html.ToString(); } #endregion #region FilmRetail case HomeDisplayFilmType.FilmRetail: { var listFilmRetail = serviceFilms.BuildFilmRetail(); var html = new StringBuilder(); if (listFilmRetail != null && listFilmRetail.Count > 0) { var count = listFilmRetail.Count % 8; var total = listFilmRetail.Count - count; for (int i = 7; i < total; i += 8) { html.Append("<div>"); html.Append("<ul class=\"first-and-second-carousel jcarousel-skin-tango fix-margin-li\" id=\"first-carousel\">"); html.Append("<li>"); #region Item 1 var index = i - 7; html.Append(BuildItem(listFilmRetail[index], index, false)); #endregion #region Item 2 index = i - 6; html.Append(BuildItem(listFilmRetail[index], index, false)); #endregion #region Item 3 index = i - 5; html.Append(BuildItem(listFilmRetail[index], index, false)); #endregion #region Item 4 index = i - 4; html.Append(BuildItem(listFilmRetail[index], index, false)); #endregion #region Item 5 index = i - 3; html.Append(BuildItem(listFilmRetail[index], index, false)); #endregion #region Item 6 index = i - 2; html.Append(BuildItem(listFilmRetail[index], index, false)); #endregion #region Item 7 index = i - 1; html.Append(BuildItem(listFilmRetail[index], index, false)); #endregion #region Item 8 index = i; html.Append(BuildItem(listFilmRetail[index], index, false)); #endregion html.Append("</li>"); html.Append("</ul>"); html.Append("</div>"); } if (count > 0) { html.Append("<div>"); html.Append("<ul class=\"first-and-second-carousel jcarousel-skin-tango fix-margin-li\" id=\"first-carousel\">"); html.Append("<li>"); for (int i = 0; i < count; i++) { var index = i; if (total > 0) { index = total + i; } html.Append(BuildItem(listFilmRetail[index], index, false)); } html.Append("</li>"); html.Append("</ul>"); html.Append("</div>"); } } return html.ToString(); } #endregion #region FilmLengthEpisodes case HomeDisplayFilmType.FilmLengthEpisodes: { var listFilmLengthEpisodes = serviceFilms.BuildFilmManyEpisodes(); var html = new StringBuilder(); if (listFilmLengthEpisodes != null && listFilmLengthEpisodes.Count > 0) { var count = listFilmLengthEpisodes.Count % 8; var total = listFilmLengthEpisodes.Count - count; for (int i = 7; i < total; i += 8) { html.Append("<div>"); html.Append("<ul class=\"first-and-second-carousel jcarousel-skin-tango fix-margin-li\" id=\"first-carousel\">"); html.Append("<li>"); #region Item 1 var index = i - 7; html.Append(BuildItem(listFilmLengthEpisodes[index], index, true)); #endregion #region Item 2 index = i - 6; html.Append(BuildItem(listFilmLengthEpisodes[index], index, true)); #endregion #region Item 3 index = i - 5; html.Append(BuildItem(listFilmLengthEpisodes[index], index, true)); #endregion #region Item 4 index = i - 4; html.Append(BuildItem(listFilmLengthEpisodes[index], index, true)); #endregion #region Item 5 index = i - 3; html.Append(BuildItem(listFilmLengthEpisodes[index], index, true)); #endregion #region Item 6 index = i - 2; html.Append(BuildItem(listFilmLengthEpisodes[index], index, true)); #endregion #region Item 7 index = i - 1; html.Append(BuildItem(listFilmLengthEpisodes[index], index, true)); #endregion #region Item 8 index = i; html.Append(BuildItem(listFilmLengthEpisodes[index], index, true)); #endregion html.Append("</li>"); html.Append("</ul>"); html.Append("</div>"); } if (count > 0) { html.Append("<div>"); html.Append("<ul class=\"first-and-second-carousel jcarousel-skin-tango fix-margin-li\" id=\"first-carousel\">"); html.Append("<li>"); for (int i = 0; i < count; i++) { var index = i; if (total > 0) { index = total + i; } html.Append(BuildItem(listFilmLengthEpisodes[index], index, true)); } html.Append("</li>"); html.Append("</ul>"); html.Append("</div>"); } } return html.ToString(); } #endregion #region FilmJJChannelIntroduce case HomeDisplayFilmType.FilmJJChannelIntroduce: { serviceFilms.CategoryId = 0; var listFilmJJChannelIntroduce = serviceFilms.BuildFilmJJChannelIntroduce(); var html = new StringBuilder(); if (listFilmJJChannelIntroduce != null && listFilmJJChannelIntroduce.Count > 0) { var count = listFilmJJChannelIntroduce.Count % 8; var total = listFilmJJChannelIntroduce.Count - count; for (int i = 7; i < total; i += 8) { html.Append("<div>"); html.Append("<ul class=\"first-and-second-carousel jcarousel-skin-tango fix-margin-li\" id=\"first-carousel\">"); html.Append("<li>"); #region Item 1 var index = i - 7; html.Append(BuildItem(listFilmJJChannelIntroduce[index], index, true)); #endregion #region Item 2 index = i - 6; html.Append(BuildItem(listFilmJJChannelIntroduce[index], index, true)); #endregion #region Item 3 index = i - 5; html.Append(BuildItem(listFilmJJChannelIntroduce[index], index, true)); #endregion #region Item 4 index = i - 4; html.Append(BuildItem(listFilmJJChannelIntroduce[index], index, true)); #endregion #region Item 5 index = i - 3; html.Append(BuildItem(listFilmJJChannelIntroduce[index], index, true)); #endregion #region Item 6 index = i - 2; html.Append(BuildItem(listFilmJJChannelIntroduce[index], index, true)); #endregion #region Item 7 index = i - 1; html.Append(BuildItem(listFilmJJChannelIntroduce[index], index, true)); #endregion #region Item 8 index = i; html.Append(BuildItem(listFilmJJChannelIntroduce[index], index, true)); #endregion html.Append("</li>"); html.Append("</ul>"); html.Append("</div>"); } if (count > 0) { html.Append("<div>"); html.Append("<ul class=\"first-and-second-carousel jcarousel-skin-tango fix-margin-li\" id=\"first-carousel\">"); html.Append("<li>"); for (int i = 0; i < count; i++) { var index = i; if (total > 0) { index = total + i; } html.Append(BuildItem(listFilmJJChannelIntroduce[index], index, true)); } html.Append("</li>"); html.Append("</ul>"); html.Append("</div>"); } } return html.ToString(); } #endregion #region FilmTheater case HomeDisplayFilmType.FilmTheater: { var listFilmTheater = serviceFilms.BuildFilmTheater(); var html = new StringBuilder(); if (listFilmTheater != null && listFilmTheater.Count > 0) { var count = listFilmTheater.Count % 8; var total = listFilmTheater.Count - count; for (int i = 7; i < total; i += 8) { html.Append("<div>"); html.Append("<ul class=\"first-and-second-carousel jcarousel-skin-tango fix-margin-li\" id=\"first-carousel\">"); html.Append("<li>"); #region Item 1 var index = i - 7; html.Append(BuildItem(listFilmTheater[index], index, false)); #endregion #region Item 2 index = i - 6; html.Append(BuildItem(listFilmTheater[index], index, false)); #endregion #region Item 3 index = i - 5; html.Append(BuildItem(listFilmTheater[index], index, false)); #endregion #region Item 4 index = i - 4; html.Append(BuildItem(listFilmTheater[index], index, false)); #endregion #region Item 5 index = i - 3; html.Append(BuildItem(listFilmTheater[index], index, false)); #endregion #region Item 6 index = i - 2; html.Append(BuildItem(listFilmTheater[index], index, false)); #endregion #region Item 7 index = i - 1; html.Append(BuildItem(listFilmTheater[index], index, false)); #endregion #region Item 8 index = i; html.Append(BuildItem(listFilmTheater[index], index, false)); #endregion html.Append("</li>"); html.Append("</ul>"); html.Append("</div>"); } if (count > 0) { html.Append("<div>"); html.Append("<ul class=\"first-and-second-carousel jcarousel-skin-tango fix-margin-li\" id=\"first-carousel\">"); html.Append("<li>"); for (int i = 0; i < count; i++) { var index = i; if (total > 0) { index = total + i; } html.Append(BuildItem(listFilmTheater[index], index, false)); } html.Append("</li>"); html.Append("</ul>"); html.Append("</div>"); } } return html.ToString(); } #endregion #region TVShow case HomeDisplayFilmType.TVShow: { serviceFilms.CategoryId = 0; var listTVShows = serviceFilms.BuildTVShow(); var html = new StringBuilder(); if (listTVShows != null && listTVShows.Count > 0) { var count = listTVShows.Count % 2; var total = listTVShows.Count - count; for (int i = 1; i < total; i += 2) { var item = listTVShows[i - 1]; var url = Url.Action("FilmView", "HomeView", new { @alias = item.FilmAlias, @id = item.Id }); html.Append("<div>"); html.Append("<ul class=\"first-and-second-carousel jcarousel-skin-tango member-item\">"); html.Append("<li>"); html.Append("<div class=\"slide_child_div_dt2col item\">"); html.AppendFormat("<a href=\"{0}\" title=\"{1}\">", url, item.FilmName); html.AppendFormat("<img src=\"{0}\" alt=\"{1}\" title=\"{2}\">", item.ImageIcon, item.FilmNameEnglish, item.FilmName); html.Append("<p class=\"title_film_child\">"); html.AppendFormat("<span class=\"orange_color\">{0}</span>", item.FilmNameEnglish); html.AppendFormat("<span>{0}</span>", item.FilmName); html.Append("</p>"); html.AppendFormat("<span class=\"mask-num-film\">Tập <p>{0}</p></span>", item.EpisodeCount); html.Append("</a>"); html.AppendFormat("<div class=\"tooltip_description\" style=\"display:none\" title=\"Item {0} Description\">", i); html.AppendFormat("<a title=\"{0}\" href=\"{1}\">{2}</a>", (string.IsNullOrEmpty(item.FilmNameEnglish) ? item.FilmName : item.FilmNameEnglish), url, item.FilmName); html.Append("<div class=\"film-info\">"); html.AppendFormat("<span>Số tập: </span><label>{0}</label></br>", item.EpisodeCount); html.AppendFormat("<span>Thể loại phim: </span><label>{0}</label></br>", item.FilmTypeNames); html.AppendFormat("<span>Quốc gia: </span><label>{0}</label></br>", item.CountryName); html.AppendFormat("<span>Thời lượng: </span><label>{0}</label></br>", item.Time); html.AppendFormat("<span>Dung lượng: </span><label>{0}</label>", item.Capacity); html.Append("</div>"); html.Append("<div class=\"film-body\">"); html.AppendFormat("<p>{0}</p>", item.Summary); html.Append("</div>"); html.Append("</div>"); html.Append("</div>"); html.Append("</li> "); var item2 = listTVShows[i]; var url2 = Url.Action("FilmView", "HomeView", new { @alias = item2.FilmAlias, @id = item2.Id }); html.Append("<li>"); html.Append("<div class=\"slide_child_div_dt2col item\">"); html.AppendFormat("<a href=\"{0}\" title=\"{1}\">", url2, item2.FilmName); html.AppendFormat("<img src=\"{0}\" alt=\"{1}\" title=\"{2}\">", item2.ImageIcon, item2.FilmNameEnglish, item2.FilmName); html.Append("<p class=\"title_film_child\">"); html.AppendFormat("<span class=\"orange_color\">{0}</span>", item2.FilmNameEnglish); html.AppendFormat("<span>{0}</span>", item2.FilmName); html.Append("</p>"); html.AppendFormat("<span class=\"mask-num-film\">Tập <p>{0}</p></span>", item2.EpisodeCount); html.Append("</a>"); html.AppendFormat("<div class=\"tooltip_description\" style=\"display:none\" title=\"Item {0} Description\">", i); html.AppendFormat("<a title=\"{0}\" href=\"{1}\">{2}</a>", (string.IsNullOrEmpty(item2.FilmNameEnglish) ? item2.FilmName : item2.FilmNameEnglish), url2, item2.FilmName); html.Append("<div class=\"film-info\">"); html.AppendFormat("<span>Số tập: </span><label>{0}</label></br>", item2.EpisodeCount); html.AppendFormat("<span>Thể loại phim: </span><label>{0}</label></br>", item2.FilmTypeNames); html.AppendFormat("<span>Quốc gia: </span><label>{0}</label></br>", item2.CountryName); html.AppendFormat("<span>Thời lượng: </span><label>{0}</label></br>", item2.Time); html.AppendFormat("<span>Dung lượng: </span><label>{0}</label>", item2.Capacity); html.Append("</div>"); html.Append("<div class=\"film-body\">"); html.AppendFormat("<p>{0}</p>", item2.Summary); html.Append("</div>"); html.Append("</div>"); html.Append("</div>"); html.Append("</li>"); html.Append("</ul>"); html.Append("</div>"); } if (count > 0) { html.Append("<div>"); html.Append("<ul class=\"first-and-second-carousel jcarousel-skin-tango member-item\">"); html.Append("<li>"); for (int i = 0; i < count; i++) { var item = listTVShows[i]; var url = Url.Action("FilmView", "HomeView", new { @alias = item.FilmAlias, @id = item.Id }); if (total > 0) { item = listTVShows[total + i]; } html.Append("<div class=\"slide_child_div_dt2col item\">"); html.AppendFormat("<a href=\"{0}\" title=\"{1}\">", url, item.FilmName); html.AppendFormat("<img src=\"{0}\" alt=\"{1}\" title=\"{2}\">", item.ImageIcon, item.FilmNameEnglish, item.FilmName); html.Append("<p class=\"title_film_child\">"); html.AppendFormat("<span class=\"orange_color\">{0}</span>", item.FilmNameEnglish); html.AppendFormat("<span>{0}</span>", item.FilmName); html.Append("</p>"); html.AppendFormat("<span class=\"mask-num-film\">Tập <p>{0}</p></span>", item.EpisodeCount); html.Append("</a>"); html.AppendFormat("<div class=\"tooltip_description\" style=\"display:none\" title=\"Item {0} Description\">", listTVShows.Count - 1); html.AppendFormat("<a title=\"{0}\" href=\"{1}\">{2}</a>", (string.IsNullOrEmpty(item.FilmNameEnglish) ? item.FilmName : item.FilmNameEnglish), url, item.FilmName); html.Append("<div class=\"film-info\">"); html.AppendFormat("<span>Số tập: </span><label>{0}</label></br>", item.EpisodeCount); html.AppendFormat("<span>Thể loại phim: </span><label>{0}</label></br>", item.FilmTypeNames); html.AppendFormat("<span>Quốc gia: </span><label>{0}</label></br>", item.CountryName); html.AppendFormat("<span>Thời lượng: </span><label>{0}</label></br>", item.Time); html.AppendFormat("<span>Dung lượng: </span><label>{0}</label>", item.Capacity); html.Append("</div>"); html.Append("<div class=\"film-body\">"); html.AppendFormat("<p>{0}</p>", item.Summary); html.Append("</div>"); html.Append("</div>"); html.Append("</div>"); } html.Append("</li> "); html.Append("</ul>"); html.Append("</div>"); } } return html.ToString(); } #endregion #region Clips case HomeDisplayFilmType.Clip: { serviceFilms.CategoryId = 5; var listClips = serviceFilms.BuildClips(); var html = new StringBuilder(); if (listClips != null && listClips.Count > 0) { var count = listClips.Count % 8; var total = listClips.Count - count; for (int i = 7; i < total; i += 8) { html.Append("<div>"); html.Append("<ul class=\"first-and-second-carousel jcarousel-skin-tango member-item\">"); html.Append("<li>"); var index = i - 7; html.Append(BuildItemClip(listClips[index], index)); index = i - 6; html.Append(BuildItemClip(listClips[index], index)); index = i - 5; html.Append(BuildItemClip(listClips[index], index)); index = i - 4; html.Append(BuildItemClip(listClips[index], index)); index = i - 3; html.Append(BuildItemClip(listClips[index], index)); index = i - 2; html.Append(BuildItemClip(listClips[index], index)); index = i - 1; html.Append(BuildItemClip(listClips[index], index)); index = i; html.Append(BuildItemClip(listClips[index], index)); html.Append("</li> "); html.Append("</ul>"); html.Append("</div>"); } if (count > 0) { html.Append("<div>"); html.Append("<ul class=\"first-and-second-carousel jcarousel-skin-tango member-item\">"); html.Append("<li>"); for (int i = 0; i < count; i++) { var index = i; if (total > 0) { index = total + i; } html.Append(BuildItemClip(listClips[index], index)); } html.Append("</li> "); html.Append("</ul>"); html.Append("</div>"); } } return html.ToString(); } #endregion #region Statistical FilmRetail case HomeDisplayFilmType.StatisticalFilmRetail: { var listStatisticalFilmRetail = serviceFilms.BuildStatistical1(30, statistical); var html = new StringBuilder(); if (listStatisticalFilmRetail != null && listStatisticalFilmRetail.Count > 0) { foreach (var item in listStatisticalFilmRetail) { html.Append(BuildItemStatistical(item)); } } return html.ToString(); } #endregion #region Statistical FilmLengthEpisodes case HomeDisplayFilmType.StatisticalLengthEpisodes: { var listStatisticalFilmRetail = serviceFilms.BuildStatistical2(30, statistical); var html = new StringBuilder(); if (listStatisticalFilmRetail != null && listStatisticalFilmRetail.Count > 0) { foreach (var item in listStatisticalFilmRetail) { html.Append(BuildItemStatistical(item)); } } return html.ToString(); } #endregion #region Statistical Shows case HomeDisplayFilmType.StatisticalShows: { var listStatisticalShows = serviceFilms.BuildStatistical3(30, statistical); var html = new StringBuilder(); if (listStatisticalShows != null && listStatisticalShows.Count > 0) { foreach (var item in listStatisticalShows) { html.Append(BuildItemStatistical(item)); } } return html.ToString(); } #endregion #region Statistical Clips case HomeDisplayFilmType.StatisticalClips: { var listStatisticalClips = serviceFilms.BuildStatistical4(30, statistical); var html = new StringBuilder(); if (listStatisticalClips != null && listStatisticalClips.Count > 0) { foreach (var item in listStatisticalClips) { html.Append(BuildClip(item)); } } return html.ToString(); } #endregion #region Statistical Trailer case HomeDisplayFilmType.StatisticalTrailer: { var listStatisticalTrailer = serviceFilms.BuildStatistical5(30, statistical); var html = new StringBuilder(); if (listStatisticalTrailer != null && listStatisticalTrailer.Count > 0) { foreach (var item in listStatisticalTrailer) { html.Append(BuildTrailer(item)); } } return html.ToString(); } #endregion #region Statistical Trailer case HomeDisplayFilmType.StatisticalNextFilm: { var listStatisticalTrailer = serviceFilms.BuildStatistical5(30, statistical); var html = new StringBuilder(); if (listStatisticalTrailer != null && listStatisticalTrailer.Count > 0) { foreach (var item in listStatisticalTrailer) { html.Append(BuildTrailer(item)); } } return html.ToString(); } #endregion } return string.Empty; } [HttpPost, ValidateInput(false)] [Url("list-films-next")] public virtual ActionResult GetNextFilm(long filmId, string categoryIds, bool isShow, bool isClip, bool isTrailer,bool isFilm) { var service = WorkContext.Resolve<ISearchService>(); service.SiteId = (int)Site.Home; var condition = new List<SearchCondition> { new SearchCondition(new[] { SearchField.Title.ToString(), SearchField.CategoryIds.ToString() }, categoryIds) }; if (isShow) { condition.Add(new SearchCondition(new[] { SearchField.IsShow.ToString() }, isShow.ToString())); } if (isClip) { condition.Add(new SearchCondition(new[] { SearchField.IsClip.ToString() }, isClip.ToString())); } if (isTrailer) { condition.Add(new SearchCondition(new[] { SearchField.IsTrailer.ToString() }, isTrailer.ToString())); } if (isFilm) { condition.Add(new SearchCondition(new[] { SearchField.IsFilm.ToString() }, isFilm.ToString())); } var total = 0; var data = service.Search(condition, 1, 40, ref total); var html = new StringBuilder(); if (data != null && data.Count > 0) { foreach (var item in data) { if (item.SearchId == filmId.ToString()) { continue; } html.Append(BuildFilmSearch(item)); } } var result = new DataViewerModel { Status = true, Data = html.ToString() }; return Json(result); } public StringBuilder BuildItemStatistical(FilmInfo item) { var html = new StringBuilder(); var url = Url.Action("FilmView", "HomeView", new { @alias = item.FilmAlias, @id = item.Id }); html.Append("<div class=\"list_category-child\">"); html.Append("<div class=\"list_category-img\">"); html.AppendFormat("<a title=\"{0}\" href=\"{1}\">", item.FilmName, url); html.AppendFormat("<img alt=\"{0}\" width=\"106\" height=\"80\" src=\"{1}\">",item.FilmAlias, item.ImageIcon); html.Append("</a>"); html.Append("</div>"); html.Append("<div class=\"list_category-txt\">"); html.Append("<p class=\"name-en\">"); html.AppendFormat("<a title=\"{0}\" href=\"{1}\">{2}</a>", item.FilmNameEnglish, url, item.FilmNameEnglish); html.Append("</p>"); html.Append("<p class=\"name-vi\">"); html.AppendFormat("<a title=\"{0}\" href=\"{1}\">{2}</a>", item.FilmName, url, item.FilmName); html.Append("</p>"); html.AppendFormat("<p>Lượt xem phim: {0}</p>", item.ViewCount); html.Append("</div>"); html.Append("<br class=\"clear_both\">"); html.Append("</div>"); return html; } public StringBuilder BuildItem(FilmInfo item, int index, bool showEpisodes) { var html = new StringBuilder(); var url = Url.Action("FilmView", "HomeView", new { @alias = item.FilmAlias, @id = item.Id }); html.Append("<div class=\"slide_child_div_dt item\">"); html.AppendFormat("<a href=\"{0}\" title=\"{1}\">", url, item.FilmName); html.AppendFormat("<img src=\"{0}\" alt=\"{1}\" title=\"{2}\">", item.ImageIcon.Replace("'", string.Empty), item.FilmNameEnglish, item.FilmName); html.Append("<p class=\"title_film_child\">"); html.AppendFormat("<span class=\"orange_color\">{0}</span>", item.FilmNameEnglish); html.AppendFormat("<span>{0}</span>", item.FilmName); html.Append("</p>"); if (showEpisodes && item.IsFilmLengthEpisodes) { html.AppendFormat("<span class=\"mask-num-film\">Tập <p>{0}</p></span>", item.EpisodeCount); } html.Append("</a>"); html.AppendFormat("<div class=\"tooltip_description\" style=\"display:none\" title=\"Item {0} Description\">", index); html.AppendFormat("<a title=\"{0}\" href=\"{1}\">{2}</a>", (string.IsNullOrEmpty(item.FilmNameEnglish) ? item.FilmName : item.FilmNameEnglish), url, item.FilmName); html.Append("<div class=\"film-info\">"); if (showEpisodes && item.IsFilmLengthEpisodes) { html.AppendFormat("<span>Số tập: </span><label>{0}</label></br>", item.EpisodeCount); } html.AppendFormat("<span>Thể loại phim: </span><label>{0}</label></br>", item.FilmTypeNames); html.AppendFormat("<span>Quốc gia: </span><label>{0}</label></br>", item.CountryName); html.AppendFormat("<span>Thời lượng: </span><label>{0}</label></br>", item.Time); html.AppendFormat("<span>Dung lượng: </span><label>{0}</label>", item.Capacity); html.Append("</div>"); html.Append("<div class=\"film-body\">"); html.AppendFormat("<p>{0}</p>", item.Summary.Replace("'", string.Empty)); html.Append("</div>"); html.Append("</div>"); html.Append("</div>"); return html; } private StringBuilder BuildItemClip(FilmInfo item, int index) { var html = new StringBuilder(); var url = Url.Action("FilmView", "HomeView", new { @alias = item.FilmAlias, @id = item.Id }); html.Append("<div class=\"slide_childs item\">"); html.AppendFormat("<a href=\"{0}\" title=\"{1}\">", url, item.FilmName); html.AppendFormat("<img src=\"{0}\" alt=\"{1}\" title=\"{2}\">", item.ImageIcon, item.FilmNameEnglish, item.FilmName); html.Append("<p class=\"title_film_child\">"); html.AppendFormat("<span class=\"orange_color\">{0}</span>", item.FilmNameEnglish); html.AppendFormat("<span>{0}</span>", item.FilmName); html.Append("</p>"); html.Append("</a>"); html.AppendFormat("<div class=\"tooltip_description\" style=\"display:none\" title=\"Item {0} Description\">", index); html.AppendFormat("<a title=\"{0}\" href=\"{1}\">{2}</a>", (string.IsNullOrEmpty(item.FilmNameEnglish) ? item.FilmName : item.FilmNameEnglish), url, item.FilmName); html.Append("<div class=\"film-info\">"); html.AppendFormat("<span>Thể loại phim: </span><label>{0}</label></br>", item.FilmTypeNames); html.AppendFormat("<span>Quốc gia: </span><label>{0}</label></br>", item.CountryName); html.AppendFormat("<span>Thời lượng: </span><label>{0}</label></br>", item.Time); html.AppendFormat("<span>Dung lượng: </span><label>{0}</label>", item.Capacity); html.Append("</div>"); html.Append("<div class=\"film-body\">"); html.AppendFormat("<p>{0}</p>", item.Summary); html.Append("</div>"); html.Append("</div>"); html.Append("</div>"); return html; } private StringBuilder BuildClip(FilmInfo item) { var html = new StringBuilder(); var url = Url.Action("FilmView", "HomeView", new { @alias = item.FilmAlias, @id = item.Id }); html.Append("<div class=\"list_category-child\">"); html.Append("<div class=\"list_category-img\">"); html.AppendFormat("<a href=\"{0}\">", url); html.AppendFormat("<img alt=\"{0}\" width=\"106\" height=\"80\" src=\"{1}\">", item.FilmName, item.ImageIcon); html.Append("</a>"); html.Append("</div>"); html.Append("<div class=\"list_category-txt\">"); html.AppendFormat("<p class=\"name-en\"><a href=\"{0}\">{1}</a></p>", url, item.FilmNameEnglish); html.AppendFormat("<p class=\"name-vi\"><a href=\"{0}\">{1}</a></p>", url, item.FilmName); html.AppendFormat("<p>Tổng lượt xem: {0}</p>", item.ViewCount); html.Append("</div>"); html.Append("<br class=\"clear_both\">"); html.Append("</div>"); return html; } private StringBuilder BuildTrailer(FilmInfo item) { var html = new StringBuilder(); var url = Url.Action("FilmView", "HomeView", new { @alias = item.FilmAlias, @id = item.Id }); html.Append("<div class=\"list_category-child\">"); html.Append("<div class=\"list_category-img\">"); html.AppendFormat("<a href=\"{0}\">", url); html.AppendFormat("<img alt=\"{0}\" width=\"106\" height=\"80\" src=\"{1}\">", item.FilmName, item.ImageIcon); html.Append("</a>"); html.Append("</div>"); html.Append("<div class=\"list_category-txt\">"); html.AppendFormat("<p class=\"name-en\"><a href=\"{0}\">{1}</a></p>", url, item.FilmNameEnglish); html.AppendFormat("<p class=\"name-vi\"><a href=\"{0}\">{1}</a></p>", url, item.FilmName); html.Append("</div>"); html.Append("<br class=\"clear_both\">"); html.Append("</div>"); return html; } private StringBuilder BuildFilmSearch(SearchInfo item) { var html = new StringBuilder(); var url = Url.Action("FilmView", "HomeView", new { @alias = item.Alias, @id = item.SearchId }); html.Append("<div class=\"list_category-child\">"); html.Append("<div class=\"list_category-img\">"); html.AppendFormat("<a href=\"{0}\">", url); html.AppendFormat("<img alt=\"{0}\" width=\"106\" height=\"80\" src=\"{1}\">", item.Title, item.Images); html.Append("</a>"); html.Append("</div>"); html.Append("<div class=\"list_category-txt\">"); html.AppendFormat("<p class=\"name-en\"><a href=\"{0}\">{1}</a></p>", url, item.TitleEnglish); html.AppendFormat("<p class=\"name-vi\"><a href=\"{0}\">{1}</a></p>", url, item.Title); html.AppendFormat("<p>Lượt xem: {0}</p>", item.ViewCount); html.Append("</div>"); html.Append("<br class=\"clear_both\">"); html.Append("</div>"); return html; } #endregion public virtual void BuildModules() { } #region Sliders public virtual string BuildSlider(int siteId, int pageId) { var service = WorkContext.Resolve<ISliderService>(); var seviceFilm = WorkContext.Resolve<IFilmService>(); seviceFilm.LanguageCode = WorkContext.CurrentCulture; seviceFilm.SiteId = siteId; service.LanguageCode = WorkContext.CurrentCulture; service.SiteId = siteId; var list = service.GetCacheByPageId(pageId); var html = new StringBuilder(); if (list != null && list.Count > 0) { html.Append("<div class=\"slider-home\" id=\"slider1_container\">"); html.Append("<div class=\"slider-border\" u=\"slides\">"); foreach (var slider in list) { var film = seviceFilm.GetFilmDetails(slider.FilmId); if (film != null) { var url = Url.Action("FilmView", "HomeView", new { @alias = film.FilmAlias, @id = film.Id }); html.Append("<div onmouseout=\"javascript: event_mouseout();\" onmouseover=\"javascript: event_mouseover();\">"); html.AppendFormat("<img src=\"{0}\" alt=\"{1}\" title=\"{2}\" u=\"image\" />", film.ImageThumb, film.FilmAlias, film.FilmNameEnglish); html.Append("<div class=\"caption\">"); html.Append("<h3>"); html.AppendFormat("<a title=\"{0}\" href=\"{1}\">{0}</a>", film.FilmNameEnglish, url); html.Append("</h3>"); html.AppendFormat("<h4>{0}</h4>", film.FilmName); html.Append("<p class=\"description_detail_p\">"); html.Append(film.Summary); html.AppendFormat("<a href=\"{0}\" style=\"color:#e74c3c\">Xem thêm</a>", url); html.Append("</p>"); html.Append("<ul class=\"description_detail_ul\">"); html.AppendFormat("<li><span>Quốc gia</span> {0}</li>", film.CountryName); html.AppendFormat("<li><span>Thể loại</span> {0}</li>", film.FilmTypeNames); html.AppendFormat("<li><span>Diễn viên</span> {0}</li>", film.ActorNames); html.AppendFormat("<li><span>Thời lượng</span> {0}</li>", film.Time); html.Append("</ul>"); html.AppendFormat("<a href=\"{0}\" class=\"see_a-link\">Xem phim</a>", url); html.Append("</div>"); html.Append("</div>"); } } html.Append("</div>"); html.Append("<div style=\"bottom: 16px; right: 6px;\" class=\"jssorb03\" u=\"navigator\">"); html.Append("<div u=\"prototype\">"); html.Append("<div u=\"numbertemplate\">&nbsp;</div>"); html.Append("</div>"); html.Append("</div>"); html.Append("<span style=\"top: 123px; left: 8px;\" class=\"jssora20l\" onmouseout=\"javascript: event_mouseout();\" onmouseover=\"javascript: event_mouseover();\" u=\"arrowleft\"></span>"); html.Append("<span style=\"top: 123px; right: 8px;\" class=\"jssora20r\" onmouseout=\"javascript: event_mouseout();\" onmouseover=\"javascript: event_mouseover();\" u=\"arrowright\"></span>"); html.Append("</div>"); } return html.ToString(); } #endregion [HttpPost, ValidateInput(false)] [Url("get-film-details")] public ActionResult FilmDetails() { var model = new DataViewCategoryModel { HtmlData = string.Empty }; if (!string.IsNullOrEmpty(Request.Form["txtFilmId"])) { var id = long.Parse(Request.Form["txtFilmId"]); var service = WorkContext.Resolve<IFilmService>(); service.LanguageCode = WorkContext.CurrentCulture; service.SiteId = (int) Site.Home; var obj = service.GetFilmDetails(id); var html = new StringBuilder(); if (obj != null) { var url = Url.Action("FilmView", "HomeView", new {@alias = obj.FilmAlias, @id = obj.Id}); html.Append("<p class=\"name-en\">"); html.AppendFormat("<a href=\"{0}\" title=\"{1}\">{1}</a>", url, obj.FilmNameEnglish); html.Append("</p>"); html.Append("<p class=\"name-vi\">"); html.AppendFormat("<a href=\"{0}\" title=\"{1}\">{1}</a>", url, obj.FilmName); html.Append("</p>"); html.AppendFormat("<p>{0}</p>", obj.Summary); html.Append("<ul>"); html.AppendFormat("<li><span>Năm phát hành:</span> {0}</li>", obj.ReleaseYear); html.AppendFormat("<li><span>Đạo diễn:</span> {0}</li>", obj.DirectorName); html.AppendFormat("<li><span>Diễn viên:</span> {0}</li>", obj.ActorNames); html.AppendFormat("<li><span>Quốc gia:</span> {0}</li>", obj.CountryName); html.AppendFormat("<li><span>Thể loại:</span> {0}</li>", obj.CategoryNames); html.AppendFormat("<li><span>IMDB:</span> {0}</li>", obj.Capacity); html.AppendFormat("<li><span>Liên quan (tag):</span> {0}</li>", obj.Tags); html.Append("</ul>"); html.AppendFormat("<a href=\"{0}\" class=\"see_a-link\">Xem phim<span></span></a>", url); html.Append("<br class=\"clear_both\">"); } model.HtmlData = html.ToString(); } return Json(model); } [HttpPost, ValidateInput(false)] [Url("get-data/tim-kiem")] public ActionResult Search() { var keyword = Request.Form["keyword"]; var service = WorkContext.Resolve<ISearchService>(); service.SiteId = (int)Site.Home; var condition = new List<SearchCondition> { new SearchCondition(new[] { SearchField.Title.ToString(), SearchField.Keyword.ToString(), SearchField.KeywordEN.ToString() }, keyword) }; var total = 0; var data = service.Search(condition, 1, 40, ref total); return Json(data); } #region Rates [HttpPost, ValidateInput(false)] [Url("danh-gia-bao-loi-phim")] public ActionResult RateFilm(int type, long filmId, int rate, int title, string messsages) { var result = new DataViewerModel(); if (!IsLogin) { result = new DataViewerModel { Status = false, Data = "Bạn chưa đăng nhập." }; return Json(result); } var service = WorkContext.Resolve<IRateService>(); var entity = service.GetByFilmCustomer(filmId, CustomerCode) ?? new RateInfo(); switch (type) { case 1: // Đánh giá entity.Rate += rate; entity.Messages = GetRateMessages(rate) + ", "; result.Status = true; result.Data = "Cảm ơn bạn đã đánh giá viphd chúc các bạn xem phim vui vẻ."; var filmService = WorkContext.Resolve<IFilmService>(); filmService.UpdateCommentCount(filmId); break; case 2: //Báo giật lag entity.AlertLag = messsages + ", "; entity.Messages = "Phim này đang bị khách hàng thông báo giật lag."; result.Status = true; result.Data = "Thông báo lỗi của bạn đã được gửi đi. Chúng tôi đang kiểm tra lại. Cảm ơn bạn đã ủng hộ và hỗ trợ viphd nhé."; break; case 3: //Báo lỗi entity.AlertError = EnumExtensions.GetDisplayName((AlertErrorVideo) title); entity.Messages += messsages + ", "; result.Status = true; result.Data = "Thông báo lỗi của bạn đã được gửi đi. Chúng tôi đang kiểm tra lại . Cảm ơn bạn đã ủng hộ và hỗ trợ viphd nhé."; break; case 4: //Thích phim entity.LikeFilm = true; entity.Messages = messsages + ", "; result.Status = false; result.Data = ""; break; } entity.Status = 1; entity.LanguageCode = WorkContext.CurrentCulture; entity.SiteId = (int)Site.Home; entity.CustomerId = UserId; entity.CustomerCode = CustomerCode; entity.FilmId = filmId; service.Save(entity); return Json(result); } private string GetRateMessages(int rate) { var text = string.Empty; if (rate == 1) { text = "Hay Chết Liền"; } if (rate == 2) { text = "Hay chỗ nào"; } if (rate == 3) { text = "Ai Bảo Hay"; } if (rate == 4) { text = "Xém nữa thì Hay"; } if (rate == 5) { text = "Có vẻ Hay"; } if (rate == 6) { text = "Ờ Cũng Hay"; } if (rate == 7) { text = "Hơi bị Hay"; } if (rate == 8) { text = "Quá Là Hay"; } if (rate == 9) { text = "Hay Quá Xá"; } if (rate == 10) { text = "Tuyệt đỉnh Hay"; } return text; } [HttpPost, ValidateInput(false)] [Url("download-games")] public virtual ActionResult CheckDownload(int id) { var result = new DataViewerModel(); result.Status = true; result.Data = "Bạn chưa đăng nhập."; if (IsLogin) { result.Data = "Nhiệm vụ đang chờ bạn thực hiện."; var service = WorkContext.Resolve<IDownloadGameService>(); var obj = service.GetById(id); if (obj != null) { var customerService = WorkContext.Resolve<ICustomerService>(); var status = customerService.AddVipXu(UserId, obj.Id, obj.VipXu); if (status == 1) { result.Data = "Bạn cần tải về, cài đặt và mở ứng dụng để nhận được " + obj.VipXu + " VIPXU."; } else { var downloadService = WorkContext.Resolve<IDownloadCustomerService>(); var item = downloadService.GetItem(UserId, id); if (item != null) { var displayDay = Utilities.GetStatusDownload(item); result.Data = "Bạn cần tải về, cài đặt và mở ứng dụng để nhận được " + obj.VipXu + " VIPXU (sau " + displayDay + ")"; } } } } return Json(result); } #endregion } } <file_sep>using System.Collections.Generic; using System.Data.SqlClient; using CMSSolutions.Data; using CMSSolutions.Events; using CMSSolutions.Services; using CMSSolutions.Websites.Entities; namespace CMSSolutions.Websites.Services { public interface IPromotionCustomersService : IGenericService<PromotionCustomerInfo, long>, IDependency { IList<PromotionCustomerInfo> GetByPromotion(int promotionId); PromotionCustomerInfo GetCode(int promotionId, int customerId); PromotionCustomerInfo GetCodeCustomer(int customerId, string code); int ActiveCode(int customerId, string code); } public class PromotionCustomersService : GenericService<PromotionCustomerInfo, long>, IPromotionCustomersService { public PromotionCustomersService(IRepository<PromotionCustomerInfo, long> repository, IEventBus eventBus) : base(repository, eventBus) { } public IList<PromotionCustomerInfo> GetByPromotion(int promotionId) { var list = new List<SqlParameter> { AddInputParameter("@PromotionId", promotionId) }; return ExecuteReader<PromotionCustomerInfo>("sp_PromotionCustomers_GetByPromotionId", list.ToArray()); } public PromotionCustomerInfo GetCode(int promotionId, int customerId) { var list = new List<SqlParameter> { AddInputParameter("@PromotionId", promotionId), AddInputParameter("@CustomerId", customerId) }; return ExecuteReaderRecord<PromotionCustomerInfo>("sp_PromotionCustomers_GetCode", list.ToArray()); } public PromotionCustomerInfo GetCodeCustomer(int customerId, string code) { var list = new List<SqlParameter> { AddInputParameter("@CustomerId", customerId), AddInputParameter("@Code", code) }; return ExecuteReaderRecord<PromotionCustomerInfo>("sp_PromotionCustomers_GetCodeCustomer", list.ToArray()); } public int ActiveCode(int customerId, string code) { var list = new List<SqlParameter> { AddInputParameter("@CustomerId", customerId), AddInputParameter("@Code", code) }; return (int)ExecuteReaderResult("sp_TransactionCode_Active", list.ToArray()); } } }<file_sep>using System.Collections.Generic; using System.Data.SqlClient; using System.Linq; using CMSSolutions.Data; using CMSSolutions.Events; using CMSSolutions.Services; using CMSSolutions.Websites.Entities; namespace CMSSolutions.Websites.Services { public interface IPromotionService : IGenericService<PromotionInfo, int>, IDependency { IList<PromotionInfo> SearchPaged( int status, int pageIndex, int pageSize, out int totalRecord); } public class PromotionService : GenericService<PromotionInfo, int>, IPromotionService { public PromotionService(IRepository<PromotionInfo, int> repository, IEventBus eventBus) : base(repository, eventBus) { } public IList<PromotionInfo> SearchPaged(int status, int pageIndex, int pageSize, out int totalRecord) { var list = new List<SqlParameter> { AddInputParameter("@Status", status), AddInputParameter("@PageIndex", pageIndex), AddInputParameter("@PageSize", pageSize) }; return ExecuteReader<PromotionInfo>("sp_Promotions_Search_Paged", "@TotalRecord", out totalRecord, list.ToArray()); } } }<file_sep>using System.ComponentModel; using System.Runtime.Serialization; using CMSSolutions.Data; using CMSSolutions.Data.Entity; namespace CMSSolutions.Websites.Entities { [DataContract] public class SmsMessageInfo : BaseEntity<int> { [DataMember] [DisplayName("LanguageCode")] public string LanguageCode { get; set; } [DataMember] [DisplayName("Code")] public string Code { get; set; } [DataMember] [DisplayName("Message")] public string Message { get; set; } [DataMember] [DisplayName("IsEvent")] public bool IsEvent { get; set; } } public class SmsMessageMap : EntityTypeConfiguration<SmsMessageInfo>, IEntityTypeConfiguration { public SmsMessageMap() { ToTable("Modules_SmsMessages"); HasKey(x => x.Id); Property(m => m.LanguageCode).IsRequired().HasMaxLength(50); Property(x => x.Code).HasMaxLength(50).IsRequired(); Property(x => x.Message).IsRequired().HasMaxLength(250); } } }<file_sep>using System; using System.ComponentModel; using System.ComponentModel.DataAnnotations.Schema; using System.Runtime.Serialization; using CMSSolutions.Data; using CMSSolutions.Data.Entity; namespace CMSSolutions.Websites.Entities { [DataContract] public class TransactionCardInfo : BaseEntity<long> { [DataMember] [DisplayName("CustomerCode")] public string CustomerCode { get; set; } [DataMember] [DisplayName("TransactionCode")] public string TransactionCode { get; set; } [DataMember] [DisplayName("CreateDate")] public DateTime CreateDate { get; set; } [NotMapped] [DisplayName(Constants.NotMapped)] public string TextStartDate { get { return CreateDate.ToString(Extensions.Constants.DateTimeFomatFull); } } [DataMember] [DisplayName("CardCode")] public string CardCode { get; set; } [NotMapped] [DisplayName("CardName")] public string CardName { get; set; } [DataMember] [DisplayName("SeriNumber")] public string SeriNumber { get; set; } [DataMember] [DisplayName("PinCode")] public string PinCode { get; set; } [DataMember] [DisplayName("Amount")] public string Amount { get; set; } [DataMember] [DisplayName("Description")] public string Description { get; set; } [DataMember] [DisplayName("Status")] public int Status { get; set; } [DataMember] [DisplayName("IsLock")] public bool IsLock { get; set; } [NotMapped] [DisplayName("FullName")] public string FullName { get; set; } } public class TransactionCardMap : EntityTypeConfiguration<TransactionCardInfo>, IEntityTypeConfiguration { public TransactionCardMap() { ToTable("Modules_TransactionCard"); HasKey(m => m.Id); Property(m => m.CustomerCode).IsRequired().HasMaxLength(50); Property(m => m.TransactionCode).IsRequired().HasMaxLength(50); Property(m => m.SeriNumber).HasMaxLength(250); Property(m => m.PinCode).IsRequired().HasMaxLength(250); Property(m => m.Description).HasMaxLength(2000); Property(m => m.Amount).HasMaxLength(250); } } }<file_sep>using CMSSolutions.Web.UI.ControlForms; using CMSSolutions.Websites.Entities; namespace CMSSolutions.Websites.Models { public class FilmVideoModel { public FilmVideoModel() { IsActived = true; } [ControlHidden] public long Id { get; set; } [ControlHidden] public string ReturnUrl { get; set; } [ControlHidden] public long FilmId { get; set; } [ControlChoice(ControlChoice.DropDownList, Required = true, LabelText = "Ngôn ngữ hiển thị", ContainerCssClass = Constants.ContainerCssClassCol4, ContainerRowIndex = 0, OnSelectedIndexChanged = "$('#" + Extensions.Constants.ServerId + "').empty();")] public string LanguageCode { get; set; } [ControlCascadingDropDown(LabelText = "Trang web", ParentControl = "LanguageCode", AbsoluteParentControl = true, ContainerCssClass = Constants.ContainerCssClassCol4, ContainerRowIndex = 0)] public int SiteId { get; set; } [ControlCascadingDropDown(LabelText = "Máy chủ", ParentControl = "SiteId", AbsoluteParentControl = true, ContainerCssClass = Constants.ContainerCssClassCol4, ContainerRowIndex = 0)] public int ServerId { get; set; } [ControlCascadingDropDown(LabelText = "Thư mục gốc", ParentControl = "ServerId", AbsoluteParentControl = true, ContainerCssClass = Constants.ContainerCssClassCol4, ContainerRowIndex = 1)] public string RootFolders { get; set; } [ControlCascadingDropDown(LabelText = "Thư mục ngày", ParentControl = "RootFolders", AbsoluteParentControl = true, ContainerCssClass = Constants.ContainerCssClassCol4, ContainerRowIndex = 1)] public string FolderDay { get; set; } [ControlCascadingDropDown(LabelText = "Thư mục theo ngày", ParentControl = "FolderDay", AbsoluteParentControl = true, ContainerCssClass = Constants.ContainerCssClassCol4, ContainerRowIndex = 1)] public string ChildrenFolders { get; set; } [ControlCascadingDropDown( AllowMultiple = true, LabelText = "Đường dẫn files", ParentControl = "ChildrenFolders", CssClass = Extensions.Constants.CssControlCustom, EnableChosen = true, ContainerCssClass = Constants.ContainerCssClassCol12, ContainerRowIndex = 2)] public long[] FileIds { get; set; } [ControlText(Type = ControlText.MultiText, Rows = 2, LabelText = "Đường dẫn nguồn album", ContainerCssClass = Constants.ContainerCssClassCol6, ContainerRowIndex = 3)] public string UrlAlbum { get; set; } [ControlText(Type = ControlText.MultiText, Rows = 2, LabelText = "Đường dẫn nguồn video", ContainerCssClass = Constants.ContainerCssClassCol6, ContainerRowIndex = 3)] public string UrlSource { get; set; } [ControlText(Type = ControlText.MultiText, Rows = 2, Required = true, LabelText = "Đường dẫn files subtitle", ContainerCssClass = Constants.ContainerCssClassCol12, ContainerRowIndex = 3)] public string Subtitle { get; set; } [ControlChoice(ControlChoice.DropDownList, AllowMultiple = true, CssClass = Extensions.Constants.CssControlCustom, EnableChosen = true, Required = true, LabelText = "Chọn tập phim", ContainerCssClass = Constants.ContainerCssClassCol4, ContainerRowIndex = 4)] public int[] EpisodeIds { get; set; } [ControlChoice(ControlChoice.CheckBox, LabelText = "", PrependText = "Trailer phim", ContainerCssClass = Constants.ContainerCssClassCol3, ContainerRowIndex = 4)] public bool IsTraller { get; set; } [ControlChoice(ControlChoice.CheckBox, LabelText = "", PrependText = "Sử dụng", ContainerCssClass = Constants.ContainerCssClassCol3, ContainerRowIndex = 4)] public bool IsActived { get; set; } //[ControlFileUpload(EnableFineUploader = true, LabelText = "Ảnh đại diện", ContainerCssClass = Constants.ContainerCssClassCol12, ContainerRowIndex = 4, ShowThumbnail = true)] //public string ImageIcon { get; set; } public static implicit operator FilmVideoModel(FilmVideoInfo entity) { return new FilmVideoModel { Id = entity.Id, FilmId = entity.FilmId, FileIds = new[] { entity.FileId }, IsTraller = entity.IsTraller, IsActived = entity.IsActived, Subtitle = entity.Subtitle, UrlSource = entity.UrlSource, EpisodeIds = new[]{entity.EpisodeId}, UrlAlbum = entity.UrlAlbum }; } } } <file_sep>using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Text; using System.Web.Mvc; using CMSSolutions.Extensions; using CMSSolutions.Web.Mvc; using CMSSolutions.Web.Routing; using CMSSolutions.Web.Themes; using CMSSolutions.Web.UI.ControlForms; using CMSSolutions.Web.UI.Navigation; using CMSSolutions.Websites.Entities; using CMSSolutions.Websites.Extensions; using CMSSolutions.Websites.Models; using CMSSolutions.Websites.Services; namespace CMSSolutions.Websites.Controllers { [Themed(IsDashboard = true), Authorize] public class AdminFilmController : BaseAdminController { public AdminFilmController(IWorkContextAccessor workContextAccessor) : base(workContextAccessor) { TableName = "tblFilms"; } private int pageSize = 50; [Url("admin/films")] public ActionResult Index() { WorkContext.Breadcrumbs.Add(new Breadcrumb { Text = T("Quản lý phim"), Url = "#" }); var result = new ControlGridFormResult<FilmInfo> { Title = T("Quản lý phim"), CssClass = "table table-bordered table-striped", IsAjaxSupported = true, FetchAjaxSource = GetFilms, UpdateActionName = "Update", ActionsColumnWidth = 150, ClientId = TableName, EnablePaginate = true, DefaultPageSize = pageSize, GridWrapperStartHtml = Constants.Grid.GridWrapperStartHtml, GridWrapperEndHtml = Constants.Grid.GridWrapperEndHtml }; result.AddCustomVar(Extensions.Constants.LanguageCode, "$('#" + Extensions.Constants.LanguageCode + "').val();", true); result.AddCustomVar(Extensions.Constants.SiteId, "$('#" + Extensions.Constants.SiteId + "').val();", true); result.AddCustomVar(Extensions.Constants.UserId, "$('#" + Extensions.Constants.UserId + "').val();", true); result.AddCustomVar(Extensions.Constants.CategoryId, "$('#" + Extensions.Constants.CategoryId + "').val();", true); result.AddCustomVar(Extensions.Constants.DirectorId, "$('#" + Extensions.Constants.DirectorId + "').val();", true); result.AddCustomVar(Extensions.Constants.ActorId, "$('#" + Extensions.Constants.ActorId + "').val();", true); result.AddCustomVar(Extensions.Constants.FilmGroup, "$('#" + Extensions.Constants.FilmGroup + "').val();", true); result.AddCustomVar(Extensions.Constants.FilmTypesId, "$('#" + Extensions.Constants.FilmTypesId + "').val();", true); result.AddCustomVar(Extensions.Constants.StatusId, "$('#" + Extensions.Constants.StatusId + "').val();", true); result.AddCustomVar(Extensions.Constants.FromDate, "$('#" + Extensions.Constants.FromDate + "').val();", true); result.AddCustomVar(Extensions.Constants.ToDate, "$('#" + Extensions.Constants.ToDate + "').val();", true); result.AddCustomVar(Extensions.Constants.SearchText, "$('#" + Extensions.Constants.SearchText + "').val();", true); result.AddColumn(x => x.Id, T("ID")).AlignCenter().HasWidth(40); result.AddColumn(x => x.ImageIcon, T("Ảnh đại diện")) .AlignCenter() .HasWidth(100) .RenderAsImage(y => y.ImageIcon, Extensions.Constants.CssThumbsSize); result.AddColumn(x => x.FilmName, T("Tên phim")); result.AddColumn(x => x.FilmNameEnglish, T("Tên tiếng anh")); result.AddColumn(x => x.CollectionName, T("Tên bộ phim")); result.AddColumn(x => x.FilmTypeNames, T("Thể loại phim")); result.AddColumn(x => x.DisplayDate, T("Ngày tạo")); result.AddColumn(x => x.FullName, T("Người đăng")); result.AddColumn(x => x.IsPublished) .HasHeaderText(T("Đã đăng")) .AlignCenter() .HasWidth(100) .RenderAsStatusImage(); result.AddColumn(x => x.IsHot) .HasHeaderText(T("Phim mới")) .AlignCenter() .HasWidth(100) .RenderAsStatusImage(); result.AddColumn(x => x.HasCopyright) .HasHeaderText(T("Có BQ")) .AlignCenter() .HasWidth(100) .RenderAsStatusImage(); result.AddAction().HasText(T("Thêm mới")) .HasUrl("javascript: redirectUrl(0, '" + Url.Action("Edit", "AdminFilm") + "');") .HasButtonStyle(ButtonStyle.Primary) .HasBoxButton(false) .HasRow(false) .HasCssClass(Constants.RowLeft) .HasRow(true); result.AddAction(new ControlFormHtmlAction(() => BuildLanguages(true, Extensions.Constants.SiteId))).HasParentClass(Constants.ContainerCssClassCol3); result.AddAction(new ControlFormHtmlAction(() => BuildSites(true, Extensions.Constants.CategoryId))).HasParentClass(Constants.ContainerCssClassCol3); result.AddAction(new ControlFormHtmlAction(BuildCategories)).HasParentClass(Constants.ContainerCssClassCol3); result.AddAction(new ControlFormHtmlAction(BuildUsers).HasParentClass(Constants.ContainerCssClassCol3)); result.AddAction(new ControlFormHtmlAction(BuildDirectors)).HasParentClass(Constants.ContainerCssClassCol3); result.AddAction(new ControlFormHtmlAction(BuildActors)).HasParentClass(Constants.ContainerCssClassCol3); result.AddAction(new ControlFormHtmlAction(BuildFilmTypes)).HasParentClass(Constants.ContainerCssClassCol3); result.AddAction(new ControlFormHtmlAction(BuildFilmGroups)).HasParentClass(Constants.ContainerCssClassCol3); result.AddAction(new ControlFormHtmlAction(BuildStatus)).HasParentClass(Constants.ContainerCssClassCol3); result.AddAction(new ControlFormHtmlAction(() => BuildFromDate())).HasParentClass(Constants.ContainerCssClassCol3); result.AddAction(new ControlFormHtmlAction(() => BuildToDate())).HasParentClass(Constants.ContainerCssClassCol3); result.AddAction(new ControlFormHtmlAction(BuildSearchText)).HasParentClass(Constants.ContainerCssClassCol3); result.AddAction(new ControlFormHtmlAction(BuildHtmlScript)).HasBoxButton(false); result.AddRowAction() .HasText(T("Sửa")) .HasUrl(x => "javascript: redirectUrl("+x.Id+", '" + Url.Action("Edit", "AdminFilm") + "');") .HasButtonStyle(ButtonStyle.Default) .HasButtonSize(ButtonSize.ExtraSmall); result.AddRowAction() .HasText(T("Videos")) .HasUrl(x => "javascript: redirectUrl(" + x.Id + ", '" + Url.Action("Index", "AdminFilmVideos") + "');") .HasButtonStyle(ButtonStyle.Info) .HasButtonSize(ButtonSize.ExtraSmall); result.AddRowAction(true) .HasText(T("Xóa")) .HasName("Delete") .HasValue(x => x.Id.ToString(CultureInfo.InvariantCulture.ToString())) .HasButtonStyle(ButtonStyle.Danger) .HasButtonSize(ButtonSize.ExtraSmall) .HasConfirmMessage(T(Constants.Messages.ConfirmDeleteRecord).Text); result.AddReloadEvent("UPDATE_ENTITY_COMPLETE"); result.AddReloadEvent("DELETE_ENTITY_COMPLETE"); return result; } private string BuildHtmlScript() { var sb = new StringBuilder(); sb.Append("<script type=\"text/javascript\">"); sb.Append("function redirectUrl(id, url) {"); sb.Append("var languageCode = $(\"#" + Extensions.Constants.LanguageCode + "\").val();"); sb.Append("var siteId = $(\"#" + Extensions.Constants.SiteId + "\").val();"); sb.Append("var categoryId = $(\"#" + Extensions.Constants.CategoryId + "\").val();"); sb.Append("var userId = $(\"#" + Extensions.Constants.UserId + "\").val();"); sb.Append("var fromDate = $(\"#" + Extensions.Constants.FromDate + "\").val();"); sb.Append("var toDate = $(\"#" + Extensions.Constants.ToDate + "\").val();"); sb.Append("var searchText = $(\"#" + Extensions.Constants.SearchText + "\").val();"); sb.Append("var statusId = $(\"#" + Extensions.Constants.StatusId + "\").val();"); sb.Append("var directorId = $(\"#" + Extensions.Constants.DirectorId + "\").val();"); sb.Append("var actorId = $(\"#" + Extensions.Constants.ActorId + "\").val();"); sb.Append("var filmGroup = $(\"#" + Extensions.Constants.FilmGroup + "\").val();"); sb.Append("var filmTypesId = $(\"#" + Extensions.Constants.FilmTypesId + "\").val();"); sb.AppendFormat("var returnUrl = languageCode + '{0}' + siteId + '{0}' + categoryId + '{0}' + userId + '{0}'", ","); sb.AppendFormat("+ directorId + '{0}' + actorId + '{0}' + filmTypesId + '{0}' + filmGroup + '{0}' + statusId + '{0}'", ","); sb.AppendFormat("+ fromDate + '{0}' + toDate + '{0}' + encode_utf8(searchText);", ","); sb.Append("var encodedString = btoa(returnUrl);"); sb.AppendFormat("window.location = url + '{0}' + id + '{1}' + encodedString;", "?id=", "&" + Extensions.Constants.ReturnUrl + "="); sb.Append("}"); sb.Append("</script>"); return sb.ToString(); } private string GetUrl() { var pageIndex = 1; if (Session[Extensions.Constants.PageIndex] != null) { pageIndex = int.Parse(Session[Extensions.Constants.PageIndex].ToString()); } Session[Extensions.Constants.BackPageIndex] = "BACKPAGE"; var returnUrl = Request.QueryString[Extensions.Constants.ReturnUrl]; var url = Url.Action("Index", "AdminFilm"); var sb = new StringBuilder(); sb.Append("<script type=\"text/javascript\">"); sb.Append("function backUrl() {"); sb.AppendFormat("window.location = '{0}?{1}={2}&{3}={4}';", url, Extensions.Constants.ReturnUrl, returnUrl, Extensions.Constants.PageIndex, pageIndex); sb.Append("}"); sb.Append("</script>"); return sb.ToString(); } private ControlGridAjaxData<FilmInfo> GetFilms(ControlGridFormRequest options) { if (Request.QueryString[Extensions.Constants.PageIndex] != null && Session[Extensions.Constants.BackPageIndex] != null) { options.PageIndex = int.Parse(Request.QueryString[Extensions.Constants.PageIndex]); } var languageCode = WorkContext.CurrentCulture; if (!string.IsNullOrEmpty(GetQueryString(0)) && Session[Extensions.Constants.BackPageIndex] != null) { languageCode = GetQueryString(0); } var siteId = 0; if (!string.IsNullOrEmpty(GetQueryString(1)) && Session[Extensions.Constants.BackPageIndex] != null) { siteId = int.Parse(GetQueryString(1)); } var categoryId = 0; if (!string.IsNullOrEmpty(GetQueryString(2)) && Session[Extensions.Constants.BackPageIndex] != null) { categoryId = Convert.ToInt32(GetQueryString(2)); } long userId = 0; if (!string.IsNullOrEmpty(GetQueryString(3)) && Session[Extensions.Constants.BackPageIndex] != null) { userId = long.Parse(GetQueryString(3)); } var directorId = 0; if (!string.IsNullOrEmpty(GetQueryString(4)) && Session[Extensions.Constants.BackPageIndex] != null) { directorId = int.Parse(GetQueryString(4)); } var actorId = 0; if (!string.IsNullOrEmpty(GetQueryString(5)) && Session[Extensions.Constants.BackPageIndex] != null) { actorId = int.Parse(GetQueryString(5)); } var filmTypesId = 0; if (!string.IsNullOrEmpty(GetQueryString(6)) && Session[Extensions.Constants.BackPageIndex] != null) { filmTypesId = int.Parse(GetQueryString(6)); } var filmGroup = 0; if (!string.IsNullOrEmpty(GetQueryString(7)) && Session[Extensions.Constants.BackPageIndex] != null) { filmGroup = int.Parse(GetQueryString(7)); } var statusId = 0; if (!string.IsNullOrEmpty(GetQueryString(8)) && Session[Extensions.Constants.BackPageIndex] != null) { statusId = int.Parse(GetQueryString(8)); } var fromDate = DateTime.Now.Date; if (!string.IsNullOrEmpty(GetQueryString(9)) && Session[Extensions.Constants.BackPageIndex] != null) { fromDate = DateTime.ParseExact(GetQueryString(9), Extensions.Constants.DateTimeFomat, CultureInfo.InvariantCulture); } var toDate = DateTime.Now.Date; if (!string.IsNullOrEmpty(GetQueryString(10)) && Session[Extensions.Constants.BackPageIndex] != null) { toDate = DateTime.ParseExact(GetQueryString(10), Extensions.Constants.DateTimeFomat, CultureInfo.InvariantCulture); } var searchText = string.Empty; if (!string.IsNullOrEmpty(GetQueryString(11)) && Session[Extensions.Constants.BackPageIndex] != null) { searchText = GetQueryString(11); } int countryId = 0; int collectionId = 0; int articlesId = 0; int serverId = 0; int releaseYear = 0; DateTime createDate = Utilities.DateNull(); DateTime publishedDate = Utilities.DateNull(); int isPublished = -1; int isHot = -1; int isHome = -1; if (Utilities.IsNotNull(Request.Form[Extensions.Constants.LanguageCode])) { languageCode = Request.Form[Extensions.Constants.LanguageCode]; } if (Utilities.IsNotNull(Request.Form[Extensions.Constants.SiteId])) { siteId = Convert.ToInt32(Request.Form[Extensions.Constants.SiteId]); } if (Utilities.IsNotNull(Request.Form[Extensions.Constants.CategoryId])) { categoryId = Convert.ToInt32(Request.Form[Extensions.Constants.CategoryId]); } if (Utilities.IsNotNull(Request.Form[Extensions.Constants.FromDate])) { fromDate = DateTime.ParseExact(Request.Form[Extensions.Constants.FromDate], "dd/MM/yyyy", CultureInfo.InvariantCulture); } if (Utilities.IsNotNull(Request.Form[Extensions.Constants.ToDate])) { toDate = DateTime.ParseExact(Request.Form[Extensions.Constants.ToDate], "dd/MM/yyyy", CultureInfo.InvariantCulture); } if (Utilities.IsNotNull(Request.Form[Extensions.Constants.SearchText])) { searchText = Request.Form[Extensions.Constants.SearchText]; } if (Utilities.IsNotNull(Request.Form[Extensions.Constants.UserId])) { userId = long.Parse(Request.Form[Extensions.Constants.UserId]); } if (Utilities.IsNotNull(Request.Form[Extensions.Constants.StatusId])) { statusId = Convert.ToInt32(Request.Form[Extensions.Constants.StatusId]); } if (Utilities.IsNotNull(Request.Form[Extensions.Constants.DirectorId])) { directorId = Convert.ToInt32(Request.Form[Extensions.Constants.DirectorId]); } if (Utilities.IsNotNull(Request.Form[Extensions.Constants.ActorId])) { actorId = Convert.ToInt32(Request.Form[Extensions.Constants.ActorId]); } if (Utilities.IsNotNull(Request.Form[Extensions.Constants.FilmGroup])) { filmGroup = Convert.ToInt32(Request.Form[Extensions.Constants.FilmGroup]); } int isFilmRetail = -1; int isFilmLengthEpisodes = -1; if (filmGroup > 0) { switch ((FilmGroup)filmGroup) { case FilmGroup.FilmRetail: isFilmRetail = 1; isFilmLengthEpisodes = 0; break; case FilmGroup.FilmLengthEpisodes: isFilmRetail = 0; isFilmLengthEpisodes = 1; break; } } if (Utilities.IsNotNull(Request.Form[Extensions.Constants.FilmTypesId])) { filmTypesId = Convert.ToInt32(Request.Form[Extensions.Constants.FilmTypesId]); } int totals; var service = WorkContext.Resolve<IFilmService>(); var records = service.SearchPaged( searchText, languageCode, siteId, categoryId, filmTypesId, countryId, directorId, actorId, collectionId, articlesId, userId, serverId, releaseYear, fromDate, toDate, createDate, publishedDate, isPublished, isHot, isHome, isFilmRetail, isFilmLengthEpisodes, statusId, options.PageIndex, options.PageSize, out totals); Session[Extensions.Constants.PageIndex] = options.PageIndex; Session[Extensions.Constants.BackPageIndex] = null; return new ControlGridAjaxData<FilmInfo>(records, totals); } [Url("admin/films/edit")] public ActionResult Edit() { var id = int.Parse(Request.QueryString["id"]); WorkContext.Breadcrumbs.Add(new Breadcrumb { Text = T("Quản lý phim"), Url = Url.Action("Index") }); WorkContext.Breadcrumbs.Add(new Breadcrumb { Text = T("Thông tin phim"), Url = "#" }); var model = new FilmModel(); if (id > 0) { var service = WorkContext.Resolve<IFilmService>(); var obj = service.GetById(id); model = obj; if (obj.IsFilmRetail) { model.FilmGroup = 1; } if (obj.IsFilmLengthEpisodes) { model.FilmGroup = 2; } } var result = new ControlFormResult<FilmModel>(model) { Title = T("Thông tin phim"), UpdateActionName = "Update", FormMethod = FormMethod.Post, SubmitButtonText = T("Lưu lại"), ShowBoxHeader = false, ShowCancelButton = false, FormWrapperStartHtml = Constants.Form.FormWrapperStartHtml, FormWrapperEndHtml = Constants.Form.FormWrapperEndHtml, SetJavascript = GetUrl() }; result.RegisterFileUploadOptions("ImageIcon.FileName", new ControlFileUploadOptions { AllowedExtensions = "jpg,jpeg,png,gif" }); result.RegisterFileUploadOptions("ImageThumb.FileName", new ControlFileUploadOptions { AllowedExtensions = "jpg,jpeg,png,gif" }); if (id > 0) { result.AddAction().HasText(T("Chọn videos")) .HasUrl(Url.Action("Index", "AdminFilmVideos", new { @id = id })) .HasButtonStyle(ButtonStyle.Info); } result.AddAction().HasText(T("Làm mới")) .HasUrl(Url.Action("Edit", RouteData.Values.Merge(new { id = 0 }))) .HasButtonStyle(ButtonStyle.Success); result.AddAction().HasText(T("Trở về")) .HasUrl("javascript: backUrl();") .HasButtonStyle(ButtonStyle.Danger); result.MakeReadOnlyProperty(x => x.StartDate); result.MakeReadOnlyProperty(x => x.EndDate); result.RegisterExternalDataSource(x => x.LanguageCode, y => BindLanguages()); result.RegisterExternalDataSource(x => x.FilmTypeIds, y => BindFilmTypes()); result.RegisterExternalDataSource(x => x.CountryId, y => BindCountries()); result.RegisterExternalDataSource(x => x.DirectorId, y => BindDirectors()); result.RegisterExternalDataSource(x => x.ActorIds, y => BindActors()); result.RegisterExternalDataSource(x => x.ServerId, y => BindServers()); result.RegisterExternalDataSource(x => x.FilmGroup, y => BindFilmGroups()); result.RegisterCascadingDropDownDataSource(x => x.CollectionId, Url.Action("GetCollectionsByType")); result.RegisterCascadingDropDownDataSource(x => x.SiteId, Url.Action("GetSitesByLanguage")); result.RegisterCascadingDropDownDataSource(x => x.CategoryIds, Url.Action("GetCategoriesBySite")); result.RegisterExternalDataSource(x => x.Status, y => BindStatus()); result.RegisterExternalDataSource(x => x.VideoType, y => BindVideoTypes()); return result; } private IEnumerable<SelectListItem> BindVideoTypes() { return EnumExtensions.GetListItems<VideoTypes>(); } [Url("admin/get-collections-by-type")] public ActionResult GetCollectionsByType() { var filmGroup = 1; if (Utilities.IsNotNull(Request.Form[Extensions.Constants.FilmGroup])) { filmGroup = Convert.ToInt32(Request.Form[Extensions.Constants.FilmGroup]); } var result = new List<SelectListItem>(); if ((FilmGroup)filmGroup == FilmGroup.FilmLengthEpisodes) { var service = WorkContext.Resolve<ICollectionService>(); var items = service.GetRecords(x => x.Status == (int)Status.Approved).OrderByDescending(x => x.Id); result.AddRange(items.Select(item => new SelectListItem { Text = item.Name, Value = item.Id.ToString() })); } result.Insert(0, new SelectListItem { Text = "--- Chọn tên bộ phim ---", Value = "0" }); return Json(result); } private IEnumerable<SelectListItem> BindDirectors() { var service = WorkContext.Resolve<IDirectorService>(); var items = service.GetRecords(x => x.Status == (int)Status.Approved).OrderByDescending(x => x.Id); var result = new List<SelectListItem>(); result.AddRange(items.Select(item => new SelectListItem { Text = item.FullName, Value = item.Id.ToString() })); result.Insert(0, new SelectListItem { Text = "--- Đạo diễn phim ---", Value = "0" }); return result; } private IEnumerable<SelectListItem> BindActors() { var service = WorkContext.Resolve<IActorService>(); var items = service.GetRecords(x => x.Status == (int)Status.Approved).OrderByDescending(x => x.Id); var result = new List<SelectListItem>(); result.AddRange(items.Select(item => new SelectListItem { Text = item.FullName, Value = item.Id.ToString() })); return result; } private IEnumerable<SelectListItem> BindFilmGroups() { var items = EnumExtensions.GetListItems<FilmGroup>(); items.Insert(0, new SelectListItem { Text = "--- Chọn nhóm film ---", Value = "0"}); return items; } private IEnumerable<SelectListItem> BindServers() { var service = WorkContext.Resolve<IFilmServersService>(); var items = service.GetRecords(x => x.Status == (int)Status.Approved); var result = new List<SelectListItem>(); result.AddRange(items.Select(item => new SelectListItem { Text = item.ServerName, Value = item.Id.ToString() })); result.Insert(0, new SelectListItem { Text = "--- Máy chủ phim ---", Value = "0" }); return result; } [HttpPost, ValidateInput(false), FormButton("Save")] [Url("admin/films/update")] public ActionResult Update(FilmModel model) { if (!ModelState.IsValid) { return new AjaxResult().Alert(T(Constants.Messages.InvalidModel)); } var service = WorkContext.Resolve<IFilmService>(); FilmInfo item; if (model.Id == 0) { item = new FilmInfo(); item.ViewCount = 20000; } else { item = service.GetById(model.Id); } var alias = model.FilmAlias; if (string.IsNullOrEmpty(alias)) { alias = Utilities.GetAlias(model.FilmName); if (service.CheckAlias(0, alias)) { alias += "-" + DateTime.Now.ToString("ddMMyyyyhhmm"); } } if (model.Id == 0 && service.CheckName(model.FilmName)) { return new AjaxResult().Alert(T("Đã tồn tại phim này!")); } if (model.Id == 0) { item.FilmCode = service.GetLatestFilmCode(); } item.FilmNameEnglish = model.FilmNameEnglish; item.FilmName = model.FilmName; item.FilmAlias = alias; item.LanguageCode = model.LanguageCode; item.SiteId = model.SiteId; item.CategoryIds = Utilities.ParseString(model.CategoryIds); item.FilmTypeIds = Utilities.ParseString(model.FilmTypeIds); item.CountryId = model.CountryId; item.DirectorId = model.DirectorId; item.ActorIds = Utilities.ParseString(model.ActorIds); item.CollectionId = model.CollectionId; item.ArticlesId = 0; item.Time = model.Time; item.Capacity = model.Capacity; item.ReleaseYear = model.ReleaseYear; item.CreateByUserId = WorkContext.CurrentUser.Id; item.CreateDate = DateTime.Now; item.Contents = model.Contents; item.Summary = model.Summary; item.Description = model.Description; item.Tags = model.Tags; item.IsPublished = model.IsPublished; if (string.IsNullOrEmpty(model.PublishedDate)) { model.PublishedDate = Extensions.Constants.DateTimeMin; } item.PublishedDate = DateTime.ParseExact(model.PublishedDate, Extensions.Constants.DateTimeFomat, CultureInfo.InvariantCulture); item.IsHot = model.IsHot; item.IsHome = model.IsHome; item.Prices = (decimal)model.Prices; item.HasCopyright = model.HasCopyright; item.StartDate = DateTime.Now; //if (string.IsNullOrEmpty(model.StartDate)) //{ // model.StartDate = Extensions.Constants.DateTimeMin; //} //item.StartDate = DateTime.ParseExact(model.StartDate, Extensions.Constants.DateTimeFomat, CultureInfo.InvariantCulture); item.EndDate = DateTime.Now; //if (string.IsNullOrEmpty(model.EndDate)) //{ // model.EndDate = Extensions.Constants.DateTimeMin; //} //item.EndDate = DateTime.ParseExact(model.EndDate, Extensions.Constants.DateTimeFomat, CultureInfo.InvariantCulture); item.ImageIcon = model.ImageIcon; item.ImageThumb = model.ImageThumb; item.ServerId = model.ServerId; var server = WorkContext.Resolve<IFilmServersService>().GetById(model.ServerId); if (server != null) { item.ServerIp = server.ServerIP; } item.Status = model.Status; bool isFilmRetail = false; bool isFilmLengthEpisodes = false; switch ((FilmGroup)model.FilmGroup) { case FilmGroup.FilmRetail: isFilmRetail = true; break; case FilmGroup.FilmLengthEpisodes: isFilmLengthEpisodes = true; break; } item.IsFilmRetail = isFilmRetail; item.IsFilmLengthEpisodes = isFilmLengthEpisodes; item.IsTheater = model.IsTheater; switch ((VideoTypes)model.VideoType) { case VideoTypes.IsFilm: item.IsFilm = true; item.IsClip = false; item.IsShow = false; item.IsTrailer = false; break; case VideoTypes.IsShow: item.IsFilm = false; item.IsClip = false; item.IsShow = true; item.IsTrailer = false; break; case VideoTypes.IsClip: item.IsFilm = false; item.IsClip = true; item.IsShow = false; item.IsTrailer = false; break; case VideoTypes.IsTrailer: item.IsFilm = false; item.IsClip = false; item.IsShow = false; item.IsTrailer = true; break; } service.Save(item); try { #region Add Search var service2 = WorkContext.Resolve<ISearchService>(); var searchObject = service2.GetBySearchId(item.Id.ToString(), (int)SearchType.Film); long id = 0; if (searchObject != null) { id = searchObject.Id; } var search = new SearchInfo { Id = id, Title = item.FilmName, Alias = item.FilmAlias, CategoryIds = item.CategoryIds, CreateDate = item.CreateDate, IsBlock = !item.IsPublished, LanguageCode = item.LanguageCode, SearchId = item.Id.ToString(), SiteId = item.SiteId, Sumary = item.Summary, Tags = item.Tags, Type = (int)SearchType.Film, TitleEnglish = item.FilmNameEnglish, Images = item.ImageIcon, ViewCount = item.ViewCount.ToString(), Processed = 0 }; service2.Save(search); var cacheSearch = new LuceneService(); cacheSearch.UpdateLuceneIndex(search); #endregion } catch (Exception) { return new AjaxResult().NotifyMessage("UPDATE_ENTITY_COMPLETE") .Alert(T("Không thể thêm dữ liệu tìm kiếm.")); } return new AjaxResult().NotifyMessage("UPDATE_ENTITY_COMPLETE") .Alert(T("Cập nhật thành công!")); } [FormButton("Delete")] [HttpPost, ActionName("Update")] public ActionResult Delete(int id) { var service = WorkContext.Resolve<IFilmService>(); var item = service.GetById(id); item.Status = (int)Status.Deleted; service.Update(item); return new AjaxResult() .NotifyMessage("DELETE_ENTITY_COMPLETE") .Alert(T("Dữ liệu chuyển trạng thái xóa tạm thời!")); } } } <file_sep>using System; using System.ComponentModel; using System.ComponentModel.DataAnnotations.Schema; using System.Runtime.Serialization; using CMSSolutions.Data; using CMSSolutions.Data.Entity; namespace CMSSolutions.Websites.Entities { [DataContract] public class LogInfo : BaseEntity<long> { [DataMember] [DisplayName("CreateDate")] public DateTime CreateDate { get; set; } [NotMapped] [DisplayName(Constants.NotMapped)] public string TextCreateDate { get { return CreateDate.ToString(Extensions.Constants.DateTimeFomatFull); } } [DataMember] [DisplayName("Type")] public int Type { get; set; } [DataMember] [DisplayName("Messages")] public string Messages { get; set; } [DataMember] [DisplayName("Keyword")] public string Keyword { get; set; } [DataMember] [DisplayName("Contents")] public string Contents { get; set; } [DataMember] [DisplayName("Status")] public int Status { get; set; } } public class LogMap : EntityTypeConfiguration<LogInfo>, IEntityTypeConfiguration { public LogMap() { ToTable("Modules_Logs"); HasKey(m => m.Id); Property(m => m.CreateDate).IsRequired(); Property(m => m.Messages).IsRequired(); Property(m => m.Keyword).HasMaxLength(250); Property(m => m.Contents).HasMaxLength(250); } } }<file_sep>using System; using System.Collections.Generic; using System.Globalization; using System.Text; using System.Web.Mvc; using CMSSolutions.Extensions; using CMSSolutions.Web.Mvc; using CMSSolutions.Web.Routing; using CMSSolutions.Web.Themes; using CMSSolutions.Web.UI.ControlForms; using CMSSolutions.Web.UI.Navigation; using CMSSolutions.Websites.Entities; using CMSSolutions.Websites.Extensions; using CMSSolutions.Websites.Models; using CMSSolutions.Websites.Services; namespace CMSSolutions.Websites.Controllers { [Themed(IsDashboard = true), Authorize] public class AdminLogController : BaseAdminController { public AdminLogController(IWorkContextAccessor workContextAccessor) : base(workContextAccessor) { TableName = "tblLogs"; } [Url("admin/logs")] public ActionResult Index() { WorkContext.Breadcrumbs.Add(new Breadcrumb { Text = T("Quản lý logs"), Url = "#" }); var result = new ControlGridFormResult<LogInfo> { Title = T("Quản lý logs"), CssClass = "table table-bordered table-striped", IsAjaxSupported = true, FetchAjaxSource = GetLogs, UpdateActionName = "Update", ActionsColumnWidth = 100, ClientId = TableName, EnablePaginate = true, DefaultPageSize = WorkContext.DefaultPageSize, GridWrapperStartHtml = Constants.Grid.GridWrapperStartHtml, GridWrapperEndHtml = Constants.Grid.GridWrapperEndHtml }; result.AddCustomVar(Extensions.Constants.FromDate, "$('#" + Extensions.Constants.FromDate + "').val();", true); result.AddCustomVar(Extensions.Constants.ToDate, "$('#" + Extensions.Constants.ToDate + "').val();", true); result.AddCustomVar(Extensions.Constants.SearchText, "$('#" + Extensions.Constants.SearchText + "').val();", true); result.AddCustomVar(Extensions.Constants.TypeSearch, "$('#" + Extensions.Constants.TypeSearch + "').val();", true); result.AddCustomVar(Extensions.Constants.StatusId, "$('#" + Extensions.Constants.StatusId + "').val();", true); result.AddColumn(x => x.Id, T("ID")).AlignCenter().HasWidth(60); result.AddColumn(x => x.Keyword, T("Thực hiện bởi")); result.AddColumn(x => x.TextCreateDate, T("Ngày tạo")); result.AddColumn(x => x.Messages, T("Thông báo")); result.AddAction(new ControlFormHtmlAction(() => BuildFromDate())).HasParentClass(Constants.ContainerCssClassCol3); result.AddAction(new ControlFormHtmlAction(() => BuildToDate())).HasParentClass(Constants.ContainerCssClassCol3).HasRow(true); result.AddAction(new ControlFormHtmlAction(BuildSearchText)).HasParentClass(Constants.ContainerCssClassCol3); result.AddAction(new ControlFormHtmlAction(BuildLogTypes)).HasParentClass(Constants.ContainerCssClassCol3); result.AddAction(new ControlFormHtmlAction(BuildLogStatus)).HasParentClass(Constants.ContainerCssClassCol3); result.AddRowAction() .HasText(T("Chi tiết")) .HasUrl(x => Url.Action("ViewDetails", RouteData.Values.Merge(new { id = x.Id }))) .HasButtonStyle(ButtonStyle.Info) .HasButtonSize(ButtonSize.ExtraSmall); result.AddReloadEvent("UPDATE_ENTITY_COMPLETE"); return result; } [Url("admin/logs/view/{id}")] public ActionResult ViewDetails(int id) { WorkContext.Breadcrumbs.Add(new Breadcrumb { Text = T("Quản lý logs"), Url = Url.Action("Index") }); WorkContext.Breadcrumbs.Add(new Breadcrumb { Text = T("Thông tin log"), Url = "#" }); var service = WorkContext.Resolve<ILogService>(); var model = new LogModel(); if (id > 0) { model = service.GetById(id); } var result = new ControlFormResult<LogModel>(model) { Title = T("Thông tin log"), ShowSubmitButton = false, ShowCancelButton = true, ShowBoxHeader = false, CancelButtonText = T("Trở về"), FormWrapperStartHtml = Constants.Form.FormWrapperStartHtml, FormWrapperEndHtml = Constants.Form.FormWrapperEndHtml }; result.ReadOnly = true; result.RegisterExternalDataSource(x => x.Type, y => BindLogTypes()); result.RegisterExternalDataSource(x => x.Status, y => BindLogStatus()); return result; } private string BuildLogTypes() { var list = EnumExtensions.GetListItems<LogType>(); var sb = new StringBuilder(); sb.AppendFormat(T("Loại") + " <select id=\"" + Extensions.Constants.TypeSearch + "\" name=\"" + Extensions.Constants.TypeSearch + "\" autocomplete=\"off\" class=\"uniform form-control col-md-3\" onchange=\"$('#" + TableName + "').jqGrid().trigger('reloadGrid');\">"); foreach (var status in list) { sb.AppendFormat("<option value=\"{1}\">{0}</option>", status.Text, status.Value); } sb.Append("</select>"); return sb.ToString(); } private IEnumerable<SelectListItem> BindLogTypes() { var items = EnumExtensions.GetListItems<LogType>(); items[0].Selected = true; return items; } private string BuildLogStatus() { var list = EnumExtensions.GetListItems<LogStatus>(); var sb = new StringBuilder(); sb.AppendFormat(T("Trạng thái") + " <select id=\"" + Extensions.Constants.StatusId + "\" name=\"" + Extensions.Constants.StatusId + "\" autocomplete=\"off\" class=\"uniform form-control col-md-3\" onchange=\"$('#" + TableName + "').jqGrid().trigger('reloadGrid');\">"); foreach (var status in list) { sb.AppendFormat("<option value=\"{1}\">{0}</option>", status.Text, status.Value); } sb.Append("</select>"); return sb.ToString(); } private IEnumerable<SelectListItem> BindLogStatus() { var items = EnumExtensions.GetListItems<LogStatus>(); items[0].Selected = true; return items; } private ControlGridAjaxData<LogInfo> GetLogs(ControlGridFormRequest options) { var searchText = string.Empty; if (Utilities.IsNotNull(Request.Form[Extensions.Constants.SearchText])) { searchText = Request.Form[Extensions.Constants.SearchText]; } var fromDate = DateTime.Now.Date; if (Utilities.IsNotNull(Request.Form[Extensions.Constants.FromDate])) { fromDate = DateTime.ParseExact(Request.Form[Extensions.Constants.FromDate], "dd/MM/yyyy", CultureInfo.InvariantCulture); } var toDate = DateTime.Now.Date; if (Utilities.IsNotNull(Request.Form[Extensions.Constants.ToDate])) { toDate = DateTime.ParseExact(Request.Form[Extensions.Constants.ToDate], "dd/MM/yyyy", CultureInfo.InvariantCulture); } var type = 0; if (Utilities.IsNotNull(Request.Form[Extensions.Constants.TypeSearch])) { type = Convert.ToInt32(Request.Form[Extensions.Constants.TypeSearch]); } var status = 0; if (Utilities.IsNotNull(Request.Form[Extensions.Constants.StatusId])) { status = Convert.ToInt32(Request.Form[Extensions.Constants.StatusId]); } int totals; var items = WorkContext.Resolve<ILogService>().GetPaged(searchText, fromDate,toDate, type,status, options.PageIndex, options.PageSize, out totals); var result = new ControlGridAjaxData<LogInfo>(items, totals); return result; } } } <file_sep>using System.Collections.Generic; using System.Data.SqlClient; using CMSSolutions.Data; using CMSSolutions.Events; using CMSSolutions.Services; using CMSSolutions.Websites.Entities; namespace CMSSolutions.Websites.Services { public interface IFilmVideoService : IGenericService<FilmVideoInfo, long>, IDependency { IList<FilmVideoInfo> GetByFilm(long filmId, int pageIndex, int pageSize, out int totalRecord); FilmVideoInfo GetByFilmFile(long filmId, long fileId); IList<FilmVideoInfo> GetFilesByFile(string folderPath); } public class FilmVideoService : GenericService<FilmVideoInfo, long>, IFilmVideoService { public FilmVideoService(IRepository<FilmVideoInfo, long> repository, IEventBus eventBus) : base(repository, eventBus) { } public IList<FilmVideoInfo> GetByFilm(long filmId, int pageIndex, int pageSize, out int totalRecord) { var list = new List<SqlParameter> { AddInputParameter("@FilmId", filmId), AddInputParameter("@PageIndex", pageIndex), AddInputParameter("@PageSize", pageSize) }; return ExecuteReader<FilmVideoInfo>("sp_FilmVideos_GetByFilm", "@TotalRecord", out totalRecord, list.ToArray()); } public FilmVideoInfo GetByFilmFile(long filmId, long fileId) { var list = new List<SqlParameter> { AddInputParameter("@FilmId", filmId), AddInputParameter("@FileId", fileId) }; return ExecuteReaderRecord<FilmVideoInfo>("sp_FilmVideos_GetByFilmFile", list.ToArray()); } public IList<FilmVideoInfo> GetFilesByFile(string folderPath) { var list = new List<SqlParameter> { AddInputParameter("@FolderPath", folderPath) }; return ExecuteReader<FilmVideoInfo>("sp_FilmVideos_GetFilesByFolder", list.ToArray()); } } } <file_sep>using System.ComponentModel; using System.ComponentModel.DataAnnotations.Schema; using System.Runtime.Serialization; using CMSSolutions.Data; using CMSSolutions.Data.Entity; namespace CMSSolutions.Websites.Entities { public class RateInfo : BaseEntity<long> { [DataMember] [DisplayName("LanguageCode")] public string LanguageCode { get; set; } [DataMember] [DisplayName("SiteId")] public int SiteId { get; set; } [DataMember] [DisplayName("FilmId")] public long FilmId { get; set; } [NotMapped] [DisplayName("FilmName")] public string FilmName { get; set; } [DataMember] [DisplayName("Rate")] public int Rate { get; set; } [DataMember] [DisplayName("CustomerId")] public int CustomerId { get; set; } [DataMember] [DisplayName("CustomerCode")] public string CustomerCode { get; set; } [NotMapped] [DisplayName("CustomerName")] public string CustomerName { get; set; } [DataMember] [DisplayName("AlertError")] public string AlertError { get; set; } [DataMember] [DisplayName("AlertLag")] public string AlertLag { get; set; } [DataMember] [DisplayName("Messages")] public string Messages { get; set; } [DataMember] [DisplayName("Status")] public int Status { get; set; } [DataMember] [DisplayName("LikeFilm")] public bool LikeFilm { get; set; } } public class RateMap : EntityTypeConfiguration<RateInfo>, IEntityTypeConfiguration { public RateMap() { ToTable("Modules_Rates"); HasKey(m => m.Id); Property(m => m.LanguageCode).HasMaxLength(50); Property(m => m.CustomerCode).HasMaxLength(250); Property(m => m.AlertError).HasMaxLength(250); Property(m => m.AlertLag).HasMaxLength(250); Property(m => m.Messages).HasMaxLength(2000); } } } <file_sep># CMS_WatchMovieSite Demo for CMSSolutions <file_sep>using System.ComponentModel; using System.Runtime.Serialization; using CMSSolutions.Data; using CMSSolutions.Data.Entity; namespace CMSSolutions.Websites.Entities { [DataContract] public class FilmServerInfo : BaseEntity<int> { [DataMember] [DisplayName("SiteId")] public int SiteId { get; set; } [DataMember] [DisplayName("LanguageCode")] public string LanguageCode { get; set; } [DataMember] [DisplayName("ServerName")] public string ServerName { get; set; } [DataMember] [DisplayName("ServerIP")] public string ServerIP { get; set; } [DataMember] [DisplayName("FolderRoot")] public string FolderRoot { get; set; } [DataMember] [DisplayName("Locations")] public string Locations { get; set; } [DataMember] [DisplayName("Description")] public string Description { get; set; } [DataMember] [DisplayName("IsVip")] public bool IsVip { get; set; } [DataMember] [DisplayName("IsDefault")] public bool IsDefault { get; set; } [DataMember] [DisplayName("UserName")] public string UserName { get; set; } [DataMember] [DisplayName("Password")] public string Password { get; set; } [DataMember] [DisplayName("Status")] public int Status { get; set; } } public class FilmServerMap : EntityTypeConfiguration<FilmServerInfo>, IEntityTypeConfiguration { public FilmServerMap() { ToTable("Modules_FilmServers"); HasKey(m => m.Id); Property(m => m.LanguageCode).IsRequired().HasMaxLength(50); Property(m => m.SiteId).IsRequired(); Property(m => m.ServerName).HasMaxLength(250).IsRequired(); Property(m => m.ServerIP).HasMaxLength(50).IsRequired(); Property(m => m.Locations).HasMaxLength(250); Property(m => m.IsVip).IsRequired(); Property(m => m.IsDefault).IsRequired(); Property(m => m.UserName).IsRequired().HasMaxLength(400); Property(m => m.Password).IsRequired().HasMaxLength(400); } } } <file_sep>using System.Collections.Generic; using System.Data.SqlClient; using CMSSolutions.Data; using CMSSolutions.Events; using CMSSolutions.Services; using CMSSolutions.Websites.Entities; namespace CMSSolutions.Websites.Services { public interface ITagService : IGenericService<TagInfo, int>, IDependency { bool CheckExist(int id, string keyword); IList<TagInfo> GetPaged(string keyword, int status, int pageIndex, int pageSize, out int totals); IList<TagInfo> GetDisplayTags(); } public class TagService : GenericService<TagInfo, int>, ITagService { public TagService(IRepository<TagInfo, int> repository, IEventBus eventBus) : base(repository, eventBus) { } public bool CheckExist(int id, string keyword) { var list = new List<SqlParameter> { AddInputParameter("@Id", id), AddInputParameter("@Keyword", keyword) }; var result = (int)ExecuteReaderResult("sp_Tags_CheckName", list.ToArray()); return result > 0; } public IList<TagInfo> GetPaged(string keyword, int status, int pageIndex, int pageSize, out int totals) { var list = new List<SqlParameter> { AddInputParameter("@Keyword", keyword), AddInputParameter("@Status", status), AddInputParameter("@PageIndex", pageIndex), AddInputParameter("@PageSize", pageSize) }; return ExecuteReader<TagInfo>("sp_Tags_Search_Paged", "@TotalRecord", out totals, list.ToArray()); } public IList<TagInfo> GetDisplayTags() { return ExecuteReader<TagInfo>("sp_Tags_GetDisplay"); } } }<file_sep>using System.ComponentModel; using System.ComponentModel.DataAnnotations.Schema; using System.Runtime.Serialization; using CMSSolutions.Data; using CMSSolutions.Data.Entity; namespace CMSSolutions.Websites.Entities { [DataContract] public class VastInfo : BaseEntity<int> { [DataMember] [DisplayName("SiteId")] public int SiteId { get; set; } [DataMember] [DisplayName("LanguageCode")] public string LanguageCode { get; set; } [DataMember] [DisplayName("KeyCode")] public string KeyCode { get; set; } [DataMember] [DisplayName("AdId")] public int AdId { get; set; } [NotMapped] [DisplayName("AdName")] public string AdName { get; set; } [DataMember] [DisplayName("AdSystemVersion")] public string AdSystemVersion { get; set; } [DataMember] [DisplayName("AdSystemValue")] public string AdSystemValue { get; set; } [DataMember] [DisplayName("AdTitle")] public string AdTitle { get; set; } [DataMember] [DisplayName("LinkError")] public string LinkError { get; set; } [DataMember] [DisplayName("LinkImpression")] public string LinkImpression { get; set; } [DataMember] [DisplayName("Skipoffset")] public string Skipoffset { get; set; } [DataMember] [DisplayName("Duration")] public string Duration { get; set; } [DataMember] [DisplayName("LinkClickThrough")] public string LinkClickThrough { get; set; } [DataMember] [DisplayName("TrackingEvent1")] public string TrackingEvent1 { get; set; } [DataMember] [DisplayName("TrackingValue1")] public string TrackingValue1 { get; set; } [DataMember] [DisplayName("TrackingEvent2")] public string TrackingEvent2 { get; set; } [DataMember] [DisplayName("TrackingValue2")] public string TrackingValue2 { get; set; } [DataMember] [DisplayName("TrackingEvent3")] public string TrackingEvent3 { get; set; } [DataMember] [DisplayName("TrackingValue3")] public string TrackingValue3 { get; set; } [DataMember] [DisplayName("TrackingEvent4")] public string TrackingEvent4 { get; set; } [DataMember] [DisplayName("TrackingValue4")] public string TrackingValue4 { get; set; } [DataMember] [DisplayName("TrackingEvent5")] public string TrackingEvent5 { get; set; } [DataMember] [DisplayName("TrackingValue5")] public string TrackingValue5 { get; set; } [DataMember] [DisplayName("TrackingEvent6")] public string TrackingEvent6 { get; set; } [DataMember] [DisplayName("TrackingValue6")] public string TrackingValue6 { get; set; } [DataMember] [DisplayName("MediaFileBitrate")] public int MediaFileBitrate { get; set; } [DataMember] [DisplayName("MediaFileDelivery")] public string MediaFileDelivery { get; set; } [DataMember] [DisplayName("MediaFileHeight")] public int MediaFileHeight { get; set; } [DataMember] [DisplayName("MediaFileWidth")] public int MediaFileWidth { get; set; } [DataMember] [DisplayName("MediaFileMaintainAspectRatio")] public bool MediaFileMaintainAspectRatio { get; set; } [DataMember] [DisplayName("MediaFileScalable")] public bool MediaFileScalable { get; set; } [DataMember] [DisplayName("MediaFileType")] public string MediaFileType { get; set; } [DataMember] [DisplayName("MediaFileValue")] public string MediaFileValue { get; set; } } public class VastMap : EntityTypeConfiguration<VastInfo>, IEntityTypeConfiguration { public VastMap() { ToTable("Modules_Vast"); HasKey(m => m.Id); Property(m => m.LanguageCode).HasMaxLength(50); Property(m => m.KeyCode).HasMaxLength(50); Property(m => m.AdSystemVersion).HasMaxLength(50); Property(m => m.AdSystemValue).HasMaxLength(250); Property(m => m.AdTitle).HasMaxLength(250); Property(m => m.LinkError).HasMaxLength(500); Property(m => m.LinkImpression).HasMaxLength(500); Property(m => m.Skipoffset).HasMaxLength(50); Property(m => m.Duration).HasMaxLength(50); Property(m => m.LinkClickThrough).HasMaxLength(500); Property(m => m.TrackingEvent1).HasMaxLength(50); Property(m => m.TrackingValue1).HasMaxLength(500); Property(m => m.TrackingEvent2).HasMaxLength(50); Property(m => m.TrackingValue2).HasMaxLength(500); Property(m => m.TrackingEvent3).HasMaxLength(50); Property(m => m.TrackingValue3).HasMaxLength(500); Property(m => m.TrackingEvent4).HasMaxLength(50); Property(m => m.TrackingValue4).HasMaxLength(500); Property(m => m.TrackingEvent5).HasMaxLength(50); Property(m => m.TrackingValue5).HasMaxLength(500); Property(m => m.TrackingEvent6).HasMaxLength(50); Property(m => m.TrackingValue6).HasMaxLength(500); Property(m => m.MediaFileDelivery).HasMaxLength(50); Property(m => m.MediaFileType).HasMaxLength(50); Property(m => m.MediaFileValue).HasMaxLength(500); } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Web.Mvc; using CMSSolutions.Extensions; using CMSSolutions.Web.Mvc; using CMSSolutions.Web.Routing; using CMSSolutions.Web.Themes; using CMSSolutions.Web.UI.ControlForms; using CMSSolutions.Web.UI.Navigation; using CMSSolutions.Websites.Entities; using CMSSolutions.Websites.Extensions; using CMSSolutions.Websites.Models; using CMSSolutions.Websites.Services; namespace CMSSolutions.Websites.Controllers { [Themed(IsDashboard = true), Authorize] public class AdminSliderController : BaseAdminController { public AdminSliderController(IWorkContextAccessor workContextAccessor) : base(workContextAccessor) { TableName = "tblSlider"; } [Url("admin/slider")] public ActionResult Index() { WorkContext.Breadcrumbs.Add(new Breadcrumb { Text = T("Quản lý slider"), Url = "#" }); var result = new ControlGridFormResult<SliderInfo> { Title = T("Quản lý slider"), CssClass = "table table-bordered table-striped", IsAjaxSupported = true, FetchAjaxSource = GetSlider, UpdateActionName = "Update", ActionsColumnWidth = 100, ClientId = TableName, DefaultPageSize = WorkContext.DefaultPageSize, GridWrapperStartHtml = Constants.Grid.GridWrapperStartHtml, GridWrapperEndHtml = Constants.Grid.GridWrapperEndHtml }; result.AddCustomVar(Extensions.Constants.LanguageCode, "$('#" + Extensions.Constants.LanguageCode + "').val();", true); result.AddCustomVar(Extensions.Constants.SiteId, "$('#" + Extensions.Constants.SiteId + "').val();", true); result.AddCustomVar(Extensions.Constants.PageId, "$('#" + Extensions.Constants.PageId + "').val();", true); result.AddColumn(x => x.OrderBy, T("Vị trí")).AlignCenter().HasWidth(60); result.AddColumn(x => EnumExtensions.GetDisplayName((SliderPages)x.PageId), T("Trang hiển thị")); result.AddColumn(x => x.CategoryName, T("Chuyên mục")); result.AddColumn(x => x.FilmName, T("Tên phim")); result.AddAction().HasText(T("Thêm mới")) .HasUrl(Url.Action("Edit", RouteData.Values.Merge(new { id = 0 }))) .HasButtonStyle(ButtonStyle.Primary) .HasBoxButton(false) .HasCssClass(Constants.RowLeft) .HasRow(true); result.AddAction(new ControlFormHtmlAction(() => BuildLanguages(true, Extensions.Constants.SiteId))).HasParentClass(Constants.ContainerCssClassCol3); result.AddAction(new ControlFormHtmlAction(() => BuildSites(false, null))).HasParentClass(Constants.ContainerCssClassCol3); result.AddAction(new ControlFormHtmlAction(BuildPages)).HasParentClass(Constants.ContainerCssClassCol3); result.AddRowAction() .HasText(T("Sửa")) .HasUrl(x => Url.Action("Edit", RouteData.Values.Merge(new { id = x.Id }))) .HasButtonStyle(ButtonStyle.Default) .HasButtonSize(ButtonSize.ExtraSmall); result.AddRowAction(true) .HasText(T("Xóa")) .HasName("Delete") .HasValue(x => x.Id) .HasButtonStyle(ButtonStyle.Danger) .HasButtonSize(ButtonSize.ExtraSmall) .HasConfirmMessage(T(Constants.Messages.ConfirmDeleteRecord).Text); result.AddReloadEvent("UPDATE_ENTITY_COMPLETE"); result.AddReloadEvent("DELETE_ENTITY_COMPLETE"); return result; } protected ControlGridAjaxData<SliderInfo> GetSlider(ControlGridFormRequest options) { var languageCode = WorkContext.CurrentCulture; if (Utilities.IsNotNull(Request.Form[Extensions.Constants.LanguageCode])) { languageCode = Request.Form[Extensions.Constants.LanguageCode]; } var siteId = 0; if (Utilities.IsNotNull(Request.Form[Extensions.Constants.SiteId])) { siteId = Convert.ToInt32(Request.Form[Extensions.Constants.SiteId]); } var pageId = 0; if (Utilities.IsNotNull(Request.Form[Extensions.Constants.PageId])) { pageId = Convert.ToInt32(Request.Form[Extensions.Constants.PageId]); } int totals; var service = WorkContext.Resolve<ISliderService>(); service.LanguageCode = languageCode; service.SiteId = siteId; var records = service.GetPaged( pageId, options.PageIndex, options.PageSize, out totals); return new ControlGridAjaxData<SliderInfo>(records, totals); } private string BuildPages() { var list = EnumExtensions.GetListItems<SliderPages>(); var sb = new StringBuilder(); sb.AppendFormat(T("Trang hiển thị") + " <select id=\"" + Extensions.Constants.PageId + "\" name=\"" + Extensions.Constants.PageId + "\" autocomplete=\"off\" class=\"uniform form-control col-md-3\" onchange=\"$('#" + TableName + "').jqGrid().trigger('reloadGrid');\">"); foreach (var item in list) { sb.AppendFormat("<option value=\"{1}\">{0}</option>", item.Text, item.Value); } sb.Append("</select>"); return sb.ToString(); } [Url("admin/slider/edit/{id}")] public ActionResult Edit(int id) { WorkContext.Breadcrumbs.Add(new Breadcrumb { Text = T("Quản lý slider"), Url = Url.Action("Index") }); WorkContext.Breadcrumbs.Add(new Breadcrumb { Text = T("Thông tin slider"), Url = "#" }); var model = new SliderModel(); if (id > 0) { var service = WorkContext.Resolve<ISliderService>(); model = service.GetById(id); } var result = new ControlFormResult<SliderModel>(model) { Title = T("Thông tin slider"), FormMethod = FormMethod.Post, UpdateActionName = "Update", SubmitButtonText = T("Lưu lại"), CancelButtonText = T("Đóng"), ShowBoxHeader = false, FormWrapperStartHtml = Constants.Form.FormWrapperStartHtml, FormWrapperEndHtml = Constants.Form.FormWrapperEndHtml }; result.RegisterFileUploadOptions("Images.FileName", new ControlFileUploadOptions { AllowedExtensions = "jpg,jpeg,png,gif" }); result.RegisterExternalDataSource(x => x.LanguageCode, y => BindLanguages()); result.RegisterCascadingDropDownDataSource(x => x.SiteId, Url.Action("GetSitesByLanguage")); result.RegisterCascadingDropDownDataSource(x => x.CategoryId, Url.Action("GetCategoriesBySite")); result.RegisterCascadingDropDownDataSource(x => x.FilmId, Url.Action("GetFilmsByCategory")); result.RegisterExternalDataSource(x => x.PageId, y => BindPages()); return result; } [Url("admin/get-films-by-category")] public ActionResult GetFilmsByCategory() { var languageCode = WorkContext.CurrentCulture; if (Utilities.IsNotNull(Request.Form[Extensions.Constants.LanguageCode])) { languageCode = Request.Form[Extensions.Constants.LanguageCode]; } var siteId = 0; if (Utilities.IsNotNull(Request.Form[Extensions.Constants.SiteId])) { siteId = int.Parse(Request.Form[Extensions.Constants.SiteId]); } var categoryId = 0; if (Utilities.IsNotNull(Request.Form[Extensions.Constants.CategoryId])) { categoryId = int.Parse(Request.Form[Extensions.Constants.CategoryId]); } var service = WorkContext.Resolve<IFilmService>(); service.SiteId = siteId; service.LanguageCode = languageCode; service.CategoryId = categoryId; var items = service.GetAllByCategoryId(); var result = new List<SelectListItem>(); result.AddRange(items.Select(item => new SelectListItem { Text = item.FilmName, Value = item.Id.ToString() })); result.Insert(0, new SelectListItem { Text = "--- Chọn phim ---", Value = "0" }); return Json(result); } private IEnumerable<SelectListItem> BindPages() { var items = EnumExtensions.GetListItems<SliderPages>(); return items; } [HttpPost, ValidateInput(false), FormButton("Save")] [Url("admin/slider/update")] public ActionResult Update(SliderModel model) { var service = WorkContext.Resolve<ISliderService>(); var service2 = WorkContext.Resolve<IFilmService>(); var film = service2.GetById(model.FilmId); SliderInfo item = model.Id == 0 ? new SliderInfo() : service.GetById(model.Id); item.LanguageCode = model.LanguageCode; item.SiteId = model.SiteId; item.CategoryId = model.CategoryId; item.FilmId = model.FilmId; item.Images = model.Images; if (film != null && string.IsNullOrEmpty(model.Images)) { item.Images = film.ImageThumb; } item.PageId = model.PageId; item.OrderBy = model.OrderBy; service.Save(item); return new AjaxResult().NotifyMessage("UPDATE_ENTITY_COMPLETE").Alert(T("Cập nhật thành công!")); } [FormButton("Delete")] [HttpPost, ActionName("Update")] public ActionResult Delete(int id) { var service = WorkContext.Resolve<ISliderService>(); var model = service.GetById(id); service.Delete(model); return new AjaxResult().NotifyMessage("DELETE_ENTITY_COMPLETE"); } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Web.Mvc; using CMSSolutions.ContentManagement.Widgets.Services; using CMSSolutions.DisplayManagement; using CMSSolutions.Web.Mvc; using CMSSolutions.Web.Themes; using CMSSolutions.Websites.Entities; using CMSSolutions.Websites.Extensions; using CMSSolutions.Websites.Models; using CMSSolutions.Websites.Services; namespace CMSSolutions.Websites.Controllers { [Themed(IsDashboard = false)] public class HomeViewController : BaseHomeController { private readonly dynamic shapeFactory; public HomeViewController(IWorkContextAccessor workContextAccessor, IShapeFactory shapeFactory) : base(workContextAccessor) { this.shapeFactory = shapeFactory; } [Url("xem-phim/{alias}/f{id}.html")] public ActionResult FilmView(string alias, long id, int tap = 0, int trang = 1) { UrlLogin = Request.Url != null ? Request.Url.AbsoluteUri : Url.Action("Index", "Home"); SiteId = (int)Site.Home; BuildFilmModules(id, tap, trang); return View("FilmView"); } [HttpPost, ValidateInput(false)] [Url("xem-tap/phan-trang.html")] public ActionResult EpisodesPager() { var pageIndex = Convert.ToInt32(Request.Form["pageIndex"]); var siteId = Convert.ToInt32(Request.Form["siteId"]); var filmId = long.Parse(Request.Form["filmId"]); var pageSize = Convert.ToInt32(Request.Form["pageSize"]); var episodeId = Convert.ToInt32(Request.Form["episodeId"]); int totalRow; var service = WorkContext.Resolve<IFilmService>(); service.LanguageCode = WorkContext.CurrentCulture; service.SiteId = siteId; var model = new DataViewerModel(); var listData = service.GetFilmEpisodes(filmId, pageIndex, pageSize, out totalRow); if (listData != null && listData.Count > 0) { var html = new StringBuilder(); for (int i = 0; i < listData.Count; i ++) { html.Append(BuildItem(listData[i], episodeId, pageIndex)); } model = new DataViewerModel { Status = true, PageSize = pageSize, TotalRow = totalRow, Data = html.ToString() }; } return Json(model); } private void BuildFilmModules(long filmId, int episodeId, int pageIndex) { var widget = WorkContext.Resolve<IWidgetService>(); var viewRenderer = new ViewRenderer { Context = ControllerContext }; if (!IsVip) { #region BannerPageLeft var bannerPageLeft = widget.GetWidget(HomeWidgets.BannerPageLeft.ToString()); if (bannerPageLeft != null) { var widgetShape = shapeFactory.Widget(); widgetShape.Widget = bannerPageLeft; WorkContext.Layout.AdBannerPageLeft(widgetShape); } #endregion #region BannerPageCenter var bannerPageCenter = widget.GetWidget(HomeWidgets.BannerPageCenter.ToString()); if (bannerPageCenter != null) { var widgetShape = shapeFactory.Widget(); widgetShape.Widget = bannerPageCenter; WorkContext.Layout.AdBannerPageCenter(widgetShape); } #endregion #region BannerPageRight var bannerPageRight = widget.GetWidget(HomeWidgets.BannerPageRight.ToString()); if (bannerPageRight != null) { var widgetShape = shapeFactory.Widget(); widgetShape.Widget = bannerPageRight; WorkContext.Layout.AdBannerPageRight(widgetShape); } #endregion } else { #region BannerPageLeftVip var bannerPageLeftVip = widget.GetWidget(HomeWidgets.BannerPageLeftVip.ToString()); if (bannerPageLeftVip != null) { var widgetShape = shapeFactory.Widget(); widgetShape.Widget = bannerPageLeftVip; WorkContext.Layout.AdBannerPageLeftVip(widgetShape); } #endregion #region BannerPageCenterVip var bannerPageCenterVip = widget.GetWidget(HomeWidgets.BannerPageCenterVip.ToString()); if (bannerPageCenterVip != null) { var widgetShape = shapeFactory.Widget(); widgetShape.Widget = bannerPageCenterVip; WorkContext.Layout.AdBannerPageCenterVip(widgetShape); } #endregion #region BannerPageRightVip var bannerPageRightVip = widget.GetWidget(HomeWidgets.BannerPageRightVip.ToString()); if (bannerPageRightVip != null) { var widgetShape = shapeFactory.Widget(); widgetShape.Widget = bannerPageRightVip; WorkContext.Layout.AdBannerPageRightVip(widgetShape); } #endregion } var model = new DataViewerModel(); model.CustomerCode = CustomerCode; #region HomeSliderBanner var service = WorkContext.Resolve<IFilmService>(); service.LanguageCode = WorkContext.CurrentCulture; service.SiteId = SiteId; model.Skin = Extensions.Constants.JWplayerSkin; model.JwplayerKey = Extensions.Constants.JWplayerKey; model.FilmDetails = service.GetFilmsMovie(filmId, episodeId) ?? service.GetFilmDetails(filmId); model.DataType = (int)LinkType.Streaming; var trailer = service.GetTrailerMovie(filmId); if (trailer != null) { model.Url = trailer.EncodeSourceUrl; } ViewData[Extensions.Constants.HeaderTitle] = model.FilmDetails.FilmName; ViewData[Extensions.Constants.HeaderDescription] = model.FilmDetails.Description; ViewData[Extensions.Constants.HeaderKeywords] = model.FilmDetails.Tags; service.UpdateViewCount(model.FilmDetails.Id); var advertisementService = WorkContext.Resolve<IAdvertisementGroupService>(); model.Advertisement = advertisementService.GetAdByCategories(WorkContext.CurrentCulture, SiteId, model.FilmDetails.CategoryIds); model.AdvertisementsPath = Convert.ToBase64String(Encoding.UTF8.GetBytes("/")); if (model.Advertisement != null) { model.AdvertisementsPath = model.Advertisement.EncodeFullPath; } if (!string.IsNullOrEmpty(model.FilmDetails.UrlAlbum)) { model.DataType = (int)LinkType.Picasa; var picasaService = new PicasaService(); model.ListFilmsPicasa = picasaService.ParseRssFile(model.FilmDetails.UrlAlbum, model.FilmDetails.UrlSource); } if (model.FilmDetails.IsClip) { model.DataType = (int)LinkType.Youtube; model.Url = model.FilmDetails.EncodeSourceUrl; } var viewSliderBanner = viewRenderer.RenderPartialView(Extensions.Constants.MoviesFilePath, model); WorkContext.Layout.SliderBanner.Add(new MvcHtmlString(viewSliderBanner)); #endregion #region CategoryContentLeftFirst model.SliderName = "ShowListEpisodes"; if (model.FilmDetails.IsFilmLengthEpisodes) { model.IsShow = true; } if (model.FilmDetails.IsFilm && model.FilmDetails.IsFilmLengthEpisodes) { model.Title = "Tập phim:"; } if (model.FilmDetails.IsShow && model.FilmDetails.IsFilmLengthEpisodes) { model.Title = "Tập show:"; } model.EpisodeId = model.FilmDetails.EpisodeId; model.SiteId = SiteId; model.PageSize = 99999; model.PageIndex = 1; var totalRow = 0; var listData = service.GetFilmEpisodes(filmId, 1, 99999, out totalRow); if (listData != null && listData.Count > 0) { var html = new StringBuilder(); for (int i = 0; i < listData.Count; i++) { html.Append(BuildItem2(listData[i], episodeId, pageIndex)); } model.Status = true; model.PageSize = 99999; model.TotalRow = totalRow; model.Data = html.ToString(); } var viewFirst = viewRenderer.RenderPartialView(Extensions.Constants.ListMoviesViewFilePath, model); WorkContext.Layout.CategoryContentLeftFirst.Add(new MvcHtmlString(viewFirst)); #endregion var viewModel = new DataViewCategoryModel(); viewModel.UrlNext = "http://" + Extensions.Constants.HomeDomainName + Url.Action("FilmView", "HomeView", new { @alias = model.FilmDetails.FilmAlias, @id = model.FilmDetails.Id, @tap = model.FilmDetails.EpisodeId }); #region CategoryContentLeftSecond var viewCommentSecond = viewRenderer.RenderPartialView(Extensions.Constants.FacebookCommentsFilePath, viewModel); WorkContext.Layout.CategoryContentLeftSecond.Add(new MvcHtmlString(viewCommentSecond)); #endregion #region CategoryContentFirst var modelFirst = new DataViewCategoryModel { Type = (int)HomeDisplayFilmType.FilmHot, Title = "Sự kiện: Phim Đang HOT", TextNext = "Còn nữa ››", UrlNext = Url.Action("FilmHot", "HomeCategory"), SliderName = "FilmFirst" }; modelFirst.HtmlFilmHot = GetFilmHtml(modelFirst.Type); var viewFilmFirst = viewRenderer.RenderPartialView(Extensions.Constants.CategoryContentFirstViewFilePath, modelFirst); WorkContext.Layout.CategoryContentLeftThird.Add(new MvcHtmlString(viewFilmFirst)); #endregion #region BannerRightFirst viewModel.FilmDetails = model.FilmDetails; viewModel.Breadcrumb = BuildBreadcrumb(Utilities.ParseListInt(model.FilmDetails.CategoryIds)[0], model.FilmDetails); var bannerRightFirst = viewRenderer.RenderPartialView(Extensions.Constants.FilmRateFilePath, viewModel); WorkContext.Layout.AdBannerRightFirst.Add(new MvcHtmlString(bannerRightFirst)); #endregion #region DisplayStatistic3 var modelStatistic3 = new DataViewCategoryModel { Type = (int)HomeDisplayFilmType.StatisticalNextFilm, Title = "PHIM LIÊN QUAN", FilmDetails = model.FilmDetails }; if (model.FilmDetails.IsClip) { modelStatistic3.Title = "CLIP LIÊN QUAN"; } if (model.FilmDetails.IsShow) { modelStatistic3.Title = "SHOW LIÊN QUAN"; } if (model.FilmDetails.IsTrailer) { modelStatistic3.Title = "TRAILER LIÊN QUAN"; } var viewStatistic3 = viewRenderer.RenderPartialView(Extensions.Constants.Statistic6FilePath, modelStatistic3); WorkContext.Layout.DisplayStatistic1.Add(new MvcHtmlString(viewStatistic3)); #endregion } private string BuildBreadcrumb(int cateId, FilmInfo film) { var serviceCategory = WorkContext.Resolve<ICategoryService>(); serviceCategory.LanguageCode = WorkContext.CurrentCulture; serviceCategory.SiteId = SiteId; CategoryInfo category = serviceCategory.GetByIdCache(cateId); var html = new StringBuilder(); html.Append("<div class=\"mh-breadcrumb-dv\">"); html.Append("<div>"); html.AppendFormat("<a title=\"{0}\" href=\"{1}\"><span><img width=\"22\" src=\"/Images/themes/ico-homesm.png\"></span></a>", "Dành cho víp", "/"); html.Append("</div>/ "); if (category.ParentId > 0) { var parent = serviceCategory.GetByIdCache(category.ParentId); html.Append("<div>"); html.AppendFormat("<a title=\"{0}\" href=\"{1}\"><span>{0}</span></a>", parent.ShortName, Url.Action("Index", "HomeCategory", new { @alias = parent.Alias, @id = parent.Id })); html.Append("</div>/ "); } html.Append("<div>"); html.AppendFormat("<a title=\"{0}\" href=\"{1}\"><span>{0}</span></a>", category.ShortName, "#"); html.Append("</div>"); html.AppendFormat("<h1 class=\"title_h1_st3\">{0}</h1>", film.FilmName); html.AppendFormat("<p>{0}</p>", film.Summary); html.Append("</div>"); return html.ToString(); } private string BuildItem(FilmInfo item, int episodeId, int trang) { var url = Url.Action("FilmView", "HomeView", new { @alias = item.FilmAlias, @id = item.Id, @tap = item.EpisodeId, @trang = trang }); var html = new StringBuilder(); if (episodeId == item.EpisodeId) { html.Append("<div class=\"show_tv-epi-img film-actived\">"); } else { html.Append("<div class=\"show_tv-epi-img\">"); } html.AppendFormat("<a href=\"{0}\" title=\"{1}\">", url, item.FilmName); html.AppendFormat("<img alt=\"{0}\" width=\"106\" height=\"80\" src=\"{1}\">", item.FilmAlias, item.ImageIcon); html.AppendFormat("<span class=\"epi_span\">{0}</span>", item.EpisodeName); html.Append("</a>"); html.Append(" </div>"); return html.ToString(); } private string BuildItem2(FilmInfo item, int episodeId, int trang) { var url = Url.Action("FilmView", "HomeView", new { @alias = item.FilmAlias, @id = item.Id, @tap = item.EpisodeId, @trang = trang }); var html = new StringBuilder(); html.AppendFormat("<a href=\"{0}\" title=\"{1}\">", url, item.FilmName); if (episodeId == item.EpisodeId) { html.Append("<div class=\"show_tv-epi-img film-actived\">"); } else { html.Append("<div class=\"show_tv-epi-img\">"); } html.AppendFormat("<span class=\"epi_span\">{0}</span>", item.EpisodeIndex); html.Append(" </div>"); html.Append("</a>"); return html.ToString(); } } } <file_sep>using CMSSolutions.Web.UI.ControlForms; using CMSSolutions.Websites.Entities; namespace CMSSolutions.Websites.Models { public class CustomerHistoriesModel { [ControlHidden()] public long Id { get; set; } [ControlNumeric(LabelText="Customer Id", Order=0, Required=true)] public int CustomerId { get; set; } [ControlDatePicker(LabelText="Create Date", Order=0, Required=true)] public System.DateTime CreateDate { get; set; } [ControlText(Required=true, MaxLength=250)] public string Action { get; set; } [ControlText(Required=true, MaxLength=2000)] public string Description { get; set; } [ControlNumeric(LabelText="Status", Order=0, Required=false)] public int Status { get; set; } public static implicit operator CustomerHistoriesModel(CustomerHistoriesInfo entity) { return new CustomerHistoriesModel { Id = entity.Id, CustomerId = entity.CustomerId, CreateDate = entity.CreateDate, Action = entity.Action, Description = entity.Description, Status = entity.Status }; } } } <file_sep>using CMSSolutions.Web.UI.ControlForms; using CMSSolutions.Websites.Entities; namespace CMSSolutions.Websites.Models { public class LogModel { [ControlHidden] public long Id { get; set; } [ControlText(LabelText = "Ngày tạo", ContainerCssClass = Constants.ContainerCssClassCol4, ContainerRowIndex = 0)] public string TextCreateDate { get; set; } [ControlChoice(ControlChoice.DropDownList, Required = true, LabelText = "Loại", ContainerCssClass = Constants.ContainerCssClassCol4, ContainerRowIndex = 0)] public int Type { get; set; } [ControlChoice(ControlChoice.DropDownList, Required = true, LabelText = "Trạng thái", ContainerCssClass = Constants.ContainerCssClassCol4, ContainerRowIndex = 0)] public int Status { get; set; } [ControlText(LabelText = "Thực hiện bởi", Type = ControlText.TextBox, ContainerCssClass = Constants.ContainerCssClassCol12, ContainerRowIndex = 1)] public string Keyword { get; set; } [ControlText(LabelText = "Thông báo", Type = ControlText.MultiText, Rows = 3, ContainerCssClass = Constants.ContainerCssClassCol12, ContainerRowIndex = 2)] public string Messages { get; set; } [ControlText(LabelText = "Nội dung thực hiện", Type = ControlText.MultiText, Rows = 2, ContainerCssClass = Constants.ContainerCssClassCol12, ContainerRowIndex = 3)] public string Contents { get; set; } public static implicit operator LogModel(LogInfo entity) { return new LogModel { Id = entity.Id, TextCreateDate = entity.TextCreateDate, Type = entity.Type, Messages = entity.Messages, Contents = entity.Contents, Keyword = entity.Keyword, Status = entity.Status }; } } }<file_sep>using System.ComponentModel; using System.Runtime.Serialization; using CMSSolutions.Data; using CMSSolutions.Data.Entity; namespace CMSSolutions.Websites.Entities { [DataContract] public class SupportInfo : BaseEntity<int> { [DataMember] [DisplayName("SiteId")] public int SiteId { get; set; } [DataMember] [DisplayName("LanguageCode")] public string LanguageCode { get; set; } [DataMember] [DisplayName("Title")] public string Title { get; set; } [DataMember] [DisplayName("Messages")] public string Messages { get; set; } [DataMember] [DisplayName("IsGroup")] public bool IsGroup { get; set; } [DataMember] [DisplayName("OrderBy")] public int OrderBy { get; set; } [DataMember] [DisplayName("Status")] public int Status { get; set; } [DataMember] [DisplayName("ParentId")] public int ParentId { get; set; } } public class SupportMap : EntityTypeConfiguration<SupportInfo>, IEntityTypeConfiguration { public SupportMap() { ToTable("Modules_Supports"); HasKey(x => x.Id); Property(x => x.LanguageCode).HasMaxLength(50).IsRequired(); Property(x => x.Title).IsRequired().HasMaxLength(250); Property(x => x.Messages).HasMaxLength(2000); } } }<file_sep>using System; namespace CMSSolutions.Websites.Entities { public class PicasaInfo { public string Medium { get; set; } public string Url { get; set; } public string Type { get; set; } public int Width { get; set; } public int Height { get; set; } public string EncodeUrl { get { if (!string.IsNullOrEmpty(Url)) { return Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes(Url)); } return string.Empty; } } } }<file_sep>using CMSSolutions.Data; using CMSSolutions.Events; using CMSSolutions.Services; using CMSSolutions.Websites.Entities; namespace CMSSolutions.Websites.Services { public interface ICityService : IGenericService<CityInfo, int>, IDependency { } public class CityService : GenericService<CityInfo, int>, ICityService { public CityService(IRepository<CityInfo, int> repository, IEventBus eventBus) : base(repository, eventBus) { } } }<file_sep>using System; using System.Web; using CMSSolutions.Websites.Entities; using CMSSolutions.Websites.Extensions; using CMSSolutions.Websites.Payments; using CMSSolutions.Websites.Services; namespace CMSSolutions.Websites.API { public class SmsService : IHttpHandler { public void ProcessRequest(HttpContext context) { context.Response.ContentType = "text/html"; string partnerid = context.Request["partnerid"]; string moid = context.Request["moid"]; string userid = context.Request["userid"]; string shortcode = context.Request["shortcode"]; string keyword = context.Request["keyword"]; string subkeyword = context.Request["subkeyword"]; string content = context.Request["content"]; string transdate = context.Request["transdate"]; string checksum = context.Request["checksum"]; string amount = context.Request["amount"]; var service = new APISmsService(); var request = new APISms(); string url = request.UrlSMSMT; var transactionCode = Utilities.GenerateUniqueNumber(); var code = HttpUtility.UrlDecode(content); var entityMO = new TransactionSmsInfo { Id = 0, PartnerId = partnerid, MoId = moid, UserId = userid, ShortCode = shortcode, Keyword = keyword, Subkeyword = subkeyword, Content = content, TransDate = transdate, CheckSum = checksum, Amount = amount, CreateDate = DateTime.Now, Status = (int)RequestStatus.Messages01, Type = (int)SMSType.MO, MtId = "", CustomerCode = "", TransactionCode = transactionCode, StartDate = new DateTime(1900,01,01), EndDate = new DateTime(1900, 01, 01), IsLock = false }; try { LogFiles.WriteLogSms(string.Format("MO URL: {0}", context.Request.Url.AbsoluteUri)); service.InsertLog(new LogInfo { CreateDate = DateTime.Now, Messages = string.Format("MO URL: {0}", context.Request.Url.AbsoluteUri), Keyword = userid, Contents = code + " " + shortcode, Type = (int)LogType.SMS, Status = (int)LogStatus.Information }); int totalDate; DateTime? startDate; DateTime? endDate; var totalMoney = service.Amount(shortcode, out totalDate, out startDate, out endDate); entityMO.TotalDay = totalDate; entityMO.StartDate = startDate; entityMO.EndDate = endDate; var list = code.Split(' '); if (list.Length <= 1) { LogFiles.WriteLogSms(string.Format("MO: CUSTOMERCODE NOT FOUND IN CONTENT: {0}", content)); entityMO.IsLock = true; service.SmsProcessing(entityMO); request.SentMT(moid, shortcode, keyword, userid, string.Format(Extensions.Constants.SMSCustomerNotFound , transactionCode), ref url); service.InsertLog(new LogInfo { CreateDate = DateTime.Now, Messages = string.Format("MO: CUSTOMERCODE NOT FOUND IN CONTENT: {0}", content), Keyword = userid, Contents = code + " " + shortcode, Type = (int)LogType.SMS, Status = (int)LogStatus.Error }); context.Response.Write(string.Format("message:requeststatus=200")); return; } var helpKey = list[1].Trim().ToUpper(); var customerCode = list[1]; var rejectShortCode = (ShortCode)int.Parse(shortcode); if (rejectShortCode == ShortCode.DauSo8376 && helpKey.ToUpper() == "HD") { LogFiles.WriteLogSms(string.Format("MO: HELP USER: {0}", Extensions.Constants.SMSUserHelp)); service.SmsProcessing(entityMO); request.SentMT(moid, shortcode, keyword, userid, Extensions.Constants.SMSUserHelp, ref url); service.InsertLog(new LogInfo { CreateDate = DateTime.Now, Messages = string.Format("MO: HELP USER: {0}", Extensions.Constants.SMSUserHelp), Keyword = userid, Contents = code + " " + shortcode, Type = (int)LogType.SMS, Status = (int)LogStatus.Error }); context.Response.Write(string.Format("message:requeststatus=200")); return; } var customer = service.GetByCustomerCode(customerCode); if (customer == null) { entityMO.IsLock = true; service.SmsProcessing(entityMO); request.SentMT(moid, shortcode, keyword, userid, string.Format(Extensions.Constants.SMSCustomerNotFound, transactionCode), ref url); service.InsertLog(new LogInfo { CreateDate = DateTime.Now, Messages = string.Format("MO: CUSTOMERCODE NOT FOUND: {0}", customerCode), Keyword = userid, Contents = code + " " + shortcode, Type = (int)LogType.SMS, Status = (int)LogStatus.Error }); LogFiles.WriteLogSms(string.Format("SYSTEM SAVE SUCCESS")); context.Response.Write(string.Format("message:requeststatus=200")); return; } var currentSum = request.Md5(moid + shortcode + keyword + content + transdate + request.Password).ToLower(); if (checksum.Length != currentSum.Length) { LogFiles.WriteLogSms(string.Format("MO: CHECKSUM FAILED {0} - {1}", checksum.Length, currentSum.Length)); service.SmsProcessing(entityMO); request.SentMT(moid, shortcode, keyword, userid, Extensions.Constants.SMSSyntax, ref url); service.InsertLog(new LogInfo { CreateDate = DateTime.Now, Messages = string.Format("MO: CHECKSUM FAILED {0} - {1}", checksum.Length, currentSum.Length), Keyword = userid, Contents = code + " " + shortcode, Type = (int)LogType.SMS, Status = (int)LogStatus.Error }); context.Response.Write(string.Format("message:requeststatus=200")); return; } if (rejectShortCode != ShortCode.DauSo8576 && rejectShortCode != ShortCode.DauSo8676 && rejectShortCode != ShortCode.DauSo8776) { LogFiles.WriteLogSms(string.Format("MO: SHORTCODE {0}", shortcode)); request.SentMT(moid, shortcode, keyword, userid, Extensions.Constants.SMSSyntax, ref url); service.InsertLog(new LogInfo { CreateDate = DateTime.Now, Messages = string.Format("MO: SHORTCODE {0}", shortcode), Keyword = userid, Contents = code + " " + shortcode, Type = (int)LogType.SMS, Status = (int)LogStatus.Error }); context.Response.Write(string.Format("message:requeststatus=200")); return; } var status = Send(url, moid, userid, shortcode, keyword, entityMO.Amount, subkeyword, transdate, checksum, customer, totalDate, startDate, endDate, transactionCode); if (status == RequestStatus.Messages200) { entityMO.Amount = totalMoney; entityMO.Status = (int)RequestStatus.Messages200; entityMO.CustomerCode = customer.CustomerCode; service.SmsProcessing(entityMO); } else { entityMO.Status = (int)RequestStatus.Messages01; service.SmsProcessing(entityMO); } LogFiles.WriteLogSms(string.Format("MO INSERT: {0} SUCCESSFUL", (int)status)); service.InsertLog(new LogInfo { CreateDate = DateTime.Now, Messages = string.Format("MO: INSERT: {0} SUCCESSFUL", (int)status), Keyword = userid, Contents = code + " " + shortcode, Type = (int)LogType.SMS, Status = (int)LogStatus.Information }); context.Response.Write(string.Format("message:requeststatus=200")); } catch (Exception ex) { entityMO.Status = (int)RequestStatus.Messages01; service.SmsProcessing(entityMO); var st = request.SentMT(moid, shortcode, keyword, userid, Extensions.Constants.SMSSystemError, ref url); LogFiles.WriteLogSms(string.Format("Error: {0} - {1} ", ex.Message, st)); service.InsertLog(new LogInfo { CreateDate = DateTime.Now, Messages = string.Format("Error: {0}", ex.Message), Keyword = userid, Contents = code + " " + shortcode, Type = (int)LogType.SMS, Status = (int)LogStatus.Error }); context.Response.Write(string.Format("message:requeststatus=200")); } } private RequestStatus Send(string url, string moid, string userid, string shortcode, string keyword, string amount, string subkeyword, string transdate, string checksum, CustomerInfo customer, int totalDate, DateTime? startDate, DateTime? endDate, string transactionCode) { var service = new APISmsService(); var request = new APISms(); var messages = string.Format("VIPHD.VN: Xin chuc mung ban da dang ky thanh cong goi tai tro {0} ngay cho tai khoan {1} tren VIPHD! Chan thanh cam on!", totalDate, customer.CustomerCode); var status = (RequestStatus)request.SentMT(moid, shortcode, keyword, userid, messages, ref url); LogFiles.WriteLogSms(string.Format("Day: {0} - StartDate: {1} - EndDate: {2} - MT URL - {3}: {4}", totalDate, startDate != null ? startDate.Value.ToString() : "", endDate != null ? endDate.Value.ToString() : "", url, customer.CustomerCode)); service.InsertLog(new LogInfo { CreateDate = DateTime.Now, Messages = string.Format("MT: REQUEST SUCCESSFUL: Day: {0} - StartDate: {1} - EndDate: {2} - CUSTOMERCODE: {3} - MT URL - {4}", totalDate, startDate != null ? startDate.Value.ToString() : "", endDate != null ? endDate.Value.ToString() : "", customer.CustomerCode, url), Keyword = userid, Contents = keyword + " " + shortcode, Type = (int)LogType.SMS, Status = (int)LogStatus.Success }); var entityMT = new TransactionSmsInfo { Id = 0, PartnerId = request.PartnerId, MoId = moid, MtId = request.CreateMTId(), UserId = userid, ShortCode = shortcode, Keyword = keyword, Subkeyword = subkeyword, Content = messages, CreateDate = DateTime.Now, Status = (int)status, Type = (int)SMSType.MT, TransDate = transdate, CheckSum = checksum, Amount = amount, CustomerCode = customer.CustomerCode, TotalDay = totalDate, StartDate = startDate, EndDate = endDate, TransactionCode = transactionCode }; service.SmsProcessing(entityMT); service.InsertLog(new LogInfo { CreateDate = DateTime.Now, Messages = string.Format("MT: INSERT {0} SUCCESSFUL", (int)status), Keyword = userid, Contents = keyword + " " + shortcode, Type = (int)LogType.SMS, Status = (int)LogStatus.Information }); return status; } public bool IsReusable { get { return false; } } } }<file_sep>using System; using System.ComponentModel; using System.ComponentModel.DataAnnotations.Schema; using System.Runtime.Serialization; using CMSSolutions.Data; using CMSSolutions.Data.Entity; namespace CMSSolutions.Websites.Entities { [DataContract] public class PromotionCustomerInfo : BaseEntity<long> { [DataMember] [DisplayName("PromotionId")] public int PromotionId { get; set; } [NotMapped] [DisplayName("Title")] public string Title { get; set; } [DataMember] [DisplayName("CustomerId")] public int CustomerId { get; set; } [DataMember] [DisplayName("CustomerCode")] public string CustomerCode { get; set; } [NotMapped] [DisplayName("FullName")] public string FullName { get; set; } [DataMember] [DisplayName("CreateDate")] public DateTime CreateDate { get; set; } [DataMember] [DisplayName("Code")] public string Code { get; set; } [DataMember] [DisplayName("Value")] public string Value { get; set; } [DataMember] [DisplayName("Description")] public string Description { get; set; } [DataMember] [DisplayName("IsUsed")] public bool IsUsed { get; set; } [DataMember] [DisplayName("UsedDate")] public DateTime? UsedDate { get; set; } [DataMember] [DisplayName("IsSendMessages")] public bool IsSendMessages { get; set; } [DataMember] [DisplayName("SendDate")] public DateTime? SendDate { get; set; } } public class PromotionCustomerMap : EntityTypeConfiguration<PromotionCustomerInfo>, IEntityTypeConfiguration { public PromotionCustomerMap() { ToTable("Modules_PromotionCustomers"); HasKey(m => m.Id); Property(m => m.CustomerCode).IsRequired().HasMaxLength(50); Property(m => m.Code).IsRequired().HasMaxLength(50); Property(m => m.Value).IsRequired().HasMaxLength(50); Property(m => m.PromotionId).IsRequired(); Property(m => m.CustomerId).IsRequired(); } } }<file_sep>using System; using System.Web.Mvc; using CMSSolutions.Web.Mvc; using CMSSolutions.Web.Routing; using CMSSolutions.Web.Themes; using CMSSolutions.Web.UI.ControlForms; using CMSSolutions.Web.UI.Navigation; using CMSSolutions.Websites.Entities; using CMSSolutions.Websites.Extensions; using CMSSolutions.Websites.Models; using CMSSolutions.Websites.Services; namespace CMSSolutions.Websites.Controllers { [Themed(IsDashboard = true), Authorize] public class AdminTagController : BaseAdminController { public AdminTagController(IWorkContextAccessor workContextAccessor) : base(workContextAccessor) { TableName = "tblTags"; } [Url("admin/tags")] public ActionResult Index() { WorkContext.Breadcrumbs.Add(new Breadcrumb { Text = T("Quản lý tags"), Url = "#" }); var result = new ControlGridFormResult<TagInfo> { Title = T("Quản lý tags"), CssClass = "table table-bordered table-striped", IsAjaxSupported = true, FetchAjaxSource = GetTags, UpdateActionName = "Update", ActionsColumnWidth = 100, ClientId = TableName, EnablePaginate = true, DefaultPageSize = WorkContext.DefaultPageSize, GridWrapperStartHtml = Constants.Grid.GridWrapperStartHtml, GridWrapperEndHtml = Constants.Grid.GridWrapperEndHtml }; result.AddCustomVar(Extensions.Constants.SearchText, "$('#" + Extensions.Constants.SearchText + "').val();", true); result.AddCustomVar(Extensions.Constants.StatusId, "$('#" + Extensions.Constants.StatusId + "').val();", true); result.AddColumn(x => x.Id, T("ID")).AlignCenter().HasWidth(60); result.AddColumn(x => x.Name, T("Tiêu đề")); result.AddColumn(x => x.Alias, T("Tên không dấu")); result.AddColumn(x => x.IsDisplay) .HasHeaderText(T("Hiển thị")) .AlignCenter() .HasWidth(100) .RenderAsStatusImage(); result.AddAction().HasText(T("Thêm mới")) .HasUrl(Url.Action("Edit", RouteData.Values.Merge(new { id = 0 }))) .HasButtonStyle(ButtonStyle.Primary) .HasBoxButton(false) .HasCssClass(Constants.RowLeft) .HasRow(true) .ShowModalDialog(); result.AddAction(new ControlFormHtmlAction(BuildSearchText)).HasParentClass(Constants.ContainerCssClassCol3); result.AddAction(new ControlFormHtmlAction(BuildStatus)).HasParentClass(Constants.ContainerCssClassCol3); result.AddRowAction() .HasText(T("Sửa")) .HasUrl(x => Url.Action("Edit", RouteData.Values.Merge(new { id = x.Id }))) .HasButtonStyle(ButtonStyle.Default) .HasButtonSize(ButtonSize.ExtraSmall) .ShowModalDialog(); result.AddRowAction(true) .HasText(T("Xóa")) .HasName("Delete") .HasValue(x => x.Id) .HasButtonStyle(ButtonStyle.Danger) .HasButtonSize(ButtonSize.ExtraSmall) .HasConfirmMessage(T(Constants.Messages.ConfirmDeleteRecord).Text); result.AddReloadEvent("UPDATE_ENTITY_COMPLETE"); result.AddReloadEvent("DELETE_ENTITY_COMPLETE"); return result; } private ControlGridAjaxData<TagInfo> GetTags(ControlGridFormRequest options) { var searchText = string.Empty; if (Utilities.IsNotNull(Request.Form[Extensions.Constants.SearchText])) { searchText = Request.Form[Extensions.Constants.SearchText]; } var status = -1; if (Utilities.IsNotNull(Request.Form[Extensions.Constants.StatusId])) { var display = Convert.ToInt32(Request.Form[Extensions.Constants.StatusId]); if (display == (int)Status.Approved) { status = 1; } else { status = 0; } } int totals; var items = WorkContext.Resolve<ITagService>().GetPaged(searchText,status, options.PageIndex, options.PageSize, out totals); var result = new ControlGridAjaxData<TagInfo>(items, totals); return result; } [Themed(false)] [Url("admin/tags/edit/{id}")] public ActionResult Edit(int id) { WorkContext.Breadcrumbs.Add(new Breadcrumb { Text = T("Quản lý tags"), Url = Url.Action("Index") }); WorkContext.Breadcrumbs.Add(new Breadcrumb { Text = T("Thông tin tags"), Url = "#" }); var service = WorkContext.Resolve<ITagService>(); var model = new TagModel(); if (id > 0) { model = service.GetById(id); } var result = new ControlFormResult<TagModel>(model) { Title = T("Thông tin tags"), FormMethod = FormMethod.Post, UpdateActionName = "Update", SubmitButtonText = T("Lưu lại"), ShowCancelButton = true, ShowBoxHeader = false, CancelButtonText = T("Đóng"), FormWrapperStartHtml = Constants.Form.FormWrapperStartHtml, FormWrapperEndHtml = Constants.Form.FormWrapperEndHtml }; result.MakeReadOnlyProperty(x => x.Alias); return result; } [HttpPost, ValidateInput(false), FormButton("Save")] [Url("admin/tags/update")] public ActionResult Update(TagModel model) { if (!ModelState.IsValid) { return new AjaxResult().Alert(T(Constants.Messages.InvalidModel)); } var service = WorkContext.Resolve<ITagService>(); TagInfo item = model.Id == 0 ? new TagInfo() : service.GetById(model.Id); if (service.CheckExist(model.Id, model.Name)) { return new AjaxResult() .NotifyMessage("UPDATE_ENTITY_COMPLETE") .Alert(T("Tiêu đề đã tồn tại!")); } var alias = Utilities.GetCharUnsigned(model.Name); if (service.CheckExist(model.Id, alias)) { return new AjaxResult() .NotifyMessage("UPDATE_ENTITY_COMPLETE") .Alert(T("Tên không dấu đã tồn tại!")); } item.Alias = Utilities.GetAlias(model.Name); item.Name = model.Name; item.IsDisplay = model.IsDisplay; service.Save(item); return new AjaxResult() .NotifyMessage("UPDATE_ENTITY_COMPLETE") .Alert(T("Cập nhật thành công!")) .CloseModalDialog(); } [FormButton("Delete")] [HttpPost, ActionName("Update")] public ActionResult Delete(int id) { var service = WorkContext.Resolve<ITagService>(); var item = service.GetById(id); item.IsDisplay = false; service.Update(item); return new AjaxResult() .NotifyMessage("DELETE_ENTITY_COMPLETE") .Alert(T("Dữ liệu chuyển trạng thái xóa tạm thời!")); } } } <file_sep>using System.ComponentModel; using System.Runtime.Serialization; using CMSSolutions.Data; using CMSSolutions.Data.Entity; namespace CMSSolutions.Websites.Entities { [DataContract] public class BankCardInfo : BaseEntity<int> { [DataMember] [DisplayName("BankCode")] public string BankCode { get; set; } [DataMember] [DisplayName("BankName")] public string BankName { get; set; } [DataMember] [DisplayName("Status")] public int Status { get; set; } } public class BankCardMap : EntityTypeConfiguration<BankCardInfo>, IEntityTypeConfiguration { public BankCardMap() { ToTable("Modules_BankCards"); HasKey(m => m.Id); Property(m => m.BankCode).IsRequired().HasMaxLength(50); Property(m => m.BankName).IsRequired().HasMaxLength(250); } } } <file_sep>using System.Web.Mvc; using CMSSolutions.Web.Mvc; using CMSSolutions.Web.Routing; using CMSSolutions.Web.Themes; using CMSSolutions.Web.UI.ControlForms; using CMSSolutions.Web.UI.Navigation; using CMSSolutions.Websites.Entities; using CMSSolutions.Websites.Extensions; using CMSSolutions.Websites.Models; using CMSSolutions.Websites.Services; namespace CMSSolutions.Websites.Controllers { [Themed(IsDashboard = true), Authorize] public class AdminDownloadGamesController : BaseAdminController { public AdminDownloadGamesController(IWorkContextAccessor workContextAccessor) : base(workContextAccessor) { TableName = "tblDownloadGames"; } [Url("admin/download-games")] public ActionResult Index() { WorkContext.Breadcrumbs.Add(new Breadcrumb { Text = T("Sự kiện đào xu"), Url = "#" }); var result = new ControlGridFormResult<DownloadGameInfo> { Title = T("Sự kiện đào xu"), CssClass = "table table-bordered table-striped", IsAjaxSupported = true, FetchAjaxSource = GetDownloadGames, DefaultPageSize = WorkContext.DefaultPageSize, EnablePaginate = true, UpdateActionName = "Update", GridWrapperStartHtml = Constants.Grid.GridWrapperStartHtml, GridWrapperEndHtml = Constants.Grid.GridWrapperEndHtml, ClientId = TableName, ActionsColumnWidth = 100 }; result.AddCustomVar(Extensions.Constants.SearchText, "$('#" + Extensions.Constants.SearchText + "').val();", true); result.AddColumn(x => x.Id, T("Mã")).HasWidth(60); result.AddColumn(x => x.Logo, T("Logo")) .AlignCenter() .HasWidth(100) .RenderAsImage(y => y.Logo, Extensions.Constants.CssThumbsSize); result.AddColumn(x => x.Title, T("Tiêu đề")); result.AddColumn(x => x.VipXu, T("VIPXU")); result.AddColumn(x => x.IsActived) .HasHeaderText(T("Đã sử dụng")) .AlignCenter() .HasWidth(100) .RenderAsStatusImage(true); result.AddAction().HasText(T("Thêm mới")) .HasUrl(Url.Action("Edit", RouteData.Values.Merge(new { id = 0 }))) .HasButtonStyle(ButtonStyle.Primary) .HasBoxButton(false) .HasCssClass(Constants.RowLeft) .HasRow(true); result.AddAction(new ControlFormHtmlAction(BuildSearchText)).HasParentClass(Constants.ContainerCssClassCol3); result.AddRowAction() .HasText(T("Sửa")) .HasUrl(x => Url.Action("Edit", RouteData.Values.Merge(new { id = x.Id }))) .HasButtonStyle(ButtonStyle.Default) .HasButtonSize(ButtonSize.ExtraSmall); result.AddRowAction(true) .HasText(T("Xóa")) .HasName("Delete") .HasValue(x => x.Id) .HasButtonStyle(ButtonStyle.Danger) .HasButtonSize(ButtonSize.ExtraSmall) .HasConfirmMessage(T(Constants.Messages.ConfirmDeleteRecord).Text); result.AddReloadEvent("UPDATE_ENTITY_COMPLETE"); result.AddReloadEvent("DELETE_ENTITY_COMPLETE"); return result; } private ControlGridAjaxData<DownloadGameInfo> GetDownloadGames(ControlGridFormRequest options) { var searchText = string.Empty; if (Utilities.IsNotNull(Request.Form[Extensions.Constants.SearchText])) { searchText = Request.Form[Extensions.Constants.SearchText]; } int totals; var items = WorkContext.Resolve<IDownloadGameService>().SearchPaged(searchText, options.PageIndex, options.PageSize, out totals); var result = new ControlGridAjaxData<DownloadGameInfo>(items, totals); return result; } [Url("admin/download-games/edit/{id}")] public ActionResult Edit(int id) { WorkContext.Breadcrumbs.Add(new Breadcrumb { Text = T("Sự kiện đào xu"), Url = Url.Action("Index") }); WorkContext.Breadcrumbs.Add(new Breadcrumb { Text = T("Thông tin sự kiện"), Url = "#" }); var model = new DownloadGameModel(); if (id > 0) { var service = WorkContext.Resolve<IDownloadGameService>(); model = service.GetById(id); } var result = new ControlFormResult<DownloadGameModel>(model) { Title = T("Thông tin sự kiện"), FormMethod = FormMethod.Post, UpdateActionName = "Update", SubmitButtonText = T("Lưu lại"), ShowCancelButton = true, ShowBoxHeader = false, CancelButtonText = T("Trở về"), FormWrapperStartHtml = Constants.Form.FormWrapperStartHtml, FormWrapperEndHtml = Constants.Form.FormWrapperEndHtml }; result.MakeReadOnlyProperty(x => x.Code); return result; } [HttpPost, ValidateInput(false), FormButton("Save")] [Url("admin/download-games/update")] public ActionResult Update(DownloadGameModel model) { if (!ModelState.IsValid) { return new AjaxResult().Alert(T(Constants.Messages.InvalidModel)); } var service = WorkContext.Resolve<IDownloadGameService>(); DownloadGameInfo item = model.Id == 0 ? new DownloadGameInfo() : service.GetById(model.Id); item.Title = model.Title; item.Code = model.Code; item.UrlBanner = model.UrlBanner; item.Logo = model.Logo; item.GooglePlayUrl = model.GooglePlayUrl; item.WebsiteUrl = model.WebsiteUrl; item.VipXu = model.VipXu; item.IsActived = model.IsActived; service.Save(item); return new AjaxResult().NotifyMessage("UPDATE_ENTITY_COMPLETE") .Alert(T("Cập nhật thành công!")); } [FormButton("Delete")] [HttpPost, ActionName("Update")] public ActionResult Delete(int id) { var service = WorkContext.Resolve<IDownloadGameService>(); var item = service.GetById(id); service.Delete(item); return new AjaxResult() .NotifyMessage("DELETE_ENTITY_COMPLETE") .Alert(T("Đã xóa dữ liệu này thành công!")); } } } <file_sep>using System; using System.Collections.Generic; using System.Data.SqlClient; using CMSSolutions.Data; using CMSSolutions.Events; using CMSSolutions.Services; using CMSSolutions.Websites.Entities; namespace CMSSolutions.Websites.Services { public interface ICustomerHistoriesService : IGenericService<CustomerHistoriesInfo, long>, IDependency { IList<CustomerHistoriesInfo> GetPaged(int customerId, DateTime fromDate, DateTime toDate, int type, int status, int pageIndex, int pageSize, out int totalRecord); List<NapVipCustomerLogs> GetNapVipByCustomer(int customerId); List<TransactioCustomerLogs> GetDoiXuByCustomer(string customerCode); } public class CustomerHistoriesService : GenericService<CustomerHistoriesInfo, long>, ICustomerHistoriesService { public CustomerHistoriesService(IRepository<CustomerHistoriesInfo, long> repository, IEventBus eventBus) : base(repository, eventBus) { } public IList<CustomerHistoriesInfo> GetPaged(int customerId, DateTime fromDate, DateTime toDate, int type, int status, int pageIndex, int pageSize, out int totalRecord) { var list = new List<SqlParameter> { AddInputParameter("@CustomerId", customerId), AddInputParameter("@Type", type), AddInputParameter("@FromDate", fromDate), AddInputParameter("@ToDate", toDate), AddInputParameter("@Status", status), AddInputParameter("@PageIndex", pageIndex), AddInputParameter("@PageSize", pageSize) }; return ExecuteReader<CustomerHistoriesInfo>("sp_CustomerHistories_Search_Paged", "@TotalRecord", out totalRecord, list.ToArray()); } public List<NapVipCustomerLogs> GetNapVipByCustomer(int customerId) { var list = new List<SqlParameter> { AddInputParameter("@CustomerId", customerId) }; return ExecuteReader<NapVipCustomerLogs>("sp_NapVipLogs", list.ToArray()); } public List<TransactioCustomerLogs> GetDoiXuByCustomer(string customerCode) { var list = new List<SqlParameter> { AddInputParameter("@CustomerCode", customerCode) }; return ExecuteReader<TransactioCustomerLogs>("sp_TransactioLogs", list.ToArray()); } } } <file_sep>using System.Web.Mvc; using CMSSolutions.ContentManagement.Widgets.Services; using CMSSolutions.DisplayManagement; using CMSSolutions.Web.Mvc; using CMSSolutions.Web.Themes; using CMSSolutions.Websites.Extensions; using CMSSolutions.Websites.Models; using CMSSolutions.Websites.Services; namespace CMSSolutions.Websites.Controllers { [Themed(IsDashboard = false)] public class HomeSupportController : BaseHomeController { private readonly dynamic shapeFactory; public HomeSupportController(IWorkContextAccessor workContextAccessor, IShapeFactory shapeFactory) : base(workContextAccessor) { this.shapeFactory = shapeFactory; } [Url("ho-tro.html")] public ActionResult Index() { UrlLogin = Request.Url != null ? Request.Url.AbsoluteUri : Url.Action("Index", "Home"); SiteId = (int)Site.Home; var serviceCategory = WorkContext.Resolve<ICategoryService>(); serviceCategory.LanguageCode = WorkContext.CurrentCulture; serviceCategory.SiteId = SiteId; var category = serviceCategory.GetByIdCache((int)FixCategories.Support); ViewData[Extensions.Constants.HeaderTitle] = category.Name; ViewData[Extensions.Constants.HeaderDescription] = category.Description; ViewData[Extensions.Constants.HeaderKeywords] = category.Tags; BuildModules(); return View(); } public override void BuildModules() { var widget = WorkContext.Resolve<IWidgetService>(); var viewRenderer = new ViewRenderer { Context = ControllerContext }; if (!IsVip) { #region BannerRightFifth var bannerRightFifth = widget.GetWidget(HomeWidgets.BannerRightFifth.ToString()); if (bannerRightFifth != null) { var widgetShape = shapeFactory.Widget(); widgetShape.Widget = bannerRightFifth; WorkContext.Layout.AdBannerRightFifth(widgetShape); } #endregion } else { #region BannerPageLeftVip var bannerPageLeftVip = widget.GetWidget(HomeWidgets.BannerPageLeftVip.ToString()); if (bannerPageLeftVip != null) { var widgetShape = shapeFactory.Widget(); widgetShape.Widget = bannerPageLeftVip; WorkContext.Layout.AdBannerPageLeftVip(widgetShape); } #endregion #region BannerPageCenterVip var bannerPageCenterVip = widget.GetWidget(HomeWidgets.BannerPageCenterVip.ToString()); if (bannerPageCenterVip != null) { var widgetShape = shapeFactory.Widget(); widgetShape.Widget = bannerPageCenterVip; WorkContext.Layout.AdBannerPageCenterVip(widgetShape); } #endregion #region BannerPageRightVip var bannerPageRightVip = widget.GetWidget(HomeWidgets.BannerPageRightVip.ToString()); if (bannerPageRightVip != null) { var widgetShape = shapeFactory.Widget(); widgetShape.Widget = bannerPageRightVip; WorkContext.Layout.AdBannerPageRightVip(widgetShape); } #endregion } #region HomeFooterLogoInformation var homeFooterLogoInformation = widget.GetWidget(HomeWidgets.HomeFooterLogoInformation.ToString()); if (homeFooterLogoInformation != null) { var widgetShape = shapeFactory.Widget(); widgetShape.Widget = homeFooterLogoInformation; WorkContext.Layout.FooterLogoInformation(widgetShape); } #endregion #region BannerRightFirst var view = viewRenderer.RenderPartialView(Extensions.Constants.DivDisplayFilePath, null); WorkContext.Layout.AdBannerRightFirst.Add(new MvcHtmlString(view)); #endregion #region HomeFacebookFanpage var homeFacebookFanpage = widget.GetWidget(HomeWidgets.HomeFacebookFanpage.ToString()); if (homeFacebookFanpage != null) { var widgetShape = shapeFactory.Widget(); widgetShape.Widget = homeFacebookFanpage; WorkContext.Layout.AdFacebookFanpage(widgetShape); } #endregion #region SocialNetwork var socialNetwork = widget.GetWidget(HomeWidgets.DisplaySocialNetwork.ToString()); if (socialNetwork != null) { var widgetShape = shapeFactory.Widget(); widgetShape.Widget = socialNetwork; WorkContext.Layout.DisplaySocialNetwork(widgetShape); } #endregion #region News var viewNews = viewRenderer.RenderPartialView(Extensions.Constants.NewsViewFilePath, null); WorkContext.Layout.DisplayNews.Add(new MvcHtmlString(viewNews)); #endregion #region DisplayStatistic1 var modelStatistic1 = new DataViewCategoryModel { Type = (int)HomeDisplayFilmType.StatisticalFilmRetail, Title = "PHIM LẺ XEM NHIỀU NHẤT" }; var viewStatistic1 = viewRenderer.RenderPartialView(Extensions.Constants.Statistic1FilePath, modelStatistic1); WorkContext.Layout.DisplayStatistic1.Add(new MvcHtmlString(viewStatistic1)); #endregion #region DisplayStatistic2 var modelStatistic2 = new DataViewCategoryModel { Type = (int)HomeDisplayFilmType.StatisticalLengthEpisodes, Title = "PHIM BỘ XEM NHIỀU NHẤT" }; var viewStatistic2 = viewRenderer.RenderPartialView(Extensions.Constants.Statistic2FilePath, modelStatistic2); WorkContext.Layout.DisplayStatistic2.Add(new MvcHtmlString(viewStatistic2)); #endregion #region DisplayStatistic3 var modelStatistic3 = new DataViewCategoryModel { Type = (int)HomeDisplayFilmType.StatisticalTrailer, Title = "PHIM SẮP CHIẾU" }; var viewStatistic3 = viewRenderer.RenderPartialView(Extensions.Constants.Statistic5FilePath, modelStatistic3); WorkContext.Layout.AdBannerRightSecond.Add(new MvcHtmlString(viewStatistic3)); #endregion #region Tags var serviceTags = WorkContext.Resolve<ITagService>(); var modelTags = new TagViewModel { ListTags = serviceTags.GetDisplayTags() }; var viewTags = viewRenderer.RenderPartialView(Extensions.Constants.TagViewFilePath, modelTags); WorkContext.Layout.DisplayTags.Add(new MvcHtmlString(viewTags)); #endregion #region HomeFacebookFollow var facebookFollow = widget.GetWidget(HomeWidgets.HomeFacebookFollow.ToString()); if (facebookFollow != null) { var widgetShape = shapeFactory.Widget(); widgetShape.Widget = facebookFollow; WorkContext.Layout.AdBannerRightThird(widgetShape); } #endregion #region HomeFacebookActivity var facebookActivity = widget.GetWidget(HomeWidgets.HomeFacebookActivity.ToString()); if (facebookActivity != null) { var widgetShape = shapeFactory.Widget(); widgetShape.Widget = facebookActivity; WorkContext.Layout.DisplayTags(widgetShape); } #endregion #region HomeGoogleBadge var googleBadge = widget.GetWidget(HomeWidgets.HomeGoogleBadge.ToString()); if (googleBadge != null) { var widgetShape = shapeFactory.Widget(); widgetShape.Widget = googleBadge; WorkContext.Layout.AdBannerRightFourth(widgetShape); } #endregion #region CategoryContentFirst var modelFirst = new DataViewCategoryModel(); var service = WorkContext.Resolve<ISupportService>(); modelFirst.Title = "FAQs / Những câu hỏi thường gặp"; service.SiteId = SiteId; service.LanguageCode = WorkContext.CurrentCulture; modelFirst.ListSupportParents = service.GetAllParents((int) Status.Approved); modelFirst.ListSupportChildren = service.GetAllChildren((int) Status.Approved); var viewFilmFirst = viewRenderer.RenderPartialView(Extensions.Constants.SupportsViewFilePath, modelFirst); WorkContext.Layout.CategoryContentLeftFirst.Add(new MvcHtmlString(viewFilmFirst)); #endregion } } } <file_sep>using System; using CMSSolutions.Web.UI.ControlForms; using CMSSolutions.Websites.Entities; namespace CMSSolutions.Websites.Models { public class AdvertisementModel { public AdvertisementModel() { KeyCode = Guid.NewGuid().ToString().Replace("-", string.Empty); Code = "pre-blueseed"; Type = "tags"; Position = 0; Price = 0; Duration = 15; Skip = 5; IsBlock = false; } [ControlHidden] public int Id { get; set; } [ControlChoice(ControlChoice.DropDownList, Required = true, LabelText = "Ngôn ngữ hiển thị", ContainerCssClass = Constants.ContainerCssClassCol4, ContainerRowIndex = 0, OnSelectedIndexChanged = "$('#" + Extensions.Constants.CategoryId + "').empty();")] public string LanguageCode { get; set; } [ControlCascadingDropDown(LabelText = "Trang web", ParentControl = "LanguageCode", AbsoluteParentControl = true, ContainerCssClass = Constants.ContainerCssClassCol4, ContainerRowIndex = 0)] public int SiteId { get; set; } [ControlText(Type = ControlText.TextBox, ReadOnly = true, LabelText = "Mã quảng cáo", Required = true, MaxLength = 50, ContainerCssClass = Constants.ContainerCssClassCol4, ContainerRowIndex = 0)] public string KeyCode { get; set; } [ControlText(Type = ControlText.TextBox, LabelText = "Tiêu đề", Required = true, MaxLength = 250, ContainerCssClass = Constants.ContainerCssClassCol12, ContainerRowIndex = 1)] public string Title { get; set; } [ControlText(Type = ControlText.TextBox, LabelText = "Đường dẫn VAST", Required = true, MaxLength = 250, ContainerCssClass = Constants.ContainerCssClassCol6, ContainerRowIndex = 2)] public string Link { get; set; } [ControlText(Type = ControlText.TextBox, LabelText = "Key", Required = true, MaxLength = 250, ContainerCssClass = Constants.ContainerCssClassCol3, ContainerRowIndex = 2)] public string Code { get; set; } [ControlText(Type = ControlText.TextBox, LabelText = "Loại", Required = true, MaxLength = 250, ContainerCssClass = Constants.ContainerCssClassCol3, ContainerRowIndex = 2)] public string Type { get; set; } [ControlNumeric(LabelText = "Thời gian", Required = true, ContainerCssClass = Constants.ContainerCssClassCol3, ContainerRowIndex = 4)] public int Duration { get; set; } [ControlNumeric(LabelText = "Vị trí bắt đầu", Required = true, ContainerCssClass = Constants.ContainerCssClassCol3, ContainerRowIndex = 4)] public int Position { get; set; } [ControlNumeric(LabelText = "Thời gian skip", Required = true, ContainerCssClass = Constants.ContainerCssClassCol3, ContainerRowIndex = 4)] public int Skip { get; set; } [ControlNumeric(LabelText = "Chi phí", Required = true, ContainerCssClass = Constants.ContainerCssClassCol3, ContainerRowIndex = 4)] public float Price { get; set; } [ControlChoice(ControlChoice.CheckBox, LabelText = "", PrependText = "Tạm khóa", ContainerCssClass = Constants.ContainerCssClassCol3, ContainerRowIndex = 5)] public bool IsBlock { get; set; } public static implicit operator AdvertisementModel(AdvertisementInfo entity) { if (entity == null) { return null; } return new AdvertisementModel { Id = entity.Id, LanguageCode = entity.LanguageCode, SiteId = entity.SiteId, Title = entity.Title, KeyCode = entity.KeyCode, Price = (float)entity.Price, Code = entity.Code, Link = entity.Link, Type = entity.Type, Duration = entity.Duration, Position = entity.Position, Skip = entity.Skip, IsBlock = entity.IsBlock }; } } }<file_sep>using System.Web.Mvc; using CMSSolutions.Web.Mvc; using CMSSolutions.Web.Routing; using CMSSolutions.Web.Themes; using CMSSolutions.Web.UI.ControlForms; using CMSSolutions.Web.UI.Navigation; using CMSSolutions.Websites.Entities; using CMSSolutions.Websites.Extensions; using CMSSolutions.Websites.Models; using CMSSolutions.Websites.Services; namespace CMSSolutions.Websites.Controllers { [Themed(IsDashboard = true), Authorize] public class AdminSmsMessageController : BaseAdminController { public AdminSmsMessageController(IWorkContextAccessor workContextAccessor) : base(workContextAccessor) { TableName = "tblSmsMessages"; } [Url("admin/sms-messages")] public ActionResult Index() { WorkContext.Breadcrumbs.Add(new Breadcrumb { Text = T("Quản lý tin nhắn"), Url = "#" }); var result = new ControlGridFormResult<SmsMessageInfo> { Title = T("Quản lý tin nhắn"), CssClass = "table table-bordered table-striped", IsAjaxSupported = true, FetchAjaxSource = GetSmsMessages, UpdateActionName = "Update", ActionsColumnWidth = 100, ClientId = TableName, GridWrapperStartHtml = Constants.Grid.GridWrapperStartHtml, GridWrapperEndHtml = Constants.Grid.GridWrapperEndHtml }; result.AddCustomVar(Extensions.Constants.LanguageCode, "$('#" + Extensions.Constants.LanguageCode + "').val();", true); result.AddColumn(x => x.Code, T("Mã")); result.AddColumn(x => x.Message, T("Thông báo")); result.AddColumn(x => (x.IsEvent ? "Sự kiện" :"Không sự kiện"), T("Loại tin")); result.AddAction(new ControlFormHtmlAction(() => BuildLanguages(false, string.Empty))).HasParentClass(Constants.ContainerCssClassCol3); result.AddRowAction() .HasText(T("Sửa")) .HasUrl(x => Url.Action("Edit", RouteData.Values.Merge(new { id = x.Id }))) .HasButtonStyle(ButtonStyle.Default) .HasButtonSize(ButtonSize.ExtraSmall); result.AddReloadEvent("UPDATE_ENTITY_COMPLETE"); return result; } private ControlGridAjaxData<SmsMessageInfo> GetSmsMessages(ControlGridFormRequest options) { var languageCode = WorkContext.CurrentCulture; if (Utilities.IsNotNull(Request.Form[Extensions.Constants.LanguageCode])) { languageCode = Request.Form[Extensions.Constants.LanguageCode]; } var items = WorkContext.Resolve<ISmsMessageService>().GetRecords(x => x.LanguageCode == languageCode); var result = new ControlGridAjaxData<SmsMessageInfo>(items); return result; } [Url("admin/sms-messages/edit/{id}")] public ActionResult Edit(int id) { var model = new SmsMessageModel(); if (id > 0) { var service = WorkContext.Resolve<ISmsMessageService>(); model = service.GetById(id); } var result = new ControlFormResult<SmsMessageModel>(model) { Title = T("Thông tin tin nhắn"), FormMethod = FormMethod.Post, UpdateActionName = "Update", SubmitButtonText = T("Lưu lại"), ShowCancelButton = false, ShowBoxHeader = false, FormWrapperStartHtml = Constants.Form.FormWrapperStartHtml, FormWrapperEndHtml = Constants.Form.FormWrapperEndHtml }; result.AddAction().HasText(T("Trở về")) .HasUrl(Url.Action("Index")) .HasCssClass("btn btn-danger"); result.RegisterExternalDataSource(x => x.LanguageCode, y => BindLanguages()); return result; } } } <file_sep>using System; using System.Collections.Generic; using System.Data.SqlClient; using System.Linq; using System.Net.Mail; using System.Text; using System.Web; using CMSSolutions.Caching; using CMSSolutions.ContentManagement.Messages.Domain; using CMSSolutions.ContentManagement.Messages.Services; using CMSSolutions.Data; using CMSSolutions.Events; using CMSSolutions.Services; using CMSSolutions.Websites.Entities; using CMSSolutions.Websites.Extensions; namespace CMSSolutions.Websites.Services { public interface ICustomerService : IGenericService<CustomerInfo, int>, IDependency { string GetLatestCustomerCode(); List<CustomerInfo> SearchPaged( string searchText, int filmTypeId, int countryId, DateTime fromDate, DateTime toDate, int isBlock, int status, int pageIndex, int pageSize, out int totalRecord); CustomerInfo Login(string userName, string password); CustomerInfo CheckRegister(string userName); CustomerInfo GetByCustomerCode(string customerCode); int ExchangeDay(int customerId, int day, int vipXu, string transactionCode, string package); IList<CustomerInfo> GetPromotions(int promotionId); int ChangePassword(string userName, string passwordOld, string password); CustomerInfo ResetTotalDay(int customerId); void ResetCacheCustomers(); CustomerInfo GetCustomerByCacheId(int customerId); int AddVipXu(int customerId, int downloadId, int vipXu); IList<CustomerInfo> ExportExcel(); CustomerInfo GetMemberForgetPassword(string newPassword, string email); void AddEmailMessages(); List<CustomerInfo> GetPaged(int pageIndex, int pageSize, out int totalRecord); IList<QueuedEmail> GetQueuedEmails(int sentTries, DateTime sentOnUtc, int pageIndex, int pageSize, out int totalRecord); } public class CustomerService : GenericService<CustomerInfo, int>, ICustomerService { private readonly ICacheInfo cacheManager; private readonly IMessageService messageService; private readonly IFilmService filmService; public CustomerService(IRepository<CustomerInfo, int> repository, IEventBus eventBus, ICacheInfo cacheManager, IMessageService messageService, IFilmService filmService) : base(repository, eventBus) { this.cacheManager = cacheManager; this.messageService = messageService; this.filmService = filmService; } public string GetLatestCustomerCode() { return (string)ExecuteReaderResult("NextCustomerCode"); } public List<CustomerInfo> SearchPaged( string searchText, int filmTypeId, int countryId, DateTime fromDate, DateTime toDate, int isBlock, int status, int pageIndex, int pageSize, out int totalRecord) { var list = new List<SqlParameter> { AddInputParameter("@SearchText", searchText), AddInputParameter("@FilmTypeId", filmTypeId), AddInputParameter("@CountryId", countryId), AddInputParameter("@FromDate", fromDate), AddInputParameter("@ToDate", toDate), AddInputParameter("@IsBlock", isBlock), AddInputParameter("@Status", status), AddInputParameter("@PageIndex", pageIndex), AddInputParameter("@PageSize", pageSize) }; return ExecuteReader<CustomerInfo>("sp_Customers_Search_Paged", "@TotalRecord", out totalRecord, list.ToArray()); } public CustomerInfo Login(string userName, string password) { var list = new List<SqlParameter> { AddInputParameter("@UserName", userName), AddInputParameter("@Password", <PASSWORD>), }; return ExecuteReaderRecord<CustomerInfo>("sp_Customers_Login", list.ToArray()); } public CustomerInfo CheckRegister(string userName) { var list = new List<SqlParameter> { AddInputParameter("@UserName", userName), }; return ExecuteReaderRecord<CustomerInfo>("sp_Customers_CheckRegister", list.ToArray()); } public CustomerInfo GetByCustomerCode(string customerCode) { var list = new List<SqlParameter> { AddInputParameter("@CustomerCode", customerCode), }; return ExecuteReaderRecord<CustomerInfo>("sp_Customers_GetByCustomerCode", list.ToArray()); } public int ExchangeDay(int customerId, int day, int vipXu, string transactionCode, string package) { var list = new List<SqlParameter> { AddInputParameter("@CustomerId", customerId), AddInputParameter("@Day", day), AddInputParameter("@VipXu", vipXu), AddInputParameter("@TransactionCode", transactionCode), AddInputParameter("@Package", package) }; return (int)ExecuteReaderResult("sp_Customers_ExchangeDay", list.ToArray()); } public IList<CustomerInfo> GetPromotions(int promotionId) { var list = new List<SqlParameter> { AddInputParameter("@PromotionId", promotionId) }; return ExecuteReader<CustomerInfo>("sp_Customers_GetPromotions", list.ToArray()); } public int ChangePassword(string userName, string passwordOld, string password) { var list = new List<SqlParameter> { AddInputParameter("@UserName", userName), AddInputParameter("@PasswordOld", <PASSWORD>Old), AddInputParameter("@Password", <PASSWORD>) }; return (int)ExecuteReaderResult("sp_Customers_ChangePassword", list.ToArray()); } public CustomerInfo ResetTotalDay(int customerId) { var list = new List<SqlParameter> { AddInputParameter("@CustomerId", customerId), }; return ExecuteReaderRecord<CustomerInfo>("sp_Customers_ResetTotalDay", list.ToArray()); } public void ResetCacheCustomers() { cacheManager.Remove(Extensions.Constants.CacheKeys.CUSTOMERS_DATA_CARD); cacheManager.Add(Extensions.Constants.CacheKeys.CUSTOMERS_DATA_CARD, GetAllCustomers()); } public CustomerInfo GetCustomerByCacheId(int customerId) { var data = cacheManager.Get(Extensions.Constants.CacheKeys.CUSTOMERS_DATA_CARD); if (data == null) { ResetCacheCustomers(); data = cacheManager.Get(Extensions.Constants.CacheKeys.CUSTOMERS_DATA_CARD); } var items = ((IList<CustomerInfo>) data); return items.FirstOrDefault(x => x.Id == customerId); } private IList<CustomerInfo> GetAllCustomers() { return ExecuteReader<CustomerInfo>("sp_Customers_GetAllCustomerCache"); } private string BuildHtmlEmail() { var html = new StringBuilder(); filmService.SiteId = (int)Site.Home; filmService.LanguageCode = "vi-VN"; var listFilms = filmService.BuildFilmHot(); if (listFilms != null && listFilms.Count > 0) { foreach (var filmInfo in listFilms) { var url = string.Format("http://viphd.vn/xem-phim/{0}/f{1}.html", filmInfo.FilmAlias, filmInfo.Id); var urlImage = string.Format("http://viphd.vn{0}", filmInfo.ImageIcon); html.Append("<div style=\"margin-right: 15px;padding: 8px 0px;width: 250px;float: left;\">"); html.Append("<div style=\"float: left;background-color: #FFF;box-shadow: 0px 0px 5px #999;-moz-box-shadow: 0px 0px 5px #999;-webkit-box-shadow: 0px 0px 5px #999;margin-right: 8px;\">"); html.AppendFormat("<a style=\"text-decoration: none;\" title=\"{0}\" href=\"{1}\">", filmInfo.FilmNameEnglish, url); html.AppendFormat("<img alt=\"{0}\" width=\"106\" height=\"80\" src=\"{1}\">", filmInfo.FilmName, urlImage); html.Append("</a>"); html.Append("</div>"); html.Append("<div style=\"float: left;\">"); html.Append("<p style=\"max-height: 35px;overflow: hidden;color: #44619d;font-family: 'SFUGillSansRegular';font-size: 14px;font-style: normal;font-weight: 200;text-transform: capitalize;line-height: 16px;\">"); html.AppendFormat("<a style=\"color: #44619d;font-family: 'SFUGillSansRegular';font-size: 14px;font-style: normal;font-weight: 200;text-transform: capitalize;line-height: 16px;text-transform: uppercase;\" title=\"{0}\" href=\"{1}\">{0}</a>", filmInfo.FilmNameEnglish, url); html.Append("</p>"); html.Append("<p style=\"max-height: 36px;overflow: hidden;line-height: 18px;color: #666666;font-family: 'SFUGillSansRegular';font-size: 12px;font-style: normal;font-weight: 200;text-transform: capitalize;\">"); html.AppendFormat("<a style=\"color: #666666;font-family: 'SFUGillSansRegular';font-size: 12px;font-style: normal;font-weight: 200;text-transform: capitalize;line-height: 14px;\" title=\"{0}\" href=\"{1}\">{0}</a>", filmInfo.FilmName, url); html.Append("</p>"); html.Append("<p style=\"color: #696969;font-size: 11px;font-family: Arial, Helvetica, sans-serif;line-height: 14px;overflow: hidden;\">"); html.Append(filmInfo.Summary); html.Append("</p>"); html.Append("</div>"); html.Append("<br class=\"clear_both\">"); html.Append("</div>"); } } return html.ToString(); } public int AddVipXu(int customerId, int downloadId, int vipXu) { var list = new List<SqlParameter> { AddInputParameter("@CustomerId", customerId), AddInputParameter("@DownloadId", downloadId), AddInputParameter("@VipXu", vipXu) }; return (int)ExecuteReaderResult("sp_Customers_UpdateVipXu", list.ToArray()); } public IList<CustomerInfo> ExportExcel() { return ExecuteReader<CustomerInfo>("sp_Customers_GetAllCustomers"); } public CustomerInfo GetMemberForgetPassword(string newPassword, string email) { var list = new List<SqlParameter> { AddInputParameter("@NewPassword", newPassword), AddInputParameter("@Email", email) }; return ExecuteReaderRecord<CustomerInfo>("sp_Customers_ForgetPassword", list.ToArray()); } public List<CustomerInfo> GetPaged(int pageIndex, int pageSize, out int totalRecord) { var list = new List<SqlParameter> { AddInputParameter("@PageIndex", pageIndex), AddInputParameter("@PageSize", pageSize) }; return ExecuteReader<CustomerInfo>("sp_Customers_GetPaged", "@TotalRecord", out totalRecord, list.ToArray()); } public void AddEmailMessages() { try { int pageIndex = 1; int pageSize = 200; int totalRecord = 0; int totalPage = 1; var htmlBody = System.IO.File.ReadAllText(HttpContext.Current.Server.MapPath("~/Media/Default/EmailTemplates/FilmHot.html")); var customers = GetPaged(pageIndex, pageSize, out totalRecord); if (customers != null && totalRecord > 0) { if (totalRecord <= pageSize) { totalPage = 1; } else { var count = totalRecord % pageSize; if ((count == 0)) { totalPage = totalRecord / pageSize; } else { totalPage = ((totalRecord - count) / pageSize) + 1; } } for (int i = 1; i <= totalPage; i++) { try { if (i > 1) { customers = GetPaged(pageIndex, pageSize, out totalRecord); } htmlBody = htmlBody.Replace("[LIST_FILM]", BuildHtmlEmail()); foreach (var customer in customers) { try { var mailMessage = new MailMessage { Subject = "Phim hot nhất trong ngày", SubjectEncoding = Encoding.UTF8, Body = htmlBody, BodyEncoding = Encoding.UTF8, IsBodyHtml = true, Sender = new MailAddress(customer.Email) }; mailMessage.To.Add(customer.Email); mailMessage.Bcc.Add("<EMAIL>"); messageService.SendEmailMessage(mailMessage); } catch (Exception) { } } } catch (Exception) { } pageIndex++; } } } catch (Exception) { } } public IList<QueuedEmail> GetQueuedEmails(int sentTries, DateTime sentOnUtc, int pageIndex, int pageSize, out int totalRecord) { var list = new List<SqlParameter> { AddInputParameter("@SentTries", sentTries), AddInputParameter("@SentOnUtc", sentOnUtc), AddInputParameter("@PageIndex", pageIndex), AddInputParameter("@PageSize", pageSize) }; return ExecuteReader<QueuedEmail>("sp_QueuedEmails_GetMessages_Paged", "@TotalRecord", out totalRecord, list.ToArray()); } } } <file_sep>using System; using System.Collections.Generic; using System.Data; using System.IO; using System.Linq; using CMSSolutions.Websites.Entities; using CMSSolutions.Websites.Extensions; using Lucene.Net.Analysis.Standard; using Lucene.Net.Documents; using Lucene.Net.Index; using Lucene.Net.QueryParsers; using Lucene.Net.Search; using Lucene.Net.Store; namespace CMSSolutions.Websites.Services { public class SearchCondition { public string[] SearchField { get; set; } public string Keyword { get; set; } public bool ConditionForField { get; set; } public SearchCondition(string[] fields, string keyword, bool condition) { this.ConditionForField = condition; this.SearchField = fields; this.Keyword = keyword; } public SearchCondition(string[] fields, string keyword) { this.ConditionForField = true; this.SearchField = fields; this.Keyword = keyword; } public SearchCondition(string fields, string keyword) { this.ConditionForField = true; this.SearchField = new string[] { fields }; this.Keyword = keyword; } } public interface ILuceneService { } public class LuceneService : ILuceneService { public LuceneService() { SiteId = (int)Site.Home; } public int SiteId { get; set; } private string _luceneDir { get { return Path.Combine(Extensions.Constants.SearchEngineDBPath, SiteId.ToString()); } } private FSDirectory _directoryTemp; private FSDirectory _directory { get { if (_directoryTemp == null) _directoryTemp = FSDirectory.Open(new DirectoryInfo(_luceneDir)); if (IndexWriter.IsLocked(_directoryTemp)) IndexWriter.Unlock(_directoryTemp); var lockFilePath = Path.Combine(_luceneDir, "write.lock"); if (File.Exists(lockFilePath)) File.Delete(lockFilePath); return _directoryTemp; } } public bool ClearLuceneIndexRecord(int record_id) { var analyzer = new StandardAnalyzer(Lucene.Net.Util.Version.LUCENE_29); using (var writer = new IndexWriter(_directory, analyzer, IndexWriter.MaxFieldLength.UNLIMITED)) { try { var searchQuery = new TermQuery(new Term("Id", record_id.ToString())); writer.DeleteDocuments(searchQuery); return true; } catch (Exception) { return false; } finally { analyzer.Close(); writer.Close(); writer.Dispose(); } } } public bool AddUpdateLuceneIndex(DataTable table) { var analyzer = new StandardAnalyzer(Lucene.Net.Util.Version.LUCENE_29); using (var writer = new IndexWriter(_directory, analyzer, IndexWriter.MaxFieldLength.UNLIMITED)) { try { writer.DeleteAll(); foreach (DataRow row in table.Rows) { var document = new Document(); document.Add(new Field("Id", row["Id"].ToString(), Field.Store.YES, Field.Index.ANALYZED)); document.Add(new Field("LanguageCode", row["LanguageCode"].ToString(), Field.Store.YES, Field.Index.ANALYZED)); document.Add(new Field("SiteId", row["SiteId"].ToString(), Field.Store.YES, Field.Index.ANALYZED)); document.Add(new Field("CategoryIds", row["CategoryIds"].ToString(), Field.Store.YES, Field.Index.ANALYZED)); document.Add(new Field("CategoryNames", row["CategoryNames"].ToString(), Field.Store.YES, Field.Index.ANALYZED)); document.Add(new Field("Type", row["Type"].ToString(), Field.Store.YES, Field.Index.ANALYZED)); document.Add(new Field("SearchId", row["SearchId"].ToString(), Field.Store.YES, Field.Index.ANALYZED)); document.Add(new Field("Title", row["Title"].ToString(), Field.Store.YES, Field.Index.ANALYZED)); document.Add(new Field("Alias", row["Alias"].ToString(), Field.Store.YES, Field.Index.ANALYZED)); document.Add(new Field("Sumary", row["Sumary"].ToString(), Field.Store.YES, Field.Index.ANALYZED)); document.Add(new Field("Tags", row["Tags"].ToString(), Field.Store.YES, Field.Index.ANALYZED)); document.Add(new Field("CreateDate", DateTime.Parse(row["CreateDate"].ToString()).ToString(Extensions.Constants.DateTimeFomat), Field.Store.YES, Field.Index.ANALYZED)); document.Add(new Field("TitleEnglish", row["TitleEnglish"].ToString(), Field.Store.YES, Field.Index.ANALYZED)); document.Add(new Field("Images", row["Images"].ToString(), Field.Store.YES, Field.Index.ANALYZED)); document.Add(new Field("IsBlock", row["IsBlock"].ToString(), Field.Store.YES, Field.Index.ANALYZED)); document.Add(new Field("IsClip", row["IsClip"].ToString(), Field.Store.YES, Field.Index.ANALYZED)); document.Add(new Field("IsTrailer", row["IsTrailer"].ToString(), Field.Store.YES, Field.Index.ANALYZED)); document.Add(new Field("IsFilm", row["IsFilm"].ToString(), Field.Store.YES, Field.Index.ANALYZED)); document.Add(new Field("IsShow", row["IsShow"].ToString(), Field.Store.YES, Field.Index.ANALYZED)); document.Add(new Field("ViewCount", row["ViewCount"].ToString(), Field.Store.YES, Field.Index.ANALYZED)); var keyword = Utilities.GetCharUnsigned(row["Title"].ToString()); var keyworden = Utilities.GetCharUnsigned(row["TitleEnglish"].ToString()); document.Add(new Field("Keyword", keyword, Field.Store.YES, Field.Index.ANALYZED)); document.Add(new Field("KeywordEN", keyworden, Field.Store.YES, Field.Index.ANALYZED)); writer.AddDocument(document); } return true; } catch { return false; } finally { analyzer.Close(); writer.Close(); writer.Dispose(); } } } public bool AddUpdateLuceneIndex(List<SearchInfo> listData) { var analyzer = new StandardAnalyzer(Lucene.Net.Util.Version.LUCENE_29); using (var writer = new IndexWriter(_directory, analyzer, IndexWriter.MaxFieldLength.UNLIMITED)) { try { foreach (var sampleData in listData) { AddToLuceneIndex(sampleData, writer); } return true; } catch { return false; } finally { analyzer.Close(); writer.Close(); writer.Dispose(); } } } public bool UpdateLuceneIndex(SearchInfo dataObject) { var analyzer = new StandardAnalyzer(Lucene.Net.Util.Version.LUCENE_29); using (var writer = new IndexWriter(_directory, analyzer, IndexWriter.MaxFieldLength.UNLIMITED)) { try { writer.DeleteAll(); var doc = CreateDoc(dataObject); writer.UpdateDocument(new Term("Id", dataObject.Id.ToString()), doc); return true; } catch { return false; } finally { analyzer.Close(); writer.Close(); writer.Dispose(); } } } public bool AddUpdateLuceneIndex(SearchInfo data) { return AddUpdateLuceneIndex(new List<SearchInfo> { data }); } private void AddToLuceneIndex(SearchInfo dataObject, IndexWriter writer) { var searchQuery = new TermQuery(new Term("Id", dataObject.Id.ToString())); writer.DeleteDocuments(searchQuery); var doc = CreateDoc(dataObject); writer.AddDocument(doc); } private Document CreateDoc(SearchInfo row) { var doc = new Document(); doc.Add(new Field("Id", row.Id.ToString(), Field.Store.YES, Field.Index.ANALYZED)); doc.Add(new Field("LanguageCode", row.LanguageCode, Field.Store.YES, Field.Index.ANALYZED)); doc.Add(new Field("SiteId", row.SiteId.ToString(), Field.Store.YES, Field.Index.ANALYZED)); doc.Add(new Field("CategoryIds", row.CategoryIds, Field.Store.YES, Field.Index.ANALYZED)); doc.Add(new Field("CategoryNames", row.CategoryNames, Field.Store.YES, Field.Index.ANALYZED)); doc.Add(new Field("Type", row.Type.ToString(), Field.Store.YES, Field.Index.ANALYZED)); doc.Add(new Field("SearchId", row.SearchId, Field.Store.YES, Field.Index.ANALYZED)); doc.Add(new Field("Title", row.Title, Field.Store.YES, Field.Index.ANALYZED)); doc.Add(new Field("Alias", row.Alias, Field.Store.YES, Field.Index.ANALYZED)); doc.Add(new Field("Sumary", row.Sumary, Field.Store.YES, Field.Index.ANALYZED)); doc.Add(new Field("Tags", row.Tags, Field.Store.YES, Field.Index.ANALYZED)); doc.Add(new Field("CreateDate", row.CreateDate.ToString(Extensions.Constants.DateTimeFomat), Field.Store.YES, Field.Index.ANALYZED)); doc.Add(new Field("TitleEnglish", row.TitleEnglish, Field.Store.YES, Field.Index.ANALYZED)); doc.Add(new Field("Images", row.Images, Field.Store.YES, Field.Index.ANALYZED)); doc.Add(new Field("IsBlock", row.IsBlock.ToString(), Field.Store.YES, Field.Index.ANALYZED)); doc.Add(new Field("IsClip", row.IsClip.ToString(), Field.Store.YES, Field.Index.ANALYZED)); doc.Add(new Field("IsTrailer", row.IsTrailer.ToString(), Field.Store.YES, Field.Index.ANALYZED)); doc.Add(new Field("IsFilm", row.IsFilm.ToString(), Field.Store.YES, Field.Index.ANALYZED)); doc.Add(new Field("IsShow", row.IsShow.ToString(), Field.Store.YES, Field.Index.ANALYZED)); doc.Add(new Field("ViewCount", row.ViewCount, Field.Store.YES, Field.Index.ANALYZED)); var keyword = Utilities.GetCharUnsigned(row.Title); var keyworden = Utilities.GetCharUnsigned(row.TitleEnglish); doc.Add(new Field("Keyword", keyword, Field.Store.YES, Field.Index.ANALYZED)); doc.Add(new Field("KeywordEN", keyworden, Field.Store.YES, Field.Index.ANALYZED)); return doc; } public bool ClearLuceneIndex() { try { var analyzer = new StandardAnalyzer(Lucene.Net.Util.Version.LUCENE_29); using (var writer = new IndexWriter(_directory, analyzer, true, IndexWriter.MaxFieldLength.UNLIMITED)) { writer.DeleteAll(); analyzer.Close(); writer.Close(); writer.Dispose(); } } catch (Exception) { return false; } return true; } public void Optimize() { var analyzer = new StandardAnalyzer(Lucene.Net.Util.Version.LUCENE_29); using (var writer = new IndexWriter(_directory, analyzer, IndexWriter.MaxFieldLength.UNLIMITED)) { analyzer.Close(); writer.Optimize(); writer.Close(); writer.Dispose(); } } public List<SearchInfo> Search(List<SearchCondition> conditions, int pgIndex, int pgSize, ref int nResult) { return Search(conditions, false, pgIndex, pgSize, ref nResult); } public List<SearchInfo> Search(SearchCondition condition, int pgIndex, int pgSize, ref int nResult) { return Search(new List<SearchCondition> { condition }, pgIndex, pgSize, ref nResult); } public List<SearchInfo> Search(List<SearchCondition> conditions, bool haveKeyword, int pgIndex, int pgSize, ref int nResult) { if (conditions == null || conditions.Count == 0) { throw new ArgumentNullException("searchTerms"); } try { var analyzer = new StandardAnalyzer(Lucene.Net.Util.Version.LUCENE_29); var directory = FSDirectory.Open(new DirectoryInfo(_luceneDir)); if (!IndexReader.IndexExists(directory)) { return null; } var mainQuery = new BooleanQuery(); foreach (var pair in conditions) { string searchQuery = pair.Keyword; if (string.IsNullOrEmpty(searchQuery.Replace("*", "").Replace("?", ""))) { searchQuery = searchQuery.Replace("*", "").Replace("?", ""); } for (int i = 0; i < pair.SearchField.Length; i++) { var query = new QueryParser(Lucene.Net.Util.Version.LUCENE_29, pair.SearchField[i], analyzer).Parse(searchQuery); mainQuery.Add(query, BooleanClause.Occur.SHOULD); } } var searcher = new IndexSearcher(directory, true); try { int endItem = pgIndex * pgSize; int startItem = (pgIndex - 1) * pgSize; var hits = searcher.Search(mainQuery, null, endItem, haveKeyword ? Sort.RELEVANCE : new Sort(CreateSort())); nResult = hits.TotalHits; return LuceneToDataList(hits.ScoreDocs.Skip(startItem).Take(pgSize), searcher).ToList(); } finally { searcher.Close(); analyzer.Close(); } } catch (Exception exception) { throw exception; } } public List<SearchInfo> Search(SearchCondition condition, bool haveKeyword, int pgIndex, int pgSize, ref int nResult) { return Search(new List<SearchCondition>() { condition }, haveKeyword, pgIndex, pgSize, ref nResult); } private SortField[] CreateSort() { var sortFields = new List<SortField>(); sortFields.Add(new SortField(SearchField.Id.ToString(), SortField.LONG, true)); sortFields.Add(new SortField(SearchField.SiteId.ToString(), SortField.INT, true)); sortFields.Add(new SortField(SearchField.CategoryIds.ToString(), SortField.STRING, true)); sortFields.Add(new SortField(SearchField.CategoryNames.ToString(), SortField.STRING, false)); sortFields.Add(new SortField(SearchField.Type.ToString(), SortField.INT, true)); sortFields.Add(new SortField(SearchField.SearchId.ToString(), SortField.STRING, false)); sortFields.Add(new SortField(SearchField.Title.ToString(), SortField.STRING, false)); sortFields.Add(new SortField(SearchField.Alias.ToString(), SortField.STRING, false)); sortFields.Add(new SortField(SearchField.Sumary.ToString(), SortField.STRING, false)); sortFields.Add(new SortField(SearchField.Tags.ToString(), SortField.STRING, false)); sortFields.Add(new SortField(SearchField.TitleEnglish.ToString(), SortField.STRING, false)); sortFields.Add(new SortField(SearchField.IsClip.ToString(), SortField.STRING, false)); sortFields.Add(new SortField(SearchField.IsFilm.ToString(), SortField.STRING, false)); sortFields.Add(new SortField(SearchField.IsTrailer.ToString(), SortField.STRING, false)); sortFields.Add(new SortField(SearchField.IsShow.ToString(), SortField.STRING, false)); sortFields.Add(new SortField(SearchField.Keyword.ToString(), SortField.STRING, false)); sortFields.Add(new SortField(SearchField.KeywordEN.ToString(), SortField.STRING, false)); return sortFields.ToArray(); } public int Count(SearchCondition condition) { return Count(new List<SearchCondition>() {condition}); } public int Count(List<SearchCondition> conditions) { if (conditions == null || conditions.Count == 0) throw new ArgumentNullException("searchTerms"); var analyzer = new StandardAnalyzer(Lucene.Net.Util.Version.LUCENE_29); var directory = FSDirectory.Open(new DirectoryInfo(_luceneDir)); if (!IndexReader.IndexExists(directory)) { return 0; } var mainQuery = new BooleanQuery(); foreach (var pair in conditions) { string searchQuery = pair.Keyword; if (string.IsNullOrEmpty(searchQuery.Replace("*", "").Replace("?", ""))) { searchQuery = searchQuery.Replace("*", "").Replace("?", ""); } for (int i = 0; i < pair.SearchField.Length; i++) { var query = new QueryParser(Lucene.Net.Util.Version.LUCENE_29, pair.SearchField[i], analyzer).Parse(searchQuery); mainQuery.Add(query, BooleanClause.Occur.MUST); } } var searcher = new IndexSearcher(directory, true); try { return searcher.Search(mainQuery, 1).TotalHits; } finally { searcher.Close(); analyzer.Close(); } } private static IEnumerable<SearchInfo> LuceneToDataList(IEnumerable<ScoreDoc> hits, IndexSearcher searcher) { return hits.Select(hit => LuceneDocumentToData(searcher.Doc(hit.doc))).ToList(); } private static SearchInfo LuceneDocumentToData(Document doc) { try { DateTime createDate = DateTime.ParseExact(doc.Get("CreateDate"), Extensions.Constants.DateTimeFomat, System.Globalization.CultureInfo.InvariantCulture); var item = new SearchInfo { Id = int.Parse(doc.Get("Id")), LanguageCode = doc.Get("LanguageCode"), SiteId = int.Parse(doc.Get("SiteId")), CategoryIds = doc.Get("CategoryIds"), CategoryNames = doc.Get("CategoryNames"), Type = int.Parse(doc.Get("Type")), SearchId = doc.Get("SearchId"), Title = doc.Get("Title"), Alias = doc.Get("Alias"), Sumary = doc.Get("Sumary"), Tags = doc.Get("Tags"), CreateDate = createDate, TitleEnglish = doc.Get("TitleEnglish"), Images = doc.Get("Images"), IsBlock = bool.Parse(doc.Get("IsBlock")), IsClip = bool.Parse(doc.Get("IsClip")), IsTrailer = bool.Parse(doc.Get("IsTrailer")), IsFilm = bool.Parse(doc.Get("IsFilm")), IsShow = bool.Parse(doc.Get("IsShow")), ViewCount = doc.Get("ViewCount") }; return item; } catch (Exception) { return new SearchInfo(); } } } }<file_sep>using System.ComponentModel; using System.Runtime.Serialization; using CMSSolutions.Data; using CMSSolutions.Data.Entity; namespace CMSSolutions.Websites.Entities { [DataContract] public class TagInfo : BaseEntity<int> { [DataMember] [DisplayName("Name")] public string Name { get; set; } [DataMember] [DisplayName("Alias")] public string Alias { get; set; } [DataMember] [DisplayName("IsDisplay")] public bool IsDisplay { get; set; } } public class TagMap : EntityTypeConfiguration<TagInfo>, IEntityTypeConfiguration { public TagMap() { ToTable("Modules_Tags"); HasKey(x => x.Id); Property(x => x.Alias).HasMaxLength(250).IsRequired(); Property(x => x.Name).IsRequired().HasMaxLength(250); Property(x => x.IsDisplay).IsRequired(); } } }<file_sep>using System; using CMSSolutions.Web.UI.ControlForms; using CMSSolutions.Websites.Entities; namespace CMSSolutions.Websites.Models { public class FilmFilesModel { public FilmFilesModel() { FileCode = Guid.NewGuid().ToString().Replace("-", string.Empty); } [ControlHidden] public long Id { get; set; } [ControlChoice(ControlChoice.DropDownList, Required = true, LabelText = "Ngôn ngữ hiển thị", ContainerCssClass = Constants.ContainerCssClassCol3, ContainerRowIndex = 0, OnSelectedIndexChanged = "$('#" + Extensions.Constants.ServerId + "').empty();")] public string LanguageCode { get; set; } [ControlCascadingDropDown(LabelText = "Trang web", ParentControl = "LanguageCode", AbsoluteParentControl = true, ContainerCssClass = Constants.ContainerCssClassCol3, ContainerRowIndex = 0)] public int SiteId { get; set; } [ControlCascadingDropDown(LabelText = "Máy chủ", ParentControl = "SiteId", AbsoluteParentControl = true, ContainerCssClass = Constants.ContainerCssClassCol3, ContainerRowIndex = 0)] public int ServerId { get; set; } [ControlText(Type = ControlText.TextBox, LabelText = "Mã file", Required = true, MaxLength = 50, ContainerCssClass = Constants.ContainerCssClassCol3, ContainerRowIndex = 1)] public string FileCode { get; set; } [ControlText(Type = ControlText.TextBox, LabelText = "Tên videos", PlaceHolder = "Tối đa 250 ký tự", Required = true, MaxLength = 250, ContainerCssClass = Constants.ContainerCssClassCol9, ContainerRowIndex = 1)] public string Name { get; set; } [ControlText(Type = ControlText.TextBox, LabelText = "Thư mục gốc", MaxLength = 50, ContainerCssClass = Constants.ContainerCssClassCol3, ContainerRowIndex = 2)] public string FolderName { get; set; } [ControlText(Type = ControlText.TextBox, LabelText = "Đường dẫn thư mục", MaxLength = 300, ContainerCssClass = Constants.ContainerCssClassCol3, ContainerRowIndex = 2)] public string FolderPath { get; set; } [ControlText(Type = ControlText.TextBox, LabelText = "Tên file", MaxLength = 50, ContainerCssClass = Constants.ContainerCssClassCol3, ContainerRowIndex = 2)] public string FileName { get; set; } [ControlText(Type = ControlText.TextBox, LabelText = "Đôi mở rộng", MaxLength = 50, ContainerCssClass = Constants.ContainerCssClassCol3, ContainerRowIndex = 2)] public string Extentions { get; set; } [ControlText(Type = ControlText.TextBox, LabelText = "Đường dẫn đầy đủ", MaxLength = 500, ContainerCssClass = Constants.ContainerCssClassCol12, ContainerRowIndex = 3)] public string FullPath { get; set; } [ControlText(Type = ControlText.TextBox, LabelText = "Kích thước", MaxLength = 250, ContainerCssClass = Constants.ContainerCssClassCol3, ContainerRowIndex = 4)] public string Size { get; set; } [ControlChoice(ControlChoice.CheckBox, LabelText = "Đang sử dụng", ContainerCssClass = Constants.ContainerCssClassCol3, ContainerRowIndex = 4)] public bool HasUse { get; set; } public static implicit operator FilmFilesModel(FilmFilesInfo entity) { return new FilmFilesModel { Id = entity.Id, LanguageCode = entity.LanguageCode, Name = entity.Name, SiteId = entity.SiteId, FolderName = entity.FolderName, FolderPath = entity.FolderPath, FileName = entity.FileName, Extentions = entity.Extentions, FullPath = entity.FullPath, Size = entity.Size, HasUse = entity.HasUse }; } } } <file_sep>using CMSSolutions.Data; using CMSSolutions.Events; using CMSSolutions.Services; using CMSSolutions.Websites.Entities; namespace CMSSolutions.Websites.Services { public interface ISmsMessageService : IGenericService<SmsMessageInfo, int>, IDependency { } public class SmsMessageService : GenericService<SmsMessageInfo, int>, ISmsMessageService { public SmsMessageService(IRepository<SmsMessageInfo, int> repository, IEventBus eventBus) : base(repository, eventBus) { } } }<file_sep>using System.Collections.Generic; using System.Data.SqlClient; using System.Linq; using CMSSolutions.Data; using CMSSolutions.Events; using CMSSolutions.Services; using CMSSolutions.Websites.Entities; namespace CMSSolutions.Websites.Services { public interface IActorService : IGenericService<ActorInfo, int>, IDependency { bool CheckExist(int id, string keyword); List<ActorInfo> SearchPaged( string searchText, int status, int pageIndex, int pageSize, out int totalRecord); } public class ActorService : GenericService<ActorInfo, int>, IActorService { public ActorService(IRepository<ActorInfo, int> repository, IEventBus eventBus) : base(repository, eventBus) { } public bool CheckExist(int id, string keyword) { var list = new List<SqlParameter> { AddInputParameter("@Id", id), AddInputParameter("@Keyword", keyword) }; var result = (int)ExecuteReaderResult("sp_Actors_CheckName", list.ToArray()); return result > 0; } public List<ActorInfo> SearchPaged(string searchText, int status,int pageIndex, int pageSize, out int totalRecord) { var list = new List<SqlParameter> { AddInputParameter("@Keyword", searchText), AddInputParameter("@Status", status), AddInputParameter("@PageIndex", pageIndex), AddInputParameter("@PageSize", pageSize) }; return ExecuteReader<ActorInfo>("sp_Actors_Search_Paged", "@TotalRecord", out totalRecord, list.ToArray()); } } } <file_sep>using CMSSolutions.Web.UI.ControlForms; using CMSSolutions.Websites.Entities; namespace CMSSolutions.Websites.Models { public class SiteModel { public SiteModel() { IsActived = true; } [ControlHidden] public int Id { get; set; } [ControlChoice(ControlChoice.DropDownList, Required = true, LabelText = "Ngôn ngữ hiển thị", ContainerCssClass = Constants.ContainerCssClassCol3, ContainerRowIndex = 0)] public string LanguageCode { get; set; } [ControlChoice(ControlChoice.CheckBox, LabelText = "", PrependText = "Sử dụng", ContainerCssClass = Constants.ContainerCssClassCol3, ContainerRowIndex = 0)] public bool IsActived { get; set; } [ControlText(Type = ControlText.TextBox, LabelText = "Tên trang web", PlaceHolder = "Tối đa 250 ký tự", Required = true, MaxLength = 250, ContainerCssClass = Constants.ContainerCssClassCol12, ContainerRowIndex = 1)] public string Name { get; set; } [ControlText(Type = ControlText.TextBox, LabelText = "Đường dẫn", PlaceHolder = "Tối đa 250 ký tự", MaxLength = 250, ContainerCssClass = Constants.ContainerCssClassCol12, ContainerRowIndex = 2)] public string Url { get; set; } [ControlText(Type = ControlText.TextBox, LabelText = "Tên miền", PlaceHolder = "Tối đa 50 ký tự", MaxLength = 50, ContainerCssClass = Constants.ContainerCssClassCol12, ContainerRowIndex = 3)] public string Domain { get; set; } [ControlText(LabelText = "Mô tả", PlaceHolder = "Tối đa 2000 ký tự", Type = ControlText.MultiText, Rows = 2, MaxLength = 2000, ContainerCssClass = Constants.ContainerCssClassCol12, ContainerRowIndex = 4)] public string Description { get; set; } public static implicit operator SiteModel(SiteInfo entity) { return new SiteModel { Id = entity.Id, LanguageCode = entity.LanguageCode, Name = entity.Name, Url = entity.Url, Domain = entity.Domain, IsActived = entity.IsActived, Description = entity.Description }; } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Web; using System.Web.Mvc; using CMSSolutions.Web.Mvc; using CMSSolutions.Web.Themes; using CMSSolutions.Web.UI.ControlForms; using CMSSolutions.Web.UI.Navigation; using CMSSolutions.Websites.Entities; using CMSSolutions.Websites.Extensions; using CMSSolutions.Websites.Models; using CMSSolutions.Websites.Services; namespace CMSSolutions.Websites.Controllers { [Themed(IsDashboard = true), Authorize] public class AdminFilmVideosController : BaseAdminController { public AdminFilmVideosController(IWorkContextAccessor workContextAccessor) : base(workContextAccessor) { } [Url("admin/films/select-videos")] public ActionResult Index() { var id = int.Parse(Request.QueryString["id"]); WorkContext.Breadcrumbs.Add(new Breadcrumb { Text = T("Quản lý phim"), Url = Url.Action("Index", "AdminFilm") }); WorkContext.Breadcrumbs.Add(new Breadcrumb { Text = T("Thông tin phim"), Url = Url.Action("Edit", "AdminFilm", new { id }) }); WorkContext.Breadcrumbs.Add(new Breadcrumb { Text = T("Chọn video hoặc trailer cho phim"), Url = "#" }); var returnUrl = Request.QueryString[Extensions.Constants.ReturnUrl]; var model = new FilmVideoModel { FilmId = id, ReturnUrl = returnUrl }; var result = new ControlFormResult<FilmVideoModel>(model) { Title = T("Chọn video hoặc trailer cho phim"), UpdateActionName = "Update", FormMethod = FormMethod.Post, SubmitButtonText = T("Lưu lại"), ShowBoxHeader = false, CancelButtonText = T("Trở về"), CancelButtonUrl = "javascript: backUrl();", FormWrapperStartHtml = Constants.Form.FormWrapperStartHtml, FormWrapperEndHtml = Constants.Form.FormWrapperEndHtml, SetJavascript = GetUrl() }; result.RegisterExternalDataSource(x => x.LanguageCode, y => BindLanguages()); result.RegisterCascadingDropDownDataSource(x => x.SiteId, Url.Action("GetSitesByLanguage")); result.RegisterCascadingDropDownDataSource(x => x.ServerId, Url.Action("GetServersBySite")); result.RegisterCascadingDropDownDataSource(x => x.RootFolders, Url.Action("GetRootFolders")); result.RegisterCascadingDropDownDataSource(x => x.FolderDay, Url.Action("GetDayFolders")); result.RegisterCascadingDropDownDataSource(x => x.ChildrenFolders, Url.Action("GetChildrenFolders")); result.RegisterCascadingDropDownDataSource(x => x.FileIds, Url.Action("GetFilesByFolder")); result.RegisterExternalDataSource(x => x.EpisodeIds, y => BindEpisodes()); var result2 = new ControlGridFormResult<FilmVideoInfo> { Title = T("Danh sách phim và trailer"), CssClass = "table table-bordered table-striped", IsAjaxSupported = true, FetchAjaxSource = GetFilmVideos, DefaultPageSize = WorkContext.DefaultPageSize, EnablePaginate = true, UpdateActionName = "Update", GridWrapperStartHtml = Constants.Grid.GridWrapperStartHtml, GridWrapperEndHtml = Constants.Grid.GridWrapperEndHtml, ClientId = TableName, ActionsColumnWidth = 100 }; result2.AddColumn(x => x.Id, T("ID")).AlignCenter().HasWidth(60); result2.AddColumn(x => x.FileName, T("Tên video")); result2.AddColumn(x => x.EpisodeName, T("Tập phim")); result2.AddColumn(x => x.FullPath, T("Đường dẫn")); result2.AddColumn(x => x.IsTraller) .HasHeaderText(T("Traller")) .AlignCenter() .HasWidth(100) .RenderAsStatusImage(); result2.AddColumn(x => x.IsActived) .HasHeaderText(T("Sử dụng")) .AlignCenter() .HasWidth(100) .RenderAsStatusImage(); result2.AddRowAction(true) .HasText(T("Xóa")) .HasName("Delete") .HasValue(x => x.Id) .HasButtonStyle(ButtonStyle.Danger) .HasButtonSize(ButtonSize.ExtraSmall) .HasConfirmMessage(T(Constants.Messages.ConfirmDeleteRecord).Text); result2.AddCustomVar(Extensions.Constants.Id, id); result2.AddReloadEvent("DELETE_ENTITY_COMPLETE"); return new ControlFormsResult(result, result2); } private string GetUrl() { var pageIndex = 1; if (Session[Extensions.Constants.PageIndex] != null) { pageIndex = int.Parse(Session[Extensions.Constants.PageIndex].ToString()); } Session[Extensions.Constants.BackPageIndex] = "BACKPAGE"; var returnUrl = Request.QueryString[Extensions.Constants.ReturnUrl]; var url = Url.Action("Index", "AdminFilm"); var sb = new StringBuilder(); sb.Append("<script type=\"text/javascript\">"); sb.Append("function backUrl() {"); sb.AppendFormat("window.location = '{0}?{1}={2}&{3}={4}';", url, Extensions.Constants.ReturnUrl, returnUrl, Extensions.Constants.PageIndex, pageIndex); sb.Append("}"); sb.Append("</script>"); return sb.ToString(); } private IEnumerable<SelectListItem> BindEpisodes() { var service = WorkContext.Resolve<IEpisodesService>(); var items = service.GetAll(WorkContext.CurrentCulture, 0, (int)Status.Approved); var result = new List<SelectListItem>(); result.AddRange(items.Select(item => new SelectListItem { Text = item.EpisodeName, Value = item.Id.ToString() })); return result; } [HttpPost, ValidateInput(false), FormButton("Save")] [Url("admin/select-videos/update")] public ActionResult Update(FilmVideoModel model) { if (!ModelState.IsValid) { return new AjaxResult().Alert(T(Constants.Messages.InvalidModel)); } var service = WorkContext.Resolve<IFilmVideoService>(); var service2 = WorkContext.Resolve<IFilmFilesService>(); var service3 = WorkContext.Resolve<IFilmService>(); var film = service3.GetById(model.FilmId); if (model.Subtitle == null) { return new AjaxResult().Alert(T("Bạn chưa nhập Subtitle.")); } var listSub = model.Subtitle.Split(','); if (listSub.Length != model.EpisodeIds.Length) { return new AjaxResult().Alert(T("Kiểm tra lại số lượng Subtitle so với số tập phim.")); } var index = 0; if (model.FileIds != null && model.FileIds.Length > 0) { if (listSub.Length != model.FileIds.Length) { return new AjaxResult().Alert(T("Kiểm tra lại số lượng Subtitle so với số phim.")); } var server = WorkContext.Resolve<IFilmServersService>().GetById(model.ServerId); foreach (var fileId in model.FileIds) { var item = service.GetByFilmFile(model.FilmId, fileId) ?? new FilmVideoInfo(); var file = service2.GetById(fileId); if (file != null) { item.FileId = file.Id; item.FullPath = file.FullPath; item.BaseUrl = file.FullPath; item.StreamingUrl = string.Format(Extensions.Constants.StreamingUrl, server.ServerIP, file.FolderPath + "/" + file.FileName); } item.FilmId = model.FilmId; item.EpisodeId = model.EpisodeIds[index]; item.IsTraller = model.IsTraller; item.IsActived = model.IsActived; item.ImageIcon = film.ImageIcon; item.Subtitle = listSub[index]; item.UrlAlbum = string.Empty; service.Save(item); #region Update name if (file != null) { file.Name = film.FilmName; file.HasUse = true; service2.Update(file); } #endregion index++; } } else { var listFilms = model.UrlSource.Split(','); if (listSub.Length != listFilms.Length) { return new AjaxResult().Alert(T("Kiểm tra lại số lượng Subtitle so với số url phim.")); } foreach (var url in listFilms) { var item = new FilmVideoInfo { FilmId = model.FilmId, EpisodeId = model.EpisodeIds[index], IsTraller = model.IsTraller, IsActived = model.IsActived, ImageIcon = film.ImageIcon, UrlSource = url, Subtitle = listSub[index], FullPath = url, BaseUrl = url, StreamingUrl = url, UrlAlbum = model.UrlAlbum }; service.Save(item); index++; } } var redirectUrl = string.Format("{0}?id={1}", Url.Action("Index", "AdminFilmVideos"), film.Id); if (!string.IsNullOrEmpty(model.ReturnUrl)) { redirectUrl = string.Format("{0}?id={1}&{2}={3}", Url.Action("Index", "AdminFilmVideos"), film.Id, Extensions.Constants.ReturnUrl, model.ReturnUrl); } return new AjaxResult() .NotifyMessage("UPDATE_ENTITY_COMPLETE") .Alert(T("Cập nhật thành công!")) .Redirect(redirectUrl); } [Url("admin/film-files/get-files-by-folders")] public ActionResult GetFilesByFolder() { var folderPath = string.Empty; if (Utilities.IsNotNull(Request.Form[Extensions.Constants.ChildrenFolders])) { folderPath = Request.Form[Extensions.Constants.ChildrenFolders]; } var service = WorkContext.Resolve<IFilmVideoService>(); var items = new List<SelectListItem>(); var listFiles = service.GetFilesByFile(folderPath); if (listFiles != null && listFiles.Count > 0) { items.AddRange(listFiles.Select(item => new SelectListItem { Text = item.FullPath, Value = item.Id.ToString() })); } return Json(items); } [Url("admin/film-files/get-day-folders")] public ActionResult GetDayFolders() { var folderName = string.Empty; if (Utilities.IsNotNull(Request.Form[Extensions.Constants.RootFolders])) { folderName = Request.Form[Extensions.Constants.RootFolders]; } var service = WorkContext.Resolve<IFilmFilesService>(); var items = new List<SelectListItem>(); var listFolders = service.GetDayFolderByRoot(folderName); if (listFolders != null && listFolders.Count > 0) { items.AddRange(listFolders.Select(item => new SelectListItem { Text = item.FolderDay, Value = item.FolderDay })); } return Json(items); } [Url("admin/film-files/get-children-folders")] public ActionResult GetChildrenFolders() { var folderName = string.Empty; if (Utilities.IsNotNull(Request.Form[Extensions.Constants.FolderDay])) { folderName = Request.Form[Extensions.Constants.FolderDay]; } var service = WorkContext.Resolve<IFilmFilesService>(); var items = new List<SelectListItem>(); var listFolders = service.GetChildrenByRootFolders(folderName); if (listFolders != null && listFolders.Count > 0) { items.AddRange(listFolders.Select(item => new SelectListItem { Text = item.FolderPath, Value = item.FolderPath })); } return Json(items); } [FormButton("Delete")] [HttpPost, ActionName("Update")] public ActionResult Delete(int id) { var service = WorkContext.Resolve<IFilmVideoService>(); var item = service.GetById(id); if (item.FileId > 0) { var fileService = WorkContext.Resolve<IFilmFilesService>(); var file = fileService.GetById(item.FileId); if (file != null) { file.HasUse = false; file.Name = string.Empty; fileService.Update(file); } } service.Delete(item); return new AjaxResult().NotifyMessage("DELETE_ENTITY_COMPLETE"); } private ControlGridAjaxData<FilmVideoInfo> GetFilmVideos(ControlGridFormRequest options) { var filmId = 0; if (Utilities.IsNotNull(Request.Form[Extensions.Constants.Id])) { filmId = Convert.ToInt32(Request.Form[Extensions.Constants.Id]); } var totals = 0; var items = WorkContext.Resolve<IFilmVideoService>().GetByFilm(filmId, options.PageIndex, options.PageSize, out totals); var result = new ControlGridAjaxData<FilmVideoInfo>(items, totals); return result; } } } <file_sep>using System; using System.Web.Mvc; using CMSSolutions.ContentManagement.Widgets.Services; using CMSSolutions.DisplayManagement; using CMSSolutions.Web.Mvc; using CMSSolutions.Web.Themes; using CMSSolutions.Websites.Entities; using CMSSolutions.Websites.Extensions; using CMSSolutions.Websites.Models; using CMSSolutions.Websites.Services; using Microsoft.Web.WebPages.OAuth; namespace CMSSolutions.Websites.Controllers { [Themed(IsDashboard = false)] public class HomeController : BaseHomeController { private readonly dynamic shapeFactory; public HomeController(IWorkContextAccessor workContextAccessor, IShapeFactory shapeFactory) : base(workContextAccessor) { this.shapeFactory = shapeFactory; } [Url("", Priority = 10)] public ActionResult Index() { UrlLogin = Url.Action("Index", "Home"); if (IsLogin) { var customerService = WorkContext.Resolve<ICustomerService>(); CustomerInfo customer = customerService.GetCustomerByCacheId(UserId); SetCustomerState(customer); } var serviceCategory = WorkContext.Resolve<ICategoryService>(); serviceCategory.LanguageCode = WorkContext.CurrentCulture; if (WorkContext.DomainName == Extensions.Constants.JJDomainName) { SiteId = (int)Site.JJHome; serviceCategory.SiteId = (int)Site.JJHome; var jjHome = serviceCategory.GetHomePage(); ViewData[Extensions.Constants.HeaderTitle] = jjHome.Name; ViewData[Extensions.Constants.HeaderDescription] = jjHome.Description; ViewData[Extensions.Constants.HeaderKeywords] = jjHome.Tags; ViewBag.ReturnUrl = ""; return View("JJIndex", OAuthWebSecurity.RegisteredClientData); } SiteId = (int)Site.Home; serviceCategory.SiteId = (int)Site.Home; var home = serviceCategory.GetHomePage(); ViewData[Extensions.Constants.HeaderTitle] = home.Name; ViewData[Extensions.Constants.HeaderDescription] = home.Description; ViewData[Extensions.Constants.HeaderKeywords] = home.Tags; BuildModules(); return View("Index", OAuthWebSecurity.RegisteredClientData); } public override void BuildModules() { var widget = WorkContext.Resolve<IWidgetService>(); var viewRenderer = new ViewRenderer { Context = ControllerContext }; if (!IsVip) { #region BannerPageLeft var bannerPageLeft = widget.GetWidget(HomeWidgets.BannerPageLeft.ToString()); if (bannerPageLeft != null) { var widgetShape = shapeFactory.Widget(); widgetShape.Widget = bannerPageLeft; WorkContext.Layout.AdBannerPageLeft(widgetShape); } #endregion #region BannerPageCenter var bannerPageCenter = widget.GetWidget(HomeWidgets.BannerPageCenter.ToString()); if (bannerPageCenter != null) { var widgetShape = shapeFactory.Widget(); widgetShape.Widget = bannerPageCenter; WorkContext.Layout.AdBannerPageCenter(widgetShape); } #endregion #region BannerPageRight var bannerPageRight = widget.GetWidget(HomeWidgets.BannerPageRight.ToString()); if (bannerPageRight != null) { var widgetShape = shapeFactory.Widget(); widgetShape.Widget = bannerPageRight; WorkContext.Layout.AdBannerPageRight(widgetShape); } #endregion #region BannerContentLeftFirst var bannerContentLeftFirst = widget.GetWidget(HomeWidgets.BannerContentLeftFirst.ToString()); if (bannerContentLeftFirst != null) { var widgetShape = shapeFactory.Widget(); widgetShape.Widget = bannerContentLeftFirst; WorkContext.Layout.AdBannerContentLeftFirst(widgetShape); } #endregion #region BannerContentLeftSecond var bannerContentLeftSecond = widget.GetWidget(HomeWidgets.BannerContentLeftSecond.ToString()); if (bannerContentLeftSecond != null) { var widgetShape = shapeFactory.Widget(); widgetShape.Widget = bannerContentLeftSecond; WorkContext.Layout.AdBannerContentLeftSecond(widgetShape); } #endregion #region BannerContentLeftThird var bannerContentLeftThird = widget.GetWidget(HomeWidgets.BannerContentLeftThird.ToString()); if (bannerContentLeftThird != null) { var widgetShape = shapeFactory.Widget(); widgetShape.Widget = bannerContentLeftThird; WorkContext.Layout.AdBannerContentLeftThird(widgetShape); } #endregion #region BannerContentLeftFourth var bannerContentLeftFourth = widget.GetWidget(HomeWidgets.BannerContentLeftFourth.ToString()); if (bannerContentLeftFourth != null) { var widgetShape = shapeFactory.Widget(); widgetShape.Widget = bannerContentLeftFourth; WorkContext.Layout.AdBannerContentLeftFourth(widgetShape); } #endregion #region BannerContentLeftFifth var bannerContentLeftFifth = widget.GetWidget(HomeWidgets.BannerContentLeftFifth.ToString()); if (bannerContentLeftFifth != null) { var widgetShape = shapeFactory.Widget(); widgetShape.Widget = bannerContentLeftFifth; WorkContext.Layout.AdBannerContentLeftFifth(widgetShape); } #endregion #region BannerContentLeftSixth var bannerContentLeftSixth = widget.GetWidget(HomeWidgets.BannerContentLeftSixth.ToString()); if (bannerContentLeftSixth != null) { var widgetShape = shapeFactory.Widget(); widgetShape.Widget = bannerContentLeftSixth; WorkContext.Layout.AdBannerContentLeftSixth(widgetShape); } #endregion #region BannerContentLeftSeventh var bannerContentLeftSeventh = widget.GetWidget(HomeWidgets.BannerContentLeftSeventh.ToString()); if (bannerContentLeftSeventh != null) { var widgetShape = shapeFactory.Widget(); widgetShape.Widget = bannerContentLeftSeventh; WorkContext.Layout.AdBannerContentLeftSeventh(widgetShape); } #endregion #region BannerRightFirst var bannerRightFirst = widget.GetWidget(HomeWidgets.BannerRightFirst.ToString()); if (bannerRightFirst != null) { var widgetShape = shapeFactory.Widget(); widgetShape.Widget = bannerRightFirst; WorkContext.Layout.AdBannerRightFirst(widgetShape); } #endregion #region BannerRightSecond var bannerRightSecond = widget.GetWidget(HomeWidgets.BannerRightSecond.ToString()); if (bannerRightSecond != null) { var widgetShape = shapeFactory.Widget(); widgetShape.Widget = bannerRightSecond; WorkContext.Layout.AdBannerRightSecond(widgetShape); } #endregion #region BannerRightSixth var bannerRightSixth = widget.GetWidget(HomeWidgets.BannerRightSixth.ToString()); if (bannerRightSixth != null) { var widgetShape = shapeFactory.Widget(); widgetShape.Widget = bannerRightSixth; WorkContext.Layout.AdBannerRightSixth(widgetShape); } #endregion #region BannerRightThird var bannerRightThird = widget.GetWidget(HomeWidgets.BannerRightThird.ToString()); if (bannerRightThird != null) { var widgetShape = shapeFactory.Widget(); widgetShape.Widget = bannerRightThird; WorkContext.Layout.AdBannerRightThird(widgetShape); } #endregion #region BannerRightFourth var bannerRightFourth = widget.GetWidget(HomeWidgets.BannerRightFourth.ToString()); if (bannerRightFourth != null) { var widgetShape = shapeFactory.Widget(); widgetShape.Widget = bannerRightFourth; WorkContext.Layout.AdBannerRightFourth(widgetShape); } #endregion } else { #region BannerPageLeftVip var bannerPageLeftVip = widget.GetWidget(HomeWidgets.BannerPageLeftVip.ToString()); if (bannerPageLeftVip != null) { var widgetShape = shapeFactory.Widget(); widgetShape.Widget = bannerPageLeftVip; WorkContext.Layout.AdBannerPageLeftVip(widgetShape); } #endregion #region BannerPageCenterVip var bannerPageCenterVip = widget.GetWidget(HomeWidgets.BannerPageCenterVip.ToString()); if (bannerPageCenterVip != null) { var widgetShape = shapeFactory.Widget(); widgetShape.Widget = bannerPageCenterVip; WorkContext.Layout.AdBannerPageCenterVip(widgetShape); } #endregion #region BannerPageRightVip var bannerPageRightVip = widget.GetWidget(HomeWidgets.BannerPageRightVip.ToString()); if (bannerPageRightVip != null) { var widgetShape = shapeFactory.Widget(); widgetShape.Widget = bannerPageRightVip; WorkContext.Layout.AdBannerPageRightVip(widgetShape); } #endregion } #region HomeSliderBanner var modelSlider = new DataViewerModel {Data = BuildSlider(SiteId, (int) SliderPages.Home)}; var viewSlider = viewRenderer.RenderPartialView(Extensions.Constants.SliderBannerFilePath, modelSlider); WorkContext.Layout.SliderBanner.Add(new MvcHtmlString(viewSlider)); var viewRegisterResource = viewRenderer.RenderPartialView(Extensions.Constants.RegisterResourceFilePath, null); WorkContext.Layout.RegisterResource.Add(new MvcHtmlString(viewRegisterResource)); #endregion #region HomeFooterLogoInformation var homeFooterLogoInformation = widget.GetWidget(HomeWidgets.HomeFooterLogoInformation.ToString()); if (homeFooterLogoInformation != null) { var widgetShape = shapeFactory.Widget(); widgetShape.Widget = homeFooterLogoInformation; WorkContext.Layout.FooterLogoInformation(widgetShape); } #endregion #region HomeFacebookFanpage var homeFacebookFanpage = widget.GetWidget(HomeWidgets.HomeFacebookFanpage.ToString()); if (homeFacebookFanpage != null) { var widgetShape = shapeFactory.Widget(); widgetShape.Widget = homeFacebookFanpage; WorkContext.Layout.AdFacebookFanpage(widgetShape); } #endregion #region SocialNetwork var socialNetwork = widget.GetWidget(HomeWidgets.DisplaySocialNetwork.ToString()); if (socialNetwork != null) { var widgetShape = shapeFactory.Widget(); widgetShape.Widget = socialNetwork; WorkContext.Layout.DisplaySocialNetwork(widgetShape); } #endregion #region News var viewNews = viewRenderer.RenderPartialView(Extensions.Constants.NewsViewFilePath, null); WorkContext.Layout.DisplayNews.Add(new MvcHtmlString(viewNews)); #endregion #region Tags var serviceTags = WorkContext.Resolve<ITagService>(); var modelTags = new TagViewModel { ListTags = serviceTags.GetDisplayTags() }; var viewTags = viewRenderer.RenderPartialView(Extensions.Constants.TagViewFilePath, modelTags); WorkContext.Layout.DisplayTags.Add(new MvcHtmlString(viewTags)); #endregion #region CategoryContentFirst var modelFirst = new DataViewCategoryModel { Type = (int)HomeDisplayFilmType.FilmHot, Title = "Sự kiện: Phim Đang HOT", TextNext = "Còn nữa ››", UrlNext = Url.Action("FilmHot", "HomeCategory"), SliderName = "FilmFirst" }; modelFirst.HtmlFilmHot = GetFilmHtml(modelFirst.Type); var viewFilmFirst = viewRenderer.RenderPartialView(Extensions.Constants.CategoryContentFirstViewFilePath, modelFirst); WorkContext.Layout.CategoryContentLeftFirst.Add(new MvcHtmlString(viewFilmFirst)); #endregion #region CategoryContentSecond var modelSecond = new DataViewCategoryModel { Type = (int)HomeDisplayFilmType.FilmRetail, Title = "Phim lẻ mới up", TextNext = "Tất Tần Tật ››", UrlNext = Url.Action("Index", "HomeCategory", new { @alias = "phim-le", @id = 2 }), SliderName = "FilmSecond" }; modelSecond.HtmlFilmRetail = GetFilmHtml(modelSecond.Type); var viewFilmSecond = viewRenderer.RenderPartialView(Extensions.Constants.CategoryContentSecondViewFilePath, modelSecond); WorkContext.Layout.CategoryContentLeftSecond.Add(new MvcHtmlString(viewFilmSecond)); #endregion #region CategoryContentThird var modelThird = new DataViewCategoryModel { Type = (int)HomeDisplayFilmType.FilmLengthEpisodes, Title = "Phim bộ mới up", TextNext = "Tất Tần Tật ››", UrlNext = Url.Action("Index", "HomeCategory", new { @alias = "phim-bo", @id = 3 }), SliderName = "FilmThird" }; modelThird.HtmlFilmLengthEpisodes = GetFilmHtml(modelThird.Type); var viewFilmThird = viewRenderer.RenderPartialView(Extensions.Constants.CategoryContentThirdViewFilePath, modelThird); WorkContext.Layout.CategoryContentLeftThird.Add(new MvcHtmlString(viewFilmThird)); #endregion #region CategoryContentFourth var modelFourth = new DataViewCategoryModel { Type = (int)HomeDisplayFilmType.FilmJJChannelIntroduce, Title = "JJ Channel giới thiệu", TextNext = "Tất Tần Tật ››", UrlNext = Url.Action("Index", "HomeJJChannel", new { @alias = "jj-channel-viphd", @id = 9 }), SliderName = "FilmFourth" }; modelFourth.HtmlFilmJJChannelIntroduce = GetFilmHtml(modelFourth.Type); var viewFilmFourth = viewRenderer.RenderPartialView(Extensions.Constants.CategoryContentFourthViewFilePath, modelFourth); WorkContext.Layout.CategoryContentLeftFourth.Add(new MvcHtmlString(viewFilmFourth)); #endregion #region CategoryContentFifth var modelFifth = new DataViewCategoryModel { Type = (int)HomeDisplayFilmType.FilmTheater, Title = "Phim chiếu rạp", TextNext = "Tất Tần Tật ››", UrlNext = Url.Action("Index", "HomeTheater"), SliderName = "FilmFifth" }; modelFifth.HtmlFilmTheater = GetFilmHtml(modelFifth.Type); var viewFilmFifth = viewRenderer.RenderPartialView(Extensions.Constants.CategoryContentFifthViewFilePath, modelFifth); WorkContext.Layout.CategoryContentLeftFifth.Add(new MvcHtmlString(viewFilmFifth)); #endregion #region CategoryContentSixth var modelSixth = new DataViewCategoryModel { Type = (int)HomeDisplayFilmType.TVShow, Title = "TV Show", TextNext = "Tất Tần Tật ››", UrlNext = Url.Action("Index", "HomeShow", new { @alias = "shows", @id = 4 }), SliderName = "TVShows" }; modelSixth.HtmlTVShow = GetFilmHtml(modelSixth.Type); var viewFilmSixth = viewRenderer.RenderPartialView(Extensions.Constants.CategoryContentSixthViewFilePath, modelSixth); WorkContext.Layout.CategoryContentLeftSixth.Add(new MvcHtmlString(viewFilmSixth)); #endregion #region CategoryContentSeventh var modelSeventh = new DataViewCategoryModel { Type = (int)HomeDisplayFilmType.Clip, Title = "Clip", TextNext = "Tất Tần Tật ››", UrlNext = Url.Action("Index", "HomeClip", new { @alias = "clip-hay", @id = 5 }), SliderName = "Clip" }; modelSeventh.HtmlClip = GetFilmHtml(modelSeventh.Type); var viewFilmSeventh = viewRenderer.RenderPartialView(Extensions.Constants.CategoryContentSeventhViewFilePath, modelSeventh); WorkContext.Layout.CategoryContentLeftSeventh.Add(new MvcHtmlString(viewFilmSeventh)); #endregion #region DisplayStatistic1 var modelStatistic1 = new DataViewCategoryModel { Type = (int)HomeDisplayFilmType.StatisticalFilmRetail, Title = "PHIM LẺ XEM NHIỀU NHẤT" }; var viewStatistic1 = viewRenderer.RenderPartialView(Extensions.Constants.Statistic1FilePath, modelStatistic1); WorkContext.Layout.DisplayStatistic1.Add(new MvcHtmlString(viewStatistic1)); #endregion #region DisplayStatistic2 var modelStatistic2 = new DataViewCategoryModel { Type = (int)HomeDisplayFilmType.StatisticalLengthEpisodes, Title = "PHIM BỘ XEM NHIỀU NHẤT" }; var viewStatistic2 = viewRenderer.RenderPartialView(Extensions.Constants.Statistic2FilePath, modelStatistic2); WorkContext.Layout.DisplayStatistic2.Add(new MvcHtmlString(viewStatistic2)); #endregion } } } <file_sep>using CMSSolutions.Web.UI.ControlForms; using CMSSolutions.Websites.Entities; namespace CMSSolutions.Websites.Models { public class RateModel { [ControlHidden] public long Id { get; set; } [ControlText(Type = ControlText.TextBox, MaxLength = 250, LabelText = "Tên phim", ContainerCssClass = Constants.ContainerCssClassCol12, ContainerRowIndex = 0)] public string FilmName { get; set; } [ControlNumeric(LabelText = "Đánh giá", ContainerCssClass = Constants.ContainerCssClassCol4, ContainerRowIndex = 1)] public int Rate { get; set; } [ControlText(Type = ControlText.TextBox, MaxLength = 50, LabelText = "Mã khách hàng", ContainerCssClass = Constants.ContainerCssClassCol4, ContainerRowIndex = 1)] public string CustomerCode { get; set; } [ControlText(Type = ControlText.TextBox, MaxLength = 250, LabelText = "Họ và Tên", ContainerCssClass = Constants.ContainerCssClassCol4, ContainerRowIndex = 1)] public string CustomerName { get; set; } [ControlText(Type = ControlText.TextBox, MaxLength = 250, LabelText = "Thông báo giật lag", ContainerCssClass = Constants.ContainerCssClassCol12, ContainerRowIndex = 2)] public string AlertLag { get; set; } [ControlText(Type = ControlText.TextBox, MaxLength = 250, LabelText = "Thông báo lỗi", ContainerCssClass = Constants.ContainerCssClassCol12, ContainerRowIndex = 3)] public string AlertError { get; set; } [ControlText(Type = ControlText.MultiText, Rows = 2, MaxLength = 2000, LabelText = "Nội dung thông báo lỗi", ContainerCssClass = Constants.ContainerCssClassCol12, ContainerRowIndex = 4)] public string Messages { get; set; } public static implicit operator RateModel(RateInfo entity) { return new RateModel { Id = entity.Id, FilmName = entity.FilmName, Rate = entity.Rate, CustomerCode = entity.CustomerCode, CustomerName = entity.CustomerName, AlertError = entity.AlertError, AlertLag = entity.AlertLag, Messages = entity.Messages }; } } } <file_sep>using System; using System.Globalization; using System.IO; using System.Text; using System.Web.Mvc; using CMSSolutions.Extensions; using CMSSolutions.Web.Mvc; using CMSSolutions.Web.Routing; using CMSSolutions.Web.Themes; using CMSSolutions.Web.UI.ControlForms; using CMSSolutions.Web.UI.Navigation; using CMSSolutions.Websites.Entities; using CMSSolutions.Websites.Extensions; using CMSSolutions.Websites.Models; using CMSSolutions.Websites.Services; using GemBox.Spreadsheet; namespace CMSSolutions.Websites.Controllers { [Themed(IsDashboard = true), Authorize] public class AdminCustomerController : BaseAdminController { public AdminCustomerController(IWorkContextAccessor workContextAccessor) : base(workContextAccessor) { TableName = "tblCustomers"; } [Url("admin/customers")] public ActionResult Index() { WorkContext.Breadcrumbs.Add(new Breadcrumb { Text = T("Quản lý khách hàng"), Url = "#" }); var result = new ControlGridFormResult<CustomerInfo> { Title = T("Quản lý khách hàng"), CssClass = "table table-bordered table-striped", IsAjaxSupported = true, FetchAjaxSource = GetCustomers, DefaultPageSize = WorkContext.DefaultPageSize, EnablePaginate = true, UpdateActionName = "Update", GridWrapperStartHtml = Constants.Grid.GridWrapperStartHtml, GridWrapperEndHtml = Constants.Grid.GridWrapperEndHtml, ClientId = TableName, ActionsColumnWidth = 200 }; result.AddCustomVar(Extensions.Constants.SearchText, "$('#" + Extensions.Constants.SearchText + "').val();", true); result.AddCustomVar(Extensions.Constants.FilmTypesId, "$('#" + Extensions.Constants.FilmTypesId + "').val();", true); result.AddCustomVar(Extensions.Constants.CountryId, "$('#" + Extensions.Constants.CountryId + "').val();", true); result.AddCustomVar(Extensions.Constants.StatusId, "$('#" + Extensions.Constants.StatusId + "').val();", true); result.AddCustomVar(Extensions.Constants.FromDate, "$('#" + Extensions.Constants.FromDate + "').val();", true); result.AddCustomVar(Extensions.Constants.ToDate, "$('#" + Extensions.Constants.ToDate + "').val();", true); result.AddColumn(x => x.CustomerCode, T("Mã KH")).HasWidth(100).AlignCenter(); result.AddColumn(x => x.FullName, T("<NAME>")); result.AddColumn(x => x.Email, T("Email")); result.AddColumn(x => x.VipXu, T("VIP Xu")); result.AddColumn(x => x.TotalDay, T("Tổng ngày")); result.AddColumn(x => x.TextStartDate, T("Từ ngày")); result.AddColumn(x => x.TextEndDate, T("Đến ngày")); result.AddAction().HasText(T("Thêm mới")) .HasUrl(Url.Action("Edit", RouteData.Values.Merge(new { id = 0 }))) .HasButtonStyle(ButtonStyle.Primary) .HasCssClass(Constants.RowLeft); result.AddAction().HasText(T("Xuất danh sách KH")) .HasUrl(Url.Action("ExportExcel")) .HasButtonStyle(ButtonStyle.Info) .HasRow(true); result.AddAction(new ControlFormHtmlAction(BuildSearchText)).HasParentClass(Constants.ContainerCssClassCol3); result.AddAction(new ControlFormHtmlAction(BuildFilmTypes)).HasParentClass(Constants.ContainerCssClassCol3); result.AddAction(new ControlFormHtmlAction(BuildCountries)).HasParentClass(Constants.ContainerCssClassCol3); result.AddAction(new ControlFormHtmlAction(BuildStatus)).HasParentClass(Constants.ContainerCssClassCol3); result.AddAction(new ControlFormHtmlAction(() => BuildFromDate())).HasParentClass(Constants.ContainerCssClassCol3); result.AddAction(new ControlFormHtmlAction(() => BuildToDate())).HasParentClass(Constants.ContainerCssClassCol3); result.AddRowAction(true) .HasText(T("Kích hoạt")) .HasName("SetActived") .HasValue(x => x.Id) .HasButtonSize(ButtonSize.ExtraSmall) .HasButtonStyle(ButtonStyle.Success) .EnableWhen(x => x.IsBlock); result.AddRowAction() .HasText(T("Sửa")) .HasUrl(x => Url.Action("Edit", RouteData.Values.Merge(new { id = x.Id }))) .HasButtonStyle(ButtonStyle.Default) .HasButtonSize(ButtonSize.ExtraSmall); result.AddRowAction() .HasText(T("Lịch sử")) .HasUrl(x => Url.Action("History", RouteData.Values.Merge(new { id = x.Id }))) .HasButtonStyle(ButtonStyle.Warning) .HasButtonSize(ButtonSize.ExtraSmall); result.AddReloadEvent("UPDATE_ENTITY_COMPLETE"); result.AddReloadEvent("DELETE_ENTITY_COMPLETE"); return result; } private ControlGridAjaxData<CustomerInfo> GetCustomers(ControlGridFormRequest options) { var searchText = string.Empty; if (Utilities.IsNotNull(Request.Form[Extensions.Constants.SearchText])) { searchText = Request.Form[Extensions.Constants.SearchText]; } var fromDate = DateTime.Now.Date; if (Utilities.IsNotNull(Request.Form[Extensions.Constants.FromDate])) { fromDate = DateTime.ParseExact(Request.Form[Extensions.Constants.FromDate], "dd/MM/yyyy", CultureInfo.InvariantCulture); } var toDate = DateTime.Now.Date; if (Utilities.IsNotNull(Request.Form[Extensions.Constants.ToDate])) { toDate = DateTime.ParseExact(Request.Form[Extensions.Constants.ToDate], "dd/MM/yyyy", CultureInfo.InvariantCulture); } var filmTypesId = 0; if (Utilities.IsNotNull(Request.Form[Extensions.Constants.FilmTypesId])) { filmTypesId = Convert.ToInt32(Request.Form[Extensions.Constants.FilmTypesId]); } var countryId = 0; if (Utilities.IsNotNull(Request.Form[Extensions.Constants.CountryId])) { countryId = Convert.ToInt32(Request.Form[Extensions.Constants.CountryId]); } var status = 0; if (Utilities.IsNotNull(Request.Form[Extensions.Constants.StatusId])) { status = Convert.ToInt32(Request.Form[Extensions.Constants.StatusId]); } int totals; var service = WorkContext.Resolve<ICustomerService>(); var records = service.SearchPaged( searchText, filmTypesId, countryId, fromDate, toDate, -1, status, options.PageIndex, options.PageSize, out totals); return new ControlGridAjaxData<CustomerInfo>(records, totals); } [ActionName("Update")] [HttpPost, FormButton("SetActived")] public ActionResult SetDefault(int id) { var service = WorkContext.Resolve<ICustomerService>(); var item = service.GetById(id); item.IsBlock = false; service.Update(item); return new AjaxResult() .NotifyMessage("UPDATE_ENTITY_COMPLETE") .Alert(T("Đã kích hoạt tài khoản " + item.UserName)); } [Url("admin/customers/history")] public ActionResult History(int id) { WorkContext.Breadcrumbs.Add(new Breadcrumb { Text = T("Quản lý khách hàng"), Url = Url.Action("Index") }); WorkContext.Breadcrumbs.Add(new Breadcrumb { Text = T("Lịch sử khách hàng"), Url = "#" }); TableName = "tblHistories"; var result = new ControlGridFormResult<CustomerHistoriesInfo> { Title = T("Lịch sử khách hàng"), CssClass = "table table-bordered table-striped", FetchAjaxSource = (x => GetHistories(id, x)), ActionsColumnWidth = 100, EnablePaginate = true, DefaultPageSize = 50, ClientId = TableName, GridWrapperStartHtml = Constants.Grid.GridWrapperStartHtml, GridWrapperEndHtml = Constants.Grid.GridWrapperEndHtml }; result.AddCustomVar(Extensions.Constants.FromDate, "$('#" + Extensions.Constants.FromDate + "').val();", true); result.AddCustomVar(Extensions.Constants.ToDate, "$('#" + Extensions.Constants.ToDate + "').val();", true); result.AddCustomVar(Extensions.Constants.TypeSearch, "$('#" + Extensions.Constants.TypeSearch + "').val();", true); result.AddCustomVar(Extensions.Constants.StatusId, "$('#" + Extensions.Constants.StatusId + "').val();", true); result.AddColumn(x => x.TransactionCode, T("Mã giao dịch")); result.AddColumn(x => x.Action, T("Hành động")); result.AddColumn(x => x.TextCreateDate, T("Ngày thực hiện")); result.AddColumn(x => x.Description, T("Nội dung thực hiện")); result.AddColumn(x => EnumExtensions.GetDisplayName((CustomerLogType)x.Type), T("Loại log")); result.AddAction().HasText(T("Trở về")) .HasUrl(Url.Action("Index")) .HasButtonStyle(ButtonStyle.Danger) .HasBoxButton(false) .HasCssClass(Constants.RowLeft) .HasRow(true); result.AddAction(new ControlFormHtmlAction(() => BuildFromDate(false))).HasParentClass(Constants.ContainerCssClassCol3); result.AddAction(new ControlFormHtmlAction(() => BuildToDate(false))).HasParentClass(Constants.ContainerCssClassCol3); result.AddAction(new ControlFormHtmlAction(BuildTypes)).HasParentClass(Constants.ContainerCssClassCol3); result.AddAction(new ControlFormHtmlAction(BuildStatus)).HasParentClass(Constants.ContainerCssClassCol3); return result; } private string BuildTypes() { var list = EnumExtensions.GetListItems<CustomerLogType>(); var sb = new StringBuilder(); sb.AppendFormat(T("Loại log") + " <select id=\"" + Extensions.Constants.TypeSearch + "\" name=\"" + Extensions.Constants.TypeSearch + "\" autocomplete=\"off\" class=\"uniform form-control col-md-3\" onchange=\"$('#" + TableName + "').jqGrid().trigger('reloadGrid');\">"); foreach (var status in list) { sb.AppendFormat("<option value=\"{1}\">{0}</option>", status.Text, status.Value); } sb.Append("</select>"); return sb.ToString(); } private ControlGridAjaxData<CustomerHistoriesInfo> GetHistories(int id, ControlGridFormRequest options) { var fromDate = Utilities.DateNull(); if (Utilities.IsNotNull(Request.Form[Extensions.Constants.FromDate])) { fromDate = DateTime.ParseExact(Request.Form[Extensions.Constants.FromDate], "dd/MM/yyyy", CultureInfo.InvariantCulture); } var toDate = Utilities.DateNull(); if (Utilities.IsNotNull(Request.Form[Extensions.Constants.ToDate])) { toDate = DateTime.ParseExact(Request.Form[Extensions.Constants.ToDate], "dd/MM/yyyy", CultureInfo.InvariantCulture); } var type = 0; if (Utilities.IsNotNull(Request.Form[Extensions.Constants.TypeSearch])) { type = Convert.ToInt32(Request.Form[Extensions.Constants.TypeSearch]); } var status = 0; if (Utilities.IsNotNull(Request.Form[Extensions.Constants.StatusId])) { status = Convert.ToInt32(Request.Form[Extensions.Constants.StatusId]); } int totals; var service = WorkContext.Resolve<ICustomerHistoriesService>(); var items = service.GetPaged(id, fromDate ,toDate, type, status, options.PageIndex, options.PageSize, out totals); var result = new ControlGridAjaxData<CustomerHistoriesInfo>(items, totals); return result; } [Url("admin/customers/edit/{id}")] public ActionResult Edit(int id) { WorkContext.Breadcrumbs.Add(new Breadcrumb { Text = T("Quản lý khách hàng"), Url = Url.Action("Index") }); WorkContext.Breadcrumbs.Add(new Breadcrumb { Text = T("Thông tin khách hàng"), Url = "#" }); var service = WorkContext.Resolve<ICustomerService>(); var model = new CustomerModel(); if (id > 0) { model = service.GetById(id); } else { model.CutomerCode = service.GetLatestCustomerCode(); } var result = new ControlFormResult<CustomerModel>(model) { Title = T("Thông tin khách hàng"), FormMethod = FormMethod.Post, UpdateActionName = "Update", SubmitButtonText = T("Lưu lại"), ShowCancelButton = false, ShowBoxHeader = false, FormWrapperStartHtml = Constants.Form.FormWrapperStartHtml, FormWrapperEndHtml = Constants.Form.FormWrapperEndHtml }; result.RegisterFileUploadOptions("ImageIcon.FileName", new ControlFileUploadOptions { AllowedExtensions = "jpg,jpeg,png,gif" }); result.MakeReadOnlyProperty(x => x.CutomerCode); result.MakeReadOnlyProperty(x => x.StartDate); result.MakeReadOnlyProperty(x => x.EndDate); result.MakeReadOnlyProperty(x => x.TotalDay); result.MakeReadOnlyProperty(x => x.TotalMoney); if (id > 0) { result.MakeReadOnlyProperty(x => x.UserName); result.MakeReadOnlyProperty(x => x.Password); } result.RegisterExternalDataSource(x => x.Sex, y => BindSex()); result.RegisterExternalDataSource(x => x.CityId, y => BindCities()); result.RegisterExternalDataSource(x => x.FilmTypeIds, y => BindFilmTypes()); result.RegisterExternalDataSource(x => x.CountryIds, y => BindCountries()); result.RegisterExternalDataSource(x => x.Status, y => BindStatus()); result.AddAction().HasText(T("Lịch sử")) .HasUrl(Url.Action("History", new {@id = id})) .HasButtonStyle(ButtonStyle.Warning); result.AddAction().HasText(T("Trở về")) .HasUrl(Url.Action("Index")) .HasButtonStyle(ButtonStyle.Danger); return result; } [HttpPost, ValidateInput(false), FormButton("Save")] [Url("admin/customers/update")] public ActionResult Update(CustomerModel model) { var service = WorkContext.Resolve<ICustomerService>(); CustomerInfo item = model.Id == 0 ? new CustomerInfo() : service.GetById(model.Id); item.CustomerCode = model.CutomerCode; if (model.Id == 0) { item.CustomerCode = service.GetLatestCustomerCode(); } item.FullName = model.FullName; item.Email = model.Email; item.Address = model.Address; item.PhoneNumber = model.PhoneNumber; item.CityId = model.CityId; item.Birthday = model.Birthday; item.Sex = model.Sex; item.ImageIcon = model.ImageIcon; item.FilmTypeIds = Utilities.ParseString(model.FilmTypeIds); item.CountryIds = Utilities.ParseString(model.CountryIds); item.MemberDate = DateTime.Now.Date; item.Skype = model.Skype; item.ZingMe = model.ZingMe; item.Facebook = model.Facebook; item.Google = model.Google; item.Yahoo = model.Yahoo; item.VipXu = model.VipXu; item.TotalMoney = model.TotalMoney; item.Status = model.Status; item.IsBlock = model.IsBlock; item.Description = model.Description; service.Save(item); return new AjaxResult() .NotifyMessage("UPDATE_ENTITY_COMPLETE") .Alert(T("Cập nhật thành công!")); } [Url("admin/customers/export-excel")] public ActionResult ExportExcel() { var ef = new ExcelFile(); string fileName = Server.MapPath("/Media/Default/ExcelTemplate/DuLieuKhachHang.xls"); ef.LoadXls(fileName, XlsOptions.PreserveAll); byte[] fileContents; ExcelWorksheet ws = ef.Worksheets[0]; var data = WorkContext.Resolve<ICustomerService>().ExportExcel(); if (data != null && data.Count > 0) { int index = 1; foreach (var item in data) { ws.Cells[index, 0].Value = index; ws.Cells[index, 1].Value = item.CustomerCode; ws.Cells[index, 2].Value = item.FullName; ws.Cells[index, 3].Value = item.MemberDate.ToString(Extensions.Constants.DateTimeFomatFull); ws.Cells[index, 4].Value = item.Email; ws.Cells[index, 5].Value = item.PhoneNumber; ws.Cells[index, 6].Value = (int)item.VipXu; ws.Cells[index, 7].Value = item.TotalDay; ws.Cells[index, 8].Value = item.TextStartDate; ws.Cells[index, 9].Value = item.TextEndDate; index++; ws.Rows[index].InsertCopy(1, ws.Rows[1]); } ws.Rows[index].Delete(); } using (var stream = new MemoryStream()) { ef.SaveXls(stream); fileContents = stream.ToArray(); } return File(fileContents, "application/vnd.ms-excel"); } } } <file_sep>using System.Collections.Generic; using System.Data.SqlClient; using System.Linq; using CMSSolutions.Caching; using CMSSolutions.Data; using CMSSolutions.Events; using CMSSolutions.Services; using CMSSolutions.Websites.Entities; namespace CMSSolutions.Websites.Services { public interface ICategoryService : ICacheService<CategoryInfo, int>, IGenericService<CategoryInfo, int>, IDependency { bool CheckAlias(int id, string alias); string LanguageCode { get; set; } int SiteId { get; set; } CategoryInfo GetByIdCache(int id); CategoryInfo GetHomePage(); string GetCategoryName(int id); IList<CategoryInfo> GetPaged(bool isDeleted, int pageIndex, int pageSize, out int totals); IList<CategoryInfo> ResetCache(); CategoryInfo GetByAlias(string alias); List<CategoryInfo> GetChildenByParentId(int parentId); List<CategoryInfo> GetAllParent(); IList<CategoryInfo> GetAllCache(); List<CategoryInfo> GetTree(); } public class CategoryService : GenericService<CategoryInfo, int>, ICategoryService { private readonly ICacheInfo cacheManager; public string LanguageCode { get; set; } public int SiteId { get; set; } public CategoryService( IRepository<CategoryInfo, int> repository, IEventBus eventBus, ICacheInfo cacheManager) : base(repository, eventBus) { this.cacheManager = cacheManager; } public override void Insert(CategoryInfo record) { Repository.Insert(record); ResetCache(); } public override void Update(CategoryInfo record) { Repository.Update(record); ResetCache(); } public override void Delete(CategoryInfo record) { Repository.Delete(record); ResetCache(); } public override void Save(CategoryInfo record) { if (record.IsTransient()) { Insert(record); } else { Update(record); } ResetCache(); } public CategoryInfo GetHomePage() { var list = GetAllCache(); if (list != null && list.Count > 0) { return list.FirstOrDefault(x => x.IsHome && x.IsActived); } return null; } public string GetCategoryName(int id) { var list = GetAllCache(); if (list != null && list.Count > 0) { return list.Where(x => x.Id == id && !x.IsActived).Select(x => x.Name).FirstOrDefault(); } return string.Empty; } public bool CheckAlias(int id, string alias) { var list = new List<SqlParameter> { AddInputParameter("@Alias", alias), AddInputParameter("@Id", id) }; var result = (int)ExecuteReaderResult("sp_Categories_CheckAlias", list.ToArray()); return result > 0; } public CategoryInfo GetByAlias(string alias) { var list = GetAllCache(); if (list != null && list.Count > 0) { return list.FirstOrDefault(x => x.Alias.ToLower() == alias.ToLower() && x.IsActived); } return null; } public List<CategoryInfo> GetTree() { var listParent = GetAllParent(); var list = new List<CategoryInfo>(); if (listParent != null) { foreach (var parent in listParent) { parent.ChildenName = parent.ShortName; parent.HasChilden = true; list.Add(parent); list.AddRange(GetChildenByParentId(parent.Id)); } } return list; } public List<CategoryInfo> GetChildenByParentId(int parentId) { var list = GetAllCache(); var results = new List<CategoryInfo>(); if (list != null && list.Count > 0) { foreach (var item in list) { if (parentId > 0 && item.ParentId == parentId && item.IsActived) { item.HasChilden = false; item.ChildenName = "--- " + item.ShortName; results.Add(item); results.AddRange(GetChildenByParentId2(item.Id)); } } return results; } return null; } public List<CategoryInfo> GetChildenByParentId2(int parentId) { var list = GetAllCache(); var results = new List<CategoryInfo>(); if (list != null && list.Count > 0) { foreach (var item in list) { if (parentId > 0 && item.ParentId == parentId && item.IsActived) { item.HasChilden = false; item.ChildenName = "--- --- " + item.ShortName; results.Add(item); } } results.Sort((foo1, foo2) => foo1.OrderBy.CompareTo(foo2.OrderBy)); return results; } return null; } public List<CategoryInfo> GetAllParent() { var list = GetAllCache(); if (list != null && list.Count > 0) { return list.Where(x => x.ParentId == 0 && x.IsActived).ToList(); } return null; } public CategoryInfo GetByIdCache(int id) { var list = GetAllCache(); if (list != null && list.Count > 0) { return list.FirstOrDefault(x => x.Id == id && x.IsActived); } return null; } public IList<CategoryInfo> GetAllCache() { var results = cacheManager.Get(string.Format(Extensions.Constants.CacheKeys.CATEGORY_ALL_TABLE, LanguageCode, SiteId)); if (results == null) { results = ResetCache(); } var list = (List<CategoryInfo>) results; if (results != null && list.Count > 0) { foreach (var item in list) { foreach (var check in list) { if (check.Id == item.ParentId) { item.ParentName = check.ShortName; break; } } } return list; } return new List<CategoryInfo>(); } public IList<CategoryInfo> GetPaged(bool isDeleted, int pageIndex, int pageSize, out int totals) { var results = GetAllCache(); if (results != null) { var list = results.Where(y => y.IsDeleted == isDeleted); totals = list.Count(); var users = (from x in list select x).Skip((pageIndex - 1) * pageSize).Take(pageSize).ToList(); return users; } totals = 0; return new List<CategoryInfo>(); } public IList<CategoryInfo> ResetCache() { cacheManager.Remove(string.Format(Extensions.Constants.CacheKeys.CATEGORY_ALL_TABLE, LanguageCode, SiteId)); var table = Repository.Table.Where(x => x.LanguageCode == LanguageCode && x.SiteId == SiteId).ToList(); cacheManager.Add(string.Format(Extensions.Constants.CacheKeys.CATEGORY_ALL_TABLE, LanguageCode, SiteId), table); return table; } } } <file_sep>using System; using System.Linq; using System.Web; using System.Web.Mvc; using CMSSolutions.Configuration; using CMSSolutions.ContentManagement.Widgets.Services; using CMSSolutions.DisplayManagement; using CMSSolutions.Security.Cryptography; using CMSSolutions.Web.Mvc; using CMSSolutions.Web.Themes; using CMSSolutions.Websites.Extensions; using CMSSolutions.Websites.Models; using CMSSolutions.Websites.Services; namespace CMSSolutions.Websites.Controllers { [Themed(IsDashboard = false)] public class HomeCustomerController : BaseHomeController { private readonly dynamic shapeFactory; public HomeCustomerController(IWorkContextAccessor workContextAccessor, IShapeFactory shapeFactory) : base(workContextAccessor) { this.shapeFactory = shapeFactory; } private void BuildModules() { var widget = WorkContext.Resolve<IWidgetService>(); var viewRenderer = new ViewRenderer { Context = ControllerContext }; #region Customer var customerService = WorkContext.Resolve<ICustomerService>(); var customer = customerService.GetById(UserId); var viewCustomer = viewRenderer.RenderPartialView(Extensions.Constants.CustomerViewFilePath, customer); WorkContext.Layout.AdBannerRightFirst.Add(new MvcHtmlString(viewCustomer)); #endregion #region SocialNetwork var socialNetwork = widget.GetWidget(HomeWidgets.DisplaySocialNetwork.ToString()); if (socialNetwork != null) { var widgetShape = shapeFactory.Widget(); widgetShape.Widget = socialNetwork; WorkContext.Layout.DisplaySocialNetwork(widgetShape); } #endregion } [Url("nguoi-dung/thong-bao")] public ActionResult UserMessages() { UrlLogin = Request.Url != null ? Request.Url.AbsoluteUri : Url.Action("Index", "Home"); var serviceCategory = WorkContext.Resolve<ICategoryService>(); serviceCategory.LanguageCode = WorkContext.CurrentCulture; SiteId = (int)Site.Home; var category = serviceCategory.GetById((int)FixCategories.NapVIP); ViewData[Extensions.Constants.HeaderTitle] = category.Name; ViewData[Extensions.Constants.HeaderDescription] = category.Description; ViewData[Extensions.Constants.HeaderKeywords] = category.Tags; BuildModules(); return View("UserMessages"); } [Url("nguoi-dung/phim-ua-thich")] public ActionResult UserHistories1() { UrlLogin = Request.Url != null ? Request.Url.AbsoluteUri : Url.Action("Index", "Home"); var serviceCategory = WorkContext.Resolve<ICategoryService>(); serviceCategory.LanguageCode = WorkContext.CurrentCulture; SiteId = (int)Site.Home; var category = serviceCategory.GetById((int)FixCategories.NapVIP); ViewData[Extensions.Constants.HeaderTitle] = category.Name; ViewData[Extensions.Constants.HeaderDescription] = category.Description; ViewData[Extensions.Constants.HeaderKeywords] = category.Tags; BuildModules(); return View("UserHistories1"); } [Url("nguoi-dung/phim-da-xem")] public ActionResult UserHistories2() { UrlLogin = Request.Url != null ? Request.Url.AbsoluteUri : Url.Action("Index", "Home"); var serviceCategory = WorkContext.Resolve<ICategoryService>(); serviceCategory.LanguageCode = WorkContext.CurrentCulture; SiteId = (int)Site.Home; var category = serviceCategory.GetById((int)FixCategories.NapVIP); ViewData[Extensions.Constants.HeaderTitle] = category.Name; ViewData[Extensions.Constants.HeaderDescription] = category.Description; ViewData[Extensions.Constants.HeaderKeywords] = category.Tags; BuildModules(); return View("UserHistories2"); } [Url("nguoi-dung/phim-dang-xem")] public ActionResult UserHistories3() { UrlLogin = Request.Url != null ? Request.Url.AbsoluteUri : Url.Action("Index", "Home"); var serviceCategory = WorkContext.Resolve<ICategoryService>(); serviceCategory.LanguageCode = WorkContext.CurrentCulture; SiteId = (int)Site.Home; var category = serviceCategory.GetById((int)FixCategories.NapVIP); ViewData[Extensions.Constants.HeaderTitle] = category.Name; ViewData[Extensions.Constants.HeaderDescription] = category.Description; ViewData[Extensions.Constants.HeaderKeywords] = category.Tags; BuildModules(); return View("UserHistories3"); } [Url("nguoi-dung/sua-thong-tin")] public ActionResult UserProfile() { UrlLogin = Request.Url != null ? Request.Url.AbsoluteUri : Url.Action("Index", "Home"); var serviceCategory = WorkContext.Resolve<ICategoryService>(); serviceCategory.LanguageCode = WorkContext.CurrentCulture; SiteId = (int)Site.Home; var category = serviceCategory.GetById((int)FixCategories.NapVIP); ViewData[Extensions.Constants.HeaderTitle] = category.Name; ViewData[Extensions.Constants.HeaderDescription] = category.Description; ViewData[Extensions.Constants.HeaderKeywords] = category.Tags; BuildModules(); var customerService = WorkContext.Resolve<ICustomerService>(); var cityService = WorkContext.Resolve<ICityService>(); var countryService = WorkContext.Resolve<ICountryService>(); var filmTypesService = WorkContext.Resolve<IFilmTypesService>(); var customer = customerService.GetById(UserId); var model = new DataViewerModel { Customer = customer, ListCities = cityService.GetRecords(x => x.Status == (int) Status.Approved).ToList(), ListCountries = countryService.GetRecords().ToList() }; model.ListFilmTypes = filmTypesService.GetByType(WorkContext.CurrentCulture,SiteId, 1).ToList(); model.ListDay = Utilities.GetListDay(); model.ListMonth = Utilities.GetListMonth(); model.ListYear = Utilities.GetListYear(); return View("CustomerProfile", model); } [HttpPost] [Url("nguoi-dung/cap-nhat")] public ActionResult UserUpdate() { var redirect = new DataViewerModel(); var fullName = Request.Form["txtFullName"]; var email = Request.Form["txtEmail"]; var address = Request.Form["txtAddress"]; var city = Request.Form["ddlCity"]; var phoneNumber = Request.Form["txtPhoneNumber"]; var day = Request.Form["ddlDay"]; var month = Request.Form["ddlMonth"]; var year = Request.Form["ddlYear"]; var gender = Request.Form["radGender"]; var password = Request.Form["txtPassword"]; var captcha = Request.Form["txtCaptcha"]; var selectFilmTypes = Request.Form["selectFilmTypes[]"]; var selectCountries = Request.Form["selectCountries[]"]; var imgImageIcon = Request.Form["imgImageIcon"]; if (string.IsNullOrEmpty(email)) { redirect.Data = "E-mail không để trống."; redirect.Status = false; return Json(redirect); } if (string.IsNullOrEmpty(city) || city == "0") { redirect.Data = "Vui lòng chọn Tỉnh/Thành."; redirect.Status = false; return Json(redirect); } if (string.IsNullOrEmpty(day) || day == "0") { redirect.Data = "Vui lòng chọn Ngày sinh của bạn."; redirect.Status = false; return Json(redirect); } if (string.IsNullOrEmpty(month) || month == "0") { redirect.Data = "Vui lòng chọn Tháng sinh của bạn."; redirect.Status = false; return Json(redirect); } if (string.IsNullOrEmpty(year) || year == "0") { redirect.Data = "Vui lòng chọn Năm sinh của bạn."; redirect.Status = false; return Json(redirect); } if (string.IsNullOrEmpty(selectFilmTypes)) { redirect.Data = "Bạn phải chọn thể loại phim."; redirect.Status = false; return Json(redirect); } if (string.IsNullOrEmpty(selectCountries)) { redirect.Data = "Bạn phải chọn quốc gia."; redirect.Status = false; return Json(redirect); } HttpPostedFileBase uploadfile = Request.Files[0]; if (uploadfile == null && string.IsNullOrEmpty(imgImageIcon)) { redirect.Status = false; redirect.Data = "Bạn chưa chọn ảnh đại diện."; return Json(redirect); } if (string.IsNullOrEmpty(captcha) || captcha.ToUpper() != GlobalCapcha.ToUpper()) { redirect.Status = false; redirect.Data = "Mã xác thực không đúng."; return Json(redirect); } var customerService = WorkContext.Resolve<ICustomerService>(); var customer = customerService.GetById(UserId); if (customer.Password != EncryptionExtensions.Encrypt(KeyConfiguration.PublishKey, Utilities.RemoveInjection(password))) { redirect.Status = false; redirect.Data = "Mật khẩu không đúng bạn không thể cập nhật thông tin cá nhân cho tài khoản này."; return Json(redirect); } var imageUrl = customer.ImageIcon; if (string.IsNullOrEmpty(customer.ImageIcon) || uploadfile == null || string.IsNullOrEmpty(uploadfile.FileName)) { imageUrl = "/Images/avatars/avatar-no-image.png"; } else { imageUrl = "/Media/Default/Customers/" + DateTime.Now.ToString("dd-MM-yyyy") + uploadfile.FileName; } var ngaySinh = new DateTime(int.Parse(year), int.Parse(month), int.Parse(day)); var fullUrl = Server.MapPath("~/Media/Default/Customers/" + DateTime.Now.ToString("dd-MM-yyyy") + uploadfile.FileName); uploadfile.SaveAs(fullUrl); customer.FullName = fullName; customer.Email = email; customer.Address = address; customer.Birthday = ngaySinh; customer.CityId = city; customer.PhoneNumber = phoneNumber; customer.Sex = int.Parse(gender); customer.FilmTypeIds = selectFilmTypes; customer.CountryIds = selectCountries; customer.ImageIcon = imageUrl; customerService.Update(customer); redirect.Data = "Đã cập nhật thông tin tài khoản thành công."; redirect.Status = true; redirect.Url = Url.Action("UserProfile", "HomeCustomer"); return Json(redirect); } [HttpPost, ValidateInput(false)] [Url("nguoi-dung/quen-mat-khau")] public ActionResult UserForgotPassword() { var redirect = new DataViewerModel(); return Json(redirect); } [Url("nguoi-dung/doi-mat-khau")] public ActionResult UserChangePassword() { UrlLogin = Request.Url != null ? Request.Url.AbsoluteUri : Url.Action("Index", "Home"); var serviceCategory = WorkContext.Resolve<ICategoryService>(); serviceCategory.LanguageCode = WorkContext.CurrentCulture; SiteId = (int)Site.Home; var category = serviceCategory.GetById((int)FixCategories.NapVIP); ViewData[Extensions.Constants.HeaderTitle] = category.Name; ViewData[Extensions.Constants.HeaderDescription] = category.Description; ViewData[Extensions.Constants.HeaderKeywords] = category.Tags; BuildModules(); return View("UserChangePassword"); } [HttpPost, ValidateInput(false)] [Url("nguoi-dung/doi-mat-khau/cap-nhat")] public ActionResult UpdateChangePassword() { var redirect = new DataViewerModel(); if (!IsLogin) { redirect.Data = "Bạn chưa đăng nhập."; redirect.Status = false; return Json(redirect); } var passwordOld = Request.Form["txtPasswordOld"]; var passwordNew = Request.Form["txtPasswordNew"]; var passwordConfirm = Request.Form["<PASSWORD>"]; var captcha = Request.Form["txtCaptcha"]; if (string.IsNullOrEmpty(captcha) || captcha.ToUpper() != GlobalCapcha.ToUpper()) { redirect.Status = false; redirect.Data = "Mã xác thực không đúng."; return Json(redirect); } if (string.IsNullOrEmpty(passwordOld)) { redirect.Status = false; redirect.Data = "Mật khẩu cũ không để trống."; return Json(redirect); } if (string.IsNullOrEmpty(passwordNew)) { redirect.Status = false; redirect.Data = "Mật khẩu mới không để trống."; return Json(redirect); } if (passwordNew.Length <= 5) { redirect.Status = false; redirect.Data = "Mật khẩu mới độ dài tối đa 6 ký tự."; return Json(redirect); } if (passwordNew != passwordConfirm) { redirect.Status = false; redirect.Data = "Mật khẩu xác nhận không đúng."; return Json(redirect); } var service = WorkContext.Resolve<ICustomerService>(); var status = service.ChangePassword(Utilities.RemoveInjection(UserName), EncryptionExtensions.Encrypt(KeyConfiguration.PublishKey, Utilities.RemoveInjection(passwordOld)), EncryptionExtensions.Encrypt(KeyConfiguration.PublishKey, Utilities.RemoveInjection(passwordNew))); if (status != 0) { redirect.Status = true; redirect.Data = "Mật khẩu của bạn đã được đổi thành công."; var customerService = WorkContext.Resolve<ICustomerService>(); var customer = customerService.GetById(UserId); SetCustomerState(customer); } else { redirect.Status = false; redirect.Data = "Mật khẩu cũ của bạn không đúng."; } return Json(redirect); } [Url("nguoi-dung/upload-videos")] public ActionResult UploadVideos() { UrlLogin = Request.Url != null ? Request.Url.AbsoluteUri : Url.Action("Index", "Home"); var serviceCategory = WorkContext.Resolve<ICategoryService>(); serviceCategory.LanguageCode = WorkContext.CurrentCulture; SiteId = (int)Site.Home; var category = serviceCategory.GetById((int)FixCategories.NapVIP); ViewData[Extensions.Constants.HeaderTitle] = category.Name; ViewData[Extensions.Constants.HeaderDescription] = category.Description; ViewData[Extensions.Constants.HeaderKeywords] = category.Tags; BuildModules(); return View("CustomerUploadVideos"); } [HttpPost, ValidateInput(false)] [Url("nguoi-dung/luu-tru-videos")] public ActionResult UserSaveVideos() { var redirect = new DataViewerModel(); redirect.Data = "Thực hiện thất bại. Chưa hỗ trợ upload videos cho khách hàng."; redirect.Status = false; return Json(redirect); } } } <file_sep>using System; using System.Globalization; using System.Web.Mvc; using CMSSolutions.Web.Mvc; using CMSSolutions.Web.Routing; using CMSSolutions.Web.Themes; using CMSSolutions.Web.UI.ControlForms; using CMSSolutions.Web.UI.Navigation; using CMSSolutions.Websites.Entities; using CMSSolutions.Websites.Extensions; using CMSSolutions.Websites.Models; using CMSSolutions.Websites.Services; namespace CMSSolutions.Websites.Controllers { [Themed(IsDashboard = true), Authorize] public class AdminCategoryController : BaseAdminController { public AdminCategoryController(IWorkContextAccessor workContextAccessor) : base(workContextAccessor) { TableName = "tblCategories"; } [Url("admin/category")] public ActionResult Index() { WorkContext.Breadcrumbs.Add(new Breadcrumb { Text = T("Quản lý chuyên mục"), Url = "#" }); var result = new ControlGridFormResult<CategoryInfo> { Title = T("Quản lý chuyên mục"), CssClass = "table table-bordered table-striped", IsAjaxSupported = true, FetchAjaxSource = GetCategories, DefaultPageSize = WorkContext.DefaultPageSize, EnablePaginate = true, UpdateActionName = "Update", GridWrapperStartHtml = Constants.Grid.GridWrapperStartHtml, GridWrapperEndHtml = Constants.Grid.GridWrapperEndHtml, ClientId = TableName, ActionsColumnWidth = 100 }; result.AddCustomVar(Extensions.Constants.LanguageCode, "$('#" + Extensions.Constants.LanguageCode + "').val();", true); result.AddCustomVar(Extensions.Constants.SiteId, "$('#" + Extensions.Constants.SiteId + "').val();", true); result.AddCustomVar(Extensions.Constants.StatusId, "$('#" + Extensions.Constants.StatusId + "').val();", true); result.AddColumn(x => x.Id, T("Mã")) .AlignCenter() .HasWidth(60); result.AddColumn(x => x.ParentName, T("Chuyên mục cha")).HasWidth(150); result.AddColumn(x => x.ShortName, T("Chuyên mục")).HasWidth(150); result.AddColumn(x => x.Name, "Tên hỗ trợ SEO"); result.AddColumn(x => x.OrderBy, "Vị trí") .AlignCenter() .HasWidth(60); result.AddColumn(x => x.IsActived) .HasHeaderText(T("Hiển thị")) .AlignCenter() .HasWidth(100) .RenderAsStatusImage(); result.AddAction().HasText(T("Thêm mới")) .HasUrl(Url.Action("Edit", RouteData.Values.Merge(new { id = 0 }))) .HasButtonStyle(ButtonStyle.Primary) .HasBoxButton(false) .HasRow(false) .HasCssClass(Constants.RowLeft) .HasRow(true); result.AddAction(new ControlFormHtmlAction(() => BuildLanguages(true, Extensions.Constants.SiteId))).HasParentClass(Constants.ContainerCssClassCol3); result.AddAction(new ControlFormHtmlAction(() => BuildSites(false, string.Empty))).HasParentClass(Constants.ContainerCssClassCol3); result.AddAction(new ControlFormHtmlAction(BuildStatus)).HasParentClass(Constants.ContainerCssClassCol3); result.AddRowAction() .HasText(T("Sửa")) .HasUrl(x => Url.Action("Edit", RouteData.Values.Merge(new { id = x.Id }))) .HasButtonStyle(ButtonStyle.Default) .HasButtonSize(ButtonSize.ExtraSmall); result.AddRowAction(true) .HasText(T("Xóa")) .HasName("Delete") .HasValue(x => x.Id.ToString(CultureInfo.InvariantCulture.ToString())) .HasButtonStyle(ButtonStyle.Danger) .HasButtonSize(ButtonSize.ExtraSmall) .HasConfirmMessage(T(Constants.Messages.ConfirmDeleteRecord).Text); result.AddReloadEvent("UPDATE_ENTITY_COMPLETE"); result.AddReloadEvent("DELETE_ENTITY_COMPLETE"); return result; } private ControlGridAjaxData<CategoryInfo> GetCategories(ControlGridFormRequest options) { var service = WorkContext.Resolve<ICategoryService>(); var languageCode = WorkContext.CurrentCulture; if (Utilities.IsNotNull(Request.Form[Extensions.Constants.LanguageCode])) { languageCode = Request.Form[Extensions.Constants.LanguageCode]; } var siteId = 0; if (Utilities.IsNotNull(Request.Form[Extensions.Constants.SiteId])) { siteId = Convert.ToInt32(Request.Form[Extensions.Constants.SiteId]); } bool status = false; if (Utilities.IsNotNull(Request.Form[Extensions.Constants.StatusId])) { var statusId = Convert.ToInt32(Request.Form[Extensions.Constants.StatusId]); switch ((Status)statusId) { case Status.Approved: status = false; break; case Status.Deleted: status = true; break; } } int totals; service.LanguageCode = languageCode; service.SiteId = siteId; var list = service.GetPaged(status, options.PageIndex, options.PageSize, out totals); return new ControlGridAjaxData<CategoryInfo>(list, totals); } [Url("admin/category/edit")] public ActionResult Edit(int id) { var model = new CategoryModel(); if (id > 0) { var service = WorkContext.Resolve<ICategoryService>(); model = service.GetById(id); } var result = new ControlFormResult<CategoryModel>(model) { Title = T("Thông tin chuyên mục"), FormMethod = FormMethod.Post, UpdateActionName = "Update", SubmitButtonText = T("Lưu lại"), ShowCancelButton = false, ShowBoxHeader = false, FormWrapperStartHtml = Constants.Form.FormWrapperStartHtml, FormWrapperEndHtml = Constants.Form.FormWrapperEndHtml }; result.RegisterExternalDataSource(x => x.LanguageCode, y => BindLanguages()); result.RegisterCascadingDropDownDataSource(x => x.SiteId, Url.Action("GetSitesByLanguage")); result.RegisterCascadingDropDownDataSource(x => x.ParentId, Url.Action("GetCategoriesBySite")); result.AddAction().HasText(T("Làm mới")) .HasUrl(Url.Action("Edit", RouteData.Values.Merge(new { id = 0 }))) .HasCssClass("btn btn-success"); result.AddAction().HasText(T("Trở về")) .HasUrl(Url.Action("Index")) .HasCssClass("btn btn-danger"); return result; } [HttpPost, ValidateInput(false), FormButton("Save")] [Url("admin/category/update")] public ActionResult Update(CategoryModel model) { if (!ModelState.IsValid) { return new AjaxResult().Alert(T(Constants.Messages.InvalidModel)); } CategoryInfo categoryInfo; var service = WorkContext.Resolve<ICategoryService>(); service.SiteId = model.SiteId; service.LanguageCode = model.LanguageCode; var alias = Utilities.GetAlias(model.Name); if (!string.IsNullOrEmpty(alias)) { if (service.CheckAlias(model.Id, alias)) { alias += DateTime.Now.ToString("ddMMyyyyhhmm"); } } var url = model.Url; if (string.IsNullOrEmpty(url)) { url = alias; } categoryInfo = model.Id == 0 ? new CategoryInfo() : service.GetById(model.Id); categoryInfo.SiteId = model.SiteId; categoryInfo.ParentId = model.ParentId; categoryInfo.ShortName = model.ShortName; categoryInfo.Name = model.Name; categoryInfo.Alias = alias; categoryInfo.LanguageCode = model.LanguageCode; categoryInfo.IsActived = model.IsActived; categoryInfo.OrderBy = model.OrderBy; categoryInfo.Description = model.Description; categoryInfo.SiteId = model.SiteId; categoryInfo.CreateDate = DateTime.Now.Date; categoryInfo.IsDeleted = model.IsDeleted; categoryInfo.Url = url; categoryInfo.IsHome = model.IsHome; categoryInfo.HasChilden = model.HasChilden; categoryInfo.Tags = model.Tags; service.Save(categoryInfo); try { #region Add Search var service2 = WorkContext.Resolve<ISearchService>(); var searchObject = service2.GetBySearchId(categoryInfo.Id.ToString(), (int)SearchType.Category); long id = 0; if (searchObject != null) { id = searchObject.Id; } var search = new SearchInfo { Id = id, Title = categoryInfo.ShortName, Alias = categoryInfo.Alias, CategoryIds = categoryInfo.Id.ToString(), CreateDate = categoryInfo.CreateDate, IsBlock = categoryInfo.IsDeleted, LanguageCode = categoryInfo.LanguageCode, SearchId = categoryInfo.Id.ToString(), SiteId = categoryInfo.SiteId, Sumary = categoryInfo.Name, Tags = categoryInfo.Tags, Type = (int)SearchType.Category, TitleEnglish = string.Empty, Images = string.Empty, ViewCount = "0", Processed = 0 }; service2.Save(search); var cacheSearch = new LuceneService(); cacheSearch.UpdateLuceneIndex(search); #endregion } catch (Exception) { return new AjaxResult().NotifyMessage("UPDATE_ENTITY_COMPLETE") .Alert(T("Không thể thêm dữ liệu tìm kiếm.")); } return new AjaxResult() .NotifyMessage("UPDATE_ENTITY_COMPLETE") .Alert(T("Cập nhật thành công!")); } [FormButton("Delete")] [HttpPost, ActionName("Update")] public ActionResult Delete(int id) { var service = WorkContext.Resolve<ICategoryService>(); var obj = service.GetById(id); service.LanguageCode = obj.LanguageCode; service.SiteId = obj.SiteId; obj.IsDeleted = true; service.Update(obj); return new AjaxResult().NotifyMessage("DELETE_ENTITY_COMPLETE"); } } } <file_sep>using System; using System.Globalization; using System.Linq; using System.Web.Mvc; using CMSSolutions.ContentManagement.Widgets.Services; using CMSSolutions.DisplayManagement; using CMSSolutions.Extensions; using CMSSolutions.Web.Mvc; using CMSSolutions.Web.Themes; using CMSSolutions.Websites.Entities; using CMSSolutions.Websites.Extensions; using CMSSolutions.Websites.Models; using CMSSolutions.Websites.Payments; using CMSSolutions.Websites.Services; using CMSSolutions.Websites.VipHDBankCardServices; namespace CMSSolutions.Websites.Controllers { [Themed(IsDashboard = false)] public class HomeVipXuController : BaseHomeController { private readonly dynamic shapeFactory; public HomeVipXuController(IWorkContextAccessor workContextAccessor, IShapeFactory shapeFactory) : base(workContextAccessor) { this.shapeFactory = shapeFactory; } [Url("tai-tro.html")] public ActionResult Index() { UrlLogin = Request.Url != null ? Request.Url.AbsoluteUri : Url.Action("Index", "Home"); var model = new PaymentModel(); model.PageName = 1; if (!IsLogin) { return Redirect(Url.Action("Index", "Home")); } var customerService = WorkContext.Resolve<ICustomerService>(); CustomerInfo customer = customerService.GetCustomerByCacheId(UserId); SetCustomerState(customer); #region Payments var transid = Request.QueryString["?transid"]; var responCode = Request.QueryString["responCode"]; var mac = Request.QueryString["mac"]; var amount = Request.QueryString["amount"]; var bankCode = Request.QueryString["bankCode"]; var encrypter = new DesSecurity(); var apiBank = new APIBankCardService(); var transactionBankService = WorkContext.Resolve<ITransactionBankService>(); var serviceLog = new APISmsService(); if (mac != encrypter.DESMAC(transid + responCode, apiBank.ReceiverKey) && !String.IsNullOrEmpty(transid)) { model.Messages = "Giao dịch nạp VIPXU qua thẻ ngân hàng thất bại."; model.Status = false; model.Url = ""; var transaction = new TransactionBankInfo { CustomerCode = CustomerCode, TransactionCode = TransactionCode, CreateDate = DateTime.Now, BankCode = bankCode, Amount = amount, ResponCode = responCode, Mac = mac, TransId = transid, Type = (int)TransferType.Rereceive, Description = "Giao dịch nạp VIPXU qua thẻ ngân hàng thất bại.", Status = (int)PaymentStatus.Close }; transactionBankService.BankProcessing(transaction, 0); serviceLog.InsertLog(new LogInfo { CreateDate = DateTime.Now, Messages = "Giao dịch nạp VIPXU qua thẻ ngân hàng thất bại.", Keyword = bankCode, Contents = "Mã GD: " + TransactionCode + " - Mã KH: " + CustomerCode + " - Số tiền nạp: " + amount, Type = (int)LogType.BankCard, Status = (int)LogStatus.Error }); TransactionCode = null; } if (!string.IsNullOrEmpty(transid) && !string.IsNullOrEmpty(responCode) && Convert.ToInt32(responCode) != (int)BankErrorMessages.Success) { model.Messages = "Giao dịch nạp VIPXU qua thẻ ngân hàng thất bại."; model.Status = false; model.Url = ""; var transaction = new TransactionBankInfo { CustomerCode = CustomerCode, TransactionCode = TransactionCode, CreateDate = DateTime.Now, BankCode = bankCode, Amount = amount, ResponCode = responCode, Mac = mac, TransId = transid, Type = (int)TransferType.Rereceive, Description = "Giao dịch thất bại", Status = (int)PaymentStatus.Close }; transactionBankService.BankProcessing(transaction, 0); serviceLog.InsertLog(new LogInfo { CreateDate = DateTime.Now, Messages = "Giao dịch nạp VIPXU qua thẻ ngân hàng thất bại.", Keyword = bankCode, Contents = TransactionCode + " " + CustomerCode + " " + amount, Type = (int)LogType.BankCard, Status = (int)LogStatus.Error }); TransactionCode = null; } if (!string.IsNullOrEmpty(TransactionCode) && !string.IsNullOrEmpty(transid) && Convert.ToInt32(responCode) == (int)BankErrorMessages.Success) { var vipXu = TotalVipXu(int.Parse(amount)); model.Messages = string.Format("Bạn đã nạp {0} VIPXU vào tài khoản {1} thành công.", vipXu, CustomerCode); model.Status = true; model.Amount = amount; model.Url = string.Format("http://{0}", Extensions.Constants.HomeDomainName); var transaction = new TransactionBankInfo { CustomerCode = CustomerCode, TransactionCode = TransactionCode, CreateDate = DateTime.Now, BankCode = bankCode, Amount = amount, ResponCode = responCode, Mac = mac, TransId = transid, Type = (int)TransferType.Rereceive, Description = string.Format("Đã nạp {0} VIPXU vào tài khoản {1} thành công.", vipXu, CustomerCode), Status = (int)PaymentStatus.Close }; transactionBankService.BankProcessing(transaction, vipXu); serviceLog.InsertLog(new LogInfo { CreateDate = DateTime.Now, Messages = "Giao dịch nạp VIPXU qua thẻ ngân hàng thành công.", Keyword = bankCode, Contents = TransactionCode + " " + CustomerCode + " " + amount, Type = (int)LogType.BankCard, Status = (int)LogStatus.Success }); TransactionCode = null; customerService.ResetCacheCustomers(); customer = customerService.GetCustomerByCacheId(UserId); SetCustomerState(customer); } #endregion #region Init var serviceCategory = WorkContext.Resolve<ICategoryService>(); serviceCategory.LanguageCode = WorkContext.CurrentCulture; SiteId = (int)Site.Home; serviceCategory.SiteId = SiteId; var cate = serviceCategory.GetByIdCache((int)FixCategories.NapVIP); ViewData[Extensions.Constants.HeaderTitle] = cate.Name; ViewData[Extensions.Constants.HeaderDescription] = cate.Description; ViewData[Extensions.Constants.HeaderKeywords] = cate.Tags; BindVipModules(); var serviceBankCard = WorkContext.Resolve<IBankCardService>(); model.ListBankCards = serviceBankCard.GetRecords(x => x.Status == (int)Status.Approved).ToList(); var serviceCard = WorkContext.Resolve<ICardTypeService>(); model.ListCardTypes = serviceCard.GetRecords(x => x.Status == (int)Status.Approved).ToList(); model.CustomerCode = CustomerCode; #endregion return View(model); } [Url("tai-tro/0/thong-tin.html")] public ActionResult VipXuInfo() { UrlLogin = Request.Url != null ? Request.Url.AbsoluteUri : Url.Action("Index", "Home"); var model = new PaymentModel(); model.PageName = 0; model.CustomerName = FullName; model.VipXu = VipXu.ToString(); if (!IsLogin) { model.Messages = "Bạn chưa đăng nhập."; model.Status = false; return Redirect(Url.Action("Index", "Home")); } #region Init var serviceCategory = WorkContext.Resolve<ICategoryService>(); serviceCategory.LanguageCode = WorkContext.CurrentCulture; SiteId = (int)Site.Home; serviceCategory.SiteId = SiteId; var cate = serviceCategory.GetByIdCache((int)FixCategories.NapVIP); ViewData[Extensions.Constants.HeaderTitle] = cate.Name; ViewData[Extensions.Constants.HeaderDescription] = cate.Description; ViewData[Extensions.Constants.HeaderKeywords] = cate.Tags; BindVipModules(); model.CustomerCode = CustomerCode; #endregion return View(model); } [Url("tai-tro/2/log-doi-xu.html")] public ActionResult LogDoiXu() { UrlLogin = Request.Url != null ? Request.Url.AbsoluteUri : Url.Action("Index", "Home"); var model = new PaymentModel(); model.PageName = 2; if (!IsLogin) { model.Messages = "Bạn chưa đăng nhập."; model.Status = false; return Redirect(Url.Action("Index", "Home")); } #region Init var serviceCategory = WorkContext.Resolve<ICategoryService>(); serviceCategory.LanguageCode = WorkContext.CurrentCulture; SiteId = (int)Site.Home; serviceCategory.SiteId = SiteId; var cate = serviceCategory.GetByIdCache((int)FixCategories.NapVIP); ViewData[Extensions.Constants.HeaderTitle] = cate.Name; ViewData[Extensions.Constants.HeaderDescription] = cate.Description; ViewData[Extensions.Constants.HeaderKeywords] = cate.Tags; BindVipModules(); model.CustomerCode = CustomerCode; var historyService = WorkContext.Resolve<ICustomerHistoriesService>(); model.CustomerDoiXuHistories = historyService.GetDoiXuByCustomer(CustomerCode); #endregion return View("LogDoiXu", model); } [Url("tai-tro/3/log-nap-vip.html")] public ActionResult LogNapVip() { UrlLogin = Request.Url != null ? Request.Url.AbsoluteUri : Url.Action("Index", "Home"); var model = new PaymentModel(); model.PageName = 3; #region Init var serviceCategory = WorkContext.Resolve<ICategoryService>(); serviceCategory.LanguageCode = WorkContext.CurrentCulture; SiteId = (int)Site.Home; serviceCategory.SiteId = SiteId; var cate = serviceCategory.GetByIdCache((int)FixCategories.NapVIP); ViewData[Extensions.Constants.HeaderTitle] = cate.Name; ViewData[Extensions.Constants.HeaderDescription] = cate.Description; ViewData[Extensions.Constants.HeaderKeywords] = cate.Tags; BindVipModules(); model.CustomerCode = CustomerCode; var historyService = WorkContext.Resolve<ICustomerHistoriesService>(); model.CustomerNapVipHistories = historyService.GetNapVipByCustomer(UserId); #endregion return View("LogNapVip", model); } private void BindVipModules() { var widget = WorkContext.Resolve<IWidgetService>(); var viewRenderer = new ViewRenderer { Context = ControllerContext }; #region Customer var customerService = WorkContext.Resolve<ICustomerService>(); var customer = customerService.GetById(UserId); if (customer == null) { customer = new CustomerInfo(); } var viewCustomer = viewRenderer.RenderPartialView(Extensions.Constants.CustomerViewFilePath, customer); WorkContext.Layout.AdBannerRightFirst.Add(new MvcHtmlString(viewCustomer)); #endregion #region SocialNetwork var socialNetwork = widget.GetWidget(HomeWidgets.DisplaySocialNetwork.ToString()); if (socialNetwork != null) { var widgetShape = shapeFactory.Widget(); widgetShape.Widget = socialNetwork; WorkContext.Layout.DisplaySocialNetwork(widgetShape); } #endregion } [HttpPost, ValidateInput(false)] [Url("thanh-toan/the-atm")] public ActionResult BankPayment() { var redirect = new DataViewerModel(); if (!IsLogin) { redirect.Data = "Bạn chưa đăng nhập."; redirect.Status = false; return Json(redirect); } var amount = Request.Form["Amount"]; var bankCode = Request.Form["BankCode"]; var captcha = Request.Form["txtCaptcha"]; if (string.IsNullOrEmpty(captcha) || captcha.ToUpper() != GlobalCapcha.ToUpper()) { redirect.Status = false; redirect.Data = "Mã xác thực không đúng."; return Json(redirect); } if (string.IsNullOrEmpty(amount.Trim())) { redirect.Status = false; redirect.Data = "Số tiền không để trống."; return Json(redirect); } if (double.Parse(amount) < 50000) { redirect.Status = false; redirect.Data = "Số tiền phải lớn hơn hoặc bằng 50.000VNĐ."; return Json(redirect); } var apiBank = new APIBankCardService(); apiBank.ReponseUrl = "http://viphd.vn" + Url.Action("Index") + "?amount=" + amount + "&bankCode=" + bankCode + "&"; //apiBank.ReponseUrl = "http://localhost:1500" + Url.Action("Index") + "?amount=" + amount + "&bankCode=" + bankCode + "&"; var encrypter = new DesSecurity(); string stan = "720527"; string termtxndatetime = DateTime.Now.ToString("yyyyMMddHHmmss"); string fee = "0"; string userName = "DuManhTan"; string IssuerID = "EPAY"; string tranID = DateTime.Now.ToString("yyyyMMddHHmmss"); string mac = apiBank.MerchantId + stan + termtxndatetime + amount + fee + userName + IssuerID + tranID + bankCode + apiBank.ReponseUrl; mac = encrypter.DESMAC(mac, apiBank.SenderKey); var service = new Service(); var result = service.Deposit(apiBank.MerchantId, stan, termtxndatetime, amount, fee, userName, IssuerID, tranID, bankCode, mac, apiBank.ReponseUrl); TransactionCode = Utilities.GenerateUniqueNumber(); var transaction = new TransactionBankInfo { CustomerCode = CustomerCode, TransactionCode = TransactionCode, CreateDate = DateTime.Now, BankCode = bankCode, Amount = amount, ResponCode = "", Mac = "", TransId = "", Type = (int) TransferType.Send, Description = "", Status = (int) PaymentStatus.Open }; var transactionBankService = WorkContext.Resolve<ITransactionBankService>(); transactionBankService.Insert(transaction); var serviceLog = new APISmsService(); serviceLog.InsertLog(new LogInfo { CreateDate = DateTime.Now, Messages = "Gửi giao dịch nạp thẻ ngân hàng.", Keyword = bankCode, Contents = TransactionCode + " " + CustomerCode + " " + amount, Type = (int)LogType.BankCard, Status = (int)LogStatus.Information }); redirect = new DataViewerModel { Status = true, Url = !string.IsNullOrEmpty(result.url) ? result.url : string.Empty }; return Json(redirect); } [HttpPost, ValidateInput(false)] [Url("thanh-toan/the-nap")] public ActionResult CardPayment() { if (string.IsNullOrEmpty(TransactionCode)) { TransactionCode = Utilities.GenerateUniqueNumber(); } var redirect = new DataViewerModel(); if (!IsLogin) { redirect.Data = "Bạn chưa đăng nhập."; redirect.Status = false; return Json(redirect); } var captcha = Request.Form["Captcha"]; if (string.IsNullOrEmpty(captcha) || captcha.ToUpper() != GlobalCapcha.ToUpper()) { redirect.Status = false; redirect.Data = "Mã xác thực không đúng."; return Json(redirect); } var service = new APICardCharging(); string sessionId; string messages = service.Login(out sessionId); if (string.IsNullOrEmpty(sessionId) || messages != Utilities.GetMessages((int)ErrorMessages.Success)) { redirect.Status = false; redirect.Data = messages; return Json(redirect); } var serviceCardTypes = WorkContext.Resolve<ICardTypeService>(); var cardTypes = Request.Form["CardTypes"]; if (string.IsNullOrEmpty(cardTypes)) { redirect.Status = false; redirect.Data = "Bạn chưa chọn mạng cho thẻ nạp"; return Json(redirect); } var seriNumber = Request.Form["SeriNumber"]; if (cardTypes != "MGC" && string.IsNullOrEmpty(seriNumber)) { redirect.Status = false; redirect.Data = "Bạn chưa nhập số seri của thẻ."; return Json(redirect); } var pinCode = Request.Form["PinCode"]; if (string.IsNullOrEmpty(pinCode)) { redirect.Status = false; redirect.Data = "Bạn chưa nhập mã thẻ cào."; return Json(redirect); } var cardType = serviceCardTypes.GetByCode(cardTypes, -1); if (cardType.HasSerial) { service.CardData = seriNumber + ":" + pinCode + "::" + cardTypes; } else if (!cardType.HasSerial) { service.CardData = pinCode + ":" + cardTypes; } string txttarget = "account"; string amount; var status = service.CardCharging(sessionId, service.CardData, txttarget, out amount); if (status == ErrorMessages.Success) { var vipXu = TotalVipXu(int.Parse(amount)); redirect.Status = true; redirect.Data = string.Format("Bạn đã nạp {0} VIPXU vào tài khoản {1} thành công.", vipXu, CustomerCode); redirect.Url = string.Format("http://{0}", Extensions.Constants.HomeDomainName); var transaction = new TransactionCardInfo { CustomerCode = CustomerCode, TransactionCode = TransactionCode, CreateDate = DateTime.Now, Amount = amount, CardCode = cardTypes, SeriNumber = seriNumber, PinCode = pinCode, Description = "Nạp thẻ thành công", Status = (int)CardStatus.Success }; var transactionCardService = WorkContext.Resolve<ITransactionCardService>(); transactionCardService.CardProcessing(transaction, vipXu); var serviceLog = new APISmsService(); serviceLog.InsertLog(new LogInfo { CreateDate = DateTime.Now, Messages = "Nạp tiền theo nhà mạng thành công", Keyword = cardTypes, Contents = "Mã GD: " + TransactionCode + " - Mã KH: " + CustomerCode + " - Số tiền nạp: " + amount + " - VIPXU: " + vipXu, Type = (int)LogType.ScratchCard, Status = (int)LogStatus.Success }); TransactionCode = null; var customerService = WorkContext.Resolve<ICustomerService>(); customerService.ResetCacheCustomers(); var customer = customerService.GetCustomerByCacheId(UserId); SetCustomerState(customer); } else { redirect.Status = true; redirect.Data = Utilities.GetMessages((int)status); var transaction = new TransactionCardInfo { CustomerCode = CustomerCode, TransactionCode = TransactionCode, CreateDate = DateTime.Now, Amount = amount, CardCode = cardTypes, SeriNumber = seriNumber, PinCode = pinCode, Description = "Nạp tiền theo nhà mạng thất bại", Status = (int)CardStatus.Error }; var transactionCardService = WorkContext.Resolve<ITransactionCardService>(); transactionCardService.CardProcessing(transaction, 0); var serviceLog = new APISmsService(); serviceLog.InsertLog(new LogInfo { CreateDate = DateTime.Now, Messages = "Nạp tiền theo nhà mạng", Keyword = cardTypes, Contents = "Mã GD: " + TransactionCode + " - Mã KH: " + CustomerCode + " - Số tiền nạp: " + amount, Type = (int)LogType.ScratchCard, Status = (int)LogStatus.Error }); } return Json(redirect); } [HttpPost, ValidateInput(false)] [Url("thanh-toan/doi-ngay")] public ActionResult ExchangeDay() { var redirect = new DataViewerModel(); if (!IsLogin) { redirect.Data = "Bạn chưa đăng nhập."; redirect.Status = false; return Json(redirect); } var day = Request.Form["txtExchangeDay"]; if (string.IsNullOrEmpty(day)) { redirect.Data = "Số ngày bạn chọn không đúng."; redirect.Status = false; return Json(redirect); } var vipXu = 0; var package = (ExchangeDay) int.Parse(day); switch (package) { case Extensions.ExchangeDay.Package15: vipXu = 200; break; case Extensions.ExchangeDay.Package50: vipXu = 500; break; case Extensions.ExchangeDay.Package100: vipXu = 1000; break; case Extensions.ExchangeDay.Package300: vipXu = 3000; break; } TransactionCode = Utilities.GenerateUniqueNumber(); var customerService = WorkContext.Resolve<ICustomerService>(); var status = customerService.ExchangeDay(UserId, int.Parse(day), vipXu, TransactionCode, EnumExtensions.GetDisplayName(package)); var serviceLog = new APISmsService(); if (status == 0) { serviceLog.InsertLog(new LogInfo { CreateDate = DateTime.Now, Messages = "Đổi VIPXU thành công", Keyword = day, Contents = "Mã GD: " + TransactionCode + " - Mã KH: " + CustomerCode + " - VIPXU: " + vipXu + " - Số ngày:" + day, Type = (int)LogType.Other, Status = (int)LogStatus.Success }); TransactionCode = null; customerService.ResetCacheCustomers(); var customer = customerService.GetCustomerByCacheId(UserId); SetCustomerState(customer); redirect.Data = string.Format("Bạn đã đổi {0} VIPXU lấy {1} ngày sử dụng thành công. Sử dụng từ ngày {2} đến hết ngày {3}", vipXu, day, customer.StartDate != null ? customer.StartDate.Value.ToString(Extensions.Constants.DateTimeFomat) : StartDate.ToString(Extensions.Constants.DateTimeFomat), customer.EndDate != null ? customer.EndDate.Value.ToString(Extensions.Constants.DateTimeFomat) : EndDate.ToString(Extensions.Constants.DateTimeFomat)); redirect.Status = true; } else { serviceLog.InsertLog(new LogInfo { CreateDate = DateTime.Now, Messages = "Đổi VIPXU thất bại", Keyword = day, Contents = "Mã GD: " + TransactionCode + " - Mã KH: " + CustomerCode + " - VIPXU: " + vipXu + " - Số ngày:" + day, Type = (int)LogType.Other, Status = (int)LogStatus.Success }); TransactionCode = null; redirect.Data = "Tài khoản của bạn không đủ VIPXU để thực hiện giao dịch. Vui lòng quay lại bước 1."; redirect.Status = false; } return Json(redirect); } private int ExchangeVipXu(int money) { var vipXu = 0; foreach (ExchangeMoney item in Enum.GetValues(typeof(ExchangeMoney))) { var name = EnumExtensions.GetDisplayName(item); var value = int.Parse(name.Replace(".", "")); if (value == money) { vipXu = (int) item; break; } } return vipXu; } private int TotalVipXu(int money) { var vipXu = ExchangeVipXu(money); if (vipXu == 0) { foreach (ExchangeMoney item in Enum.GetValues(typeof(ExchangeMoney))) { var name = EnumExtensions.GetDisplayName(item); var value = int.Parse(name.Replace(".", "")); if (money > value) { var newMoney = money - value; vipXu += ExchangeVipXu(value); vipXu += ExchangeVipXu(newMoney); break; } } } return vipXu; } [HttpPost, ValidateInput(false)] [Url("thanh-toan/kich-hoat-khuyenmai")] public ActionResult ActiveCode() { var redirect = new DataViewerModel(); if (!IsLogin) { redirect.Data = "Bạn chưa đăng nhập."; redirect.Status = false; return Json(redirect); } var freeCode = Request.Form["txtFreeCode"]; if (string.IsNullOrEmpty(freeCode)) { redirect.Data = "Mã khuyến mãi không tồn tại."; redirect.Status = false; return Json(redirect); } var servicePromotionCustomers = WorkContext.Resolve<IPromotionCustomersService>(); var promotionCustomers = servicePromotionCustomers.GetCodeCustomer(UserId, freeCode); if (promotionCustomers == null) { redirect.Data = "Mã khuyến mãi không tồn tại."; redirect.Status = false; return Json(redirect); } var status = servicePromotionCustomers.ActiveCode(UserId, freeCode); var serviceLog = new APISmsService(); if (status == 0) { serviceLog.InsertLog(new LogInfo { CreateDate = DateTime.Now, Messages = "Kích hoạt mã khuyến mãi thành công.", Keyword = freeCode, Contents = string.Format("Kích hoạt mã khuyến mãi {0} thành công. Đã nhận được {1} VIPXU từ mã khuyến mãi.", freeCode, promotionCustomers.Value), Type = (int)LogType.Other, Status = (int)LogStatus.Success }); var customerService = WorkContext.Resolve<ICustomerService>(); customerService.ResetCacheCustomers(); var customer = customerService.GetCustomerByCacheId(UserId); SetCustomerState(customer); redirect.Data = string.Format("Bạn đã kích hoạt thành công mã khuyến mãi {0}. Bạn nhận được {1} VIPXU.", freeCode, promotionCustomers.Value); redirect.Status = true; redirect.Url = string.Format("http://{0}", Extensions.Constants.HomeDomainName); } else { serviceLog.InsertLog(new LogInfo { CreateDate = DateTime.Now, Messages = "Kích hoạt mã khuyến mãi thất bại.", Keyword = freeCode, Contents = string.Format("Mã khuyến mãi {0} có thể đã được sử dụng hoặc đã quá hạn sử dụng.", freeCode), Type = (int)LogType.Other, Status = (int)LogStatus.Error }); redirect.Data = string.Format("Mã khuyến mãi {0} có thể đã được sử dụng hoặc đã quá hạn sử dụng.", freeCode); redirect.Status = false; } return Json(redirect); } [HttpPost, ValidateInput(false)] [Url("vip-xu/cap-nhat")] public ActionResult LoadVipXu() { var redirect = new DataViewerModel(); var customerService = WorkContext.Resolve<ICustomerService>(); customerService.ResetCacheCustomers(); var customer = customerService.GetCustomerByCacheId(UserId); SetCustomerState(customer); redirect.Url = Url.Action("Index"); redirect.Status = true; return Json(redirect); } [HttpPost, ValidateInput(false)] [Url("thanh-toan/kich-hoat/sms")] public ActionResult ActiveSmsCode() { var redirect = new DataViewerModel(); if (!IsLogin) { redirect.Data = "Bạn chưa đăng nhập."; redirect.Status = false; return Json(redirect); } var transactionCode = Request.Form["TransactionCode"]; if (string.IsNullOrEmpty(transactionCode)) { redirect.Data = "Mã giao dịch không tồn tại."; redirect.Status = false; return Json(redirect); } var service = WorkContext.Resolve<ITransactionSmsService>(); var transaction = service.GetByMOCode(transactionCode); if (transaction == null) { redirect.Data = "Mã giao dịch không tồn tại."; redirect.Status = false; return Json(redirect); } var status = service.ActiveSms(transactionCode, CustomerCode); var serviceLog = new APISmsService(); if (status == 0) { var mo = service.GetByMOCode(transactionCode); mo.Id = 0; mo.Status = (int) RequestStatus.Messages200; mo.Type = (int) SMSType.MT; mo.StartDate = transaction.StartDate; mo.EndDate = transaction.EndDate; service.Insert(mo); serviceLog.InsertLog(new LogInfo { CreateDate = DateTime.Now, Messages = "Kích hoạt mã giao dịch SMS thành công.", Keyword = transactionCode, Contents = string.Format("Kích hoạt mã giao dịch SMS {0} thành công. Đã nhận được {1} ngày từ mã giao dịch. Bắt đầu từ ngày {2} đến hết ngày {3}", transactionCode, transaction.TotalDay, transaction.StartDate != null ? transaction.StartDate.Value.ToString(Extensions.Constants.DateTimeFomat) : "", transaction.EndDate != null ? transaction.EndDate.Value.ToString(Extensions.Constants.DateTimeFomat): ""), Type = (int)LogType.SMS, Status = (int)LogStatus.Success }); var customerService = WorkContext.Resolve<ICustomerService>(); customerService.ResetCacheCustomers(); var customer = customerService.GetCustomerByCacheId(UserId); SetCustomerState(customer); redirect.Data = string.Format("Kích hoạt mã giao dịch SMS {0} thành công. Đã nhận được {1} ngày từ mã giao dịch. Bắt đầu từ ngày {2} đến hết ngày {3}", transactionCode, transaction.TotalDay, transaction.StartDate != null ? transaction.StartDate.Value.ToString(Extensions.Constants.DateTimeFomat) : "", transaction.EndDate != null ? transaction.EndDate.Value.ToString(Extensions.Constants.DateTimeFomat) : ""); redirect.Status = true; redirect.Url = string.Format("http://{0}", Extensions.Constants.HomeDomainName); } else { serviceLog.InsertLog(new LogInfo { CreateDate = DateTime.Now, Messages = "Kích hoạt mã giao dịch thất bại.", Keyword = transactionCode, Contents = string.Format("Mã giao dịch {0} có thể đã được sử dụng hoặc đã bị khóa. Vui lòng liên hệ với quản trị để được trợ giúp.", transactionCode), Type = (int)LogType.SMS, Status = (int)LogStatus.Error }); redirect.Data = string.Format("Mã giao dịch {0} có thể đã được sử dụng hoặc đã bị khóa. Vui lòng liên hệ với quản trị để được trợ giúp.", transactionCode); redirect.Status = false; } return Json(redirect); } } } <file_sep>using System; using System.Collections.Generic; using System.Data.SqlClient; using CMSSolutions.Data; using CMSSolutions.Events; using CMSSolutions.Services; using CMSSolutions.Websites.Entities; namespace CMSSolutions.Websites.Services { public interface IVastService : IGenericService<VastInfo, int>, IDependency { List<VastInfo> SearchPaged( string languageCode, int siteId, int adId, int pageIndex, int pageSize, out int totalRecord); } public class VastService : GenericService<VastInfo, int>, IVastService { public VastService(IRepository<VastInfo, int> repository, IEventBus eventBus) : base(repository, eventBus) { } public List<VastInfo> SearchPaged(string languageCode, int siteId, int adId, int pageIndex, int pageSize, out int totalRecord) { var list = new List<SqlParameter> { AddInputParameter("@LanguageCode", languageCode), AddInputParameter("@SiteId", siteId), AddInputParameter("@AdId", adId), AddInputParameter("@PageIndex", pageIndex), AddInputParameter("@PageSize", pageSize) }; return ExecuteReader<VastInfo>("sp_Vast_Search_Paged", "@TotalRecord", out totalRecord, list.ToArray()); } } } <file_sep>using System; using System.Globalization; using System.Web.Mvc; using CMSSolutions.Web.Mvc; using CMSSolutions.Web.Routing; using CMSSolutions.Web.Themes; using CMSSolutions.Web.UI.ControlForms; using CMSSolutions.Web.UI.Navigation; using CMSSolutions.Websites.Entities; using CMSSolutions.Websites.Extensions; using CMSSolutions.Websites.Models; using CMSSolutions.Websites.Services; namespace CMSSolutions.Websites.Controllers { [Themed(IsDashboard = true), Authorize] public class AdminArticlesController : BaseAdminController { public AdminArticlesController( IWorkContextAccessor workContextAccessor) : base(workContextAccessor) { TableName = "tblArticles"; } [Url("admin/articles")] public ActionResult Index() { WorkContext.Breadcrumbs.Add(new Breadcrumb { Text = T("Quản lý bài viết"), Url = "#" }); var result = new ControlGridFormResult<ArticlesInfo> { Title = T("Quản lý bài viết"), CssClass = "table table-bordered table-striped", IsAjaxSupported = true, FetchAjaxSource = GetArticles, DefaultPageSize = WorkContext.DefaultPageSize, UpdateActionName = "Update", EnablePaginate = true, ClientId =TableName, ActionsColumnWidth = 150, GridWrapperStartHtml = Constants.Grid.GridWrapperStartHtml, GridWrapperEndHtml = Constants.Grid.GridWrapperEndHtml }; result.AddCustomVar(Extensions.Constants.LanguageCode, "$('#" + Extensions.Constants.LanguageCode + "').val();", true); result.AddCustomVar(Extensions.Constants.SiteId, "$('#" + Extensions.Constants.SiteId + "').val();", true); result.AddCustomVar(Extensions.Constants.UserId, "$('#" + Extensions.Constants.UserId + "').val();", true); result.AddCustomVar(Extensions.Constants.CategoryId, "$('#" + Extensions.Constants.CategoryId + "').val();", true); result.AddCustomVar(Extensions.Constants.FromDate, "$('#" + Extensions.Constants.FromDate + "').val();", true); result.AddCustomVar(Extensions.Constants.ToDate, "$('#" + Extensions.Constants.ToDate + "').val();", true); result.AddCustomVar(Extensions.Constants.SearchText, "$('#" + Extensions.Constants.SearchText + "').val();", true); result.AddCustomVar(Extensions.Constants.StatusId, "$('#" + Extensions.Constants.StatusId + "').val();", true); result.AddColumn(x => x.Id, T("ID")).AlignCenter().HasWidth(100); result.AddColumn(x => x.Icon, T("Ảnh đại diện")) .AlignCenter() .HasWidth(100) .RenderAsImage(y => y.Icon, Extensions.Constants.CssThumbsSize); result.AddColumn(x => x.Title, T("Tiêu đề")); result.AddColumn(x => x.Alias, T("Tiêu đề không dấu")); result.AddColumn(x => x.CategoryName, "Chuyên mục"); result.AddColumn(x => x.IsPublished) .HasHeaderText(T("Đã đăng")) .AlignCenter() .HasWidth(100) .RenderAsStatusImage(false); result.AddColumn(x => x.IsHome) .HasHeaderText(T("Trang chủ")) .AlignCenter() .HasWidth(100) .RenderAsStatusImage(false); result.AddColumn(x => x.IsVideo) .HasHeaderText(T("Có Videos")) .AlignCenter() .HasWidth(100) .RenderAsStatusImage(false); result.AddAction().HasText(T("Thêm mới")) .HasUrl(Url.Action("Edit", RouteData.Values.Merge(new { id = 0 }))) .HasButtonStyle(ButtonStyle.Primary) .HasBoxButton(false) .HasRow(false) .HasCssClass(Constants.RowLeft) .HasRow(true); result.AddAction(new ControlFormHtmlAction(() => BuildLanguages(true, Extensions.Constants.SiteId))).HasParentClass(Constants.ContainerCssClassCol3); result.AddAction(new ControlFormHtmlAction(() => BuildSites(true, Extensions.Constants.CategoryId))).HasParentClass(Constants.ContainerCssClassCol3); result.AddAction(new ControlFormHtmlAction(BuildCategories)).HasParentClass(Constants.ContainerCssClassCol3); result.AddAction(new ControlFormHtmlAction(BuildUsers).HasParentClass(Constants.ContainerCssClassCol3)); result.AddAction(new ControlFormHtmlAction(() => BuildFromDate())).HasParentClass(Constants.ContainerCssClassCol3); result.AddAction(new ControlFormHtmlAction(() => BuildToDate())).HasParentClass(Constants.ContainerCssClassCol3); result.AddAction(new ControlFormHtmlAction(BuildSearchText)).HasParentClass(Constants.ContainerCssClassCol3); result.AddAction(new ControlFormHtmlAction(BuildStatus)).HasParentClass(Constants.ContainerCssClassCol3); result.AddRowAction() .HasText(T("Sửa")) .HasUrl(x => Url.Action("Edit", RouteData.Values.Merge(new {id = x.Id}))) .HasButtonStyle(ButtonStyle.Default) .HasButtonSize(ButtonSize.ExtraSmall); result.AddRowAction(true) .HasText(T("Xóa")) .HasName("Delete") .HasValue(x => x.Id.ToString(CultureInfo.InvariantCulture.ToString())) .HasButtonStyle(ButtonStyle.Danger) .HasButtonSize(ButtonSize.ExtraSmall) .HasConfirmMessage(T(Constants.Messages.ConfirmDeleteRecord).Text); result.AddReloadEvent("UPDATE_ENTITY_COMPLETE"); result.AddReloadEvent("DELETE_ENTITY_COMPLETE"); return result; } protected ControlGridAjaxData<ArticlesInfo> GetArticles(ControlGridFormRequest options) { var searchText = string.Empty; if (Utilities.IsNotNull(Request.Form[Extensions.Constants.SearchText])) { searchText = Request.Form[Extensions.Constants.SearchText]; } var languageCode = WorkContext.CurrentCulture; if (Utilities.IsNotNull(Request.Form[Extensions.Constants.LanguageCode])) { languageCode = Request.Form[Extensions.Constants.LanguageCode]; } var siteId = 0; if (Utilities.IsNotNull(Request.Form[Extensions.Constants.SiteId] )) { siteId = Convert.ToInt32(Request.Form[Extensions.Constants.SiteId]); } var categoryId = 0; if (Utilities.IsNotNull(Request.Form[Extensions.Constants.CategoryId])) { categoryId = Convert.ToInt32(Request.Form[Extensions.Constants.CategoryId]); } var fromDate = DateTime.Now.Date; if (Utilities.IsNotNull(Request.Form[Extensions.Constants.FromDate])) { fromDate = DateTime.ParseExact(Request.Form[Extensions.Constants.FromDate], Extensions.Constants.DateTimeFomat, CultureInfo.InvariantCulture); } var toDate = DateTime.Now.Date; if (Utilities.IsNotNull(Request.Form[Extensions.Constants.ToDate])) { toDate = DateTime.ParseExact(Request.Form[Extensions.Constants.ToDate], Extensions.Constants.DateTimeFomat, CultureInfo.InvariantCulture); } var status = -1; if (Utilities.IsNotNull(Request.Form[Extensions.Constants.StatusId])) { var statusId = Convert.ToInt32(Request.Form[Extensions.Constants.StatusId]); switch ((Status)statusId) { case Status.Approved: status = 0; break; case Status.Deleted: status = 1; break; } } var userId = 0; if (Utilities.IsNotNull(Request.Form[Extensions.Constants.UserId])) { userId = int.Parse(Request.Form[Extensions.Constants.UserId]); } int totals; var service = WorkContext.Resolve<IArticlesService>(); service.LanguageCode = languageCode; service.CategoryId = categoryId; var records = service.SearchPaged( searchText, siteId, userId, fromDate, toDate, status, options.PageIndex, options.PageSize, out totals); return new ControlGridAjaxData<ArticlesInfo>(records, totals); } [Url("admin/articles/edit")] public ActionResult Edit(int id) { WorkContext.Breadcrumbs.Add(new Breadcrumb { Text = T("Quản lý bài viết"), Url = Url.Action("Index") }); WorkContext.Breadcrumbs.Add(new Breadcrumb { Text = T("Thông tin bài viết"), Url = "#" }); if (!ModelState.IsValid) { return new AjaxResult().Alert(T(Constants.Messages.InvalidModel)); } var model = new ArticlesModel(); if (id > 0) { var service = WorkContext.Resolve<IArticlesService>(); model = service.GetById(id); } var result = new ControlFormResult<ArticlesModel>(model) { Title = T("Thông tin bài viết"), UpdateActionName = "Update", FormMethod = FormMethod.Post, SubmitButtonText = T("Lưu lại"), ShowBoxHeader = false, ShowCancelButton = false, FormWrapperStartHtml = Constants.Form.FormWrapperStartHtml, FormWrapperEndHtml = Constants.Form.FormWrapperEndHtml }; result.RegisterFileUploadOptions("Icon.FileName", new ControlFileUploadOptions { AllowedExtensions = "jpg,jpeg,png,gif" }); result.AddAction().HasText(T("Làm mới")) .HasUrl(Url.Action("Edit", RouteData.Values.Merge(new { id = 0 }))) .HasCssClass("btn btn-success"); result.AddAction().HasText(T("Trở về")) .HasUrl(Url.Action("Index")) .HasCssClass("btn btn-danger"); result.RegisterExternalDataSource(x => x.LanguageCode, y => BindLanguages()); result.RegisterCascadingDropDownDataSource(x => x.SiteId, Url.Action("GetSitesByLanguage")); result.RegisterCascadingDropDownDataSource(x => x.CategoryId, Url.Action("GetCategoriesBySite")); return result; } [HttpPost, ValidateInput(false), FormButton("Save")] [Url("admin/articles/update")] public ActionResult Update(ArticlesModel model) { var service = WorkContext.Resolve<IArticlesService>(); service.CategoryId = model.CategoryId; service.LanguageCode = model.LanguageCode; var alias = model.Alias; if (string.IsNullOrEmpty(alias)) { alias = Utilities.GetAlias(model.Title); if (service.CheckAlias(alias)) { alias += "-1"; } } ArticlesInfo articlesInfo = model.Id == 0 ? new ArticlesInfo() : service.GetById(model.Id); articlesInfo.ParentId = model.ParentId; articlesInfo.SiteId = model.SiteId; articlesInfo.CategoryId = model.CategoryId; articlesInfo.Title = model.Title; articlesInfo.LanguageCode = model.LanguageCode; articlesInfo.Icon = model.Icon; articlesInfo.Alias = alias; articlesInfo.Summary = model.Summary; articlesInfo.Contents = model.Contents; articlesInfo.CreateDate = DateTime.Now.Date; articlesInfo.CreateByUser = WorkContext.CurrentUser.Id; articlesInfo.IsPublished = model.IsPublished; articlesInfo.PublishedDate = DateTime.Now.Date; articlesInfo.IsHome = model.IsHome; articlesInfo.IsVideo = model.IsVideo; articlesInfo.Description = model.Description; articlesInfo.IsDeleted = model.IsDeleted; articlesInfo.Tags = model.Tags; articlesInfo.VideosUrl = model.VideosUrl; service.Save(articlesInfo); try { #region Add Search var service2 = WorkContext.Resolve<ISearchService>(); var searchObject = service2.GetBySearchId(articlesInfo.Id.ToString(), (int)SearchType.Articles); long id = 0; if (searchObject != null) { id = searchObject.Id; } var search = new SearchInfo { Id = id, Title = articlesInfo.Title, Alias = articlesInfo.Alias, CategoryIds = articlesInfo.CategoryId.ToString(), CreateDate = articlesInfo.CreateDate, IsBlock = articlesInfo.IsDeleted, LanguageCode = articlesInfo.LanguageCode, SearchId = articlesInfo.Id.ToString(), SiteId = articlesInfo.SiteId, Sumary = articlesInfo.Summary, Tags = articlesInfo.Tags, Type = (int)SearchType.Articles, TitleEnglish = string.Empty, Images = articlesInfo.Icon, ViewCount = articlesInfo.ViewCount.ToString(), Processed = 0 }; service2.Save(search); var cacheSearch = new LuceneService(); cacheSearch.UpdateLuceneIndex(search); #endregion } catch (Exception) { return new AjaxResult().NotifyMessage("UPDATE_ENTITY_COMPLETE") .Alert(T("Không thể thêm dữ liệu tìm kiếm.")); } return new AjaxResult().NotifyMessage("UPDATE_ENTITY_COMPLETE") .Alert(T("Cập nhật thành công!")); } [FormButton("Delete")] [HttpPost, ActionName("Update")] public ActionResult Delete(int id) { var service = WorkContext.Resolve<IArticlesService>(); var obj = service.GetById(id); service.CategoryId = obj.CategoryId; obj.IsDeleted = true; service.Update(obj); return new AjaxResult() .NotifyMessage("DELETE_ENTITY_COMPLETE") .Alert(T("Dữ liệu chuyển trạng thái xóa tạm thời!")); } } } <file_sep>using System; using CMSSolutions.Web.UI.ControlForms; using CMSSolutions.Websites.Entities; using CMSSolutions.Websites.Extensions; namespace CMSSolutions.Websites.Models { public class AdvertisementGroupModel { public AdvertisementGroupModel() { Code = Guid.NewGuid().ToString().Replace("-", string.Empty); IsActived = true; } [ControlHidden] public int Id { get; set; } [ControlChoice(ControlChoice.DropDownList, Required = true, LabelText = "Ngôn ngữ hiển thị", ContainerCssClass = Constants.ContainerCssClassCol4, ContainerRowIndex = 0, OnSelectedIndexChanged = "$('#" + Extensions.Constants.CategoryId + "').empty();")] public string LanguageCode { get; set; } [ControlCascadingDropDown(LabelText = "Trang web", ParentControl = "LanguageCode", AbsoluteParentControl = true, ContainerCssClass = Constants.ContainerCssClassCol4, ContainerRowIndex = 0)] public int SiteId { get; set; } [ControlCascadingDropDown(LabelText = "Chuyên mục hiển thị", ParentControl = "SiteId", AbsoluteParentControl = true, ContainerCssClass = Constants.ContainerCssClassCol4, ContainerRowIndex = 0)] public int CategoryId { get; set; } [ControlCascadingDropDown(AllowMultiple = true, EnableChosen = true, LabelText = "Quảng cáo", ParentControl = "SiteId", ContainerCssClass = Constants.ContainerCssClassCol12, ContainerRowIndex = 1)] public int[] AdvertisementIds { get; set; } [ControlText(Type = ControlText.TextBox, ReadOnly = true, LabelText = "Mã quảng cáo", Required = true, MaxLength = 50, ContainerCssClass = Constants.ContainerCssClassCol4, ContainerRowIndex = 2)] public string Code { get; set; } [ControlText(Type = ControlText.TextBox, LabelText = "Tên nhóm", Required = true, MaxLength = 250, ContainerCssClass = Constants.ContainerCssClassCol8, ContainerRowIndex = 2)] public string GroupName { get; set; } [ControlText(LabelText = "<NAME>", Type = ControlText.MultiText, Rows = 2, MaxLength = 2000, ContainerCssClass = Constants.ContainerCssClassCol12, ContainerRowIndex = 3)] public string Description { get; set; } [ControlChoice(ControlChoice.CheckBox, LabelText = "", PrependText = "Đã tạo Xml", ContainerCssClass = Constants.ContainerCssClassCol3, ContainerRowIndex = 4)] public bool IsGenerate { get; set; } [ControlChoice(ControlChoice.CheckBox, LabelText = "", PrependText = "Đang sử dụng", ContainerCssClass = Constants.ContainerCssClassCol3, ContainerRowIndex = 4)] public bool IsActived { get; set; } [ControlDatePicker(LabelText = "Ngày hết hạn", Required = true, ContainerCssClass = Constants.ContainerCssClassCol3, ContainerRowIndex = 4)] public string FinishDate { get; set; } [ControlText(Type = ControlText.TextBox, LabelText = "Giờ hết hạn", Required = true, MaxLength = 250, ContainerCssClass = Constants.ContainerCssClassCol3, ContainerRowIndex = 4)] public string FinishTime { get; set; } public static implicit operator AdvertisementGroupModel(AdvertisementGroupInfo entity) { return new AdvertisementGroupModel { LanguageCode = entity.LanguageCode, SiteId = entity.SiteId, CategoryId = entity.CategoryId, Id = entity.Id, Code = entity.Code, GroupName = entity.GroupName, Description = entity.Description, AdvertisementIds = Utilities.ParseListInt(entity.AdvertisementIds), IsGenerate = entity.IsGenerate, IsActived = entity.IsActived, FinishDate = entity.FinishDate.ToString(Extensions.Constants.DateTimeFomat), FinishTime = entity.FinishTime }; } } } <file_sep>using System; using System.Collections.Generic; using System.Data.SqlClient; using CMSSolutions.Data; using CMSSolutions.Events; using CMSSolutions.Services; using CMSSolutions.Websites.Entities; namespace CMSSolutions.Websites.Services { public interface ITransactionSmsService : IGenericService<TransactionSmsInfo, long>, IDependency { int ActiveSms(string transactionCode, string customerCode); TransactionSmsInfo GetByMOCode(string transactionCode); IList<TransactionSmsInfo> GetPaged(string keyword, int type, int status, int isClosed, DateTime fromDate, DateTime toDate, int pageIndex, int pageSize, out int totals); IList<TransactionSmsInfo> ExportExcelSms(DateTime fromDate, DateTime toDate, int type); int SmsClosed(DateTime toDate); } public class TransactionSmsService : GenericService<TransactionSmsInfo, long>, ITransactionSmsService { public TransactionSmsService(IRepository<TransactionSmsInfo, long> repository, IEventBus eventBus) : base(repository, eventBus) { } public int ActiveSms(string transactionCode, string customerCode) { var list = new List<SqlParameter> { AddInputParameter("@TransactionCode", transactionCode), AddInputParameter("@CustomerCode", customerCode) }; return (int)ExecuteReaderResult("sp_TransactionSms_Active", list.ToArray()); } public TransactionSmsInfo GetByMOCode(string transactionCode) { var list = new List<SqlParameter> { AddInputParameter("@TransactionCode", transactionCode) }; return ExecuteReaderRecord<TransactionSmsInfo>("sp_TransactionSms_GetMOCode", list.ToArray()); } public IList<TransactionSmsInfo> GetPaged(string keyword, int type, int status, int isClosed, DateTime fromDate, DateTime toDate, int pageIndex, int pageSize, out int totals) { var list = new List<SqlParameter> { AddInputParameter("@SearchText", keyword), AddInputParameter("@Type", type), AddInputParameter("@Status", status), AddInputParameter("@IsClosed", isClosed), AddInputParameter("@FromDate", fromDate), AddInputParameter("@ToDate", toDate), AddInputParameter("@PageIndex", pageIndex), AddInputParameter("@PageSize", pageSize) }; return ExecuteReader<TransactionSmsInfo>("sp_TransactionSms_Search_Paged", "@TotalRecord", out totals, list.ToArray()); } public IList<TransactionSmsInfo> ExportExcelSms(DateTime fromDate, DateTime toDate, int type) { var list = new List<SqlParameter> { AddInputParameter("@Type", type), AddInputParameter("@FromDate", fromDate), AddInputParameter("@ToDate", toDate) }; return ExecuteReader<TransactionSmsInfo>("sp_TransactionSms_ReportSms", list.ToArray()); } public int SmsClosed(DateTime toDate) { var list = new List<SqlParameter> { AddInputParameter("@ToDate", toDate) }; return ExecuteNonQuery("sp_TransactionSms_Closed", list.ToArray()); } } }<file_sep>using CMSSolutions.Web.UI.ControlForms; using CMSSolutions.Websites.Entities; namespace CMSSolutions.Websites.Models { public class ArticlesModel { public ArticlesModel() { CategoryId = 59; IsPublished = true; } [ControlHidden] public int Id { get; set; } [ControlChoice(ControlChoice.DropDownList, Required = true, LabelText = "Ngôn ngữ hiển thị", ContainerCssClass = Constants.ContainerCssClassCol3, ContainerRowIndex = 0, OnSelectedIndexChanged = "$('#" + Extensions.Constants.CategoryId + "').empty();")] public string LanguageCode { get; set; } [ControlCascadingDropDown(LabelText = "Trang web", ParentControl = "LanguageCode", AbsoluteParentControl = true, ContainerCssClass = Constants.ContainerCssClassCol3, ContainerRowIndex = 0)] public int SiteId { get; set; } [ControlCascadingDropDown(LabelText = "Chuyên mục hiển thị", ParentControl = "SiteId", AbsoluteParentControl = true, ContainerCssClass = Constants.ContainerCssClassCol3, ContainerRowIndex = 0)] public int CategoryId { get; set; } [ControlText(LabelText = "Bài viết liên quan", Type = ControlText.TextBox, ContainerCssClass = Constants.ContainerCssClassCol3, ContainerRowIndex = 0)] public int ParentId { get; set; } [ControlChoice(ControlChoice.CheckBox, LabelText = "", PrependText = "Đăng tin", ContainerCssClass = Constants.ContainerCssClassCol3, ContainerRowIndex = 1)] public bool IsPublished { get; set; } [ControlChoice(ControlChoice.CheckBox, LabelText = "", PrependText = "Hiện trên trang chủ", ContainerCssClass = Constants.ContainerCssClassCol3, ContainerRowIndex = 1)] public bool IsHome { get; set; } [ControlChoice(ControlChoice.CheckBox, LabelText = "", PrependText = "Không sử dụng", ContainerCssClass = Constants.ContainerCssClassCol3, ContainerRowIndex = 1)] public bool IsDeleted { get; set; } [ControlChoice(ControlChoice.CheckBox, LabelText = "", PrependText = "Tin có videos", ContainerCssClass = Constants.ContainerCssClassCol3, ContainerRowIndex = 1)] public bool IsVideo { get; set; } [ControlText(Type = ControlText.TextBox, PlaceHolder = "Vui lòng nhập tiêu đề bài viết. Tối đa 200 ký tự.", LabelText = "Tiêu đề", Required = true, MaxLength = 200, ContainerCssClass = Constants.ContainerCssClassCol12, ContainerRowIndex = 1)] public string Title { get; set; } [ControlText(Type = ControlText.TextBox, LabelText = "Tiêu đề hỗ trợ SEO", PlaceHolder = "Mặc định để trống, tự sinh.", MaxLength = 200, ContainerCssClass = Constants.ContainerCssClassCol12, ContainerRowIndex = 2)] public string Alias { get; set; } [ControlFileUpload(EnableFineUploader = true, LabelText = "Ảnh đại diện", ContainerCssClass = Constants.ContainerCssClassCol6, ContainerRowIndex = 3, Required = true, ShowThumbnail = true)] public string Icon { get; set; } [ControlText(Type = ControlText.MultiText, PlaceHolder = "Nhập nhiều đường dẫn videos ở đây chú ý tách nhau bởi dấu ';'", LabelText = "Đường dẫn vieos", ContainerCssClass = Constants.ContainerCssClassCol12, ContainerRowIndex = 4)] public string VideosUrl { get; set; } [ControlText(LabelText = "Tóm tắt nội dung", PlaceHolder = "Vui lòng tóm tắt nội dung bài viết. Tối đa 400 ký tự.", Type = ControlText.MultiText, Rows = 2, Required = true, MaxLength = 400, ContainerCssClass = Constants.ContainerCssClassCol12, ContainerRowIndex = 5)] public string Summary { get; set; } [ControlText(LabelText = "Nội dung bài viết", Required = true, Type = ControlText.RichText, ContainerCssClass = Constants.ContainerCssClassCol12, ContainerRowIndex = 6)] public string Contents { get; set; } [ControlText(LabelText = "Từ khóa SEO", Required = true, PlaceHolder = "Vui lòng nhập từ khóa SEO cho bài viết. Tối đa 400 ký tự.", Type = ControlText.MultiText, Rows = 2, MaxLength = 400, ContainerCssClass = Constants.ContainerCssClassCol12, ContainerRowIndex = 7)] public string Description { get; set; } [ControlText(LabelText = "Tags SEO", Required = true, PlaceHolder = "Nhập từ khóa SEO cách nhau bởi dấu, Tối đa 500 ký tự.", Type = ControlText.MultiText, Rows = 2, MaxLength = 500, ContainerCssClass = Constants.ContainerCssClassCol12, ContainerRowIndex = 8)] public string Tags { get; set; } public static implicit operator ArticlesModel(ArticlesInfo other) { if (other == null) { return null; } return new ArticlesModel { Id = other.Id, LanguageCode = other.LanguageCode, Alias = other.Alias, ParentId = other.ParentId, CategoryId = other.CategoryId, Title = other.Title, Icon = other.Icon, IsPublished = other.IsPublished, IsHome = other.IsHome, IsVideo = other.IsVideo, Summary = other.Summary, Contents = other.Contents, Description = other.Description, IsDeleted = other.IsDeleted, VideosUrl = other.VideosUrl, Tags = other.Tags, SiteId = other.SiteId }; } } }<file_sep>using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Text; using System.Web.Mvc; using CMSSolutions.Extensions; using CMSSolutions.Web.Mvc; using CMSSolutions.Web.Routing; using CMSSolutions.Web.Themes; using CMSSolutions.Web.UI.ControlForms; using CMSSolutions.Web.UI.Navigation; using CMSSolutions.Websites.Entities; using CMSSolutions.Websites.Extensions; using CMSSolutions.Websites.Models; using CMSSolutions.Websites.Services; namespace CMSSolutions.Websites.Controllers { [Themed(IsDashboard = true), Authorize] public class AdminPromotionController : BaseAdminController { public AdminPromotionController(IWorkContextAccessor workContextAccessor) : base(workContextAccessor) { TableName = "tblPromotions"; } [Url("admin/promotions")] public ActionResult Index() { WorkContext.Breadcrumbs.Add(new Breadcrumb { Text = T("Quản lý đợt khuyến mãi"), Url = "#" }); var result = new ControlGridFormResult<PromotionInfo> { Title = T("Quản lý đợt khuyến mãi"), CssClass = "table table-bordered table-striped", IsAjaxSupported = true, FetchAjaxSource = GetPromotions, DefaultPageSize = WorkContext.DefaultPageSize, EnablePaginate = true, UpdateActionName = "Update", GridWrapperStartHtml = Constants.Grid.GridWrapperStartHtml, GridWrapperEndHtml = Constants.Grid.GridWrapperEndHtml, ClientId = TableName, ActionsColumnWidth = 250 }; result.AddCustomVar(Extensions.Constants.StatusId, "$('#" + Extensions.Constants.StatusId + "').val();", true); result.AddColumn(x => x.Id, T("ID")).HasWidth(60).AlignCenter(); result.AddColumn(x => x.Title, T("Thông tin khuyến mãi")); result.AddColumn(x => x.TextFromDate, T("Ngày bắt đầu")); result.AddColumn(x => x.TextToDate, T("Ngày kết thúc")); result.AddColumn(x => EnumExtensions.GetDisplayName((PromotionStatus)x.Status), T("Trạng thái")); result.AddAction().HasText(T("Thêm mới")) .HasUrl(Url.Action("Edit", RouteData.Values.Merge(new { id = 0 }))) .HasButtonStyle(ButtonStyle.Primary) .HasBoxButton(false) .HasCssClass(Constants.RowLeft) .HasRow(true); result.AddAction(new ControlFormHtmlAction(BuildPromotionStatus)).HasParentClass(Constants.ContainerCssClassCol3); result.AddRowAction().HasText(T("Áp dụng KM")) .HasUrl(x => Url.Action("Index","AdminPromotionCustomers", RouteData.Values.Merge(new { @promotionId = x.Id }))) .HasButtonStyle(ButtonStyle.Info) .HasButtonSize(ButtonSize.ExtraSmall); result.AddRowAction() .HasText(T("Sửa")) .HasUrl(x => Url.Action("Edit", RouteData.Values.Merge(new { id = x.Id }))) .HasButtonStyle(ButtonStyle.Default) .HasButtonSize(ButtonSize.ExtraSmall); result.AddRowAction(true) .HasText(T("Đã kết thúc")) .HasName("Delete") .HasValue(x => x.Id.ToString(CultureInfo.InvariantCulture.ToString())) .HasButtonStyle(ButtonStyle.Danger) .HasButtonSize(ButtonSize.ExtraSmall); result.AddReloadEvent("UPDATE_ENTITY_COMPLETE"); result.AddReloadEvent("DELETE_ENTITY_COMPLETE"); return result; } private string BuildPromotionStatus() { var list = EnumExtensions.GetListItems<PromotionStatus>(); var sb = new StringBuilder(); sb.AppendFormat(T("Trạng thái") + " <select id=\"" + Extensions.Constants.StatusId + "\" name=\"" + Extensions.Constants.StatusId + "\" autocomplete=\"off\" class=\"uniform form-control col-md-3\" onchange=\"$('#" + TableName + "').jqGrid().trigger('reloadGrid');\">"); foreach (var status in list) { sb.AppendFormat("<option value=\"{1}\">{0}</option>", status.Text, status.Value); } sb.Append("</select>"); return sb.ToString(); } private ControlGridAjaxData<PromotionInfo> GetPromotions(ControlGridFormRequest options) { var statusId = 0; if (Utilities.IsNotNull(Request.Form[Extensions.Constants.StatusId])) { statusId = Convert.ToInt32(Request.Form[Extensions.Constants.StatusId]); } int totals; var items = WorkContext.Resolve<IPromotionService>().SearchPaged(statusId, options.PageIndex, options.PageSize, out totals); var result = new ControlGridAjaxData<PromotionInfo>(items, totals); return result; } [Url("admin/promotions/edit/{id}")] public ActionResult Edit(int id) { WorkContext.Breadcrumbs.Add(new Breadcrumb { Text = T("Quản lý đợt khuyến mãi"), Url = Url.Action("Index") }); WorkContext.Breadcrumbs.Add(new Breadcrumb { Text = T("Thông tin đợt khuyến mãi"), Url = "#" }); var model = new PromotionModel(); if (id > 0) { var service = WorkContext.Resolve<IPromotionService>(); model = service.GetById(id); } var result = new ControlFormResult<PromotionModel>(model) { Title = T("Thông tin đợt khuyến mãi"), FormMethod = FormMethod.Post, UpdateActionName = "Update", SubmitButtonText = T("Lưu lại"), CancelButtonText = T("Trở về"), ShowBoxHeader = false, FormWrapperStartHtml = Constants.Form.FormWrapperStartHtml, FormWrapperEndHtml = Constants.Form.FormWrapperEndHtml }; result.RegisterExternalDataSource(x => x.Status, y => EnumExtensions.GetListItems<PromotionStatus>()); if (id > 0) { result.AddAction().HasText(T("Áp dụng KM")) .HasUrl(Url.Action("Index","AdminPromotionCustomers", new { @promotionId = id })) .HasButtonStyle(ButtonStyle.Info); } return result; } [HttpPost, ValidateInput(false), FormButton("Save")] [Url("admin/promotions/update")] public ActionResult Update(PromotionModel model) { PromotionInfo item; var service = WorkContext.Resolve<IPromotionService>(); if (model.Id == 0) { item = new PromotionInfo(); } else { item = service.GetById(model.Id); } item.Title = model.Title; item.Contents = model.Contents; item.FromDate = model.FromDate; item.ToDate = model.ToDate; item.Status = model.Status; service.Save(item); return new AjaxResult().NotifyMessage("UPDATE_ENTITY_COMPLETE").Alert(T("Cập nhật thành công!")); } [FormButton("Delete")] [HttpPost, ActionName("Update")] public ActionResult Delete(int id) { var service = WorkContext.Resolve<IPromotionService>(); var model = service.GetById(id); model.Status = (int)PromotionStatus.Finish; service.Update(model); return new AjaxResult().NotifyMessage("DELETE_ENTITY_COMPLETE"); } } } <file_sep>using System.ComponentModel; using System.Runtime.Serialization; using CMSSolutions.Data; using CMSSolutions.Data.Entity; namespace CMSSolutions.Websites.Entities { [DataContract] public class CardTypeInfo : BaseEntity<int> { [DataMember] [DisplayName("Code")] public string Code { get; set; } [DataMember] [DisplayName("Name")] public string Name { get; set; } [DataMember] [DisplayName("HasSerial")] public bool HasSerial { get; set; } [DataMember] [DisplayName("Status")] public int Status { get; set; } } public class CardTypeMap : EntityTypeConfiguration<CardTypeInfo>, IEntityTypeConfiguration { public CardTypeMap() { ToTable("Modules_CardTypes"); HasKey(m => m.Id); Property(m => m.Code).HasMaxLength(50); Property(m => m.Name).HasMaxLength(250); } } } <file_sep>using CMSSolutions.Web.UI.ControlForms; using CMSSolutions.Websites.Entities; namespace CMSSolutions.Websites.Models { public class CountryModel { [ControlHidden] public int Id { get; set; } [ControlText(Type = ControlText.TextBox, Required = true, MaxLength = 50, LabelText = "Mã nước", ContainerCssClass = Constants.ContainerCssClassCol12, ContainerRowIndex = 0)] public string Code { get; set; } [ControlText(Type = ControlText.TextBox, Required = true, MaxLength = 50, LabelText = "Tên nước", ContainerCssClass = Constants.ContainerCssClassCol12, ContainerRowIndex = 1)] public string Name { get; set; } public static implicit operator CountryModel(CountryInfo entity) { return new CountryModel { Id = entity.Id, Code = entity.Code, Name = entity.Name }; } } } <file_sep>using System; using System.Collections.Generic; using System.Data.SqlClient; using CMSSolutions.Data; using CMSSolutions.Events; using CMSSolutions.Services; using CMSSolutions.Websites.Entities; namespace CMSSolutions.Websites.Services { public interface ITransactionBankService : IGenericService<TransactionBankInfo, long>, IDependency { int BankProcessing(TransactionBankInfo entity, int vipXu); IList<TransactionBankInfo> GetPaged(string keyword, string bankCode, int type, int status, int isLock, DateTime fromDate, DateTime toDate, int pageIndex, int pageSize, out int totals); int ATMClosed(DateTime toDate); IList<TransactionBankInfo> ExportExcelAtm(DateTime fromDate, DateTime toDate, int type); } public class TransactionBankService : GenericService<TransactionBankInfo, long>, ITransactionBankService { public TransactionBankService(IRepository<TransactionBankInfo, long> repository, IEventBus eventBus) : base(repository, eventBus) { } public int BankProcessing(TransactionBankInfo entity, int vipXu) { var list = new List<SqlParameter> { AddInputParameter("@CustomerCode", entity.CustomerCode), AddInputParameter("@TransactionCode", entity.TransactionCode), AddInputParameter("@CreateDate", entity.CreateDate), AddInputParameter("@BankCode", entity.BankCode), AddInputParameter("@Amount", entity.Amount), AddInputParameter("@ResponCode", entity.ResponCode), AddInputParameter("@Mac", entity.Mac), AddInputParameter("@TransId", entity.TransId), AddInputParameter("@Type", entity.Type), AddInputParameter("@Description", entity.Description), AddInputParameter("@Status", entity.Status), AddInputParameter("@VipXu", vipXu) }; return ExecuteNonQuery("sp_TransactionBank_BankProcessing", list.ToArray()); } public IList<TransactionBankInfo> ExportExcelAtm(DateTime fromDate, DateTime toDate, int type) { var list = new List<SqlParameter> { AddInputParameter("@Type", type), AddInputParameter("@FromDate", fromDate), AddInputParameter("@ToDate", toDate) }; return ExecuteReader<TransactionBankInfo>("sp_TransactionBank_ReportATM", list.ToArray()); } public IList<TransactionBankInfo> GetPaged(string keyword, string bankCode, int type, int status, int isLock, DateTime fromDate, DateTime toDate, int pageIndex, int pageSize, out int totals) { var list = new List<SqlParameter> { AddInputParameter("@SearchText", keyword), AddInputParameter("@BankCode", bankCode), AddInputParameter("@Type", type), AddInputParameter("@Status", status), AddInputParameter("@IsLock", isLock), AddInputParameter("@FromDate", fromDate), AddInputParameter("@ToDate", toDate), AddInputParameter("@PageIndex", pageIndex), AddInputParameter("@PageSize", pageSize) }; return ExecuteReader<TransactionBankInfo>("sp_TransactionBank_Search_Paged", "@TotalRecord", out totals, list.ToArray()); } public int ATMClosed(DateTime toDate) { var list = new List<SqlParameter> { AddInputParameter("@ToDate", toDate) }; return ExecuteNonQuery("sp_TransactionAtm_Closed", list.ToArray()); } } }<file_sep>using System.Collections.Generic; using System.Data.SqlClient; using CMSSolutions.Data; using CMSSolutions.Events; using CMSSolutions.Services; using CMSSolutions.Websites.Entities; namespace CMSSolutions.Websites.Services { public interface ISupportService : IGenericService<SupportInfo, int>, IDependency { string LanguageCode { get; set; } int SiteId { get; set; } IList<SupportInfo> GetAllParents(int status); IList<SupportInfo> GetPaged(string keyword, int parentId, int status, int pageIndex, int pageSize, out int totals); IList<SupportInfo> GetByParent(int parentId); IList<SupportInfo> GetAllChildren(int status); } public class SupportService : GenericService<SupportInfo, int>, ISupportService { public SupportService(IRepository<SupportInfo, int> repository, IEventBus eventBus) : base(repository, eventBus) { } public string LanguageCode { get; set; } public int SiteId { get; set; } public IList<SupportInfo> GetAllParents(int status) { var list = new List<SqlParameter> { AddInputParameter("@SiteId", SiteId), AddInputParameter("@LanguageCode", LanguageCode), AddInputParameter("@Status", status), }; return ExecuteReader<SupportInfo>("sp_Supports_GetAllParents", list.ToArray()); } public IList<SupportInfo> GetPaged(string keyword, int parentId, int status, int pageIndex, int pageSize, out int totals) { var list = new List<SqlParameter> { AddInputParameter("@Keyword", keyword), AddInputParameter("@SiteId", SiteId), AddInputParameter("@LanguageCode", LanguageCode), AddInputParameter("@ParentId", parentId), AddInputParameter("@Status", status), AddInputParameter("@PageIndex", pageIndex), AddInputParameter("@PageSize", pageSize) }; return ExecuteReader<SupportInfo>("sp_Supports_Search_Paged", "@TotalRecord", out totals, list.ToArray()); } public IList<SupportInfo> GetByParent(int parentId) { var list = new List<SqlParameter> { AddInputParameter("@SiteId", SiteId), AddInputParameter("@LanguageCode", LanguageCode), AddInputParameter("@ParentId", parentId) }; return ExecuteReader<SupportInfo>("sp_Supports_GetByParent", list.ToArray()); } public IList<SupportInfo> GetAllChildren(int status) { var list = new List<SqlParameter> { AddInputParameter("@SiteId", SiteId), AddInputParameter("@LanguageCode", LanguageCode), AddInputParameter("@Status", status), }; return ExecuteReader<SupportInfo>("sp_Supports_GetAllChildren", list.ToArray()); } } }<file_sep>using System; using System.Web.Mvc; using CMSSolutions.Extensions; using CMSSolutions.Web.Mvc; using CMSSolutions.Web.Routing; using CMSSolutions.Web.Themes; using CMSSolutions.Web.UI.ControlForms; using CMSSolutions.Web.UI.Navigation; using CMSSolutions.Websites.Entities; using CMSSolutions.Websites.Extensions; using CMSSolutions.Websites.Models; using CMSSolutions.Websites.Services; namespace CMSSolutions.Websites.Controllers { [Themed(IsDashboard = true), Authorize] public class AdminFilmTypesController : BaseAdminController { public AdminFilmTypesController(IWorkContextAccessor workContextAccessor) : base(workContextAccessor) { TableName = "tblFilmTypes"; } [Url("admin/film-types")] public ActionResult Index() { WorkContext.Breadcrumbs.Add(new Breadcrumb { Text = T("Quản lý thể loại phim"), Url = "#" }); var result = new ControlGridFormResult<FilmTypesInfo> { Title = T("Quản lý thể loại phim"), CssClass = "table table-bordered table-striped", IsAjaxSupported = true, FetchAjaxSource = GetFilmTypes, UpdateActionName = "Update", ActionsColumnWidth = 100, ClientId = TableName, DefaultPageSize = WorkContext.DefaultPageSize, GridWrapperStartHtml = Constants.Grid.GridWrapperStartHtml, GridWrapperEndHtml = Constants.Grid.GridWrapperEndHtml }; result.AddCustomVar(Extensions.Constants.LanguageCode, "$('#" + Extensions.Constants.LanguageCode + "').val();", true); result.AddCustomVar(Extensions.Constants.SiteId, "$('#" + Extensions.Constants.SiteId + "').val();", true); result.AddCustomVar(Extensions.Constants.StatusId, "$('#" + Extensions.Constants.StatusId + "').val();", true); result.AddColumn(x => x.Id, T("ID")).AlignCenter().HasWidth(60); result.AddColumn(x => x.Name, T("Tên thể loại phim")); result.AddColumn(x => EnumExtensions.GetDisplayName((Status)x.Status), T("Trạng thái")); result.AddAction().HasText(T("Thêm mới")) .HasUrl(Url.Action("Edit", RouteData.Values.Merge(new { id = 0 }))) .HasButtonStyle(ButtonStyle.Primary) .HasBoxButton(false) .HasCssClass(Constants.RowLeft) .HasRow(true); result.AddAction(new ControlFormHtmlAction(() => BuildLanguages(true, Extensions.Constants.SiteId))).HasParentClass(Constants.ContainerCssClassCol3); result.AddAction(new ControlFormHtmlAction(() => BuildSites(false, string.Empty))).HasParentClass(Constants.ContainerCssClassCol3); result.AddAction(new ControlFormHtmlAction(BuildStatus)).HasParentClass(Constants.ContainerCssClassCol3); result.AddRowAction() .HasText(T("Sửa")) .HasUrl(x => Url.Action("Edit", RouteData.Values.Merge(new { id = x.Id }))) .HasButtonStyle(ButtonStyle.Default) .HasButtonSize(ButtonSize.ExtraSmall); result.AddRowAction(true) .HasText(T("Xóa")) .HasName("Delete") .HasValue(x => x.Id) .HasButtonStyle(ButtonStyle.Danger) .HasButtonSize(ButtonSize.ExtraSmall) .HasConfirmMessage(T(Constants.Messages.ConfirmDeleteRecord).Text); result.AddReloadEvent("UPDATE_ENTITY_COMPLETE"); result.AddReloadEvent("DELETE_ENTITY_COMPLETE"); return result; } private ControlGridAjaxData<FilmTypesInfo> GetFilmTypes(ControlGridFormRequest options) { var languageCode = WorkContext.CurrentCulture; if (Utilities.IsNotNull(Request.Form[Extensions.Constants.LanguageCode])) { languageCode = Request.Form[Extensions.Constants.LanguageCode]; } var siteId = 0; if (Utilities.IsNotNull(Request.Form[Extensions.Constants.SiteId])) { siteId = Convert.ToInt32(Request.Form[Extensions.Constants.SiteId]); } var statusId = 0; if (Utilities.IsNotNull(Request.Form[Extensions.Constants.StatusId])) { statusId = Convert.ToInt32(Request.Form[Extensions.Constants.StatusId]); } int totals; var items = WorkContext.Resolve<IFilmTypesService>().GetPaged(languageCode,siteId, statusId, options.PageIndex, options.PageSize, out totals); var result = new ControlGridAjaxData<FilmTypesInfo>(items, totals); return result; } [Url("admin/film-types/edit/{id}")] public ActionResult Edit(int id) { WorkContext.Breadcrumbs.Add(new Breadcrumb { Text = T("Quản lý thể loại phim"), Url = Url.Action("Index") }); WorkContext.Breadcrumbs.Add(new Breadcrumb { Text = T("Thông tin thể loại phim"), Url = "#" }); var model = new FilmTypesModel(); if (id > 0) { var service = WorkContext.Resolve<IFilmTypesService>(); model = service.GetById(id); } var result = new ControlFormResult<FilmTypesModel>(model) { Title = T("Thông tin thể loại phim"), FormMethod = FormMethod.Post, UpdateActionName = "Update", SubmitButtonText = T("Lưu lại"), CancelButtonText = T("Trở về"), ShowBoxHeader = false, FormWrapperStartHtml = Constants.Form.FormWrapperStartHtml, FormWrapperEndHtml = Constants.Form.FormWrapperEndHtml }; result.RegisterExternalDataSource(x => x.LanguageCode, y => BindLanguages()); result.RegisterCascadingDropDownDataSource(x => x.SiteId, Url.Action("GetSitesByLanguage")); result.RegisterExternalDataSource(x => x.Status, y => BindStatus()); return result; } [HttpPost, ValidateInput(false), FormButton("Save")] [Url("admin/film-types/update")] public ActionResult Update(FilmTypesModel model) { if (!ModelState.IsValid) { return new AjaxResult().Alert(T(Constants.Messages.InvalidModel)); } var service = WorkContext.Resolve<IFilmTypesService>(); FilmTypesInfo item = model.Id == 0 ? new FilmTypesInfo() : service.GetById(model.Id); item.LanguageCode = model.LanguageCode; item.SiteId = model.SiteId; item.Name = model.Name; item.Description = model.Description; item.Status = model.Status; item.IsFilm = model.IsFilm; item.IsShow = model.IsShow; item.IsClip = model.IsClip; item.IsJJFilm = model.IsJJFilm; service.Save(item); return new AjaxResult().NotifyMessage("UPDATE_ENTITY_COMPLETE") .Alert(T("Cập nhật thành công!")); } [FormButton("Delete")] [HttpPost, ActionName("Update")] public ActionResult Delete(int id) { var service = WorkContext.Resolve<IFilmTypesService>(); var item = service.GetById(id); item.Status = (int)Status.Deleted; service.Update(item); return new AjaxResult() .NotifyMessage("DELETE_ENTITY_COMPLETE") .Alert(T("Dữ liệu chuyển trạng thái xóa tạm thời!")); } } } <file_sep>using System.ComponentModel; using System.ComponentModel.DataAnnotations.Schema; using System.Runtime.Serialization; using CMSSolutions.Data; using CMSSolutions.Data.Entity; namespace CMSSolutions.Websites.Entities { [DataContract] public class SliderInfo : BaseEntity<int> { [DataMember] [DisplayName("SiteId")] public int SiteId { get; set; } [DataMember] [DisplayName("LanguageCode")] public string LanguageCode { get; set; } [DataMember] [DisplayName("CategoryId")] public int CategoryId { get; set; } [NotMapped] [DisplayName("CategoryName")] public string CategoryName { get; set; } [DataMember] [DisplayName("PageId")] public int PageId { get; set; } [DataMember] [DisplayName("FilmId")] public long FilmId { get; set; } [NotMapped] [DisplayName("FilmName")] public string FilmName { get; set; } [DataMember] [DisplayName("Images")] public string Images { get; set; } [DataMember] [DisplayName("OrderBy")] public int OrderBy { get; set; } } public class SliderMap : EntityTypeConfiguration<SliderInfo>, IEntityTypeConfiguration { public SliderMap() { ToTable("Modules_Slider"); HasKey(x => x.Id); Property(x => x.LanguageCode).HasMaxLength(50).IsRequired(); Property(x => x.SiteId).IsRequired(); Property(x => x.CategoryId).IsRequired(); Property(x => x.PageId).IsRequired(); Property(x => x.FilmId).IsRequired(); Property(x => x.Images).IsRequired().HasMaxLength(500); Property(x => x.OrderBy).IsRequired(); } } }<file_sep>using System.Collections.Generic; using System.Data.SqlClient; using CMSSolutions.Caching; using CMSSolutions.Data; using CMSSolutions.Events; using CMSSolutions.Services; using CMSSolutions.Websites.Entities; namespace CMSSolutions.Websites.Services { public interface ISliderService : ICacheService<SliderInfo, int>, IGenericService<SliderInfo, int>, IDependency { string LanguageCode { get; set; } int SiteId { get; set; } IList<SliderInfo> GetPaged(int pageId, int pageIndex, int pageSize, out int totals); IList<SliderInfo> GetByPageId(int pageId); void RefreshByPage(int pageId); IList<SliderInfo> GetCacheByPageId(int pageId); } public class SliderService : GenericService<SliderInfo, int>, ISliderService { private readonly ICacheInfo cacheManager; private readonly ICategoryService categoryService; public SliderService(IRepository<SliderInfo, int> repository, IEventBus eventBus, ICacheInfo cacheManager, ICategoryService categoryService) : base(repository, eventBus) { this.cacheManager = cacheManager; this.categoryService = categoryService; } public string LanguageCode { get; set; } public int SiteId { get; set; } public IList<SliderInfo> GetPaged(int pageId, int pageIndex, int pageSize, out int totals) { var list = new List<SqlParameter> { AddInputParameter("@LanguageCode", LanguageCode), AddInputParameter("@SiteId", SiteId), AddInputParameter("@PageId", pageId), AddInputParameter("@PageIndex", pageIndex), AddInputParameter("@PageSize", pageSize) }; return ExecuteReader<SliderInfo>("sp_Slider_Search_Paged", "@TotalRecord", out totals, list.ToArray()); } public IList<SliderInfo> GetByPageId(int pageId) { var list = new List<SqlParameter> { AddInputParameter("@LanguageCode", LanguageCode), AddInputParameter("@SiteId", SiteId), AddInputParameter("@PageId", pageId) }; return ExecuteReader<SliderInfo>("sp_Slider_GetByPageId", list.ToArray()); } public IList<SliderInfo> GetCacheByPageId(int pageId) { var list = cacheManager.Get(string.Format(Extensions.Constants.CacheKeys.HOME_SLIDER_PAGE, pageId)); if (list == null) { list = GetByPageId(pageId); cacheManager.Remove(string.Format(Extensions.Constants.CacheKeys.HOME_SLIDER_PAGE, pageId)); cacheManager.Add(string.Format(Extensions.Constants.CacheKeys.HOME_SLIDER_PAGE, pageId), list); } return (IList<SliderInfo>)list; } public void RefreshByPage(int pageId) { cacheManager.Remove(string.Format(Extensions.Constants.CacheKeys.HOME_SLIDER_PAGE, pageId)); cacheManager.Add(string.Format(Extensions.Constants.CacheKeys.HOME_SLIDER_PAGE, pageId), GetByPageId(pageId)); } public SliderInfo GetByIdCache(int id) { throw new System.NotImplementedException(); } public IList<SliderInfo> GetAllCache() { throw new System.NotImplementedException(); } public IList<SliderInfo> ResetCache() { throw new System.NotImplementedException(); } } }<file_sep>using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Text; using System.Web.Mvc; using CMSSolutions.Configuration; using CMSSolutions.Extensions; using CMSSolutions.Localization.Domain; using CMSSolutions.Localization.Services; using CMSSolutions.Security.Cryptography; using CMSSolutions.Web.Mvc; using CMSSolutions.Web.Security; using CMSSolutions.Web.Security.Services; using CMSSolutions.Web.Themes; using CMSSolutions.Websites.Entities; using CMSSolutions.Websites.Extensions; using CMSSolutions.Websites.Services; namespace CMSSolutions.Websites.Controllers { [Authorize] [Themed(IsDashboard = true)] public class BaseAdminController : BaseController { public BaseAdminController( IWorkContextAccessor workContextAccessor) : base(workContextAccessor) { } public virtual FTPClient GetConnectionFtp(int serverId, out string rootFolder, out string languageCode, out int siteId) { var service = WorkContext.Resolve<IFilmServersService>(); var server = service.GetById(serverId); if (server != null) { string password = EncryptionExtensions.Decrypt(KeyConfiguration.PublishKey, server.Password); if (string.IsNullOrEmpty(password)) { throw new ArgumentException(T(SecurityConstants.ErrorConfigKey).Text); } string userName = EncryptionExtensions.Decrypt(KeyConfiguration.PublishKey, server.UserName); if (string.IsNullOrEmpty(userName)) { throw new ArgumentException(T(SecurityConstants.ErrorConfigKey).Text); } rootFolder = server.FolderRoot; languageCode = server.LanguageCode; siteId = server.SiteId; return new FTPClient(server.ServerIP, userName, password); } rootFolder = string.Empty; languageCode = string.Empty; siteId = 0; return null; } public virtual string BuildFromDate(bool showDefaultDate = true) { var sb = new StringBuilder(); var date = ""; if (showDefaultDate) { date = DateTime.Now.AddDays(-7).ToString("dd/MM/yyyy"); } var fromDateSelected = GetQueryString(9); if (!string.IsNullOrEmpty(fromDateSelected)) { date = fromDateSelected; } sb.AppendFormat(T("Từ ngày") + " <input id=\"" + Extensions.Constants.FromDate + "\" name=\"" + Extensions.Constants.FromDate + "\" value=\"" + date + "\" class=\"form-control datepicker\"></input>"); sb.Append("<script>$(document).ready(function () { " + "$('.datepicker').datepicker({ " + "dateFormat: 'dd/mm/yy', " + "changeMonth: true, " + "changeYear: true, " + "onSelect: function (dateText) { " + "$('#" + TableName + "').jqGrid().trigger('reloadGrid'); " + "}}); });</script>"); return sb.ToString(); } public virtual string BuildToDate(bool showDefaultDate = true) { var sb = new StringBuilder(); var date = ""; if (showDefaultDate) { date = DateTime.Now.ToString("dd/MM/yyyy"); } var toDateSelected = GetQueryString(10); if (!string.IsNullOrEmpty(toDateSelected)) { date = toDateSelected; } sb.AppendFormat(T("Đến ngày") + " <input id=\"" + Extensions.Constants.ToDate + "\" name=\"" + Extensions.Constants.ToDate + "\" value=\"" + date + "\" class=\"form-control datepicker\"></input>"); sb.Append("<script>$(document).ready(function () { " + "$('.datepicker').datepicker({ " + "dateFormat: 'dd/mm/yy', " + "changeMonth: true, " + "changeYear: true, " + "onSelect: function (dateText) { " + "$('#" + TableName + "').jqGrid().trigger('reloadGrid'); " + "}}); });</script>"); return sb.ToString(); } public virtual string BuildSearchText() { var sb = new StringBuilder(); var keyword = GetQueryString(11); sb.AppendFormat(T("Từ khóa") + " <input value=\"" + keyword + "\" placeholder=\"" + T("Nhập từ khóa cần tìm.") + "\" id=\"" + Extensions.Constants.SearchText + "\" name=\"" + Extensions.Constants.SearchText + "\" class=\"form-control\" onkeypress = \"return InputEnterEvent(event, '" + TableName + "');\" onblur=\"$('#" + TableName + "').jqGrid().trigger('reloadGrid');\"></input>"); return sb.ToString(); } public virtual string BuildStatus() { var list = EnumExtensions.GetListItems<Status>(); var statusSelected = GetQueryString(8); var sb = new StringBuilder(); sb.AppendFormat(T("Trạng thái") + " <select id=\"" + Extensions.Constants.StatusId + "\" name=\"" + Extensions.Constants.StatusId + "\" autocomplete=\"off\" class=\"uniform form-control col-md-3\" onchange=\"$('#" + TableName + "').jqGrid().trigger('reloadGrid');\">"); foreach (var status in list) { if (!string.IsNullOrEmpty(statusSelected) && status.Value == statusSelected) { sb.AppendFormat("<option selected value=\"{1}\">{0}</option>", status.Text, status.Value); continue; } sb.AppendFormat("<option value=\"{1}\">{0}</option>", status.Text, status.Value); } sb.Append("</select>"); return sb.ToString(); } public virtual string BuildServers() { var languageCode = WorkContext.CurrentCulture; if (Utilities.IsNotNull(Request.Form[Extensions.Constants.LanguageCode])) { languageCode = Request.Form[Extensions.Constants.LanguageCode]; } var siteId = 0; if (Utilities.IsNotNull(Request.Form[Extensions.Constants.SiteId])) { siteId = Convert.ToInt32(Request.Form[Extensions.Constants.SiteId]); } var service = WorkContext.Resolve<IFilmServersService>(); var list = service.GetRecords(x => x.LanguageCode == languageCode && x.SiteId == siteId); var sb = new StringBuilder(); sb.AppendFormat(T("Máy chủ") + " <select id=\"" + Extensions.Constants.ServerId + "\" name=\"" + Extensions.Constants.ServerId + "\" autocomplete=\"off\" class=\"uniform form-control col-md-3\" onchange=\"$('#" + TableName + "').jqGrid().trigger('reloadGrid');\">"); foreach (var server in list) { sb.AppendFormat("<option value=\"{1}\">{0}</option>", server.ServerName, server.Id); } sb.Append("</select>"); return sb.ToString(); } public virtual IEnumerable<SelectListItem> BindServers() { var service = WorkContext.Resolve<IFilmServersService>(); var items = service.GetRecords(); var result = new List<SelectListItem>(); result.AddRange(items.Select(item => new SelectListItem { Text = string.Format("[{0}] {1} {2}", item.ServerIP, item.ServerName, item.IsVip ? T(" - VIP") : T(" - Thường")), Value = item.Id.ToString(), Selected = item.IsDefault })); result.Insert(0, new SelectListItem { Text = "--- Chọn máy chủ ---", Value = "0" }); return result; } public virtual string BuildUsers() { var service = WorkContext.Resolve<IMembershipService>(); var list = service.GetRecords(x => !x.IsLockedOut); var sb = new StringBuilder(); var userSelected = GetQueryString(3); sb.AppendFormat(T("Người quản trị") + " <select id=\"" + Extensions.Constants.UserId + "\" name=\"" + Extensions.Constants.UserId + "\" autocomplete=\"off\" class=\"uniform form-control col-md-3\" onchange=\"$('#" + TableName + "').jqGrid().trigger('reloadGrid');\">"); foreach (var user in list) { if (string.IsNullOrEmpty(userSelected)) { if (user.Id == WorkContext.CurrentUser.Id) { sb.AppendFormat("<option selected value=\"{1}\">{0}</option>", user.FullName, user.Id); continue; } } if (!string.IsNullOrEmpty(userSelected) && user.Id == int.Parse(userSelected)) { sb.AppendFormat("<option selected value=\"{1}\">{0}</option>", user.FullName, user.Id); continue; } sb.AppendFormat("<option value=\"{1}\">{0}</option>", user.FullName, user.Id); } sb.Append("</select>"); return sb.ToString(); } public virtual string BuildCountries() { var service = WorkContext.Resolve<ICountryService>(); var items = service.GetRecords(); var result = new List<SelectListItem>(); result.AddRange(items.Select(item => new SelectListItem { Text = item.Name, Value = item.Id.ToString() })); result.Insert(0, new SelectListItem {Text = T("--- Chọn nước sản xuât ---"), Value = "0"}); var sb = new StringBuilder(); sb.AppendFormat(T("Nước sản xuất") + " <select id=\"" + Extensions.Constants.CountryId + "\" name=\"" + Extensions.Constants.CountryId + "\" autocomplete=\"off\" class=\"uniform form-control col-md-3\" onchange=\"$('#" + TableName + "').jqGrid().trigger('reloadGrid');\">"); foreach (var item in result) { sb.AppendFormat("<option value=\"{1}\">{0}</option>", item.Text, item.Value); } sb.Append("</select>"); return sb.ToString(); } public string GetQueryString(int index) { var returnUrl = Request.QueryString[Extensions.Constants.ReturnUrl]; if (!string.IsNullOrEmpty(returnUrl)) { var data = Encoding.UTF8.GetString(Convert.FromBase64String(returnUrl)); if (!string.IsNullOrEmpty(data)) { var list = data.Split(','); if (list.Length > index) { var result = list[index]; if (result != "null") { return result; } } } } return string.Empty; } public virtual string BuildLanguages(bool hasEvent, string controlName) { var service = WorkContext.Resolve<ILanguageService>(); var items = service.GetActiveLanguages(); var list = new List<Language>(); list.AddRange(items.Where(x => x.Theme == Constants.ThemeDefault)); var sb = new StringBuilder(); if (hasEvent) { var url = Url.Action("GetSitesByLanguage"); sb.AppendFormat(T("Ngôn ngữ") + " <select id=\"" + Extensions.Constants.LanguageCode + "\" name=\"" + Extensions.Constants.LanguageCode + "\" autocomplete=\"off\" class=\"uniform form-control col-md-3\" onchange=\"" + " var data = $('#" + TableName + "_Container').find('select').serialize();" + @"$.ajax({{ url: '" + url + @"', data: data, type: 'POST', dataType: 'json', success: function (result) {{ $('#" + controlName + @"').empty(); if (result != null){{ $.each(result, function(idx, item) {{ $('#" + controlName + @"').append($('<option>', {{ value: item.Value, text: item.Text }})); }}); }} }} }}); $('#" + TableName + "').jqGrid().trigger('reloadGrid');" + "\">"); } else { sb.AppendFormat(T("Ngôn ngữ") + " <select id=\"" + Extensions.Constants.LanguageCode + "\" name=\"" + Extensions.Constants.LanguageCode + "\" autocomplete=\"off\" class=\"uniform form-control col-md-3\" onchange=\"$('#" + TableName + "').jqGrid().trigger('reloadGrid');\">"); } var languageSelected = GetQueryString(0); foreach (var language in list) { if (string.IsNullOrEmpty(languageSelected)) { if (language.CultureCode == WorkContext.CurrentCulture) { sb.AppendFormat("<option selected value=\"{1}\">{0}</option>", language.Name, language.CultureCode); continue; } } if (!string.IsNullOrEmpty(languageSelected) && language.CultureCode == languageSelected) { sb.AppendFormat("<option selected value=\"{1}\">{0}</option>", language.Name, language.CultureCode); continue; } sb.AppendFormat("<option value=\"{1}\">{0}</option>", language.Name, language.CultureCode); } sb.Append("</select>"); return sb.ToString(); } public virtual IEnumerable<SelectListItem> BindFilmTypes() { var service = WorkContext.Resolve<IFilmTypesService>(); var items = service.GetRecords(x => x.Status == (int)Status.Approved); var result = new List<SelectListItem>(); result.AddRange(items.Select(item => new SelectListItem { Text = item.Name, Value = item.Id.ToString() })); return result; } public virtual IEnumerable<SelectListItem> BindCountries() { var service = WorkContext.Resolve<ICountryService>(); var items = service.GetRecords(); var result = new List<SelectListItem>(); result.AddRange(items.Select(item => new SelectListItem { Text = item.Name, Value = item.Id.ToString() })); return result; } public virtual string BuildSites(bool hasEvent, string controlName) { var languageCode = WorkContext.CurrentCulture; if (Utilities.IsNotNull(Request.Form[Extensions.Constants.LanguageCode])) { languageCode = Request.Form[Extensions.Constants.LanguageCode]; } var service = WorkContext.Resolve<ISiteService>(); var list = service.GetRecords(x => x.LanguageCode == languageCode); var result = new List<SelectListItem>(); result.AddRange(list.Select(item => new SelectListItem { Text = item.Name, Value = item.Id.ToString(), Selected = item.IsActived })); result.Insert(0, new SelectListItem { Text = "--- Chọn trang web ---", Value = "0" }); var url = Url.Action("GetCategoriesBySite"); var sb = new StringBuilder(); if (hasEvent) { sb.AppendFormat(T("Trang web") + " <select id=\"" + Extensions.Constants.SiteId + "\" name=\"" + Extensions.Constants.SiteId + "\" autocomplete=\"off\" class=\"uniform form-control col-md-3\" onchange=\"" + " var data = $('#" + TableName + "_Container').find('select').serialize();" + @"$.ajax({{ url: '" + url + @"', data: data, type: 'POST', dataType: 'json', success: function (result) {{ $('#" + controlName + @"').empty(); if (result != null){{ $.each(result, function(idx, item) {{ $('#" + controlName + @"').append($('<option>', {{ value: item.Value, text: item.Text }})); }}); }} }} }}); $('#" + TableName + "').jqGrid().trigger('reloadGrid');" + "\">"); } else { sb.AppendFormat(T("Trang web") + " <select id=\"" + Extensions.Constants.SiteId + "\" name=\"" + Extensions.Constants.SiteId + "\" autocomplete=\"off\" class=\"uniform form-control col-md-3\" onchange=\"$('#" + TableName + "').jqGrid().trigger('reloadGrid');\">"); } var siteSelected = GetQueryString(1); foreach (var site in result) { if (!string.IsNullOrEmpty(siteSelected) && site.Value == siteSelected) { sb.AppendFormat("<option selected value=\"{1}\">{0}</option>", site.Text, site.Value); continue; } sb.AppendFormat("<option value=\"{1}\">{0}</option>", site.Text, site.Value); } sb.Append("</select>"); var categorySelected = GetQueryString(2); if (!string.IsNullOrEmpty(siteSelected) && !string.IsNullOrEmpty(categorySelected)) { sb.AppendFormat("<script type=\"text/javascript\">$(document).ready(function() {{" + "var data = $('#" + TableName + "_Container').find('select').serialize();" + @"$.ajax({{ url: '" + url + @"', data: data, type: 'POST', dataType: 'json', success: function (result) {{ $('#" + controlName + @"').empty(); if (result != null){{ $.each(result, function(idx, item) {{ if(item.Value == '"+categorySelected+@"'){{ $('#" + controlName + @"').append('<option selected value=' + item.Value + '>'+ item.Text +'</option>'); }} else{{ $('#" + controlName + @"').append('<option value=' + item.Value + '>'+ item.Text +'</option>'); }} }}); }} }} }});}});</script>"); } return sb.ToString(); } public virtual string BuildSiteServers(bool hasEvent, string controlName) { var languageCode = WorkContext.CurrentCulture; if (Utilities.IsNotNull(Request.Form[Extensions.Constants.LanguageCode])) { languageCode = Request.Form[Extensions.Constants.LanguageCode]; } var service = WorkContext.Resolve<ISiteService>(); var list = service.GetRecords(x => x.LanguageCode == languageCode); var result = new List<SelectListItem>(); result.AddRange(list.Select(item => new SelectListItem { Text = item.Name, Value = item.Id.ToString(), Selected = item.IsActived })); result.Insert(0, new SelectListItem { Text = "--- Chọn trang web ---", Value = "0" }); var sb = new StringBuilder(); if (hasEvent) { var url = Url.Action("GetServersBySite"); sb.AppendFormat(T("Trang web") + " <select id=\"" + Extensions.Constants.SiteId + "\" name=\"" + Extensions.Constants.SiteId + "\" autocomplete=\"off\" class=\"uniform form-control col-md-3\" onchange=\"" + " var data = $('#" + TableName + "_Container').find('select').serialize();" + @"$.ajax({{ url: '" + url + @"', data: data, type: 'POST', dataType: 'json', success: function (result) {{ $('#" + controlName + @"').empty(); if (result != null){{ $.each(result, function(idx, item) {{ $('#" + controlName + @"').append($('<option>', {{ value: item.Value, text: item.Text }})); }}); }} }} }}); $('#" + TableName + "').jqGrid().trigger('reloadGrid');" + "\">"); } else { sb.AppendFormat(T("Trang web") + " <select id=\"" + Extensions.Constants.SiteId + "\" name=\"" + Extensions.Constants.SiteId + "\" autocomplete=\"off\" class=\"uniform form-control col-md-3\" onchange=\"$('#" + TableName + "').jqGrid().trigger('reloadGrid');\">"); } foreach (var site in result) { sb.AppendFormat("<option value=\"{1}\">{0}</option>", site.Text, site.Value); } sb.Append("</select>"); return sb.ToString(); } [Url("admin/vast/get-ads-by-site")] public ActionResult GetAdBySite() { var languageCode = WorkContext.CurrentCulture; if (Utilities.IsNotNull(Request.Form[Extensions.Constants.LanguageCode])) { languageCode = Request.Form[Extensions.Constants.LanguageCode]; } var siteId = 0; if (Utilities.IsNotNull(Request.Form[Extensions.Constants.SiteId])) { siteId = Convert.ToInt32(Request.Form[Extensions.Constants.SiteId]); } var service = WorkContext.Resolve<IAdvertisementService>(); var items = service.GetAdBySite(languageCode, siteId); var result = new List<SelectListItem>(); result.AddRange(items.Select(item => new SelectListItem { Text = item.Title, Value = item.Id.ToString() })); return Json(result); } public virtual string BuildSiteAds(bool hasEvent, string controlName) { var languageCode = WorkContext.CurrentCulture; if (Utilities.IsNotNull(Request.Form[Extensions.Constants.LanguageCode])) { languageCode = Request.Form[Extensions.Constants.LanguageCode]; } var service = WorkContext.Resolve<ISiteService>(); var list = service.GetRecords(x => x.LanguageCode == languageCode); var result = new List<SelectListItem>(); result.AddRange(list.Select(item => new SelectListItem { Text = item.Name, Value = item.Id.ToString(), Selected = item.IsActived })); result.Insert(0, new SelectListItem { Text = "--- Chọn trang web ---", Value = "0" }); var sb = new StringBuilder(); if (hasEvent) { var url = Url.Action("GetAdsBySite"); sb.AppendFormat(T("Trang web") + " <select id=\"" + Extensions.Constants.SiteId + "\" name=\"" + Extensions.Constants.SiteId + "\" autocomplete=\"off\" class=\"uniform form-control col-md-3\" onchange=\"" + " var data = $('#" + TableName + "_Container').find('select').serialize();" + @"$.ajax({{ url: '" + url + @"', data: data, type: 'POST', dataType: 'json', success: function (result) {{ $('#" + controlName + @"').empty(); if (result != null){{ $.each(result, function(idx, item) {{ $('#" + controlName + @"').append($('<option>', {{ value: item.Value, text: item.Text }})); }}); }} }} }}); $('#" + TableName + "').jqGrid().trigger('reloadGrid');" + "\">"); } else { sb.AppendFormat(T("Trang web") + " <select id=\"" + Extensions.Constants.SiteId + "\" name=\"" + Extensions.Constants.SiteId + "\" autocomplete=\"off\" class=\"uniform form-control col-md-3\" onchange=\"$('#" + TableName + "').jqGrid().trigger('reloadGrid');\">"); } foreach (var site in result) { sb.AppendFormat("<option value=\"{1}\">{0}</option>", site.Text, site.Value); } sb.Append("</select>"); return sb.ToString(); } public virtual string BuildCategories() { var languageCode = WorkContext.CurrentCulture; if (Utilities.IsNotNull(Request.Form[Extensions.Constants.LanguageCode])) { languageCode = Request.Form[Extensions.Constants.LanguageCode]; } var siteId = 0; if (Utilities.IsNotNull(Request.Form[Extensions.Constants.SiteId])) { siteId = Convert.ToInt32(Request.Form[Extensions.Constants.SiteId]); } var service = WorkContext.Resolve<ICategoryService>(); service.LanguageCode = languageCode; service.SiteId = siteId; var sb = new StringBuilder(); var categorySelected = GetQueryString(2); sb.AppendFormat(T("Chuyên mục") + " <select id=\"" + Extensions.Constants.CategoryId + "\" name=\"" + Extensions.Constants.CategoryId + "\" autocomplete=\"off\" class=\"uniform form-control col-md-3\" onchange=\"$('#"+TableName+"').jqGrid().trigger('reloadGrid');\">"); var list = service.GetTree(); foreach (var cate in list) { if (!string.IsNullOrEmpty(categorySelected) && cate.Id == int.Parse(categorySelected)) { sb.AppendFormat("<option selected value=\"{1}\">{0}</option>", cate.ChildenName, cate.Id); continue; } sb.AppendFormat("<option value=\"{1}\">{0}</option>", cate.ChildenName, cate.Id); } sb.Append("</select>"); return sb.ToString(); } public virtual IEnumerable<SelectListItem> BindLanguages() { var service = WorkContext.Resolve<ILanguageService>(); var items = service.GetActiveLanguages(); var result = new List<SelectListItem>(); result.AddRange(items.Where(x => x.Theme == Constants.ThemeDefault).Select(item => new SelectListItem { Text = item.Name, Value = item.CultureCode.ToString(), Selected = item.CultureCode == WorkContext.CurrentCulture })); return result; } public virtual IEnumerable<SelectListItem> BindSites() { var languageCode = WorkContext.CurrentCulture; if (Utilities.IsNotNull(Request.Form[Extensions.Constants.LanguageCode])) { languageCode = Request.Form[Extensions.Constants.LanguageCode]; } var service = WorkContext.Resolve<ISiteService>(); var items = service.GetRecords(x => x.LanguageCode == languageCode); var result = new List<SelectListItem>(); result.AddRange(items.Select(item => new SelectListItem { Text = item.Name, Value = item.Id.ToString(), Selected = item.IsActived })); result.Insert(0, new SelectListItem { Text = "--- Chọn trang web ---", Value = "0" }); return result; } public virtual string BuildDirectors() { var service = WorkContext.Resolve<IDirectorService>(); var items = service.GetRecords(x => x.Status == (int)Status.Approved); var result = new List<SelectListItem>(); result.AddRange(items.Select(item => new SelectListItem { Text = item.FullName, Value = item.Id.ToString() })); result.Insert(0, new SelectListItem { Text = "--- Đạo diễn phim ---", Value = "0" }); var directorSelected = GetQueryString(4); var sb = new StringBuilder(); sb.AppendFormat(T("Đạo diễn") + " <select id=\"" + Extensions.Constants.DirectorId + "\" name=\"" + Extensions.Constants.DirectorId + "\" autocomplete=\"off\" class=\"uniform form-control col-md-3\" onchange=\"$('#" + TableName + "').jqGrid().trigger('reloadGrid');\">"); foreach (var director in result) { if (!string.IsNullOrEmpty(directorSelected) && director.Value == directorSelected) { sb.AppendFormat("<option selected value=\"{1}\">{0}</option>", director.Text, director.Value); continue; } sb.AppendFormat("<option value=\"{1}\">{0}</option>", director.Text, director.Value); } sb.Append("</select>"); return sb.ToString(); } public virtual string BuildActors() { var service = WorkContext.Resolve<IActorService>(); var items = service.GetRecords(x => x.Status == (int)Status.Approved); var result = new List<SelectListItem>(); result.AddRange(items.Select(item => new SelectListItem { Text = item.FullName, Value = item.Id.ToString() })); result.Insert(0, new SelectListItem { Text = "--- Diễn viên ---", Value = "0" }); var actorSelected = GetQueryString(5); var sb = new StringBuilder(); sb.AppendFormat(T("Diễn viên") + " <select id=\"" + Extensions.Constants.ActorId + "\" name=\"" + Extensions.Constants.ActorId + "\" autocomplete=\"off\" class=\"uniform form-control col-md-3\" onchange=\"$('#" + TableName + "').jqGrid().trigger('reloadGrid');\">"); foreach (var actor in result) { if (!string.IsNullOrEmpty(actorSelected) && actor.Value == actorSelected) { sb.AppendFormat("<option selected value=\"{1}\">{0}</option>", actor.Text, actor.Value); continue; } sb.AppendFormat("<option value=\"{1}\">{0}</option>", actor.Text, actor.Value); } sb.Append("</select>"); return sb.ToString(); } public virtual string BuildFilmTypes() { var service = WorkContext.Resolve<IFilmTypesService>(); var items = service.GetRecords(x => x.Status == (int)Status.Approved); var result = new List<SelectListItem>(); result.AddRange(items.Select(item => new SelectListItem { Text = item.Name, Value = item.Id.ToString() })); result.Insert(0, new SelectListItem { Text = "--- Thể loại phim ---", Value = "0" }); var filmTypesSelected = GetQueryString(6); var sb = new StringBuilder(); sb.AppendFormat(T("Thể loại phim") + " <select id=\"" + Extensions.Constants.FilmTypesId + "\" name=\"" + Extensions.Constants.FilmTypesId + "\" autocomplete=\"off\" class=\"uniform form-control col-md-3\" onchange=\"$('#" + TableName + "').jqGrid().trigger('reloadGrid');\">"); foreach (var item in result) { if (!string.IsNullOrEmpty(filmTypesSelected) && item.Value == filmTypesSelected) { sb.AppendFormat("<option selected value=\"{1}\">{0}</option>", item.Text, item.Value); continue; } sb.AppendFormat("<option value=\"{1}\">{0}</option>", item.Text, item.Value); } sb.Append("</select>"); return sb.ToString(); } public virtual string BuildFilmGroups() { var items = EnumExtensions.GetListItems<FilmGroup>(); items.Insert(0, new SelectListItem { Text = "--- Nhóm phim ---", Value = "0" }); var filmGroupSelected = GetQueryString(7); var sb = new StringBuilder(); sb.AppendFormat(T("Nhóm phim") + " <select id=\"" + Extensions.Constants.FilmGroup + "\" name=\"" + Extensions.Constants.FilmGroup + "\" autocomplete=\"off\" class=\"uniform form-control col-md-3\" onchange=\"$('#" + TableName + "').jqGrid().trigger('reloadGrid');\">"); foreach (var group in items) { if (!string.IsNullOrEmpty(filmGroupSelected) && group.Value == filmGroupSelected) { sb.AppendFormat("<option selected value=\"{1}\">{0}</option>", group.Text, group.Value); continue; } sb.AppendFormat("<option value=\"{1}\">{0}</option>", group.Text, group.Value); } sb.Append("</select>"); return sb.ToString(); } public virtual IEnumerable<SelectListItem> BindStatus() { var items = EnumExtensions.GetListItems<Status>(); items[0].Selected = true; return items; } public virtual IEnumerable<SelectListItem> BindSex() { var items = EnumExtensions.GetListItems<Sex>(); items[0].Selected = true; return items; } public virtual IEnumerable<SelectListItem> BindCities() { var cityService = WorkContext.Resolve<ICityService>(); var items = cityService.GetRecords(x => x.Status == (int)Status.Approved).ToList(); var result = new List<SelectListItem>(); result.AddRange(items.Select(item => new SelectListItem { Text = item.Name, Value = item.Id.ToString() })); result.Insert(0, new SelectListItem { Text = "--- Chọn Quận huyện/Thành phố ---", Value = "0" }); return result; } [Url("admin/video-files/get-root-folders")] public virtual ActionResult GetRootFolders() { var serverId = 0; if (Utilities.IsNotNull(Request.Form[Extensions.Constants.ServerId])) { serverId = Convert.ToInt32(Request.Form[Extensions.Constants.ServerId]); } var service = WorkContext.Resolve<IFilmServersService>(); var items = service.GetRecords(x => x.Id == serverId); var result = new List<SelectListItem>(); result.AddRange(items.Select(item => new SelectListItem { Text = item.FolderRoot, Value = item.FolderRoot })); result.Insert(0, new SelectListItem { Text = "--- Tất cả ---", Value = Extensions.Constants.ValueAll }); return Json(result); } [Url("admin/get-sites-by-language")] public ActionResult GetSitesByLanguage() { var languageCode = WorkContext.CurrentCulture; if (Utilities.IsNotNull(Request.Form[Extensions.Constants.LanguageCode])) { languageCode = Request.Form[Extensions.Constants.LanguageCode]; } var service = WorkContext.Resolve<ISiteService>(); var items = service.GetRecords(x => x.LanguageCode == languageCode); var result = new List<SelectListItem>(); result.AddRange(items.Select(item => new SelectListItem { Text = item.Name, Value = item.Id.ToString() })); result.Insert(0, new SelectListItem { Text = "--- Chọn trang web ---", Value = "0" }); return Json(result); } [Url("admin/category/get-servers-by-site")] public ActionResult GetServersBySite() { var languageCode = WorkContext.CurrentCulture; if (Utilities.IsNotNull(Request.Form[Extensions.Constants.LanguageCode])) { languageCode = Request.Form[Extensions.Constants.LanguageCode]; } var siteId = 0; if (Utilities.IsNotNull(Request.Form[Extensions.Constants.SiteId])) { siteId = Convert.ToInt32(Request.Form[Extensions.Constants.SiteId]); } var service = WorkContext.Resolve<IFilmServersService>(); var items = service.GetRecords(x => x.LanguageCode == languageCode && x.SiteId == siteId); var result = new List<SelectListItem>(); result.AddRange(items.Select(item => new SelectListItem { Text = item.ServerName, Value = item.Id.ToString() })); result.Insert(0, new SelectListItem { Text = T("--- Chọn máy chủ ---"), Value = "0" }); return Json(result); } [Url("admin/vast/get-ads-by-site")] public ActionResult GetAdsBySite() { var languageCode = WorkContext.CurrentCulture; if (Utilities.IsNotNull(Request.Form[Extensions.Constants.LanguageCode])) { languageCode = Request.Form[Extensions.Constants.LanguageCode]; } var siteId = 0; if (Utilities.IsNotNull(Request.Form[Extensions.Constants.SiteId])) { siteId = Convert.ToInt32(Request.Form[Extensions.Constants.SiteId]); } var service = WorkContext.Resolve<IAdvertisementService>(); var items = service.GetRecords(x => x.LanguageCode == languageCode && x.SiteId == siteId); var result = new List<SelectListItem>(); result.AddRange(items.Select(item => new SelectListItem { Text = item.Title, Value = item.Id.ToString() })); result.Insert(0, new SelectListItem { Text = T("--- Chọn quảng cáo ---"), Value = "0" }); return Json(result); } [Url("admin/category/get-categories-by-site")] public ActionResult GetCategoriesBySite() { var languageCode = WorkContext.CurrentCulture; if (Utilities.IsNotNull(Request.Form[Extensions.Constants.LanguageCode])) { languageCode = Request.Form[Extensions.Constants.LanguageCode]; } var siteId = 0; if (Utilities.IsNotNull(Request.Form[Extensions.Constants.SiteId])) { siteId = Convert.ToInt32(Request.Form[Extensions.Constants.SiteId]); } var service = WorkContext.Resolve<ICategoryService>(); service.LanguageCode = languageCode; service.SiteId = siteId; var items = service.GetTree(); var result = new List<SelectListItem>(); result.AddRange(items.Select(item => new SelectListItem { Text = item.ChildenName, Value = item.Id.ToString() })); result.Insert(0, new SelectListItem { Text = T("--- Không chọn ---"), Value = "0" }); return Json(result); } [Url("admin/reset-cache")] public ActionResult ResetCache() { var serviceLanguage = WorkContext.Resolve<ILanguageService>(); var items = serviceLanguage.GetRecords(x => x.Theme == Constants.ThemeDefault); if (items != null && items.Count > 0) { var categoryService = WorkContext.Resolve<ICategoryService>(); foreach (var language in items) { try { categoryService.LanguageCode = language.CultureCode; categoryService.SiteId = 1; categoryService.ResetCache(); } catch (Exception) { continue; } } foreach (var language in items) { try { categoryService.LanguageCode = language.CultureCode; categoryService.SiteId = 2; categoryService.ResetCache(); } catch (Exception) { continue; } } } #region Film try { var serviceFilms = WorkContext.Resolve<IFilmService>(); serviceFilms.LanguageCode = WorkContext.CurrentCulture; serviceFilms.SiteId = (int)Site.Home; serviceFilms.ResetCache(); serviceFilms.RefreshFilmJJChannelIntroduce(0); serviceFilms.RefreshTVShows(0); serviceFilms.RefreshClips(5); serviceFilms.RefreshStatistical1(30, 1); serviceFilms.RefreshStatistical1(30, 2); serviceFilms.RefreshStatistical1(30, 3); serviceFilms.RefreshStatistical2(30, 1); serviceFilms.RefreshStatistical2(30, 2); serviceFilms.RefreshStatistical2(30, 3); serviceFilms.RefreshStatistical3(30, 1); serviceFilms.RefreshStatistical3(30, 2); serviceFilms.RefreshStatistical3(30, 3); serviceFilms.RefreshStatistical4(30, 1); serviceFilms.RefreshStatistical4(30, 2); serviceFilms.RefreshStatistical4(30, 3); serviceFilms.RefreshStatistical5(30, 1); } catch (Exception) { } #endregion #region Articles try { var serviceArticles = WorkContext.Resolve<IArticlesService>(); serviceArticles.LanguageCode = WorkContext.CurrentCulture; serviceArticles.SiteId = 1; serviceArticles.CategoryId = 0; serviceArticles.ResetCache(); serviceArticles.CategoryId = 60; serviceArticles.ResetCache(); serviceArticles.CategoryId = 61; serviceArticles.ResetCache(); serviceArticles.CategoryId = 62; serviceArticles.ResetCache(); } catch (Exception) { } #endregion #region Search try { var service = WorkContext.Resolve<ISearchService>(); service.SearchRestore(1); service.SiteId = (int)Site.Home; service.ResetCache(); } catch (Exception) { } #endregion #region Slider var sliderService = WorkContext.Resolve<ISliderService>(); sliderService.LanguageCode = WorkContext.CurrentCulture; sliderService.SiteId = (int) Site.Home; var list = EnumExtensions.GetListItems<SliderPages>(); foreach (var page in list) { try { sliderService.RefreshByPage(int.Parse(page.Value)); } catch (Exception) { } } #endregion #region Customers var customerService = WorkContext.Resolve<ICustomerService>(); customerService.ResetCacheCustomers(); #endregion return Redirect(Url.Action("Index", "Admin")); } } }<file_sep>using System; using System.ComponentModel; using System.ComponentModel.DataAnnotations.Schema; using System.Runtime.Serialization; using CMSSolutions.Data; namespace CMSSolutions.Websites.Entities { [DataContract] public class DownloadCustomerInfo : BaseEntity<long> { [DataMember] [DisplayName("DownloadId")] public int DownloadId { get; set; } [DataMember] [DisplayName("CustomerId")] public int CustomerId { get; set; } [DataMember] [DisplayName("StartDate")] public DateTime? StartDate { get; set; } [NotMapped] [DisplayName(Constants.NotMapped)] public string TextStartDate { get { if (StartDate == null) { return ""; } return StartDate.Value.ToString(Extensions.Constants.DateTimeFomatFull); } } [DataMember] [DisplayName("EndDate")] public DateTime? EndDate { get; set; } [NotMapped] [DisplayName(Constants.NotMapped)] public string TextEndDate { get { if (EndDate == null) { return ""; } return EndDate.Value.ToString(Extensions.Constants.DateTimeFomatFull); } } [DataMember] [DisplayName("VipXu")] public int VipXu { get; set; } [DataMember] [DisplayName("Day")] public int Day { get; set; } } }<file_sep>using System.ComponentModel; using System.Runtime.Serialization; using CMSSolutions.Data; using CMSSolutions.Data.Entity; namespace CMSSolutions.Websites.Entities { [DataContract] public class SiteInfo : BaseEntity<int> { [DataMember] [DisplayName("Name")] public string Name { get; set; } [DataMember] [DisplayName("LanguageCode")] public string LanguageCode { get; set; } [DataMember] [DisplayName("Url")] public string Url { get; set; } [DataMember] [DisplayName("Domain")] public string Domain { get; set; } [DataMember] [DisplayName("IsActived")] public bool IsActived { get; set; } [DataMember] [DisplayName("Description")] public string Description { get; set; } } public class SiteMap : EntityTypeConfiguration<SiteInfo>, IEntityTypeConfiguration { public SiteMap() { ToTable("Modules_Sites"); HasKey(x => x.Id); Property(x => x.LanguageCode).HasMaxLength(50).IsRequired(); Property(x => x.Name).IsRequired().HasMaxLength(250); Property(x => x.Url).HasMaxLength(250); Property(x => x.Domain).HasMaxLength(50); Property(x => x.IsActived).IsRequired(); Property(x => x.Description).HasMaxLength(2000); } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Web.Mvc; using CMSSolutions.ContentManagement.Widgets.Services; using CMSSolutions.DisplayManagement; using CMSSolutions.Extensions; using CMSSolutions.Web.Mvc; using CMSSolutions.Web.Themes; using CMSSolutions.Websites.Entities; using CMSSolutions.Websites.Extensions; using CMSSolutions.Websites.Models; using CMSSolutions.Websites.Services; namespace CMSSolutions.Websites.Controllers { [Themed(IsDashboard = false)] public class HomeCategoryController : BaseHomeController { private readonly dynamic shapeFactory; public HomeCategoryController( IWorkContextAccessor workContextAccessor, IShapeFactory shapeFactory) : base(workContextAccessor) { this.shapeFactory = shapeFactory; PageIndex = 1; } [HttpGet] [Url("{alias}/c{id}.html")] public ActionResult Index(string alias, int id) { UrlLogin = Request.Url != null ? Request.Url.AbsoluteUri : Url.Action("Index", "Home"); SiteId = (int)Site.Home; var serviceCategory = WorkContext.Resolve<ICategoryService>(); serviceCategory.LanguageCode = WorkContext.CurrentCulture; serviceCategory.SiteId = SiteId; var category = serviceCategory.GetByIdCache(id); ViewData[Extensions.Constants.HeaderTitle] = category.Name; ViewData[Extensions.Constants.HeaderDescription] = category.Description; ViewData[Extensions.Constants.HeaderKeywords] = category.Tags; if (Request.QueryString["trang"] != null) { PageIndex = int.Parse(Request.QueryString["trang"]); } PageSize = 40; BuildModulesCategory(category); return View(); } [HttpGet] [Url("su-kien/phim-dang-hot.html")] public ActionResult FilmHot() { UrlLogin = Request.Url != null ? Request.Url.AbsoluteUri : Url.Action("Index", "Home"); SiteId = (int)Site.Home; var serviceCategory = WorkContext.Resolve<ICategoryService>(); serviceCategory.LanguageCode = WorkContext.CurrentCulture; serviceCategory.SiteId = (int)Site.Home; var category = serviceCategory.GetByIdCache((int)FixCategories.FilmHot); ViewData[Extensions.Constants.HeaderTitle] = category.Name; ViewData[Extensions.Constants.HeaderDescription] = category.Description; ViewData[Extensions.Constants.HeaderKeywords] = category.Tags; if (Request.QueryString["trang"] != null) { PageIndex = int.Parse(Request.QueryString["trang"]); } PageSize = 16; BuildModules(); return View("FilmHot"); } private string BuildBreadcrumb(CategoryInfo category) { var serviceCategory = WorkContext.Resolve<ICategoryService>(); serviceCategory.LanguageCode = WorkContext.CurrentCulture; serviceCategory.SiteId = (int)Site.Home; var html = new StringBuilder(); html.Append("<div class=\"mh-breadcrumb-dv\">"); html.Append("<div>"); html.AppendFormat("<a title=\"{0}\" href=\"{1}\"><span><img width=\"22\" src=\"/Images/themes/ico-home_trans.png\"></span></a>", "Dành cho víp", "/"); html.Append("</div>/ "); if (category.ParentId > 0) { var parent = serviceCategory.GetByIdCache(category.ParentId); html.Append("<div>"); html.AppendFormat("<a title=\"{0}\" href=\"{1}\"><span>{0}</span></a>", parent.ShortName, Url.Action("Index", "HomeCategory", new { @alias = parent.Alias, @id = parent.Id })); html.Append("</div>/ "); } html.Append("<div>"); html.AppendFormat("<a title=\"{0}\" href=\"{1}\"><span>{0}</span></a>", category.ShortName, "#"); html.Append("</div>"); html.Append("</div>"); return html.ToString(); } private void BuildModulesCategory(CategoryInfo category) { var widget = WorkContext.Resolve<IWidgetService>(); var viewRenderer = new ViewRenderer { Context = ControllerContext }; if (!IsVip) { #region BannerPageLeft var bannerPageLeft = widget.GetWidget(HomeWidgets.BannerPageLeft.ToString()); if (bannerPageLeft != null) { var widgetShape = shapeFactory.Widget(); widgetShape.Widget = bannerPageLeft; WorkContext.Layout.AdBannerPageLeft(widgetShape); } #endregion #region BannerPageCenter var bannerPageCenter = widget.GetWidget(HomeWidgets.BannerPageCenter.ToString()); if (bannerPageCenter != null) { var widgetShape = shapeFactory.Widget(); widgetShape.Widget = bannerPageCenter; WorkContext.Layout.AdBannerPageCenter(widgetShape); } #endregion #region BannerPageRight var bannerPageRight = widget.GetWidget(HomeWidgets.BannerPageRight.ToString()); if (bannerPageRight != null) { var widgetShape = shapeFactory.Widget(); widgetShape.Widget = bannerPageRight; WorkContext.Layout.AdBannerPageRight(widgetShape); } #endregion #region BannerContentLeftSeventh var bannerContentLeftSeventh = widget.GetWidget(HomeWidgets.BannerContentLeftSeventh.ToString()); if (bannerContentLeftSeventh != null) { var widgetShape = shapeFactory.Widget(); widgetShape.Widget = bannerContentLeftSeventh; WorkContext.Layout.AdBannerContentLeftSeventh(widgetShape); } #endregion #region BannerRightFirst var bannerRightFirst = widget.GetWidget(HomeWidgets.BannerRightFirst.ToString()); if (bannerRightFirst != null) { var widgetShape = shapeFactory.Widget(); widgetShape.Widget = bannerRightFirst; WorkContext.Layout.AdBannerRightFirst(widgetShape); } #endregion #region BannerRightSecond var bannerRightSecond = widget.GetWidget(HomeWidgets.BannerRightSecond.ToString()); if (bannerRightSecond != null) { var widgetShape = shapeFactory.Widget(); widgetShape.Widget = bannerRightSecond; WorkContext.Layout.AdBannerRightSecond(widgetShape); } #endregion #region BannerRightThird var bannerRightThird = widget.GetWidget(HomeWidgets.BannerRightThird.ToString()); if (bannerRightThird != null) { var widgetShape = shapeFactory.Widget(); widgetShape.Widget = bannerRightThird; WorkContext.Layout.AdBannerRightThird(widgetShape); } #endregion #region BannerRightFourth var bannerRightFourth = widget.GetWidget(HomeWidgets.BannerRightFourth.ToString()); if (bannerRightFourth != null) { var widgetShape = shapeFactory.Widget(); widgetShape.Widget = bannerRightFourth; WorkContext.Layout.AdBannerRightFourth(widgetShape); } #endregion } else { #region BannerPageLeftVip var bannerPageLeftVip = widget.GetWidget(HomeWidgets.BannerPageLeftVip.ToString()); if (bannerPageLeftVip != null) { var widgetShape = shapeFactory.Widget(); widgetShape.Widget = bannerPageLeftVip; WorkContext.Layout.AdBannerPageLeftVip(widgetShape); } #endregion #region BannerPageCenterVip var bannerPageCenterVip = widget.GetWidget(HomeWidgets.BannerPageCenterVip.ToString()); if (bannerPageCenterVip != null) { var widgetShape = shapeFactory.Widget(); widgetShape.Widget = bannerPageCenterVip; WorkContext.Layout.AdBannerPageCenterVip(widgetShape); } #endregion #region BannerPageRightVip var bannerPageRightVip = widget.GetWidget(HomeWidgets.BannerPageRightVip.ToString()); if (bannerPageRightVip != null) { var widgetShape = shapeFactory.Widget(); widgetShape.Widget = bannerPageRightVip; WorkContext.Layout.AdBannerPageRightVip(widgetShape); } #endregion } #region HomeSliderBanner if (category.Id == 2 || category.ParentId == 2) { var modelSlider = new DataViewerModel { Data = BuildSlider(SiteId, (int)SliderPages.CatetegoryPhimLe) }; var viewSlider = viewRenderer.RenderPartialView(Extensions.Constants.SliderBannerFilePath, modelSlider); WorkContext.Layout.SliderBanner.Add(new MvcHtmlString(viewSlider)); } if (category.Id == 3 || category.ParentId == 3) { var modelSlider = new DataViewerModel { Data = BuildSlider(SiteId, (int)SliderPages.CatetegoryPhimBo) }; var viewSlider = viewRenderer.RenderPartialView(Extensions.Constants.SliderBannerFilePath, modelSlider); WorkContext.Layout.SliderBanner.Add(new MvcHtmlString(viewSlider)); } var viewRegisterResource = viewRenderer.RenderPartialView(Extensions.Constants.RegisterResourceFilePath, null); WorkContext.Layout.RegisterResource.Add(new MvcHtmlString(viewRegisterResource)); #endregion #region HomeFooterLogoInformation var homeFooterLogoInformation = widget.GetWidget(HomeWidgets.HomeFooterLogoInformation.ToString()); if (homeFooterLogoInformation != null) { var widgetShape = shapeFactory.Widget(); widgetShape.Widget = homeFooterLogoInformation; WorkContext.Layout.FooterLogoInformation(widgetShape); } #endregion var type = 0; if (category.Id == (int)FixCategories.FilmLe || category.ParentId == (int)FixCategories.FilmLe) { type = 1; #region DisplayStatistic1 var modelStatistic1 = new DataViewCategoryModel { Type = (int)HomeDisplayFilmType.StatisticalFilmRetail, Title = "PHIM LẺ XEM NHIỀU NHẤT" }; var viewStatistic1 = viewRenderer.RenderPartialView(Extensions.Constants.Statistic1FilePath, modelStatistic1); WorkContext.Layout.DisplayStatistic1.Add(new MvcHtmlString(viewStatistic1)); #endregion } if (category.Id == (int)FixCategories.FilmBo || category.ParentId == (int)FixCategories.FilmBo) { type = 2; #region DisplayStatistic2 var modelStatistic2 = new DataViewCategoryModel { Type = (int)HomeDisplayFilmType.StatisticalLengthEpisodes, Title = "PHIM BỘ XEM NHIỀU NHẤT" }; var viewStatistic2 = viewRenderer.RenderPartialView(Extensions.Constants.Statistic2FilePath, modelStatistic2); WorkContext.Layout.DisplayStatistic2.Add(new MvcHtmlString(viewStatistic2)); #endregion } #region SocialNetwork var socialNetwork = widget.GetWidget(HomeWidgets.DisplaySocialNetwork.ToString()); if (socialNetwork != null) { var widgetShape = shapeFactory.Widget(); widgetShape.Widget = socialNetwork; WorkContext.Layout.DisplaySocialNetwork(widgetShape); } #endregion #region Tags var serviceTags = WorkContext.Resolve<ITagService>(); var modelTags = new TagViewModel { ListTags = serviceTags.GetDisplayTags() }; var viewTags = viewRenderer.RenderPartialView(Extensions.Constants.TagViewFilePath, modelTags); WorkContext.Layout.DisplayTags.Add(new MvcHtmlString(viewTags)); #endregion #region CategoryContentFirst var modelFirst = new DataViewCategoryModel(); var countryService = WorkContext.Resolve<ICountryService>(); var filmTypesService = WorkContext.Resolve<IFilmTypesService>(); modelFirst.Breadcrumb = BuildBreadcrumb(category); modelFirst.ListCountries = countryService.GetRecords().ToList(); modelFirst.ListFilmTypes = filmTypesService.GetByType(WorkContext.CurrentCulture, SiteId, 1).ToList(); modelFirst.SearchOrderBy = EnumExtensions.GetListItems<SearchOrderBy>(); modelFirst.SelectedFilmTypes = 0; if (Request.QueryString["theloaiphim"] != null) { modelFirst.SelectedFilmTypes = int.Parse(Request.QueryString["theloaiphim"]); } modelFirst.SelectedCountry = 0; if (Request.QueryString["quocgia"] != null) { modelFirst.SelectedCountry = int.Parse(Request.QueryString["quocgia"]); } modelFirst.SelectedOrderBy = "0"; if (Request.QueryString["sortOrder"] != null) { modelFirst.SelectedOrderBy = Request.QueryString["sortOrder"]; } modelFirst.SelectedSortBy = (int) SearchSortBy.DESC; if (Request.QueryString["sortBy"] != null) { modelFirst.SelectedSortBy = int.Parse(Request.QueryString["sortBy"]); } modelFirst.SliderName = "DataListView"; modelFirst.CurrentCategory = category; modelFirst.PageIndex = PageIndex; modelFirst.PageSize = PageSize; var service = WorkContext.Resolve<IFilmService>(); service.SiteId = SiteId; service.LanguageCode = WorkContext.CurrentCulture; var totalRow = 0; var listFilmCategory = service.GetByCategoryId( SiteId, WorkContext.CurrentCulture, category.ParentId > 0 ? category.Id : 0, category.ParentId == 0 ? category.Id : 0, modelFirst.SelectedFilmTypes, modelFirst.SelectedCountry, type, int.Parse(modelFirst.SelectedOrderBy), modelFirst.SelectedSortBy, modelFirst.PageIndex, modelFirst.PageSize, out totalRow); modelFirst.TotalRow = totalRow; modelFirst.ListFilms = listFilmCategory; modelFirst.Type = type; var viewFilmFirst = viewRenderer.RenderPartialView(Extensions.Constants.CategoryListViewViewFilePath, modelFirst); WorkContext.Layout.CategoryContentLeftFirst.Add(new MvcHtmlString(viewFilmFirst)); #endregion } public override void BuildModules() { var widget = WorkContext.Resolve<IWidgetService>(); var viewRenderer = new ViewRenderer { Context = ControllerContext }; if (!IsVip) { } else { #region BannerPageLeftVip var bannerPageLeftVip = widget.GetWidget(HomeWidgets.BannerPageLeftVip.ToString()); if (bannerPageLeftVip != null) { var widgetShape = shapeFactory.Widget(); widgetShape.Widget = bannerPageLeftVip; WorkContext.Layout.AdBannerPageLeftVip(widgetShape); } #endregion #region BannerPageCenterVip var bannerPageCenterVip = widget.GetWidget(HomeWidgets.BannerPageCenterVip.ToString()); if (bannerPageCenterVip != null) { var widgetShape = shapeFactory.Widget(); widgetShape.Widget = bannerPageCenterVip; WorkContext.Layout.AdBannerPageCenterVip(widgetShape); } #endregion #region BannerPageRightVip var bannerPageRightVip = widget.GetWidget(HomeWidgets.BannerPageRightVip.ToString()); if (bannerPageRightVip != null) { var widgetShape = shapeFactory.Widget(); widgetShape.Widget = bannerPageRightVip; WorkContext.Layout.AdBannerPageRightVip(widgetShape); } #endregion } #region HomeSliderBanner var modelSlider = new DataViewerModel { Data = BuildSlider(SiteId, (int)SliderPages.FilmHot) }; var viewSlider = viewRenderer.RenderPartialView(Extensions.Constants.SliderBannerFilePath, modelSlider); WorkContext.Layout.SliderBanner.Add(new MvcHtmlString(viewSlider)); var viewRegisterResource = viewRenderer.RenderPartialView(Extensions.Constants.RegisterResourceFilePath, null); WorkContext.Layout.RegisterResource.Add(new MvcHtmlString(viewRegisterResource)); #endregion #region HomeFooterLogoInformation var homeFooterLogoInformation = widget.GetWidget(HomeWidgets.HomeFooterLogoInformation.ToString()); if (homeFooterLogoInformation != null) { var widgetShape = shapeFactory.Widget(); widgetShape.Widget = homeFooterLogoInformation; WorkContext.Layout.FooterLogoInformation(widgetShape); } #endregion #region CategoryContentFirst var modelFirst = new DataViewCategoryModel { HtmlData = "", Title = "Phim Đang HOT", UrlNext = "javascript: void(0);", SliderName = "FilmHot", PageIndex = PageIndex, PageSize = PageSize }; var data = BuilHtml(modelFirst); var viewFilmFirst = viewRenderer.RenderPartialView(Extensions.Constants.HomeFilmHotViewFilePath, modelFirst); WorkContext.Layout.CategoryContentLeftFirst.Add(new MvcHtmlString(viewFilmFirst)); #endregion #region HomeFacebookFanpage var modelSliderOne = new DataViewCategoryModel(); modelSliderOne.Data = data == null ? "[]" : Utilities.ConvertObjectToJson(data.Select(x => x.Id).ToList()); var viewSliderOne = viewRenderer.RenderPartialView(Extensions.Constants.SliderOneViewFilePath, modelSliderOne); WorkContext.Layout.AdFacebookFanpage.Add(new MvcHtmlString(viewSliderOne)); #endregion #region SocialNetwork var socialNetwork = widget.GetWidget(HomeWidgets.DisplaySocialNetwork.ToString()); if (socialNetwork != null) { var widgetShape = shapeFactory.Widget(); widgetShape.Widget = socialNetwork; WorkContext.Layout.DisplaySocialNetwork(widgetShape); } #endregion } private IEnumerable<FilmInfo> BuilHtml(DataViewCategoryModel model) { var service = WorkContext.Resolve<IFilmService>(); service.SiteId = SiteId; service.LanguageCode = WorkContext.CurrentCulture; var totalRow = 0; var listFilmHot = service.GetFilmHot(model.PageIndex, model.PageSize, out totalRow); model.TotalRow = totalRow; var html = new StringBuilder(); if (listFilmHot != null && listFilmHot.Count > 0) { html.Append("<div>"); html.Append("<ul class=\"first-and-second-carousel jcarousel-skin-tango fix-margin-li\" id=\"first-carousel\">"); html.Append("<li>"); for (int i = 0; i < listFilmHot.Count; i++) { html.Append(BuildItem(listFilmHot[i], i, true)); } html.Append("</li>"); html.Append("</ul>"); html.Append("</div>"); } model.HtmlData = html.ToString(); return listFilmHot != null ? listFilmHot.ToList(): null; } } } <file_sep>using System.Collections.Generic; using System.Data.SqlClient; using CMSSolutions.Data; using CMSSolutions.Events; using CMSSolutions.Services; using CMSSolutions.Websites.Entities; namespace CMSSolutions.Websites.Services { public interface IFilmTypesService : IGenericService<FilmTypesInfo, int>, IDependency { IList<FilmTypesInfo> GetPaged(string languageCode, int siteId, int status, int pageIndex, int pageSize, out int totals); IList<FilmTypesInfo> GetByType(string languageCode, int siteId, int type); } public class FilmTypesService : GenericService<FilmTypesInfo, int>, IFilmTypesService { public FilmTypesService(IRepository<FilmTypesInfo, int> repository, IEventBus eventBus) : base(repository, eventBus) { } public IList<FilmTypesInfo> GetPaged(string languageCode, int siteId, int status, int pageIndex, int pageSize, out int totals) { var list = new List<SqlParameter> { AddInputParameter("@SiteId", siteId), AddInputParameter("@LanguageCode", languageCode), AddInputParameter("@Status", status), AddInputParameter("@PageIndex", pageIndex), AddInputParameter("@PageSize", pageSize) }; return ExecuteReader<FilmTypesInfo>("sp_FilmTypes_Search_Paged", "@TotalRecord", out totals, list.ToArray()); } public IList<FilmTypesInfo> GetByType(string languageCode, int siteId, int type) { var list = new List<SqlParameter> { AddInputParameter("@SiteId", siteId), AddInputParameter("@LanguageCode", languageCode), AddInputParameter("@Type", type) }; return ExecuteReader<FilmTypesInfo>("sp_FilmTypes_GetByType", list.ToArray()); } } } <file_sep>using System.Web.Mvc; using CMSSolutions.Web.Mvc; using CMSSolutions.Web.Routing; using CMSSolutions.Web.Themes; using CMSSolutions.Web.UI.ControlForms; using CMSSolutions.Web.UI.Navigation; using CMSSolutions.Websites.Entities; using CMSSolutions.Websites.Extensions; using CMSSolutions.Websites.Models; using CMSSolutions.Websites.Services; namespace CMSSolutions.Websites.Controllers { [Themed(IsDashboard = true), Authorize] public class AdminCountryController : BaseAdminController { public AdminCountryController(IWorkContextAccessor workContextAccessor) : base(workContextAccessor) { TableName = "tblCountries"; } [Url("admin/country")] public ActionResult Index() { WorkContext.Breadcrumbs.Add(new Breadcrumb { Text = T("Quản lý nước sản xuất phim"), Url = "#" }); var result = new ControlGridFormResult<CountryInfo> { Title = T("Quản lý nước sản xuất phim"), CssClass = "table table-bordered table-striped", IsAjaxSupported = true, FetchAjaxSource = GetCountries, DefaultPageSize = WorkContext.DefaultPageSize, EnablePaginate = true, UpdateActionName = "Update", GridWrapperStartHtml = Constants.Grid.GridWrapperStartHtml, GridWrapperEndHtml = Constants.Grid.GridWrapperEndHtml, ClientId = TableName, ActionsColumnWidth = 100 }; result.AddCustomVar(Extensions.Constants.SearchText, "$('#" + Extensions.Constants.SearchText + "').val();", true); result.AddColumn(x => x.Id, T("ID")).AlignCenter().HasWidth(60); result.AddColumn(x => x.Code, T("Mã nước")); result.AddColumn(x => x.Name, T("Tên nước")); result.AddAction().HasText(T("Thêm mới")) .HasUrl(Url.Action("Edit", RouteData.Values.Merge(new { id = 0 }))) .HasButtonStyle(ButtonStyle.Primary) .HasBoxButton(false) .HasCssClass(Constants.RowLeft) .HasRow(true) .ShowModalDialog(); result.AddAction(new ControlFormHtmlAction(BuildSearchText)).HasParentClass(Constants.ContainerCssClassCol3); result.AddRowAction() .HasText(T("Sửa")) .HasUrl(x => Url.Action("Edit", RouteData.Values.Merge(new { id = x.Id }))) .HasButtonStyle(ButtonStyle.Default) .HasButtonSize(ButtonSize.ExtraSmall) .ShowModalDialog(); //result.AddRowAction(true) // .HasText(T("Xóa")) // .HasName("Delete") // .HasValue(x => x.Id) // .HasButtonStyle(ButtonStyle.Danger) // .HasButtonSize(ButtonSize.ExtraSmall) // .HasConfirmMessage(T(Constants.Messages.ConfirmDeleteRecord).Text); result.AddReloadEvent("UPDATE_ENTITY_COMPLETE"); //result.AddReloadEvent("DELETE_ENTITY_COMPLETE"); return result; } private ControlGridAjaxData<CountryInfo> GetCountries(ControlGridFormRequest options) { var searchText = string.Empty; if (Utilities.IsNotNull(Request.Form[Extensions.Constants.SearchText])) { searchText = Request.Form[Extensions.Constants.SearchText]; } int totals; var items = WorkContext.Resolve<ICountryService>().SearchPaged(searchText, options.PageIndex, options.PageSize, out totals); var result = new ControlGridAjaxData<CountryInfo>(items, totals); return result; } [Themed(false)] [Url("admin/country/edit/{id}")] public ActionResult Edit(int id) { WorkContext.Breadcrumbs.Add(new Breadcrumb { Text = T("Quản lý nước sản xuất phim"), Url = Url.Action("Index") }); WorkContext.Breadcrumbs.Add(new Breadcrumb { Text = T("Thông tin nước sản xuất phim"), Url = "#" }); var service = WorkContext.Resolve<ICountryService>(); var model = new CountryModel(); if (id > 0) { model = service.GetById(id); } var result = new ControlFormResult<CountryModel>(model) { Title = T("Thông tin nước sản xuất phim"), FormMethod = FormMethod.Post, UpdateActionName = "Update", SubmitButtonText = T("Lưu lại"), ShowCancelButton = true, ShowBoxHeader = false, CancelButtonText = T("Đóng"), FormWrapperStartHtml = Constants.Form.FormWrapperStartHtml, FormWrapperEndHtml = Constants.Form.FormWrapperEndHtml }; return result; } [HttpPost, ValidateInput(false), FormButton("Save")] [Url("admin/country/update")] public ActionResult Update(CountryModel model) { if (!ModelState.IsValid) { return new AjaxResult().Alert(T(Constants.Messages.InvalidModel)); } var service = WorkContext.Resolve<ICountryService>(); CountryInfo item = model.Id == 0 ? new CountryInfo() : service.GetById(model.Id); if (service.CheckExist(model.Id, model.Code)) { return new AjaxResult() .NotifyMessage("UPDATE_ENTITY_COMPLETE") .Alert(T("Mã nước sản xuất đã tồn tại!")); } if (service.CheckExist(model.Id, model.Name)) { return new AjaxResult() .NotifyMessage("UPDATE_ENTITY_COMPLETE") .Alert(T("Tên nước sản xuất đã tồn tại!")); } item.Code = model.Code; item.Name = model.Name; service.Save(item); return new AjaxResult() .NotifyMessage("UPDATE_ENTITY_COMPLETE") .Alert(T("Cập nhật thành công!")) .CloseModalDialog(); } [FormButton("Delete")] [HttpPost, ActionName("Update")] public ActionResult Delete(int id) { var service = WorkContext.Resolve<ICountryService>(); var item = service.GetById(id); service.Delete(item); return new AjaxResult().NotifyMessage("DELETE_ENTITY_COMPLETE"); } } } <file_sep>using System.Collections.Generic; using System.Data.SqlClient; using CMSSolutions.Data; using CMSSolutions.Events; using CMSSolutions.Services; using CMSSolutions.Websites.Entities; namespace CMSSolutions.Websites.Services { public interface ISearchService : IGenericService<SearchInfo, long>, IDependency { int SiteId { get; set; } SearchInfo GetBySearchId(string searchId, int type); IList<SearchInfo> Search(List<SearchCondition> conditions, int pageIndex, int pageSize, ref int total); IList<SearchInfo> ResetCache(); void SearchRestore(int type); } public class SearchService : GenericService<SearchInfo, long>, ISearchService { public SearchService(IRepository<SearchInfo, long> repository, IEventBus eventBus) : base(repository, eventBus) { } public IList<SearchInfo> Search(List<SearchCondition> conditions, int pageIndex, int pageSize, ref int total) { var service = new LuceneService(); return service.Search(conditions, true, pageIndex, pageSize, ref total); } public int SiteId { get; set; } public SearchInfo GetBySearchId(string searchId, int type) { var list = new List<SqlParameter> { AddInputParameter("@SearchId", searchId), AddInputParameter("@Type", type) }; return ExecuteReaderRecord<SearchInfo>("sp_Search_GetDetails", list.ToArray()); } public void SearchRestore(int type) { var list = new List<SqlParameter> { AddInputParameter("@Type", type) }; ExecuteNonQuery("sp_AutoSearh", list.ToArray()); } public IList<SearchInfo> ResetCache() { var list = new List<SqlParameter> { AddInputParameter("@SiteId", SiteId) }; var data = ExecuteReader("sp_Search_BuildJson", list.ToArray()); var service = new LuceneService {SiteId = SiteId}; service.AddUpdateLuceneIndex(data.Tables[0]); return null; } } } <file_sep>using System; using CMSSolutions.Web.UI.ControlForms; using CMSSolutions.Websites.Entities; namespace CMSSolutions.Websites.Models { public class VastModel { public VastModel() { KeyCode = Guid.NewGuid().ToString().Replace("-", string.Empty); AdSystemVersion = "3.0"; Skipoffset = "00:00:05"; Duration = "00:00:30.03"; MediaFileBitrate = 660; MediaFileDelivery = "progressive"; MediaFileHeight = 480; MediaFileWidth = 854; MediaFileMaintainAspectRatio = true; MediaFileScalable = true; MediaFileType = "video/mp4"; } [ControlHidden] public int Id { get; set; } [ControlChoice(ControlChoice.DropDownList, Required = true, LabelText = "Ngôn ngữ hiển thị", ContainerCssClass = Constants.ContainerCssClassCol4, ContainerRowIndex = 0, OnSelectedIndexChanged = "$('#" + Extensions.Constants.AdId + "').empty();")] public string LanguageCode { get; set; } [ControlCascadingDropDown(LabelText = "Trang web", ParentControl = "LanguageCode", AbsoluteParentControl = true, ContainerCssClass = Constants.ContainerCssClassCol4, ContainerRowIndex = 0)] public int SiteId { get; set; } [ControlCascadingDropDown(LabelText = "Quảng cáo", ParentControl = "SiteId", AbsoluteParentControl = true, ContainerCssClass = Constants.ContainerCssClassCol4, ContainerRowIndex = 0)] public int AdId { get; set; } [ControlText(Type = ControlText.TextBox, ReadOnly = true, LabelText = "Mã Vast", Required = true, MaxLength = 50, ContainerCssClass = Constants.ContainerCssClassCol3, ContainerRowIndex = 1)] public string KeyCode { get; set; } [ControlText(Type = ControlText.TextBox, LabelText = "Version", Required = true, MaxLength = 250, ContainerCssClass = Constants.ContainerCssClassCol3, ContainerRowIndex = 1)] public string AdSystemVersion { get; set; } [ControlText(Type = ControlText.TextBox, LabelText = "Thời gian bỏ qua", Required = true, MaxLength = 50, ContainerCssClass = Constants.ContainerCssClassCol3, ContainerRowIndex = 1)] public string Skipoffset { get; set; } [ControlText(Type = ControlText.TextBox, LabelText = "Thời gian chạy", Required = true, MaxLength = 50, ContainerCssClass = Constants.ContainerCssClassCol3, ContainerRowIndex = 1)] public string Duration { get; set; } [ControlText(Type = ControlText.TextBox, LabelText = "Tiêu đề", Required = true, MaxLength = 250, ContainerCssClass = Constants.ContainerCssClassCol6, ContainerRowIndex = 2)] public string AdSystemValue { get; set; } [ControlText(Type = ControlText.TextBox, LabelText = "Mô tả", Required = true, MaxLength = 250, ContainerCssClass = Constants.ContainerCssClassCol6, ContainerRowIndex = 2)] public string AdTitle { get; set; } [ControlText(Type = ControlText.TextBox, LabelText = "Đường dẫn lỗi", MaxLength = 500, ContainerCssClass = Constants.ContainerCssClassCol12, ContainerRowIndex = 3)] public string LinkError { get; set; } [ControlText(Type = ControlText.TextBox, LabelText = "Đường dẫn impression", MaxLength = 500, ContainerCssClass = Constants.ContainerCssClassCol12, ContainerRowIndex = 4)] public string LinkImpression { get; set; } [ControlText(Type = ControlText.TextBox, LabelText = "Đường dẫn đơn vị quảng cáo", MaxLength = 500, ContainerCssClass = Constants.ContainerCssClassCol12, ContainerRowIndex = 5)] public string LinkClickThrough { get; set; } [ControlText(Type = ControlText.TextBox, LabelText = "Đường dẫn tracking 1", MaxLength = 500, ContainerCssClass = Constants.ContainerCssClassCol12, ContainerRowIndex = 6)] public string TrackingValue1 { get; set; } [ControlText(Type = ControlText.TextBox, LabelText = "Đường dẫn tracking 2", MaxLength = 500, ContainerCssClass = Constants.ContainerCssClassCol12, ContainerRowIndex = 7)] public string TrackingValue2 { get; set; } [ControlText(Type = ControlText.TextBox, LabelText = "Đường dẫn tracking 3", MaxLength = 500, ContainerCssClass = Constants.ContainerCssClassCol12, ContainerRowIndex = 8)] public string TrackingValue3 { get; set; } [ControlText(Type = ControlText.TextBox, LabelText = "Đường dẫn tracking 4", MaxLength = 500, ContainerCssClass = Constants.ContainerCssClassCol12, ContainerRowIndex = 9)] public string TrackingValue4 { get; set; } [ControlText(Type = ControlText.TextBox, LabelText = "Đường dẫn tracking 5", MaxLength = 500, ContainerCssClass = Constants.ContainerCssClassCol12, ContainerRowIndex = 10)] public string TrackingValue5 { get; set; } [ControlText(Type = ControlText.TextBox, LabelText = "Đường dẫn tracking 6", MaxLength = 500, ContainerCssClass = Constants.ContainerCssClassCol12, ContainerRowIndex = 11)] public string TrackingValue6 { get; set; } [ControlNumeric(LabelText = "Bitrate", Required = true, ContainerCssClass = Constants.ContainerCssClassCol3, ContainerRowIndex = 12)] public int MediaFileBitrate { get; set; } [ControlText(Type = ControlText.TextBox, LabelText = "Delivery", Required = true, MaxLength = 250, ContainerCssClass = Constants.ContainerCssClassCol3, ContainerRowIndex = 12)] public string MediaFileDelivery { get; set; } [ControlNumeric(LabelText = "Chiều cao", Required = true, ContainerCssClass = Constants.ContainerCssClassCol3, ContainerRowIndex = 12)] public int MediaFileHeight { get; set; } [ControlNumeric(LabelText = "Chiều rộng", Required = true, ContainerCssClass = Constants.ContainerCssClassCol3, ContainerRowIndex = 12)] public int MediaFileWidth { get; set; } [ControlChoice(ControlChoice.CheckBox, LabelText = "", PrependText = "Duy trì tỷ lệ", ContainerCssClass = Constants.ContainerCssClassCol3, ContainerRowIndex = 13)] public bool MediaFileMaintainAspectRatio { get; set; } [ControlChoice(ControlChoice.CheckBox, LabelText = "", PrependText = "Scalable", ContainerCssClass = Constants.ContainerCssClassCol3, ContainerRowIndex = 13)] public bool MediaFileScalable { get; set; } [ControlText(Type = ControlText.TextBox, LabelText = "Đường dẫn video quảng cáo", MaxLength = 500, ContainerCssClass = Constants.ContainerCssClassCol10, ContainerRowIndex = 14)] public string MediaFileValue { get; set; } [ControlText(Type = ControlText.TextBox, LabelText = "Loại file", Required = true, MaxLength = 250, ContainerCssClass = Constants.ContainerCssClassCol2, ContainerRowIndex = 14)] public string MediaFileType { get; set; } public static implicit operator VastModel(VastInfo entity) { return new VastModel { Id = entity.Id, LanguageCode = entity.LanguageCode, SiteId = entity.SiteId, KeyCode = entity.KeyCode, AdId = entity.AdId, AdSystemVersion = entity.AdSystemVersion, AdSystemValue = entity.AdSystemValue, AdTitle = entity.AdTitle, LinkError = entity.LinkError, LinkImpression = entity.LinkImpression, Skipoffset = entity.Skipoffset, Duration = entity.Duration, LinkClickThrough = entity.LinkClickThrough, TrackingValue1 = entity.TrackingValue1, TrackingValue2 = entity.TrackingValue2, TrackingValue3 = entity.TrackingValue3, TrackingValue4 = entity.TrackingValue4, TrackingValue5 = entity.TrackingValue5, TrackingValue6 = entity.TrackingValue6, MediaFileBitrate = entity.MediaFileBitrate, MediaFileDelivery = entity.MediaFileDelivery, MediaFileHeight = entity.MediaFileHeight, MediaFileWidth = entity.MediaFileWidth, MediaFileMaintainAspectRatio = entity.MediaFileMaintainAspectRatio, MediaFileScalable = entity.MediaFileScalable, MediaFileType = entity.MediaFileType, MediaFileValue = entity.MediaFileValue }; } } } <file_sep>using CMSSolutions.Web.UI.ControlForms; using CMSSolutions.Websites.Entities; namespace CMSSolutions.Websites.Models { public class TagModel { public TagModel() { IsDisplay = true; } [ControlHidden] public int Id { get; set; } [ControlText(Type = ControlText.TextBox, LabelText = "Tiêu đề", PlaceHolder = "Tối đa 250 ký tự", Required = true, MaxLength = 250, ContainerCssClass = Constants.ContainerCssClassCol4, ContainerRowIndex = 1)] public string Name { get; set; } [ControlText(Type = ControlText.TextBox, Required = true, LabelText = "Tên không dấu", PlaceHolder = "Hệ thống tự động sinh.", MaxLength = 250, ContainerCssClass = Constants.ContainerCssClassCol4, ContainerRowIndex = 2)] public string Alias { get; set; } [ControlChoice(ControlChoice.CheckBox, LabelText = "", PrependText = "Được hiển thị", ContainerCssClass = Constants.ContainerCssClassCol3, ContainerRowIndex = 3)] public bool IsDisplay { get; set; } public static implicit operator TagModel(TagInfo other) { if (other == null) { return null; } return new TagModel { Id = other.Id, Name = other.Name, Alias = other.Alias, IsDisplay = other.IsDisplay }; } } }<file_sep>using System.Collections.Generic; using System.Data.SqlClient; using CMSSolutions.Data; using CMSSolutions.Events; using CMSSolutions.Services; using CMSSolutions.Websites.Entities; namespace CMSSolutions.Websites.Services { public interface IEpisodesService : IGenericService<EpisodeInfo, int>, IDependency { bool CheckExist(int id, string keyword); IList<EpisodeInfo> GetPaged(string languageCode, int siteId, string keyword, int status, int pageIndex, int pageSize, out int totals); IList<EpisodeInfo> GetAll(string languageCode, int siteId, int status); } public class EpisodeService : GenericService<EpisodeInfo, int>, IEpisodesService { public EpisodeService(IRepository<EpisodeInfo, int> repository, IEventBus eventBus) : base(repository, eventBus) { } public bool CheckExist(int id, string keyword) { var list = new List<SqlParameter> { AddInputParameter("@Id", id), AddInputParameter("@Keyword", keyword) }; var result = (int)ExecuteReaderResult("sp_Episodes_CheckName", list.ToArray()); return result > 0; } public IList<EpisodeInfo> GetPaged(string languageCode, int siteId, string keyword, int status, int pageIndex, int pageSize, out int totals) { var list = new List<SqlParameter> { AddInputParameter("@SiteId", siteId), AddInputParameter("@LanguageCode", languageCode), AddInputParameter("@Keyword", keyword), AddInputParameter("@Status", status), AddInputParameter("@PageIndex", pageIndex), AddInputParameter("@PageSize", pageSize) }; return ExecuteReader<EpisodeInfo>("sp_Episodes_Search_Paged", "@TotalRecord", out totals, list.ToArray()); } public IList<EpisodeInfo> GetAll(string languageCode, int siteId, int status) { var list = new List<SqlParameter> { AddInputParameter("@SiteId", siteId), AddInputParameter("@LanguageCode", languageCode), AddInputParameter("@Status", status) }; return ExecuteReader<EpisodeInfo>("sp_Episodes_GetAll", list.ToArray()); } } } <file_sep>using System.Xml.Serialization; namespace CMSSolutions.Websites.Models { #region ads [XmlRoot("VAST")] public class Vast { [XmlElement("Ad")] public Ads ItemAds { get; set; } } [XmlRoot("Ad")] public class Ads { [XmlAttributeAttribute("id")] public int Id { get; set; } [XmlElement("InLine")] public InLine ObjectInLine { get; set; } } [XmlRoot("InLine")] public class InLine { [XmlElement("AdSystem")] public AdSystem ObjectAdSystem { get; set; } [XmlElement("AdTitle")] public string AdTitle { get; set; } [XmlElement("Error")] public string Error { get; set; } [XmlElement("Impression")] public string Impression { get; set; } [XmlElement("Creatives")] public Creatives Creatives { get; set; } } [XmlRoot("AdSystem")] public class AdSystem { [XmlAttributeAttribute("version")] public string Version { get; set; } [XmlText] public string Value { get; set; } } [XmlRoot("Creatives")] public class Creatives { [XmlElement("Creative")] public Creative[] ListCreatives { get; set; } } [XmlRoot("Creative")] public class Creative { [XmlElement("Linear")] public Linear ObjectLinear { get; set; } } [XmlRoot("Linear")] public class Linear { [XmlAttributeAttribute("skipoffset")] public string Skipoffset { get; set; } [XmlElement("Duration")] public string Duration { get; set; } [XmlElement("VideoClicks")] public VideoClicks VideoClicks { get; set; } [XmlElement("TrackingEvents")] public TrackingEvents TrackingEvents { get; set; } [XmlElement("MediaFiles")] public MediaFiles MediaFiles { get; set; } } [XmlRoot("VideoClicks")] public class VideoClicks { [XmlElement("ClickThrough")] public string ClickThrough { get; set; } } public class TrackingEvents { [XmlElement("Tracking")] public Tracking[] LisTrackings { get; set; } } [XmlRoot("Tracking")] public class Tracking { [XmlAttributeAttribute("event")] public string Event { get; set; } [XmlText] public string Value { get; set; } } [XmlRoot("MediaFiles")] public class MediaFiles { [XmlElement("MediaFile")] public MediaFile[] ListMediaFiles { get; set; } } [XmlRoot("MediaFile")] public class MediaFile { [XmlAttributeAttribute("bitrate")] public int Bitrate { get; set; } [XmlAttributeAttribute("delivery")] public string Delivery { get; set; } [XmlAttributeAttribute("height")] public int Height { get; set; } [XmlAttributeAttribute("width")] public int Width { get; set; } [XmlAttributeAttribute("maintainAspectRatio")] public bool MaintainAspectRatio { get; set; } [XmlAttributeAttribute("scalable")] public bool Scalable { get; set; } [XmlAttributeAttribute("type")] public string Type { get; set; } [XmlText] public string Value { get; set; } } #endregion #region vplugin xml [XmlRoot("Ad")] public class Ad { [XmlElement("link")] public string Link { get; set; } [XmlElement("type")] public string Type { get; set; } [XmlElement("id")] public string Id { get; set; } [XmlElement("click")] public string Click { get; set; } [XmlElement("duration")] public int Duration { get; set; } [XmlElement("position")] public int Position { get; set; } [XmlElement("skip")] public int Skip { get; set; } } [XmlRoot("vplugin")] public class Vplugin { [XmlElement("Ad")] public Ad[] ListAds { get; set; } } #endregion }<file_sep>using System.Collections.Generic; using System.Xml; using CMSSolutions.Websites.Entities; namespace CMSSolutions.Websites.Extensions { public class PicasaService { public List<PicasaInfo> ParseRssFile(string albumLink,string currentLink) { var rssXmlDoc = new XmlDocument(); rssXmlDoc.Load(albumLink); XmlNodeList rssNodes = rssXmlDoc.SelectNodes("rss/channel/item"); var list = new List<PicasaInfo>(); foreach (XmlNode rssNode in rssNodes) { XmlNode rssSubNode = rssNode.SelectSingleNode("link"); if (rssSubNode == null) { continue; } string link = rssSubNode.InnerText; if (link != currentLink) { continue; } rssSubNode = rssNode.LastChild; XmlNodeList listUrl = rssSubNode.ChildNodes; foreach (XmlNode item in listUrl) { if (item == null || item.Attributes == null || item.Attributes.Count <= 0) { continue; } if (item.Attributes["medium"] == null) { continue; } string medium = item.Attributes["medium"].Value; if (!string.IsNullOrEmpty(medium) && medium == "video") { var info = new PicasaInfo(); info.Medium = medium; string url = item.Attributes["url"].Value; info.Url = url.Replace("&amp;", "&"); string width = item.Attributes["width"].Value; info.Width = int.Parse(width); string height = item.Attributes["height"].Value; info.Height = int.Parse(height); string type = item.Attributes["type"].Value; info.Type = type; list.Add(info); } } } return list; } } }<file_sep>using System.Collections.Generic; using System.Linq; using System.Web.Mvc; using CMSSolutions.ContentManagement.Widgets.Services; using CMSSolutions.DisplayManagement; using CMSSolutions.Web.Mvc; using CMSSolutions.Web.Themes; using CMSSolutions.Websites.Entities; using CMSSolutions.Websites.Extensions; using CMSSolutions.Websites.Models; using CMSSolutions.Websites.Services; namespace CMSSolutions.Websites.Controllers { [Themed(IsDashboard = false)] public class HomeSearchController : BaseHomeController { private readonly dynamic shapeFactory; public HomeSearchController(IWorkContextAccessor workContextAccessor, IShapeFactory shapeFactory) : base(workContextAccessor) { this.shapeFactory = shapeFactory; PageIndex = 1; } [HttpGet] [Url("tim-kiem")] public ActionResult Index() { UrlLogin = Request.Url != null ? Request.Url.AbsoluteUri : Url.Action("Index", "Home"); string keyword = Request.QueryString["keyword"]; BuildModulesSearch(keyword); return View(); } private void BuildModulesSearch(string keyword) { var widget = WorkContext.Resolve<IWidgetService>(); var viewRenderer = new ViewRenderer { Context = ControllerContext }; if (!IsVip) { } #region HomeFooterLogoInformation var homeFooterLogoInformation = widget.GetWidget(HomeWidgets.HomeFooterLogoInformation.ToString()); if (homeFooterLogoInformation != null) { var widgetShape = shapeFactory.Widget(); widgetShape.Widget = homeFooterLogoInformation; WorkContext.Layout.FooterLogoInformation(widgetShape); } #endregion #region SocialNetwork var socialNetwork = widget.GetWidget(HomeWidgets.DisplaySocialNetwork.ToString()); if (socialNetwork != null) { var widgetShape = shapeFactory.Widget(); widgetShape.Widget = socialNetwork; WorkContext.Layout.DisplaySocialNetwork(widgetShape); } #endregion #region BannerRightFirst var view = viewRenderer.RenderPartialView(Extensions.Constants.DivDisplayFilePath, null); WorkContext.Layout.AdBannerRightFirst.Add(new MvcHtmlString(view)); #endregion #region HomeFacebookFanpage var homeFacebookFanpage = widget.GetWidget(HomeWidgets.HomeFacebookFanpage.ToString()); if (homeFacebookFanpage != null) { var widgetShape = shapeFactory.Widget(); widgetShape.Widget = homeFacebookFanpage; WorkContext.Layout.AdFacebookFanpage(widgetShape); } #endregion #region News var viewNews = viewRenderer.RenderPartialView(Extensions.Constants.NewsViewFilePath, null); WorkContext.Layout.DisplayNews.Add(new MvcHtmlString(viewNews)); #endregion #region Tags var serviceTags = WorkContext.Resolve<ITagService>(); var modelTags = new TagViewModel { ListTags = serviceTags.GetDisplayTags() }; var viewTags = viewRenderer.RenderPartialView(Extensions.Constants.TagViewFilePath, modelTags); WorkContext.Layout.DisplayTags.Add(new MvcHtmlString(viewTags)); #endregion #region CategoryContentFirst if (Request.QueryString["trang"] != null) { PageIndex = int.Parse(Request.QueryString["trang"]); } PageSize = 100; SiteId = (int)Site.Home; ViewData[Extensions.Constants.HeaderTitle] = "Từ khóa " + keyword + " trang " + PageIndex; ViewData[Extensions.Constants.HeaderDescription] = "xem phim, phim hay, phim online, phim hd, phim miễn phí, xem phim hay, xem phim online, xem phim hd, xem phim miễn phí"; ViewData[Extensions.Constants.HeaderKeywords] = "Từ khóa " + keyword + " trang " + PageIndex; var condition = new List<SearchCondition> { new SearchCondition(new[] { SearchField.Title.ToString(), SearchField.Keyword.ToString(), SearchField.KeywordEN.ToString() }, keyword) }; var service = WorkContext.Resolve<ISearchService>(); service.SiteId = SiteId; var totalRow = 0; var data = service.Search(condition, PageIndex, PageSize, ref totalRow); var modelFirst = new DataViewCategoryModel(); if (data != null && data.Count > 0) { modelFirst.ListSearchFilms = data.Where(x => x.IsFilm).ToList(); modelFirst.ListSearchClip = data.Where(x => x.IsClip).ToList(); modelFirst.ListSearchShow = data.Where(x => x.IsShow).ToList(); modelFirst.ListSearchTrailer = data.Where(x => x.IsTrailer).ToList(); } modelFirst.PageIndex = PageIndex; modelFirst.PageSize = PageSize; modelFirst.TotalRow = totalRow; modelFirst.Keyword = keyword; var viewFilmFirst = viewRenderer.RenderPartialView(Extensions.Constants.SearchResultsViewFilePath, modelFirst); WorkContext.Layout.CategoryContentLeftFirst.Add(new MvcHtmlString(viewFilmFirst)); #endregion } } } <file_sep>using CMSSolutions.Web.UI.ControlForms; using CMSSolutions.Websites.Entities; namespace CMSSolutions.Websites.Models { public class SliderModel { [ControlHidden] public int Id { get; set; } [ControlChoice(ControlChoice.DropDownList, Required = true, LabelText = "Chọn ngôn ngữ", ContainerCssClass = Constants.ContainerCssClassCol4, ContainerRowIndex = 0, OnSelectedIndexChanged = "$('#" + Extensions.Constants.CategoryId + "').empty();")] public string LanguageCode { get; set; } [ControlCascadingDropDown(LabelText = "Chọn trang web", ParentControl = "LanguageCode", AbsoluteParentControl = true, ContainerCssClass = Constants.ContainerCssClassCol4, ContainerRowIndex = 0)] public int SiteId { get; set; } [ControlCascadingDropDown(LabelText = "Chọn chuyên mục", ParentControl = "SiteId", AbsoluteParentControl = true, ContainerCssClass = Constants.ContainerCssClassCol4, ContainerRowIndex = 0)] public int CategoryId { get; set; } [ControlCascadingDropDown(EnableChosen = true, CssClass = Extensions.Constants.CssControlCustom, LabelText = "Chọn phim", ParentControl = "CategoryId", AbsoluteParentControl = true, ContainerCssClass = Constants.ContainerCssClassCol4, ContainerRowIndex = 1)] public long FilmId { get; set; } [ControlChoice(ControlChoice.DropDownList, LabelText = "Trang hiển thị", ContainerCssClass = Constants.ContainerCssClassCol4, ContainerRowIndex = 1)] public int PageId { get; set; } [ControlNumeric(LabelText = "Thứ tự", Required = true, ContainerCssClass = Constants.ContainerCssClassCol4, ContainerRowIndex = 1)] public int OrderBy { get; set; } [ControlFileUpload(EnableFineUploader = true, LabelText = "Ảnh nền", ContainerCssClass = Constants.ContainerCssClassCol12, ContainerRowIndex = 6, ShowThumbnail = true)] public string Images { get; set; } public static implicit operator SliderModel(SliderInfo entity) { return new SliderModel { Id = entity.Id, LanguageCode = entity.LanguageCode, SiteId = entity.SiteId, CategoryId = entity.CategoryId, FilmId = entity.FilmId, PageId = entity.PageId, OrderBy = entity.OrderBy, Images = entity.Images }; } } }<file_sep>using System.ComponentModel; using System.Runtime.Serialization; using CMSSolutions.Data; using CMSSolutions.Data.Entity; namespace CMSSolutions.Websites.Entities { [DataContract] public class DownloadGameInfo : BaseEntity<int> { [DataMember] [DisplayName("Code")] public string Code { get; set; } [DataMember] [DisplayName("UrlBanner")] public string UrlBanner { get; set; } [DataMember] [DisplayName("Logo")] public string Logo { get; set; } [DataMember] [DisplayName("Title")] public string Title { get; set; } [DataMember] [DisplayName("GooglePlayUrl")] public string GooglePlayUrl { get; set; } [DataMember] [DisplayName("WebsiteUrl")] public string WebsiteUrl { get; set; } [DataMember] [DisplayName("VipXu")] public int VipXu { get; set; } [DataMember] [DisplayName("IsActived")] public bool IsActived { get; set; } } public class DownloadGameMap : EntityTypeConfiguration<DownloadGameInfo>, IEntityTypeConfiguration { public DownloadGameMap() { ToTable("Modules_DownloadGames"); HasKey(m => m.Id); Property(m => m.Code).IsRequired().HasMaxLength(100); Property(m => m.UrlBanner).IsRequired().HasMaxLength(500); Property(m => m.Logo).IsRequired().HasMaxLength(500); Property(m => m.Title).IsRequired().HasMaxLength(250); Property(m => m.GooglePlayUrl).IsRequired().HasMaxLength(500); Property(m => m.WebsiteUrl).HasMaxLength(500); Property(m => m.VipXu).IsRequired(); } } }<file_sep>using System; using CMSSolutions.ContentManagement.Messages.Services; using CMSSolutions.Net.Mail; using CMSSolutions.Tasks; using CMSSolutions.Websites.Services; using Castle.Core.Logging; namespace CMSSolutions.Websites.Tasks { public class SendEmailTasks: IScheduleTask { public SendEmailTasks() { Logger = NullLogger.Instance; } public ILogger Logger { get; set; } public string Name { get { return "Gửi danh sách phim tự động qua email"; } } public bool Enabled { get { return false; } } public string CronExpression { get { return "0 0 23 ? * MON-FRI *"; } } public bool DisallowConcurrentExecution { get { return true; } } public void Execute(IWorkContextScope scope) { int maxTries = 1; int pageSize = 100; int pageIndex = 1; int totalRecord = 0; int totalPage = 1; var smtpSettings = scope.Resolve<SmtpSettings>(); if (smtpSettings.MessagesPerBatch > 0) { maxTries = smtpSettings.MaxTries; pageSize = smtpSettings.MessagesPerBatch; } var emailSender = scope.Resolve<IEmailSender>(); var messageService = scope.Resolve<IMessageService>(); var customerService = scope.Resolve<ICustomerService>(); try { customerService.AddEmailMessages(); } catch (Exception) { } var queuedEmails = customerService.GetQueuedEmails(maxTries, DateTime.Parse("01/01/1900"), pageIndex, pageSize, out totalRecord); if (queuedEmails != null && totalRecord > 0) { if (totalRecord <= pageSize) { totalPage = 1; } else { var count = totalRecord % pageSize; if ((count == 0)) { totalPage = totalRecord / pageSize; } else { totalPage = ((totalRecord - count) / pageSize) + 1; } } for (int i = 1; i <= totalPage; i++) { try { if (i > 1) { queuedEmails = customerService.GetQueuedEmails(maxTries, DateTime.Parse("01/01/1900"), pageIndex, pageSize, out totalRecord); } foreach (var queuedEmail in queuedEmails) { try { var mailMessage = queuedEmail.GetMailMessage(); emailSender.Send(mailMessage); queuedEmail.SentOnUtc = DateTime.UtcNow; } catch (Exception exc) { Logger.Error(string.Format("Error sending e-mail. {0}", exc.Message), exc); } finally { queuedEmail.SentTries = queuedEmail.SentTries + 1; messageService.Update(queuedEmail); } } } catch (Exception) { } pageIndex++; } } } } }<file_sep>using System; using System.ComponentModel; using System.ComponentModel.DataAnnotations.Schema; using System.Runtime.Serialization; using CMSSolutions.Data; using CMSSolutions.Data.Entity; namespace CMSSolutions.Websites.Entities { [DataContract] public class AdvertisementGroupInfo : BaseEntity<int> { [DataMember] [DisplayName("SiteId")] public int SiteId { get; set; } [DataMember] [DisplayName("LanguageCode")] public string LanguageCode { get; set; } [DataMember] [DisplayName("CategoryId")] public int CategoryId { get; set; } [NotMapped] [DisplayName("CategoryName")] public string CategoryName { get; set; } [DataMember] [DisplayName("Code")] public string Code { get; set; } [DataMember] [DisplayName("GroupName")] public string GroupName { get; set; } [DataMember] [DisplayName("Description")] public string Description { get; set; } [DataMember] [DisplayName("AdvertisementIds")] public string AdvertisementIds { get; set; } [DataMember] [DisplayName("IsGenerate")] public bool IsGenerate { get; set; } [DataMember] [DisplayName("IsActived")] public bool IsActived { get; set; } [DataMember] [DisplayName("FolderPath")] public string FolderPath { get; set; } [DataMember] [DisplayName("FileName")] public string FileName { get; set; } [DataMember] [DisplayName("FullPath")] public string FullPath { get; set; } [NotMapped] [DisplayName(Constants.NotMapped)] public string EncodeFullPath { get { if (!string.IsNullOrEmpty(FullPath)) { return Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes(FullPath)); } return string.Empty; } } [DataMember] [DisplayName("CreateDate")] public DateTime CreateDate { get; set; } [NotMapped] [DisplayName(Constants.NotMapped)] public string TextCreateDate { get { return string.Format("{0}", CreateDate.ToString(Extensions.Constants.DateTimeFomat)); } } [DataMember] [DisplayName("FinishDate")] public DateTime FinishDate { get; set; } [DataMember] [DisplayName("EndTime")] public string FinishTime { get; set; } [NotMapped] [DisplayName(Constants.NotMapped)] public string TextFinishTime { get { return string.Format("{0} {1}", FinishDate.ToString(Extensions.Constants.DateTimeFomat), FinishTime); } } } public class AdvertisementGroupMap : EntityTypeConfiguration<AdvertisementGroupInfo>, IEntityTypeConfiguration { public AdvertisementGroupMap() { ToTable("Modules_AdvertisementGroup"); Property(m => m.LanguageCode).HasMaxLength(50); Property(m => m.Code).HasMaxLength(50); Property(m => m.GroupName).HasMaxLength(250); Property(m => m.AdvertisementIds).HasMaxLength(250); Property(m => m.FolderPath).HasMaxLength(250); Property(m => m.FileName).HasMaxLength(250); Property(m => m.FullPath).HasMaxLength(500); Property(m => m.Description).HasMaxLength(2000); } } } <file_sep>using CMSSolutions.Web.UI.ControlForms; using CMSSolutions.Websites.Entities; namespace CMSSolutions.Websites.Models { public class FilmServerModel { [ControlHidden] public int Id { get; set; } [ControlChoice(ControlChoice.DropDownList, Required = true, LabelText = "Ngôn ngữ hiển thị", ContainerCssClass = Constants.ContainerCssClassCol6, ContainerRowIndex = 0)] public string LanguageCode { get; set; } [ControlCascadingDropDown(LabelText = "Trang web", ParentControl = "LanguageCode", AbsoluteParentControl = true, ContainerCssClass = Constants.ContainerCssClassCol6, ContainerRowIndex = 0)] public int SiteId { get; set; } [ControlText(Type = ControlText.TextBox, Required = true, MaxLength = 250, LabelText = "Tên máy chủ", ContainerCssClass = Constants.ContainerCssClassCol12, ContainerRowIndex = 0)] public string ServerName { get; set; } [ControlText(Type = ControlText.TextBox, Required = true, MaxLength = 50, LabelText = "Địa chỉ IP", ContainerCssClass = Constants.ContainerCssClassCol6, ContainerRowIndex = 1)] public string ServerIP { get; set; } [ControlText(Type = ControlText.TextBox, Required = true, MaxLength = 50, LabelText = "Thư mục gốc", ContainerCssClass = Constants.ContainerCssClassCol6, ContainerRowIndex = 1)] public string FolderRoot { get; set; } [ControlText(Type = ControlText.TextBox, Required = true, LabelText = "Tài khoản FTP", MaxLength = 50, ContainerCssClass = Constants.ContainerCssClassCol6, ContainerRowIndex = 2)] public string UserName { get; set; } [ControlText(Type = ControlText.Password, LabelText = "Mật khẩu", Required = true, MaxLength = 50, ContainerCssClass = Constants.ContainerCssClassCol6, ContainerRowIndex = 2)] public string Password { get; set; } [ControlText(Type = ControlText.TextBox, MaxLength = 250, LabelText = "Địa điểm đặt", ContainerCssClass = Constants.ContainerCssClassCol12, ContainerRowIndex = 3)] public string Locations { get; set; } [ControlChoice(ControlChoice.CheckBox, LabelText = "", PrependText = "Máy chủ VIP", ContainerCssClass = Constants.ContainerCssClassCol3, ContainerRowIndex = 4)] public bool IsVip { get; set; } [ControlChoice(ControlChoice.CheckBox, LabelText = "", PrependText = "Máy chủ mặc định", ContainerCssClass = Constants.ContainerCssClassCol3, ContainerRowIndex = 4)] public bool IsDefault { get; set; } [ControlChoice(ControlChoice.DropDownList, LabelText = "Trạng thái", ContainerCssClass = Constants.ContainerCssClassCol4, ContainerRowIndex = 4)] public int Status { get; set; } [ControlText(Type = ControlText.MultiText, Rows = 2, MaxLength = 2000, LabelText = "Ghi chú", ContainerCssClass = Constants.ContainerCssClassCol12, ContainerRowIndex = 6)] public string Description { get; set; } public static implicit operator FilmServerModel(FilmServerInfo entity) { return new FilmServerModel { Id = entity.Id, LanguageCode = entity.LanguageCode, SiteId = entity.SiteId, ServerName = entity.ServerName, ServerIP = entity.ServerIP, UserName = entity.UserName, Password = <PASSWORD>, Locations = entity.Locations, IsVip = entity.IsVip, IsDefault = entity.IsDefault, Description = entity.Description, Status = entity.Status, FolderRoot = entity.FolderRoot }; } } } <file_sep>using System.Collections.Generic; using System.Data.SqlClient; using CMSSolutions.Data; using CMSSolutions.Events; using CMSSolutions.Services; using CMSSolutions.Websites.Entities; namespace CMSSolutions.Websites.Services { public interface IRateService : IGenericService<RateInfo, long>, IDependency { IList<RateInfo> SearchPaged(string searchText, int pageIndex, int pageSize, out int totalRecord); RateInfo GetByFilmCustomer(long filmId, string customerCode); } public class RateService : GenericService<RateInfo, long>, IRateService { public RateService(IRepository<RateInfo, long> repository, IEventBus eventBus) : base(repository, eventBus) { } public IList<RateInfo> SearchPaged(string searchText, int pageIndex, int pageSize, out int totalRecord) { var list = new List<SqlParameter> { AddInputParameter("@Keyword", searchText), AddInputParameter("@PageIndex", pageIndex), AddInputParameter("@PageSize", pageSize) }; return ExecuteReader<RateInfo>("sp_Rates_Search_Paged", "@TotalRecord", out totalRecord, list.ToArray()); } public RateInfo GetByFilmCustomer(long filmId, string customerCode) { var list = new List<SqlParameter> { AddInputParameter("@FilmId", filmId), AddInputParameter("@CustomerCode", customerCode), }; return ExecuteReaderRecord<RateInfo>("sp_Rates_GetByFilmAndCustomer", list.ToArray()); } public override RateInfo GetById(long id) { var list = new List<SqlParameter> { AddInputParameter("@Id", id), }; return ExecuteReaderRecord<RateInfo>("sp_Rates_GetById", list.ToArray()); } } } <file_sep>using System.Collections.Generic; using System.Data; using System.Linq; using System.Web.Mvc; using CMSSolutions.Websites.Entities; using CMSSolutions.Websites.Extensions; namespace CMSSolutions.Websites.Models { public class DataViewerModel { public string CustomerCode { get; set; } public int DataType { get; set; } public int TotalRow { get; set; } public int TotalPage { get { if (TotalRow <= PageSize) { return 1; } var count = TotalRow % PageSize; if ((count == 0)) { return TotalRow / PageSize; } return ((TotalRow - count) / PageSize) + 1; } } public int PageSize { get; set; } public int PageIndex { get; set; } public string Title { get; set; } public string SliderName { get; set; } public int SiteId { get; set; } public bool IsShow { get; set; } public bool Status { get; set; } public string Data { get; set; } public string Url { get; set; } public CustomerInfo Customer { get; set; } public List<CityInfo> ListCities { get; set; } public List<FilmTypesInfo> ListFilmTypes { get; set; } public List<CountryInfo> ListCountries { get; set; } public List<SelectListItem> ListDay { get; set; } public List<SelectListItem> ListMonth { get; set; } public List<SelectListItem> ListYear { get; set; } public FilmInfo FilmDetails { get; set; } public string JwplayerKey { get; set; } public int EpisodeId { get; set; } public List<PicasaInfo> ListFilmsPicasa { get; set; } public AdvertisementGroupInfo Advertisement { get; set; } public string UrlSwitch { get { var url = string.Empty; switch (DataType) { case (int)LinkType.Streaming: url = FilmDetails.EncodeStreamingUrl; break; case (int)LinkType.Picasa: if (ListFilmsPicasa != null && ListFilmsPicasa.Count > 0) { url = ListFilmsPicasa.FirstOrDefault().EncodeUrl; if (ListFilmsPicasa.Count > 1) { url = ListFilmsPicasa[1].EncodeUrl; } } break; case (int)LinkType.Youtube: url = FilmDetails.EncodeSourceUrl; break; } return url; } } public string Skin { get; set; } public string AdvertisementsPath { get; set; } public List<DownloadGameInfo> ListGames { get; set; } public List<DownloadCustomerInfo> ListDownloadCustomer { get; set; } public DataTable ListHistoryDownload { get; set; } public DownloadCustomerInfo GetByGame(int id) { if (ListDownloadCustomer != null) { return ListDownloadCustomer.FirstOrDefault(x => x.DownloadId == id); } return null; } } }<file_sep>using System.Web.Mvc; using CMSSolutions.Web.Mvc; using CMSSolutions.Web.Routing; using CMSSolutions.Web.Themes; using CMSSolutions.Web.UI.ControlForms; using CMSSolutions.Web.UI.Navigation; using CMSSolutions.Websites.Entities; using CMSSolutions.Websites.Extensions; using CMSSolutions.Websites.Models; using CMSSolutions.Websites.Services; namespace CMSSolutions.Websites.Controllers { [Themed(IsDashboard = true), Authorize] public class AdminRateController : BaseAdminController { public AdminRateController(IWorkContextAccessor workContextAccessor) : base(workContextAccessor) { TableName = "tblRates"; } [Url("admin/rates")] public ActionResult Index() { WorkContext.Breadcrumbs.Add(new Breadcrumb { Text = T("Đánh giá và Báo lỗi phim"), Url = "#" }); var result = new ControlGridFormResult<RateInfo> { Title = T("Đánh giá và Báo lỗi phim"), CssClass = "table table-bordered table-striped", IsAjaxSupported = true, FetchAjaxSource = GetRates, DefaultPageSize = WorkContext.DefaultPageSize, EnablePaginate = true, UpdateActionName = "Update", GridWrapperStartHtml = Constants.Grid.GridWrapperStartHtml, GridWrapperEndHtml = Constants.Grid.GridWrapperEndHtml, ClientId = TableName, ActionsColumnWidth = 100 }; result.AddCustomVar(Extensions.Constants.SearchText, "$('#" + Extensions.Constants.SearchText + "').val();", true); result.AddColumn(x => x.FilmId, T("Mã phim")); result.AddColumn(x => x.FilmName, T("Tên phim")); result.AddColumn(x => x.CustomerCode, T("Mã KH")); result.AddColumn(x => x.CustomerName, T("Họ và Tên")); result.AddAction(new ControlFormHtmlAction(BuildSearchText)).HasParentClass(Constants.ContainerCssClassCol3); result.AddRowAction() .HasText(T("Xem")) .HasUrl(x => Url.Action("Edit", RouteData.Values.Merge(new { id = x.Id }))) .HasButtonStyle(ButtonStyle.Default) .HasButtonSize(ButtonSize.ExtraSmall); result.AddReloadEvent("UPDATE_ENTITY_COMPLETE"); result.AddReloadEvent("DELETE_ENTITY_COMPLETE"); return result; } private ControlGridAjaxData<RateInfo> GetRates(ControlGridFormRequest options) { var searchText = string.Empty; if (Utilities.IsNotNull(Request.Form[Extensions.Constants.SearchText])) { searchText = Request.Form[Extensions.Constants.SearchText]; } int totals; var items = WorkContext.Resolve<IRateService>().SearchPaged(searchText, options.PageIndex, options.PageSize, out totals); var result = new ControlGridAjaxData<RateInfo>(items, totals); return result; } [Url("admin/rates/edit/{id}")] public ActionResult Edit(int id) { WorkContext.Breadcrumbs.Add(new Breadcrumb { Text = T("Đánh giá và Báo lỗi phim"), Url = Url.Action("Index") }); WorkContext.Breadcrumbs.Add(new Breadcrumb { Text = T("Thông tin đánh giá và Báo lỗi phim"), Url = "#" }); var model = new RateModel(); if (id > 0) { var service = WorkContext.Resolve<IRateService>(); model = service.GetById(id); } var result = new ControlFormResult<RateModel>(model) { Title = T("Thông tin đánh giá và Báo lỗi phim"), FormMethod = FormMethod.Post, UpdateActionName = "Update", CancelButtonText = T("Trở về"), ShowBoxHeader = false, ShowSubmitButton = false, FormWrapperStartHtml = Constants.Form.FormWrapperStartHtml, FormWrapperEndHtml = Constants.Form.FormWrapperEndHtml }; result.ReadOnly = true; return result; } } } <file_sep>using System; using System.Collections.Generic; using System.Data.SqlClient; using System.Linq; using CMSSolutions.Caching; using CMSSolutions.Data; using CMSSolutions.Events; using CMSSolutions.Services; using CMSSolutions.Websites.Entities; namespace CMSSolutions.Websites.Services { public interface IFilmService : ICacheService<FilmInfo, long>, IGenericService<FilmInfo, long>, IDependency { string LanguageCode { get; set; } int SiteId { get; set; } int CategoryId { get; set; } bool CheckAlias(long id, string alias); bool CheckName(string filmName); List<FilmInfo> SearchPaged( string searchText, string languageCode, int siteId, int categoryId, int filmTypeId, int countryId, int directorId, int actorId, int collectionId, int articlesId, long createByUserId, int serverId, int releaseYear, DateTime fromDate, DateTime toDate, DateTime createDate, DateTime publishedDate, int isPublished, int isHot, int isHome, int isFilmRetail, int isFilmLengthEpisodes, int status, int pageIndex, int pageSize, out int totalRecord); string GetLatestFilmCode(); IList<FilmInfo> BuildFilmHot(); IList<FilmInfo> BuildFilmRetail(); IList<FilmInfo> BuildFilmManyEpisodes(); IList<FilmInfo> BuildFilmJJChannelIntroduce(); IList<FilmInfo> BuildFilmTheater(); IList<FilmInfo> BuildTVShow(); IList<FilmInfo> BuildClips(); IList<FilmInfo> GetFilmHot(int pageIndex, int pageSize, out int totalRecord); IList<FilmInfo> GetFilmRetail(int pageIndex, int pageSize, out int totalRecord); IList<FilmInfo> GetFilmManyEpisodes(int pageIndex, int pageSize, out int totalRecord); IList<FilmInfo> GetFilmJJChannelIntroduce(int pageIndex, int pageSize, out int totalRecord); IList<FilmInfo> GetFilmTheater(int pageIndex, int pageSize, out int totalRecord); IList<FilmInfo> GetTVShow(int pageIndex, int pageSize, out int totalRecord); IList<FilmInfo> GetClips(int pageIndex, int pageSize, out int totalRecord); void RefreshFilmJJChannelIntroduce(int categoryId); void RefreshTVShows(int categoryId); void RefreshClips(int categoryId); FilmInfo GetFilmDetails(long filmId); void RefreshStatistical1(int top, int type); IList<FilmInfo> GetStatistical1(int top, int type); IList<FilmInfo> BuildStatistical1(int top, int type); IList<FilmInfo> GetStatistical2(int top, int type); IList<FilmInfo> BuildStatistical2(int top, int type); void RefreshStatistical2(int top, int type); IList<FilmInfo> BuildStatistical3(int top, int type); IList<FilmInfo> GetStatistical3(int top, int type); void RefreshStatistical3(int top, int type); IList<FilmInfo> BuildStatistical4(int top, int type); IList<FilmInfo> GetStatistical4(int top, int type); void RefreshStatistical4(int top, int type); IList<FilmInfo> BuildStatistical5(int top, int type); IList<FilmInfo> GetStatistical5(int top, int type); void RefreshStatistical5(int top, int type); IList<FilmInfo> GetByCategoryId(int siteId, string languageCode, int categoryId, int parentId, int filmType, int countryId, int type, int orderBy, int sortBy, int pageIndex, int pageSize, out int totalRecord); IList<FilmInfo> GetByCategoryJJChannelPaged(int siteId, string languageCode, int categoryId, int parentId, int filmType, int countryId, int orderBy, int sortBy, int pageIndex, int pageSize, out int totalRecord); IList<FilmInfo> GetByFilmTheater(int siteId, string languageCode, int filmType, int countryId, int orderBy, int sortBy, int pageIndex, int pageSize, out int totalRecord); IList<FilmInfo> GetByShows(int siteId, string languageCode, int categoryId, int parentId, int showType, int countryId, int orderBy, int sortBy, int pageIndex, int pageSize, out int totalRecord); IList<FilmInfo> GetByClips(int siteId, string languageCode, int categoryId, int parentId, int showType, int orderBy, int sortBy, int pageIndex, int pageSize, out int totalRecord); IList<FilmInfo> GetByTrailer(int siteId, string languageCode, int pageIndex, int pageSize, out int totalRecord); FilmInfo GetFilmsMovie(long filmId, int episodeId); FilmInfo GetTrailerMovie(long filmId); IList<FilmInfo> GetFilmEpisodes(long filmId, int pageIndex, int pageSize, out int totalRecord); int UpdateViewCount(long filmId); IList<FilmInfo> GetAllByCategoryId(); int UpdateCommentCount(long filmId); } public class FilmService : GenericService<FilmInfo, long>, IFilmService { private readonly ICacheInfo cacheManager; private readonly ICategoryService categoryService; public string LanguageCode { get; set; } public int SiteId { get; set; } public int CategoryId { get; set; } public FilmService(IRepository<FilmInfo, long> repository, IEventBus eventBus, ICacheInfo cacheManager, ICategoryService categoryService) : base(repository, eventBus) { this.cacheManager = cacheManager; this.categoryService = categoryService; } public bool CheckAlias(long id, string alias) { var list = new List<SqlParameter> { AddInputParameter("@FilmAlias", alias), AddInputParameter("@Id", id) }; var result = (int)ExecuteReaderResult("sp_Film_CheckAlias", list.ToArray()); return result > 0; } public bool CheckName(string filmName) { var list = new List<SqlParameter> { AddInputParameter("@FilmName", filmName) }; var result = (int)ExecuteReaderResult("sp_Film_CheckName", list.ToArray()); return result > 0; } public List<FilmInfo> SearchPaged( string searchText, string languageCode, int siteId, int categoryId, int filmTypeId, int countryId, int directorId, int actorId, int collectionId, int articlesId, long createByUserId, int serverId, int releaseYear, DateTime fromDate, DateTime toDate, DateTime createDate, DateTime publishedDate, int isPublished, int isHot, int isHome, int isFilmRetail, int isFilmLengthEpisodes, int status, int pageIndex, int pageSize, out int totalRecord) { var list = new List<SqlParameter> { AddInputParameter("@SearchText", searchText), AddInputParameter("@SiteId", siteId), AddInputParameter("@CategoryId", categoryId), AddInputParameter("@LanguageCode", languageCode), AddInputParameter("@FilmTypeId", filmTypeId), AddInputParameter("@CountryId", countryId), AddInputParameter("@DirectorId", directorId), AddInputParameter("@ActorId", actorId), AddInputParameter("@CollectionId", collectionId), AddInputParameter("@ArticlesId", articlesId), AddInputParameter("@CreateByUserId", createByUserId), AddInputParameter("@ServerId", serverId), AddInputParameter("@ReleaseYear", releaseYear), AddInputParameter("@FromDate", fromDate), AddInputParameter("@ToDate", toDate), AddInputParameter("@CreateDate", createDate), AddInputParameter("@PublishedDate", publishedDate), AddInputParameter("@IsPublished", isPublished), AddInputParameter("@IsHot", isHot), AddInputParameter("@IsHome", isHome), AddInputParameter("@IsFilmRetail", isFilmRetail), AddInputParameter("@IsFilmLengthEpisodes", isFilmLengthEpisodes), AddInputParameter("@Status", status), AddInputParameter("@PageIndex", pageIndex), AddInputParameter("@PageSize", pageSize) }; return ExecuteReader<FilmInfo>("sp_Film_Search_Paged", "@TotalRecord", out totalRecord, list.ToArray()); } public string GetLatestFilmCode() { return (string)ExecuteReaderResult("NextFilmCode"); } public IList<FilmInfo> GetFilmHot(int pageIndex, int pageSize, out int totalRecord) { var list = new List<SqlParameter> { AddInputParameter("@SiteId", SiteId), AddInputParameter("@LanguageCode", LanguageCode), AddInputParameter("@PageIndex", pageIndex), AddInputParameter("@PageSize", pageSize) }; return ExecuteReader<FilmInfo>("sp_Films_GetFilmHot_Paged", "@TotalRecord", out totalRecord, list.ToArray()); } public IList<FilmInfo> BuildFilmHot() { var list = cacheManager.Get(Extensions.Constants.CacheKeys.HOME_FILM_HOT); if (list == null) { int totalRecord; list = GetFilmHot(1, 16, out totalRecord); cacheManager.Remove(Extensions.Constants.CacheKeys.HOME_FILM_HOT); cacheManager.Add(Extensions.Constants.CacheKeys.HOME_FILM_HOT, list); } return (IList<FilmInfo>)list; } public IList<FilmInfo> GetFilmRetail(int pageIndex, int pageSize, out int totalRecord) { var list = new List<SqlParameter> { AddInputParameter("@SiteId", SiteId), AddInputParameter("@LanguageCode", LanguageCode), AddInputParameter("@PageIndex", pageIndex), AddInputParameter("@PageSize", pageSize) }; return ExecuteReader<FilmInfo>("sp_Films_GetFilmRetail_Paged", "@TotalRecord", out totalRecord, list.ToArray()); } public IList<FilmInfo> BuildFilmRetail() { var list = cacheManager.Get(Extensions.Constants.CacheKeys.HOME_FILM_RETAIL); if (list == null) { int totalRecord; list = GetFilmRetail(1, 16, out totalRecord); cacheManager.Remove(Extensions.Constants.CacheKeys.HOME_FILM_RETAIL); cacheManager.Add(Extensions.Constants.CacheKeys.HOME_FILM_RETAIL, list); } return (IList<FilmInfo>)list; } public IList<FilmInfo> BuildFilmManyEpisodes() { var list = cacheManager.Get(Extensions.Constants.CacheKeys.HOME_FILM_MANY_EPISODES); if (list == null) { int totalRecord; list = GetFilmManyEpisodes(1, 16, out totalRecord); cacheManager.Remove(Extensions.Constants.CacheKeys.HOME_FILM_MANY_EPISODES); cacheManager.Add(Extensions.Constants.CacheKeys.HOME_FILM_MANY_EPISODES, list); } return (IList<FilmInfo>)list; } public IList<FilmInfo> GetFilmManyEpisodes(int pageIndex, int pageSize, out int totalRecord) { var list = new List<SqlParameter> { AddInputParameter("@SiteId", SiteId), AddInputParameter("@LanguageCode", LanguageCode), AddInputParameter("@PageIndex", pageIndex), AddInputParameter("@PageSize", pageSize) }; return ExecuteReader<FilmInfo>("sp_Films_GetFilmManyEpisodes_Paged", "@TotalRecord", out totalRecord, list.ToArray()); } public IList<FilmInfo> BuildFilmJJChannelIntroduce() { var list = cacheManager.Get(Extensions.Constants.CacheKeys.HOME_FILM_JJ_CHANNEL_INTRODUCE); if (list == null) { int totalRecord; list = GetFilmJJChannelIntroduce(1, 16, out totalRecord); cacheManager.Remove(Extensions.Constants.CacheKeys.HOME_FILM_JJ_CHANNEL_INTRODUCE); cacheManager.Add(Extensions.Constants.CacheKeys.HOME_FILM_JJ_CHANNEL_INTRODUCE, list); } return (IList<FilmInfo>)list; } public IList<FilmInfo> GetFilmJJChannelIntroduce(int pageIndex, int pageSize, out int totalRecord) { var list = new List<SqlParameter> { AddInputParameter("@SiteId", SiteId), AddInputParameter("@LanguageCode", LanguageCode), AddInputParameter("@CategoryId", CategoryId), AddInputParameter("@PageIndex", pageIndex), AddInputParameter("@PageSize", pageSize) }; return ExecuteReader<FilmInfo>("sp_Films_GetFilmJJChannelIntroduce_Paged", "@TotalRecord", out totalRecord, list.ToArray()); } public IList<FilmInfo> BuildFilmTheater() { var list = cacheManager.Get(Extensions.Constants.CacheKeys.HOME_FILM_THEATER); if (list == null) { int totalRecord; list = GetFilmTheater(1, 16, out totalRecord); cacheManager.Remove(Extensions.Constants.CacheKeys.HOME_FILM_THEATER); cacheManager.Add(Extensions.Constants.CacheKeys.HOME_FILM_THEATER, list); } return (IList<FilmInfo>)list; } public IList<FilmInfo> GetFilmTheater(int pageIndex, int pageSize, out int totalRecord) { var list = new List<SqlParameter> { AddInputParameter("@SiteId", SiteId), AddInputParameter("@LanguageCode", LanguageCode), AddInputParameter("@PageIndex", pageIndex), AddInputParameter("@PageSize", pageSize) }; return ExecuteReader<FilmInfo>("sp_Films_GetFilmTheater_Paged", "@TotalRecord", out totalRecord, list.ToArray()); } public IList<FilmInfo> BuildTVShow() { var list = cacheManager.Get(Extensions.Constants.CacheKeys.HOME_FILM_TV_SHOWS); if (list == null) { int totalRecord; list = GetTVShow(1, 10, out totalRecord); cacheManager.Remove(Extensions.Constants.CacheKeys.HOME_FILM_TV_SHOWS); cacheManager.Add(Extensions.Constants.CacheKeys.HOME_FILM_TV_SHOWS, list); } return (IList<FilmInfo>)list; } public IList<FilmInfo> GetTVShow(int pageIndex, int pageSize, out int totalRecord) { var list = new List<SqlParameter> { AddInputParameter("@SiteId", SiteId), AddInputParameter("@LanguageCode", LanguageCode), AddInputParameter("@CategoryId", CategoryId), AddInputParameter("@PageIndex", pageIndex), AddInputParameter("@PageSize", pageSize) }; return ExecuteReader<FilmInfo>("sp_Films_GetTVShows_Paged", "@TotalRecord", out totalRecord, list.ToArray()); } public IList<FilmInfo> BuildClips() { var list = cacheManager.Get(Extensions.Constants.CacheKeys.HOME_FILM_TV_CLIPS); if (list == null) { int totalRecord; list = GetClips(1, 16, out totalRecord); cacheManager.Remove(Extensions.Constants.CacheKeys.HOME_FILM_TV_CLIPS); cacheManager.Add(Extensions.Constants.CacheKeys.HOME_FILM_TV_CLIPS, list); } return (IList<FilmInfo>)list; } public IList<FilmInfo> GetClips(int pageIndex, int pageSize, out int totalRecord) { var list = new List<SqlParameter> { AddInputParameter("@SiteId", SiteId), AddInputParameter("@LanguageCode", LanguageCode), AddInputParameter("@CategoryId", 0), AddInputParameter("@PageIndex", pageIndex), AddInputParameter("@PageSize", pageSize) }; return ExecuteReader<FilmInfo>("sp_Films_GetClips_Paged", "@TotalRecord", out totalRecord, list.ToArray()); } public void RefreshFilmJJChannelIntroduce(int categoryId) { CategoryId = categoryId; var totalRecord = 0; cacheManager.Remove(Extensions.Constants.CacheKeys.HOME_FILM_JJ_CHANNEL_INTRODUCE); cacheManager.Add(Extensions.Constants.CacheKeys.HOME_FILM_JJ_CHANNEL_INTRODUCE, GetFilmJJChannelIntroduce(1, 16, out totalRecord)); } public void RefreshTVShows(int categoryId) { CategoryId = categoryId; var totalRecord = 0; cacheManager.Remove(Extensions.Constants.CacheKeys.HOME_FILM_TV_SHOWS); cacheManager.Add(Extensions.Constants.CacheKeys.HOME_FILM_TV_SHOWS, GetTVShow(1, 10, out totalRecord)); } public void RefreshClips(int categoryId) { CategoryId = categoryId; var totalRecord = 0; cacheManager.Remove(Extensions.Constants.CacheKeys.HOME_FILM_TV_CLIPS); cacheManager.Add(Extensions.Constants.CacheKeys.HOME_FILM_TV_CLIPS, GetClips(1, 16, out totalRecord)); } public FilmInfo GetByIdCache(long id) { throw new NotImplementedException(); } public IList<FilmInfo> GetAllCache() { throw new NotImplementedException(); } public IList<FilmInfo> ResetCache() { int totalRecord; cacheManager.Remove(Extensions.Constants.CacheKeys.HOME_FILM_HOT); cacheManager.Add(Extensions.Constants.CacheKeys.HOME_FILM_HOT, GetFilmHot(1, 16, out totalRecord)); cacheManager.Remove(Extensions.Constants.CacheKeys.HOME_FILM_RETAIL); cacheManager.Add(Extensions.Constants.CacheKeys.HOME_FILM_RETAIL, GetFilmRetail(1, 16, out totalRecord)); cacheManager.Remove(Extensions.Constants.CacheKeys.HOME_FILM_MANY_EPISODES); cacheManager.Add(Extensions.Constants.CacheKeys.HOME_FILM_MANY_EPISODES, GetFilmManyEpisodes(1, 16, out totalRecord)); cacheManager.Remove(Extensions.Constants.CacheKeys.HOME_FILM_THEATER); cacheManager.Add(Extensions.Constants.CacheKeys.HOME_FILM_THEATER, GetFilmTheater(1, 16, out totalRecord)); return null; } public FilmInfo GetFilmDetails(long filmId) { var list = new List<SqlParameter> { AddInputParameter("@SiteId", SiteId), AddInputParameter("@LanguageCode", LanguageCode), AddInputParameter("@FilmId", filmId) }; return ExecuteReaderRecord<FilmInfo>("sp_Films_GetFilmDetails", list.ToArray()); } public void RefreshStatistical1(int top, int type) { cacheManager.Remove(string.Format(Extensions.Constants.CacheKeys.HOME_STATISTICAL_1_TYPE, type)); cacheManager.Add(string.Format(Extensions.Constants.CacheKeys.HOME_STATISTICAL_1_TYPE, type), GetStatistical1(top, type)); } public IList<FilmInfo> BuildStatistical1(int top, int type) { var list = cacheManager.Get(string.Format(Extensions.Constants.CacheKeys.HOME_STATISTICAL_1_TYPE, type)); if (list == null) { list = GetStatistical1(top, type); cacheManager.Remove(string.Format(Extensions.Constants.CacheKeys.HOME_STATISTICAL_1_TYPE, type)); cacheManager.Add(string.Format(Extensions.Constants.CacheKeys.HOME_STATISTICAL_1_TYPE, type), list); } return (IList<FilmInfo>)list; } public IList<FilmInfo> GetStatistical1(int top, int type) { var list = new List<SqlParameter> { AddInputParameter("@SiteId", SiteId), AddInputParameter("@LanguageCode", LanguageCode), AddInputParameter("@TopRecord", top), AddInputParameter("@Type", type) }; return ExecuteReader<FilmInfo>("sp_Films_GetStatistical", list.ToArray()); } public void RefreshStatistical2(int top, int type) { cacheManager.Remove(string.Format(Extensions.Constants.CacheKeys.HOME_STATISTICAL_2_TYPE, type)); cacheManager.Add(string.Format(Extensions.Constants.CacheKeys.HOME_STATISTICAL_2_TYPE, type), GetStatistical2(top, type)); } public void RefreshStatistical3(int top, int type) { cacheManager.Remove(string.Format(Extensions.Constants.CacheKeys.HOME_STATISTICAL_3_TYPE, type)); cacheManager.Add(string.Format(Extensions.Constants.CacheKeys.HOME_STATISTICAL_3_TYPE, type), GetStatistical3(top, type)); } public IList<FilmInfo> GetStatistical4(int top, int type) { var list = new List<SqlParameter> { AddInputParameter("@SiteId", SiteId), AddInputParameter("@LanguageCode", LanguageCode), AddInputParameter("@TopRecord", top), AddInputParameter("@Type", type) }; return ExecuteReader<FilmInfo>("sp_Films_GetStatisticalClips", list.ToArray()); } public void RefreshStatistical4(int top, int type) { cacheManager.Remove(string.Format(Extensions.Constants.CacheKeys.HOME_STATISTICAL_4_TYPE, type)); cacheManager.Add(string.Format(Extensions.Constants.CacheKeys.HOME_STATISTICAL_4_TYPE, type), GetStatistical4(top, type)); } public IList<FilmInfo> BuildStatistical5(int top, int type) { var list = cacheManager.Get(string.Format(Extensions.Constants.CacheKeys.HOME_STATISTICAL_5_TYPE, type)); if (list == null) { list = GetStatistical5(top, type); cacheManager.Remove(string.Format(Extensions.Constants.CacheKeys.HOME_STATISTICAL_5_TYPE, type)); cacheManager.Add(string.Format(Extensions.Constants.CacheKeys.HOME_STATISTICAL_5_TYPE, type), list); } return (IList<FilmInfo>)list; } public IList<FilmInfo> GetStatistical5(int top, int type) { var list = new List<SqlParameter> { AddInputParameter("@SiteId", SiteId), AddInputParameter("@LanguageCode", LanguageCode), AddInputParameter("@TopRecord", top), AddInputParameter("@Type", type) }; return ExecuteReader<FilmInfo>("sp_Films_GetStatisticalTrailer", list.ToArray()); } public void RefreshStatistical5(int top, int type) { cacheManager.Remove(string.Format(Extensions.Constants.CacheKeys.HOME_STATISTICAL_5_TYPE, type)); cacheManager.Add(string.Format(Extensions.Constants.CacheKeys.HOME_STATISTICAL_5_TYPE, type), GetStatistical5(top, type)); } public IList<FilmInfo> BuildStatistical4(int top, int type) { var list = cacheManager.Get(string.Format(Extensions.Constants.CacheKeys.HOME_STATISTICAL_4_TYPE, type)); if (list == null) { list = GetStatistical4(top, type); cacheManager.Remove(string.Format(Extensions.Constants.CacheKeys.HOME_STATISTICAL_4_TYPE, type)); cacheManager.Add(string.Format(Extensions.Constants.CacheKeys.HOME_STATISTICAL_4_TYPE, type), list); } return (IList<FilmInfo>)list; } public IList<FilmInfo> GetStatistical2(int top, int type) { var list = new List<SqlParameter> { AddInputParameter("@SiteId", SiteId), AddInputParameter("@LanguageCode", LanguageCode), AddInputParameter("@TopRecord", top), AddInputParameter("@Type", type) }; return ExecuteReader<FilmInfo>("sp_Films_GetStatisticalLengthEpisodes", list.ToArray()); } public IList<FilmInfo> BuildStatistical2(int top, int type) { var list = cacheManager.Get(string.Format(Extensions.Constants.CacheKeys.HOME_STATISTICAL_2_TYPE, type)); if (list == null) { list = GetStatistical2(top, type); cacheManager.Remove(string.Format(Extensions.Constants.CacheKeys.HOME_STATISTICAL_2_TYPE, type)); cacheManager.Add(string.Format(Extensions.Constants.CacheKeys.HOME_STATISTICAL_2_TYPE, type), list); } return (IList<FilmInfo>)list; } public IList<FilmInfo> BuildStatistical3(int top, int type) { var list = cacheManager.Get(string.Format(Extensions.Constants.CacheKeys.HOME_STATISTICAL_3_TYPE, type)); if (list == null) { list = GetStatistical3(top, type); cacheManager.Remove(string.Format(Extensions.Constants.CacheKeys.HOME_STATISTICAL_3_TYPE, type)); cacheManager.Add(string.Format(Extensions.Constants.CacheKeys.HOME_STATISTICAL_3_TYPE, type), list); } return (IList<FilmInfo>)list; } public IList<FilmInfo> GetStatistical3(int top, int type) { var list = new List<SqlParameter> { AddInputParameter("@SiteId", SiteId), AddInputParameter("@LanguageCode", LanguageCode), AddInputParameter("@TopRecord", top), AddInputParameter("@Type", type) }; return ExecuteReader<FilmInfo>("sp_Films_GetStatisticalShows", list.ToArray()); } public IList<FilmInfo> GetByCategoryId(int siteId, string languageCode, int categoryId, int parentId, int filmType, int countryId, int type,int orderBy, int sortBy, int pageIndex, int pageSize, out int totalRecord) { var list = new List<SqlParameter> { AddInputParameter("@SiteId", SiteId), AddInputParameter("@LanguageCode", LanguageCode), AddInputParameter("@CategoryId", categoryId), AddInputParameter("@ParentId", parentId), AddInputParameter("@FilmTypeId", filmType), AddInputParameter("@CountryId", countryId), AddInputParameter("@Type", type), AddInputParameter("@OrderBy", orderBy), AddInputParameter("@SortBy", sortBy), AddInputParameter("@PageIndex", pageIndex), AddInputParameter("@PageSize", pageSize) }; return ExecuteReader<FilmInfo>("sp_Film_GetByCategoryId", "@TotalRecord", out totalRecord, list.ToArray()); } public IList<FilmInfo> GetByCategoryJJChannelPaged(int siteId, string languageCode, int categoryId, int parentId, int filmType, int countryId, int orderBy, int sortBy, int pageIndex, int pageSize, out int totalRecord) { var list = new List<SqlParameter> { AddInputParameter("@SiteId", SiteId), AddInputParameter("@LanguageCode", LanguageCode), AddInputParameter("@CategoryId", categoryId), AddInputParameter("@ParentId", parentId), AddInputParameter("@FilmTypeId", filmType), AddInputParameter("@CountryId", countryId), AddInputParameter("@OrderBy", orderBy), AddInputParameter("@SortBy", sortBy), AddInputParameter("@PageIndex", pageIndex), AddInputParameter("@PageSize", pageSize) }; return ExecuteReader<FilmInfo>("sp_Film_GetByCategoryJJChannel_Paged", "@TotalRecord", out totalRecord, list.ToArray()); } public IList<FilmInfo> GetByFilmTheater(int siteId, string languageCode, int filmType, int countryId, int orderBy, int sortBy, int pageIndex, int pageSize, out int totalRecord) { var list = new List<SqlParameter> { AddInputParameter("@SiteId", SiteId), AddInputParameter("@LanguageCode", LanguageCode), AddInputParameter("@FilmTypeId", filmType), AddInputParameter("@CountryId", countryId), AddInputParameter("@OrderBy", orderBy), AddInputParameter("@SortBy", sortBy), AddInputParameter("@PageIndex", pageIndex), AddInputParameter("@PageSize", pageSize) }; return ExecuteReader<FilmInfo>("sp_Film_GetFilmsTheater", "@TotalRecord", out totalRecord, list.ToArray()); } public IList<FilmInfo> GetByShows(int siteId, string languageCode, int categoryId, int parentId, int showType, int countryId, int orderBy, int sortBy, int pageIndex, int pageSize, out int totalRecord) { var list = new List<SqlParameter> { AddInputParameter("@SiteId", SiteId), AddInputParameter("@LanguageCode", LanguageCode), AddInputParameter("@CategoryId", categoryId), AddInputParameter("@ParentId", parentId), AddInputParameter("@ShowTypeId", showType), AddInputParameter("@CountryId", countryId), AddInputParameter("@OrderBy", orderBy), AddInputParameter("@SortBy", sortBy), AddInputParameter("@PageIndex", pageIndex), AddInputParameter("@PageSize", pageSize) }; return ExecuteReader<FilmInfo>("sp_Film_GetShows", "@TotalRecord", out totalRecord, list.ToArray()); } public IList<FilmInfo> GetByClips(int siteId, string languageCode, int categoryId, int parentId, int showType, int orderBy, int sortBy, int pageIndex, int pageSize, out int totalRecord) { var list = new List<SqlParameter> { AddInputParameter("@SiteId", SiteId), AddInputParameter("@LanguageCode", LanguageCode), AddInputParameter("@CategoryId", categoryId), AddInputParameter("@ParentId", parentId), AddInputParameter("@ShowTypeId", showType), AddInputParameter("@OrderBy", orderBy), AddInputParameter("@SortBy", sortBy), AddInputParameter("@PageIndex", pageIndex), AddInputParameter("@PageSize", pageSize) }; return ExecuteReader<FilmInfo>("sp_Film_GetClips", "@TotalRecord", out totalRecord, list.ToArray()); } public IList<FilmInfo> GetByTrailer(int siteId, string languageCode, int pageIndex, int pageSize, out int totalRecord) { var list = new List<SqlParameter> { AddInputParameter("@SiteId", SiteId), AddInputParameter("@LanguageCode", LanguageCode), AddInputParameter("@PageIndex", pageIndex), AddInputParameter("@PageSize", pageSize) }; return ExecuteReader<FilmInfo>("sp_Film_GetTrailer", "@TotalRecord", out totalRecord, list.ToArray()); } public FilmInfo GetFilmsMovie(long filmId, int episodeId) { var list = new List<SqlParameter> { AddInputParameter("@LanguageCode", LanguageCode), AddInputParameter("@SiteId", SiteId), AddInputParameter("@FilmId", filmId), AddInputParameter("@EpisodeId", episodeId) }; return ExecuteReaderRecord<FilmInfo>("sp_Films_Movies", list.ToArray()); } public FilmInfo GetTrailerMovie(long filmId) { var list = new List<SqlParameter> { AddInputParameter("@LanguageCode", LanguageCode), AddInputParameter("@SiteId", SiteId), AddInputParameter("@FilmId", filmId) }; return ExecuteReaderRecord<FilmInfo>("sp_Films_TrailerMovies", list.ToArray()); } public IList<FilmInfo> GetFilmEpisodes(long filmId, int pageIndex, int pageSize, out int totalRecord) { var list = new List<SqlParameter> { AddInputParameter("@SiteId", SiteId), AddInputParameter("@LanguageCode", LanguageCode), AddInputParameter("@FilmId", filmId), AddInputParameter("@PageIndex", pageIndex), AddInputParameter("@PageSize", pageSize) }; return ExecuteReader<FilmInfo>("sp_Films_GetFilmEpisodes", "@TotalRecord", out totalRecord, list.ToArray()); } public int UpdateViewCount(long filmId) { var list = new List<SqlParameter> { AddInputParameter("@FilmId", filmId) }; return ExecuteNonQuery("sp_Films_UpdateViewCount", list.ToArray()); } public int UpdateCommentCount(long filmId) { var list = new List<SqlParameter> { AddInputParameter("@FilmId", filmId) }; return ExecuteNonQuery("sp_Films_UpdateCommentCount", list.ToArray()); } public IList<FilmInfo> GetAllByCategoryId() { var list = new List<SqlParameter> { AddInputParameter("@SiteId", SiteId), AddInputParameter("@LanguageCode", LanguageCode), AddInputParameter("@CategoryId", CategoryId) }; return ExecuteReader<FilmInfo>("sp_Films_GetAllByCategoryId", list.ToArray()); } } } <file_sep>using CMSSolutions.Web.UI.ControlForms; namespace CMSSolutions.Websites.Models { public class VideoRefreshModel { [ControlChoice(ControlChoice.DropDownList, Required = true, LabelText = "Máy chủ", ContainerCssClass = Constants.ContainerCssClassCol12, ContainerRowIndex = 0, OnSelectedIndexChanged = "$('#" + Extensions.Constants.ChildrenFolders + "').empty();")] public int ServerId { get; set; } [ControlCascadingDropDown(LabelText = "Thư mục gốc", ParentControl = "ServerId", AbsoluteParentControl = true, ContainerCssClass = Constants.ContainerCssClassCol12, ContainerRowIndex = 1)] public string RootFolders { get; set; } [ControlCascadingDropDown(AllowMultiple = true, LabelText = "Thư mục con", ParentControl = "RootFolders", AbsoluteParentControl = true, ContainerCssClass = Constants.ContainerCssClassCol12, ContainerRowIndex = 1)] public string ChildrenFolders { get; set; } } }<file_sep>using System; using System.Web.Mvc; using CMSSolutions.Web.Mvc; using CMSSolutions.Web.Routing; using CMSSolutions.Web.Themes; using CMSSolutions.Web.UI.ControlForms; using CMSSolutions.Web.UI.Navigation; using CMSSolutions.Websites.Entities; using CMSSolutions.Websites.Extensions; using CMSSolutions.Websites.Models; using CMSSolutions.Websites.Services; namespace CMSSolutions.Websites.Controllers { [Themed(IsDashboard = true), Authorize] public class AdminVipCardController : BaseAdminController { public AdminVipCardController(IWorkContextAccessor workContextAccessor) : base(workContextAccessor) { TableName = "tblVipcards"; } [Url("admin/vipcards")] public ActionResult Index() { WorkContext.Breadcrumbs.Add(new Breadcrumb { Text = T("Quản lý thẻ VIP"), Url = "#" }); var result = new ControlGridFormResult<VIPCardInfo> { Title = T("Quản lý thẻ VIP"), CssClass = "table table-bordered table-striped", IsAjaxSupported = true, FetchAjaxSource = GetVipCards, UpdateActionName = "Update", ActionsColumnWidth = 100, ClientId = TableName, GridWrapperStartHtml = Constants.Grid.GridWrapperStartHtml, GridWrapperEndHtml = Constants.Grid.GridWrapperEndHtml }; result.AddCustomVar(Extensions.Constants.LanguageCode, "$('#" + Extensions.Constants.LanguageCode + "').val();", true); result.AddCustomVar(Extensions.Constants.SiteId, "$('#" + Extensions.Constants.SiteId + "').val();", true); result.AddCustomVar(Extensions.Constants.StatusId, "$('#" + Extensions.Constants.ServerId + "').val();", true); result.AddColumn(x => x.VIPCode, T("Mã thẻ")).AlignCenter().HasWidth(100); result.AddColumn(x => x.VIPName, T("Tên thẻ")); result.AddColumn(x => x.ServerName, T("Máy chủ")); result.AddColumn(x => x.VIPValue, T("Định mức")); result.AddAction().HasText(T("Thêm mới")) .HasUrl(Url.Action("Edit", RouteData.Values.Merge(new { id = 0 }))) .HasButtonStyle(ButtonStyle.Primary) .HasBoxButton(false) .HasCssClass(Constants.RowLeft) .HasRow(true); result.AddAction(new ControlFormHtmlAction(() => BuildLanguages(true, Extensions.Constants.SiteId))).HasParentClass(Constants.ContainerCssClassCol3); result.AddAction(new ControlFormHtmlAction(() => BuildSiteServers(true, Extensions.Constants.ServerId))).HasParentClass(Constants.ContainerCssClassCol3); result.AddAction(new ControlFormHtmlAction(BuildServers)).HasParentClass(Constants.ContainerCssClassCol3); result.AddRowAction() .HasText(T("Sửa")) .HasUrl(x => Url.Action("Edit", RouteData.Values.Merge(new { id = x.Id }))) .HasButtonStyle(ButtonStyle.Default) .HasButtonSize(ButtonSize.ExtraSmall); result.AddReloadEvent("UPDATE_ENTITY_COMPLETE"); result.AddReloadEvent("DELETE_ENTITY_COMPLETE"); return result; } private ControlGridAjaxData<VIPCardInfo> GetVipCards(ControlGridFormRequest options) { var languageCode = WorkContext.CurrentCulture; if (Utilities.IsNotNull(Request.Form[Extensions.Constants.LanguageCode])) { languageCode = Request.Form[Extensions.Constants.LanguageCode]; } var siteId = 0; if (Utilities.IsNotNull(Request.Form[Extensions.Constants.SiteId])) { siteId = Convert.ToInt32(Request.Form[Extensions.Constants.SiteId]); } var serverId = 0; if (Utilities.IsNotNull(Request.Form[Extensions.Constants.ServerId])) { serverId = Convert.ToInt32(Request.Form[Extensions.Constants.ServerId]); } int totals; var items = WorkContext.Resolve<IVIPCardService>().SearchPaged(string.Empty, languageCode, siteId, serverId, options.PageIndex, options.PageSize, out totals); var result = new ControlGridAjaxData<VIPCardInfo>(items, totals); return result; } [Url("admin/vipcards/edit/{id}")] public ActionResult Edit(int id) { WorkContext.Breadcrumbs.Add(new Breadcrumb { Text = T("Quản lý thẻ VIP"), Url = Url.Action("Index") }); WorkContext.Breadcrumbs.Add(new Breadcrumb { Text = T("Thông tin thẻ VIP"), Url = "#" }); var model = new VIPCardModel(); if (id > 0) { var service = WorkContext.Resolve<IVIPCardService>(); model = service.GetById(id); } var result = new ControlFormResult<VIPCardModel>(model) { Title = T("Thông tin thẻ VIP"), FormMethod = FormMethod.Post, UpdateActionName = "Update", SubmitButtonText = T("Lưu lại"), ShowCancelButton = true, ShowBoxHeader = false, CancelButtonText = T("Trở về"), FormWrapperStartHtml = Constants.Form.FormWrapperStartHtml, FormWrapperEndHtml = Constants.Form.FormWrapperEndHtml }; result.RegisterExternalDataSource(x => x.LanguageCode, y => BindLanguages()); result.RegisterCascadingDropDownDataSource(x => x.SiteId, Url.Action("GetSitesByLanguage")); result.RegisterCascadingDropDownDataSource(x => x.ServerId, Url.Action("GetServersBySite")); return result; } [HttpPost, ValidateInput(false), FormButton("Save")] [Url("admin/vipcards/update")] public ActionResult Update(VIPCardModel model) { if (!ModelState.IsValid) { return new AjaxResult().Alert(T(Constants.Messages.InvalidModel)); } var service = WorkContext.Resolve<IVIPCardService>(); VIPCardInfo item = model.Id == 0 ? new VIPCardInfo() : service.GetById(model.Id); if (service.CheckVipCode(item.Id, model.VIPCode)) { return new AjaxResult() .NotifyMessage("UPDATE_ENTITY_COMPLETE") .Alert(T("Đã tồn tại mã thẻ VIP này!")); } item.VIPCode = model.VIPCode.ToUpper(); item.VIPName = model.VIPName; item.VIPValue = model.VIPValue; item.LanguageCode = model.LanguageCode; item.SiteId = model.SiteId; item.ServerId = model.ServerId; service.Save(item); return new AjaxResult().NotifyMessage("UPDATE_ENTITY_COMPLETE") .Alert(T("Cập nhật thành công!")) .CloseModalDialog(); } } } <file_sep>using System; using System.Configuration; namespace CMSSolutions.Websites.Extensions { public class Constants { public const string SearchText = "SearchText"; public const string FromDate = "FromDate"; public const string ToDate = "ToDate"; public const string LanguageCode = "LanguageCode"; public const string SiteId = "SiteId"; public const string CategoryId = "CategoryId"; public const string CategoryIds = "CategoryIds"; public const string ParentId = "ParentId"; public const string ServerId = "ServerId"; public const string IsNull = "null"; public const string IsUndefined = "undefined"; public const string UserId = "UserId"; public const string DirectorId = "DirectorId"; public const string ActorId = "ActorId"; public const string FilmTypesId = "FilmTypesId"; public const string FilmGroup = "FilmGroup"; public const string StatusId = "StatusId"; public const string TypeId = "TypeId"; public const string BankCode = "BankCode"; public const string CardCode = "CardCode"; public const string Locked = "Locked"; public const string TypeSearch = "TypeSearch"; public const string ChildrenFolders = "ChildrenFolders"; public const string RootFolders = "RootFolders"; public const string FolderDay = "FolderDay"; public const string ValueAll = "All"; public const string FilmId = "FilmId"; public const string Id = "id"; public const string PageId = "PageId"; public const string AdId = "AdId"; public const string CountryId = "CountryId"; public const string GlobalCapcha = "GLObAL_CAPCHA"; public const string GlobalCustomerCode = "GLObAL_LOGIN_USER_CODE"; public const string GlobalUserName = "GLObAL_LOGIN_USERNAME"; public const string GlobalFullName = "GLObAL_LOGIN_USER_FULLNAME"; public const string GlobalUserId = "GLObAL_LOGIN_USERID"; public const string GlobalVipXu = "GLObAL_LOGIN_USER_VIPXU"; public const string GlobalSiteId = "GLObAL_SITE_ID"; public const string TransactionCode = "TRANSACTION_CODE"; public const string CurrentDate = "CURRENT_DATETIME"; public const string UrlLoginHistory = "URL_LOGIN_HISTORY"; public const string PageIndex = "pageIndex"; public const string ReturnUrl = "returnUrl"; public const string BackPageIndex = "BackPageIndex"; public const string GlobalTotalMoney = "GLObAL_TOTAL_MONEY"; public const string GlobalTotalDay = "GLObAL_TOTAL_DAY"; public const string GlobalStartDate = "GLObAL_START_DATE"; public const string GlobalEndDate = "GLObAL_END_DATE"; public const string DefaultPassword = "<PASSWORD>"; public const string CssControlCustom = "form-control-custom"; public const string RecieveSmsParameters = "RecieveSms?partnerid={partnerid}&moid={moid}&userid={userid}&shortcode={shortcode}&keyword={keyword}&content={content}&transdate={transdate}&checksum={checksum}&amount={amount}"; public const string SMSSyntax = "Tin nhan sai cu phap vui long kiem tra lai."; public const string SMSCustomerNotFound = "Rat tiec ID khong ton tai. Vui long dang nhap viphd.vn vao muc GOI TAI TRO va nhap ma giao dich sau {0}"; public const string SMSKeywordNotFound = "Tin nhan sai cu phap. Soan VIPXU HD GUI 8376 de nhan huong dan dich vu cua 8x76 (Cuoc phi tin nhan 3.000VND)"; public const string SMSUserHelp = "Soan tin VIPXU MaKH GUI 8576(5.000VND/SMS) hoac VIPXU MaKH GUI 8676(10.000VND/SMS) hoac VIPXU MaKH GUI 8776(15.000VND/SMS)"; public const string SMSSystemError = "He thong thanh toan dang qua tai ban vui long thu lai sau."; public const string VipXuKeyword = "VIPXU"; public const string CategoryContentFirstViewFilePath = "~/Views/Shared/CategoryContentFirst.cshtml"; public const string HomeFilmHotViewFilePath = "~/Views/Shared/HomeFilmHot.cshtml"; public const string SliderOneViewFilePath = "~/Views/Shared/SliderViewOne.cshtml"; public const string CategoryListViewViewFilePath = "~/Views/Shared/CategoryListView.cshtml"; public const string CategoryJJListViewFilePath = "~/Views/Shared/CategoryJJListView.cshtml"; public const string NewsDetailsViewFilePath = "~/Views/Shared/NewsDetails.cshtml"; public const string NewsCategoryViewFilePath = "~/Views/Shared/NewsCategory.cshtml"; public const string FilmTheaterViewFilePath = "~/Views/Shared/FilmTheater.cshtml"; public const string ShowListViewFilePath = "~/Views/Shared/ShowListView.cshtml"; public const string ClipListViewFilePath = "~/Views/Shared/ClipListView.cshtml"; public const string TrailerListViewFilePath = "~/Views/Shared/TrailerListView.cshtml"; public const string SupportsViewFilePath = "~/Views/Shared/HomeSupports.cshtml"; public const string ListMoviesViewFilePath = "~/Views/Shared/ListMovies.cshtml"; public const string SearchResultsViewFilePath = "~/Views/Shared/SearchResults.cshtml"; public const string CategoryContentSecondViewFilePath = "~/Views/Shared/CategoryContentSecond.cshtml"; public const string CategoryContentThirdViewFilePath = "~/Views/Shared/CategoryContentThird.cshtml"; public const string CategoryContentFourthViewFilePath = "~/Views/Shared/CategoryContentFourth.cshtml"; public const string CategoryContentFifthViewFilePath = "~/Views/Shared/CategoryContentFifth.cshtml"; public const string CategoryContentSixthViewFilePath = "~/Views/Shared/CategoryContentSixth.cshtml"; public const string CategoryContentSeventhViewFilePath = "~/Views/Shared/CategoryContentSeventh.cshtml"; public const string SocialNetworkViewFilePath = "~/Views/Shared/SocialNetwork.cshtml"; public const string CustomerViewFilePath = "~/Views/Shared/CustomerInfomations.cshtml"; public const string NewsViewFilePath = "~/Views/Shared/NewsViewer.cshtml"; public const string TagViewFilePath = "~/Views/Shared/Tags.cshtml"; public const string DivDisplayFilePath = "~/Views/Shared/DivDisplay.cshtml"; public const string Statistic1FilePath = "~/Views/Shared/Statistic1.cshtml"; public const string Statistic2FilePath = "~/Views/Shared/Statistic2.cshtml"; public const string Statistic3FilePath = "~/Views/Shared/Statistic3.cshtml"; public const string Statistic4FilePath = "~/Views/Shared/Statistic4.cshtml"; public const string Statistic5FilePath = "~/Views/Shared/Statistic5.cshtml"; public const string Statistic6FilePath = "~/Views/Shared/Statistic6.cshtml"; public const string RegisterResourceFilePath = "~/Views/Shared/HomeRegisterResource.cshtml"; public const string MoviesFilePath = "~/Views/Shared/Movies.cshtml"; public const string FacebookCommentsFilePath = "~/Views/Shared/FacebookComments.cshtml"; public const string FilmRateFilePath = "~/Views/Shared/FilmRate.cshtml"; public const string SliderBannerFilePath = "~/Views/Shared/HomeSliderBanner.cshtml"; public const string DigCoinsFilePath = "~/Views/Shared/DigCoins.cshtml"; public const string DaoXuInformationsFilePath = "~/Views/Shared/DaoXuInformations.cshtml"; public const string DaoXuHelpsFilePath = "~/Views/Shared/DaoXuHelps.cshtml"; public const string DaoXuLogsFilePath = "~/Views/Shared/DaoXuLogs.cshtml"; public const string ImageMale = "/Images/avatars/avatar-no-image.png"; public const string ImageFemale = "/Images/avatars/female-user.png"; public const string DateTimeFomat = "dd/MM/yyyy"; public const string DateTimeFomat2 = "dd.MM.yyyy"; public const string DateTimeFomatFull = "dd/MM/yyyy H:mm:ss"; public const string DateTimeFomatFull2 = "dd-MM-yyyy H:mm:ss"; public const string DateTimeMin = "01/01/1900"; public const string CssThumbsSize = "thumbs-size"; public const string HeaderTitle = "HeaderTitle"; public const string HeaderDescription = "HeaderDescription"; public const string HeaderKeywords = "HeaderKeywords"; //public static string SiteName = ConfigurationManager.AppSettings["SiteName"]; //public static string ContactEmail = ConfigurationManager.AppSettings["ContactEmail"]; public static string HomeDomainName = ConfigurationManager.AppSettings["HomeDomainName"]; public static string JJDomainName = ConfigurationManager.AppSettings["JJDomainName"]; public static string SmsLogFiles = ConfigurationManager.AppSettings["SmsLogFiles"]; public static string SearchEngineDBPath = ConfigurationManager.AppSettings["SearchEngineDBPath"]; public static string JWplayerSkin = Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes(ConfigurationManager.AppSettings["JWplayerSkin"])); public static string JWplayerKey = Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes(ConfigurationManager.AppSettings["JWplayerKey"])); public static string StreamingUrl = ConfigurationManager.AppSettings["StreamingUrl"]; public class CacheKeys { public const string CATEGORY_ALL_TABLE = "CATEGORY_ALL_TABLE_{0}_{1}"; public const string ARTICLES_BY_CATEGORY_ID = "ARTICLES_BY_CATEGORY_ID"; public const string CATALOG_ALL_TABLE = "CATALOG_ALL_TABLE"; public const string SETTING_ALL_TABLE = "SETTING_ALL_TABLE_{0}"; public const string PRODUCT_ALL_TABLE = "PRODUCT_ALL_TABLE_{0}"; public const string HOME_FILM_HOT = "HOME_FILM_HOT"; public const string HOME_FILM_RETAIL = "HOME_FILM_RETAIL"; public const string HOME_FILM_MANY_EPISODES = "HOME_FILM_MANY_EPISODES"; public const string HOME_FILM_JJ_CHANNEL_INTRODUCE = "HOME_FILM_JJ_CHANNEL_INTRODUCE"; public const string HOME_FILM_THEATER = "HOME_FILM_THEATER"; public const string HOME_FILM_TV_SHOWS = "HOME_FILM_TV_SHOWS"; public const string HOME_FILM_TV_CLIPS = "HOME_FILM_TV_CLIPS"; public const string HOME_CATEGORY_ID = "HOME_CATEGORY_{0}"; public const string SEARCH_TEXT = "HOME_SEARCH_TEXT_{0}"; public const string HOME_STATISTICAL_1_TYPE = "HOME_STATISTICAL_1_TYPE_{0}"; public const string HOME_STATISTICAL_2_TYPE = "HOME_STATISTICAL_2_TYPE_{0}"; public const string HOME_STATISTICAL_3_TYPE = "HOME_STATISTICAL_3_TYPE_{0}"; public const string HOME_STATISTICAL_4_TYPE = "HOME_STATISTICAL_4_TYPE_{0}"; public const string HOME_STATISTICAL_5_TYPE = "HOME_STATISTICAL_5_TYPE_{0}"; public const string HOME_SLIDER_PAGE = "HOME_SLIDER_PAGE_{0}"; public const string CUSTOMERS_DATA_CARD = "CUSTOMERS_DATA_CARD"; } } }<file_sep>using System.Collections.Generic; using System.Data; using System.Data.SqlClient; using CMSSolutions.Data; using CMSSolutions.Events; using CMSSolutions.Services; using CMSSolutions.Websites.Entities; namespace CMSSolutions.Websites.Services { public interface IAdvertisementGroupService : IGenericService<AdvertisementGroupInfo, int>, IDependency { List<AdvertisementGroupInfo> SearchPaged( string languageCode, int siteId, int categoryId, int pageIndex, int pageSize, out int totalRecord); AdvertisementGroupInfo GetAdByCategories(string languageCode, int siteId, string categoryIds); DataTable GetDataGenerateXml(string languageCode); IList<AdvertisementGroupInfo> GetGroupGenerateXml(string languageCode); } public class AdvertisementGroupService : GenericService<AdvertisementGroupInfo, int>, IAdvertisementGroupService { public AdvertisementGroupService(IRepository<AdvertisementGroupInfo, int> repository, IEventBus eventBus) : base(repository, eventBus) { } public List<AdvertisementGroupInfo> SearchPaged(string languageCode, int siteId, int categoryId, int pageIndex, int pageSize, out int totalRecord) { var list = new List<SqlParameter> { AddInputParameter("@LanguageCode", languageCode), AddInputParameter("@SiteId", siteId), AddInputParameter("@CategoryId", categoryId), AddInputParameter("@PageIndex", pageIndex), AddInputParameter("@PageSize", pageSize) }; return ExecuteReader<AdvertisementGroupInfo>("sp_AdvertisementGroup_Search_Paged", "@TotalRecord", out totalRecord, list.ToArray()); } public AdvertisementGroupInfo GetAdByCategories(string languageCode, int siteId, string categoryIds) { var list = new List<SqlParameter> { AddInputParameter("@LanguageCode", languageCode), AddInputParameter("@SiteId", siteId), AddInputParameter("@CategoryIds", categoryIds) }; return ExecuteReaderRecord<AdvertisementGroupInfo>("sp_AdvertisementGroup_GetAdByCategory", list.ToArray()); } public DataTable GetDataGenerateXml(string languageCode) { var list = new List<SqlParameter> { AddInputParameter("@LanguageCode", languageCode) }; return ExecuteReader("sp_Advertisement_GetGenerateXml", list.ToArray()).Tables[0]; } public IList<AdvertisementGroupInfo> GetGroupGenerateXml(string languageCode) { var list = new List<SqlParameter> { AddInputParameter("@LanguageCode", languageCode) }; return ExecuteReader<AdvertisementGroupInfo>("sp_AdvertisementGroup_GetGenerateXml", list.ToArray()); } } } <file_sep>using CMSSolutions.Web.UI.ControlForms; using CMSSolutions.Websites.Entities; namespace CMSSolutions.Websites.Models { public class SupportModel { [ControlHidden] public int Id { get; set; } [ControlChoice(ControlChoice.DropDownList, Required = true, LabelText = "Ngôn ngữ hiển thị", ContainerCssClass = Constants.ContainerCssClassCol4, ContainerRowIndex = 0, OnSelectedIndexChanged = "$('#" + Extensions.Constants.ParentId+ "').empty();")] public string LanguageCode { get; set; } [ControlCascadingDropDown(LabelText = "Trang web", ParentControl = "LanguageCode", AbsoluteParentControl = true, ContainerCssClass = Constants.ContainerCssClassCol4, ContainerRowIndex = 0)] public int SiteId { get; set; } [ControlCascadingDropDown(LabelText = "Chọn nhóm", ParentControl = "SiteId", AbsoluteParentControl = true, ContainerCssClass = Constants.ContainerCssClassCol4, ContainerRowIndex = 0)] public int ParentId { get; set; } [ControlChoice(ControlChoice.CheckBox, LabelText = "", PrependText = "Tạo nhóm", ContainerCssClass = Constants.ContainerCssClassCol4, ContainerRowIndex = 1)] public bool IsGroup { get; set; } [ControlNumeric(LabelText = "Sắp xếp theo nhóm", Required = true, MaxLength = 15, ContainerCssClass = Constants.ContainerCssClassCol4, ContainerRowIndex = 1)] public int OrderBy { get; set; } [ControlChoice(ControlChoice.DropDownList, LabelText = "Trạng thái", ContainerCssClass = Constants.ContainerCssClassCol4, ContainerRowIndex = 1)] public int Status { get; set; } [ControlText(Type = ControlText.TextBox, LabelText = "Câu hỏi", PlaceHolder = "Tối đa 250 ký tự", Required = true, MaxLength = 400, ContainerCssClass = Constants.ContainerCssClassCol12, ContainerRowIndex = 2)] public string Title { get; set; } [ControlText(LabelText = "Trả lời câu hỏi", Type = ControlText.RichText, MaxLength = 500, ContainerCssClass = Constants.ContainerCssClassCol12, ContainerRowIndex = 3)] public string Messages { get; set; } public static implicit operator SupportModel(SupportInfo entity) { return new SupportModel { Id = entity.Id, LanguageCode = entity.LanguageCode, SiteId = entity.SiteId, Title = entity.Title, OrderBy = entity.OrderBy, Messages = entity.Messages, Status = entity.Status, ParentId = entity.ParentId }; } } }<file_sep>using System.ComponentModel; using System.Runtime.Serialization; using CMSSolutions.Data; using CMSSolutions.Data.Entity; namespace CMSSolutions.Websites.Entities { [DataContract] public class CityInfo : BaseEntity<int> { [DataMember] [DisplayName("Code")] public string Code { get; set; } [DataMember] [DisplayName("Name")] public string Name { get; set; } [DataMember] [DisplayName("CountryId")] public int CountryId { get; set; } [DataMember] [DisplayName("Status")] public int Status { get; set; } } public class CityMap : EntityTypeConfiguration<CityInfo>, IEntityTypeConfiguration { public CityMap() { ToTable("Modules_City"); HasKey(x => x.Id); Property(x => x.Code).HasMaxLength(50); Property(x => x.Name).IsRequired().HasMaxLength(250); Property(x => x.CountryId).IsRequired(); } } }<file_sep>using System.Collections.Generic; using System.Data.SqlClient; using CMSSolutions.Data; using CMSSolutions.Events; using CMSSolutions.Services; using CMSSolutions.Websites.Entities; namespace CMSSolutions.Websites.Services { public interface ICollectionService : IGenericService<CollectionInfo, int>, IDependency { bool CheckExist(int id, string keyword); IList<CollectionInfo> GetPaged(string languageCode, int siteId, string keyword, int status, int pageIndex, int pageSize, out int totals); } public class CollectionService : GenericService<CollectionInfo, int>, ICollectionService { public CollectionService(IEventBus eventBus, IRepository<CollectionInfo, int> repository) : base(repository, eventBus) { } public bool CheckExist(int id, string keyword) { var list = new List<SqlParameter> { AddInputParameter("@Id", id), AddInputParameter("@Keyword", keyword) }; var result = (int)ExecuteReaderResult("sp_Collections_CheckName", list.ToArray()); return result > 0; } public IList<CollectionInfo> GetPaged(string languageCode, int siteId, string keyword, int status, int pageIndex, int pageSize, out int totals) { var list = new List<SqlParameter> { AddInputParameter("@SiteId", siteId), AddInputParameter("@LanguageCode", languageCode), AddInputParameter("@Keyword", keyword), AddInputParameter("@Status", status), AddInputParameter("@PageIndex", pageIndex), AddInputParameter("@PageSize", pageSize) }; return ExecuteReader<CollectionInfo>("sp_Collections_Search_Paged", "@TotalRecord", out totals, list.ToArray()); } } } <file_sep>using System; using CMSSolutions.Web.UI.ControlForms; using CMSSolutions.Websites.Entities; using CMSSolutions.Websites.Extensions; namespace CMSSolutions.Websites.Models { public class FilmModel { public FilmModel() { PublishedDate = DateTime.Now.ToString(Extensions.Constants.DateTimeFomat); IsPublished = true; VideoType = (int)VideoTypes.IsFilm; Status = (int)Extensions.Status.Approved; } [ControlHidden] public long Id { get; set; } [ControlChoice(ControlChoice.DropDownList, Required = true, LabelText = "Ngôn ngữ hiển thị", ContainerCssClass = Constants.ContainerCssClassCol3, ContainerRowIndex = 0, OnSelectedIndexChanged = "$('#" + Extensions.Constants.CategoryIds + "').empty();")] public string LanguageCode { get; set; } [ControlCascadingDropDown(LabelText = "Trang web", ParentControl = "LanguageCode", AbsoluteParentControl = true, ContainerCssClass = Constants.ContainerCssClassCol3, ContainerRowIndex = 0)] public int SiteId { get; set; } [ControlChoice(ControlChoice.DropDownList, Required = true, LabelText = "Máy chủ mặc định", ContainerCssClass = Constants.ContainerCssClassCol3, ContainerRowIndex = 0)] public int ServerId { get; set; } [ControlChoice(ControlChoice.DropDownList, EnableChosen = true, CssClass = Extensions.Constants.CssControlCustom, Required = true, LabelText = "Đạo diễn", ContainerCssClass = Constants.ContainerCssClassCol3, ContainerRowIndex = 0)] public int DirectorId { get; set; } [ControlCascadingDropDown(AllowMultiple = true, EnableChosen = true, LabelText = "Chuyên mục hiển thị", ParentControl = "SiteId", ContainerCssClass = Constants.ContainerCssClassCol4, ContainerRowIndex = 1)] public int[] CategoryIds { get; set; } [ControlChoice(ControlChoice.DropDownList, AllowMultiple = true, CssClass = Extensions.Constants.CssControlCustom, EnableChosen = true, Required = true, LabelText = "Thể loại phim", ContainerCssClass = Constants.ContainerCssClassCol4, ContainerRowIndex = 1)] public int[] FilmTypeIds { get; set; } [ControlChoice(ControlChoice.DropDownList, AllowMultiple = true, EnableChosen = true, CssClass = Extensions.Constants.CssControlCustom, Required = true, LabelText = "Diễn viên", ContainerCssClass = Constants.ContainerCssClassCol4, ContainerRowIndex = 1)] public int[] ActorIds { get; set; } [ControlChoice(ControlChoice.CheckBox, LabelText = "", PrependText = "Phim chiếu rạp", ContainerCssClass = Constants.ContainerCssClassCol3, ContainerRowIndex = 2)] public bool IsTheater { get; set; } [ControlChoice(ControlChoice.DropDownList, LabelText = "Nhóm phim", ContainerCssClass = Constants.ContainerCssClassCol3, ContainerRowIndex = 2)] public int FilmGroup { get; set; } [ControlCascadingDropDown(LabelText = "Tên bộ phim", EnableChosen = true, CssClass = Extensions.Constants.CssControlCustom, ParentControl = "FilmGroup", AbsoluteParentControl = true, ContainerCssClass = Constants.ContainerCssClassCol3, ContainerRowIndex = 2)] public int CollectionId { get; set; } [ControlChoice(ControlChoice.DropDownList, EnableChosen = true, CssClass = Extensions.Constants.CssControlCustom, Required = true, LabelText = "Nước sản xuất", ContainerCssClass = Constants.ContainerCssClassCol3, ContainerRowIndex = 2)] public int CountryId { get; set; } [ControlChoice(ControlChoice.DropDownList, LabelText = "Loại video", ContainerCssClass = Constants.ContainerCssClassCol4, ContainerRowIndex = 3)] public int VideoType { get; set; } [ControlText(Type = ControlText.TextBox, Required = true, MaxLength = 250, LabelText = "Tên phim tiếng việt", ContainerCssClass = Constants.ContainerCssClassCol4, ContainerRowIndex = 3)] public string FilmName { get; set; } [ControlText(Type = ControlText.TextBox, MaxLength = 250, LabelText = "Tên phim tiếng anh", ContainerCssClass = Constants.ContainerCssClassCol4, ContainerRowIndex = 3)] public string FilmNameEnglish { get; set; } [ControlText(Type = ControlText.TextBox, LabelText = "Tên không dấu", PlaceHolder = "Mặc định để trống tự sinh theo tên phim tiếng việt", MaxLength = 250, ContainerCssClass = Constants.ContainerCssClassCol12, ContainerRowIndex = 3)] public string FilmAlias { get; set; } [ControlFileUpload(EnableFineUploader = true, LabelText = "Ảnh đại diện", ContainerCssClass = Constants.ContainerCssClassCol6, ContainerRowIndex = 4, Required = true, ShowThumbnail = true)] public string ImageIcon { get; set; } [ControlFileUpload(EnableFineUploader = true, LabelText = "Ảnh đại diện lớn", ContainerCssClass = Constants.ContainerCssClassCol6, ContainerRowIndex = 4, Required = true, ShowThumbnail = true)] public string ImageThumb { get; set; } [ControlChoice(ControlChoice.CheckBox, LabelText = "", PrependText = "Hiện trên trang chủ", ContainerCssClass = Constants.ContainerCssClassCol3, ContainerRowIndex = 5)] public bool IsHome { get; set; } [ControlNumeric(LabelText = "Năm sản xuất", MinimumValue = "1900", MaximumValue = "2050", Required = true, ContainerCssClass = Constants.ContainerCssClassCol3, ContainerRowIndex = 5)] public int ReleaseYear { get; set; } [ControlText(Required = true, MaxLength = 50, LabelText = "Thời gian(Phút)", ContainerCssClass = Constants.ContainerCssClassCol3, ContainerRowIndex = 5)] public string Time { get; set; } [ControlText(Required = true, MaxLength = 50, LabelText = "Tổng dung lượng(MB)", ContainerCssClass = Constants.ContainerCssClassCol3, ContainerRowIndex = 5)] public string Capacity { get; set; } [ControlChoice(ControlChoice.CheckBox, LabelText = "", PrependText = "Có bản quyền", ContainerCssClass = Constants.ContainerCssClassCol3, ContainerRowIndex = 6)] public bool HasCopyright { get; set; } [ControlNumeric(LabelText = "Giá nhập", Required = true, ContainerCssClass = Constants.ContainerCssClassCol3, ContainerRowIndex = 6)] public float Prices { get; set; } [ControlChoice(ControlChoice.CheckBox, LabelText = "", PrependText = "Xuất bản", ContainerCssClass = Constants.ContainerCssClassCol3, ContainerRowIndex = 6)] public bool IsPublished { get; set; } [ControlDatePicker(LabelText = "Ngày xuất bản", ContainerCssClass = Constants.ContainerCssClassCol3, ContainerRowIndex = 6)] public string PublishedDate { get; set; } [ControlChoice(ControlChoice.CheckBox, LabelText = "", PrependText = "Phim hot", ContainerCssClass = Constants.ContainerCssClassCol3, ContainerRowIndex = 7)] public bool IsHot { get; set; } [ControlDatePicker(LabelText = "Từ ngày", ContainerCssClass = Constants.ContainerCssClassCol3, ContainerRowIndex = 7)] public string StartDate { get; set; } [ControlDatePicker(LabelText = "Đến ngày", ContainerCssClass = Constants.ContainerCssClassCol3, ContainerRowIndex = 7)] public string EndDate { get; set; } [ControlChoice(ControlChoice.DropDownList, LabelText = "Trạng thái", ContainerCssClass = Constants.ContainerCssClassCol3, ContainerRowIndex = 7)] public int Status { get; set; } [ControlText(LabelText = "Tóm tắt phim", PlaceHolder = "Tối đa 400 ký tự.", Type = ControlText.MultiText, Rows = 3, Required = true, MaxLength = 400, ContainerCssClass = Constants.ContainerCssClassCol12, ContainerRowIndex = 8)] public string Summary { get; set; } [ControlText(LabelText = "Nội dung phim", Required = true, Type = ControlText.RichText, ContainerCssClass = Constants.ContainerCssClassCol12, ContainerRowIndex = 9)] public string Contents { get; set; } [ControlText(LabelText = "Từ khóa SEO", Required = true, PlaceHolder = "Tối đa 400 ký tự.", Type = ControlText.MultiText, Rows = 2, MaxLength = 400, ContainerCssClass = Constants.ContainerCssClassCol6, ContainerRowIndex = 10)] public string Description { get; set; } [ControlText(LabelText = "Tags SEO", Required = true, PlaceHolder = "Nhập từ khóa SEO cách nhau bởi dấu ','và tối đa 250 ký tự.", Type = ControlText.MultiText, Rows = 2, MaxLength = 250, ContainerCssClass = Constants.ContainerCssClassCol6, ContainerRowIndex = 10)] public string Tags { get; set; } public static implicit operator FilmModel(FilmInfo entity) { var item = new FilmModel { Id = entity.Id, FilmNameEnglish = entity.FilmNameEnglish, FilmName = entity.FilmName, FilmAlias = entity.FilmAlias, LanguageCode = entity.LanguageCode, SiteId = entity.SiteId, CategoryIds = Utilities.ParseListInt(entity.CategoryIds), FilmTypeIds = Utilities.ParseListInt(entity.FilmTypeIds), CountryId = entity.CountryId, DirectorId = entity.DirectorId, ActorIds = Utilities.ParseListInt(entity.ActorIds), CollectionId = entity.CollectionId, Time = entity.Time, Capacity = entity.Capacity, ReleaseYear = entity.ReleaseYear, Contents = entity.Contents, Summary = entity.Summary, Description = entity.Description, Tags = entity.Tags, IsPublished = entity.IsPublished, IsHot = entity.IsHot, IsHome = entity.IsHome, Prices = (float)entity.Prices, HasCopyright = entity.HasCopyright, ImageIcon = entity.ImageIcon, ImageThumb = entity.ImageThumb, ServerId = entity.ServerId, Status = entity.Status, IsTheater = entity.IsTheater }; if (entity.IsFilm) { item.VideoType = (int)VideoTypes.IsFilm; } if (entity.IsShow) { item.VideoType = (int)VideoTypes.IsShow; } if (entity.IsClip) { item.VideoType = (int)VideoTypes.IsClip; } if (entity.IsTrailer) { item.VideoType = (int)VideoTypes.IsTrailer; } if (entity.PublishedDate != null && entity.PublishedDate.Value.ToString(Extensions.Constants.DateTimeFomat) != Extensions.Constants.DateTimeMin) { item.PublishedDate = entity.PublishedDate.Value.ToString(Extensions.Constants.DateTimeFomat); } if (entity.StartDate != null && entity.StartDate.Value.ToString(Extensions.Constants.DateTimeFomat) != Extensions.Constants.DateTimeMin) { item.StartDate = entity.StartDate.Value.ToString(Extensions.Constants.DateTimeFomat); } if (entity.EndDate != null && entity.EndDate.Value.ToString(Extensions.Constants.DateTimeFomat) != Extensions.Constants.DateTimeMin) { item.EndDate = entity.EndDate.Value.ToString(Extensions.Constants.DateTimeFomat); } return item; } } } <file_sep>using System.Collections.Generic; using System.Data.SqlClient; using CMSSolutions.Data; using CMSSolutions.Events; using CMSSolutions.Services; using CMSSolutions.Websites.Entities; namespace CMSSolutions.Websites.Services { public interface IDownloadGameService : IGenericService<DownloadGameInfo, int>, IDependency { IList<DownloadGameInfo> SearchPaged(string keyword, int pageIndex, int pageSize, out int totalRecord); List<DownloadGameInfo> GetPaged(int pageIndex, int pageSize, out int totalRecord); } public class DownloadGameService : GenericService<DownloadGameInfo, int>, IDownloadGameService { public DownloadGameService(IRepository<DownloadGameInfo, int> repository, IEventBus eventBus) : base(repository, eventBus) { } public IList<DownloadGameInfo> SearchPaged(string keyword, int pageIndex, int pageSize, out int totalRecord) { var list = new List<SqlParameter> { AddInputParameter("@Keyword", keyword), AddInputParameter("@PageIndex", pageIndex), AddInputParameter("@PageSize", pageSize) }; return ExecuteReader<DownloadGameInfo>("sp_DownloadGames_Search_Paged", "@TotalRecord", out totalRecord, list.ToArray()); } public List<DownloadGameInfo> GetPaged(int pageIndex, int pageSize, out int totalRecord) { var list = new List<SqlParameter> { AddInputParameter("@PageIndex", pageIndex), AddInputParameter("@PageSize", pageSize) }; return ExecuteReader<DownloadGameInfo>("sp_DownloadGames_GetPaged", "@TotalRecord", out totalRecord, list.ToArray()); } } }<file_sep>using System; using System.Collections.Generic; using System.Data.SqlClient; using CMSSolutions.Caching; using CMSSolutions.Data; using CMSSolutions.Events; using CMSSolutions.Services; using CMSSolutions.Websites.Entities; namespace CMSSolutions.Websites.Services { public interface IArticlesService : ICacheService<ArticlesInfo, int>, IGenericService<ArticlesInfo, int>, IDependency { bool CheckAlias(string alias); string LanguageCode { get; set; } int CategoryId { get; set; } int SiteId { get; set; } List<ArticlesInfo> SearchPaged( string searchText, int siteId, int userId, DateTime fromDate, DateTime toDate, int status, int pageIndex, int pageSize, out int totalRecord); IList<ArticlesInfo> BuildNewsByCategory(); IList<ArticlesInfo> GetByCategory(); IList<ArticlesInfo> GetByCategoryPaged(int pageIndex, int pageSize, out int totalRecord); } public class ArticlesService : GenericService<ArticlesInfo, int>, IArticlesService { private readonly ICacheInfo cacheManager; public string LanguageCode { get; set; } public int CategoryId { get; set; } public int SiteId { get; set; } public ArticlesService( IRepository<ArticlesInfo, int> repository, IEventBus eventBus, ICacheInfo cacheManager) : base(repository, eventBus) { this.cacheManager = cacheManager; } public bool CheckAlias(string alias) { var list = new List<SqlParameter> { AddInputParameter("@Alias", alias) }; var result = (int)ExecuteReaderResult("sp_Articles_CheckAlias", list.ToArray()); return result > 0; } public List<ArticlesInfo> SearchPaged(string searchText, int siteId, int userId, DateTime fromDate, DateTime toDate, int status, int pageIndex, int pageSize, out int totalRecord) { var list = new List<SqlParameter> { AddInputParameter("@SearchText", searchText), AddInputParameter("@SiteId", siteId), AddInputParameter("@CategoryId", CategoryId), AddInputParameter("@UserId", userId), AddInputParameter("@LanguageCode", LanguageCode), AddInputParameter("@FromDate", fromDate), AddInputParameter("@Todate", toDate), AddInputParameter("@Status", status), AddInputParameter("@PageIndex", pageIndex), AddInputParameter("@PageSize", pageSize) }; return ExecuteReader<ArticlesInfo>("sp_Articles_Search_Paged", "@TotalRecord", out totalRecord, list.ToArray()); } public IList<ArticlesInfo> GetByCategory() { var list = new List<SqlParameter> { AddInputParameter("@SiteId", SiteId), AddInputParameter("@LanguageCode", LanguageCode), AddInputParameter("@CategoryId", CategoryId) }; return ExecuteReader<ArticlesInfo>("sp_Articles_GetByCategory", list.ToArray()); } public IList<ArticlesInfo> GetByCategoryPaged(int pageIndex, int pageSize, out int totalRecord) { var list = new List<SqlParameter> { AddInputParameter("@SiteId", SiteId), AddInputParameter("@LanguageCode", LanguageCode), AddInputParameter("@CategoryId", CategoryId), AddInputParameter("@PageIndex", pageIndex), AddInputParameter("@PageSize", pageSize) }; return ExecuteReader<ArticlesInfo>("sp_Articles_GetByCategory_Paged", "@TotalRecord", out totalRecord, list.ToArray()); } public IList<ArticlesInfo> BuildNewsByCategory() { var list = cacheManager.Get(string.Format(Extensions.Constants.CacheKeys.HOME_CATEGORY_ID, CategoryId)); if (list == null) { list = ResetCache(); } return (IList<ArticlesInfo>)list; } public ArticlesInfo GetByIdCache(int id) { throw new NotImplementedException(); } public IList<ArticlesInfo> GetAllCache() { throw new NotImplementedException(); } public IList<ArticlesInfo> ResetCache() { cacheManager.Remove(string.Format(Extensions.Constants.CacheKeys.HOME_CATEGORY_ID, CategoryId)); var list = GetByCategory(); cacheManager.Add(string.Format(Extensions.Constants.CacheKeys.HOME_CATEGORY_ID, CategoryId), list); return list; } } } <file_sep>using System; using System.ComponentModel; using System.ComponentModel.DataAnnotations.Schema; using System.Runtime.Serialization; using CMSSolutions.Data; using CMSSolutions.Data.Entity; namespace CMSSolutions.Websites.Entities { [DataContract] public class CustomerInfo : BaseEntity<int> { [DataMember] [DisplayName("CustomerCode")] public string CustomerCode { get; set; } [DataMember] [DisplayName("UserName")] public string UserName { get; set; } [DataMember] [DisplayName("Password")] public string Password { get; set; } [DataMember] [DisplayName("FullName")] public string FullName { get; set; } [DataMember] [DisplayName("Email")] public string Email { get; set; } [DataMember] [DisplayName("Address")] public string Address { get; set; } [DataMember] [DisplayName("PhoneNumber")] public string PhoneNumber { get; set; } [DataMember] [DisplayName("CityId")] public string CityId { get; set; } [DataMember] [DisplayName("Birthday")] public System.DateTime Birthday { get; set; } [DataMember] [DisplayName("Sex")] public int Sex { get; set; } [DataMember] [DisplayName("ImageIcon")] public string ImageIcon { get; set; } [DataMember] [DisplayName("FilmTypeIds")] public string FilmTypeIds { get; set; } [DataMember] [DisplayName("CountryIds")] public string CountryIds { get; set; } [DataMember] [DisplayName("MemberDate")] public System.DateTime MemberDate { get; set; } [DataMember] [DisplayName("Skype")] public string Skype { get; set; } [DataMember] [DisplayName("ZingMe")] public string ZingMe { get; set; } [DataMember] [DisplayName("Facebook")] public string Facebook { get; set; } [DataMember] [DisplayName("Google")] public string Google { get; set; } [DataMember] [DisplayName("Yahoo")] public string Yahoo { get; set; } [DataMember] [DisplayName("VipXu")] public decimal VipXu { get; set; } [DataMember] [DisplayName("TotalMoney")] public decimal TotalMoney { get; set; } [DataMember] [DisplayName("IsBlock")] public bool IsBlock { get; set; } [DataMember] [DisplayName("Status")] public int Status { get; set; } [DataMember] [DisplayName("Description")] public string Description { get; set; } [DataMember] [DisplayName("TotalDay")] public int TotalDay { get; set; } [DataMember] [DisplayName("StartDate")] public DateTime? StartDate { get; set; } [NotMapped] [DisplayName(Constants.NotMapped)] public string TextStartDate { get { if (StartDate == null) { return ""; } return StartDate.Value.ToString(Extensions.Constants.DateTimeFomatFull); } } [DataMember] [DisplayName("EndDate")] public DateTime? EndDate { get; set; } [NotMapped] [DisplayName(Constants.NotMapped)] public string TextEndDate { get { if (EndDate == null) { return ""; } return EndDate.Value.ToString(Extensions.Constants.DateTimeFomatFull); } } [DataMember] [DisplayName("IsTest")] public bool IsTest { get; set; } } public class CustomerMap : EntityTypeConfiguration<CustomerInfo>, IEntityTypeConfiguration { public CustomerMap() { ToTable("Modules_Customers"); HasKey(m => m.Id); Property(m => m.CustomerCode).IsRequired().HasMaxLength(250); Property(m => m.UserName).IsRequired().HasMaxLength(50); Property(m => m.Password).IsRequired().HasMaxLength(500); Property(m => m.FullName).IsRequired().HasMaxLength(250); Property(m => m.Email).IsRequired().HasMaxLength(50); Property(m => m.Address).HasMaxLength(2000); Property(m => m.PhoneNumber).HasMaxLength(50); Property(m => m.CityId).HasMaxLength(250); Property(m => m.ImageIcon).IsRequired().HasMaxLength(300); Property(m => m.FilmTypeIds).HasMaxLength(2000); Property(m => m.CountryIds).HasMaxLength(2000); Property(m => m.MemberDate).IsRequired(); Property(m => m.Skype).HasMaxLength(50); Property(m => m.ZingMe).HasMaxLength(50); Property(m => m.Facebook).HasMaxLength(50); Property(m => m.Google).HasMaxLength(50); Property(m => m.Yahoo).HasMaxLength(50); Property(m => m.IsBlock).IsRequired(); Property(m => m.Description).HasMaxLength(500); } } } <file_sep>using System; using System.ComponentModel; using System.ComponentModel.DataAnnotations.Schema; using System.Runtime.Serialization; using CMSSolutions.Data; using CMSSolutions.Data.Entity; namespace CMSSolutions.Websites.Entities { [DataContract] public class TransactionBankInfo : BaseEntity<long> { [DataMember] [DisplayName("CustomerCode")] public string CustomerCode { get; set; } [DataMember] [DisplayName("TransactionCode")] public string TransactionCode { get; set; } [DataMember] [DisplayName("CreateDate")] public DateTime CreateDate { get; set; } [NotMapped] [DisplayName(Constants.NotMapped)] public string TextStartDate { get { return CreateDate.ToString(Extensions.Constants.DateTimeFomatFull); } } [DataMember] [DisplayName("BankCode")] public string BankCode { get; set; } [NotMapped] [DisplayName("BankName")] public string BankName { get; set; } [DataMember] [DisplayName("Amount")] public string Amount { get; set; } [DataMember] [DisplayName("ResponCode")] public string ResponCode { get; set; } [DataMember] [DisplayName("Mac")] public string Mac { get; set; } [DataMember] [DisplayName("TransId")] public string TransId { get; set; } [DataMember] [DisplayName("Type")] public int Type { get; set; } [DataMember] [DisplayName("Description")] public string Description { get; set; } [DataMember] [DisplayName("Status")] public int Status { get; set; } [DataMember] [DisplayName("IsLock")] public bool IsLock { get; set; } [NotMapped] [DisplayName("FullName")] public string FullName { get; set; } } public class TransactionBankMap : EntityTypeConfiguration<TransactionBankInfo>, IEntityTypeConfiguration { public TransactionBankMap() { ToTable("Modules_TransactionBank"); HasKey(m => m.Id); Property(m => m.CustomerCode).HasMaxLength(50); Property(m => m.TransactionCode).HasMaxLength(250); Property(m => m.BankCode).HasMaxLength(50); Property(m => m.Amount).HasMaxLength(250); Property(m => m.ResponCode).HasMaxLength(100); Property(m => m.Mac).HasMaxLength(250); Property(m => m.TransId).HasMaxLength(250); Property(m => m.Description).HasMaxLength(2000); } } }<file_sep>using System; using System.IO; using System.Net; using System.Text; namespace CMSSolutions.Websites.Extensions { public class FTPClient { public string ServerIP { get; set; } public string UserName { get; set; } public string Password { get; set; } public int BufferSize { get; set; } public FTPClient() { BufferSize = 2048; } public FTPClient(string hostIP, string userName, string password) { ServerIP = hostIP; UserName = userName; Password = <PASSWORD>; BufferSize = 2048; } private string GetUrl(string path) { return "ftp://" + ServerIP + "/" + path; } public void Download(string remoteFile, string localFile) { try { var ftpRequest = (FtpWebRequest)WebRequest.Create(GetUrl(remoteFile)); ftpRequest.Credentials = new NetworkCredential(UserName, Password); ftpRequest.UseBinary = true; ftpRequest.UsePassive = true; ftpRequest.KeepAlive = true; ftpRequest.Method = WebRequestMethods.Ftp.DownloadFile; var ftpResponse = (FtpWebResponse)ftpRequest.GetResponse(); Stream ftpStream = ftpResponse.GetResponseStream(); if (ftpStream != null) { var localFileStream = new FileStream(localFile, FileMode.Create); var byteBuffer = new byte[BufferSize]; int bytesRead = ftpStream.Read(byteBuffer, 0, BufferSize); while (bytesRead > 0) { localFileStream.Write(byteBuffer, 0, bytesRead); bytesRead = ftpStream.Read(byteBuffer, 0, BufferSize); } localFileStream.Close(); ftpStream.Close(); } ftpResponse.Close(); } catch (Exception ex) { throw ex; } } public void Upload(string remoteFile, string localFile) { try { var ftpRequest = (FtpWebRequest)WebRequest.Create(GetUrl(remoteFile)); ftpRequest.Credentials = new NetworkCredential(UserName, Password); ftpRequest.UseBinary = true; ftpRequest.UsePassive = true; ftpRequest.KeepAlive = true; ftpRequest.Method = WebRequestMethods.Ftp.UploadFile; Stream ftpStream = ftpRequest.GetRequestStream(); if (ftpStream != null) { var localFileStream = new FileStream(localFile, FileMode.Create); var byteBuffer = new byte[BufferSize]; int bytesSent = localFileStream.Read(byteBuffer, 0, BufferSize); while (bytesSent != 0) { ftpStream.Write(byteBuffer, 0, bytesSent); bytesSent = localFileStream.Read(byteBuffer, 0, BufferSize); } localFileStream.Close(); ftpStream.Close(); } } catch (Exception ex) { throw ex; } } public void Delete(string deleteFile) { try { var ftpRequest = (FtpWebRequest)WebRequest.Create(GetUrl(deleteFile)); ftpRequest.Credentials = new NetworkCredential(UserName, Password); ftpRequest.UseBinary = true; ftpRequest.UsePassive = true; ftpRequest.KeepAlive = true; ftpRequest.Method = WebRequestMethods.Ftp.DeleteFile; var ftpResponse = (FtpWebResponse)ftpRequest.GetResponse(); ftpResponse.Close(); } catch (Exception ex) { throw ex; } } public void Rename(string currentFileNameAndPath, string newFileName) { try { var ftpRequest = (FtpWebRequest)WebRequest.Create(GetUrl(currentFileNameAndPath)); ftpRequest.Credentials = new NetworkCredential(UserName, Password); ftpRequest.UseBinary = true; ftpRequest.UsePassive = true; ftpRequest.KeepAlive = true; ftpRequest.Method = WebRequestMethods.Ftp.Rename; ftpRequest.RenameTo = newFileName; var ftpResponse = (FtpWebResponse)ftpRequest.GetResponse(); ftpResponse.Close(); } catch (Exception ex) { throw ex; } } public void CreateDirectory(string newDirectory) { try { var ftpRequest = (FtpWebRequest)WebRequest.Create(GetUrl(newDirectory)); ftpRequest.Credentials = new NetworkCredential(UserName, Password); ftpRequest.UseBinary = true; ftpRequest.UsePassive = true; ftpRequest.KeepAlive = true; ftpRequest.Method = WebRequestMethods.Ftp.MakeDirectory; var ftpResponse = (FtpWebResponse)ftpRequest.GetResponse(); ftpResponse.Close(); } catch (Exception ex) { throw ex; } } public string GetFileCreatedDateTime(string fileName) { try { var ftpRequest = (FtpWebRequest)WebRequest.Create(GetUrl(fileName)); ftpRequest.Credentials = new NetworkCredential(UserName, Password); ftpRequest.UseBinary = true; ftpRequest.UsePassive = true; ftpRequest.KeepAlive = true; ftpRequest.Method = WebRequestMethods.Ftp.GetDateTimestamp; var ftpResponse = (FtpWebResponse)ftpRequest.GetResponse(); Stream ftpStream = ftpResponse.GetResponseStream(); if (ftpStream != null) { var ftpReader = new StreamReader(ftpStream); string fileInfo = ftpReader.ReadToEnd(); ftpReader.Close(); ftpStream.Close(); ftpResponse.Close(); return fileInfo; } ftpResponse.Close(); return string.Empty; } catch (Exception ex) { throw ex; } } public string GetFileSize(string fileName) { try { var ftpRequest = (FtpWebRequest)WebRequest.Create(GetUrl(fileName)); ftpRequest.Credentials = new NetworkCredential(UserName, Password); ftpRequest.UseBinary = true; ftpRequest.UsePassive = true; ftpRequest.KeepAlive = true; ftpRequest.Method = WebRequestMethods.Ftp.GetFileSize; var ftpResponse = (FtpWebResponse)ftpRequest.GetResponse(); Stream ftpStream = ftpResponse.GetResponseStream(); if (ftpStream != null) { var ftpReader = new StreamReader(ftpStream); string fileInfo = null; while (ftpReader.Peek() != -1) { fileInfo = ftpReader.ReadToEnd(); } ftpReader.Close(); ftpStream.Close(); ftpResponse.Close(); return fileInfo; } ftpResponse.Close(); return string.Empty; } catch (Exception ex) { throw ex; } } public string[] DirectoryList(string directory) { try { var ftpRequest = (FtpWebRequest)WebRequest.Create(GetUrl(directory)); ftpRequest.Credentials = new NetworkCredential(UserName, Password); ftpRequest.UseBinary = true; ftpRequest.UsePassive = true; ftpRequest.KeepAlive = true; ftpRequest.Method = WebRequestMethods.Ftp.ListDirectory; var ftpResponse = (FtpWebResponse)ftpRequest.GetResponse(); Stream ftpStream = ftpResponse.GetResponseStream(); if (ftpStream != null) { var ftpReader = new StreamReader(ftpStream); string directoryRaw = null; while (ftpReader.Peek() != -1) { directoryRaw += ftpReader.ReadLine() + "|"; } ftpReader.Close(); ftpStream.Close(); ftpResponse.Close(); if (directoryRaw != null) { return directoryRaw.Split("|".ToCharArray()); } } ftpResponse.Close(); return new[] { "" }; } catch (Exception ex) { throw ex; } } public string[] DirectoryListDetailed(string directory) { try { var ftpRequest = (FtpWebRequest)WebRequest.Create(GetUrl(directory)); ftpRequest.Credentials = new NetworkCredential(UserName, Password); ftpRequest.UseBinary = true; ftpRequest.UsePassive = true; ftpRequest.KeepAlive = true; ftpRequest.Method = WebRequestMethods.Ftp.ListDirectoryDetails; var ftpResponse = (FtpWebResponse)ftpRequest.GetResponse(); Stream ftpStream = ftpResponse.GetResponseStream(); if (ftpStream != null) { var ftpReader = new StreamReader(ftpStream); string directoryRaw = null; while (ftpReader.Peek() != -1) { directoryRaw += ftpReader.ReadLine() + "|"; } ftpReader.Close(); ftpStream.Close(); ftpResponse.Close(); if (directoryRaw != null) { string[] directoryList = directoryRaw.Split("|".ToCharArray()); return directoryList; } } ftpResponse.Close(); return new[] { "" }; } catch (Exception ex) { throw ex; } } } }<file_sep>using System.Collections.Generic; using System.Data.SqlClient; using System.Linq; using CMSSolutions.Data; using CMSSolutions.Events; using CMSSolutions.Services; using CMSSolutions.Websites.Entities; namespace CMSSolutions.Websites.Services { public interface IBankCardService : IGenericService<BankCardInfo, int>, IDependency { IList<BankCardInfo> GetPaged(int status, int pageIndex, int pageSize, out int totals); BankCardInfo GetByCode(string code); } public class BankCardService : GenericService<BankCardInfo, int>, IBankCardService { public BankCardService(IRepository<BankCardInfo, int> repository, IEventBus eventBus) : base(repository, eventBus) { } public IList<BankCardInfo> GetPaged(int status, int pageIndex, int pageSize, out int totals) { var results = Repository.Table.Where(x => x.Status == status).ToList(); { totals = results.Count(); return (from x in results select x).Skip((pageIndex - 1) * pageSize).Take(pageSize).ToList(); } } public BankCardInfo GetByCode(string code) { var list = new List<SqlParameter> { AddInputParameter("@Code", code) }; return ExecuteReaderRecord<BankCardInfo>("sp_BankCards_GetByCode", list.ToArray()); } } } <file_sep>using System; using System.Collections.Generic; using System.Data.SqlClient; using System.Linq; using CMSSolutions.Data; using CMSSolutions.Events; using CMSSolutions.Services; using CMSSolutions.Websites.Entities; namespace CMSSolutions.Websites.Services { public interface ILogService : IGenericService<LogInfo, long>, IDependency { IList<LogInfo> GetPaged(string keyword, DateTime fromDate, DateTime toDate, int type, int status, int pageIndex, int pageSize, out int totals); } public class LogService : GenericService<LogInfo, long>, ILogService { public LogService(IRepository<LogInfo, long> repository, IEventBus eventBus) : base(repository, eventBus) { } protected override IOrderedQueryable<LogInfo> MakeDefaultOrderBy(IQueryable<LogInfo> queryable) { return queryable.OrderByDescending(x => x.CreateDate); } public IList<LogInfo> GetPaged(string keyword, DateTime fromDate, DateTime toDate, int type, int status, int pageIndex, int pageSize, out int totals) { var list = new List<SqlParameter> { AddInputParameter("@SearchText", keyword), AddInputParameter("@FromDate", fromDate), AddInputParameter("@ToDate", toDate), AddInputParameter("@Type", type), AddInputParameter("@Status", status), AddInputParameter("@PageIndex", pageIndex), AddInputParameter("@PageSize", pageSize) }; return ExecuteReader<LogInfo>("sp_Logs_Search_Paged", "@TotalRecord", out totals, list.ToArray()); } } }<file_sep>using System; using System.Collections.Generic; using System.Data.SqlClient; using CMSSolutions.Data; using CMSSolutions.Events; using CMSSolutions.Services; using CMSSolutions.Websites.Entities; namespace CMSSolutions.Websites.Services { public interface IAdvertisementService : IGenericService<AdvertisementInfo, int>, IDependency { List<AdvertisementInfo> SearchPaged( string searchText, string languageCode, int siteId, DateTime fromDate, DateTime toDate, int pageIndex, int pageSize, out int totalRecord); List<AdvertisementInfo> GetAdBySite(string languageCode, int siteId); } public class AdvertisementService : GenericService<AdvertisementInfo, int>, IAdvertisementService { public AdvertisementService(IRepository<AdvertisementInfo, int> repository, IEventBus eventBus) : base(repository, eventBus) { } public List<AdvertisementInfo> SearchPaged(string searchText, string languageCode, int siteId, DateTime fromDate, DateTime toDate, int pageIndex, int pageSize, out int totalRecord) { var list = new List<SqlParameter> { AddInputParameter("@SearchText", searchText), AddInputParameter("@LanguageCode", languageCode), AddInputParameter("@SiteId", siteId), AddInputParameter("@FromDate", fromDate), AddInputParameter("@Todate", toDate), AddInputParameter("@PageIndex", pageIndex), AddInputParameter("@PageSize", pageSize) }; return ExecuteReader<AdvertisementInfo>("sp_Advertisement_Search_Paged", "@TotalRecord", out totalRecord, list.ToArray()); } public List<AdvertisementInfo> GetAdBySite(string languageCode, int siteId) { var list = new List<SqlParameter> { AddInputParameter("@LanguageCode", languageCode), AddInputParameter("@SiteId", siteId) }; return ExecuteReader<AdvertisementInfo>("sp_Advertisement_GetAdBySite", list.ToArray()); } } }<file_sep>using CMSSolutions.Web.UI.ControlForms; using CMSSolutions.Websites.Extensions; namespace CMSSolutions.Websites.Models { public class PromotionCustomersModel { public PromotionCustomersModel() { Code = Utilities.GenerateUniqueNumber(); Value = 50; } [ControlHidden] public int PromotionId { get; set; } [ControlText(Type = ControlText.TextBox, Required = true, MaxLength = 50, LabelText = "Chương trình khuyến mãi", ContainerCssClass = Constants.ContainerCssClassCol12, ContainerRowIndex = 0)] public string PromotionName { get; set; } [ControlText(Type = ControlText.TextBox, Required = true, MaxLength = 50, LabelText = "Mã khuyến mãi", ContainerCssClass = Constants.ContainerCssClassCol6, ContainerRowIndex = 1)] public string Code { get; set; } [ControlNumeric(LabelText = "Giá trị khuyến mãi (VIPXU)", MinimumValue = "50", Required = true, ContainerCssClass = Constants.ContainerCssClassCol6, ContainerRowIndex = 1)] public int Value { get; set; } [ControlChoice(ControlChoice.DropDownList, AllowMultiple = true, CssClass = Extensions.Constants.CssControlCustom, EnableChosen = true, Required = true, LabelText = "Chọn khách hàng", ContainerCssClass = Constants.ContainerCssClassCol12, ContainerRowIndex = 2)] public int[] CustomerIds { get; set; } } }<file_sep>using System.ComponentModel; using System.Runtime.Serialization; using CMSSolutions.Data; using CMSSolutions.Data.Entity; namespace CMSSolutions.Websites.Entities { /// <summary> /// Bộ phim /// </summary> [DataContract] public class CollectionInfo : BaseEntity<int> { [DataMember] [DisplayName("LanguageCode")] public string LanguageCode { get; set; } [DataMember] [DisplayName("SiteId")] public int SiteId { get; set; } [DataMember] [DisplayName("Name")] public string Name { get; set; } [DataMember] [DisplayName("IsHost")] public bool IsHot { get; set; } [DataMember] [DisplayName("OrderBy")] public int OrderBy { get; set; } [DataMember] [DisplayName("Description")] public string Description { get; set; } [DataMember] [DisplayName("Status")] public int Status { get; set; } } public class CollectionMap : EntityTypeConfiguration<CollectionInfo>, IEntityTypeConfiguration { public CollectionMap() { ToTable("Modules_Collections"); HasKey(m => m.Id); Property(m => m.LanguageCode).IsRequired().HasMaxLength(50); Property(m => m.SiteId).IsRequired(); Property(m => m.Name).IsRequired().HasMaxLength(250); Property(m => m.Description).HasMaxLength(2000); } } } <file_sep>using CMSSolutions.Web.UI.ControlForms; using CMSSolutions.Websites.Entities; namespace CMSSolutions.Websites.Models { public class FilmTypesModel { [ControlHidden] public int Id { get; set; } [ControlChoice(ControlChoice.DropDownList, Required = true, LabelText = "Ngôn ngữ hiển thị", ContainerCssClass = Constants.ContainerCssClassCol4, ContainerRowIndex = 0)] public string LanguageCode { get; set; } [ControlCascadingDropDown(LabelText = "Trang web", Required = true, ParentControl = "LanguageCode", AbsoluteParentControl = true, ContainerCssClass = Constants.ContainerCssClassCol4, ContainerRowIndex = 1)] public int SiteId { get; set; } [ControlText(Type = ControlText.TextBox, Required = true, MaxLength = 250, LabelText = "Tên thể loại phim", ContainerCssClass = Constants.ContainerCssClassCol4, ContainerRowIndex = 2)] public string Name { get; set; } [ControlChoice(ControlChoice.CheckBox, LabelText = "", PrependText = "Phim trang chủ", ContainerCssClass = Constants.ContainerCssClassCol3, ContainerRowIndex = 3)] public bool IsFilm { get; set; } [ControlChoice(ControlChoice.CheckBox, LabelText = "", PrependText = "Show", ContainerCssClass = Constants.ContainerCssClassCol3, ContainerRowIndex = 3)] public bool IsShow { get; set; } [ControlChoice(ControlChoice.CheckBox, LabelText = "", PrependText = "Clip", ContainerCssClass = Constants.ContainerCssClassCol3, ContainerRowIndex = 3)] public bool IsClip { get; set; } [ControlChoice(ControlChoice.CheckBox, LabelText = "", PrependText = "Phim trang JJ", ContainerCssClass = Constants.ContainerCssClassCol3, ContainerRowIndex = 3)] public bool IsJJFilm { get; set; } [ControlChoice(ControlChoice.DropDownList, LabelText = "Trạng thái", ContainerCssClass = Constants.ContainerCssClassCol4, ContainerRowIndex = 3)] public int Status { get; set; } [ControlText(Type = ControlText.MultiText, Rows = 2, MaxLength = 2000, LabelText = "Giới thiệu", ContainerCssClass = Constants.ContainerCssClassCol12, ContainerRowIndex = 4)] public string Description { get; set; } public static implicit operator FilmTypesModel(FilmTypesInfo entity) { return new FilmTypesModel { Id = entity.Id, LanguageCode = entity.LanguageCode, SiteId = entity.SiteId, Name = entity.Name, Description = entity.Description, Status = entity.Status, IsFilm = entity.IsFilm, IsShow = entity.IsShow, IsClip = entity.IsClip, IsJJFilm = entity.IsJJFilm }; } } } <file_sep>using System.Collections.Generic; using System.Linq; using CMSSolutions.Data; using CMSSolutions.Events; using CMSSolutions.Services; using CMSSolutions.Websites.Entities; namespace CMSSolutions.Websites.Services { public interface IFilmServersService : IGenericService<FilmServerInfo, int>, IDependency { IList<FilmServerInfo> GetPaged(string languageCode, int siteId, int status, int pageIndex, int pageSize, out int totals); } public class FilmServersService : GenericService<FilmServerInfo, int>, IFilmServersService { public FilmServersService(IRepository<FilmServerInfo, int> repository, IEventBus eventBus) : base(repository, eventBus) { } public IList<FilmServerInfo> GetPaged(string languageCode, int siteId, int status, int pageIndex, int pageSize, out int totals) { var results = Repository.Table.Where(x => x.Status == status && x.LanguageCode == languageCode && x.SiteId == siteId).ToList(); { totals = results.Count(); return (from x in results select x).Skip((pageIndex - 1) * pageSize).Take(pageSize).ToList(); } } } } <file_sep>function dialogBox(id) { $(id).fadeIn("slow"); $('body').append('<div id="over"></div>'); $('#over').fadeIn(300); } $(document).ready(function () { $(document).on('click', "a.close-reveal-modal, #over", function () { $('#over, .reveal-modal').fadeOut(300, function () { $('#over').remove(); }); return false; }); }); <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Web.Mvc; using CMSSolutions.Configuration; using CMSSolutions.Security.Cryptography; using CMSSolutions.Web.Mvc; using CMSSolutions.Web.Routing; using CMSSolutions.Web.Security; using CMSSolutions.Web.Themes; using CMSSolutions.Web.UI.ControlForms; using CMSSolutions.Web.UI.Navigation; using CMSSolutions.Websites.Entities; using CMSSolutions.Websites.Extensions; using CMSSolutions.Websites.Models; using CMSSolutions.Websites.Services; namespace CMSSolutions.Websites.Controllers { [Themed(IsDashboard = true), Authorize] public class FilmFilesController : BaseAdminController { public FilmFilesController(IWorkContextAccessor workContextAccessor) : base(workContextAccessor) { TableName = "tblVideoFiles"; } [Url("admin/video-files")] public ActionResult Index() { WorkContext.Breadcrumbs.Add(new Breadcrumb { Text = T("Quản lý video files"), Url = "#" }); var result = new ControlGridFormResult<FilmFilesInfo> { Title = T("Quản lý video files"), CssClass = "table table-bordered table-striped", IsAjaxSupported = true, FetchAjaxSource = GetFilmFiles, DefaultPageSize = WorkContext.DefaultPageSize, EnablePaginate = true, UpdateActionName = "Update", GridWrapperStartHtml = Constants.Grid.GridWrapperStartHtml, GridWrapperEndHtml = Constants.Grid.GridWrapperEndHtml, ClientId = TableName, ActionsColumnWidth = 100 }; result.AddCustomVar(Extensions.Constants.LanguageCode, "$('#" + Extensions.Constants.LanguageCode + "').val();", true); result.AddCustomVar(Extensions.Constants.SiteId, "$('#" + Extensions.Constants.SiteId + "').val();", true); result.AddCustomVar(Extensions.Constants.StatusId, "$('#" + Extensions.Constants.ServerId + "').val();", true); result.AddColumn(x => x.Name, T("Tên file")); result.AddColumn(x => x.FullPath, T("Đường dẫn đầy đủ")); result.AddColumn(x => x.ServerName, T("Máy chủ")); result.AddColumn(x => x.DisplayDate, T("Ngày tạo")).HasWidth(100); result.AddColumn(x => x.Size, T("Kích thước")).HasWidth(100).AlignCenter(); result.AddColumn(x => x.HasUse, T("Sử dụng")) .HasHeaderText(T("Sử dụng")) .AlignCenter() .HasWidth(100) .RenderAsStatusImage(); result.AddAction().HasText(T("Đồng bộ videos")) .HasUrl(Url.Action("RefreshVideos")) .HasButtonStyle(ButtonStyle.Primary) .HasBoxButton(false) .HasRow(false) .HasCssClass(Constants.RowLeft) .HasRow(true) .ShowModalDialog(); result.AddAction(new ControlFormHtmlAction(() => BuildLanguages(true, Extensions.Constants.SiteId))).HasParentClass(Constants.ContainerCssClassCol3); result.AddAction(new ControlFormHtmlAction(() => BuildSiteServers(true, Extensions.Constants.ServerId))).HasParentClass(Constants.ContainerCssClassCol3); result.AddAction(new ControlFormHtmlAction(BuildServers)).HasParentClass(Constants.ContainerCssClassCol3); result.AddRowAction() .HasText(T("Xem")) .HasUrl(x => Url.Action("Edit", RouteData.Values.Merge(new { id = x.Id }))) .HasButtonStyle(ButtonStyle.Default) .HasButtonSize(ButtonSize.ExtraSmall); //result.AddRowAction(true) // .HasText(T("Xóa")) // .HasName("Delete") // .HasValue(x => x.Id) // .HasButtonStyle(ButtonStyle.Danger) // .HasButtonSize(ButtonSize.ExtraSmall) // .HasConfirmMessage(T(Constants.Messages.ConfirmDeleteRecord).Text); result.AddReloadEvent("UPDATE_ENTITY_COMPLETE"); result.AddReloadEvent("DELETE_ENTITY_COMPLETE"); return result; } private ControlGridAjaxData<FilmFilesInfo> GetFilmFiles(ControlGridFormRequest options) { var languageCode = WorkContext.CurrentCulture; if (Utilities.IsNotNull(Request.Form[Extensions.Constants.LanguageCode])) { languageCode = Request.Form[Extensions.Constants.LanguageCode]; } var siteId = 0; if (Utilities.IsNotNull(Request.Form[Extensions.Constants.SiteId])) { siteId = Convert.ToInt32(Request.Form[Extensions.Constants.SiteId]); } var serverId = 0; if (Utilities.IsNotNull(Request.Form[Extensions.Constants.ServerId])) { serverId = Convert.ToInt32(Request.Form[Extensions.Constants.ServerId]); } int totals; var items = WorkContext.Resolve<IFilmFilesService>().SearchPaged(string.Empty, languageCode, siteId, serverId, options.PageIndex, options.PageSize, out totals); var result = new ControlGridAjaxData<FilmFilesInfo>(items, totals); return result; } [Themed(false)] [Url("admin/video-files/refresh-videos")] public ActionResult RefreshVideos() { WorkContext.Breadcrumbs.Add(new Breadcrumb { Text = T("Quản lý video files"), Url = Url.Action("Index") }); WorkContext.Breadcrumbs.Add(new Breadcrumb { Text = T("Đồng bộ videos từ máy chủ"), Url = "#" }); var model = new VideoRefreshModel(); var result = new ControlFormResult<VideoRefreshModel>(model) { Title = T("Đồng bộ videos từ máy chủ"), FormMethod = FormMethod.Post, UpdateActionName = "Refresh", SubmitButtonText = T("Đồng bộ"), CancelButtonText = T("Đóng"), ShowBoxHeader = false, FormWrapperStartHtml = Constants.Form.FormWrapperStartHtml, FormWrapperEndHtml = Constants.Form.FormWrapperEndHtml }; result.RegisterExternalDataSource(x => x.ServerId, y => BindServers()); result.RegisterCascadingDropDownDataSource(x => x.RootFolders, Url.Action("GetRootFolders")); result.RegisterCascadingDropDownDataSource(x => x.ChildrenFolders, Url.Action("GetChildrenFolders")); return result; } [Url("admin/video-files/get-children-folders")] public ActionResult GetChildrenFolders() { var serverId = 0; if (Utilities.IsNotNull(Request.Form[Extensions.Constants.ServerId])) { serverId = Convert.ToInt32(Request.Form[Extensions.Constants.ServerId]); } var rootFolderName = Extensions.Constants.ValueAll; if (Utilities.IsNotNull(Request.Form[Extensions.Constants.RootFolders])) { rootFolderName = Request.Form[Extensions.Constants.RootFolders]; } var items = new List<SelectListItem>(); string rootFolder; string languageCode; int siteId; var client = GetConnectionFtp(serverId, out rootFolder, out languageCode, out siteId); if (client != null) { var list = client.DirectoryList(rootFolderName); foreach (var folderPath in list) { if (string.IsNullOrEmpty(folderPath)) { continue; } if (rootFolderName == Extensions.Constants.ValueAll) { items.Add(new SelectListItem {Text = folderPath, Value = folderPath}); continue; } var index = folderPath.LastIndexOf('/'); if (index != -1) { var folderName = folderPath.Substring(index + 1, folderPath.Length - (index + 1)); items.Add(new SelectListItem { Text = string.Format("{0}/{1}", rootFolder, folderName), Value = folderName }); } } } return Json(items); } [HttpPost, ValidateInput(false), FormButton("Save")] [Url("admin/video-files/refresh")] public ActionResult Refresh(VideoRefreshModel model) { var childrenFolders = Extensions.Constants.ValueAll; if (Utilities.IsNotNull(Request.Form[Extensions.Constants.ChildrenFolders])) { childrenFolders = Request.Form[Extensions.Constants.ChildrenFolders]; } if (!string.IsNullOrEmpty(childrenFolders)) { var service = WorkContext.Resolve<IFilmFilesService>(); string rootFolder; string languageCode; int siteId; var client = GetConnectionFtp(model.ServerId, out rootFolder, out languageCode, out siteId); if (client != null) { var folder = string.Empty; var f = rootFolder.LastIndexOf('/'); if (f != -1) { folder = rootFolder.Substring(f + 1, rootFolder.Length - (f + 1)); } var list = childrenFolders.Split(','); foreach (var path in list) { if (string.IsNullOrEmpty(path)) { continue; } var listFolderFiles = client.DirectoryList(string.Format("{0}/{1}", rootFolder, path)); if (listFolderFiles != null && listFolderFiles.Any()) { foreach (var folderFilePath in listFolderFiles) { if (string.IsNullOrEmpty(folderFilePath)) { continue; } var listFiles = client.DirectoryList(string.Format("{0}/{1}", rootFolder, folderFilePath)); if (listFiles != null && listFiles.Any()) { var folderName = string.Empty; var n = folderFilePath.LastIndexOf('/'); if (n != -1) { folderName = folderFilePath.Substring(n + 1, folderFilePath.Length - (n + 1)); } foreach (var filePath in listFiles) { if (string.IsNullOrEmpty(filePath)) { continue; } var index = filePath.LastIndexOf('/'); if (index != -1) { var fileName = filePath.Substring(index + 1, filePath.Length - (index + 1)); var fullPath = string.Format("{0}/{1}/{2}", rootFolder, folderFilePath, fileName); var info = service.GetByFullPathFile(fullPath); if (info == null) { var y = fileName.LastIndexOf('.'); if (y != -1) { var extentions = fileName.Substring(y + 1, fileName.Length - (y + 1)); var file = new FilmFilesInfo { Id = 0, LanguageCode = languageCode, SiteId = siteId, ServerId = model.ServerId, Name = string.Empty, FolderRoot = rootFolder, FileName = fileName, FolderName = folderName, FolderDay = path, FolderPath = string.Format("{0}/{1}", folder, folderFilePath), Extentions = extentions, FullPath = fullPath, Size = "",//client.GetFileSize(fullPath), CreateDate = DateTime.Now.Date, HasUse = false, FileCode = Guid.NewGuid().ToString().Replace("-", string.Empty) }; service.Insert(file); } } } } } } } } } } return new AjaxResult() .NotifyMessage("UPDATE_ENTITY_COMPLETE") .Alert(T("Cập nhật thành công!")); } [Url("admin/video-files/edit/{id}")] public ActionResult Edit(int id) { WorkContext.Breadcrumbs.Add(new Breadcrumb { Text = T("Quản lý video files"), Url = Url.Action("Index") }); WorkContext.Breadcrumbs.Add(new Breadcrumb { Text = T("Thông tin video files"), Url = "#" }); var model = new FilmFilesModel(); if (id > 0) { var service = WorkContext.Resolve<IFilmFilesService>(); model = service.GetById(id); } var result = new ControlFormResult<FilmFilesModel>(model) { Title = T("Thông tin video files"), FormMethod = FormMethod.Post, UpdateActionName = "Update", ShowCancelButton = true, ShowSubmitButton = false, ShowBoxHeader = false, CancelButtonText = T("Trở về"), FormWrapperStartHtml = Constants.Form.FormWrapperStartHtml, FormWrapperEndHtml = Constants.Form.FormWrapperEndHtml }; result.RegisterExternalDataSource(x => x.LanguageCode, y => BindLanguages()); result.RegisterCascadingDropDownDataSource(x => x.SiteId, Url.Action("GetSitesByLanguage")); result.RegisterCascadingDropDownDataSource(x => x.ServerId, Url.Action("GetServersBySite")); result.MakeReadOnlyProperty(x => x.FolderName); result.MakeReadOnlyProperty(x => x.FullPath); result.MakeReadOnlyProperty(x => x.FileName); result.MakeReadOnlyProperty(x => x.FolderPath); result.MakeReadOnlyProperty(x => x.Extentions); result.MakeReadOnlyProperty(x => x.FileCode); result.MakeReadOnlyProperty(x => x.Size); result.MakeReadOnlyProperty(x => x.Name); result.MakeReadOnlyProperty(x => x.HasUse); return result; } [HttpPost, ValidateInput(false), FormButton("Save")] [Url("admin/video-files/update")] public ActionResult Update(FilmFilesModel model) { if (!ModelState.IsValid) { return new AjaxResult().Alert(T(Constants.Messages.InvalidModel)); } var service = WorkContext.Resolve<IFilmFilesService>(); FilmFilesInfo item = model.Id == 0 ? new FilmFilesInfo() : service.GetById(model.Id); item.Name = model.Name; item.FolderName = model.FolderName; item.HasUse = model.HasUse; service.Save(item); return new AjaxResult() .NotifyMessage("UPDATE_ENTITY_COMPLETE") .Alert(T("Cập nhật thành công!")); } //[FormButton("Delete")] //[HttpPost, ActionName("Update")] //public ActionResult Delete(int id) //{ // return new AjaxResult() // .NotifyMessage("DELETE_ENTITY_COMPLETE") // .Alert(T("Đã xóa videos thành công !")); //} } } <file_sep>using System; using System.Web.Mvc; using CMSSolutions.Configuration; using CMSSolutions.Extensions; using CMSSolutions.Security.Cryptography; using CMSSolutions.Web.Mvc; using CMSSolutions.Web.Routing; using CMSSolutions.Web.Security; using CMSSolutions.Web.Themes; using CMSSolutions.Web.UI.ControlForms; using CMSSolutions.Web.UI.Navigation; using CMSSolutions.Websites.Entities; using CMSSolutions.Websites.Extensions; using CMSSolutions.Websites.Models; using CMSSolutions.Websites.Services; namespace CMSSolutions.Websites.Controllers { [Themed(IsDashboard = true), Authorize] public class AdminFilmServerController : BaseAdminController { public AdminFilmServerController(IWorkContextAccessor workContextAccessor) : base(workContextAccessor) { TableName = "tblFilmServers"; } [Url("admin/server-films")] public ActionResult Index() { WorkContext.Breadcrumbs.Add(new Breadcrumb { Text = T("Quản lý máy chủ phim"), Url = "#" }); var result = new ControlGridFormResult<FilmServerInfo> { Title = T("Quản lý máy chủ phim"), CssClass = "table table-bordered table-striped", IsAjaxSupported = true, FetchAjaxSource = GetFilmServer, UpdateActionName = "Update", ActionsColumnWidth = 100, ClientId = TableName, GridWrapperStartHtml = Constants.Grid.GridWrapperStartHtml, GridWrapperEndHtml = Constants.Grid.GridWrapperEndHtml }; result.AddCustomVar(Extensions.Constants.LanguageCode, "$('#" + Extensions.Constants.LanguageCode + "').val();", true); result.AddCustomVar(Extensions.Constants.SiteId, "$('#" + Extensions.Constants.SiteId + "').val();", true); result.AddCustomVar(Extensions.Constants.StatusId, "$('#" + Extensions.Constants.StatusId + "').val();", true); result.AddColumn(x => x.Id, T("ID")).AlignCenter().HasWidth(60); result.AddColumn(x => x.ServerName, T("Tên máy chủ")); result.AddColumn(x => x.ServerIP, T("Địa chỉ IP")); result.AddColumn(x => x.Locations,T("Địa điểm")); result.AddColumn(x => x.IsVip) .HasHeaderText(T("Máy chủ VIP")) .AlignCenter() .HasWidth(100) .RenderAsStatusImage(false); result.AddColumn(x => EnumExtensions.GetDisplayName((Status)x.Status), T("Trạng thái")); result.AddAction().HasText(T("Thêm mới")) .HasUrl(Url.Action("Edit", RouteData.Values.Merge(new { id = 0 }))) .HasButtonStyle(ButtonStyle.Primary) .HasBoxButton(false) .HasCssClass(Constants.RowLeft) .HasRow(true); result.AddAction(new ControlFormHtmlAction(() => BuildLanguages(true, Extensions.Constants.SiteId))).HasParentClass(Constants.ContainerCssClassCol3); result.AddAction(new ControlFormHtmlAction(() => BuildSites(false, string.Empty))).HasParentClass(Constants.ContainerCssClassCol3); result.AddAction(new ControlFormHtmlAction(BuildStatus)).HasParentClass(Constants.ContainerCssClassCol3); result.AddRowAction() .HasText(T("Sửa")) .HasUrl(x => Url.Action("Edit", RouteData.Values.Merge(new { id = x.Id }))) .HasButtonStyle(ButtonStyle.Default) .HasButtonSize(ButtonSize.ExtraSmall); result.AddRowAction(true) .HasText(T("Xóa")) .HasName("Delete") .HasValue(x => x.Id) .HasButtonStyle(ButtonStyle.Danger) .HasButtonSize(ButtonSize.ExtraSmall) .HasConfirmMessage(T(Constants.Messages.ConfirmDeleteRecord).Text); result.AddReloadEvent("UPDATE_ENTITY_COMPLETE"); result.AddReloadEvent("DELETE_ENTITY_COMPLETE"); return result; } private ControlGridAjaxData<FilmServerInfo> GetFilmServer(ControlGridFormRequest options) { var languageCode = WorkContext.CurrentCulture; if (Utilities.IsNotNull(Request.Form[Extensions.Constants.LanguageCode])) { languageCode = Request.Form[Extensions.Constants.LanguageCode]; } var siteId = 0; if (Utilities.IsNotNull(Request.Form[Extensions.Constants.SiteId])) { siteId = Convert.ToInt32(Request.Form[Extensions.Constants.SiteId]); } var statusId = 0; if (Utilities.IsNotNull(Request.Form[Extensions.Constants.StatusId])) { statusId = Convert.ToInt32(Request.Form[Extensions.Constants.StatusId]); } int totals; var items = WorkContext.Resolve<IFilmServersService>().GetPaged(languageCode, siteId, statusId, options.PageIndex, options.PageSize, out totals); var result = new ControlGridAjaxData<FilmServerInfo>(items, totals); return result; } [Url("admin/server-films/edit/{id}")] public ActionResult Edit(int id) { WorkContext.Breadcrumbs.Add(new Breadcrumb { Text = T("Quản lý máy chủ phim"), Url = Url.Action("Index") }); WorkContext.Breadcrumbs.Add(new Breadcrumb { Text = T("Thông tin máy chủ phim"), Url = "#" }); var service = WorkContext.Resolve<IFilmServersService>(); var model = new FilmServerModel(); if (id > 0) { model = service.GetById(id); string password = EncryptionExtensions.Decrypt(KeyConfiguration.PublishKey, model.Password); if (string.IsNullOrEmpty(password)) { throw new ArgumentException(T(SecurityConstants.ErrorConfigKey).Text); } model.Password = <PASSWORD>; string userName = EncryptionExtensions.Decrypt(KeyConfiguration.PublishKey, model.UserName); if (string.IsNullOrEmpty(userName)) { throw new ArgumentException(T(SecurityConstants.ErrorConfigKey).Text); } model.UserName = userName; } var result = new ControlFormResult<FilmServerModel>(model) { Title = T("Thông tin máy chủ phim"), FormMethod = FormMethod.Post, UpdateActionName = "Update", SubmitButtonText = T("Lưu lại"), CancelButtonText = T("Trở về"), ShowBoxHeader = false, FormWrapperStartHtml = Constants.Form.FormWrapperStartHtml, FormWrapperEndHtml = Constants.Form.FormWrapperEndHtml }; result.RegisterExternalDataSource(x => x.LanguageCode, y => BindLanguages()); result.RegisterCascadingDropDownDataSource(x => x.SiteId, Url.Action("GetSitesByLanguage")); result.RegisterExternalDataSource(x => x.Status, y => BindStatus()); return result; } [HttpPost, ValidateInput(false), FormButton("Save")] [Url("admin/server-films/update")] public ActionResult Update(FilmServerModel model) { if (!ModelState.IsValid) { return new AjaxResult().Alert(T(Constants.Messages.InvalidModel)); } string password = EncryptionExtensions.Encrypt(KeyConfiguration.PublishKey, model.Password); if (string.IsNullOrEmpty(password)) { throw new ArgumentException(T(SecurityConstants.ErrorConfigKey).Text); } string userName = EncryptionExtensions.Encrypt(KeyConfiguration.PublishKey, model.UserName); if (string.IsNullOrEmpty(userName)) { throw new ArgumentException(T(SecurityConstants.ErrorConfigKey).Text); } var service = WorkContext.Resolve<IFilmServersService>(); FilmServerInfo item = model.Id == 0 ? new FilmServerInfo() : service.GetById(model.Id); item.LanguageCode = model.LanguageCode; item.SiteId = model.SiteId; item.ServerName = model.ServerName; item.ServerIP = model.ServerIP; item.Password = <PASSWORD>; item.UserName = userName; item.FolderRoot = model.FolderRoot; item.IsDefault = model.IsDefault; item.Locations = model.Locations; item.IsVip = model.IsVip; item.Description = model.Description; item.Status = model.Status; service.Save(item); return new AjaxResult().NotifyMessage("UPDATE_ENTITY_COMPLETE") .Alert(T("Cập nhật thành công!")); } [FormButton("Delete")] [HttpPost, ActionName("Update")] public ActionResult Delete(int id) { var service = WorkContext.Resolve<IFilmServersService>(); var item = service.GetById(id); item.Status = (int)Status.Deleted; service.Update(item); return new AjaxResult() .NotifyMessage("DELETE_ENTITY_COMPLETE") .Alert(T("Dữ liệu chuyển trạng thái xóa tạm thời!")); } } } <file_sep>using System.ComponentModel; using System.ComponentModel.DataAnnotations.Schema; using System.Runtime.Serialization; using CMSSolutions.Data; using CMSSolutions.Data.Entity; namespace CMSSolutions.Websites.Entities { [DataContract] public class VIPCardInfo : BaseEntity<int> { [DataMember] [DisplayName("LanguageCode")] public string LanguageCode { get; set; } [DataMember] [DisplayName("SiteId")] public int SiteId { get; set; } [DataMember] [DisplayName("ServerId")] public int ServerId { get; set; } [NotMapped] [DisplayName("ServerName")] public string ServerName { get; set; } [DataMember] [DisplayName("VIPCode")] public string VIPCode { get; set; } [DataMember] [DisplayName("VIPName")] public string VIPName { get; set; } [DataMember] [DisplayName("VIPValue")] public decimal VIPValue { get; set; } } public class VIPCardMap : EntityTypeConfiguration<VIPCardInfo>, IEntityTypeConfiguration { public VIPCardMap() { ToTable("Modules_VIPCards"); HasKey(m => m.Id); Property(m => m.LanguageCode).HasMaxLength(50).IsRequired(); Property(m => m.SiteId).IsRequired(); Property(m => m.VIPCode).HasMaxLength(50).IsRequired(); Property(m => m.VIPName).HasMaxLength(250); Property(m => m.VIPValue).IsRequired(); Property(m => m.ServerId).IsRequired(); } } } <file_sep>using System.ComponentModel; using System.Runtime.Serialization; using CMSSolutions.Data; using CMSSolutions.Data.Entity; namespace CMSSolutions.Websites.Entities { /// <summary> /// Tập phim /// </summary> [DataContract] public class EpisodeInfo : BaseEntity<int> { [DataMember] [DisplayName("LanguageCode")] public string LanguageCode { get; set; } [DataMember] [DisplayName("SiteId")] public int SiteId { get; set; } [DataMember] [DisplayName("EpisodeName")] public string EpisodeName { get; set; } [DataMember] [DisplayName("OrderBy")] public int OrderBy { get; set; } [DataMember] [DisplayName("Description")] public string Description { get; set; } [DataMember] [DisplayName("Status")] public int Status { get; set; } } public class EpisodeMap : EntityTypeConfiguration<EpisodeInfo>, IEntityTypeConfiguration { public EpisodeMap() { ToTable("Modules_Episodes"); HasKey(m => m.Id); Property(m => m.LanguageCode).IsRequired().HasMaxLength(50); Property(m => m.SiteId).IsRequired(); Property(m => m.EpisodeName).HasMaxLength(50); Property(m => m.Description).HasMaxLength(2000); } } } <file_sep>using System; using System.Collections.Generic; using System.Data.SqlClient; using CMSSolutions.Data; using CMSSolutions.Events; using CMSSolutions.Services; using CMSSolutions.Websites.Entities; namespace CMSSolutions.Websites.Services { public interface ITransactionCardService : IGenericService<TransactionCardInfo, long>, IDependency { int CardProcessing(TransactionCardInfo entity, int vipXu); IList<TransactionCardInfo> GetPaged(string keyword, string cardCode, int status, int isLock, DateTime fromDate, DateTime toDate, int pageIndex, int pageSize, out int totals); IList<TransactionCardInfo> ExportExcelAtm(DateTime fromDate, DateTime toDate); int CardClosed(DateTime toDate); } public class TransactionCardService : GenericService<TransactionCardInfo, long>, ITransactionCardService { public TransactionCardService(IRepository<TransactionCardInfo, long> repository, IEventBus eventBus) : base(repository, eventBus) { } public int CardProcessing(TransactionCardInfo entity, int vipXu) { var list = new List<SqlParameter> { AddInputParameter("@CustomerCode", entity.CustomerCode), AddInputParameter("@TransactionCode", entity.TransactionCode), AddInputParameter("@CreateDate", entity.CreateDate), AddInputParameter("@CardCode", entity.CardCode), AddInputParameter("@Amount", entity.Amount), AddInputParameter("@SeriNumber", entity.SeriNumber), AddInputParameter("@PinCode", entity.PinCode), AddInputParameter("@Description", entity.Description), AddInputParameter("@Status", entity.Status), AddInputParameter("@VipXu", vipXu) }; return ExecuteNonQuery("sp_TransactionCard_CardProcessing", list.ToArray()); } public IList<TransactionCardInfo> GetPaged(string keyword, string cardCode, int status, int isLock, DateTime fromDate, DateTime toDate, int pageIndex, int pageSize, out int totals) { var list = new List<SqlParameter> { AddInputParameter("@SearchText", keyword), AddInputParameter("@CardCode", cardCode), AddInputParameter("@Status", status), AddInputParameter("@IsLock", isLock), AddInputParameter("@FromDate", fromDate), AddInputParameter("@ToDate", toDate), AddInputParameter("@PageIndex", pageIndex), AddInputParameter("@PageSize", pageSize) }; return ExecuteReader<TransactionCardInfo>("sp_TransactionCard_Search_Paged", "@TotalRecord", out totals, list.ToArray()); } public IList<TransactionCardInfo> ExportExcelAtm(DateTime fromDate, DateTime toDate) { var list = new List<SqlParameter> { AddInputParameter("@FromDate", fromDate), AddInputParameter("@ToDate", toDate) }; return ExecuteReader<TransactionCardInfo>("sp_TransactionBank_ReportCard", list.ToArray()); } public int CardClosed(DateTime toDate) { var list = new List<SqlParameter> { AddInputParameter("@ToDate", toDate) }; return ExecuteNonQuery("sp_TransactionCard_Closed", list.ToArray()); } } }<file_sep>using System; using System.Collections.Generic; using System.Diagnostics; using System.Globalization; using System.IO; using System.Linq; using System.Security.Cryptography; using System.Text; using System.Text.RegularExpressions; using System.Web.Mvc; using System.Web.Script.Serialization; using System.Xml.Serialization; using CMSSolutions.Extensions; using CMSSolutions.Websites.Entities; namespace CMSSolutions.Websites.Extensions { public class Utilities { public static string GetStatusDownload(DownloadCustomerInfo download) { var displayDay = "Sẵn sàng"; if (download != null && download.EndDate.HasValue && download.EndDate.Value.Date >= DateTime.Now.Date) { int date = download.EndDate.Value.Day; int date2 = DateTime.Now.Date.Day; if ((date - date2) >= 3) { displayDay = "3 ngày"; } if ((date - date2) == 2) { displayDay = "2 ngày"; } if ((date - date2) == 1) { displayDay = "1 ngày"; } } return displayDay; } public static bool IsNumeric(string val, NumberStyles numberStyle) { Double result; return Double.TryParse(val, numberStyle, CultureInfo.CurrentCulture, out result); } public static string SerializeXml<T>(T dataToSerialize) { var stringwriter = new StringWriter(); var serializer = new XmlSerializer(typeof(T)); serializer.Serialize(stringwriter, dataToSerialize); return stringwriter.ToString(); } public static T DeserializeXml<T>(string xmlText) { var stringReader = new StringReader(xmlText); var serializer = new XmlSerializer(typeof(T)); return (T)serializer.Deserialize(stringReader); } public static void WriteEventLog(string messages) { try { var eventLogName = "ErrorVipHD"; if (!EventLog.SourceExists(eventLogName)) { EventLog.CreateEventSource(eventLogName, "Error VIPHD.VN"); } var log = new EventLog { Source = eventLogName }; log.WriteEntry(messages, EventLogEntryType.Error); } catch (Exception) { } } public static string RemoveInjection(string query) { query = query.Replace("'", "''"); return query; } public static string GenerateUniqueNumber() { var bytes = new byte[4]; var rng = RandomNumberGenerator.Create(); rng.GetBytes(bytes); uint random = BitConverter.ToUInt32(bytes, 0) % 100000000; return String.Format("{0:D8}", random); } public static bool ValidateUserName(string userName) { if (IsEmailValid(userName)) { return true; } var userNameAllowedRegEx = new Regex(@"^[a-zA-Z]{1}[a-zA-Z0-9\._\-]{0,23}[^.-]$", RegexOptions.Compiled); var userNameIllegalEndingRegEx = new Regex(@"(\.|\-|\._|\-_)$", RegexOptions.Compiled); if (string.IsNullOrEmpty(userName) || !userNameAllowedRegEx.IsMatch(userName) || userNameIllegalEndingRegEx.IsMatch(userName)) { return false; } return true; } public static string GetBankMessages(int errorCode) { var list = EnumExtensions.ToSelectList<BankErrorMessages>(); var message = "Bank: Lỗi không xác định từ hệ thống ngân hàng đối tác."; foreach (var item in list) { var value = Convert.ToInt32(item.Value); if (value == errorCode) { message = EnumExtensions.GetDisplayName((BankErrorMessages)value); break; } } return message; } public static string GetMessages(int errorCode) { var list = EnumExtensions.ToSelectList<ErrorMessages>(); var message = "Card: Lỗi không xác định từ hệ thống đối tác."; foreach (var item in list) { var value = Convert.ToInt32(item.Value); if (value == errorCode) { message = EnumExtensions.GetDisplayName((ErrorMessages)value); break; } } return message; } public static int[] ParseListInt(string value) { if (string.IsNullOrEmpty(value)) { return new int[0]; } return value.Split(',').Select(Int32.Parse).ToArray(); } public static string ParseString(int[] list) { if (list != null && list.Length > 0) { return string.Join(", ", list); } return string.Empty; } public static bool IsDirectory(string path) { FileAttributes attr = File.GetAttributes(path); if ((attr & FileAttributes.Directory) == FileAttributes.Directory) { return true; } return false; } public static bool IsPathExists(string path) { if (Directory.Exists(path)) { return true; } if (File.Exists(path)) { return true; } return false; } public static string DateString(DateTime? dateTime) { if (dateTime == null) { return "01/01/1900"; } return dateTime.Value.ToString(Constants.DateTimeFomat); } public static DateTime DateNull() { return new DateTime(1900, 01, 01); } public static bool IsNotNull(object value) { if (value == null) { return false; } if (value.Equals(Constants.IsNull) || value.Equals("")) { return false; } if (value.Equals(Constants.IsUndefined)) { return false; } return true; } private static string DomainMapper(Match match) { var idn = new IdnMapping(); string domainName = match.Groups[2].Value; try { domainName = idn.GetAscii(domainName); } catch (ArgumentException ex) { throw ex; } return match.Groups[1].Value + domainName; } public static bool IsEmailValid(string emailaddress) { if (String.IsNullOrEmpty(emailaddress)) { return false; } emailaddress = Regex.Replace(emailaddress, @"(@)(.+)$", DomainMapper); return Regex.IsMatch(emailaddress, @"^(?("")(""[^""]+?""@)|(([0-9a-z]((\.(?!\.))|[-!#\$%&'\*\+/=\?\^`\{\}\|~\w])*)(?<=[0-9a-z])@))" + @"(?(\[)(\[(\d{1,3}\.){3}\d{1,3}\])|(([0-9a-z][-\w]*[0-9a-z]*\.)+[a-z0-9]{2,17}))$", RegexOptions.IgnoreCase); } public static string GetAlias(string values) { if (string.IsNullOrEmpty(values)) { return string.Empty; } var regex = new Regex("\\p{IsCombiningDiacriticalMarks}+"); string temp = values.Normalize(NormalizationForm.FormD); var converttext = regex.Replace(temp, String.Empty).Replace('\u0111', 'd').Replace('\u0110', 'D'); converttext = Regex.Replace(converttext, "[^a-zA-Z0-9_.]+", " ", RegexOptions.Compiled); var list = new char[] { ' ','/',',','&','\"','?','|',':','"', '`', '\\', ';', '~', '!', '@', '#', '$', '%', '^', '*', '(', ')', '\'', '_', '=', '+', '{', '}', '[', ']', '.', '>', '<' }; converttext = list.Aggregate(converttext, (current, schar) => current.Replace(schar, '-')); converttext = converttext.Replace("--", "-").Trim('.').TrimEnd('-').TrimStart('-'); return converttext.ToLower(); } public static string GetCharUnsigned(string values) { if (string.IsNullOrEmpty(values)) { return string.Empty; } var regex = new Regex("\\p{IsCombiningDiacriticalMarks}+"); string temp = values.Normalize(NormalizationForm.FormD); var converttext = regex.Replace(temp, String.Empty).Replace('\u0111', 'd').Replace('\u0110', 'D'); converttext = Regex.Replace(converttext, "[^a-zA-Z0-9_.]+", " ", RegexOptions.Compiled); var list = new char[] { ' ', '/', ',', '&', '\"', '?', '|', ':', '"', '`', '\\', ';', '~', '!', '@', '#', '$', '%', '^', '*', '(', ')', '\'', '_', '=', '+', '{', '}', '[', ']', '.', '>', '<' }; converttext = list.Aggregate(converttext, (current, schar) => current.Replace(schar, ' ')); converttext = converttext.Replace("--", " ").Trim('.').TrimEnd(' ').TrimStart(' '); return converttext.ToLower(); } public static T ConvertJsonToObject<T>(string input) { var json = new JavaScriptSerializer(); return json.Deserialize<T>(input.Trim()); } public static string ConvertObjectToJson<T>(T input) { var json = new JavaScriptSerializer(); return json.Serialize(input); } public static List<SelectListItem> GetListDay() { var list = new List<SelectListItem>(); for (int i = 1; i <= 31; i++) { var text = (i <= 9 ? "0" + i : i.ToString()); list.Add(new SelectListItem { Value = text, Text = text, }); } return list; } public static List<SelectListItem> GetListMonth() { var list = new List<SelectListItem>(); for (int i = 1; i <= 12; i++) { var text = (i <= 9 ? "0" + i : i.ToString()); list.Add(new SelectListItem { Value = text, Text = "Tháng " + text, }); } return list; } public static List<SelectListItem> GetListYear() { var year = DateTime.Now.Year; var list = new List<SelectListItem>(); for (int i = 1900; i <= year; i++) { var text = i.ToString(); list.Add(new SelectListItem { Value = text, Text = text, }); } return list.OrderByDescending(x => x.Value).ToList(); } } }<file_sep>using System.IO; using System.Web.Mvc; using CMSSolutions.Websites.Controllers; namespace CMSSolutions.Websites.Extensions { public class ViewRenderer { public ControllerContext Context { get; set; } public string RenderView(string viewPath, object model) { return RenderViewToStringInternal(viewPath, model, false); } public string RenderPartialView(string viewPath, object model) { return RenderViewToStringInternal(viewPath, model, true); } protected string RenderViewToStringInternal(string viewPath, object model, bool partial = false) { // first find the ViewEngine for this view ViewEngineResult viewEngineResult = null; if (partial) viewEngineResult = ViewEngines.Engines.FindPartialView(Context, viewPath); else viewEngineResult = ViewEngines.Engines.FindView(Context, viewPath, null); if (viewEngineResult == null) throw new FileNotFoundException("ViewCouldNotBeFound"); // get the view and attach the model to view data var view = viewEngineResult.View; Context.Controller.ViewData.Model = model; string result = null; using (var sw = new StringWriter()) { var ctx = new ViewContext(Context, view, Context.Controller.ViewData, Context.Controller.TempData, sw); view.Render(ctx, sw); result = sw.ToString(); } return result; } } }<file_sep>using System; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Text; using System.Web.Mvc; using CMSSolutions.Extensions; using CMSSolutions.Web.Mvc; using CMSSolutions.Web.Themes; using CMSSolutions.Web.UI.ControlForms; using CMSSolutions.Web.UI.Navigation; using CMSSolutions.Websites.Entities; using CMSSolutions.Websites.Extensions; using CMSSolutions.Websites.Services; using GemBox.Spreadsheet; namespace CMSSolutions.Websites.Controllers { [Themed(IsDashboard = true), Authorize] public class AdminReportBankController : BaseAdminController { public AdminReportBankController(IWorkContextAccessor workContextAccessor) : base(workContextAccessor) { TableName = "tblReportAtm"; } [Url("admin/report/bank")] public ActionResult Index() { WorkContext.Breadcrumbs.Add(new Breadcrumb { Text = T("Báo cáo ATM"), Url = "#" }); var result = new ControlGridFormResult<TransactionBankInfo> { Title = T("Báo cáo ATM"), CssClass = "table table-bordered table-striped", IsAjaxSupported = true, FetchAjaxSource = GetReportBank, DefaultPageSize = WorkContext.DefaultPageSize, EnablePaginate = true, UpdateActionName = "Update", GridWrapperStartHtml = Constants.Grid.GridWrapperStartHtml, GridWrapperEndHtml = Constants.Grid.GridWrapperEndHtml, ClientId = TableName, ActionsColumnWidth = 150 }; result.AddCustomVar(Extensions.Constants.StatusId, "$('#" + Extensions.Constants.StatusId + "').val();", true); result.AddCustomVar(Extensions.Constants.BankCode, "$('#" + Extensions.Constants.BankCode + "').val();", true); result.AddCustomVar(Extensions.Constants.TypeId, "$('#" + Extensions.Constants.TypeId + "').val();", true); result.AddCustomVar(Extensions.Constants.Locked, "$('#" + Extensions.Constants.Locked + "').val();", true); result.AddCustomVar(Extensions.Constants.FromDate, "$('#" + Extensions.Constants.FromDate + "').val();", true); result.AddCustomVar(Extensions.Constants.ToDate, "$('#" + Extensions.Constants.ToDate + "').val();", true); result.AddCustomVar(Extensions.Constants.SearchText, "$('#" + Extensions.Constants.SearchText + "').val();", true); result.AddColumn(x => x.TransactionCode, T("Mã GD")).HasWidth(60).AlignCenter(); result.AddColumn(x => x.CustomerCode, T("Mã KH")); result.AddColumn(x => x.FullName, T("Tên KH")); result.AddColumn(x => x.Amount, T("Số tiền")); result.AddColumn(x => x.TextStartDate, T("Ngày giao dịch")); result.AddColumn(x => EnumExtensions.GetDisplayName((PaymentStatus)x.Status), T("Trạng thái")); result.AddColumn(x => x.IsLock) .HasHeaderText(T("Đang khóa")) .AlignCenter() .HasWidth(100) .RenderAsStatusImage(); result.AddAction().HasText(T("Chốt đối soát")) .HasUrl(Url.Action("Index", "AdminClosedBank")) .HasButtonStyle(ButtonStyle.Danger) .HasCssClass(Constants.RowLeft); result.AddAction().HasText(T("Xuất dữ liệu gửi giao dịch")) .HasUrl(Url.Action("ExportExcelSend")) .HasButtonStyle(ButtonStyle.Info) .HasCssClass(Constants.RowLeft); result.AddAction().HasText(T("Xuất dữ liệu nhận giao dịch")) .HasUrl(Url.Action("ExportExcelRereceive")) .HasButtonStyle(ButtonStyle.Info) .HasCssClass(Constants.RowLeft) .HasRow(true); result.AddAction(new ControlFormHtmlAction(BuildStatus)).HasParentClass(Constants.ContainerCssClassCol3); result.AddAction(new ControlFormHtmlAction(BuildBanks)).HasParentClass(Constants.ContainerCssClassCol3); result.AddAction(new ControlFormHtmlAction(BuildTypes)).HasParentClass(Constants.ContainerCssClassCol3); result.AddAction(new ControlFormHtmlAction(BuildLocked)).HasParentClass(Constants.ContainerCssClassCol3).HasRow(true); result.AddAction(new ControlFormHtmlAction(() => BuildFromDate())).HasParentClass(Constants.ContainerCssClassCol3); result.AddAction(new ControlFormHtmlAction(() => BuildToDate())).HasParentClass(Constants.ContainerCssClassCol3); result.AddAction(new ControlFormHtmlAction(BuildSearchText)).HasParentClass(Constants.ContainerCssClassCol3); return result; } public override string BuildStatus() { var list = EnumExtensions.GetListItems<PaymentStatus>(); var sb = new StringBuilder(); sb.AppendFormat(T("Trạng thái") + " <select id=\"" + Extensions.Constants.StatusId + "\" name=\"" + Extensions.Constants.StatusId + "\" autocomplete=\"off\" class=\"uniform form-control col-md-3\" onchange=\"$('#" + TableName + "').jqGrid().trigger('reloadGrid');\">"); foreach (var status in list) { sb.AppendFormat("<option value=\"{1}\">{0}</option>", status.Text, status.Value); } sb.Append("</select>"); return sb.ToString(); } private string BuildBanks() { var list = WorkContext.Resolve<IBankCardService>().GetRecords(); var sb = new StringBuilder(); sb.AppendFormat(T("Ngân hàng") + " <select id=\"" + Extensions.Constants.BankCode + "\" name=\"" + Extensions.Constants.BankCode + "\" autocomplete=\"off\" class=\"uniform form-control col-md-3\" onchange=\"$('#" + TableName + "').jqGrid().trigger('reloadGrid');\">"); foreach (var status in list) { sb.AppendFormat("<option value=\"{1}\">{0}</option>", status.BankName, status.BankCode); } sb.Append("</select>"); return sb.ToString(); } private string BuildTypes() { var list = EnumExtensions.GetListItems<TransferType>(); var sb = new StringBuilder(); sb.AppendFormat(T("Loại xử lý") + " <select id=\"" + Extensions.Constants.TypeId + "\" name=\"" + Extensions.Constants.TypeId + "\" autocomplete=\"off\" class=\"uniform form-control col-md-3\" onchange=\"$('#" + TableName + "').jqGrid().trigger('reloadGrid');\">"); foreach (var status in list) { sb.AppendFormat("<option value=\"{1}\">{0}</option>", status.Text, status.Value); } sb.Append("</select>"); return sb.ToString(); } private string BuildLocked() { var list = new List<SelectListItem> { new SelectListItem{Value = "0", Text = "Chưa chốt sổ đối soát"}, new SelectListItem{Value = "1", Text = "Đã chốt sổ đối soát"} }; var sb = new StringBuilder(); sb.AppendFormat(T("Đối soát") + " <select id=\"" + Extensions.Constants.Locked + "\" name=\"" + Extensions.Constants.Locked + "\" autocomplete=\"off\" class=\"uniform form-control col-md-3\" onchange=\"$('#" + TableName + "').jqGrid().trigger('reloadGrid');\">"); foreach (var status in list) { sb.AppendFormat("<option value=\"{1}\">{0}</option>", status.Text, status.Value); } sb.Append("</select>"); return sb.ToString(); } private ControlGridAjaxData<TransactionBankInfo> GetReportBank(ControlGridFormRequest options) { var searchText = string.Empty; if (Utilities.IsNotNull(Request.Form[Extensions.Constants.SearchText])) { searchText = Request.Form[Extensions.Constants.SearchText]; } var bankCode = string.Empty; if (Utilities.IsNotNull(Request.Form[Extensions.Constants.BankCode])) { bankCode = Request.Form[Extensions.Constants.BankCode]; } var type = 0; if (Utilities.IsNotNull(Request.Form[Extensions.Constants.TypeId])) { type = Convert.ToInt32(Request.Form[Extensions.Constants.TypeId]); } var status = 0; if (Utilities.IsNotNull(Request.Form[Extensions.Constants.StatusId])) { status = Convert.ToInt32(Request.Form[Extensions.Constants.StatusId]); } var locked = 0; if (Utilities.IsNotNull(Request.Form[Extensions.Constants.Locked])) { locked = Convert.ToInt32(Request.Form[Extensions.Constants.Locked]); } var fromDate = DateTime.Now.Date; if (Utilities.IsNotNull(Request.Form[Extensions.Constants.FromDate])) { fromDate = DateTime.ParseExact(Request.Form[Extensions.Constants.FromDate], "dd/MM/yyyy", CultureInfo.InvariantCulture); } var toDate = DateTime.Now.Date; if (Utilities.IsNotNull(Request.Form[Extensions.Constants.ToDate])) { toDate = DateTime.ParseExact(Request.Form[Extensions.Constants.ToDate], "dd/MM/yyyy", CultureInfo.InvariantCulture); } int totals; var items = WorkContext.Resolve<ITransactionBankService>().GetPaged(searchText, bankCode, type, status, locked, fromDate, toDate, options.PageIndex, options.PageSize, out totals); var result = new ControlGridAjaxData<TransactionBankInfo>(items, totals); return result; } [Url("admin/report/sms/export-excel-send")] public ActionResult ExportExcelSend() { var ef = new ExcelFile(); string fileName = Server.MapPath("/Media/Default/ExcelTemplate/DuLieuATM.xls"); ef.LoadXls(fileName, XlsOptions.PreserveAll); byte[] fileContents; ExcelWorksheet ws = ef.Worksheets[0]; var data = WorkContext.Resolve<ITransactionBankService>().ExportExcelAtm(Utilities.DateNull(), Utilities.DateNull(), (int)TransferType.Send); if (data != null && data.Count > 0) { int index = 1; foreach (var item in data) { ws.Cells[index, 0].Value = index; ws.Cells[index, 1].Value = item.CustomerCode; ws.Cells[index, 2].Value = item.FullName; ws.Cells[index, 3].Value = item.Amount; ws.Cells[index, 4].Value = item.CreateDate.ToString(Extensions.Constants.DateTimeFomatFull); ws.Cells[index, 5].Value = EnumExtensions.GetDisplayName((RequestStatus)item.Status); index++; ws.Rows[index].InsertCopy(1, ws.Rows[1]); } ws.Rows[index].Delete(); } using (var stream = new MemoryStream()) { ef.SaveXls(stream); fileContents = stream.ToArray(); } return File(fileContents, "application/vnd.ms-excel"); } [Url("admin/report/sms/export-excel-rereceive")] public ActionResult ExportExcelRereceive() { var ef = new ExcelFile(); string fileName = Server.MapPath("/Media/Default/ExcelTemplate/DuLieuATM.xls"); ef.LoadXls(fileName, XlsOptions.PreserveAll); ExcelWorksheet ws = ef.Worksheets[0]; var data = WorkContext.Resolve<ITransactionBankService>().ExportExcelAtm(Utilities.DateNull(), Utilities.DateNull(), (int)TransferType.Rereceive); if (data != null && data.Count > 0) { int index = 1; foreach (var item in data) { ws.Cells[index, 0].Value = index; ws.Cells[index, 1].Value = item.CustomerCode; ws.Cells[index, 2].Value = item.FullName; ws.Cells[index, 3].Value = item.Amount; ws.Cells[index, 4].Value = item.CreateDate.ToString(Extensions.Constants.DateTimeFomatFull); ws.Cells[index, 5].Value = EnumExtensions.GetDisplayName((RequestStatus)item.Status); index++; ws.Rows[index].InsertCopy(1, ws.Rows[1]); } ws.Rows[index].Delete(); } byte[] fileContents; using (var stream = new MemoryStream()) { ef.SaveXls(stream); fileContents = stream.ToArray(); } return File(fileContents, "application/vnd.ms-excel"); } } } <file_sep>using CMSSolutions.Web.UI.ControlForms; using CMSSolutions.Websites.Entities; namespace CMSSolutions.Websites.Models { public class BankCardModel { [ControlHidden] public int Id { get; set; } [ControlText(Type = ControlText.TextBox, Required = true, MaxLength = 250, LabelText = "Mã ngân hàng", ContainerCssClass = Constants.ContainerCssClassCol3, ContainerRowIndex = 0)] public string BankCode { get; set; } [ControlText(Type = ControlText.TextBox, Required = true, MaxLength = 250, LabelText = "Tên ngân hàng", ContainerCssClass = Constants.ContainerCssClassCol3, ContainerRowIndex = 1)] public string BankName { get; set; } [ControlChoice(ControlChoice.DropDownList, Required = true, LabelText = "Trạng thái", ContainerCssClass = Constants.ContainerCssClassCol3, ContainerRowIndex = 2)] public int Status { get; set; } public static implicit operator BankCardModel(BankCardInfo entity) { return new BankCardModel { Id = entity.Id, BankCode = entity.BankCode, BankName = entity.BankName, Status = entity.Status }; } } } <file_sep>using System.ComponentModel.DataAnnotations; namespace CMSSolutions.Websites.Extensions { public enum AlertErrorVideo { [Display(Name = "..Chọn thông báo lỗi..")] None = 0, [Display(Name = "Lỗi tiêu đề")] Aler1 = 1, [Display(Name = "Lỗi hình ảnh")] Aler2 = 2, [Display(Name = "Lỗi âm thanh")] Aler3 = 3, [Display(Name = "Không xem được")] Aler4 = 4, [Display(Name = "Lỗi đứng hình, tiếng vẫn phát")] Aler5 = 5, [Display(Name = "Lỗi khác")] Aler6 = 6, } public enum LinkType { Streaming = 1, Picasa = 2, Youtube = 3 } public enum SliderPages { [Display(Name = "Trang chủ")] Home = 1, [Display(Name = "Chuyên mục phim lẻ")] CatetegoryPhimLe = 2, [Display(Name = "Phim mới nhất")] FilmHot = 3, [Display(Name = "Chiếu rạp")] FilmTheater = 4, [Display(Name = "Show")] Show = 5, [Display(Name = "Clip")] Clip = 6, [Display(Name = "Trailer")] Trailer = 7, [Display(Name = "JJ Channel")] JJChannel = 8, [Display(Name = "Chuyên mục phim bộ")] CatetegoryPhimBo = 9, } public enum SearchSortBy { [Display(Name = "Tăng dần")] ASC = 1, [Display(Name = "Giảm dần")] DESC = 2, } public enum SearchOrderBy { [Display(Name = "Xếp theo")] Id = 0, [Display(Name = "Mới Up")] CreateDate = 1, [Display(Name = "Năm sản xuất")] ReleaseYear = 2, [Display(Name = "Tên phim")] FilmName = 3, [Display(Name = "Lượt xem")] ViewCount = 4, [Display(Name = "Lượt like")] CommentCount = 5 } public enum FixCategories { [Display(Name = "Nạp VIP")] NapVIP = 63, [Display(Name = "Phim hót")] FilmHot = 101, [Display(Name = "Phim lẻ")] FilmLe = 2, [Display(Name = "Phim bộ")] FilmBo = 3, [Display(Name = "Tất cả")] AllNews = 59, [Display(Name = "Sự kiện")] Events = 60, [Display(Name = "Tin tức")] News = 61, [Display(Name = "Tuyển dụng")] Recruitment = 62, [Display(Name = "Phim chiếu rạp")] FilmTheater = 102, [Display(Name = "Hỗ trợ")] Support = 64 } public enum PromotionStatus { [Display(Name = "Đang thực hiện")] Running = 1, [Display(Name = "Đã kết thúc")] Finish = 2 } public enum ExchangeMoney { [Display(Name = "10.000")] VipXu10 = 100, [Display(Name = "20.000")] VipXu20 = 200, [Display(Name = "30.000")] VipXu30 = 300, [Display(Name = "50.000")] VipXu50 = 500, [Display(Name = "100.000")] VipXu100 = 1000, [Display(Name = "200.000")] VipXu200 = 2000, [Display(Name = "300.000")] VipXu300 = 3000, [Display(Name = "500.000")] VipXu500 = 5000 } public enum ExchangeDay { [Display(Name = "15 Ngày")] Package15 = 15, [Display(Name = "50 Ngày")] Package50 = 50, [Display(Name = "100 Ngày")] Package100 = 100, [Display(Name = "300 Ngày")] Package300 = 300 } public enum CardStatus { [Display(Name = "Nạp thẻ thất bại")] Error = 1, [Display(Name = "Nạp thẻ thành công")] Success = 2 } public enum PaymentStatus { [Display(Name = "Đang thực hiện")] Open = 1, [Display(Name = "Đã hoàn thành")] Close = 2 } public enum TransferType { [Display(Name = "Gửi đi")] Send = 1, [Display(Name = "Nhận về")] Rereceive = 2 } public enum VideoTypes { [Display(Name = "Phim")] IsFilm = 1, [Display(Name = "Show")] IsShow = 2, [Display(Name = "Clip")] IsClip = 3, [Display(Name = "Trailer")] IsTrailer = 4 } public enum Site { [Display(Name = "viphd.vn")] Home = 1, [Display(Name = "jj.viphd.vn")] JJHome = 2 } public enum HomeDisplayFilmType { [Display(Name = "Sự kiện: Phim Đang HOT")] FilmHot = 1, [Display(Name = "Phim lẻ mới up")] FilmRetail = 2, [Display(Name = "Phim bộ mới up")] FilmLengthEpisodes = 3, [Display(Name = "JJ Channel giới thiệu")] FilmJJChannelIntroduce = 4, [Display(Name = "Phim chiếu rạp")] FilmTheater = 5, [Display(Name = "TV Show")] TVShow = 6, [Display(Name = "Clip")] Clip = 7, [Display(Name = "Bình luận Facebook")] FacebookComments = 8, [Display(Name = "Phim lẻ xem nhiều nhất")] StatisticalFilmRetail = 9, [Display(Name = "Phim bộ xem nhiều nhất")] StatisticalLengthEpisodes = 10, [Display(Name = "Show xem nhiều nhất")] StatisticalShows = 11, [Display(Name = "Clip xem nhiều nhất")] StatisticalClips = 12, [Display(Name = "Phim sắp chiếu")] StatisticalTrailer = 13, [Display(Name = "Phim liên quan")] StatisticalNextFilm = 14 } public enum LogStatus { [Display(Name = "Thông báo lỗi")] Error = 1, [Display(Name = "Thông báo thành công")] Success = 2, [Display(Name = "Cập nhập dữ liệu")] Information = 3 } public enum LogType { [Display(Name = "Tin nhắn tổng đài")] SMS = 1, [Display(Name = "Thẻ ngân hàng")] BankCard = 2, [Display(Name = "Thẻ cào")] ScratchCard = 3, [Display(Name = "Khác")] Other = 4, } public enum CustomerLogType { [Display(Name = "Hệ thống log")] SystemLogs = 1, [Display(Name = "Nạp tiền")] NapVipLogs = 2, [Display(Name = "Đổi VipXu")] VipXuLogs = 3, [Display(Name = "Đào Xu")] DaoXuLogs = 4 } public enum AmountType { [Display(Name = "Không tính tiền khách hàng")] NotAmount = 0, [Display(Name = "Tính tiền khách hàng")] Amount = 1, [Display(Name = "Trả lại tiền khách hàng")] ResultAmount = 2 } public enum SMSType { [Display(Name = "Nhận dữ liệu từ nhà mạng")] MO = 1, [Display(Name = "Gửi thông báo cho khách hàng")] MT = 2 } public enum RequestStatus { [Display(Name = "Thực hiện giao dịch thành công")] Messages200 = 200, [Display(Name = "Thực hiện giao dịch thất bại, yêu cầu gửi lại")] Messages01 = 1, [Display(Name = "Trùng MTID")] Messages02 = 2, [Display(Name = "IP của đối tác không hợp lệ hoặc chưa được cấu hình trong hệ thống")] Messages03 = 3, [Display(Name = "Không tìm thấy thông tin Command Code trên hệ thống")] Messages04 = 4, [Display(Name = "Không tìm thấy service number trên hệ thống")] Messages05 = 5, [Display(Name = "Hệ thống tạm thời gặp lỗi")] Messages06 = 6, [Display(Name = "Sai check sum")] Messages17 = 17, [Display(Name = "Sai định dạng MTID")] Messages18 = 18, [Display(Name = "Method không được hỗ trợ")] Messages19 = 19, [Display(Name = "Không tim thấy MO của MT này(trong trường hợp xử dụng method= mtReceiver)")] Messages20 = 20 } public enum ShortCode { [Display(Name = "8076")] DauSo8076 = 8076, [Display(Name = "8176")] DauSo8176 = 8176, [Display(Name = "8276")] DauSo8276 = 8276, [Display(Name = "8376")] DauSo8376 = 8376, [Display(Name = "8476")] DauSo8476 = 8476, [Display(Name = "8576")] DauSo8576 = 8576, [Display(Name = "8676")] DauSo8676 = 8676, [Display(Name = "8776")] DauSo8776 = 8776 } public enum Gender { [Display(Name = "Không xác định")] None = 0, [Display(Name = "Nam")] Male = 1, [Display(Name = "Nữ")] Female = 2, } public enum LoginTypes { [Display(Name = "Mặc định")] None = 0, [Display(Name = "Facebook")] Facebook = 1, [Display(Name = "Google")] Google = 2, } public enum HomeWidgets { [Display(Name = "Banner ở bên trái slide chính")] BannerPageLeft = 1, [Display(Name = "Banner ở dưới slide chính")] BannerPageCenter = 2, [Display(Name = "Banner ở bên phải slide chính")] BannerPageRight = 3, [Display(Name = "Banner vị trí thứ nhất nội dung bên trái")] BannerContentLeftFirst = 4, [Display(Name = "Banner vị trí thứ hai nội dung bên trái")] BannerContentLeftSecond = 5, [Display(Name = "Banner vị trí thứ ba nội dung bên trái")] BannerContentLeftThird = 6, [Display(Name = "Banner vị trí thứ tư nội dung bên trái")] BannerContentLeftFourth = 7, [Display(Name = "Banner vị trí thứ năm nội dung bên trái")] BannerContentLeftFifth = 8, [Display(Name = "Banner vị trí thứ sáu nội dung bên trái")] BannerContentLeftSixth = 9, [Display(Name = "Banner vị trí thứ bảy nội dung bên trái")] BannerContentLeftSeventh = 10, [Display(Name = "Banner vị trí thứ nhất bên phải")] BannerRightFirst = 11, [Display(Name = "Banner vị trí thứ hai bên phải")] BannerRightSecond = 12, [Display(Name = "Banner vị trí thứ ba nội dung bên trái")] BannerRightThird = 13, [Display(Name = "Banner vị trí thứ tư nội dung bên trái")] BannerRightFourth = 14, [Display(Name = "Slider chính")] HomeSliderBanner = 15, [Display(Name = "Footer thông tin bản quyền")] HomeFooterLogoInformation = 16, [Display(Name = "Facebook Fanpage")] HomeFacebookFanpage = 17, [Display(Name = "Facebook Activity")] HomeFacebookActivity = 18, [Display(Name = "Facebook Follow")] HomeFacebookFollow = 19, [Display(Name = "Google Badge")] HomeGoogleBadge = 20, [Display(Name = "Banner vị trí thứ năm bên phải")] BannerRightFifth = 21, [Display(Name = "Banner vị trí thứ sáu bên phải")] BannerRightSixth = 22, [Display(Name = "Banner khu vực VIP")] BannerPageCenterVip = 23, [Display(Name = "Banner khu vực VIP trái")] BannerPageLeftVip = 24, [Display(Name = "Banner khu vực VIP phải")] BannerPageRightVip = 25, [Display(Name = "Chia sẻ mạng xã hội")] DisplaySocialNetwork = 26 } public enum BankErrorMessages { [Display(Name = "Thành công.")] Success = 0, [Display(Name = "Thất bại.")] Fail = 1, [Display(Name = "Chưa confirm được.")] NotConfirmedYet = 2, [Display(Name = "Đã confirm trước đó.")] ConfirmedBefore = 3, [Display(Name = "Giao dịch Pending.")] TransactionPending = 4, [Display(Name = "Sai MAC.")] MacFail = 5, [Display(Name = "Không xác định mã lỗi.")] Exception = 6, [Display(Name = "Giao dịch không tồn tại.")] NotExistTransaction = 7, [Display(Name = "Thông tin không đầy đủ.")] FieldsNotFull = 8, [Display(Name = "Đại lý không tồn tại.")] NotExistMerchant = 9, [Display(Name = "Sai định dạng.")] FalseFormat = 10, [Display(Name = "Sai thông tin.")] WrongInformation = 11, [Display(Name = "Ngân hàng tạm khóa hoặc không tồn tại.")] BankNotActive = 12, [Display(Name = "Có lỗi.")] Error = 13, [Display(Name = "Code không hợp lệ.")] NotExactlyCode = 14, [Display(Name = "Ngân hàng từ chối giao dịch.")] BankDeclined = 801, [Display(Name = "Mã đơn vị không tồn tại.")] MerchantNotExist = 803, [Display(Name = "Mã đơn vị không tồn tại.")] InvalidAccessCode = 804, [Display(Name = "Số tiền không hợp lệ.")] InvalidAmount = 805, [Display(Name = "Mã tiền tệ không tồn tại.")] InvalidCurrencyCode = 806, [Display(Name = "Lỗi không xác định.")] UnspecifiedFailure = 807, [Display(Name = "Số thẻ không đúng.")] InvalidCardNumber = 808, [Display(Name = "Tên chủ thẻ không đúng.")] InvalidCardName = 809, [Display(Name = "Thẻ hết hạn/thẻ bị khóa.")] ExpiredCard = 810, [Display(Name = "Thẻ chưa đăng ký dịch vụ Internet banking.")] CardNotRegisterService = 811, [Display(Name = "Ngày phát hành/hết hạn không đúng.")] InvalidCardDate = 812, [Display(Name = "Vượt quá hạn mức thanh toán.")] ExistAmount = 813, [Display(Name = "Số tiền không đủ để thanh toán.")] InsufficientFund = 821, [Display(Name = "Người sử dụng cancel.")] UserCancel = 899, [Display(Name = "Merchant_code không hợp lệ.")] InvalidMerchantCode = 901, [Display(Name = "Chuỗi mã hóa không hợp lệ.")] InvalidEncryption = 902, [Display(Name = "Merchant_tran_id không hợp lệ.")] InvalidMerchantTranId = 903, [Display(Name = "Không tìm thấy giao dịch trong hệ thống.")] NotFoundTransaction = 904, [Display(Name = "Đã xác nhận trước đó.")] AlreadyConfirmed = 906, [Display(Name = "Lỗi timeout xảy ra do không nhận thông điệp trả về.")] ErrorTimeout = 908, [Display(Name = "Số tiền không hợp lệ.")] NotInvalidAmount = 911, [Display(Name = "Phí không hợp lệ.")] InvalidFee = 912, [Display(Name = "Tax không hợp lệ.")] InvalidTax = 913 } public enum ErrorMessages { [Display(Name = "Giao dịch thành công")] Success = 1, [Display(Name = "Thẻ đã sử dụng")] CardIsUsed = -1, [Display(Name = "Thẻ đã khóa")] CardIsLocked = -2, [Display(Name = "Thẻ đã hết hạn sử dụng")] CardIsExpired = -3, [Display(Name = "Mã thẻ chưa được kích hoạt")] CardIsNotActivate = -4, [Display(Name = "Mã thẻ sai định dạng")] CardFormatIsIncorrect = -10, [Display(Name = "Thẻ không tồn tại")] CardIsNotExist = -12, [Display(Name = "Lỗi thẻ VMS không đúng định dạng.")] VMSCardWrongFomat = -99, [Display(Name = "Partner nhập sai mã thẻ quá 5 lần.")] WrongCardInputExceed = 5, [Display(Name = "Sai thông tin partner.")] PartnerInformationError = 6, [Display(Name = "Chưa nhận được kết quả trả về từ nhà cung cấp mã thẻ.")] TransactionPending = 99, [Display(Name = "Dữ liệu carddata không đúng.")] BadCardData = -24, [Display(Name = "Nhà cung cấp không tồn tại.")] NoProviderFound = -11, [Display(Name = "Sai IP.")] InvalidIPRequest = 8, [Display(Name = "Sai Session.")] InvalidSessionID = 3, [Display(Name = "Session hết hạn.")] SessionTimeOut = 7, [Display(Name = "Thẻ không sử dụng được.")] CardIsIncorrect = 4, [Display(Name = "Hệ thống tạm thời bận.")] SystemBusy = 13, [Display(Name = "Giao dịch thất bại.")] Fail = 0, [Display(Name = "Tạm thời khóa kênh nạp VMS do quá tải.")] VMSChargingChanelOverload = 9, [Display(Name = "Hệ thống nhà cung cấp gặp lỗi.")] ProviderError = 10, [Display(Name = "Nhà cung cấp tạm thời khóa partner do lỗi hệ thống.")] PartnerLocked = 10, [Display(Name = "Trùng TransactionId.")] TransactionDuplicate = 12, [Display(Name = "Thẻ đã sử dụng hoặc không tồn tại.")] CardIsUsedOrCardDoNotExist = 50, [Display(Name = "Seri thẻ không đúng.")] CardSerialIsInvalid = 51, [Display(Name = "Mã thẻ và serial không khớp.")] CardSerialAndPinIsNotMatch = 52, [Display(Name = "Serial hoặc mã thẻ không đúng.")] CardSerialOrPinIsIncorrect = 53, [Display(Name = "Serial hoặc mã thẻ không đúng.")] CardIsWaitingForActivate = 54, [Display(Name = "Các tạm thời bị block 24h.")] CardIsBlockFor24Hours = 55 } public enum Sex { [Display(Name = "Không xác định")] Other = 0, [Display(Name = "Nam")] Male = 1, [Display(Name = "Nữ")] Female = 2 } public enum Status { [Display(Name = "Đang sử dụng")] Approved = 1, [Display(Name = "Xóa tạm thời")] Deleted = 2 } public enum FilmGroup { [Display(Name = "Phim một tập")] FilmRetail = 1, [Display(Name = "Phim dài tập")] FilmLengthEpisodes = 2 } public enum SearchType { [Display(Name = "Phim")] Film = 1, [Display(Name = "Tin tức")] Articles = 2, [Display(Name = "Chuyên mục")] Category = 3 } }<file_sep>using System; using System.ComponentModel; using System.ComponentModel.DataAnnotations.Schema; using System.Runtime.Serialization; using CMSSolutions.Data; using CMSSolutions.Data.Entity; namespace CMSSolutions.Websites.Entities { [DataContract] public class TransactionSmsInfo : BaseEntity<long> { [DataMember] [DisplayName("PartnerId")] public string PartnerId { get; set; } [DataMember] [DisplayName("MoId")] public string MoId { get; set; } [DataMember] [DisplayName("MtId")] public string MtId { get; set; } [DataMember] [DisplayName("UserId")] public string UserId { get; set; } [DataMember] [DisplayName("ShortCode")] public string ShortCode { get; set; } [DataMember] [DisplayName("Keyword")] public string Keyword { get; set; } [DataMember] [DisplayName("Subkeyword")] public string Subkeyword { get; set; } [DataMember] [DisplayName("Content")] public string Content { get; set; } [DataMember] [DisplayName("TransDate")] public string TransDate { get; set; } [DataMember] [DisplayName("CheckSum")] public string CheckSum { get; set; } [DataMember] [DisplayName("Amount")] public string Amount { get; set; } [DataMember] [DisplayName("CreateDate")] public DateTime CreateDate { get; set; } [DataMember] [DisplayName("Type")] public int Type { get; set; } [DataMember] [DisplayName("Status")] public int Status { get; set; } [DataMember] [DisplayName("CustomerCode")] public string CustomerCode { get; set; } [NotMapped] [DisplayName("FullName")] public string FullName { get; set; } [DataMember] [DisplayName("TotalDay")] public int TotalDay { get; set; } [DataMember] [DisplayName("StartDate")] public DateTime? StartDate { get; set; } [NotMapped] [DisplayName(Constants.NotMapped)] public string TextStartDate { get { if (StartDate == null) { return string.Empty; } return StartDate.Value.ToString(Extensions.Constants.DateTimeFomatFull); } } [DataMember] [DisplayName("EndDate")] public DateTime? EndDate { get; set; } [NotMapped] [DisplayName(Constants.NotMapped)] public string TextEndDate { get { if (EndDate == null) { return string.Empty; } return EndDate.Value.ToString(Extensions.Constants.DateTimeFomatFull); } } [DataMember] [DisplayName("TransactionCode")] public string TransactionCode { get; set; } [DataMember] [DisplayName("IsLock")] public bool IsLock { get; set; } [DataMember] [DisplayName("IsClosed")] public bool IsClosed { get; set; } } public class TransactionSmsMap : EntityTypeConfiguration<TransactionSmsInfo>, IEntityTypeConfiguration { public TransactionSmsMap() { ToTable("Modules_TransactionSms"); HasKey(m => m.Id); Property(m => m.MoId).HasMaxLength(50); Property(m => m.UserId).HasMaxLength(250); Property(m => m.ShortCode).HasMaxLength(50); Property(m => m.Keyword).HasMaxLength(250); Property(m => m.Subkeyword).HasMaxLength(250); Property(m => m.TransDate).HasMaxLength(100); Property(m => m.Amount).HasMaxLength(250); Property(m => m.CustomerCode).HasMaxLength(250); Property(m => m.TransactionCode).HasMaxLength(50); } } }<file_sep>using System; using System.Globalization; using System.Web.Mvc; using CMSSolutions.Web.Mvc; using CMSSolutions.Web.Routing; using CMSSolutions.Web.Themes; using CMSSolutions.Web.UI.ControlForms; using CMSSolutions.Web.UI.Navigation; using CMSSolutions.Websites.Entities; using CMSSolutions.Websites.Extensions; using CMSSolutions.Websites.Models; using CMSSolutions.Websites.Services; namespace CMSSolutions.Websites.Controllers { [Themed(IsDashboard = true), Authorize] public class AdminAdvertisementGroupController : BaseAdminController { public AdminAdvertisementGroupController(IWorkContextAccessor workContextAccessor) : base(workContextAccessor) { TableName = "tblAdvertisementGroup"; } [Url("admin/advertisementgroup")] public ActionResult Index() { WorkContext.Breadcrumbs.Add(new Breadcrumb { Text = T("Quản lý nhóm quảng cáo"), Url = "#" }); var result = new ControlGridFormResult<AdvertisementGroupInfo> { Title = T("Quản lý nhóm quảng cáo"), CssClass = "table table-bordered table-striped", IsAjaxSupported = true, FetchAjaxSource = GetAdvertisementGroup, DefaultPageSize = WorkContext.DefaultPageSize, EnablePaginate = true, UpdateActionName = "Update", GridWrapperStartHtml = Constants.Grid.GridWrapperStartHtml, GridWrapperEndHtml = Constants.Grid.GridWrapperEndHtml, ClientId = TableName, ActionsColumnWidth = 100 }; result.AddCustomVar(Extensions.Constants.LanguageCode, "$('#" + Extensions.Constants.LanguageCode + "').val();", true); result.AddCustomVar(Extensions.Constants.SiteId, "$('#" + Extensions.Constants.SiteId + "').val();", true); result.AddCustomVar(Extensions.Constants.CategoryId, "$('#" + Extensions.Constants.CategoryId + "').val();", true); result.AddColumn(x => x.Code, T("Mã Nhóm")); result.AddColumn(x => x.GroupName, T("Tên nhóm")); result.AddColumn(x => x.CategoryName, T("Chuyên mục")); result.AddColumn(x => x.FullPath, T("Đường dẫn Xml")); result.AddColumn(x => x.TextCreateDate, "Ngày bắt đầu"); result.AddColumn(x => x.TextFinishTime, "Ngày hết hạn"); result.AddColumn(x => x.IsActived) .HasHeaderText(T("Sử dụng")) .AlignCenter() .HasWidth(100) .RenderAsStatusImage(false); result.AddAction().HasText(T("Thêm mới")) .HasUrl(Url.Action("Edit", RouteData.Values.Merge(new { id = 0 }))) .HasButtonStyle(ButtonStyle.Primary) .HasCssClass(Constants.RowLeft); result.AddAction().HasText(T("Tạo Xml")) .HasUrl(Url.Action("Index", "AdminVastXml")) .HasButtonStyle(ButtonStyle.Success) .HasRow(true); result.AddAction(new ControlFormHtmlAction(() => BuildLanguages(true, Extensions.Constants.SiteId))).HasParentClass(Constants.ContainerCssClassCol3); result.AddAction(new ControlFormHtmlAction(() => BuildSites(true, Extensions.Constants.CategoryId))).HasParentClass(Constants.ContainerCssClassCol3); result.AddAction(new ControlFormHtmlAction(BuildCategories)).HasParentClass(Constants.ContainerCssClassCol3).HasRow(true); result.AddRowAction() .HasText(T("Sửa")) .HasUrl(x => Url.Action("Edit", RouteData.Values.Merge(new { id = x.Id }))) .HasButtonStyle(ButtonStyle.Default) .HasButtonSize(ButtonSize.ExtraSmall); result.AddRowAction(true) .HasText(T("Xóa")) .HasName("Delete") .HasValue(x => x.Id.ToString(CultureInfo.InvariantCulture.ToString())) .HasButtonStyle(ButtonStyle.Danger) .HasButtonSize(ButtonSize.ExtraSmall); result.AddReloadEvent("UPDATE_ENTITY_COMPLETE"); result.AddReloadEvent("DELETE_ENTITY_COMPLETE"); return result; } private ControlGridAjaxData<AdvertisementGroupInfo> GetAdvertisementGroup(ControlGridFormRequest options) { var languageCode = WorkContext.CurrentCulture; if (Utilities.IsNotNull(Request.Form[Extensions.Constants.LanguageCode])) { languageCode = Request.Form[Extensions.Constants.LanguageCode]; } var siteId = 0; if (Utilities.IsNotNull(Request.Form[Extensions.Constants.SiteId])) { siteId = Convert.ToInt32(Request.Form[Extensions.Constants.SiteId]); } var categoryId = 0; if (Utilities.IsNotNull(Request.Form[Extensions.Constants.CategoryId])) { categoryId = Convert.ToInt32(Request.Form[Extensions.Constants.CategoryId]); } int totals; var items = WorkContext.Resolve<IAdvertisementGroupService>().SearchPaged(languageCode, siteId, categoryId, options.PageIndex, options.PageSize, out totals); var result = new ControlGridAjaxData<AdvertisementGroupInfo>(items, totals); return result; } [Url("admin/advertisementgroup/edit")] public ActionResult Edit(int id) { WorkContext.Breadcrumbs.Add(new Breadcrumb { Text = T("Quản lý nhóm quảng cáo"), Url = Url.Action("Index") }); WorkContext.Breadcrumbs.Add(new Breadcrumb { Text = T("Thông tin nhóm quảng cáo"), Url = "#" }); if (!ModelState.IsValid) { return new AjaxResult().Alert(T(Constants.Messages.InvalidModel)); } var model = new AdvertisementGroupModel(); if (id > 0) { var service = WorkContext.Resolve<IAdvertisementGroupService>(); model = service.GetById(id); } var result = new ControlFormResult<AdvertisementGroupModel>(model) { Title = T("Thông tin nhóm quảng cáo"), UpdateActionName = "Update", FormMethod = FormMethod.Post, SubmitButtonText = T("Lưu lại"), ShowBoxHeader = false, ShowCancelButton = false, FormWrapperStartHtml = Constants.Form.FormWrapperStartHtml, FormWrapperEndHtml = Constants.Form.FormWrapperEndHtml }; result.MakeReadOnlyProperty(x => x.Code); result.AddAction().HasText(T("Làm mới")) .HasUrl(Url.Action("Edit", RouteData.Values.Merge(new { id = 0 }))) .HasCssClass("btn btn-success"); result.AddAction().HasText(T("Trở về")) .HasUrl(Url.Action("Index")) .HasCssClass("btn btn-danger"); result.RegisterExternalDataSource(x => x.LanguageCode, y => BindLanguages()); result.RegisterCascadingDropDownDataSource(x => x.SiteId, Url.Action("GetSitesByLanguage")); result.RegisterCascadingDropDownDataSource(x => x.CategoryId, Url.Action("GetCategoriesBySite")); result.RegisterCascadingDropDownDataSource(x => x.AdvertisementIds, Url.Action("GetAdBySite")); return result; } [HttpPost, ValidateInput(false), FormButton("Save")] [Url("admin/advertisementgroup/update")] public ActionResult Update(AdvertisementGroupModel model) { if (!ModelState.IsValid) { return new AjaxResult().Alert(T(Constants.Messages.InvalidModel)); } var service = WorkContext.Resolve<IAdvertisementGroupService>(); AdvertisementGroupInfo item = model.Id == 0 ? new AdvertisementGroupInfo() : service.GetById(model.Id); item.LanguageCode = model.LanguageCode; item.SiteId = model.SiteId; item.CategoryId = model.CategoryId; item.Code = model.Code; item.GroupName = model.GroupName; item.Description = model.Description; item.AdvertisementIds = Utilities.ParseString(model.AdvertisementIds); item.IsGenerate = model.IsGenerate; item.IsActived = model.IsActived; item.CreateDate = DateTime.Now; item.FinishDate = DateTime.ParseExact(model.FinishDate, Extensions.Constants.DateTimeFomat, CultureInfo.InvariantCulture); item.FinishTime = model.FinishTime; service.Save(item); return new AjaxResult() .NotifyMessage("UPDATE_ENTITY_COMPLETE") .Alert(T("Cập nhật thành công!")); } [FormButton("Delete")] [HttpPost, ActionName("Update")] public ActionResult Delete(int id) { var service = WorkContext.Resolve<IAdvertisementGroupService>(); var obj = service.GetById(id); obj.IsActived = false; service.Update(obj); return new AjaxResult() .NotifyMessage("DELETE_ENTITY_COMPLETE") .Alert(T("Dữ liệu chuyển trạng thái xóa tạm thời!")); } } } <file_sep>using System; using System.Globalization; using System.Web.Mvc; using CMSSolutions.Extensions; using CMSSolutions.Web.Mvc; using CMSSolutions.Web.Routing; using CMSSolutions.Web.Themes; using CMSSolutions.Web.UI.ControlForms; using CMSSolutions.Web.UI.Navigation; using CMSSolutions.Websites.Entities; using CMSSolutions.Websites.Extensions; using CMSSolutions.Websites.Models; using CMSSolutions.Websites.Services; namespace CMSSolutions.Websites.Controllers { [Themed(IsDashboard = true), Authorize] public class AdminBankCardController : BaseAdminController { public AdminBankCardController(IWorkContextAccessor workContextAccessor) : base(workContextAccessor) { TableName = "tblBankCards"; } [Url("admin/bank-cards")] public ActionResult Index() { WorkContext.Breadcrumbs.Add(new Breadcrumb { Text = T("Quản lý dịch vụ thẻ ngân hàng"), Url = "#" }); var result = new ControlGridFormResult<BankCardInfo> { Title = T("Quản lý dịch vụ thẻ ngân hàng"), CssClass = "table table-bordered table-striped", IsAjaxSupported = true, FetchAjaxSource = GetBankCards, DefaultPageSize = WorkContext.DefaultPageSize, EnablePaginate = true, UpdateActionName = "Update", GridWrapperStartHtml = Constants.Grid.GridWrapperStartHtml, GridWrapperEndHtml = Constants.Grid.GridWrapperEndHtml, ClientId = TableName, ActionsColumnWidth = 100 }; result.AddCustomVar(Extensions.Constants.StatusId, "$('#" + Extensions.Constants.StatusId + "').val();", true); result.AddColumn(x => x.Id, T("ID")).HasWidth(60).AlignCenter(); result.AddColumn(x => x.BankCode, T("Mã ngân hàng")).AlignCenter().HasWidth(150); result.AddColumn(x => x.BankName, T("Tên ngân hàng")); result.AddColumn(x => EnumExtensions.GetDisplayName((Status)x.Status), T("Trạng thái")); result.AddAction().HasText(T("Thêm mới")) .HasUrl(Url.Action("Edit", RouteData.Values.Merge(new { id = 0 }))) .HasButtonStyle(ButtonStyle.Primary) .HasBoxButton(false) .HasRow(false) .HasCssClass(Constants.RowLeft) .HasRow(true) .ShowModalDialog(); result.AddAction(new ControlFormHtmlAction(BuildStatus)).HasParentClass(Constants.ContainerCssClassCol3); result.AddRowAction() .HasText(T("Sửa")) .HasUrl(x => Url.Action("Edit", RouteData.Values.Merge(new { id = x.Id }))) .HasButtonStyle(ButtonStyle.Default) .HasButtonSize(ButtonSize.ExtraSmall) .ShowModalDialog(); result.AddRowAction(true) .HasText(T("Xóa")) .HasName("Delete") .HasValue(x => x.Id.ToString(CultureInfo.InvariantCulture.ToString())) .HasButtonStyle(ButtonStyle.Danger) .HasButtonSize(ButtonSize.ExtraSmall) .HasConfirmMessage(T(Constants.Messages.ConfirmDeleteRecord).Text); result.AddReloadEvent("UPDATE_ENTITY_COMPLETE"); result.AddReloadEvent("DELETE_ENTITY_COMPLETE"); return result; } private ControlGridAjaxData<BankCardInfo> GetBankCards(ControlGridFormRequest options) { var status = 0; if (Utilities.IsNotNull(Request.Form[Extensions.Constants.StatusId])) { status = Convert.ToInt32(Request.Form[Extensions.Constants.StatusId]); } int totals; var items = WorkContext.Resolve<IBankCardService>().GetPaged(status, options.PageIndex, options.PageSize, out totals); var result = new ControlGridAjaxData<BankCardInfo>(items, totals); return result; } [Themed(false)] [Url("admin/bank-cards/edit/{id}")] public ActionResult Edit(int id) { WorkContext.Breadcrumbs.Add(new Breadcrumb { Text = T("Quản lý dịch vụ thẻ ngân hàng"), Url = Url.Action("Index") }); WorkContext.Breadcrumbs.Add(new Breadcrumb { Text = T("Thông tin dịch vụ thẻ ngân hàng"), Url = "#" }); var model = new BankCardModel(); if (id > 0) { var service = WorkContext.Resolve<IBankCardService>(); model = service.GetById(id); } var result = new ControlFormResult<BankCardModel>(model) { Title = T("Thông tin dịch vụ thẻ ngân hàng"), FormMethod = FormMethod.Post, UpdateActionName = "Update", SubmitButtonText = T("Lưu lại"), CancelButtonText = T("Đóng"), ShowBoxHeader = false, FormWrapperStartHtml = Constants.Form.FormWrapperStartHtml, FormWrapperEndHtml = Constants.Form.FormWrapperEndHtml }; result.RegisterExternalDataSource(x => x.Status, y => BindStatus()); return result; } [HttpPost, ValidateInput(false), FormButton("Save")] [Url("admin/bank-cards/update")] public ActionResult Update(BankCardModel model) { if (!ModelState.IsValid) { return new AjaxResult().Alert(T(Constants.Messages.InvalidModel)); } var service = WorkContext.Resolve<IBankCardService>(); BankCardInfo item = model.Id == 0 ? new BankCardInfo() : service.GetById(model.Id); item.BankCode = model.BankCode; item.BankName = model.BankName; item.Status = model.Status; service.Save(item); return new AjaxResult().NotifyMessage("UPDATE_ENTITY_COMPLETE") .Alert(T("Cập nhật thành công!")) .CloseModalDialog(); } [FormButton("Delete")] [HttpPost, ActionName("Update")] public ActionResult Delete(int id) { var service = WorkContext.Resolve<IBankCardService>(); var item = service.GetById(id); item.Status = (int)Status.Deleted; service.Update(item); return new AjaxResult() .NotifyMessage("DELETE_ENTITY_COMPLETE") .Alert(T("Dữ liệu chuyển trạng thái xóa tạm thời!")); } } } <file_sep>using System.Web.Mvc; using CMSSolutions.Web.Mvc; using CMSSolutions.Web.Themes; using CMSSolutions.Websites.Extensions; using CMSSolutions.Websites.Models; using CMSSolutions.Websites.Services; namespace CMSSolutions.Websites.Controllers { [Themed(IsDashboard = false)] public class HomeDigCoinsController : BaseHomeController { public HomeDigCoinsController(IWorkContextAccessor workContextAccessor) : base(workContextAccessor) { PageIndex = 1; } [HttpGet] [Url("{alias}/d{id}.html")] public ActionResult Index(string alias, int id) { if (!IsLogin) { return Redirect(Url.Action("Index", "Home")); } UrlLogin = Request.Url != null ? Request.Url.AbsoluteUri : Url.Action("Index", "Home"); SiteId = (int)Site.Home; var serviceCategory = WorkContext.Resolve<ICategoryService>(); serviceCategory.LanguageCode = WorkContext.CurrentCulture; serviceCategory.SiteId = SiteId; var category = serviceCategory.GetByIdCache(id); ViewData[Extensions.Constants.HeaderTitle] = category.Name; ViewData[Extensions.Constants.HeaderDescription] = category.Description; ViewData[Extensions.Constants.HeaderKeywords] = category.Tags; if (Request.QueryString["trang"] != null) { PageIndex = int.Parse(Request.QueryString["trang"]); } PageSize = 10; BuildFilmModules(); return View(); } [Url("{alias}/thongtin/{id}.html")] public ActionResult ShowInformations(string alias, int id) { if (!IsLogin) { return Redirect(Url.Action("Index", "Home")); } UrlLogin = Request.Url != null ? Request.Url.AbsoluteUri : Url.Action("Index", "Home"); SiteId = (int)Site.Home; var serviceCategory = WorkContext.Resolve<ICategoryService>(); serviceCategory.LanguageCode = WorkContext.CurrentCulture; serviceCategory.SiteId = SiteId; var category = serviceCategory.GetByIdCache(id); ViewData[Extensions.Constants.HeaderTitle] = category.Name; ViewData[Extensions.Constants.HeaderDescription] = category.Description; ViewData[Extensions.Constants.HeaderKeywords] = category.Tags; var viewRenderer = new ViewRenderer { Context = ControllerContext }; var customerService = WorkContext.Resolve<ICustomerService>(); var model = new DataViewerModel { Customer = customerService.GetCustomerByCacheId(UserId), DataType = 0 }; var view = viewRenderer.RenderPartialView(Extensions.Constants.DaoXuInformationsFilePath, model); WorkContext.Layout.FullContent.Add(new MvcHtmlString(view)); return View("Index"); } [Url("{alias}/xem-logs/{id}.html")] public ActionResult ShowLogs(string alias, int id) { UrlLogin = Request.Url != null ? Request.Url.AbsoluteUri : Url.Action("Index", "Home"); SiteId = (int)Site.Home; var serviceCategory = WorkContext.Resolve<ICategoryService>(); serviceCategory.LanguageCode = WorkContext.CurrentCulture; serviceCategory.SiteId = SiteId; var category = serviceCategory.GetByIdCache(id); ViewData[Extensions.Constants.HeaderTitle] = category.Name; ViewData[Extensions.Constants.HeaderDescription] = category.Description; ViewData[Extensions.Constants.HeaderKeywords] = category.Tags; var viewRenderer = new ViewRenderer { Context = ControllerContext }; var customerService = WorkContext.Resolve<ICustomerService>(); var service = WorkContext.Resolve<IDownloadCustomerService>(); var model = new DataViewerModel { Customer = customerService.GetCustomerByCacheId(UserId), DataType = 2, ListHistoryDownload = service.GetHistory(UserId) }; var view = viewRenderer.RenderPartialView(Extensions.Constants.DaoXuLogsFilePath, model); WorkContext.Layout.FullContent.Add(new MvcHtmlString(view)); return View("Index"); } [Url("{alias}/huong-dan/{id}.html")] public ActionResult ShowHelps(string alias, int id) { if (!IsLogin) { return Redirect(Url.Action("Index", "Home")); } UrlLogin = Request.Url != null ? Request.Url.AbsoluteUri : Url.Action("Index", "Home"); SiteId = (int)Site.Home; var serviceCategory = WorkContext.Resolve<ICategoryService>(); serviceCategory.LanguageCode = WorkContext.CurrentCulture; serviceCategory.SiteId = SiteId; var category = serviceCategory.GetByIdCache(id); ViewData[Extensions.Constants.HeaderTitle] = category.Name; ViewData[Extensions.Constants.HeaderDescription] = category.Description; ViewData[Extensions.Constants.HeaderKeywords] = category.Tags; var viewRenderer = new ViewRenderer { Context = ControllerContext }; var customerService = WorkContext.Resolve<ICustomerService>(); var model = new DataViewerModel { Customer = customerService.GetCustomerByCacheId(UserId), DataType = 3 }; var view = viewRenderer.RenderPartialView(Extensions.Constants.DaoXuHelpsFilePath, model); WorkContext.Layout.FullContent.Add(new MvcHtmlString(view)); return View("Index"); } private void BuildFilmModules() { var viewRenderer = new ViewRenderer {Context = ControllerContext}; if (!IsVip) { } var customerService = WorkContext.Resolve<ICustomerService>(); var service = WorkContext.Resolve<IDownloadGameService>(); var downloadService = WorkContext.Resolve<IDownloadCustomerService>(); var model = new DataViewerModel { Customer = customerService.GetCustomerByCacheId(UserId), PageIndex = PageIndex, PageSize = PageSize, DataType = 1, ListDownloadCustomer = downloadService.GetByCustomer(UserId) }; var totalRow = 0; model.ListGames = service.GetPaged(model.PageIndex, model.PageSize, out totalRow); model.TotalRow = totalRow; var view = viewRenderer.RenderPartialView(Extensions.Constants.DigCoinsFilePath, model); WorkContext.Layout.FullContent.Add(new MvcHtmlString(view)); } } } <file_sep>using System.ComponentModel; using System.ComponentModel.DataAnnotations.Schema; using System.Runtime.Serialization; using CMSSolutions.Data; using CMSSolutions.Data.Entity; namespace CMSSolutions.Websites.Entities { [DataContract] public class FilmVideoInfo : BaseEntity<long> { [DataMember] [DisplayName("FilmId")] public long FilmId { get; set; } [DataMember] [DisplayName("EpisodeId")] public int EpisodeId { get; set; } [NotMapped] [DisplayName("EpisodeName")] public string EpisodeName { get; set; } [NotMapped] [DisplayName("EpisodeCount")] public int EpisodeCount { get; set; } [DataMember] [DisplayName("FileId")] public long FileId { get; set; } [NotMapped] [DisplayName("FileName")] public string FileName { get; set; } [DataMember] [DisplayName("FullPath")] public string FullPath { get; set; } [DataMember] [DisplayName("ImageIcon")] public string ImageIcon { get; set; } [DataMember] [DisplayName("IsTraller")] public bool IsTraller { get; set; } [DataMember] [DisplayName("IsActived")] public bool IsActived { get; set; } [DataMember] [DisplayName("UrlSource")] public string UrlSource { get; set; } [DataMember] [DisplayName("UrlAlbum")] public string UrlAlbum { get; set; } [DataMember] [DisplayName("Subtitle")] public string Subtitle { get; set; } [DataMember] [DisplayName("StreamingUrl")] public string StreamingUrl { get; set; } [DataMember] [DisplayName("BaseUrl")] public string BaseUrl { get; set; } } public class FilmVideoMap : EntityTypeConfiguration<FilmVideoInfo>, IEntityTypeConfiguration { public FilmVideoMap() { ToTable("Modules_FilmVideos"); HasKey(m => m.Id); Property(m => m.FilmId).IsRequired(); Property(m => m.FileId).IsRequired(); Property(m => m.FullPath).HasMaxLength(300); Property(m => m.EpisodeId).IsRequired(); Property(m => m.ImageIcon).HasMaxLength(500); Property(m => m.UrlSource).HasMaxLength(500); Property(m => m.Subtitle).HasMaxLength(500); Property(m => m.BaseUrl).HasMaxLength(500); Property(m => m.StreamingUrl).HasMaxLength(500); Property(m => m.UrlAlbum).HasMaxLength(500); } } } <file_sep>using System; using System.Globalization; using System.Web.Mvc; using CMSSolutions.Web.Mvc; using CMSSolutions.Web.Routing; using CMSSolutions.Web.Themes; using CMSSolutions.Web.UI.ControlForms; using CMSSolutions.Web.UI.Navigation; using CMSSolutions.Websites.Entities; using CMSSolutions.Websites.Extensions; using CMSSolutions.Websites.Models; using CMSSolutions.Websites.Services; namespace CMSSolutions.Websites.Controllers { [Themed(IsDashboard = true), Authorize] public class AdminAdvertisementController : BaseAdminController { public AdminAdvertisementController(IWorkContextAccessor workContextAccessor) : base(workContextAccessor) { TableName = "tblAdvertisements"; } [Url("admin/advertisements")] public ActionResult Index() { WorkContext.Breadcrumbs.Add(new Breadcrumb { Text = T("Quản lý quảng cáo"), Url = "#" }); var result = new ControlGridFormResult<AdvertisementInfo> { Title = T("Quản lý quảng cáo"), CssClass = "table table-bordered table-striped", IsAjaxSupported = true, FetchAjaxSource = GetAdvertisements, DefaultPageSize = WorkContext.DefaultPageSize, EnablePaginate = true, UpdateActionName = "Update", GridWrapperStartHtml = Constants.Grid.GridWrapperStartHtml, GridWrapperEndHtml = Constants.Grid.GridWrapperEndHtml, ClientId = TableName, ActionsColumnWidth = 100 }; result.AddCustomVar(Extensions.Constants.LanguageCode, "$('#" + Extensions.Constants.LanguageCode + "').val();", true); result.AddCustomVar(Extensions.Constants.SiteId, "$('#" + Extensions.Constants.SiteId + "').val();", true); result.AddCustomVar(Extensions.Constants.FromDate, "$('#" + Extensions.Constants.FromDate + "').val();", true); result.AddCustomVar(Extensions.Constants.ToDate, "$('#" + Extensions.Constants.ToDate + "').val();", true); result.AddCustomVar(Extensions.Constants.SearchText, "$('#" + Extensions.Constants.SearchText + "').val();", true); result.AddColumn(x => x.KeyCode, T("Mã QC")); result.AddColumn(x => x.Title, T("Tiêu đề")); result.AddColumn(x => x.Link, T("Đường dẫn vast")); result.AddColumn(x => x.IsBlock) .HasHeaderText(T("Tạm khóa")) .AlignCenter() .HasWidth(100) .RenderAsStatusImage(false); result.AddAction().HasText(T("Thêm mới")) .HasUrl(Url.Action("Edit", RouteData.Values.Merge(new { id = 0 }))) .HasButtonStyle(ButtonStyle.Primary) .HasBoxButton(false) .HasRow(false) .HasCssClass(Constants.RowLeft) .HasRow(true); result.AddAction(new ControlFormHtmlAction(() => BuildLanguages(true, Extensions.Constants.SiteId))).HasParentClass(Constants.ContainerCssClassCol3); result.AddAction(new ControlFormHtmlAction(() => BuildSites(true, Extensions.Constants.CategoryId))).HasParentClass(Constants.ContainerCssClassCol3); result.AddAction(new ControlFormHtmlAction(() => BuildFromDate(false))).HasParentClass(Constants.ContainerCssClassCol3); result.AddAction(new ControlFormHtmlAction(() => BuildToDate(false))).HasParentClass(Constants.ContainerCssClassCol3); result.AddAction(new ControlFormHtmlAction(BuildSearchText)).HasParentClass(Constants.ContainerCssClassCol3); result.AddRowAction() .HasText(T("Sửa")) .HasUrl(x => Url.Action("Edit", RouteData.Values.Merge(new { id = x.Id }))) .HasButtonStyle(ButtonStyle.Default) .HasButtonSize(ButtonSize.ExtraSmall); result.AddRowAction(true) .HasText(T("Khóa")) .HasName("Delete") .HasValue(x => x.Id.ToString(CultureInfo.InvariantCulture.ToString())) .HasButtonStyle(ButtonStyle.Danger) .HasButtonSize(ButtonSize.ExtraSmall); result.AddReloadEvent("UPDATE_ENTITY_COMPLETE"); result.AddReloadEvent("DELETE_ENTITY_COMPLETE"); return result; } private ControlGridAjaxData<AdvertisementInfo> GetAdvertisements(ControlGridFormRequest options) { var searchText = string.Empty; if (Utilities.IsNotNull(Request.Form[Extensions.Constants.SearchText])) { searchText = Request.Form[Extensions.Constants.SearchText]; } var languageCode = WorkContext.CurrentCulture; if (Utilities.IsNotNull(Request.Form[Extensions.Constants.LanguageCode])) { languageCode = Request.Form[Extensions.Constants.LanguageCode]; } var siteId = 0; if (Utilities.IsNotNull(Request.Form[Extensions.Constants.SiteId])) { siteId = Convert.ToInt32(Request.Form[Extensions.Constants.SiteId]); } var fromDate = Utilities.DateNull(); if (Utilities.IsNotNull(Request.Form[Extensions.Constants.FromDate])) { fromDate = DateTime.ParseExact(Request.Form[Extensions.Constants.FromDate], Extensions.Constants.DateTimeFomat, CultureInfo.InvariantCulture); } var toDate = Utilities.DateNull(); if (Utilities.IsNotNull(Request.Form[Extensions.Constants.ToDate])) { toDate = DateTime.ParseExact(Request.Form[Extensions.Constants.ToDate], Extensions.Constants.DateTimeFomat, CultureInfo.InvariantCulture); } int totals; var items = WorkContext.Resolve<IAdvertisementService>().SearchPaged(searchText, languageCode, siteId, fromDate, toDate, options.PageIndex, options.PageSize, out totals); var result = new ControlGridAjaxData<AdvertisementInfo>(items, totals); return result; } [Url("admin/advertisements/edit")] public ActionResult Edit(int id) { WorkContext.Breadcrumbs.Add(new Breadcrumb { Text = T("Quản lý quảng cáo"), Url = Url.Action("Index") }); WorkContext.Breadcrumbs.Add(new Breadcrumb { Text = T("Thông tin quảng cáo"), Url = "#" }); if (!ModelState.IsValid) { return new AjaxResult().Alert(T(Constants.Messages.InvalidModel)); } var model = new AdvertisementModel(); if (id > 0) { var service = WorkContext.Resolve<IAdvertisementService>(); model = service.GetById(id); } var result = new ControlFormResult<AdvertisementModel>(model) { Title = T("Thông tin quảng cáo"), UpdateActionName = "Update", FormMethod = FormMethod.Post, SubmitButtonText = T("Lưu lại"), ShowBoxHeader = false, ShowCancelButton = false, FormWrapperStartHtml = Constants.Form.FormWrapperStartHtml, FormWrapperEndHtml = Constants.Form.FormWrapperEndHtml }; result.MakeReadOnlyProperty(x => x.KeyCode); result.AddAction().HasText(T("Làm mới")) .HasUrl(Url.Action("Edit", RouteData.Values.Merge(new { id = 0 }))) .HasCssClass("btn btn-success"); result.AddAction().HasText(T("Trở về")) .HasUrl(Url.Action("Index")) .HasCssClass("btn btn-danger"); result.RegisterExternalDataSource(x => x.LanguageCode, y => BindLanguages()); result.RegisterCascadingDropDownDataSource(x => x.SiteId, Url.Action("GetSitesByLanguage")); return result; } [HttpPost, ValidateInput(false), FormButton("Save")] [Url("admin/advertisements/update")] public ActionResult Update(AdvertisementModel model) { var service = WorkContext.Resolve<IAdvertisementService>(); AdvertisementInfo adsInfo = model.Id == 0 ? new AdvertisementInfo() : service.GetById(model.Id); adsInfo.Id = model.Id; adsInfo.LanguageCode = model.LanguageCode; adsInfo.SiteId = model.SiteId; adsInfo.Title = model.Title; adsInfo.KeyCode = model.KeyCode; adsInfo.Price = Convert.ToDecimal(model.Price); adsInfo.Code = model.Code; adsInfo.Link = model.Link; adsInfo.Type = model.Type; adsInfo.Duration = model.Duration; adsInfo.Position = model.Position; adsInfo.Skip = model.Skip; adsInfo.IsBlock = model.IsBlock; adsInfo.Click = string.Empty; service.Save(adsInfo); return new AjaxResult() .NotifyMessage("UPDATE_ENTITY_COMPLETE") .Alert(T("Cập nhật thành công!")); } [FormButton("Delete")] [HttpPost, ActionName("Update")] public ActionResult Delete(int id) { var service = WorkContext.Resolve<IAdvertisementService>(); var obj = service.GetById(id); obj.IsBlock = true; service.Update(obj); return new AjaxResult() .NotifyMessage("DELETE_ENTITY_COMPLETE") .Alert(T("Dữ liệu chuyển trạng thái xóa tạm thời!")); } } } <file_sep>using CMSSolutions.Localization; using CMSSolutions.Web.UI.Navigation; using CMSSolutions.Websites.Permissions; namespace CMSSolutions.Websites.Menus { public class NavigationProvider : INavigationProvider { public Localizer T { get; set; } public NavigationProvider() { T = NullLocalizer.Instance; } public void GetNavigation(NavigationBuilder builder) { builder.Add(T("Home"), "0", BuildHomeMenu); builder.Add(T("Danh mục"), "1", BuildManagers); builder.Add(T("Quản lý chuyên mục"), "2", b => b.Action("Index", "AdminCategory", new { area = "" }) .IconCssClass("fa-th") .Permission(AdminPermissions.ManagerCategories)); builder.Add(T("Quản lý tin tức"), "3", b => b.Action("Index", "AdminArticles", new { area = "" }) .IconCssClass("fa-rss-square") .Permission(AdminPermissions.ManagerArticles)); builder.Add(T("Quản lý phim"), "4", BuildMenuFilms); builder.Add(T("Quản lý giao dịch"), "5", BuildMenuCustomers); builder.Add(T("Quản lý logs"), "6", BuildMenuLogs); builder.Add(T("Quản lý đối soát"), "7", BuildReports); builder.Add(T("Hỏi đáp"), "8", BuildQandA); builder.Add(T("Đào xu"), "9", b => b.Action("Index", "AdminDownloadGames", new { area = "" }) .IconCssClass("fa-bullseye") .Permission(AdminPermissions.ManagerDownloadGames)); builder.Add(T("Quảng cáo"), "10", BuildAds); } private void BuildHomeMenu(NavigationItemBuilder builder) { builder.IconCssClass("fa-home") .Action("Index", "Admin", new { area = "" }) .Permission(AdminPermissions.ManagerAdmin); } private void BuildManagers(NavigationItemBuilder builder) { builder.IconCssClass("fa-qrcode"); builder.Add(T("Quản lý trang"), "0", b => b .Action("Index", "AdminSite", new {area = ""}) .IconCssClass("fa-flag") .Permission(AdminPermissions.ManagerSites)); builder.Add(T("Nước sản xuất"), "1", b => b .Action("Index", "AdminCountry", new { area = "" }) .Permission(AdminPermissions.ManagerCountries)); builder.Add(T("Đạo diễn"), "2", b => b .Action("Index", "AdminDirector", new { area = "" }) .Permission(AdminPermissions.ManagerDirectors)); builder.Add(T("Diễn viên"), "3", b => b .Action("Index", "AdminActor", new { area = "" }) .Permission(AdminPermissions.ManagerActors)); builder.Add(T("Thể loại phim"), "4", b => b .Action("Index", "AdminFilmTypes", new { area = "" }) .Permission(AdminPermissions.ManagerFilmTypes)); builder.Add(T("Bộ phim"), "5", b => b .Action("Index", "AdminCollection", new { area = "" }) .Permission(AdminPermissions.ManagerCollections)); builder.Add(T("Tập phim"), "6", b => b .Action("Index", "AdminEpisode", new { area = "" }) .Permission(AdminPermissions.ManagerEpisodes)); builder.Add(T("Tags"), "7", b => b .Action("Index", "AdminTag", new { area = "" }) .Permission(AdminPermissions.ManagerTags)); } private void BuildMenuFilms(NavigationItemBuilder builder) { builder.IconCssClass("fa-film"); builder.Add(T("Máy chủ"), "0", b => b .Action("Index", "AdminFilmServer", new { area = "" }) .Permission(AdminPermissions.ManagerServerFilms)); builder.Add(T("Videos"), "1", b => b .Action("Index", "FilmFiles", new { area = "" }) .Permission(AdminPermissions.ManagerFilmFiles)); builder.Add(T("Phim"), "2", b => b .Action("Index", "AdminFilm", new { area = "" }) .Permission(AdminPermissions.ManagerFilms)); builder.Add(T("Slider"), "3", b => b .Action("Index", "AdminSlider", new { area = "" }) .Permission(AdminPermissions.ManagerSlider)); } private void BuildMenuCustomers(NavigationItemBuilder builder) { builder.IconCssClass("fa-shopping-cart"); builder.Add(T("Loại thẻ cào"), "0", b => b .Action("Index", "AdminCardType", new { area = "" }) .Permission(AdminPermissions.ManagerCardTypes)); builder.Add(T("Thẻ ngân hàng"), "1", b => b .Action("Index", "AdminBankCard", new { area = "" }) .Permission(AdminPermissions.ManagerBankCards)); builder.Add(T("Thẻ VIP"), "2", b => b .Action("Index", "AdminVIPCard", new { area = "" }) .Permission(AdminPermissions.ManagerVipCards)); builder.Add(T("Khách hàng"), "3", b => b .Action("Index", "AdminCustomer", new { area = "" }) .Permission(AdminPermissions.ManagerCustomers)); builder.Add(T("Khuyến mãi"), "4", b => b .Action("Index", "AdminPromotion", new { area = "" }) .Permission(AdminPermissions.ManagerPromotions)); } private void BuildMenuLogs(NavigationItemBuilder builder) { builder.IconCssClass("fa-bug"); builder.Add(T("Logs hệ thống"), "0", b => b .Action("Index", "AdminLog", new { area = "" }) .Permission(AdminPermissions.ManagerSystemLogs)); } private void BuildReports(NavigationItemBuilder builder) { builder.IconCssClass("fa fa-bar-chart-o"); builder.Add(T("Đối soát SMS"), "0", b => b .Action("Index", "AdminReportSms", new { area = "" }) .Permission(AdminPermissions.ManagerAdminReportSms)); builder.Add(T("Đối soát ATM"), "1", b => b .Action("Index", "AdminReportBank", new { area = "" }) .Permission(AdminPermissions.ManagerAdminReportAtm)); builder.Add(T("Đối soát thẻ cào"), "2", b => b .Action("Index", "AdminReportCard", new { area = "" }) .Permission(AdminPermissions.ManagerAdminReportCard)); } private void BuildAds(NavigationItemBuilder builder) { builder.IconCssClass("fa-desktop"); builder.Add(T("Danh mục"), "0", b => b .Action("Index", "AdminAdvertisement", new { area = "" }) .Permission(AdminPermissions.ManagerAdvertisement)); builder.Add(T("Nội dung"), "1", b => b .Action("Index", "AdminVast", new { area = "" }) .Permission(AdminPermissions.ManagerVast)); builder.Add(T("Phân nhóm"), "2", b => b .Action("Index", "AdminAdvertisementGroup", new { area = "" }) .Permission(AdminPermissions.ManagerAdvertisementGroup)); } private void BuildQandA(NavigationItemBuilder builder) { builder.IconCssClass("fa-comments-o"); builder.Add(T("Hỏi đáp"), "0", b => b .Action("Index", "AdminSupport", new { area = "" }) .Permission(AdminPermissions.ManagerSupports)); builder.Add(T("Đánh giá, báo lỗi"), "1", b => b .Action("Index", "AdminRate", new { area = "" }) .Permission(AdminPermissions.ManagerRates)); } } }<file_sep>using System; using System.Collections.Generic; using System.Collections.Specialized; using System.IO; using System.Linq; using System.Net; using System.Net.Http; using System.Runtime.Serialization.Json; using System.Text; using System.Threading.Tasks; using System.Web; using DotNetOpenAuth.AspNet.Clients; using DotNetOpenAuth.Messaging; using Newtonsoft.Json; namespace CMSSolutions.Websites.Extensions { public class GoogleClient : OAuth2Client { private const string AuthorizationEndpoint = "https://accounts.google.com/o/oauth2/auth"; private const string TokenEndpoint = "https://accounts.google.com/o/oauth2/token"; private const string UserInfoEndpoint = "https://www.googleapis.com/oauth2/v1/userinfo"; private readonly string clientId; private readonly string clientSecret; public GoogleClient(string clientId, string clientSecret) : base("Google") { if (clientId == null) throw new ArgumentNullException("clientId"); if (clientSecret == null) throw new ArgumentNullException("clientSecret"); this.clientId = clientId; this.clientSecret = clientSecret; } protected override Uri GetServiceLoginUrl(Uri returnUrl) { var uriBuilder = new UriBuilder(AuthorizationEndpoint); uriBuilder.AppendQueryArgument("client_id", this.clientId); uriBuilder.AppendQueryArgument("redirect_uri", returnUrl.GetLeftPart(UriPartial.Path)); uriBuilder.AppendQueryArgument("response_type", "code"); uriBuilder.AppendQueryArgument("scope", "https://www.googleapis.com/auth/plus.login https://www.googleapis.com/auth/userinfo.email"); uriBuilder.AppendQueryArgument("state", returnUrl.Query.Substring(1)); return uriBuilder.Uri; } protected override IDictionary<string, string> GetUserData(string accessToken) { var uriBuilder = new UriBuilder(UserInfoEndpoint); uriBuilder.AppendQueryArgument("access_token", accessToken); WebRequest webRequest = WebRequest.Create(uriBuilder.Uri); using (var webResponse = (HttpWebResponse)webRequest.GetResponse()) { if (webResponse.StatusCode == HttpStatusCode.OK) { using (var responseStream = webResponse.GetResponseStream()) { if (responseStream == null) return null; var streamReader = new StreamReader(responseStream); var values = JsonConvert.DeserializeObject<Dictionary<string, string>>(streamReader.ReadToEnd()); if (values.ContainsKey("email") && !values.ContainsKey("username")) values.Add("username", values["email"]); return values; } } } return null; } protected override string QueryAccessToken(Uri returnUrl, string authorizationCode) { var values = new Dictionary<string, string> { {"code", authorizationCode}, {"client_id", this.clientId}, {"client_secret", this.clientSecret}, {"redirect_uri", returnUrl.GetLeftPart(UriPartial.Path)}, {"grant_type", "authorization_code"} }; string postData = String.Join("&", values.Select(x => Uri.EscapeDataString(x.Key) + "=" + Uri.EscapeDataString(x.Value)).ToArray()); WebRequest webRequest = WebRequest.Create(TokenEndpoint); webRequest.ContentType = "application/x-www-form-urlencoded"; webRequest.ContentLength = postData.Length; webRequest.Method = "POST"; using (Stream requestStream = webRequest.GetRequestStream()) { var streamWriter = new StreamWriter(requestStream); streamWriter.Write(postData); streamWriter.Flush(); } using (var webResponse = (HttpWebResponse)webRequest.GetResponse()) { if (webResponse.StatusCode == HttpStatusCode.OK) { using (Stream responseStream = webResponse.GetResponseStream()) { var streamReader = new StreamReader(responseStream); dynamic response = JsonConvert.DeserializeObject<dynamic>(streamReader.ReadToEnd()); return (string)response.access_token; } } } return null; } public static void RewriteRequest() { var ctx = HttpContext.Current; var stateString = HttpUtility.UrlDecode(ctx.Request.QueryString["state"]); if (stateString == null || !stateString.Contains("__provider__=Google")) return; var q = HttpUtility.ParseQueryString(stateString); q.Add(ctx.Request.QueryString); q.Remove("state"); ctx.RewritePath(ctx.Request.Path + "?" + q); } } }<file_sep>using System; using System.ComponentModel; using System.ComponentModel.DataAnnotations.Schema; using System.Runtime.Serialization; using CMSSolutions.Data; using CMSSolutions.Data.Entity; using CMSSolutions.Websites.Extensions; namespace CMSSolutions.Websites.Entities { [DataContract] public class FilmInfo : BaseEntity<long> { [DataMember] [DisplayName("FilmCode")] public string FilmCode { get; set; } [DataMember] [DisplayName("FilmNameEnglish")] public string FilmNameEnglish { get; set; } [DataMember] [DisplayName("FilmName")] public string FilmName { get; set; } [DataMember] [DisplayName("FilmAlias")] public string FilmAlias { get; set; } [DataMember] [DisplayName("LanguageCode")] public string LanguageCode { get; set; } [DataMember] [DisplayName("SiteId")] public int SiteId { get; set; } [DataMember] [DisplayName("CategoryIds")] public string CategoryIds { get; set; } [NotMapped] [DisplayName("CategoryAlias")] public string CategoryAlias { get; set; } [NotMapped] [DisplayName("CategoryNames")] public string CategoryNames { get; set; } [DataMember] [DisplayName("FilmTypeIds")] public string FilmTypeIds { get; set; } [NotMapped] [DisplayName("FilmTypeNames")] public string FilmTypeNames { get; set; } [NotMapped] [DisplayName("EpisodeCount")] public int EpisodeCount { get; set; } [DataMember] [DisplayName("CountryId")] public int CountryId { get; set; } [NotMapped] [DisplayName("CountryName")] public string CountryName { get; set; } [DataMember] [DisplayName("DirectorId")] public int DirectorId { get; set; } [NotMapped] [DisplayName("DirectorName")] public string DirectorName { get; set; } [DataMember] [DisplayName("ActorIds")] public string ActorIds { get; set; } [NotMapped] [DisplayName("ActorNames")] public string ActorNames { get; set; } [DataMember] [DisplayName("CollectionId")] public int CollectionId { get; set; } [NotMapped] [DisplayName("CollectionName")] public string CollectionName { get; set; } [DataMember] [DisplayName("IsFilmRetail")] public bool IsFilmRetail { get; set; } [DataMember] [DisplayName("IsFilmLengthEpisodes")] public bool IsFilmLengthEpisodes { get; set; } [DataMember] [DisplayName("ArticlesId")] public int ArticlesId { get; set; } [DataMember] [DisplayName("Time")] public string Time { get; set; } [DataMember] [DisplayName("Capacity")] public string Capacity { get; set; } [DataMember] [DisplayName("ReleaseYear")] public int ReleaseYear { get; set; } [DataMember] [DisplayName("CommentCount")] public int CommentCount { get; set; } [DataMember] [DisplayName("ViewCount")] public int ViewCount { get; set; } [DataMember] [DisplayName("CreateByUserId")] public int CreateByUserId { get; set; } [NotMapped] [DisplayName("FullName")] public string FullName { get; set; } [DataMember] [DisplayName("CreateDate")] public DateTime CreateDate { get; set; } [NotMapped] [DisplayName(Constants.NotMapped)] public string DisplayDate { get { return Utilities.DateString(CreateDate); } } [DataMember] [DisplayName("Contents")] public string Contents { get; set; } [DataMember] [DisplayName("Summary")] public string Summary { get; set; } [DataMember] [DisplayName("Description")] public string Description { get; set; } [DataMember] [DisplayName("Tags")] public string Tags { get; set; } [DataMember] [DisplayName("IsPublished")] public bool IsPublished { get; set; } [DataMember] [DisplayName("PublishedDate")] public DateTime? PublishedDate { get; set; } [DataMember] [DisplayName("IsHot")] public bool IsHot { get; set; } [DataMember] [DisplayName("IsHome")] public bool IsHome { get; set; } [DataMember] [DisplayName("Prices")] public decimal Prices { get; set; } [DataMember] [DisplayName("HasCopyright")] public bool HasCopyright { get; set; } [DataMember] [DisplayName("StartDate")] public DateTime? StartDate { get; set; } [DataMember] [DisplayName("EndDate")] public DateTime? EndDate { get; set; } [DataMember] [DisplayName("ImageIcon")] public string ImageIcon { get; set; } [DataMember] [DisplayName("ImageThumb")] public string ImageThumb { get; set; } [NotMapped] [DisplayName(Constants.NotMapped)] public string EncodeImageThumb { get { if (!string.IsNullOrEmpty(ImageThumb)) { return Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes(ImageThumb)); } return string.Empty; } } [DataMember] [DisplayName("ServerId")] public int ServerId { get; set; } [DataMember] [DisplayName("ServerIP")] public string ServerIp { get; set; } [NotMapped] [DisplayName("ServerName")] public string ServerName { get; set; } [DataMember] [DisplayName("Status")] public int Status { get; set; } [DataMember] [DisplayName("IsTheater")] public bool IsTheater { get; set; } [DataMember] [DisplayName("IsShow")] public bool IsShow { get; set; } [DataMember] [DisplayName("IsClip")] public bool IsClip { get; set; } [DataMember] [DisplayName("IsTrailer")] public bool IsTrailer { get; set; } [DataMember] [DisplayName("IsFilm")] public bool IsFilm { get; set; } #region Videos [NotMapped] [DisplayName("FullPath")] public string FullPath { get; set; } [NotMapped] [DisplayName("EpisodeId")] public int EpisodeId { get; set; } [NotMapped] [DisplayName("ImageIcon2")] public string ImageIcon2 { get; set; } [NotMapped] [DisplayName("HasTraller")] public bool HasTraller { get; set; } [NotMapped] [DisplayName("UrlSource")] public string UrlSource { get; set; } [NotMapped] [DisplayName(Constants.NotMapped)] public string EncodeSourceUrl { get { if (string.IsNullOrEmpty(UrlAlbum) && !string.IsNullOrEmpty(UrlSource)) { return Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes(UrlSource)); } return string.Empty; } } [NotMapped] [DisplayName("Subtitle")] public string Subtitle { get; set; } [NotMapped] [DisplayName(Constants.NotMapped)] public string EncodeSubtitle { get { if (!string.IsNullOrEmpty(Subtitle)) { return Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes(Subtitle)); } return string.Empty; } } [NotMapped] [DisplayName("StreamingUrl")] public string StreamingUrl { get; set; } [NotMapped] [DisplayName(Constants.NotMapped)] public string EncodeStreamingUrl { get { if (!string.IsNullOrEmpty(StreamingUrl)) { return Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes(StreamingUrl)); } return string.Empty; } } [NotMapped] [DisplayName("BaseUrl")] public string BaseUrl { get; set; } [NotMapped] [DisplayName("UrlAlbum")] public string UrlAlbum { get; set; } [NotMapped] [DisplayName("EpisodeName")] public string EpisodeName { get; set; } [NotMapped] [DisplayName("EpisodeIndex")] public int EpisodeIndex { get; set; } #endregion } public class FilmMap : EntityTypeConfiguration<FilmInfo>, IEntityTypeConfiguration { public FilmMap() { ToTable("Modules_Film"); HasKey(m => m.Id); Property(m => m.FilmCode).IsRequired().HasMaxLength(50); Property(m => m.FilmNameEnglish).HasMaxLength(250); Property(m => m.FilmName).IsRequired().HasMaxLength(250); Property(m => m.FilmAlias).IsRequired().HasMaxLength(250); Property(m => m.LanguageCode).IsRequired().HasMaxLength(50); Property(m => m.SiteId).IsRequired(); Property(m => m.CategoryIds).HasMaxLength(250).IsRequired(); Property(m => m.FilmTypeIds).HasMaxLength(250).IsRequired(); Property(m => m.CountryId).IsRequired(); Property(m => m.DirectorId).IsRequired(); Property(m => m.ActorIds).IsRequired().HasMaxLength(250); Property(m => m.Time).IsRequired().HasMaxLength(50); Property(m => m.Capacity).IsRequired().HasMaxLength(50); Property(m => m.Contents).IsRequired(); Property(m => m.Summary).IsRequired().HasMaxLength(400); Property(m => m.Description).IsRequired().HasMaxLength(400); Property(m => m.Tags).IsRequired().HasMaxLength(250); Property(m => m.ImageIcon).IsRequired().HasMaxLength(250); Property(m => m.ImageThumb).HasMaxLength(250); Property(m => m.ServerIp).IsRequired().HasMaxLength(50); } } } <file_sep>using System; using System.Text; using System.Web.Mvc; using CMSSolutions.ContentManagement.Widgets.Services; using CMSSolutions.DisplayManagement; using CMSSolutions.Web.Mvc; using CMSSolutions.Web.Themes; using CMSSolutions.Websites.Entities; using CMSSolutions.Websites.Extensions; using CMSSolutions.Websites.Models; using CMSSolutions.Websites.Services; namespace CMSSolutions.Websites.Controllers { [Themed(IsDashboard = false)] public class HomeNewsController : BaseHomeController { private readonly dynamic shapeFactory; public HomeNewsController(IWorkContextAccessor workContextAccessor, IShapeFactory shapeFactory) : base(workContextAccessor) { this.shapeFactory = shapeFactory; PageIndex = 1; } [Url("tintuc.html")] public ActionResult Index() { UrlLogin = Request.Url != null ? Request.Url.AbsoluteUri : Url.Action("Index", "Home"); BuildNewsModules((int)FixCategories.AllNews, true); return View(); } [Url("{alias}/nc{id}.html")] public ActionResult ViewNewsCategory(string alias, int id) { UrlLogin = Request.Url != null ? Request.Url.AbsoluteUri : Url.Action("Index", "Home"); BuildNewsModules(id, true); return View(); } [Url("tintuc/{alias}/n{id}.html")] public ActionResult ViewDetails(string alias, int id) { UrlLogin = Request.Url != null ? Request.Url.AbsoluteUri : Url.Action("Index", "Home"); BuildNewsModules(id, false); return View(); } private void BuildNewsModules(int id, bool isCategory) { var widget = WorkContext.Resolve<IWidgetService>(); var viewRenderer = new ViewRenderer { Context = ControllerContext }; if (!IsVip) { #region BannerRightFifth var bannerRightFifth = widget.GetWidget(HomeWidgets.BannerRightFifth.ToString()); if (bannerRightFifth != null) { var widgetShape = shapeFactory.Widget(); widgetShape.Widget = bannerRightFifth; WorkContext.Layout.AdBannerRightFifth(widgetShape); } #endregion } else { #region BannerPageLeftVip var bannerPageLeftVip = widget.GetWidget(HomeWidgets.BannerPageLeftVip.ToString()); if (bannerPageLeftVip != null) { var widgetShape = shapeFactory.Widget(); widgetShape.Widget = bannerPageLeftVip; WorkContext.Layout.AdBannerPageLeftVip(widgetShape); } #endregion #region BannerPageCenterVip var bannerPageCenterVip = widget.GetWidget(HomeWidgets.BannerPageCenterVip.ToString()); if (bannerPageCenterVip != null) { var widgetShape = shapeFactory.Widget(); widgetShape.Widget = bannerPageCenterVip; WorkContext.Layout.AdBannerPageCenterVip(widgetShape); } #endregion #region BannerPageRightVip var bannerPageRightVip = widget.GetWidget(HomeWidgets.BannerPageRightVip.ToString()); if (bannerPageRightVip != null) { var widgetShape = shapeFactory.Widget(); widgetShape.Widget = bannerPageRightVip; WorkContext.Layout.AdBannerPageRightVip(widgetShape); } #endregion } #region HomeFooterLogoInformation var homeFooterLogoInformation = widget.GetWidget(HomeWidgets.HomeFooterLogoInformation.ToString()); if (homeFooterLogoInformation != null) { var widgetShape = shapeFactory.Widget(); widgetShape.Widget = homeFooterLogoInformation; WorkContext.Layout.FooterLogoInformation(widgetShape); } #endregion #region BannerRightFirst var view = viewRenderer.RenderPartialView(Extensions.Constants.DivDisplayFilePath, null); WorkContext.Layout.AdBannerRightFirst.Add(new MvcHtmlString(view)); #endregion #region HomeFacebookFanpage var homeFacebookFanpage = widget.GetWidget(HomeWidgets.HomeFacebookFanpage.ToString()); if (homeFacebookFanpage != null) { var widgetShape = shapeFactory.Widget(); widgetShape.Widget = homeFacebookFanpage; WorkContext.Layout.AdFacebookFanpage(widgetShape); } #endregion #region SocialNetwork var socialNetwork = widget.GetWidget(HomeWidgets.DisplaySocialNetwork.ToString()); if (socialNetwork != null) { var widgetShape = shapeFactory.Widget(); widgetShape.Widget = socialNetwork; WorkContext.Layout.DisplaySocialNetwork(widgetShape); } #endregion #region News var viewNews = viewRenderer.RenderPartialView(Extensions.Constants.NewsViewFilePath, null); WorkContext.Layout.DisplayNews.Add(new MvcHtmlString(viewNews)); #endregion #region Tags var serviceTags = WorkContext.Resolve<ITagService>(); var modelTags = new TagViewModel { ListTags = serviceTags.GetDisplayTags() }; var viewTags = viewRenderer.RenderPartialView(Extensions.Constants.TagViewFilePath, modelTags); WorkContext.Layout.DisplayTags.Add(new MvcHtmlString(viewTags)); #endregion #region CategoryContentFirst SiteId = (int)Site.Home; PageSize = 15; if (Request.QueryString["trang"] != null) { PageIndex = int.Parse(Request.QueryString["trang"]); } var serviceNews = WorkContext.Resolve<IArticlesService>(); serviceNews.LanguageCode = WorkContext.CurrentCulture; serviceNews.SiteId = SiteId; var serviceCategory = WorkContext.Resolve<ICategoryService>(); serviceCategory.SiteId = SiteId; serviceCategory.LanguageCode = WorkContext.CurrentCulture; var modelFirst = new DataViewCategoryModel(); if (!isCategory) { var news = serviceNews.GetById(id); ViewData[Extensions.Constants.HeaderTitle] = news.Title; ViewData[Extensions.Constants.HeaderDescription] = news.Description; ViewData[Extensions.Constants.HeaderKeywords] = news.Tags; modelFirst.News = news; modelFirst.CurrentCategory = serviceCategory.GetByIdCache(news.CategoryId); var viewFilmFirst = viewRenderer.RenderPartialView(Extensions.Constants.NewsDetailsViewFilePath, modelFirst); WorkContext.Layout.CategoryContentLeftFirst.Add(new MvcHtmlString(viewFilmFirst)); #region CategoryContentLeftSecond var viewModel = new DataViewCategoryModel(); viewModel.UrlNext = "http://" + Extensions.Constants.HomeDomainName + Url.Action("ViewDetails", "HomeNews", new { @alias = news.Alias, @id = news.Id }); var viewCommentFirst = viewRenderer.RenderPartialView(Extensions.Constants.FacebookCommentsFilePath, viewModel); WorkContext.Layout.CategoryContentLeftSecond.Add(new MvcHtmlString(viewCommentFirst)); #endregion } else { var category = serviceCategory.GetByIdCache(id); ViewData[Extensions.Constants.HeaderTitle] = category.Name; ViewData[Extensions.Constants.HeaderDescription] = category.Description; ViewData[Extensions.Constants.HeaderKeywords] = category.Tags; modelFirst.Breadcrumb = BuildBreadcrumb(category); modelFirst.CurrentCategory = category; var cateId = category.Id; if (cateId == (int)FixCategories.AllNews) { cateId = 0; } serviceNews.CategoryId = cateId; var totalRow = 0; modelFirst.ListArticles = serviceNews.GetByCategoryPaged(PageIndex, PageSize, out totalRow); modelFirst.TotalRow = totalRow; modelFirst.PageIndex = PageIndex; modelFirst.PageSize = PageSize; var viewFilmFirst = viewRenderer.RenderPartialView(Extensions.Constants.NewsCategoryViewFilePath, modelFirst); WorkContext.Layout.CategoryContentLeftFirst.Add(new MvcHtmlString(viewFilmFirst)); } #endregion #region DisplayStatistic1 var modelStatistic1 = new DataViewCategoryModel { Type = (int)HomeDisplayFilmType.StatisticalFilmRetail, Title = "PHIM LẺ XEM NHIỀU NHẤT" }; var viewStatistic1 = viewRenderer.RenderPartialView(Extensions.Constants.Statistic1FilePath, modelStatistic1); WorkContext.Layout.DisplayStatistic1.Add(new MvcHtmlString(viewStatistic1)); #endregion #region DisplayStatistic2 var modelStatistic2 = new DataViewCategoryModel { Type = (int)HomeDisplayFilmType.StatisticalLengthEpisodes, Title = "PHIM BỘ XEM NHIỀU NHẤT" }; var viewStatistic2 = viewRenderer.RenderPartialView(Extensions.Constants.Statistic2FilePath, modelStatistic2); WorkContext.Layout.DisplayStatistic2.Add(new MvcHtmlString(viewStatistic2)); #endregion } private string BuildBreadcrumb(CategoryInfo category) { var serviceCategory = WorkContext.Resolve<ICategoryService>(); serviceCategory.LanguageCode = WorkContext.CurrentCulture; serviceCategory.SiteId = SiteId; var html = new StringBuilder(); html.Append("<div class=\"mh-breadcrumb-dv\">"); html.Append("<div>"); html.AppendFormat("<a title=\"{0}\" href=\"{1}\"><span><img width=\"22\" src=\"/Images/themes/ico-home_trans.png\"></span></a>", "Dành cho víp", "/"); html.Append("</div>/ "); if (category.ParentId > 0) { var parent = serviceCategory.GetByIdCache(category.ParentId); html.Append("<div>"); html.AppendFormat("<a title=\"{0}\" href=\"{1}\"><span>{0}</span></a>", parent.ShortName, Url.Action("Index", "HomeCategory", new { @alias = parent.Alias, @id = parent.Id })); html.Append("</div>/ "); } html.Append("<div>"); html.AppendFormat("<a title=\"{0}\" href=\"{1}\"><span>{0}</span></a>", category.ShortName, "#"); html.Append("</div>"); html.Append("</div>"); return html.ToString(); } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Web.Mvc; using CMSSolutions.Web.Mvc; using CMSSolutions.Web.Themes; using CMSSolutions.Web.UI.ControlForms; using CMSSolutions.Web.UI.Navigation; using CMSSolutions.Websites.Entities; using CMSSolutions.Websites.Extensions; using CMSSolutions.Websites.Models; using CMSSolutions.Websites.Services; namespace CMSSolutions.Websites.Controllers { [Themed(IsDashboard = true), Authorize] public class AdminPromotionCustomersController : BaseAdminController { public AdminPromotionCustomersController(IWorkContextAccessor workContextAccessor) : base(workContextAccessor) { TableName = "tblPromotionCustomers"; } [Url("admin/promotion-customer/apply/{promotionId}")] public ActionResult Index(int promotionId) { WorkContext.Breadcrumbs.Add(new Breadcrumb { Text = T("Quản lý đợt khuyến mãi"), Url = Url.Action("Index","AdminPromotion") }); WorkContext.Breadcrumbs.Add(new Breadcrumb { Text = T("Áp dụng chương trình khuyến mãi"), Url = "#" }); var promotionCustomers = WorkContext.Resolve<IPromotionCustomersService>().GetCode(promotionId, 0); var model = new PromotionCustomersModel(); var promotion = WorkContext.Resolve<IPromotionService>().GetById(promotionId); if (promotion != null) { model.PromotionId = promotion.Id; model.PromotionName = promotion.Title; if (promotionCustomers != null) { model.Code = promotionCustomers.Code; model.Value = Convert.ToInt32(promotionCustomers.Value); } } var result = new ControlFormResult<PromotionCustomersModel>(model) { Title = T("Áp dụng chương trình khuyến mãi"), UpdateActionName = "Update", FormMethod = FormMethod.Post, SubmitButtonText = T("Lưu lại"), ShowBoxHeader = false, CancelButtonText = T("Trở về"), FormWrapperStartHtml = Constants.Form.FormWrapperStartHtml, FormWrapperEndHtml = Constants.Form.FormWrapperEndHtml }; result.MakeReadOnlyProperty(x => x.Code); result.MakeReadOnlyProperty(x => x.PromotionName); if (promotionCustomers != null) { result.MakeReadOnlyProperty(x => x.Value); } result.RegisterExternalDataSource(x => x.CustomerIds, y => BindCustomers(promotionId)); result.AddAction().HasText(T("Gửi thông báo")).HasButtonStyle(ButtonStyle.Info).HasUrl("javascript: void(0);") .OnClientClick("$.ajax({ url: '" + Url.Action("Send", "AdminPromotionCustomers") + "', data: {\"promotionId\": " + promotionId + "}, type: 'POST', dataType: 'json', success: function (result) { alert(result.Data);}});"); var result2 = new ControlGridFormResult<PromotionCustomerInfo> { Title = T("Khách hàng được khuyến mãi"), CssClass = "table table-bordered table-striped", IsAjaxSupported = true, FetchAjaxSource = GetPromotionCustomers, DefaultPageSize = WorkContext.DefaultPageSize, EnablePaginate = true, UpdateActionName = "Update", GridWrapperStartHtml = Constants.Grid.GridWrapperStartHtml, GridWrapperEndHtml = Constants.Grid.GridWrapperEndHtml, ClientId = TableName, ActionsColumnWidth = 100 }; result2.AddColumn(x => x.CustomerCode, T("Mã KH")); result2.AddColumn(x => x.FullName, T("Họ và Tên")); result2.AddColumn(x => x.Code, T("Mã KM")); result2.AddColumn(x => x.Value, T("Giá trị(VIPXU)")); result2.AddColumn(x => x.Description, T("Thông báo")); result2.AddColumn(x => x.IsUsed) .HasHeaderText(T("Sử dụng")) .AlignCenter() .HasWidth(100) .RenderAsStatusImage(); result2.AddColumn(x => x.IsSendMessages) .HasHeaderText(T("Gửi TB")) .AlignCenter() .HasWidth(100) .RenderAsStatusImage(); result2.AddRowAction(true) .HasText(T("Xóa")) .HasName("Delete") .HasValue(x => x.Id) .HasButtonStyle(ButtonStyle.Danger) .HasButtonSize(ButtonSize.ExtraSmall) .HasConfirmMessage(T(Constants.Messages.ConfirmDeleteRecord).Text); result2.AddCustomVar(Extensions.Constants.Id, promotionId); result2.AddReloadEvent("DELETE_ENTITY_COMPLETE"); return new ControlFormsResult(result, result2); } [HttpPost, ValidateInput(false)] [Url("admin/promotion-customer/send")] public ActionResult Send() { var redirect = new DataViewerModel(); var promotionId = Request.Form["promotionId"]; if (string.IsNullOrEmpty(promotionId)) { redirect.Status = true; redirect.Data = "Không tìm thấy ID đợt khuyến mãi."; return Json(redirect); } var id = int.Parse(promotionId); var promotion = WorkContext.Resolve<IPromotionService>().GetById(id); var customerHistoriesService = WorkContext.Resolve<ICustomerHistoriesService>(); var service = WorkContext.Resolve<IPromotionCustomersService>(); var listPromotionCustomers = service.GetByPromotion(id); foreach (var item in listPromotionCustomers) { if (item.IsSendMessages) { continue; } var historyCustomer = new CustomerHistoriesInfo { Type = (int)CustomerLogType.NapVipLogs, CustomerId = item.CustomerId, CreateDate = DateTime.Now, Action = item.Title, Description = string.Format("Bạn nhận được mã khuyến mãi {0} từ website VIPHD.VN. Vui lòng đăng nhập để kích hoạt khuyến mãi. Thời gian từ ngày {1} đến hết ngày {2}. Xin cảm ơn.", item.Code, promotion.FromDate.ToString(Extensions.Constants.DateTimeFomat), promotion.ToDate.ToString(Extensions.Constants.DateTimeFomat)), Status = (int)Status.Approved, TransactionCode = item.Code }; customerHistoriesService.Insert(historyCustomer); item.IsSendMessages = true; item.SendDate = DateTime.Now; service.Update(item); } redirect.Status = true; redirect.Data = "Đã gửi thông báo tới tất cả khách hàng có trong đợt khuyến mãi này."; return Json(redirect); } [HttpPost, ValidateInput(false), FormButton("Save")] [Url("admin/promotion-customer/update")] public ActionResult Update(PromotionCustomersModel model) { if (!ModelState.IsValid) { return new AjaxResult().Alert(T(Constants.Messages.InvalidModel)); } var service = WorkContext.Resolve<IPromotionCustomersService>(); var customerService = WorkContext.Resolve<ICustomerService>(); var promotion = WorkContext.Resolve<IPromotionService>().GetById(model.PromotionId); var listCustomerIds = model.CustomerIds; if (listCustomerIds.Contains(0)) { var items = customerService.GetPromotions(model.PromotionId); listCustomerIds = items.Select(x => x.Id).ToArray(); } for (int i = 0; i < listCustomerIds.Length; i++) { var customerId = listCustomerIds[i]; var customer = customerService.GetById(customerId); var promotionCustomers = service.GetCode(promotion.Id, customer.Id); if (promotionCustomers != null && customerId != 0) { continue; } var entity = new PromotionCustomerInfo { PromotionId = model.PromotionId, CustomerId = customer.Id, CustomerCode = customer.CustomerCode, CreateDate = DateTime.Now, Code = model.Code, Value = model.Value.ToString(), Description = string.Format("Bạn nhận được mã khuyến mãi {0} từ website VIPHD.VN. Vui lòng đăng nhập để kích hoạt khuyến mãi. Thời gian từ ngày {1} đến hết ngày {2}. Xin cảm ơn.", model.Code, promotion.FromDate.ToString(Extensions.Constants.DateTimeFomat), promotion.ToDate.ToString(Extensions.Constants.DateTimeFomat)), IsUsed = false, UsedDate = Utilities.DateNull(), IsSendMessages = false, SendDate = Utilities.DateNull() }; service.Insert(entity); } return new AjaxResult() .NotifyMessage("UPDATE_ENTITY_COMPLETE") .Alert(T("Cập nhật thành công!")) .Redirect(Url.Action("Index", new { @promotionId = model.PromotionId })); } [FormButton("Delete")] [HttpPost, ActionName("Update")] public ActionResult Delete(int id) { var service = WorkContext.Resolve<IPromotionCustomersService>(); var item = service.GetById(id); if (item.IsUsed) { return new AjaxResult().Alert("Dữ liệu này đã sử dụng bạn không thể xóa."); } service.Delete(item); return new AjaxResult() .NotifyMessage("DELETE_ENTITY_COMPLETE") .Redirect(Url.Action("Index", new { @promotionId = item.PromotionId })); } private ControlGridAjaxData<PromotionCustomerInfo> GetPromotionCustomers(ControlGridFormRequest options) { var promotionId = 0; if (Utilities.IsNotNull(Request.Form[Extensions.Constants.Id])) { promotionId = Convert.ToInt32(Request.Form[Extensions.Constants.Id]); } var items = WorkContext.Resolve<IPromotionCustomersService>().GetByPromotion(promotionId); var result = new ControlGridAjaxData<PromotionCustomerInfo>(items); return result; } private IEnumerable<SelectListItem> BindCustomers(int promotionId) { var service = WorkContext.Resolve<ICustomerService>(); var items = service.GetPromotions(promotionId); var result = new List<SelectListItem>(); result.AddRange(items.Select(item => new SelectListItem { Text = item.FullName, Value = item.Id.ToString() })); result.Insert(0, new SelectListItem {Text = "--- Áp dụng cho tất cả khách hàng ---", Value = "0"}); return result; } } } <file_sep>using System; using System.Collections.Generic; using System.Data.SqlClient; using CMSSolutions.Extensions; using CMSSolutions.Websites.Entities; using CMSSolutions.Websites.Extensions; namespace CMSSolutions.Websites.Services { public class APISmsService : DataContexService { public string Amount(string shortCode, out int totalDate, out DateTime? startDate, out DateTime? endDate) { startDate = Utilities.DateNull(); endDate = Utilities.DateNull(); totalDate = 0; string amount = "0"; var code = EnumExtensions.Parse<ShortCode>(shortCode); switch (code) { case ShortCode.DauSo8076: amount = "500"; break; case ShortCode.DauSo8176: amount = "1000"; break; case ShortCode.DauSo8276: amount = "2000"; break; case ShortCode.DauSo8376: amount = "3000"; break; case ShortCode.DauSo8476: amount = "4000"; break; case ShortCode.DauSo8576: startDate = DateTime.Now; endDate = DateTime.Now.AddDays(1); totalDate = 1; amount = "5000"; break; case ShortCode.DauSo8676: startDate = DateTime.Now; endDate = DateTime.Now.AddDays(3); totalDate = 3; amount = "10000"; break; case ShortCode.DauSo8776: startDate = DateTime.Now; endDate = DateTime.Now.AddDays(5); totalDate = 5; amount = "15000"; break; } return amount; } public CustomerInfo GetByCustomerCode(string customerCode) { var list = new List<SqlParameter> { AddInputParameter("@CustomerCode", customerCode), }; return ExecuteReaderRecord<CustomerInfo>("sp_Customers_GetByCustomerCode", list.ToArray()); } public int SmsProcessing(TransactionSmsInfo entity) { var list = new List<SqlParameter> { AddInputParameter("@PartnerId", entity.PartnerId), AddInputParameter("@MoId", entity.MoId), AddInputParameter("@UserId", entity.UserId), AddInputParameter("@ShortCode", entity.ShortCode), AddInputParameter("@Keyword", entity.Keyword), AddInputParameter("@Subkeyword", entity.Subkeyword), AddInputParameter("@Content", entity.Content), AddInputParameter("@TransDate", entity.TransDate), AddInputParameter("@CheckSum", entity.CheckSum), AddInputParameter("@Amount", entity.Amount), AddInputParameter("@CreateDate", entity.CreateDate), AddInputParameter("@Status", entity.Status), AddInputParameter("@Type", entity.Type), AddInputParameter("@MtId", entity.MtId), AddInputParameter("@CustomerCode", entity.CustomerCode), AddInputParameter("@TotalDay", entity.TotalDay), AddInputParameter("@StartDate", entity.StartDate), AddInputParameter("@EndDate", entity.EndDate), AddInputParameter("@TransactionCode", entity.TransactionCode), AddInputParameter("@IsLock", entity.IsLock) }; return ExecuteNonQuery("sp_TransactionSms_SmsProcessing", list.ToArray()); } public int InsertLog(LogInfo entity) { var list = new List<SqlParameter> { AddInputParameter("@CreateDate", entity.CreateDate), AddInputParameter("@Type", entity.Type), AddInputParameter("@Messages", entity.Messages), AddInputParameter("@Keyword", entity.Keyword), AddInputParameter("@Contents", entity.Contents), AddInputParameter("@Status", entity.Status) }; return ExecuteNonQuery("sp_Logs_Insert", list.ToArray()); } } }<file_sep>using System.Collections.Generic; using System.Data; using System.Web.Mvc; using System.Xml; using CMSSolutions.Web.Mvc; using CMSSolutions.Web.Themes; using CMSSolutions.Web.UI.ControlForms; using CMSSolutions.Web.UI.Navigation; using CMSSolutions.Websites.Extensions; using CMSSolutions.Websites.Models; using CMSSolutions.Websites.Services; namespace CMSSolutions.Websites.Controllers { [Themed(IsDashboard = true), Authorize] public class AdminVastXmlController : BaseAdminController { public AdminVastXmlController(IWorkContextAccessor workContextAccessor) : base(workContextAccessor) { } [Url("admin/vast/xml")] public ActionResult Index() { WorkContext.Breadcrumbs.Add(new Breadcrumb { Text = T("Quản lý nhóm quảng cáo"), Url = Url.Action("Index","AdminAdvertisementGroup") }); WorkContext.Breadcrumbs.Add(new Breadcrumb { Text = T("Tạo vast xml"), Url = "#" }); var model = new VastXmlModel(); var result = new ControlFormResult<VastXmlModel>(model) { Title = T("Tạo vast xml"), FormMethod = FormMethod.Post, UpdateActionName = "Update", SubmitButtonText = T("Tạo Xml"), CancelButtonText = T("Trở về"), CancelButtonUrl = Url.Action("Index", "AdminAdvertisementGroup"), ShowBoxHeader = false, FormWrapperStartHtml = Constants.Form.FormWrapperStartHtml, FormWrapperEndHtml = Constants.Form.FormWrapperEndHtml }; result.MakeReadOnlyProperty(x => x.Messages); return result; } [HttpPost, ValidateInput(false), FormButton("Save")] [Url("admin/vast/xml/create")] public ActionResult Update(VastXmlModel model) { var service = WorkContext.Resolve<IAdvertisementGroupService>(); var list = service.GetGroupGenerateXml(WorkContext.CurrentCulture); var data = service.GetDataGenerateXml(WorkContext.CurrentCulture).DefaultView; if (data.Count > 0) { foreach (var group in list) { data.RowFilter = string.Format("Id IN ({0})", group.AdvertisementIds); var listAds = new List<Ad>(); var doc = new XmlDocument(); foreach (DataRowView row in data) { var link = row["Link"].ToString(); if (link != "/") { continue; } var fileName = row["KeyCode"] + ".xml"; link = "/Media/Default/Advertisement/Vast/" + fileName; var item = new Ad { Click = row["Click"].ToString(), Duration = (int)row["Duration"], Id = row["Id"].ToString(), Link = link, Position = (int)row["Position"], Skip = (int)row["Skip"], Type = row["Type"].ToString() }; listAds.Add(item); data.RowFilter = string.Format("AdId = {0}", item.Id); foreach (DataRowView vast in data) { var dataVast = new Vast(); dataVast.ItemAds = new Ads { Id = int.Parse(item.Id), ObjectInLine = new InLine { ObjectAdSystem = new AdSystem { Version = vast["AdSystemVersion"].ToString(), Value = vast["AdSystemValue"].ToString() }, AdTitle = vast["AdTitle"].ToString(), Error = vast["LinkError"].ToString(), Impression = vast["LinkImpression"].ToString(), Creatives = new Creatives { ListCreatives = new Creative[] { new Creative { ObjectLinear = new Linear { Skipoffset = vast["Skipoffset"].ToString(), Duration = vast["Duration"].ToString(), VideoClicks = new VideoClicks { ClickThrough = vast["LinkClickThrough"].ToString() }, TrackingEvents = new TrackingEvents { LisTrackings = new Tracking[] { new Tracking { Event = vast["TrackingEvent1"].ToString(), Value = vast["TrackingValue1"].ToString()}, new Tracking { Event = vast["TrackingEvent2"].ToString(), Value = vast["TrackingValue2"].ToString()}, new Tracking { Event = vast["TrackingEvent3"].ToString(), Value = vast["TrackingValue3"].ToString()}, new Tracking { Event = vast["TrackingEvent4"].ToString(), Value = vast["TrackingValue4"].ToString()}, new Tracking { Event = vast["TrackingEvent5"].ToString(), Value = vast["TrackingValue5"].ToString()}, new Tracking { Event = vast["TrackingEvent6"].ToString(), Value = vast["TrackingValue6"].ToString()} } }, MediaFiles = new MediaFiles { ListMediaFiles = new MediaFile[] { new MediaFile { Bitrate = (int)vast["MediaFileBitrate"], Delivery = vast["MediaFileDelivery"].ToString(), Height = (int)vast["MediaFileHeight"], Width = (int)vast["MediaFileWidth"], MaintainAspectRatio = bool.Parse(vast["MediaFileMaintainAspectRatio"].ToString()), Scalable = bool.Parse(vast["MediaFileScalable"].ToString()), Type = vast["MediaFileType"].ToString(), Value = vast["MediaFileValue"].ToString() } } } } } } } } }; var xml = Utilities.SerializeXml<Vast>(dataVast); doc = new XmlDocument(); doc.LoadXml(xml); doc.Save(Server.MapPath(link)); } } if (listAds.Count > 0) { var ads = new Vplugin { ListAds = listAds.ToArray() }; var name = group.Code + ".xml"; var path = "/Media/Default/Advertisement/"; var rootXml = Utilities.SerializeXml<Vplugin>(ads); doc = new XmlDocument(); doc.LoadXml(rootXml); doc.Save(Server.MapPath(path + name)); var obj = service.GetById(group.Id); obj.IsGenerate = true; obj.FolderPath = path; obj.FileName = name; obj.FullPath = path + name; service.Update(obj); } } } return new AjaxResult() .NotifyMessage("UPDATE_ENTITY_COMPLETE") .Alert(string.Format(T("Đã tạo thành công các file vast xml!"))); } } } <file_sep>using CMSSolutions.Data; using CMSSolutions.Events; using CMSSolutions.Services; using CMSSolutions.Websites.Entities; namespace CMSSolutions.Websites.Services { public interface ISiteService : IGenericService<SiteInfo, int>, IDependency { } public class SiteService : GenericService<SiteInfo, int>, ISiteService { public SiteService(IRepository<SiteInfo, int> repository, IEventBus eventBus) : base(repository, eventBus) { } } } <file_sep>using System.ComponentModel; using System.ComponentModel.DataAnnotations.Schema; using System.Runtime.Serialization; using CMSSolutions.Data; using CMSSolutions.Data.Entity; using CMSSolutions.Websites.Extensions; namespace CMSSolutions.Websites.Entities { [DataContract] public class FilmFilesInfo : BaseEntity<long> { [DataMember] [DisplayName("FileCode")] public string FileCode { get; set; } [DataMember] [DisplayName("LanguageCode")] public string LanguageCode { get; set; } [DataMember] [DisplayName("SiteId")] public int SiteId { get; set; } [DataMember] [DisplayName("ServerId")] public int ServerId { get; set; } [NotMapped] [DisplayName("ServerName")] public string ServerName { get; set; } [DataMember] [DisplayName("Name")] public string Name { get; set; } [DataMember] [DisplayName("FolderRoot")] public string FolderRoot { get; set; } [DataMember] [DisplayName("FolderName")] public string FolderName { get; set; } [DataMember] [DisplayName("FolderDay")] public string FolderDay { get; set; } [DataMember] [DisplayName("FolderPath")] public string FolderPath { get; set; } [DataMember] [DisplayName("FileName")] public string FileName { get; set; } [DataMember] [DisplayName("Extentions")] public string Extentions { get; set; } [DataMember] [DisplayName("FullPath")] public string FullPath { get; set; } [DataMember] [DisplayName("Size")] public string Size { get; set; } [DataMember] [DisplayName("CreateDate")] public System.DateTime CreateDate { get; set; } [NotMapped] [DisplayName(Constants.NotMapped)] public string DisplayDate { get { return Utilities.DateString(CreateDate); } } [DataMember] [DisplayName("HasUse")] public bool HasUse { get; set; } } public class FilmFilesMap : EntityTypeConfiguration<FilmFilesInfo>, IEntityTypeConfiguration { public FilmFilesMap() { ToTable("Modules_FilmFiles"); HasKey(m => m.Id); Property(m => m.FileCode).IsRequired().HasMaxLength(50); Property(m => m.LanguageCode).HasMaxLength(50); Property(m => m.Name).IsRequired().HasMaxLength(250); Property(m => m.FolderRoot).HasMaxLength(250); Property(m => m.FolderName).HasMaxLength(100); Property(m => m.FolderPath).IsRequired().HasMaxLength(300); Property(m => m.FileName).IsRequired().HasMaxLength(100); Property(m => m.Extentions).HasMaxLength(50); Property(m => m.FullPath).IsRequired().HasMaxLength(500); Property(m => m.CreateDate).IsRequired(); Property(m => m.HasUse).IsRequired(); Property(m => m.Size).HasMaxLength(250); Property(m => m.ServerId).IsRequired(); Property(m => m.FolderDay).HasMaxLength(100); } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Web.Mvc; using CMSSolutions.Extensions; using CMSSolutions.Web.Mvc; using CMSSolutions.Web.Routing; using CMSSolutions.Web.Themes; using CMSSolutions.Web.UI.ControlForms; using CMSSolutions.Web.UI.Navigation; using CMSSolutions.Websites.Entities; using CMSSolutions.Websites.Extensions; using CMSSolutions.Websites.Models; using CMSSolutions.Websites.Services; namespace CMSSolutions.Websites.Controllers { [Themed(IsDashboard = true), Authorize] public class AdminSupportController : BaseAdminController { public AdminSupportController(IWorkContextAccessor workContextAccessor) : base(workContextAccessor) { TableName = "tblSupports"; } [Url("admin/supports")] public ActionResult Index() { WorkContext.Breadcrumbs.Add(new Breadcrumb { Text = T("Hỗ trợ hỏi đáp"), Url = "#" }); var result = new ControlGridFormResult<SupportInfo> { Title = T("Hỗ trợ hỏi đáp"), CssClass = "table table-bordered table-striped", IsAjaxSupported = true, FetchAjaxSource = GetSupports, UpdateActionName = "Update", ActionsColumnWidth = 100, ClientId = TableName, DefaultPageSize = WorkContext.DefaultPageSize, GridWrapperStartHtml = Constants.Grid.GridWrapperStartHtml, GridWrapperEndHtml = Constants.Grid.GridWrapperEndHtml }; result.AddCustomVar(Extensions.Constants.LanguageCode, "$('#" + Extensions.Constants.LanguageCode + "').val();", true); result.AddCustomVar(Extensions.Constants.SiteId, "$('#" + Extensions.Constants.SiteId + "').val();", true); result.AddCustomVar(Extensions.Constants.SearchText, "$('#" + Extensions.Constants.SearchText + "').val();", true); result.AddCustomVar(Extensions.Constants.StatusId, "$('#" + Extensions.Constants.StatusId + "').val();", true); result.AddColumn(x => x.Title, T("Câu hỏi")); result.AddColumn(x => x.Messages, T("Trả lời")); result.AddColumn(x => EnumExtensions.GetDisplayName((Status)x.Status), T("Trạng thái")); result.AddAction().HasText(T("Thêm mới")) .HasUrl(Url.Action("Edit", RouteData.Values.Merge(new { id = 0 }))) .HasButtonStyle(ButtonStyle.Primary) .HasBoxButton(false) .HasCssClass(Constants.RowLeft) .HasRow(true); result.AddAction(new ControlFormHtmlAction(() => BuildLanguages(true, Extensions.Constants.SiteId))).HasParentClass(Constants.ContainerCssClassCol3); result.AddAction(new ControlFormHtmlAction(() => BuildSites(false, string.Empty))).HasParentClass(Constants.ContainerCssClassCol3); result.AddAction(new ControlFormHtmlAction(BuildSearchText)).HasParentClass(Constants.ContainerCssClassCol3); result.AddAction(new ControlFormHtmlAction(BuildStatus)).HasParentClass(Constants.ContainerCssClassCol3); result.AddRowAction() .HasText(T("Sửa")) .HasUrl(x => Url.Action("Edit", RouteData.Values.Merge(new { id = x.Id }))) .HasButtonStyle(ButtonStyle.Default) .HasButtonSize(ButtonSize.ExtraSmall); result.AddRowAction(true) .HasText(T("Xóa")) .HasName("Delete") .HasValue(x => x.Id) .HasButtonStyle(ButtonStyle.Danger) .HasButtonSize(ButtonSize.ExtraSmall) .HasConfirmMessage(T(Constants.Messages.ConfirmDeleteRecord).Text); result.AddReloadEvent("UPDATE_ENTITY_COMPLETE"); result.AddReloadEvent("DELETE_ENTITY_COMPLETE"); return result; } private ControlGridAjaxData<SupportInfo> GetSupports(ControlGridFormRequest options) { var languageCode = WorkContext.CurrentCulture; if (Utilities.IsNotNull(Request.Form[Extensions.Constants.LanguageCode])) { languageCode = Request.Form[Extensions.Constants.LanguageCode]; } var siteId = 0; if (Utilities.IsNotNull(Request.Form[Extensions.Constants.SiteId])) { siteId = Convert.ToInt32(Request.Form[Extensions.Constants.SiteId]); } var searchText = string.Empty; if (Utilities.IsNotNull(Request.Form[Extensions.Constants.SearchText])) { searchText = Request.Form[Extensions.Constants.SearchText]; } var statusId = 0; if (Utilities.IsNotNull(Request.Form[Extensions.Constants.StatusId])) { statusId = Convert.ToInt32(Request.Form[Extensions.Constants.StatusId]); } var total = 0; var service = WorkContext.Resolve<ISupportService>(); service.SiteId = siteId; service.LanguageCode = languageCode; var items = service.GetPaged(searchText, 0, statusId, options.PageIndex, options.PageSize, out total); var result = new ControlGridAjaxData<SupportInfo>(items, total); return result; } [Url("admin/supports/edit/{id}")] public ActionResult Edit(int id) { WorkContext.Breadcrumbs.Add(new Breadcrumb { Text = T("Hỗ trợ hỏi đáp"), Url = Url.Action("Index") }); WorkContext.Breadcrumbs.Add(new Breadcrumb { Text = T("Thông tin hỏi đáp"), Url = "#" }); var model = new SupportModel(); if (id > 0) { var service = WorkContext.Resolve<ISupportService>(); model = service.GetById(id); } var result = new ControlFormResult<SupportModel>(model) { Title = T("Thông tin hỏi đáp"), FormMethod = FormMethod.Post, UpdateActionName = "Update", SubmitButtonText = T("Lưu lại"), CancelButtonText = T("Trở về"), ShowBoxHeader = false, FormWrapperStartHtml = Constants.Form.FormWrapperStartHtml, FormWrapperEndHtml = Constants.Form.FormWrapperEndHtml }; result.RegisterExternalDataSource(x => x.LanguageCode, y => BindLanguages()); result.RegisterCascadingDropDownDataSource(x => x.SiteId, Url.Action("GetSitesByLanguage")); result.RegisterCascadingDropDownDataSource(x => x.ParentId, Url.Action("GetSupportBySite")); result.RegisterExternalDataSource(x => x.Status, y => BindStatus()); result.AddAction().HasText(T("Làm mới")) .HasUrl(Url.Action("Edit", RouteData.Values.Merge(new { id = 0 }))) .HasCssClass("btn btn-success"); return result; } [Url("admin/supports/get--support-by-site")] public ActionResult GetSupportBySite() { var languageCode = WorkContext.CurrentCulture; if (Utilities.IsNotNull(Request.Form[Extensions.Constants.LanguageCode])) { languageCode = Request.Form[Extensions.Constants.LanguageCode]; } var siteId = 0; if (Utilities.IsNotNull(Request.Form[Extensions.Constants.SiteId])) { siteId = Convert.ToInt32(Request.Form[Extensions.Constants.SiteId]); } var service = WorkContext.Resolve<ISupportService>(); service.LanguageCode = languageCode; service.SiteId = siteId; var items = service.GetRecords(x=> x.SiteId == siteId && x.LanguageCode == languageCode && x.IsGroup).ToList(); var result = new List<SelectListItem>(); result.AddRange(items.Select(item => new SelectListItem { Text = item.Title, Value = item.Id.ToString() })); result.Insert(0, new SelectListItem { Text = T("--- Không chọn ---"), Value = "0" }); return Json(result); } [HttpPost, ValidateInput(false), FormButton("Save")] [Url("admin/supports/update")] public ActionResult Update(SupportModel model) { if (!ModelState.IsValid) { return new AjaxResult().Alert(T(Constants.Messages.InvalidModel)); } var service = WorkContext.Resolve<ISupportService>(); SupportInfo item = model.Id == 0 ? new SupportInfo() : service.GetById(model.Id); item.LanguageCode = model.LanguageCode; item.SiteId = model.SiteId; item.ParentId = model.ParentId; item.OrderBy = model.OrderBy; item.Title = model.Title; item.Messages = model.Messages; item.IsGroup = model.IsGroup; item.Status = model.Status; service.Save(item); return new AjaxResult().NotifyMessage("UPDATE_ENTITY_COMPLETE") .Alert(T("Cập nhật thành công!")); } [FormButton("Delete")] [HttpPost, ActionName("Update")] public ActionResult Delete(int id) { var service = WorkContext.Resolve<ISupportService>(); var item = service.GetById(id); service.Delete(item); return new AjaxResult() .NotifyMessage("DELETE_ENTITY_COMPLETE") .Alert(T("Xóa dữ liệu thành công!")); } } }<file_sep>namespace CMSSolutions.Websites.Payments { public class APIBankCardService { public string SenderKey { get { return System.Configuration.ConfigurationManager.AppSettings["SenderKey"]; } } public string ReceiverKey { get { return System.Configuration.ConfigurationManager.AppSettings["ReceiverKey"]; } } public string MerchantId = "88000072"; public string ReponseUrl { get; set; } } }<file_sep>using System; using System.Configuration; using System.IO; using System.Net; using System.Security.Cryptography; using System.Text; using System.Web; using CMSSolutions.Websites.Extensions; namespace CMSSolutions.Websites.Payments { public class APISms { public string PartnerId = ConfigurationManager.AppSettings["PartnerId"]; public string Password = ConfigurationManager.AppSettings["PartnerPassword"]; public string UrlSMSMT = ConfigurationManager.AppSettings["UrlSMSMT"]; public string Md5(string source_str) { MD5 encrypter = new MD5CryptoServiceProvider(); Byte[] original_bytes = ASCIIEncoding.Default.GetBytes(source_str); Byte[] encoded_bytes = encrypter.ComputeHash(original_bytes); return BitConverter.ToString(encoded_bytes).Replace("-", "").ToLower(); } public int SentMT(string moid, string shortcode, string keyword, string mobinumber, string contentmt, ref string url_) { url_ = CreatUrlMT(moid, shortcode, keyword, mobinumber, HttpUtility.UrlEncode(contentmt)); LogFiles.WriteLogSms(string.Format("MT URL: {0}", url_)); return SendRequest(url_); } private string CreatUrlMT(string moid, string shortcode, string keyword, string mobinumber, string contentmt) { var mtid = CreateMTId(); var transdate = DateTime.Now.ToString("yyyyMMddHHmmss"); string and = "&"; string url_ = UrlSMSMT; url_ += "partnerid=" + PartnerId + and; url_ += "moid=" + moid + and; url_ += "mtid=" + mtid + and; url_ += "userid=" + mobinumber + and; url_ += "shortcode=" + shortcode + and; url_ += "keyword=" + keyword + and; url_ += "content=" + contentmt + and; url_ += "messagetype=1" + and; url_ += "totalmessage=1" + and; url_ += "messageindex=1" + and; url_ += "ismore=0" + and; url_ += "contenttype=0" + and; url_ += "transdate=" + transdate + and; string checkSum = CreateCheckSumMT(transdate, contentmt, keyword, shortcode, moid, mtid); url_ += "checksum=" + checkSum; return url_; } public string CreateMTId() { var ran = new Random(); string kqran = ran.Next(0, 99999).ToString(); return PartnerId + DateTime.Now.ToString("yyyyMMddHHmmss") + kqran; } public string CreateCheckSumMT(string transdate, string Content, string Keyword, string ShortCode, string MoId, string mtId) { return Md5(mtId + MoId + ShortCode + Keyword + Content + transdate + Password); } public int SendRequest(string url) { try { var myRequest = (HttpWebRequest)WebRequest.Create(url); myRequest.Method = "GET"; WebResponse myResponse = myRequest.GetResponse(); var sr = new StreamReader(myResponse.GetResponseStream(), System.Text.Encoding.UTF8); string result = sr.ReadToEnd(); sr.Close(); myResponse.Close(); string[] s = result.Split('='); LogFiles.WriteLogSms(string.Format("MT: RESULT {0}", result)); if (result == "requeststatus=200") { return 200; } if (result == "requeststatus=17") { return 17; } LogFiles.WriteLogSms(string.Format("MT: SEND {0}", result)); return int.Parse(s[1]); } catch (Exception ex) { LogFiles.WriteLogSms(string.Format("MT: SEND ERROR {0}", ex.InnerException.Message)); throw ex; } } } }<file_sep>using CMSSolutions.Web.UI.ControlForms; using CMSSolutions.Websites.Entities; namespace CMSSolutions.Websites.Models { public class CardTypeModel { [ControlHidden()] public int Id { get; set; } [ControlText(Type = ControlText.TextBox, Required = true, MaxLength = 250, LabelText = "Mã loại thẻ", ContainerCssClass = Constants.ContainerCssClassCol3, ContainerRowIndex = 0)] public string Code { get; set; } [ControlText(Type = ControlText.TextBox, Required = true, MaxLength = 250, LabelText = "Tên loại thẻ", ContainerCssClass = Constants.ContainerCssClassCol3, ContainerRowIndex = 1)] public string Name { get; set; } [ControlChoice(ControlChoice.CheckBox, LabelText = "", PrependText = "Có serial", ContainerCssClass = Constants.ContainerCssClassCol3, ContainerRowIndex = 2)] public bool HasSerial { get; set; } [ControlChoice(ControlChoice.DropDownList, Required = true, LabelText = "Trạng thái", ContainerCssClass = Constants.ContainerCssClassCol3, ContainerRowIndex = 3)] public int Status { get; set; } public static implicit operator CardTypeModel(CardTypeInfo entity) { return new CardTypeModel { Id = entity.Id, Code = entity.Code, Name = entity.Name, HasSerial = entity.HasSerial, Status = entity.Status }; } } } <file_sep>using CMSSolutions.Web.UI.ControlForms; using CMSSolutions.Websites.Entities; namespace CMSSolutions.Websites.Models { public class SmsMessageModel { [ControlHidden] public int Id { get; set; } [ControlChoice(ControlChoice.DropDownList, Required = true, LabelText = "Ngôn ngữ hiển thị", ContainerCssClass = Constants.ContainerCssClassCol3, ContainerRowIndex = 0)] public string LanguageCode { get; set; } [ControlText(Type = ControlText.TextBox, LabelText = "Mã", PlaceHolder = "Tối đa 50 ký tự", Required = true, MaxLength = 250, ContainerCssClass = Constants.ContainerCssClassCol12, ContainerRowIndex = 1)] public string Code { get; set; } [ControlText(Type = ControlText.TextBox, LabelText = "Thông báo", PlaceHolder = "Tối đa 250 ký tự", Required = true, MaxLength = 250, ContainerCssClass = Constants.ContainerCssClassCol12, ContainerRowIndex = 1)] public string Messages { get; set; } [ControlChoice(ControlChoice.CheckBox, LabelText = "", PrependText = "Loại tin", ContainerCssClass = Constants.ContainerCssClassCol3, ContainerRowIndex = 0)] public bool IsEvent { get; set; } public static implicit operator SmsMessageModel(SmsMessageInfo entity) { return new SmsMessageModel { Id = entity.Id, LanguageCode = entity.LanguageCode, Code = entity.Code, Messages = entity.Message, IsEvent = entity.IsEvent }; } } }<file_sep>using System; using CMSSolutions.Web.UI.ControlForms; using CMSSolutions.Websites.Entities; namespace CMSSolutions.Websites.Models { public class PromotionModel { public PromotionModel() { FromDate = DateTime.Now.Date; ToDate = DateTime.Now.AddMonths(1).Date; } [ControlHidden] public int Id { get; set; } [ControlText(Type = ControlText.TextBox, LabelText = "Tiêu đề", PlaceHolder = "Tối đa 250 ký tự", Required = true, MaxLength = 250, ContainerCssClass = Constants.ContainerCssClassCol12, ContainerRowIndex = 0)] public string Title { get; set; } [ControlText(LabelText = "Nội dung thông báo", Required = true, Type = ControlText.RichText, ContainerCssClass = Constants.ContainerCssClassCol12, ContainerRowIndex = 1)] public string Contents { get; set; } [ControlDatePicker(LabelText = "Ngày bắt đầu", ContainerCssClass = Constants.ContainerCssClassCol4, ContainerRowIndex = 2)] public DateTime FromDate { get; set; } [ControlDatePicker(LabelText = "Ngày kết thúc", ContainerCssClass = Constants.ContainerCssClassCol4, ContainerRowIndex = 2)] public DateTime ToDate { get; set; } [ControlChoice(ControlChoice.DropDownList, Required = true, LabelText = "Trạng thái", ContainerCssClass = Constants.ContainerCssClassCol4, ContainerRowIndex = 2)] public int Status { get; set; } public static implicit operator PromotionModel(PromotionInfo entity) { return new PromotionModel { Id = entity.Id, Title = entity.Title, Contents = entity.Contents, FromDate = entity.FromDate, ToDate = entity.ToDate, Status = entity.Status }; } } }<file_sep>using System; using System.Globalization; using System.Web.Mvc; using CMSSolutions.Extensions; using CMSSolutions.Web.Mvc; using CMSSolutions.Web.Routing; using CMSSolutions.Web.Themes; using CMSSolutions.Web.UI.ControlForms; using CMSSolutions.Web.UI.Navigation; using CMSSolutions.Websites.Entities; using CMSSolutions.Websites.Extensions; using CMSSolutions.Websites.Models; using CMSSolutions.Websites.Services; namespace CMSSolutions.Websites.Controllers { [Themed(IsDashboard = true), Authorize] public class AdminEpisodeController : BaseAdminController { public AdminEpisodeController(IWorkContextAccessor workContextAccessor) : base(workContextAccessor) { TableName = "tblEpisodes"; } [Url("admin/episodes")] public ActionResult Index() { WorkContext.Breadcrumbs.Add(new Breadcrumb { Text = T("Quản lý các tập phim"), Url = "#" }); var result = new ControlGridFormResult<EpisodeInfo> { Title = T("Quản lý các tập phim"), CssClass = "table table-bordered table-striped", IsAjaxSupported = true, FetchAjaxSource = GetEpisodes, DefaultPageSize = WorkContext.DefaultPageSize, EnablePaginate = true, UpdateActionName = "Update", GridWrapperStartHtml = Constants.Grid.GridWrapperStartHtml, GridWrapperEndHtml = Constants.Grid.GridWrapperEndHtml, ClientId = TableName, ActionsColumnWidth = 100 }; result.AddCustomVar(Extensions.Constants.LanguageCode, "$('#" + Extensions.Constants.LanguageCode + "').val();", true); result.AddCustomVar(Extensions.Constants.SiteId, "$('#" + Extensions.Constants.SiteId + "').val();", true); result.AddCustomVar(Extensions.Constants.SearchText, "$('#" + Extensions.Constants.SearchText + "').val();", true); result.AddCustomVar(Extensions.Constants.StatusId, "$('#" + Extensions.Constants.StatusId + "').val();", true); result.AddColumn(x => x.EpisodeName, T("Tên tập phim")); result.AddColumn(x => x.OrderBy, T("Thứ tự")).AlignCenter().HasWidth(150); result.AddColumn(x => EnumExtensions.GetDisplayName((Status)x.Status), T("Trạng thái")); result.AddAction().HasText(T("Thêm mới")) .HasUrl(Url.Action("Edit", RouteData.Values.Merge(new { id = 0 }))) .HasButtonStyle(ButtonStyle.Primary) .HasBoxButton(false) .HasRow(false) .HasCssClass(Constants.RowLeft) .HasRow(true); result.AddAction(new ControlFormHtmlAction(() => BuildLanguages(true, Extensions.Constants.SiteId))).HasParentClass(Constants.ContainerCssClassCol3); result.AddAction(new ControlFormHtmlAction(() => BuildSites(false, string.Empty))).HasParentClass(Constants.ContainerCssClassCol3); result.AddAction(new ControlFormHtmlAction(BuildSearchText)).HasParentClass(Constants.ContainerCssClassCol3); result.AddAction(new ControlFormHtmlAction(BuildStatus)).HasParentClass(Constants.ContainerCssClassCol3); result.AddRowAction() .HasText(T("Sửa")) .HasUrl(x => Url.Action("Edit", RouteData.Values.Merge(new { id = x.Id }))) .HasButtonStyle(ButtonStyle.Default) .HasButtonSize(ButtonSize.ExtraSmall); result.AddRowAction(true) .HasText(T("Xóa")) .HasName("Delete") .HasValue(x => x.Id.ToString(CultureInfo.InvariantCulture.ToString())) .HasButtonStyle(ButtonStyle.Danger) .HasButtonSize(ButtonSize.ExtraSmall) .HasConfirmMessage(T(Constants.Messages.ConfirmDeleteRecord).Text); result.AddReloadEvent("UPDATE_ENTITY_COMPLETE"); result.AddReloadEvent("DELETE_ENTITY_COMPLETE"); return result; } private ControlGridAjaxData<EpisodeInfo> GetEpisodes(ControlGridFormRequest options) { var languageCode = WorkContext.CurrentCulture; if (Utilities.IsNotNull(Request.Form[Extensions.Constants.LanguageCode])) { languageCode = Request.Form[Extensions.Constants.LanguageCode]; } var siteId = 0; if (Utilities.IsNotNull(Request.Form[Extensions.Constants.SiteId])) { siteId = Convert.ToInt32(Request.Form[Extensions.Constants.SiteId]); } var searchText = string.Empty; if (Utilities.IsNotNull(Request.Form[Extensions.Constants.SearchText])) { searchText = Request.Form[Extensions.Constants.SearchText]; } var statusId = 0; if (Utilities.IsNotNull(Request.Form[Extensions.Constants.StatusId])) { statusId = Convert.ToInt32(Request.Form[Extensions.Constants.StatusId]); } int totals; var items = WorkContext.Resolve<IEpisodesService>().GetPaged(languageCode, siteId, searchText, statusId, options.PageIndex, options.PageSize, out totals); var result = new ControlGridAjaxData<EpisodeInfo>(items, totals); return result; } [Url("admin/episodes/edit/{id}")] public ActionResult Edit(int id) { WorkContext.Breadcrumbs.Add(new Breadcrumb { Text = T("Quản lý các tập phim"), Url = Url.Action("Index") }); WorkContext.Breadcrumbs.Add(new Breadcrumb { Text = T("Thông tin các tập phim"), Url = "#" }); var model = new EpisodeModel(); if (id > 0) { var service = WorkContext.Resolve<IEpisodesService>(); model = service.GetById(id); } var result = new ControlFormResult<EpisodeModel>(model) { Title = T("Thông tin các tập phim"), FormMethod = FormMethod.Post, UpdateActionName = "Update", SubmitButtonText = T("Lưu lại"), CancelButtonText = T("Đóng"), ShowBoxHeader = false, FormWrapperStartHtml = Constants.Form.FormWrapperStartHtml, FormWrapperEndHtml = Constants.Form.FormWrapperEndHtml }; result.RegisterExternalDataSource(x => x.LanguageCode, y => BindLanguages()); result.RegisterCascadingDropDownDataSource(x => x.SiteId, Url.Action("GetSitesByLanguage")); result.RegisterExternalDataSource(x => x.Status, y => BindStatus()); return result; } [HttpPost, ValidateInput(false), FormButton("Save")] [Url("admin/episodes/update")] public ActionResult Update(EpisodeModel model) { if (!ModelState.IsValid) { return new AjaxResult().Alert(T(Constants.Messages.InvalidModel)); } var service = WorkContext.Resolve<IEpisodesService>(); EpisodeInfo item = model.Id == 0 ? new EpisodeInfo() : service.GetById(model.Id); if (service.CheckExist(model.Id, model.EpisodeName)) { return new AjaxResult().NotifyMessage("UPDATE_ENTITY_COMPLETE") .Alert(T("Tên tập phim đã tồn tại.")); } item.LanguageCode = model.LanguageCode; item.SiteId = model.SiteId; item.EpisodeName = model.EpisodeName; item.OrderBy = model.OrderBy; item.Description = model.Description; item.Status = model.Status; service.Save(item); return new AjaxResult().NotifyMessage("UPDATE_ENTITY_COMPLETE") .Alert(T("Cập nhật thành công!")); } [FormButton("Delete")] [HttpPost, ActionName("Update")] public ActionResult Delete(int id) { var service = WorkContext.Resolve<IEpisodesService>(); var item = service.GetById(id); item.Status = (int)Status.Deleted; service.Update(item); return new AjaxResult() .NotifyMessage("DELETE_ENTITY_COMPLETE") .Alert(T("Dữ liệu chuyển trạng thái xóa tạm thời!")); } } } <file_sep>using CMSSolutions.Web.UI.ControlForms; using CMSSolutions.Websites.Entities; using CMSSolutions.Websites.Extensions; namespace CMSSolutions.Websites.Models { public class ActorModel { [ControlHidden] public int Id { get; set; } [ControlText(Type = ControlText.TextBox, Required = true, MaxLength = 250, LabelText = "<NAME>", ContainerCssClass = Constants.ContainerCssClassCol12, ContainerRowIndex = 0)] public string FullName { get; set; } [ControlChoice(ControlChoice.DropDownList, Required = true, LabelText = "Trạng thái", ContainerCssClass = Constants.ContainerCssClassCol12, ContainerRowIndex = 1)] public int Status { get; set; } [ControlText(Type = ControlText.MultiText, Rows = 3, MaxLength = 2000, LabelText = "Giới thiệu", ContainerCssClass = Constants.ContainerCssClassCol12, ContainerRowIndex = 2)] public string Description { get; set; } public static implicit operator ActorModel(ActorInfo entity) { return new ActorModel { Id = entity.Id, FullName = entity.FullName, Description = entity.Description, Status = entity.Status }; } } } <file_sep>using System; using System.Text; using System.Web.Mvc; using CMSSolutions.Web.Mvc; using CMSSolutions.Web.Routing; using CMSSolutions.Web.Themes; using CMSSolutions.Web.UI.ControlForms; using CMSSolutions.Web.UI.Navigation; using CMSSolutions.Websites.Entities; using CMSSolutions.Websites.Extensions; using CMSSolutions.Websites.Models; using CMSSolutions.Websites.Services; namespace CMSSolutions.Websites.Controllers { [Themed(IsDashboard = true), Authorize] public class AdminVastController : BaseAdminController { public AdminVastController(IWorkContextAccessor workContextAccessor) : base(workContextAccessor) { TableName = "tblVast"; } [Url("admin/vast")] public ActionResult Index() { WorkContext.Breadcrumbs.Add(new Breadcrumb { Text = T("Quản lý vast"), Url = "#" }); var result = new ControlGridFormResult<VastInfo> { Title = T("Quản lý vast"), CssClass = "table table-bordered table-striped", IsAjaxSupported = true, FetchAjaxSource = GetVast, UpdateActionName = "Update", ActionsColumnWidth = 100, ClientId = TableName, EnablePaginate = true, DefaultPageSize = WorkContext.DefaultPageSize, GridWrapperStartHtml = Constants.Grid.GridWrapperStartHtml, GridWrapperEndHtml = Constants.Grid.GridWrapperEndHtml }; result.AddCustomVar(Extensions.Constants.LanguageCode, "$('#" + Extensions.Constants.LanguageCode + "').val();", true); result.AddCustomVar(Extensions.Constants.SiteId, "$('#" + Extensions.Constants.SiteId + "').val();", true); result.AddCustomVar(Extensions.Constants.AdId, "$('#" + Extensions.Constants.AdId + "').val();", true); result.AddColumn(x => x.KeyCode, T("Mã Vast")); result.AddColumn(x => x.AdTitle, T("Tiêu đề")); result.AddColumn(x => x.AdName, T("Tên quảng cáo")); result.AddColumn(x => x.MediaFileValue, T("Đường dẫn file")); result.AddColumn(x => x.MediaFileType, T("Loại file")); result.AddAction().HasText(T("Thêm mới")) .HasUrl(Url.Action("Edit", RouteData.Values.Merge(new { id = 0 }))) .HasButtonStyle(ButtonStyle.Primary) .HasBoxButton(false) .HasCssClass(Constants.RowLeft) .HasRow(true); result.AddAction(new ControlFormHtmlAction(() => BuildLanguages(true, Extensions.Constants.SiteId))).HasParentClass(Constants.ContainerCssClassCol3); result.AddAction(new ControlFormHtmlAction(() => BuildSiteAds(true, Extensions.Constants.AdId))).HasParentClass(Constants.ContainerCssClassCol3); result.AddAction(new ControlFormHtmlAction(BuildAds)).HasParentClass(Constants.ContainerCssClassCol3).HasRow(true); result.AddRowAction() .HasText(T("Sửa")) .HasUrl(x => Url.Action("Edit", RouteData.Values.Merge(new { id = x.Id }))) .HasButtonStyle(ButtonStyle.Default) .HasButtonSize(ButtonSize.ExtraSmall); result.AddRowAction(true) .HasText(T("Xóa")) .HasName("Delete") .HasValue(x => x.Id) .HasButtonStyle(ButtonStyle.Danger) .HasButtonSize(ButtonSize.ExtraSmall) .HasConfirmMessage(T(Constants.Messages.ConfirmDeleteRecord).Text); result.AddReloadEvent("UPDATE_ENTITY_COMPLETE"); result.AddReloadEvent("DELETE_ENTITY_COMPLETE"); return result; } private string BuildAds() { var languageCode = WorkContext.CurrentCulture; if (Utilities.IsNotNull(Request.Form[Extensions.Constants.LanguageCode])) { languageCode = Request.Form[Extensions.Constants.LanguageCode]; } var siteId = 0; if (Utilities.IsNotNull(Request.Form[Extensions.Constants.SiteId])) { siteId = Convert.ToInt32(Request.Form[Extensions.Constants.SiteId]); } var service = WorkContext.Resolve<IAdvertisementService>(); var sb = new StringBuilder(); sb.AppendFormat(T("Chuyên mục") + " <select id=\"" + Extensions.Constants.CategoryId + "\" name=\"" + Extensions.Constants.CategoryId + "\" autocomplete=\"off\" class=\"uniform form-control col-md-3\" onchange=\"$('#" + TableName + "').jqGrid().trigger('reloadGrid');\">"); var list = service.GetRecords(x => x.LanguageCode == languageCode && x.SiteId == siteId); foreach (var cate in list) { sb.AppendFormat("<option value=\"{1}\">{0}</option>", cate.Title, cate.Id); } sb.Append("</select>"); return sb.ToString(); } private ControlGridAjaxData<VastInfo> GetVast(ControlGridFormRequest options) { var languageCode = WorkContext.CurrentCulture; if (Utilities.IsNotNull(Request.Form[Extensions.Constants.LanguageCode])) { languageCode = Request.Form[Extensions.Constants.LanguageCode]; } var siteId = 0; if (Utilities.IsNotNull(Request.Form[Extensions.Constants.SiteId])) { siteId = Convert.ToInt32(Request.Form[Extensions.Constants.SiteId]); } var adId = 0; if (Utilities.IsNotNull(Request.Form[Extensions.Constants.AdId])) { adId = Convert.ToInt32(Request.Form[Extensions.Constants.AdId]); } int totals; var items = WorkContext.Resolve<IVastService>().SearchPaged(languageCode, siteId, adId, options.PageIndex, options.PageSize, out totals); var result = new ControlGridAjaxData<VastInfo>(items, totals); return result; } [Url("admin/vast/edit/{id}")] public ActionResult Edit(int id) { WorkContext.Breadcrumbs.Add(new Breadcrumb { Text = T("Quản lý vast"), Url = Url.Action("Index") }); WorkContext.Breadcrumbs.Add(new Breadcrumb { Text = T("Thông tin vast"), Url = "#" }); var model = new VastModel(); if (id > 0) { var service = WorkContext.Resolve<IVastService>(); model = service.GetById(id); } var result = new ControlFormResult<VastModel>(model) { Title = T("Thông tin vast"), FormMethod = FormMethod.Post, UpdateActionName = "Update", SubmitButtonText = T("Lưu lại"), ShowCancelButton = true, ShowBoxHeader = false, CancelButtonText = T("Đóng"), FormWrapperStartHtml = Constants.Form.FormWrapperStartHtml, FormWrapperEndHtml = Constants.Form.FormWrapperEndHtml }; result.MakeReadOnlyProperty(x => x.KeyCode); result.MakeReadOnlyProperty(x => x.AdSystemVersion); result.MakeReadOnlyProperty(x => x.MediaFileDelivery); result.RegisterExternalDataSource(x => x.LanguageCode, y => BindLanguages()); result.RegisterCascadingDropDownDataSource(x => x.SiteId, Url.Action("GetSitesByLanguage")); result.RegisterCascadingDropDownDataSource(x => x.AdId, Url.Action("GetAdBySite")); return result; } [HttpPost, ValidateInput(false), FormButton("Save")] [Url("admin/vast/update")] public ActionResult Update(VastModel model) { if (!ModelState.IsValid) { return new AjaxResult().Alert(T(Constants.Messages.InvalidModel)); } var service = WorkContext.Resolve<IVastService>(); VastInfo item = model.Id == 0 ? new VastInfo() : service.GetById(model.Id); item.LanguageCode = model.LanguageCode; item.SiteId = model.SiteId; item.KeyCode = model.KeyCode; item.AdId = model.AdId; item.AdSystemVersion = model.AdSystemVersion; item.AdSystemValue = model.AdSystemValue; item.AdTitle = model.AdTitle; item.LinkError = model.LinkError; item.LinkImpression = model.LinkImpression; item.Skipoffset = model.Skipoffset; item.Duration = model.Duration; item.LinkClickThrough = model.LinkClickThrough; item.TrackingEvent1 = "start"; item.TrackingValue1 = model.TrackingValue1; item.TrackingEvent2 = "firstQuartile"; item.TrackingValue2 = model.TrackingValue2; item.TrackingEvent3 = "midpoint"; item.TrackingValue3 = model.TrackingValue3; item.TrackingEvent4 = "thirdQuartile"; item.TrackingValue4 = model.TrackingValue4; item.TrackingEvent5 = "complete"; item.TrackingValue5 = model.TrackingValue5; item.TrackingEvent6 = "creativeView"; item.TrackingValue6 = model.TrackingValue6; item.MediaFileBitrate = model.MediaFileBitrate; item.MediaFileDelivery = model.MediaFileDelivery; item.MediaFileHeight = model.MediaFileHeight; item.MediaFileWidth = model.MediaFileWidth; item.MediaFileMaintainAspectRatio = model.MediaFileMaintainAspectRatio; item.MediaFileScalable = model.MediaFileScalable; item.MediaFileType = model.MediaFileType; item.MediaFileValue = model.MediaFileValue; service.Save(item); return new AjaxResult() .NotifyMessage("UPDATE_ENTITY_COMPLETE") .Alert(T("Cập nhật thành công!")) .CloseModalDialog(); } [FormButton("Delete")] [HttpPost, ActionName("Update")] public ActionResult Delete(int id) { var service = WorkContext.Resolve<IVastService>(); var item = service.GetById(id); service.Delete(item); return new AjaxResult() .NotifyMessage("DELETE_ENTITY_COMPLETE") .Alert(T("Dữ liệu đã xóa khỏi hệ thống!")); } } } <file_sep>using CMSSolutions.Web.UI.ControlForms; using CMSSolutions.Websites.Entities; namespace CMSSolutions.Websites.Models { public class EpisodeModel { [ControlHidden] public int Id { get; set; } [ControlChoice(ControlChoice.DropDownList, Required = true, LabelText = "Ngôn ngữ hiển thị", ContainerCssClass = Constants.ContainerCssClassCol4, ContainerRowIndex = 0)] public string LanguageCode { get; set; } [ControlCascadingDropDown(LabelText = "Trang web", ParentControl = "LanguageCode", AbsoluteParentControl = true, ContainerCssClass = Constants.ContainerCssClassCol4, ContainerRowIndex = 1)] public int SiteId { get; set; } [ControlText(Type = ControlText.TextBox, Required = true, MaxLength = 50, LabelText = "Tên tập phim", ContainerCssClass = Constants.ContainerCssClassCol4, ContainerRowIndex = 2)] public string EpisodeName { get; set; } [ControlNumeric(LabelText = "Thư tự", Required = true, MaxLength = 15, ContainerCssClass = Constants.ContainerCssClassCol4, ContainerRowIndex = 3)] public int OrderBy { get; set; } [ControlChoice(ControlChoice.DropDownList, LabelText = "Trạng thái", ContainerCssClass = Constants.ContainerCssClassCol4, ContainerRowIndex = 4)] public int Status { get; set; } [ControlText(Type = ControlText.MultiText, Rows = 2, MaxLength = 2000, LabelText = "Giới thiệu", ContainerCssClass = Constants.ContainerCssClassCol12, ContainerRowIndex = 5)] public string Description { get; set; } public static implicit operator EpisodeModel(EpisodeInfo entity) { return new EpisodeModel { Id = entity.Id, LanguageCode = entity.LanguageCode, SiteId = entity.SiteId, EpisodeName = entity.EpisodeName, OrderBy = entity.OrderBy, Description = entity.Description, Status = entity.Status }; } } } <file_sep>using System.Collections.Generic; using System.Web.Mvc; using CMSSolutions.Websites.Entities; namespace CMSSolutions.Websites.Models { public class DataViewCategoryModel { public int Type { get; set; } public string Title { get; set; } public string TextNext { get; set; } public string UrlNext { get; set; } public string SliderName { get; set; } public int PageIndex { get; set; } public int PageSize { get; set; } public int TotalRow { get; set; } public int TotalPage { get { if (TotalRow <= PageSize) { return 1; } var count = TotalRow % PageSize; if ((count == 0)) { return TotalRow / PageSize; } return ((TotalRow - count) / PageSize) + 1; } } public string HtmlData { get; set; } public string HtmlFilmHot { get; set; } public string HtmlFilmRetail { get; set; } public string HtmlFilmLengthEpisodes { get; set; } public string HtmlFilmJJChannelIntroduce { get; set; } public string HtmlFilmTheater { get; set; } public string HtmlTVShow { get; set; } public string HtmlClip { get; set; } public string Data { get; set; } public string Breadcrumb { get; set; } public CategoryInfo CurrentCategory { get; set; } public List<FilmTypesInfo> ListFilmTypes { get; set; } public int SelectedFilmTypes { get; set; } public List<CountryInfo> ListCountries { get; set; } public int SelectedCountry { get; set; } public List<SelectListItem> SearchOrderBy { get; set; } public string SelectedOrderBy { get; set; } public int SelectedSortBy { get; set; } public IList<FilmInfo> ListFilms { get; set; } public ArticlesInfo News { get; set; } public IList<SupportInfo> ListSupportParents { get; set; } public IList<SupportInfo> ListSupportChildren { get; set; } public IList<ArticlesInfo> ListArticles { get; set; } public string Keyword { get; set; } public IList<SearchInfo> ListSearchFilms { get; set; } public IList<SearchInfo> ListSearchClip { get; set; } public IList<SearchInfo> ListSearchShow { get; set; } public IList<SearchInfo> ListSearchTrailer { get; set; } public FilmInfo FilmDetails { get; set; } } }<file_sep>using CMSSolutions.Web.UI.ControlForms; using CMSSolutions.Websites.Entities; namespace CMSSolutions.Websites.Models { public class VIPCardModel { public VIPCardModel() { VIPValue = 0; } [ControlHidden] public int Id { get; set; } [ControlChoice(ControlChoice.DropDownList, Required = true, LabelText = "Ngôn ngữ hiển thị", ContainerCssClass = Constants.ContainerCssClassCol6, ContainerRowIndex = 0, OnSelectedIndexChanged = "$('#" + Extensions.Constants.ServerId + "').empty();")] public string LanguageCode { get; set; } [ControlCascadingDropDown(LabelText = "Trang web", ParentControl = "LanguageCode", AbsoluteParentControl = true, ContainerCssClass = Constants.ContainerCssClassCol6, ContainerRowIndex = 1)] public int SiteId { get; set; } [ControlCascadingDropDown(LabelText = "Máy chủ", ParentControl = "SiteId", AbsoluteParentControl = true, ContainerCssClass = Constants.ContainerCssClassCol6, ContainerRowIndex = 2)] public int ServerId { get; set; } [ControlText(Type = ControlText.TextBox, LabelText = "Mã thẻ VIP", PlaceHolder = "Tối đa 50 ký tự", Required = true, MaxLength = 50, ContainerCssClass = Constants.ContainerCssClassCol6, ContainerRowIndex = 3)] public string VIPCode { get; set; } [ControlText(Type = ControlText.TextBox, LabelText = "Tên thẻ VIP", PlaceHolder = "Tối đa 250 ký tự", Required = true, MaxLength = 250, ContainerCssClass = Constants.ContainerCssClassCol6, ContainerRowIndex = 4)] public string VIPName { get; set; } [ControlNumeric(LabelText = "Định mức giá trị thẻ VIP", Required = true, ContainerCssClass = Constants.ContainerCssClassCol12, ContainerRowIndex = 5)] public decimal VIPValue { get; set; } public static implicit operator VIPCardModel(VIPCardInfo entity) { return new VIPCardModel { Id = entity.Id, LanguageCode = entity.LanguageCode, SiteId = entity.SiteId, ServerId = entity.ServerId, VIPCode = entity.VIPCode, VIPName = entity.VIPName, VIPValue = entity.VIPValue }; } } } <file_sep>using System.Collections.Generic; using System.Data.SqlClient; using CMSSolutions.Data; using CMSSolutions.Events; using CMSSolutions.Services; using CMSSolutions.Websites.Entities; namespace CMSSolutions.Websites.Services { public interface IVIPCardService : IGenericService<VIPCardInfo, int>, IDependency { bool CheckVipCode(int id, string vipCode); List<VIPCardInfo> SearchPaged( string searchText, string languageCode, int siteId, int serverId, int pageIndex, int pageSize, out int totalRecord); } public class VIPCardService : GenericService<VIPCardInfo, int>, IVIPCardService { public VIPCardService(IRepository<VIPCardInfo, int> repository, IEventBus eventBus) : base(repository, eventBus) { } public bool CheckVipCode(int id, string vipCode) { var list = new List<SqlParameter> { AddInputParameter("@VIPCode", vipCode), AddInputParameter("@Id", id) }; var result = (int)ExecuteReaderResult("sp_VIPCards_CheckAlias", list.ToArray()); return result > 0; } public List<VIPCardInfo> SearchPaged(string searchText, string languageCode, int siteId, int serverId, int pageIndex, int pageSize, out int totalRecord) { var list = new List<SqlParameter> { AddInputParameter("@LanguageCode", languageCode), AddInputParameter("@SiteId", siteId), AddInputParameter("@ServerId", serverId), AddInputParameter("@PageIndex", pageIndex), AddInputParameter("@PageSize", pageSize) }; return ExecuteReader<VIPCardInfo>("sp_VIPCards_Search_Paged", "@TotalRecord", out totalRecord, list.ToArray()); } } } <file_sep>using System.Collections.Generic; using CMSSolutions.Websites.Entities; namespace CMSSolutions.Websites.Models { public class PaymentModel { public List<BankCardInfo> ListBankCards { get; set; } public List<CardTypeInfo> ListCardTypes { get; set; } public string CustomerCode { get; set; } public string CustomerName { get; set; } public string VipXu { get; set; } public string Messages { get; set; } public string Amount { get; set; } public bool Status { get; set; } public string Url { get; set; } public int PageName { get; set; } public List<NapVipCustomerLogs> CustomerNapVipHistories { get; set; } public List<TransactioCustomerLogs> CustomerDoiXuHistories { get; set; } } }<file_sep>using System.Configuration; using Microsoft.Web.WebPages.OAuth; namespace CMSSolutions.Websites.Extensions { public static class AuthConfig { public static string FacebookAppId = ConfigurationManager.AppSettings["FacebookAppId"]; public static string FacebookAppSecret = ConfigurationManager.AppSettings["FacebookAppSecret"]; public static string GoogleAppId = ConfigurationManager.AppSettings["GoogleAppId"]; public static string GoogleAppSecret = ConfigurationManager.AppSettings["GoogleAppSecret"]; public static void RegisterAuth() { OAuthWebSecurity.RegisterFacebookClient(FacebookAppId, FacebookAppSecret); OAuthWebSecurity.RegisterClient(new GoogleClient(GoogleAppId, GoogleAppSecret), "Google", null); } } }<file_sep>using System.ComponentModel; using System.Runtime.Serialization; using CMSSolutions.Data; using CMSSolutions.Data.Entity; namespace CMSSolutions.Websites.Entities { /// <summary> /// Đạo diễn /// </summary> [DataContract] public class DirectorInfo : BaseEntity<int> { [DataMember] [DisplayName("FullName")] public string FullName { get; set; } [DataMember] [DisplayName("Description")] public string Description { get; set; } [DataMember] [DisplayName("Status")] public int Status { get; set; } } public class DirectorMap : EntityTypeConfiguration<DirectorInfo>, IEntityTypeConfiguration { public DirectorMap() { ToTable("Modules_Directors"); HasKey(m => m.Id); Property(m => m.FullName).IsRequired().HasMaxLength(250); Property(m => m.Description).HasMaxLength(2000); } } } <file_sep>using System.Collections.Generic; using System.Data.SqlClient; using System.Linq; using CMSSolutions.Data; using CMSSolutions.Events; using CMSSolutions.Services; using CMSSolutions.Websites.Entities; namespace CMSSolutions.Websites.Services { public interface IDirectorService : IGenericService<DirectorInfo, int>, IDependency { bool CheckExist(int id, string keyword); List<DirectorInfo> SearchPaged( string searchText, int status, int pageIndex, int pageSize, out int totalRecord); } public class DirectorService : GenericService<DirectorInfo, int>, IDirectorService { public DirectorService(IRepository<DirectorInfo, int> repository, IEventBus eventBus) : base(repository, eventBus) { } public bool CheckExist(int id, string keyword) { var list = new List<SqlParameter> { AddInputParameter("@Id", id), AddInputParameter("@Keyword", keyword) }; var result = (int)ExecuteReaderResult("sp_Directors_CheckName", list.ToArray()); return result > 0; } public List<DirectorInfo> SearchPaged(string searchText, int status, int pageIndex, int pageSize, out int totalRecord) { var list = new List<SqlParameter> { AddInputParameter("@Keyword", searchText), AddInputParameter("@Status", status), AddInputParameter("@PageIndex", pageIndex), AddInputParameter("@PageSize", pageSize) }; return ExecuteReader<DirectorInfo>("sp_Directors_Search_Paged", "@TotalRecord", out totalRecord, list.ToArray()); } } } <file_sep>using CMSSolutions.Web.UI.ControlForms; namespace CMSSolutions.Websites.Models { public class VastXmlModel { public VastXmlModel() { Messages = "Chú ý: Khi bạn click vào nút Tạo Xml hệ thống sẽ tự động tìm tất cả những nhóm quảng cáo nào đã có quảng cáo và có nội dung quảng cáo để tạo thành các file xml theo chuẩn VAST 3.0."; } [ControlText(Type = ControlText.MultiText, Rows = 3, LabelText = "Ghi chú", ContainerCssClass = Constants.ContainerCssClassCol12, ContainerRowIndex = 0)] public string Messages { get; set; } } }<file_sep>using System; using System.ComponentModel; using System.ComponentModel.DataAnnotations.Schema; using System.Runtime.Serialization; using CMSSolutions.Data; using CMSSolutions.Data.Entity; namespace CMSSolutions.Websites.Entities { [DataContract] public class AdvertisementInfo : BaseEntity<int> { [DataMember] [DisplayName("SiteId")] public int SiteId { get; set; } [DataMember] [DisplayName("LanguageCode")] public string LanguageCode { get; set; } [DataMember] [DisplayName("KeyCode")] public string KeyCode { get; set; } [DataMember] [DisplayName("Title")] public string Title { get; set; } [DataMember] [DisplayName("Price")] public decimal Price { get; set; } [DataMember] [DisplayName("Code")] public string Code { get; set; } [DataMember] [DisplayName("Link")] public string Link { get; set; } [DataMember] [DisplayName("Type")] public string Type { get; set; } [DataMember] [DisplayName("Click")] public string Click { get; set; } [DataMember] [DisplayName("Duration")] public int Duration { get; set; } [DataMember] [DisplayName("Position")] public int Position { get; set; } [DataMember] [DisplayName("Skip")] public int Skip { get; set; } [DataMember] [DisplayName("IsBlock")] public bool IsBlock { get; set; } } public class AdvertisementMap : EntityTypeConfiguration<AdvertisementInfo>, IEntityTypeConfiguration { public AdvertisementMap() { ToTable("Modules_Advertisement"); HasKey(m => m.Id); Property(m => m.LanguageCode).HasMaxLength(50); Property(m => m.KeyCode).IsRequired().HasMaxLength(50); Property(m => m.Title).IsRequired().HasMaxLength(250); Property(m => m.Code).IsRequired().HasMaxLength(50); Property(m => m.Link).IsRequired().HasMaxLength(500); Property(m => m.Type).IsRequired().HasMaxLength(50); Property(m => m.Click).HasMaxLength(500); Property(m => m.Duration).IsRequired(); Property(m => m.Position).IsRequired(); Property(m => m.Skip).IsRequired(); } } }<file_sep>using System; using System.ComponentModel; using System.ComponentModel.DataAnnotations.Schema; using System.Runtime.Serialization; namespace CMSSolutions.Websites.Entities { [DataContract] public class TransactioCustomerLogs { [DataMember] [DisplayName("CreateDate")] public DateTime CreateDate { get; set; } [DataMember] [DisplayName("Amount")] public string Amount { get; set; } [DataMember] [DisplayName("Type")] public string Type { get; set; } [DataMember] [DisplayName("TransactionCode")] public string TransactionCode { get; set; } } public class NapVipCustomerLogs { [DataMember] [DisplayName("CreateDate")] public DateTime CreateDate { get; set; } [DataMember] [DisplayName("Amount")] public string Amount { get; set; } [DataMember] [DisplayName("TotalDay")] public string TotalDay { get; set; } [DataMember] [DisplayName("Package")] public string Package { get; set; } [DataMember] [DisplayName("StartDate")] public DateTime StartDate { get; set; } [NotMapped] [DisplayName(Constants.NotMapped)] public string TextStartDate { get { return StartDate.ToString(Extensions.Constants.DateTimeFomatFull); } } [DataMember] [DisplayName("EndDate")] public DateTime EndDate { get; set; } [NotMapped] [DisplayName(Constants.NotMapped)] public string TextEndDate { get { return EndDate.ToString(Extensions.Constants.DateTimeFomatFull); } } } }<file_sep>using System; using System.ComponentModel; using System.ComponentModel.DataAnnotations.Schema; using System.Runtime.Serialization; using CMSSolutions.Data; using CMSSolutions.Data.Entity; namespace CMSSolutions.Websites.Entities { [DataContract] public class CategoryInfo : BaseEntity<int> { [DataMember] [DisplayName("SiteId")] public int SiteId { get; set; } [DataMember] [DisplayName("LanguageCode")] public string LanguageCode { get; set; } [DataMember] [DisplayName("ParentId")] public int ParentId { get; set; } [NotMapped] [DisplayName(Constants.NotMapped)] public string ParentName { get; set; } [DataMember] [DisplayName("ShortName")] public string ShortName { get; set; } [DataMember] [DisplayName("Name")] public string Name { get; set; } [DataMember] [DisplayName("Alias")] public string Alias { get; set; } [DataMember] [DisplayName("IsHome")] public bool IsHome { get; set; } [DataMember] [DisplayName("HasChilden")] public bool HasChilden { get; set; } [NotMapped] [DisplayName(Constants.NotMapped)] public string ChildenName { get; set; } [DataMember] [DisplayName("CreateDate")] public DateTime CreateDate { get; set; } [DataMember] [DisplayName("Description")] public string Description { get; set; } [DataMember] [DisplayName("Tags")] public string Tags { get; set; } [DataMember] [DisplayName("Url")] public string Url { get; set; } [DataMember] [DisplayName("IsDisplay")] public bool IsActived { get; set; } [DataMember] [DisplayName("OrderBy")] public int OrderBy { get; set; } [DataMember] [DisplayName("IsDeleted")] public bool IsDeleted { get; set; } } public class CategoryMap : EntityTypeConfiguration<CategoryInfo>, IEntityTypeConfiguration { public CategoryMap() { ToTable("Modules_Categories"); HasKey(x => x.Id); Property(x => x.SiteId).IsRequired(); Property(x => x.ParentId); Property(x => x.LanguageCode).HasMaxLength(50); Property(x => x.ShortName).IsRequired().HasMaxLength(250); Property(x => x.Name).IsRequired().HasMaxLength(400); Property(x => x.Alias).IsRequired().HasMaxLength(400); Property(x => x.CreateDate).IsRequired(); Property(x => x.Description).HasMaxLength(2000).IsRequired(); Property(x => x.Tags).HasMaxLength(2000).IsRequired(); Property(x => x.Url).IsRequired(); Property(x => x.IsActived).IsRequired(); Property(x => x.OrderBy).IsRequired(); Property(x => x.IsDeleted).IsRequired(); Property(x => x.IsHome).IsRequired(); Property(x => x.HasChilden).IsRequired(); } } }<file_sep>using System; using System.IO; using System.Security.Cryptography; using System.Text; using CMSSolutions.Websites.Extensions; using CMSSolutions.Websites.VipHDCardServices; using Org.BouncyCastle.Crypto; using Org.BouncyCastle.Crypto.Engines; namespace CMSSolutions.Websites.Payments { public class APICardCharging { public APICardCharging() { Password = System.Configuration.ConfigurationManager.AppSettings["Password"]; TransactionId = int.Parse(System.Configuration.ConfigurationManager.AppSettings["TransactionId"]); MPin = System.Configuration.ConfigurationManager.AppSettings["MPin"]; CardList = System.Configuration.ConfigurationManager.AppSettings["CardList"]; CardData = System.Configuration.ConfigurationManager.AppSettings["CardData"]; } private string UserName { get { return System.Configuration.ConfigurationManager.AppSettings["UserName"]; } } private string Password { get; set; } private string PartnerId { get { return System.Configuration.ConfigurationManager.AppSettings["CardPartnerId"]; } } private int TransactionId { get; set; } private string MPin { get; set; } public string CardList { get; set; } public string CardData { get; set; } public string EncryptDataRSA(string origData, string publicKey) { byte[] plaintext = Encoding.ASCII.GetBytes(origData); byte[] bKey = JavaScience.opensslkey.DecodePkcs8EncPrivateKey(publicKey); RSACryptoServiceProvider myrsa = JavaScience.opensslkey.DecodeX509PublicKey(bKey); byte[] encrypt = myrsa.Encrypt(plaintext, false); string enStr = Convert.ToBase64String(encrypt); return enStr; } public string DecryptDataRSA(string deData, string privateKey) { try { byte[] Databyte = Convert.FromBase64String(deData); byte[] privatebKEY = JavaScience.opensslkey.DecodeOpenSSLPrivateKey(privateKey); RSACryptoServiceProvider rsa = JavaScience.opensslkey.DecodeRSAPrivateKey(privatebKEY); string dataDecript = Encoding.ASCII.GetString(rsa.Decrypt(Databyte, false)); return dataDecript; } catch (Exception ex) { throw ex; } } public string EncryptDataTripdesPKCS7(string origData, string key) { byte[] tripkey = Encrypt.hexa.hexatobyte(key); byte[] entrip = TripleDES_Encrypt_Byte(tripkey, Encoding.UTF8.GetBytes(origData)); return ByteArrayToHexString(entrip); } public string EncryptDataTripdes(string origData, string key) { byte[] tripkey = Encrypt.hexa.hexatobyte(key); string erro = ""; string entrip = Encrypt.Encrypt._EncryptTripleDes(origData, tripkey, ref erro); return entrip; } public string DecryptDataTripdes(string deData, string key) { byte[] tripkey = Encrypt.hexa.hexatobyte(key); string error = ""; string detrip = Encrypt.Encrypt._DecryptTripleDes(deData, tripkey, ref error); return detrip; } private String GetLocal() { String local = System.Web.HttpContext.Current.Request.MapPath("~"); return local; } public string Login(out string tokenKey) { try { var keyDir = GetLocal() + "\\RsaKeys\\"; var websv = new ServicesService(); var loginRes = new LoginResponse(); string publicKey = keyDir + "epay_public_key.pem"; string encryptPass = Encrypt2(publicKey, Password); loginRes = websv.login(UserName, encryptPass, PartnerId); if ((ErrorMessages)Convert.ToInt32(loginRes.status) == ErrorMessages.Success) { string privateKey = keyDir + "private_key.pem"; tokenKey = Decrypt2(privateKey, loginRes.sessionid); return Utilities.GetMessages(Convert.ToInt32(loginRes.status)); } tokenKey = string.Empty; return Utilities.GetMessages(Convert.ToInt32(loginRes.status)); } catch (Exception ex) { tokenKey = string.Empty; return ex.Message; } } public string Logout(string sessionid) { var websv = new ServicesService(); string md5hex2str = HashWithMD5(sessionid); byte[] cvmd52 = Convert.FromBase64String(md5hex2str); string md5sess = ByteArrayToHexString(cvmd52); var logoutres = new LogoutResponse(); logoutres = websv.logout(UserName, PartnerId, md5sess); var message = Utilities.GetMessages(Convert.ToInt32(logoutres.status)); return message + "-" + message; } public string ChangeMpin(string sessionid, string newPassword) { string datetime = GetDateTime(); string strTransID = PartnerId.Trim() + "_" + UserName.Trim() + "_" + datetime.Trim() + "_" + TransactionId; TransactionId++; if (newPassword.Length == 0) { return "Mật khẩu nhập không đúng."; } if (newPassword.Equals(MPin)) { return "Mật khẩu trùng với mật khẩu cũ."; } string ensess = HashWithMD5(sessionid); byte[] cvmd52 = Convert.FromBase64String(ensess); string md5sess = ByteArrayToHexString(cvmd52); var websv = new ServicesService(); string enoldpin = EncryptDataTripdes(MPin, sessionid); string ennewpin = EncryptDataTripdes(newPassword, sessionid); var changeRes = new ChangeResponse(); changeRes = websv.changeMPIN(strTransID, UserName, PartnerId, enoldpin, ennewpin, md5sess); var message = Utilities.GetMessages(Convert.ToInt32(changeRes.status)); if ((ErrorMessages)Convert.ToInt32(changeRes.status) == ErrorMessages.Success) { MPin = newPassword; } return message; } public string GetDateTime() { return DateTime.Now.ToString("yyyyMMddHHmmss"); } public string ChangePassword(string sessionid, string newPassword) { string datetime = GetDateTime(); string strTransID = PartnerId.Trim() + "_" + UserName.Trim() + "_" + datetime.Trim() + "_" + TransactionId; TransactionId++; if (newPassword.Length == 0) { return "Mật khẩu nhập không đúng"; } if (newPassword.Equals(Password)) { return "Mật khẩu trùng với mật khẩu cũ."; } string ensess = HashWithMD5(sessionid); byte[] cvmd52 = Convert.FromBase64String(ensess); string md5sess = ByteArrayToHexString(cvmd52); var websv = new ServicesService(); string enoldpass = EncryptDataTripdes(Password, sessionid); string ennewpass = EncryptDataTripdes(newPassword, sessionid); var changeRes = new ChangeResponse(); changeRes = websv.changePassword(strTransID, UserName, PartnerId, enoldpass, ennewpass, md5sess); var message = Utilities.GetMessages(Convert.ToInt32(changeRes.status)); if ((ErrorMessages)Convert.ToInt32(changeRes.status) == ErrorMessages.Success) { Password = <PASSWORD>; } return message; } public string CheckTrain(string sessionid, string tranid) { if (string.IsNullOrEmpty(tranid)) { return "Mã không để trống."; } string ensess = HashWithMD5(sessionid); byte[] cvmd52 = Convert.FromBase64String(ensess); string md5sess = ByteArrayToHexString(cvmd52); var websv = new ServicesService(); var chargres = new ChargeReponse(); chargres = websv.getTransactionStatus(tranid, UserName, PartnerId, md5sess); return Utilities.GetMessages(Convert.ToInt32(chargres.status)); } public string CardCharging(string sessionid, int seed, string carddata, string transID, string target, out string amount) { string mapin = EncryptDataTripdesPKCS7(MPin, sessionid); string enCard = EncryptDataTripdesPKCS7(carddata, sessionid); string md5hex2str = HashWithMD5(sessionid); byte[] cvmd52 = Convert.FromBase64String(md5hex2str); string md5sess = ByteArrayToHexString(cvmd52); var chargeRes = new ChargeReponse(); var message = string.Empty; amount = "0"; try { var websv = new ServicesService(); chargeRes = websv.cardCharging(transID, UserName, PartnerId, mapin, target, enCard, md5sess); if ((ErrorMessages)Convert.ToInt32(chargeRes.status) == ErrorMessages.Success) { message = Utilities.GetMessages((int)ErrorMessages.Success); amount = DecryptDataTripdesPKCS7(chargeRes.responseamount, sessionid); } else { message = Utilities.GetMessages(Convert.ToInt32(chargeRes.status)); } } catch { message = Utilities.GetMessages((int)ErrorMessages.SystemBusy); } return message; } public ErrorMessages CardCharging(string sessionid, string carddata, string target, out string amount) { string datetime = GetDateTime(); var ran = new Random(); string kqran = ran.Next(10000, 99999).ToString(); string strTransID = System.Configuration.ConfigurationManager.AppSettings["TransactionId"] + "_" + datetime + "_" + kqran; string mapin = EncryptDataTripdesPKCS7(MPin, sessionid); string enCard = EncryptDataTripdesPKCS7(carddata, sessionid); string md5hex2str = HashWithMD5(sessionid); byte[] cvmd52 = Convert.FromBase64String(md5hex2str); string md5sess = ByteArrayToHexString(cvmd52); var chargeRes = new ChargeReponse(); amount = "0"; try { var websv = new ServicesService(); chargeRes = websv.cardCharging(strTransID, UserName, PartnerId, mapin, target, enCard, md5sess); var status = (ErrorMessages) Convert.ToInt32(chargeRes.status); if (status == ErrorMessages.Success) { amount = DecryptDataTripdesPKCS7(chargeRes.responseamount, sessionid); } return status; } catch { return ErrorMessages.Fail; } } public static string HashWithMD5(string text) { var hashAlgorithm = new MD5CryptoServiceProvider(); return HashString(text, hashAlgorithm); } public static string HashString(string stringToHash, HashAlgorithm algo) { byte[] bytes = Encoding.UTF8.GetBytes(stringToHash); bytes = algo.ComputeHash(bytes); return Convert.ToBase64String(bytes); } private static string ByteArrayToHexString(byte[] Bytes) { var Result = new StringBuilder(); string HexAlphabet = "0123456789ABCDEF"; foreach (byte B in Bytes) { Result.Append(HexAlphabet[(int)(B >> 4)]); Result.Append(HexAlphabet[(int)(B & 0xF)]); } return Result.ToString(); } public string DecryptDataTripdesPKCS7(string origData, string key) { byte[] tripkey = Encrypt.hexa.hexatobyte(key); string erro = ""; byte[] entrip = TripleDES_Decrypt_Byte(tripkey, Encrypt.hexa.hexatobyte(origData));//Encrypt.Encrypt._EncryptTripleDes(origData, tripkey, ref erro); return Encoding.UTF8.GetString(entrip); } private byte[] TripleDES_Encrypt_Byte(byte[] Keys, byte[] clearText) { try { byte[] IVs = new byte[8]; var des = new TripleDESCryptoServiceProvider { IV = IVs, KeySize = 192, Key = Keys, Mode = CipherMode.ECB, Padding = PaddingMode.PKCS7 }; byte[] cipherText = des.CreateEncryptor().TransformFinalBlock(clearText, 0, clearText.Length); return cipherText; } catch (Exception ex) { throw ex; } } private byte[] TripleDES_Decrypt_Byte(byte[] Keys, byte[] clearText) { try { byte[] IVs = new byte[8]; var des = new TripleDESCryptoServiceProvider(); des.IV = IVs; des.KeySize = 192; des.Key = Keys; des.Mode = CipherMode.ECB; des.Padding = PaddingMode.PKCS7; byte[] cipherText = des.CreateDecryptor().TransformFinalBlock(clearText, 0, clearText.Length); return cipherText; } catch (Exception ex) { throw ex; } } public AsymmetricCipherKeyPair GetPrivateKey(string privateKey) { try { var sr = new StreamReader(privateKey); var pr = new Org.BouncyCastle.OpenSsl.PemReader(sr); var KeyPair = (AsymmetricCipherKeyPair)pr.ReadObject(); sr.Close(); return KeyPair; } catch (Exception ex) { throw new Exception("Exception:", ex); } } public AsymmetricKeyParameter GetPublicKey(string publicKey) { try { var sr = new StreamReader(publicKey); var pr = new Org.BouncyCastle.OpenSsl.PemReader(sr); var KeyPair = (AsymmetricKeyParameter)pr.ReadObject(); sr.Close(); return KeyPair; } catch (Exception ex) { throw new Exception("Exception:", ex); } } public string Decrypt2(string privateKeyFileName, string encryptString) { try { AsymmetricCipherKeyPair keyPair = GetPrivateKey(privateKeyFileName); IAsymmetricBlockCipher cipher = new RsaEngine(); cipher.Init(false, keyPair.Private); byte[] encryptByte = Convert.FromBase64String(encryptString); byte[] cipheredBytes = cipher.ProcessBlock(encryptByte, 0, encryptByte.Length); String decryptString = Encoding.UTF8.GetString(cipheredBytes); return decryptString; } catch (Exception ex) { throw new Exception("Exception encrypting file:", ex); } } public string Encrypt2(string publicKeyFileName, string inputMessage) { try { AsymmetricKeyParameter keyPair = GetPublicKey(publicKeyFileName); var utf8enc = new UTF8Encoding(); byte[] inputBytes = utf8enc.GetBytes(inputMessage); AsymmetricKeyParameter publicKey = keyPair; IAsymmetricBlockCipher cipher = new RsaEngine(); cipher.Init(true, publicKey); byte[] cipheredBytes = cipher.ProcessBlock(inputBytes, 0, inputMessage.Length); String encrypt = Convert.ToBase64String(cipheredBytes); return encrypt; } catch (Exception ex) { throw new Exception("Encrypt string fail:", ex); } } } }<file_sep>using System.ComponentModel; using System.Runtime.Serialization; using CMSSolutions.Data; using CMSSolutions.Data.Entity; namespace CMSSolutions.Websites.Entities { [DataContract] public class FilmTypesInfo : BaseEntity<int> { [DataMember] [DisplayName("LanguageCode")] public string LanguageCode { get; set; } [DataMember] [DisplayName("SiteId")] public int SiteId { get; set; } [DataMember] [DisplayName("Name")] public string Name { get; set; } [DataMember] [DisplayName("Description")] public string Description { get; set; } [DataMember] [DisplayName("Status")] public int Status { get; set; } [DataMember] [DisplayName("IsFilm")] public bool IsFilm { get; set; } [DataMember] [DisplayName("IsShow")] public bool IsShow { get; set; } [DataMember] [DisplayName("IsClip")] public bool IsClip { get; set; } [DataMember] [DisplayName("IsJJFilm")] public bool IsJJFilm { get; set; } } public class FilmTypeMap : EntityTypeConfiguration<FilmTypesInfo>, IEntityTypeConfiguration { public FilmTypeMap() { ToTable("Modules_FilmTypes"); HasKey(m => m.Id); Property(m => m.LanguageCode).IsRequired().HasMaxLength(50); Property(m => m.SiteId).IsRequired(); Property(m => m.Name).IsRequired().HasMaxLength(250); Property(m => m.Description).HasMaxLength(200); Property(m => m.Status); } } } <file_sep>using System.Collections.Generic; using System.Data.SqlClient; using CMSSolutions.Data; using CMSSolutions.Events; using CMSSolutions.Services; using CMSSolutions.Websites.Entities; namespace CMSSolutions.Websites.Services { public interface ICountryService : IGenericService<CountryInfo, int>, IDependency { bool CheckExist(int id, string keyword); List<CountryInfo> SearchPaged( string searchText, int pageIndex, int pageSize, out int totalRecord); } public class CountryService : GenericService<CountryInfo, int>, ICountryService { public CountryService(IRepository<CountryInfo, int> repository, IEventBus eventBus) : base(repository, eventBus) { } public bool CheckExist(int id, string keyword) { var list = new List<SqlParameter> { AddInputParameter("@Id", id), AddInputParameter("@Keyword", keyword) }; var result = (int)ExecuteReaderResult("sp_Countries_CheckName", list.ToArray()); return result > 0; } public List<CountryInfo> SearchPaged(string searchText, int pageIndex, int pageSize, out int totalRecord) { var list = new List<SqlParameter> { AddInputParameter("@Keyword", searchText), AddInputParameter("@PageIndex", pageIndex), AddInputParameter("@PageSize", pageSize) }; return ExecuteReader<CountryInfo>("sp_Countries_Search_Paged", "@TotalRecord", out totalRecord, list.ToArray()); } } } <file_sep>using System.Collections.Generic; using CMSSolutions.Web.Security.Permissions; namespace CMSSolutions.Websites.Permissions { public class AdminPermissions : IPermissionProvider { public static readonly Permission ManagerSlider = new Permission { Name = "ManagerSlider", Category = "Management", Description = "Quản lý slider" }; public static readonly Permission ManagerFilms = new Permission { Name = "ManagerFilms", Category = "Management", Description = "Quản lý phim" }; public static readonly Permission ManagerFilmTypes = new Permission { Name = "ManagerFilmTypes", Category = "Management", Description = "Quản lý thể loại phim" }; public static readonly Permission ManagerServerFilms = new Permission { Name = "ManagerServerFilms", Category = "Management", Description = "Quản lý máy chủ phim" }; public static readonly Permission ManagerEpisodes = new Permission { Name = "ManagerEpisodes", Category = "Management", Description = "Quản lý các tập phim" }; public static readonly Permission ManagerDirectors = new Permission { Name = "ManagerDirectors", Category = "Management", Description = "Quản lý đạo diễn phim" }; public static readonly Permission ManagerCountries = new Permission { Name = "ManagerCountries", Category = "Management", Description = "Quản lý nước sản xuất phim" }; public static readonly Permission ManagerCollections = new Permission { Name = "ManagerCollections", Category = "Management", Description = "Quản lý các bộ phim" }; public static readonly Permission ManagerActors = new Permission { Name = "ManagerActors", Category = "Management", Description = "Quản lý diễn viên" }; public static readonly Permission ManagerTags = new Permission { Name = "ManagerTags", Category = "Management", Description = "Quản lý tags" }; public static readonly Permission ManagerArticles = new Permission { Name = "ManagerArticles", Category = "Management", Description = "Quản lý tin tức" }; public static readonly Permission ManagerDownloadGames = new Permission { Name = "ManagerDownloadGames", Category = "Management", Description = "Quản lý sự kiện đào xu" }; public static readonly Permission ManagerSites = new Permission { Name = "ManagerSites", Category = "Management", Description = "Quản lý các site" }; public static readonly Permission ManagerCategories = new Permission { Name = "ManagerCategories", Category = "Management", Description = "Quản lý chuyên mục" }; public static readonly Permission ManagerAdvertisementGroup = new Permission { Name = "ManagerAdvertisementGroup", Category = "Management", Description = "Quản lý nhóm quảng cáo" }; public static readonly Permission ManagerAdvertisement = new Permission { Name = "ManagerAdvertisement", Category = "Management", Description = "Quản lý quảng cáo" }; public static readonly Permission ManagerVast = new Permission { Name = "ManagerVast", Category = "Management", Description = "Quản lý Vast" }; public static readonly Permission ManagerSupports = new Permission { Name = "ManagerSupports", Category = "Management", Description = "Hỏi đáp" }; public static readonly Permission ManagerRates = new Permission { Name = "ManagerRates", Category = "Management", Description = "Đánh giá và báo lỗi" }; public static readonly Permission ManagerAdmin = new Permission { Name = "ManagerAdmin", Category = "Management", Description = "Bảng điều khiển" }; public static readonly Permission ManagerBankCards = new Permission { Name = "ManagerBankCards", Category = "Management", Description = "Quản lý dịch vụ thẻ ngân hàng" }; public static readonly Permission ManagerCardTypes = new Permission { Name = "ManagerCardTypes", Category = "Management", Description = "Quản lý loại thẻ cào" }; public static readonly Permission ManagerVipCards = new Permission { Name = "ManagerVipCards", Category = "Management", Description = "Quản lý thẻ VIP" }; public static readonly Permission ManagerPromotions = new Permission { Name = "ManagerPromotions", Category = "Management", Description = "Quản lý khuyến mãi" }; public static readonly Permission ManagerCustomers = new Permission { Name = "ManagerCustomers", Category = "Management", Description = "Quản lý khách hàng" }; public static readonly Permission ManagerFilmFiles = new Permission { Name = "ManagerFilmFiles", Category = "Management", Description = "Quản lý video files" }; public static readonly Permission ManagerSystemLogs = new Permission { Name = "ManagerSystemLogs", Category = "Management", Description = "Quản lý logs hệ thống" }; public static readonly Permission ManagerAdminReportSms = new Permission { Name = "ManagerAdminReportSms", Category = "Management", Description = "Đối soát SMS" }; public static readonly Permission ManagerAdminReportAtm = new Permission { Name = "ManagerAdminReportAtm", Category = "Management", Description = "Đối soát ATM" }; public static readonly Permission ManagerAdminReportCard = new Permission { Name = "ManagerAdminReportCard", Category = "Management", Description = "Đối soát thẻ cào" }; public IEnumerable<Permission> GetPermissions() { yield return ManagerAdmin; yield return ManagerCategories; yield return ManagerSites; yield return ManagerArticles; yield return ManagerDirectors; yield return ManagerCountries; yield return ManagerCollections; yield return ManagerActors; yield return ManagerEpisodes; yield return ManagerServerFilms; yield return ManagerFilmTypes; yield return ManagerFilms; yield return ManagerVipCards; yield return ManagerCustomers; yield return ManagerFilmFiles; yield return ManagerSystemLogs; yield return ManagerPromotions; yield return ManagerAdminReportSms; yield return ManagerAdminReportAtm; yield return ManagerAdminReportCard; yield return ManagerSupports; yield return ManagerAdvertisementGroup; yield return ManagerAdvertisement; yield return ManagerVast; yield return ManagerRates; yield return ManagerDownloadGames; yield return ManagerSlider; yield return ManagerTags; } } }<file_sep>using System; using System.IO; namespace CMSSolutions.Websites.Extensions { public class LogFiles { public static void WriteLogSms(string msg) { try { var logFile = string.Format(@"{0}\{1}_{2}.txt", Constants.SmsLogFiles, "SMS", DateTime.Now.ToString("dd-MM-yyyy")); using (var sw = new StreamWriter(logFile, true)) { sw.WriteLine(DateTime.Now.ToShortTimeString() + ": " + msg); sw.Close(); } } catch (Exception) { } } } }<file_sep>using System; using CMSSolutions.Web.UI.ControlForms; using CMSSolutions.Websites.Entities; using CMSSolutions.Websites.Extensions; namespace CMSSolutions.Websites.Models { public class CustomerModel { public CustomerModel() { Birthday = DateTime.Now.AddYears(-10); ImageIcon = "/Images/avatars/avatar-no-image.png"; } [ControlHidden] public int Id { get; set; } [ControlText(Type = ControlText.TextBox, LabelText = "Mã khách hàng", PlaceHolder = "Tự động sinh mã", MaxLength = 250, ContainerCssClass = Constants.ContainerCssClassCol3, ContainerRowIndex = 0)] public string CutomerCode { get; set; } [ControlText(Type = ControlText.TextBox, LabelText = "Tài khoản đăng nhập", PlaceHolder = "Nhập ký tự không dấu, email, sđt.", Required = true, MaxLength = 50, ContainerCssClass = Constants.ContainerCssClassCol3, ContainerRowIndex = 0)] public string UserName { get; set; } [ControlText(Type = ControlText.Password, LabelText = "Mật <NAME>", PlaceHolder = "Mật khẩu chứa ký tự Hoa, Thường, Số, 1 ký tự đặc biệt.", Required = true, MaxLength = 500, ContainerCssClass = Constants.ContainerCssClassCol3, ContainerRowIndex = 0)] public string Password { get; set; } [ControlText(Type = ControlText.Email, LabelText = "Email", Required = true, MaxLength = 50, ContainerCssClass = Constants.ContainerCssClassCol3, ContainerRowIndex = 0)] public string Email { get; set; } [ControlText(Type = ControlText.TextBox, LabelText = "<NAME>", Required = true, MaxLength = 250, ContainerCssClass = Constants.ContainerCssClassCol3, ContainerRowIndex = 1)] public string FullName { get; set; } [ControlDatePicker(LabelText = "Ngày sinh", Required = true, ContainerCssClass = Constants.ContainerCssClassCol3, ContainerRowIndex = 1)] public DateTime Birthday { get; set; } [ControlChoice(ControlChoice.DropDownList, LabelText = "Giới tính", ContainerCssClass = Constants.ContainerCssClassCol3, ContainerRowIndex = 1)] public int Sex { get; set; } [ControlText(Type = ControlText.TextBox, LabelText = "Số điện thoại", MaxLength = 50, ContainerCssClass = Constants.ContainerCssClassCol3, ContainerRowIndex = 1)] public string PhoneNumber { get; set; } [ControlChoice(ControlChoice.CheckBox, LabelText = "", PrependText = "Khóa tài khoản", ContainerCssClass = Constants.ContainerCssClassCol2, ContainerRowIndex = 2)] public bool IsBlock { get; set; } [ControlNumeric(LabelText = "VIP Xu", Required = true, ContainerCssClass = Constants.ContainerCssClassCol2, ContainerRowIndex = 2)] public decimal VipXu { get; set; } [ControlNumeric(LabelText = "Tổng tiền", Required = true, ContainerCssClass = Constants.ContainerCssClassCol2, ContainerRowIndex = 2)] public decimal TotalMoney { get; set; } [ControlNumeric(LabelText = "Tổng số ngày", Required = true, ContainerCssClass = Constants.ContainerCssClassCol2, ContainerRowIndex = 2)] public int TotalDay { get; set; } [ControlText(Type = ControlText.TextBox, ContainerCssClass = Constants.ContainerCssClassCol2, ContainerRowIndex = 2)] public string StartDate { get; set; } [ControlText(Type = ControlText.TextBox, ContainerCssClass = Constants.ContainerCssClassCol2, ContainerRowIndex = 2)] public string EndDate { get; set; } [ControlFileUpload(EnableFineUploader = true, Required = true, LabelText = "Ảnh đại diện", ContainerCssClass = Constants.ContainerCssClassCol6, ContainerRowIndex = 3, ShowThumbnail = true)] public string ImageIcon { get; set; } [ControlChoice(ControlChoice.DropDownList, LabelText = "Quận huyện/Thành phố", ContainerCssClass = Constants.ContainerCssClassCol2, ContainerRowIndex = 3)] public string CityId { get; set; } [ControlText(Type = ControlText.TextBox, LabelText = "Địa chỉ", MaxLength = 2000, ContainerCssClass = Constants.ContainerCssClassCol4, ContainerRowIndex = 3)] public string Address { get; set; } [ControlChoice(ControlChoice.DropDownList, AllowMultiple = true, CssClass = Extensions.Constants.CssControlCustom, EnableChosen = true, Required = true, LabelText = "Thể loại phim", ContainerCssClass = Constants.ContainerCssClassCol6, ContainerRowIndex = 4)] public int[] FilmTypeIds { get; set; } [ControlChoice(ControlChoice.DropDownList, AllowMultiple = true, CssClass = Extensions.Constants.CssControlCustom, EnableChosen = true, Required = true, LabelText = "Nước sản xuất", ContainerCssClass = Constants.ContainerCssClassCol6, ContainerRowIndex = 4)] public int[] CountryIds { get; set; } [ControlText(Type = ControlText.TextBox, LabelText = "Facebook", MaxLength = 50, ContainerCssClass = Constants.ContainerCssClassCol4, ContainerRowIndex = 6)] public string Facebook { get; set; } [ControlText(Type = ControlText.TextBox, LabelText = "Skype", MaxLength = 50, ContainerCssClass = Constants.ContainerCssClassCol4, ContainerRowIndex = 6)] public string Skype { get; set; } [ControlText(Type = ControlText.TextBox, LabelText = "Zing Me", MaxLength = 50, ContainerCssClass = Constants.ContainerCssClassCol4, ContainerRowIndex = 6)] public string ZingMe { get; set; } [ControlText(Type = ControlText.TextBox, LabelText = "Google", MaxLength = 50, ContainerCssClass = Constants.ContainerCssClassCol4, ContainerRowIndex = 7)] public string Google { get; set; } [ControlText(Type = ControlText.TextBox, LabelText = "Yahoo", MaxLength = 50, ContainerCssClass = Constants.ContainerCssClassCol4, ContainerRowIndex = 7)] public string Yahoo { get; set; } [ControlChoice(ControlChoice.DropDownList, LabelText = "Trạng thái", ContainerCssClass = Constants.ContainerCssClassCol4, ContainerRowIndex = 7)] public int Status { get; set; } [ControlText(Type = ControlText.MultiText, Rows = 3, MaxLength = 2000, LabelText = "Giới thiệu", ContainerCssClass = Constants.ContainerCssClassCol12, ContainerRowIndex = 8)] public string Description { get; set; } public static implicit operator CustomerModel(CustomerInfo entity) { return new CustomerModel { Id = entity.Id, CutomerCode = entity.CustomerCode, UserName = entity.UserName, Password = <PASSWORD>, FullName = entity.FullName, Email = entity.Email, Address = entity.Address, PhoneNumber = entity.PhoneNumber, CityId = entity.CityId, Birthday = entity.Birthday, Sex = entity.Sex, ImageIcon = entity.ImageIcon, FilmTypeIds = Utilities.ParseListInt(entity.FilmTypeIds), CountryIds = Utilities.ParseListInt(entity.CountryIds), Skype = entity.Skype, ZingMe = entity.ZingMe, Facebook = entity.Facebook, Google = entity.Google, Yahoo = entity.Yahoo, VipXu = entity.VipXu, TotalMoney = entity.TotalMoney, IsBlock = entity.IsBlock, Status = entity.Status, Description = entity.Description, TotalDay = entity.TotalDay, StartDate = entity.TextStartDate, EndDate = entity.TextEndDate }; } } } <file_sep>using System; using System.Web.Mvc; using CMSSolutions.Web.Mvc; using CMSSolutions.Web.Themes; using CMSSolutions.Web.UI.ControlForms; using CMSSolutions.Web.UI.Navigation; using CMSSolutions.Websites.Models; using CMSSolutions.Websites.Services; namespace CMSSolutions.Websites.Controllers { [Themed(IsDashboard = true), Authorize] public class AdminClosedBankController : BaseAdminController { public AdminClosedBankController(IWorkContextAccessor workContextAccessor) : base(workContextAccessor) { } [Url("admin/bank/close")] public ActionResult Index() { WorkContext.Breadcrumbs.Add(new Breadcrumb { Text = T("Báo cáo ATM"), Url = Url.Action("Index","AdminReportBank") }); WorkContext.Breadcrumbs.Add(new Breadcrumb { Text = T("Chốt sổ đối soát ATM"), Url = "#" }); var model = new BankCloseModel(); var result = new ControlFormResult<BankCloseModel>(model) { Title = T("Chốt sổ đối soát ATM"), FormMethod = FormMethod.Post, UpdateActionName = "Update", SubmitButtonText = T("Chốt"), CancelButtonText = T("Trở về"), CancelButtonUrl = Url.Action("Index", "AdminReportBank"), ShowBoxHeader = false, FormWrapperStartHtml = Constants.Form.FormWrapperStartHtml, FormWrapperEndHtml = Constants.Form.FormWrapperEndHtml }; result.MakeReadOnlyProperty(x => x.Messages); return result; } [HttpPost, ValidateInput(false), FormButton("Save")] [Url("admin/bank/close/update")] public ActionResult Update(BankCloseModel model) { if (!ModelState.IsValid) { return new AjaxResult().Alert(T(Constants.Messages.InvalidModel)); } if (model.EndDate > DateTime.Now) { return new AjaxResult().Alert(T("Thời gian bạn chọn chưa phát sinh giao dịch mới!")); } WorkContext.Resolve<ITransactionBankService>().ATMClosed(model.EndDate); return new AjaxResult() .NotifyMessage("UPDATE_ENTITY_COMPLETE") .Alert(string.Format(T("Đã chốt sổ đối soát đến hết ngày {0} thành công!"), model.EndDate.ToString(Extensions.Constants.DateTimeFomat))); } } } <file_sep>using System; using System.ComponentModel; using System.ComponentModel.DataAnnotations.Schema; using System.Runtime.Serialization; using CMSSolutions.Data; using CMSSolutions.Data.Entity; namespace CMSSolutions.Websites.Entities { [DataContract] public class PromotionInfo : BaseEntity<int> { [DataMember] [DisplayName("Title")] public string Title { get; set; } [DataMember] [DisplayName("Contents")] public string Contents { get; set; } [DataMember] [DisplayName("FromDate")] public DateTime FromDate { get; set; } [NotMapped] [DisplayName(Constants.NotMapped)] public string TextFromDate { get { return FromDate.ToString(Extensions.Constants.DateTimeFomat); } } [DataMember] [DisplayName("ToDate")] public DateTime ToDate { get; set; } [NotMapped] [DisplayName(Constants.NotMapped)] public string TextToDate { get { return ToDate.ToString(Extensions.Constants.DateTimeFomat); } } [DataMember] [DisplayName("Status")] public int Status { get; set; } } public class PromotionMap : EntityTypeConfiguration<PromotionInfo>, IEntityTypeConfiguration { public PromotionMap() { ToTable("Modules_Promotions"); HasKey(m => m.Id); Property(m => m.Title).IsRequired().HasMaxLength(250); Property(m => m.Contents).IsRequired(); Property(m => m.FromDate).IsRequired(); Property(m => m.ToDate).IsRequired(); } } }<file_sep>using System; using CMSSolutions.Web.UI.ControlForms; using CMSSolutions.Websites.Entities; namespace CMSSolutions.Websites.Models { public class DownloadGameModel { public DownloadGameModel() { Code = Guid.NewGuid().ToString().Replace("-", string.Empty); } [ControlHidden] public int Id { get; set; } [ControlText(Type = ControlText.TextBox, LabelText = "Mã sự kiện", Required = true, MaxLength = 100, ContainerCssClass = Constants.ContainerCssClassCol4, ContainerRowIndex = 0)] public string Code { get; set; } [ControlText(Type = ControlText.TextBox, Required = true, MaxLength = 250, LabelText = "Tên sự kiện", ContainerCssClass = Constants.ContainerCssClassCol8, ContainerRowIndex = 0)] public string Title { get; set; } [ControlFileUpload(EnableFineUploader = true, LabelText = "Logo", ContainerCssClass = Constants.ContainerCssClassCol6, ContainerRowIndex = 1, Required = true, ShowThumbnail = true)] public string Logo { get; set; } [ControlFileUpload(EnableFineUploader = true, LabelText = "Banner", ContainerCssClass = Constants.ContainerCssClassCol6, ContainerRowIndex = 1, Required = true, ShowThumbnail = true)] public string UrlBanner { get; set; } [ControlText(Type = ControlText.TextBox, Required = true, MaxLength = 500, LabelText = "Đường dẫn tới game", ContainerCssClass = Constants.ContainerCssClassCol8, ContainerRowIndex = 2)] public string GooglePlayUrl { get; set; } [ControlNumeric(LabelText = "VIPXU", Required = true, ContainerCssClass = Constants.ContainerCssClassCol4, ContainerRowIndex = 2)] public int VipXu { get; set; } [ControlText(Type = ControlText.TextBox, Required = true, MaxLength = 500, LabelText = "Đường dẫn tới website", ContainerCssClass = Constants.ContainerCssClassCol8, ContainerRowIndex = 3)] public string WebsiteUrl { get; set; } [ControlChoice(ControlChoice.CheckBox, LabelText = "", PrependText = "Hiện trên trang chủ", ContainerCssClass = Constants.ContainerCssClassCol4, ContainerRowIndex = 3)] public bool IsActived { get; set; } public static implicit operator DownloadGameModel(DownloadGameInfo entity) { var item = new DownloadGameModel { Id = entity.Id, IsActived = entity.IsActived, Code = entity.Code, UrlBanner = entity.UrlBanner, Logo = entity.Logo, Title = entity.Title, GooglePlayUrl = entity.GooglePlayUrl, WebsiteUrl = entity.WebsiteUrl, VipXu = entity.VipXu }; return item; } } }<file_sep>using System; using System.ComponentModel; using System.ComponentModel.DataAnnotations.Schema; using System.Runtime.Serialization; using CMSSolutions.Data; using CMSSolutions.Data.Entity; using CMSSolutions.Websites.Extensions; namespace CMSSolutions.Websites.Entities { [DataContract] public class CustomerHistoriesInfo : BaseEntity<long> { [DataMember] [DisplayName("CustomerId")] public int CustomerId { get; set; } [DataMember] [DisplayName("CreateDate")] public System.DateTime CreateDate { get; set; } [NotMapped] [DisplayName(Constants.NotMapped)] public string TextCreateDate { get { return CreateDate.ToString(Extensions.Constants.DateTimeFomatFull); } } [DataMember] [DisplayName("Action")] public string Action { get; set; } [DataMember] [DisplayName("Description")] public string Description { get; set; } [DataMember] [DisplayName("Status")] public int Status { get; set; } [DataMember] [DisplayName("Type")] public int Type { get; set; } [DataMember] [DisplayName("TransactionCode")] public string TransactionCode { get; set; } [DataMember] [DisplayName("Package")] public string Package { get; set; } [DataMember] [DisplayName("Amount")] public string Amount { get; set; } [DataMember] [DisplayName("TotalDay")] public string TotalDay { get; set; } [DataMember] [DisplayName("StartDate")] public DateTime? StartDate { get; set; } [NotMapped] [DisplayName(Constants.NotMapped)] public string TextStartDate { get { if (StartDate == null) { return ""; } return StartDate.Value.ToString(Extensions.Constants.DateTimeFomatFull); } } [DataMember] [DisplayName("EndDate")] public DateTime? EndDate { get; set; } [NotMapped] [DisplayName(Constants.NotMapped)] public string TextEndDate { get { if (EndDate == null) { return ""; } return EndDate.Value.ToString(Extensions.Constants.DateTimeFomatFull); } } } public class CustomerHistoriesMap : EntityTypeConfiguration<CustomerHistoriesInfo>, IEntityTypeConfiguration { public CustomerHistoriesMap() { ToTable("Modules_CustomerHistories"); HasKey(m => m.Id); Property(m => m.CustomerId).IsRequired(); Property(m => m.CreateDate).IsRequired(); Property(m => m.Action).IsRequired().HasMaxLength(250); Property(m => m.Description).IsRequired().HasMaxLength(2000); Property(m => m.TransactionCode).HasMaxLength(50); Property(m => m.Package).HasMaxLength(250); Property(m => m.Amount).HasMaxLength(50); Property(m => m.TotalDay).HasMaxLength(50); } } } <file_sep>using System; using CMSSolutions.Web.UI.ControlForms; namespace CMSSolutions.Websites.Models { public class CardCloseModel { public CardCloseModel() { EndDate = DateTime.Now; Messages = "Bạn chắc chắn đã xuất dữ liệu chưa đối soát? Hãy lưu lại nó vì nếu bạn chốt sẽ rồi sẽ không lấy lại được dữ liệu chưa đối soát."; } [ControlText(Type = ControlText.MultiText,Rows = 3, LabelText = "Ghi chú", ContainerCssClass = Constants.ContainerCssClassCol4, ContainerRowIndex = 0)] public string Messages { get; set; } [ControlDatePicker(LabelText = "Tính đến hết ngày", ContainerCssClass = Constants.ContainerCssClassCol4, ContainerRowIndex = 1)] public DateTime EndDate { get; set; } } }
d7fb2afb2bc16ffbad6f1b2f102b1bc709eb48d3
[ "Markdown", "C#", "JavaScript" ]
171
C#
hungvv6574/CMS_WatchMovieSite
ea0a632ec13041555d732150a0a0372793328bbe
5b99375b1c27d7466d1d69f08203b7ba670e49ad
refs/heads/master
<file_sep>#include "Shape.h" class Circle : public Shape { public: Circle(const double & = 1); void setRadius(const double &); double getRadius()const; virtual double Area()const override; private: double mRadius; }; <file_sep>#include <iostream> #include <iomanip> #include "Complex.h" using namespace std; Complex::Complex(const double &figureA, const double &figureB) { setFigureA(figureA); setFigureB(figureB); } void Complex::display() const { cout << fixed << setprecision(3); cout << "(" << getFigureA() << ", " << getFigureB() << ")"; } void Complex::setFigureA(const double &figureA) { this->figureA = figureA; } double Complex::getFigureA() const { return this->figureA; } void Complex::setFigureB(const double &figureB) { this->figureB = figureB; } double Complex::getFigureB() const { return this->figureB; } Complex Complex::operator +=(const Complex &otherComplex) { this->setFigureA(this->getFigureA() + otherComplex.getFigureA()); this->setFigureB(this->getFigureB() + otherComplex.getFigureB()); return *this; } Complex Complex::operator +(const Complex &otherComplex) const { return Complex((this->getFigureA() + otherComplex.getFigureA()), this->getFigureB() + otherComplex.getFigureB()); } Complex Complex::operator -=(const Complex &otherComplex) { this->setFigureA(this->getFigureA() - otherComplex.getFigureA()); this->setFigureB(this->getFigureB() - otherComplex.getFigureB()); return *this; } Complex Complex::operator -(const Complex &otherComplex) const { return Complex((this->getFigureA() - otherComplex.getFigureA()), this->getFigureB() - otherComplex.getFigureB()); } bool Complex::operator ==(const Complex &otherComplex) const { if(this->getFigureA() == otherComplex.getFigureA() && this->getFigureB() == otherComplex.getFigureB()){ return true; } else{ return false; } } bool Complex::operator !=(const Complex &otherComplex) const { if(this->getFigureA() != otherComplex.getFigureA() || this->getFigureB() != otherComplex.getFigureB()){ return true; } else{ return false; } } <file_sep>#ifndef BASEPLUS_H #define BASEPLUS_H #include <string> #include "CommissionEmployee.h" class BasePlusCommissionEmployee : public CommissionEmployee { public: BasePlusCommissionEmployee( const std::string &, const std::string &, const std::string &, const int &, const int &, const int &, double = 0.0, double = 0.0, double = 0.0 ); virtual ~BasePlusCommissionEmployee() { } void setBaseSalary( double ); double getBaseSalary() const; virtual double earnings() const override; virtual void print() const override; private: double baseSalary; }; #endif <file_sep>#include "banana.h" using namespace std; Banana::Banana(bool ripe) { this->ripe = ripe; } bool Banana::isRipe() { return this->ripe; } bool Banana::operator==(Banana& otherBanana){ if (this->isRipe() == otherBanana.isRipe()){ return true; } else{ return false; } } ostream& operator<<(ostream &output, Banana &banana){ output << "A "; if (banana.isRipe()){ output << "ripe "; } else { output << "rotten "; } output << "banana"; return output; }<file_sep>#include "Circle.h" class Cylinder : public Circle { public: Cylinder(const double & = 1, const double & = 1); void setHeight(const double &); double getHeight()const; virtual double Area()const override; virtual double Volume()const override; private: double mHeight; }; <file_sep>// Lab 1 Driver Program - used to test the 3 classes // File Name: MainProg.cpp // Author: <NAME> // Date: Jan 16, 2013 #include "Cylinder.h" #include <iostream> #include <iomanip> using namespace std; int main() { Shape shpeObj; // instantiate a Shape object cout << "The Shape object count is: " << Shape::getObjectCount() << '\n'; Circle crclObj; // instantiate a Circle object Cylinder cyldObj; // instantiate a Cylinder object // Count will be 3 in statement below because a Shape object is contained // within each Circle and Cylinder object as well. cout << "The Shape object count is: " << Shape::getObjectCount() << "\n"; Shape * shpePtr = &cyldObj; // declare a Shape pointer // and have it point to the Cylinder object Shape & shpeRef = cyldObj; // declare a Shape reference // and have it reference the Cylinder object // The above 2 statments are ok because a derived class object IsA base class object! // No additional objects created, so the count is still the same. cout << "The Shape object count is: " << Shape::getObjectCount() << "\n"; // Dynamically create 2 Shape objects Shape * shpePtr2 = new Shape; Shape & shpeRef2 = *new Shape; // The count should now be 5 cout << "The Shape object count is: " << Shape::getObjectCount() << "\n"; // Now destroy the 2 dynamically created objects! delete shpePtr2; delete &shpeRef2; //The count should now be 3 again. cout << "The Shape object count is: " << Shape::getObjectCount() << "\n\n"; // Test Shape class shpeObj.setNoOfSides(0); cout << fixed << setprecision(4); // force use of decimal point and 4 digits of // precision after the decimal place cout << "The number of sides is: " << shpeObj.getNoOfSides() << "\n\n"; cout << "The area of shpeObj is: " << shpeObj.Area() << '\n'; cout << "The volume of shpeObj is: " << shpeObj.Volume() << "\n\n\n"; // Test Circle class crclObj.setRadius(3.0); cout << "The radius of crclObj is: " << crclObj.getRadius() << "\n\n"; cout << "The number of sides is: " << crclObj.getNoOfSides() << "\n\n"; cout << "The area of crclObj is: " << crclObj.Area() << '\n'; cout << "The volume of crclObj is: " << crclObj.Volume() << "\n\n\n"; // Test Cylinder class cyldObj.setRadius(5.5); cyldObj.setHeight(2.5); cout << "The radius of cyldObj is: " << cyldObj.getRadius() << '\n'; cout << "The height of cyldObj is: " << cyldObj.getHeight() << "\n\n"; cout << "The number of sides is: " << cyldObj.getNoOfSides() << "\n\n"; cout << "The area of cyldObj is: " << cyldObj.Area() << '\n'; cout << "The volume of cyldObj is: " << cyldObj.Volume() << "\n\n"; // Let us see what happens when we ... shpeObj = cyldObj; // Assign the Cylinder class object to the // Shape class object cout << "When we invoke the shpeObj with the Area() method, the result is: " << shpeObj.Area() << '\n'; cout << "When we invoke the shpePtr with the Area() method, the result is: " << shpePtr->Area() << '\n'; cout << "When we invoke the shpeRef with the Area() method, the result is: " << shpeRef.Area() << '\n' << endl; return 0; }<file_sep>// Exercise 2 Start: Complex.h // Declaration of class Complex. // Member functions are defined in Complex.cpp. // Author: <NAME> // Date: Jan 30th, 2014 // Modified: <NAME> // Date: Apr 30th, 2015 /* Please note that you normally need to provide a prototype for any global functions used to overload an operator. This prototype statement is normally appended to the end of the class interface file (the class .h file), but it must _NOT_ be in the actual class declaration (with the exception of friend statements - see explanation further on in this paragraph). Why not put the prototype statement in the actual class declaration you ask? Because if it was, the function would be interpreted as a member function of the class instead of as a global function. This is what I have done below for the overloaded "+" , "-" and "!=" operators that are implemented as non-friend global functions. Note that the exception to this rule is when the class offers friendship to the global function (as with the overloaded << and >> operators). In this case the friend statements also serve the purpose of providing a prototype statement to the compiler. But I consider it good programming style to also provide prototypes below the class declaration for these friend functions, even though the compiler does not require them. */ #ifndef Complex_incl #define Complex_incl #include <iostream> class Complex // Complex class { public: Complex (double real = 1.0, double imag = 0.0 ); // ctor with // 2 default arguments Complex & operator+= (const Complex & RHS ) ; //Adds RHS to the Complex object invoked with this method // (thereby modifying the Complex object) and returns the result // Overloads the "+=" operator Complex & operator-= (const Complex & RHS ) ; //Subtracts RHS from the Complex object invoked with this method // (thereby modifying the Complex object) and returns the result // Overloads the "-=" operator bool operator == (const Complex & RHS) const; // Overloads "==" operator double getReal(void) const; // Returns real part double getImaginary(void) const; // Returns imaginary part void setReal(const double &); void setReal(std::istream &); void setImaginary(const double &); void setImaginary(std::istream &); void display(void); // Outputs to standard output stream the Complex object // in the format: (real_part,imaginary_part) private: double real_part, // represents real part of the Complex object imaginary_part; // represents imaginary part of the Complex object }; // The following are global function prototypes and not member functions of the Complex class. // They are included here because these functions are closely associated with the Complex class. // Their implementation is also in the same .cpp file as the implementation of the Complex // class. This is not required but is the norm in these situations. // overloads the binary "+" operator through a global function Complex operator + (const Complex & LHS, const Complex & RHS ); // overloads the binary "-" operator through a global function Complex operator - (const Complex & LHS, const Complex & RHS ); // overloads the binary "!=" operator through a global function bool operator != (const Complex & LHS, const Complex & RHS); std::ostream &operator<<(std::ostream &, const Complex &); std::istream &operator>>(std::istream &, Complex &); #endif <file_sep>class Shape { public: Shape(); ~Shape(); void setNoOfSides(const unsigned int &); unsigned int getNoOfSides()const; virtual double Area()const; virtual double Volume()const; static unsigned int getObjectCount(); private: unsigned int mNoOfSides; static unsigned int objectCount; void incrementObjectCount(); void decrementObjectCount(); }; <file_sep>template<typename T> bool isEqual(T a, T b) { if (a == b){ return true; } return false; }<file_sep>#include <iostream> using namespace std; class Banana { friend ostream& operator<<(ostream &, Banana &); public: Banana(bool = true); // default ctr bool isRipe(); bool operator==(Banana&); private: bool ripe; // is the banana ripe? };<file_sep>#ifndef DATE_H #define DATE_H #include <array> #include <iostream> class Date { friend std::ostream &operator<<( std::ostream &, const Date & ); public: Date( int m = 1, int d = 1, int y = 1900 ); void setDate( int, int, int ); int getMonth() const; int getDay() const; int getYear() const; Date &operator++(); Date operator++( int ); Date &operator+=( unsigned int ); static bool leapYear( int ); bool endOfMonth( int ) const; private: unsigned int month; unsigned int day; unsigned int year; static const std::array< unsigned int, 13 > days; void helpIncrement(); }; #endif <file_sep>// Exercise 1 Starting Point: Fraction.cpp // Member-function definitions for class Fraction. // Author: <NAME> // Date: Jan 30th, 2014 // Modified by: <NAME> // Date: Apr 29th, 2015 #include "Fraction.h" #include "GCD.h" // template function for calculating greatest common divisor #include <iostream> using namespace std; Fraction::Fraction (void) :numerator(0),denominator(1) { } Fraction::Fraction ( long long num, long long denom ) :numerator(num),denominator(denom) { simplify(); } Fraction & Fraction::plusEq (const Fraction & op ) { if (denominator != op.denominator ) { long long common_divisor = gcd(denominator,op.denominator); numerator *= (op.denominator / common_divisor); numerator += op.numerator * (denominator / common_divisor); denominator *= (op.denominator / common_divisor); } else { numerator += op.numerator; } simplify(); return (*this); } Fraction & Fraction::operator+=(const Fraction & op) { if (denominator != op.denominator) { long long common_divisor = gcd(denominator, op.denominator); numerator *= (op.denominator / common_divisor); numerator += op.numerator * (denominator / common_divisor); denominator *= (op.denominator / common_divisor); } else { numerator += op.numerator; } simplify(); return (*this); } Fraction & Fraction::minusEq (const Fraction & op ) { if (denominator != op.denominator ) { long long common_divisor = gcd(denominator,op.denominator); numerator *= (op.denominator / common_divisor); numerator -= op.numerator * ( denominator / common_divisor); denominator *= (op.denominator / common_divisor); } else { numerator -= op.numerator; } simplify(); return (*this); } Fraction & Fraction::operator -= (const Fraction & op) { if (denominator != op.denominator) { long long common_divisor = gcd(denominator, op.denominator); numerator *= (op.denominator / common_divisor); numerator -= op.numerator * (denominator / common_divisor); denominator *= (op.denominator / common_divisor); } else { numerator -= op.numerator; } simplify(); return (*this); } //Implementation of the timesEq method //Performs similar operation as the *= operator on the built-in types Fraction & Fraction::timesEq (const Fraction & op) { numerator *= op.numerator; denominator *= op.denominator; simplify(); // will make sure that denominator is positive and // will invoke gcd() function to reduce fraction // as much as possible return (*this); // returns the object which invoked the method } Fraction & Fraction::operator *= (const Fraction & op) { numerator *= op.numerator; denominator *= op.denominator; simplify(); // will make sure that denominator is positive and // will invoke gcd() function to reduce fraction // as much as possible return (*this); // returns the object which invoked the method } Fraction & Fraction::divideEq (const Fraction & op ) { numerator *= op.denominator; denominator *= op.numerator; simplify(); return (*this); } Fraction & Fraction::operator /= (const Fraction & op) { numerator *= op.denominator; denominator *= op.numerator; simplify(); return (*this); } Fraction Fraction::negate ( void ) const { return (Fraction(-(numerator), (denominator))); } Fraction Fraction::operator-(void)const { return (Fraction(-(numerator), (denominator))); } void Fraction::simplify(void) { if (denominator < 0 ) //correct sign if necessay { numerator = - numerator; denominator = - denominator; } if (numerator == 0 ) { denominator = 1; } // Reduce by dividing by gcd, if gcd > 1 else { long long gcd_val = gcd (numerator, denominator); if (gcd_val > 1) { numerator /= gcd_val; denominator /= gcd_val; } } } long long Fraction::getNum(void)const { return numerator; } long long Fraction::getDenom(void)const { return denominator; } void Fraction::display (void)const { cout << numerator << '/' << denominator; } <file_sep>// Exercise 1 Starting Point: Main Program - used to "test drive" the Fraction class // File Name: MainProg.cpp // Author: <NAME> // Date: Jan 30th, 2014 // Modified by: <NAME> // Date: Apr 29th, 2015 #include <iostream> #include "Fraction.h" // include definition of class Fraction from Fraction.h #include "GCD.h" // include definition of gcd template function using namespace std; int main() { Fraction A; // create a Fraction object with default ctor cout << "The default object is: "; A.display(); Fraction B(1,1024); // create a Fraction object with the non-default ctor cout << "\n\nThe non-default object is: "; B.display(); Fraction C(8,-1024); // test to see if the simplify method is invoked from // the non-default ctor cout << "\n\n8/-1024 simplified is: "; C.display(); // Test timesEq() cout << "\n\n- Test timesEq()"; A = Fraction(2,3); //Assign new values to Fraction objects B = Fraction(3,5); // NOTE: Equivalent to: C = A *= B; C = A *= (B); cout << "\nA = "; A.display(); cout << "\nB = "; B.display(); cout << "\nC = "; C.display(); // Test divideEq() cout << "\n\n- Test divideEq()"; A = Fraction(2,3); //Assign new values to Fraction objects B = Fraction(-7,3); // NOTE: Equivalent to: C = A /= B; C = A /= (B); cout << "\nA = "; A.display(); cout << "\nB = "; B.display(); cout << "\nC = "; C.display(); // Test plusEq() cout << "\n\n- Test plusEq()"; A = Fraction(-2,-3); //Assign new values to Fraction objects B = Fraction(8,9); // NOTE: Equivalent to: C = A += B; C = A += (B); cout << "\nA = "; A.display(); cout << "\nB = "; B.display(); cout << "\nC = "; C.display(); // Test minusEq() cout << "\n\n- Test minusEq()"; A = Fraction(2,3); //Assign new values to Fraction objects B = Fraction(8,9); // NOTE: Equivalent to: C = A -= B; C = A -= (B); cout << "\nA = "; A.display(); cout << "\nB = "; B.display(); cout << "\nC = "; C.display(); // Test negate() cout << "\n\n- Test negateEq()"; A = Fraction(-2,3); //Assign new values to Fraction objects B = Fraction(8,9); // NOTE: Equivalent to: C = -A; C = -A; cout << "\nA = "; A.display(); cout << "\nC = "; C.display(); // NOTE: Equivalent to: C = -B; C = -B; cout << "\nB = "; B.display(); cout << "\nC = "; C.display(); cout << '\n' << endl; return 0; } // end main <file_sep>#include "Circle.h" #include <cmath> Circle::Circle(const double &radius) : Shape() { Shape::setNoOfSides(1); setRadius(radius); } void Circle::setRadius(const double &radius) { if (radius > 0){ this->mRadius = radius; } } double Circle::getRadius()const { return this->mRadius; } double Circle::Area()const { return M_PI * getRadius() * getRadius(); } <file_sep>#include "Cylinder.h" #include <cmath> Cylinder::Cylinder(const double &radius, const double &height) : Circle(radius) { Shape::setNoOfSides(3); setHeight(height); } void Cylinder::setHeight(const double &height) { if(height > 0) { this->mHeight = height; } } double Cylinder::getHeight() const { return this->mHeight; } double Cylinder::Area()const { return ( 2 * M_PI * Circle::getRadius() * Circle::getRadius()) + ( 2 * M_PI * Circle::getRadius() * getHeight()); } double Cylinder::Volume()const { return M_PI * Circle::getRadius() * Circle::getRadius() * getHeight(); } <file_sep>#include <iostream> #include "Employee.h" using namespace std; Employee::Employee( const string &first, const string &last, const string &ssn, const int &month, const int &day, const int &year) : firstName( first ), lastName( last ), socialSecurityNumber( ssn ), birthdate( month, day, year ) { } void Employee::setFirstName( const string &first ) { firstName = first; } string Employee::getFirstName() const { return firstName; } void Employee::setLastName( const string &last ) { lastName = last; } string Employee::getLastName() const { return lastName; } void Employee::setSocialSecurityNumber( const string &ssn ) { socialSecurityNumber = ssn; } string Employee::getSocialSecurityNumber() const { return socialSecurityNumber; } Date Employee::getBirthDate() const { return this->birthdate; } void Employee::setBirthDate(const int &month, const int &day, const int &year) { this->birthdate.setDate(month, day, year); } void Employee::print() const { cout << getFirstName() << ' ' << getLastName() << "\nsocial security number: " << getSocialSecurityNumber(); } <file_sep>#include <iostream> #include <string> #include "equality.h" #include "banana.h" using namespace std; int main() { int intA = 5; int intB = 5; int intC = 6; cout << boolalpha; cout << "intA: " << intA << " is equal to intB: " << intB << "? " << isEqual(intA, intB) << endl; cout << "intA: " << intA << " is equal to intC: " << intC << "? " << isEqual(intA, intC) << endl; string stringA = "hello"; string stringB = "hello"; string stringC = "bonjour"; cout << "stringA: " << stringA << " is equal to stringB: " << stringB << "? " << isEqual(stringA, stringB) << endl; cout << "stringA: " << stringA << " is equal to stringC: " << stringC << "? " << isEqual(stringA, stringC) << endl; Banana bananaA; Banana bananaB; Banana bananaC(false); cout << "Two bananas that are ripe are considered the equal" << endl; cout << "bananaA: " << bananaA << " is equal to bananaB: " << bananaB << "? " << isEqual(bananaA, bananaB) << endl; cout << "bananaA: " << bananaA << " is equal to intC: " << bananaC << "? " << isEqual(bananaA, bananaC) << endl; return 0; }<file_sep>class Complex { public: Complex(const double & = 1.0, const double & = 0.0); void display() const; void setFigureA(const double &); double getFigureA() const; void setFigureB(const double &); double getFigureB() const; Complex operator +=(const Complex &); Complex operator +(const Complex &) const; Complex operator -=(const Complex &); Complex operator -(const Complex &) const; bool operator ==(const Complex &) const; bool operator !=(const Complex &) const; private: double figureA; double figureB; }; <file_sep>// Exercise 2 start: Complex.cpp // Member-function definitions for class Complex. // Author: <NAME> // Date: Jan 30th, 2014 // Modified: <NAME> // Date: Apr 30th, 2015 #include "Complex.h" #include <iomanip> using namespace std; ostream &operator<<(ostream &output, const Complex &op) { output << "( " << op.getReal() << ", " << op.getImaginary() << " )"; return output; } istream &operator>>(istream &input, Complex &op) { input.ignore(2); op.setReal(input); input.ignore(2); op.setImaginary(input); input.ignore(2); return input; } void Complex::setReal(istream &input) { input >> this->real_part; } void Complex::setImaginary(istream &input) { input >> this->imaginary_part; } Complex::Complex ( double real, double imag ) { this->real_part = real; this->imaginary_part = imag; } // overload the "+=" operator Complex & Complex::operator += (const Complex & op ) { this->real_part += op.real_part; this->imaginary_part += op.imaginary_part; return (*this); } // overload the "-=" operator Complex & Complex::operator -= (const Complex & op ) { this->real_part -= op.real_part; this->imaginary_part -= op.imaginary_part; return (*this); } // overload the "==" operator bool Complex::operator == (const Complex & RHS) const { if (this->real_part != RHS.real_part) return false; else if (this->imaginary_part != RHS.imaginary_part) return false; else return true; } void Complex::setReal(const double & real_part) { this->real_part = real_part; } void Complex::setImaginary(const double & imaginary_part) { this->imaginary_part = imaginary_part; } double Complex::getReal(void) const { return this->real_part; } double Complex::getImaginary(void) const { return this->imaginary_part; } void Complex::display (void) { // set floating-point number format cout << fixed << setprecision(3); cout << "( " << this->getReal() << " , " << this->getImaginary() << " )"; } // overloads the binary '+' operator through a global function Complex operator + (const Complex & LHS, const Complex & RHS ) { Complex temp = LHS; temp += RHS; // uses the overloaded "+=" operator return temp; } // overloads the binary '-' operator through a global function Complex operator - (const Complex & LHS, const Complex & RHS ) { Complex temp = LHS; temp -= RHS; // uses the overloaded "-=" operator return temp; } // overloads the binary "!=" operator through a global function bool operator != (const Complex & LHS, const Complex & RHS) { return !(LHS == RHS); // uses overloaded "==" operator } <file_sep>#include "Shape.h" unsigned int Shape::objectCount = 0; Shape::Shape() { setNoOfSides(0); incrementObjectCount(); } Shape::~Shape() { decrementObjectCount(); } void Shape::setNoOfSides(const unsigned int &noOfSides) { if (noOfSides >= 0){ this->mNoOfSides = noOfSides; } } unsigned int Shape::getNoOfSides()const { return this->mNoOfSides; } double Shape::Area()const { return 0; } double Shape::Volume()const { return 0; } unsigned int Shape::getObjectCount() { return objectCount; } void Shape::incrementObjectCount() { objectCount++; } void Shape::decrementObjectCount() { if (objectCount > 0){ objectCount--; } } <file_sep>// Main Program - used to "test drive" the Complex class // File Name: MainProg_P2.cpp // Author: <NAME> // Date: Date: Jan 30th, 2014 // Modified: <NAME> // Date: Apr 30th, 2015 #include "Complex.h" // include definition of class Complex from Complex.h using namespace std; int main() { // Test constructor -NOTE: your Complex class should have only // one constructor. Your constructor should have default arguments // for the real and imaginary parts of the complex object. Complex A; // create a Complex object using default arguments cout << "The default object is: " << A; Complex B(-2.45, 1.0); // create a Complex object supplying values to the ctor cout << "\n\nThe non-default object is: " << B; Complex C(25.777,-35.668); // create another Complex object supplying values to the ctor cout << "\n\nThe second non-default object is: " << C; // Test overloaded += operator cout << "\n\n- Test overloaded += operator"; A = Complex(-25.44,-3.543); //Assign new values to Complex objects B = Complex(30.3,-34.876); C = A += B; cout << "\nA = " << A; cout << "\nB = " << B; cout << "\nC = " << C; // Test overloaded -= operator cout << "\n\n- Test overloaded -= operator"; A = Complex(4.65,3.789); //Assign new values to Complex objects B = Complex(6.78,9.222); C = A -= B; cout << "\nA = " << A; cout << "\nB = " << B; cout << "\nC = " << C; // Test overloaded + operator cout << "\n\n- Test overloaded + operator"; cout << "\nEnter a value for A: "; cin >> A; cout << "\nEnter a value for B: "; cin >> B; C = A + B; cout << "\nA = " << A << " <== is this correct?"; cout << "\nB = " << B << " <== is this correct?"; cout << "\nC = " << C << " <== is this correct?"; // Test overloaded - operator cout << "\n\n- Test overloaded - operator"; cout << "\nEnter a value for A and B: "; cin >> A >> B; C = A - B; cout << "\nA = " << A << " <== is this correct?"; cout << "\nB = " << B << " <== is this correct?"; cout << "\nC = " << C << " <== is this correct?"; // Test overloaded == and != operators cout << "\n\n- Test overloaded == and != operators"; A = Complex(4.65,3.789); //Assign new values to Complex objects B = Complex(6.78,9.222); if (A == B) cout << "\nA is equal to B" << '\n'; else cout << "\nA is not equal to B" << '\n'; if (A != B) cout << "A is not equal to B" << '\n'; else cout << "A is equal to B" << '\n'; cout << "\nA = " << A; cout << "\nB = " << B; A = Complex(4.65,3.789); //Assign new values to Complex objects B = Complex(4.65,3.789); if (A == B) cout << "\n\nA is equal to B" << '\n'; else cout << "\n\nA is not equal to B" << '\n'; if (A != B) cout << "A is not equal to B" << '\n'; else cout << "A is equal to B" << '\n'; cout << "\nA = " << A; cout << "\nB = " << B; cout << '\n' << endl; system("pause"); return 0; } // end main <file_sep>#include <iostream> #include "Complex.h" using namespace std; int main() { Complex A; cout << "The default object is: "; A.display(); Complex B(-2.45, 1.0); cout << "\n\nThe non-default object is: "; B.display(); Complex C(25.777,-35.668); cout << "\n\nThe second non-default object is: "; C.display(); cout << "\n\n- Test overloaded += operator"; A = Complex(-25.44,-3.543); B = Complex(30.3,-34.876); C = A += B; cout << "\nA = "; A.display(); cout << "\nB = "; B.display(); cout << "\nC = "; C.display(); cout << "\n\n- Test overloaded -= operator"; A = Complex(4.65,3.789); B = Complex(6.78,9.222); C = A -= B; cout << "\nA = "; A.display(); cout << "\nB = "; B.display(); cout << "\nC = "; C.display(); cout << "\n\n- Test overloaded + operator"; A = Complex(-25.44,-3.543); B = Complex(30.3,-34.876); C = A + B; cout << "\nA = "; A.display(); cout << "\nB = "; B.display(); cout << "\nC = "; C.display(); cout << "\n\n- Test overloaded - operator"; A = Complex(4.65,3.789); B = Complex(6.78,9.222); C = A - B; cout << "\nA = "; A.display(); cout << "\nB = "; B.display(); cout << "\nC = "; C.display(); cout << "\n\n- Test overloaded == and != operators"; A = Complex(4.65,3.789); B = Complex(6.78,9.222); if (A == B) cout << "\nA is equal to B" << '\n'; else cout << "\nA is not equal to B" << '\n'; if (A != B) cout << "A is not equal to B" << '\n'; else cout << "A is equal to B" << '\n'; cout << "\nA = "; A.display(); cout << "\nB = "; B.display(); A = Complex(4.65,3.789); B = Complex(4.65,3.789); if (A == B) cout << "\n\nA is equal to B" << '\n'; else cout << "\n\nA is not equal to B" << '\n'; if (A != B) cout << "A is not equal to B" << '\n'; else cout << "A is equal to B" << '\n'; cout << "\nA = "; A.display(); cout << "\nB = "; B.display(); cout << '\n' << endl; return 0; }
2dc35e76c78bf51901f91006ec6235e0d27f6038
[ "C++" ]
22
C++
davidenglishmusic/comp2618_labs
46ee1500affa0352549a9dc3d31c76b7432a10af
f32b45bd9af5ecc03ac9b43622a6fd75604db30f
refs/heads/master
<repo_name>466262360/MyKotlin<file_sep>/lib/framework/src/main/java/com/test/framework/ui/base/BaseApplication.kt package com.test.framework.ui.base import android.app.Application /** * Created by Administrator on 2021/5/27. * Des: */ open class BaseApplication :Application(){ }<file_sep>/lib/framework/src/main/java/com/test/framework/ui/base/BaseVMActivity.kt package com.test.framework.ui.base import android.os.Bundle import androidx.appcompat.app.AppCompatActivity import androidx.lifecycle.Observer import androidx.lifecycle.ViewModelProvider import com.test.framework.ext.getVMClass /** * Created by Administrator on 2021/5/27. * Des: */ abstract class BaseVMActivity<VM : BaseViewModel> : AppCompatActivity() { lateinit var viewModel: VM abstract fun createObserver() abstract fun initView() abstract fun initDataBinding() abstract fun showLoading(it: String = "加载中...") abstract fun dismissLoading() abstract fun getLayout():Int override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) initDataBinding() init() } private fun init() { viewModel = createViewModel() registerUIChange() initView() createObserver() } private fun registerUIChange() { viewModel.uiChange.showDialog.observeInActivity(this, Observer { showLoading(it) }) viewModel.uiChange.dismissDialog.observeInActivity(this, Observer { dismissLoading() }) } private fun createViewModel(): VM { return ViewModelProvider(this).get(getVMClass(this)) } } <file_sep>/lib/framework/src/main/java/com/test/framework/ui/base/BaseViewModel.kt package com.test.framework.ui.base import androidx.lifecycle.ViewModel import com.kunminx.architecture.ui.callback.UnPeekLiveData /** * Created by Administrator on 2021/5/27. * Des: */ class BaseViewModel :ViewModel(){ val uiChange by lazy{ UiChange()} inner class UiChange{ val showDialog by lazy { UnPeekLiveData<String>() } val dismissDialog by lazy { UnPeekLiveData<Boolean>() } } }<file_sep>/lib/framework/src/main/java/com/test/framework/ui/base/BaseVMDBActivity.kt package com.test.framework.ui.base import android.os.Bundle import androidx.databinding.DataBindingUtil import androidx.databinding.ViewDataBinding /** * Created by Administrator on 2021/5/28. * Des: */ abstract class BaseVMDBActivity<VM:BaseViewModel,DB:ViewDataBinding>:BaseVMActivity<VM>() { lateinit var mDataBind:DB override fun initDataBinding() { mDataBind = DataBindingUtil.setContentView(this, getLayout()) mDataBind.lifecycleOwner=this } }<file_sep>/app/src/main/java/com/test/myapplication/MainActivity.kt package com.test.myapplication import com.test.framework.ui.base.BaseActivity import com.test.framework.ui.base.BaseViewModel import com.test.myapplication.databinding.ActivityMainBinding class MainActivity : BaseActivity<BaseViewModel,ActivityMainBinding>() { override fun initView() { TODO("Not yet implemented") } override fun getLayout()=R.layout.activity_main override fun createObserver() { } }<file_sep>/lib/framework/src/main/java/com/test/framework/ext/getViewModelExt.kt package com.test.framework.ext import java.lang.reflect.ParameterizedType /** * Created by Administrator on 2021/5/28. * Des: */ @Suppress("UNCHECKED_CAST") fun <VM> getVMClass(obj:Any):VM{ return (obj.javaClass.genericSuperclass as ParameterizedType).actualTypeArguments[0] as VM }<file_sep>/settings.gradle include ':module:main' include ':module' include ':lib:framework' include ':lib' include ':lib' include ':app' rootProject.name = "My Application"<file_sep>/module/main/src/main/java/com/test/main/SplashActivity.kt package com.test.main import androidx.appcompat.app.AppCompatActivity /** * Created by Administrator on 2021/5/27. * Des: */ class SplashActivity : AppCompatActivity(){ }<file_sep>/lib/framework/src/main/java/com/test/framework/ui/base/BaseFragment.kt package com.test.framework.ui.base import androidx.fragment.app.Fragment /** * Created by Administrator on 2021/5/21. * Des: */ abstract class BaseFragment :Fragment(){ }<file_sep>/app/src/main/java/com/test/myapplication/MyApplication.kt package com.test.myapplication import android.app.Application import androidx.viewbinding.BuildConfig import com.alibaba.android.arouter.launcher.ARouter import com.test.framework.ui.base.BaseApplication /** * Created by Administrator on 2021/5/21. * Des: */ class MyApplication :BaseApplication(){ override fun onCreate() { super.onCreate() if(BuildConfig.DEBUG){ ARouter.openDebug() ARouter.openLog() } ARouter.init(this) } }<file_sep>/lib/framework/src/main/java/com/test/framework/ui/base/BaseActivity.kt package com.test.framework.ui.base import androidx.databinding.ViewDataBinding /** * Created by Administrator on 2021/5/21. * Des: */ abstract class BaseActivity<VM : BaseViewModel, DB : ViewDataBinding> : BaseVMDBActivity<VM, DB>() { abstract override fun getLayout(): Int abstract override fun initView() override fun createObserver() { TODO("Not yet implemented") } override fun showLoading(it: String) { TODO("Not yet implemented") } override fun dismissLoading() { TODO("Not yet implemented") } }<file_sep>/config.gradle ext { build = [ compileSdkVersion: 30, buildToolsVersion: "30.0.2", minSdkVersion : 23, targetSdkVersion : 30, versionCode : 1, versionName : "1" ] deps = [ //kotlin core_ktx : 'androidx.core:core-ktx:1.3.0', //androidx appcompat : 'androidx.appcompat:appcompat:1.1.0', //ARouter arouter_api : 'com.alibaba:arouter-api:1.5.0', //liveData livedata : 'androidx.lifecycle:lifecycle-livedata-ktx:2.2.0', unpeek_livedata: 'com.kunminx.archi:unpeek-livedata:4.4.1-beta1', //ViewModel activity扩展 activity_ktx : 'androidx.activity:activity-ktx:1.1.0', //ViewModel fragment扩展 fragment_ktx : 'androidx.fragment:fragment-ktx:1.2.5', //viewModel扩展 viewModelScope : 'androidx.lifecycle:lifecycle-viewmodel-ktx:2.2.0', //material,如BottomNavigationView、TabLayout等 material : 'com.google.android.material:material:1.3.0-alpha01', //约束布局 constraintlayout : 'androidx.constraintlayout:constraintlayout:1.1.3', ] //单元测试 apiTestDepds = [ junit: 'junit:junit:4.12' ] //android 测试 apiAndroidTestDepds = [ junit : 'androidx.test.ext:junit:1.1.1', espresso: 'androidx.test.espresso:espresso-core:3.2.0' ] }
c5a84ca0dc39b3591b359d58bfa6d93954516795
[ "Kotlin", "Gradle" ]
12
Kotlin
466262360/MyKotlin
860a81e534933232ac229ba1f5191b8de112cf34
bc4841897d0cc4d247dec750284870300df1a41a
refs/heads/master
<repo_name>processosunicredscpr/integrascpr<file_sep>/integravalidation.js $(document).ready(function() { verificarCamposDoTipoFile(); }); function verificarCamposDoTipoFile() { for (let index = 0; index < $('#form-integra').find('div[xtype="FILE"]').length; index++) { $($($('#form-integra').find('div[xtype="FILE"]')[index]).children()[0]).text('Arquivo'); } } <file_sep>/integravalidationSTONE.js $(document).ready(function() { $('.form-group [XTYPE="TEXT"]').css('display', 'block'); $('.form-group [XTYPE="SELECT"]').css('display', 'block'); $('#rangeFaturamentoOutput').hide(); $('#rangeFaturamentoInput').hide(); $('inp:tpvMensalEstimado').parent().show(); $('inp:cooperativa').parent().parent().show(); $('#taxas td').show(); $('#taxas th').show(); });
ff4224fe3c751b24f4d940f48786af94c22998f7
[ "JavaScript" ]
2
JavaScript
processosunicredscpr/integrascpr
f1a0a7bda7566a272a0079450e1b74a18601d65a
d96a0012ef9a6b7bccdc189bf8e96e9d80fef5f6
refs/heads/master
<file_sep>import bpy import bmesh import copy import mathutils import random import time from datetime import datetime from mathutils import Euler from math import sqrt ### 3D Context creation. ### def view3d_find( return_area = False ): # returns first 3d view, normally we get from context for area in bpy.context.window.screen.areas: if area.type == 'VIEW_3D': v3d = area.spaces[0] rv3d = v3d.region_3d for region in area.regions: if region.type == 'WINDOW': if return_area: return region, rv3d, v3d, area return region, rv3d, v3d return None, None def createOverrideContext(): region, rv3d, v3d, area = view3d_find(True) # Define context override dictionary for overriding the knife_project operator's context override = { 'scene' : bpy.context.scene, 'region' : region, 'area' : area, 'space' : v3d, 'active_object' : bpy.context.object, 'window' : bpy.context.window, 'screen' : bpy.context.screen, 'selected_objects' : bpy.context.selected_objects, 'edit_object' : bpy.context.object, 'region_3d' : rv3d } originalRegion3D = { 'view_location' : copy.copy(rv3d.view_location), 'view_distance' : rv3d.view_distance, 'view_rotation' : copy.copy(rv3d.view_rotation), 'view_perspective' : rv3d.view_perspective} # Set the view to origin with a small distance so that we have a better precision for the knife projection. rv3d.view_location = (0,0,0) rv3d.view_distance = 1 # Set view to TOP by directly rotating the 3D view region's view_rotation. rv3d.view_rotation = Euler( (0,0,0) ).to_quaternion() # Set the canera to orthographic. rv3d.view_perspective = 'ORTHO' return override, originalRegion3D def createFaceOverrideContext(position, direction): region, rv3d, v3d, area = view3d_find(True) # Define context override dictionary for overriding the knife_project operator's context override = { 'scene' : bpy.context.scene, 'region' : region, 'area' : area, 'space' : v3d, 'active_object' : bpy.context.object, 'window' : bpy.context.window, 'screen' : bpy.context.screen, 'selected_objects' : bpy.context.selected_objects, 'edit_object' : bpy.context.object, 'region_3d' : rv3d } print("after creating override") originalRegion3D = { 'view_location' : copy.copy(rv3d.view_location), 'view_distance' : rv3d.view_distance, 'view_rotation' : copy.copy(rv3d.view_rotation), 'view_perspective' : rv3d.view_perspective} print("after creating originalRegion3D") # Set the view to origin with a small distance so that we have a better precision for the knife projection. rv3d.view_location = position rv3d.view_distance = 1 print("after setting position") print(direction == None) print(direction) print("direction = " + str(direction)) # Set view to TOP by directly rotating the 3D view region's view_rotation. rotationQuat = direction.to_track_quat('Z', 'Y') print("rotationQuat = " + str(rotationQuat)) print("euler rotation = " + str(rotationQuat.to_euler())) rv3d.view_rotation = rotationQuat print("after setting rotation") # Set the canera to orthographic. rv3d.view_perspective = 'ORTHO' print("after setting perspective") return override, originalRegion3D def setRegion3D(override, originalConfiguration): rv3d = override['region_3d'] rv3d.view_location = originalConfiguration['view_location'] rv3d.view_distance = originalConfiguration['view_distance'] rv3d.view_rotation = originalConfiguration['view_rotation'] rv3d.view_perspective = originalConfiguration['view_perspective'] ### Quick math. ### def distance(aVert, bVert): return sqrt((aVert.x - bVert.x)**2 + (aVert.y - bVert.y)**2 + (aVert.z - bVert.z)**2) # Compute the length of an edge. # The edge here is a bmesh edge, regular edges don't carry the whole vertices. def edgeLength(bmeshEdge): return distance(bmeshEdge.verts[0].co, bmeshEdge.verts[1].co) ### Handling meshes. ### def findEdge(mesh, edgeKey): for currentEdge in mesh.edges: currentEdgeKey = currentEdge.key if (currentEdgeKey[0] == edgeKey[0] and currentEdgeKey[1] == edgeKey[1]): return currentEdge def findEdgeIndex(mesh, edgeKey): foundEdge = findEdge(mesh, edgeKey) if not foundEdge==None: return foundEdge.index # Return the tangent of a face. # The face has to be a flat quad. def faceTangent(object, faceIndex): face = object.data.polygons[faceIndex] # Take the first edge as the tangent. edgeKeys = face.edge_keys[0] vertA = object.data.vertices[edgeKeys[0]] vertB = object.data.vertices[edgeKeys[1]] tangent = (vertA.co - vertB.co).normalized() return tangent def buildFaceTuple(objectToBrowse, faceIndex): polygon = objectToBrowse.data.polygons[faceIndex] verticesArray = [] for currentVertexIndex in polygon.vertices: # Make a deep copy of the vertex to be sure it doesn't get modified accidentaly. currentCoordinates = objectToBrowse.data.vertices[currentVertexIndex].co verticesArray.append((currentCoordinates.x, currentCoordinates.y, currentCoordinates.z)) return (faceIndex, verticesArray) # The face tuple should contain first the index of the face, then an array of vertices. def checkIsSameFace(objectToBrowse, faceTuple): faceIndex = faceTuple[0] verticesArray = faceTuple[1] faceToCheck = objectToBrowse.data.polygons[faceIndex] polygonMatches = True for currentVertexIndexFromPolygon in faceToCheck.vertices: currentVertexFromPolygon = objectToBrowse.data.vertices[currentVertexIndexFromPolygon] foundSameVertice = False for currentVertexFromArray in verticesArray: if currentVertexFromArray[0] == currentVertexFromPolygon.co.x and currentVertexFromArray[1] == currentVertexFromPolygon.co.y and currentVertexFromArray[2] == currentVertexFromPolygon.co.z: foundSameVertice = True # If one of the vertices doesn't match, then the polygon doesn't match. if foundSameVertice == False: polygonMatches = False # If all the vertices in the polygon matched, then polygonMatches is still True. return polygonMatches # Function to find a face in an object according to the position of the vertices it contains. # This function is necessary because faces tend to change index when others are created. def findFaceByVertices(objectToBrowse, verticesArray): foundFace = None dataToBrowse = objectToBrowse.data for currentPolygon in dataToBrowse.polygons: if checkIsSameFace(objectToBrowse, (currentPolygon.index, verticesArray)): foundFace = currentPolygon.index return foundFace # Material related functions. # Switch the selected material slot of the current object taking a string in. def switchMaterialSlotByName(slotName): currentIndex = 0 for currentSlot in bpy.context.object.material_slots: if currentSlot.name == slotName: bpy.context.object.active_material_index = currentIndex return currentIndex = currentIndex + 1 # Assign a material slot by name to the currently selected faces. def assignMaterialSlotByName(slotName): # Switch to the right material slot. switchMaterialSlotByName(slotName) # Make sure we are in edit mode. bpy.ops.object.mode_set(mode = 'EDIT') # Assign the slot. bpy.ops.object.material_slot_assign()<file_sep>import bpy import bmesh import mathutils import random import time from datetime import datetime from mathutils import Euler # Import submodules. import sys import os import importlib import copy # Utils. import utils_2_8 importlib.reload(utils_2_8) from utils_2_8 import * insetThickness = 0.01 # Thickness of the inset operation. insetDepth = 0.01 # Depth of the inset operation. insetRelativeOffset = True # True of the offset value should represent a proportion of offset. inwardProbability = 0.5 # Probability of the inset to go in the surface's direction. def insetGeneric(seed, objectToInset, faceTuple): # Initialize the random seed, this is important in order to generate exactly the same content for a given seed. random.seed(seed) # Find the right face despit faces that have been reindexed. #if checkIsSameFace(objectToInset, faceTuple): #print("face corresponding") #faceToSubdivideIndex = faceTuple[0] #else: #print("no correspondance") #faceToSubdivideIndex = findFaceByVertices(objectToInset, faceTuple[1]) faceToSubdivideIndex = faceTuple[0] bpy.ops.object.mode_set(mode = 'EDIT') # Deselect everything. bpy.ops.mesh.select_all(action='DESELECT') # Selecting faces only works when not in edit mode, for some reason. bpy.ops.object.mode_set(mode = 'OBJECT') # Select only the face to inset. objectToInset.data.polygons[faceToSubdivideIndex].select = True # Enter edit mode for the object in argument. bpy.context.view_layer.objects.active = objectToInset bpy.ops.object.mode_set(mode = 'EDIT') # Randomly pick if the inset is to be made inward or outward. if random.uniform(0, 1) < inwardProbability: finalDepth = -insetDepth else: finalDepth = insetDepth # Perform the inset operation. bpy.ops.mesh.inset(thickness=insetThickness, depth=finalDepth, use_relative_offset=insetRelativeOffset) # Refresh data. objectToInset.data.validate(verbose=True) objectToInset.update_from_editmode() # Return an array of face tuples for the selected face. # The selected face is the one resulting of the inset. faceTuplesResult = [buildFaceTuple(objectToInset, currentPolygon.index) for currentPolygon in objectToInset.data.polygons if currentPolygon.select] return faceTuplesResult # Test function if __name__ == "__main__": # Keep track of the selected object. originalySelectedObject = bpy.context.active_object originalySelectedObject.data.validate(verbose=True) originalySelectedObject.update_from_editmode() for currentPolygon in originalySelectedObject.data.polygons: if currentPolygon.select: insetGeneric(datetime.now(), originalySelectedObject, buildFaceTuple(originalySelectedObject, currentPolygon.index))<file_sep>import bpy import bmesh import mathutils import random import time from datetime import datetime from mathutils import Euler # Import submodules. import sys import os import importlib import copy # Utils. import utils_2_8 importlib.reload(utils_2_8) from utils_2_8 import * # Global parameters. minCuts = 1 # Minimum number of cuts per subdivision. maxCuts = 4 # Maximum number of cuts per subdivision. verticalProbability = 0.5 # Probability of doing a vertical subdivision. # Conditions minimumLength = 0.2 # Should be in object mode when calling this function. def findFirstSelectedPolygon(objectToSubdivide): for currentPolygon in objectToSubdivide.data.polygons: if currentPolygon.select: return currentPolygon def subdivideGeneric(seed, objectToSubdivide, faceTuple): # Initialize the random seed, this is important in order to generate exactly the same content for a given seed. random.seed(seed) # Find the right face despit faces that have been reindexed. #if checkIsSameFace(objectToSubdivide, faceTuple): #faceToSubdivideIndex = faceTuple[0] #else: #faceToSubdivideIndex = findFaceByVertices(objectToSubdivide, faceTuple[1]) faceToSubdivideIndex = faceTuple[0] faceToSubdivide = objectToSubdivide.data.polygons[faceToSubdivideIndex] # Sanity check. if len(faceToSubdivide.edge_keys) != 4: print("Face does not have 4 edges.") return # Decide whether the subidivision is to happen vertically of horizontally. if random.uniform(0, 1) < verticalProbability: verticalSubdivision = True else: verticalSubdivision = False if verticalSubdivision: aEdgeKey = faceToSubdivide.edge_keys[0] else: aEdgeKey = faceToSubdivide.edge_keys[1] # Minimum length test. point0Coordinates = objectToSubdivide.data.vertices[aEdgeKey[0]].co point1Coordinates = objectToSubdivide.data.vertices[aEdgeKey[1]].co edgeLength = distance(point0Coordinates, point1Coordinates) if edgeLength < minimumLength: return None bpy.ops.object.mode_set(mode = 'EDIT') # Deselect everything. bpy.ops.mesh.select_all(action='DESELECT') # Selecting faces only works when not in edit mode, for some reason. bpy.ops.object.mode_set(mode = 'OBJECT') # Select only the face to inset. objectToSubdivide.data.polygons[faceToSubdivideIndex].select = True # Enter edit mode for the object in argument. bpy.context.view_layer.objects.active = objectToSubdivide bpy.ops.object.mode_set(mode = 'EDIT') bpy.ops.mesh.inset(thickness=0.0001) bpy.ops.object.mode_set(mode = 'OBJECT') faceToSubdivide_inset = findFirstSelectedPolygon(objectToSubdivide) if verticalSubdivision: aEdgeKey_inset = faceToSubdivide_inset.edge_keys[0] bEdgeKey_inset = faceToSubdivide_inset.edge_keys[2] else: aEdgeKey_inset = faceToSubdivide_inset.edge_keys[1] bEdgeKey_inset = faceToSubdivide_inset.edge_keys[3] # Find the chosen edges in the object's data. aEdge_inset = findEdge(objectToSubdivide.data, aEdgeKey_inset) bEdge_inset = findEdge(objectToSubdivide.data, bEdgeKey_inset) # Deselect all the faces. bpy.ops.object.mode_set(mode = 'EDIT') bpy.ops.mesh.select_all(action='DESELECT') # Find the index of the edges to select. # We get the index rather than the edge itself because of references issues. aEdgeIndex_inset = findEdgeIndex(objectToSubdivide.data, aEdgeKey_inset) bEdgeIndex_inset = findEdgeIndex(objectToSubdivide.data, bEdgeKey_inset) # Select the chosen edges. Be careful, edges can only be selected properly when in object mode. bpy.ops.object.mode_set(mode = 'OBJECT') objectToSubdivide.data.edges[aEdgeIndex_inset].select = True objectToSubdivide.data.edges[bEdgeIndex_inset].select = True bpy.ops.object.mode_set(mode = 'EDIT') # Randomly choose how many cuts are going to be applied. numberOfCuts = random.randint(minCuts, maxCuts) # Apply the subdivision. subdivisionResult = bpy.ops.mesh.subdivide(number_cuts=numberOfCuts, quadcorner='INNERVERT') # Refresh data. objectToSubdivide.data.validate(verbose=True) objectToSubdivide.update_from_editmode() # We always want to exit functions in object mode. bpy.ops.object.mode_set(mode = 'OBJECT') # Return an array of face tuples for the selected faces. # The selected faces are the ones resulting of the subdivision. faceTuplesResult = [buildFaceTuple(objectToSubdivide, currentPolygon.index) for currentPolygon in objectToSubdivide.data.polygons if currentPolygon.select] return faceTuplesResult # Test function if __name__ == "__main__": # Keep track of the selected object. originalySelectedObject = bpy.context.active_object originalySelectedObject.data.validate(verbose=True) originalySelectedObject.update_from_editmode() for currentPolygon in originalySelectedObject.data.polygons: if currentPolygon.select: subdivideGeneric(datetime.now(), originalySelectedObject, buildFaceTuple(originalySelectedObject, currentPolygon.index))<file_sep>import bpy import bmesh import mathutils import random # Probabilities. randomSeed = 0 # Seed for randomization, different everytime when set to negative. rectangleProbability = 0.5 # Probability to pop a rectangle rather than a sphere. poppingNewEdge = 1.0 # Probability for each edge to enter a recursive cycle if the recursivity limit has not been hit. notchType45 = 0.5 # Probability to pop a 45 degrees notch. outerProbability = 0.5 # Probability to have a notch coming outward rather than inward. relativeWidthMin = 0.1 # Minimum length of a notch relative to the edge it is created from. relativeWidthMax = 0.9 # Maximum length of a notch relative to the edge it is created from. relativeDepthWidthRatioMax = 0.3 # Maximum depth of a notch relative to it's length. # Rectangles probabilities. maximumRatioDifference = 0.2 # Maximum ratio between height and width, smaller values make for a bigger ratio. Should belong to [0 ; 1]. verticalProbability = 0.5 # Probability of poping a vertical rectangle if maximumRatioDifference is different from 1. # Circle probabilities. minmumCircleEdges = 3 # Minimum possible edges in a circle. maximumCircleEdges = 6 # Maximum possible edges in a circle. # Global settings. recursivity = 0 # Recursivity limit. squareRadius = 10 # Drives the number of shapes generated. # ___________ -> _____ _____ # |_____| def edgeToNotch90(originalBmesh, edge, relativeWidth, relativeDepth, outer): # Remember the original 2 vertices. vertA = edge.verts[0] vertB = edge.verts[1] # First delete the original edge (but not the associated verts). edgeToDelete = [edge] bmesh.ops.delete(originalBmesh, geom=edgeToDelete, context=4) # Local coordinate system. vectorU = vertB.co - vertA.co vectorV = mathutils.Vector((-vectorU.y, vectorU.x, 0)) if (outer): vectorV = -vectorV # Temp values thinnestOffset = 0.05 widthOffset = random.uniform(thinnestOffset, (1.0 - thinnestOffset) - relativeWidth) # Outer part. # C vert. vertC = originalBmesh.verts.new(vertA.co + widthOffset * vectorU) # F vert. vertF = originalBmesh.verts.new(vertA.co + (widthOffset + relativeWidth) * vectorU) # Inner part. # D vert. vertD = originalBmesh.verts.new(vertA.co + widthOffset * vectorU + relativeDepth * vectorV) # E vert. vertE = originalBmesh.verts.new(vertA.co + (widthOffset + relativeWidth) * vectorU + relativeDepth * vectorV) # Link vertices as edges. newEdges = [] newEdges.append(originalBmesh.edges.new((vertA, vertC))) newEdges.append(originalBmesh.edges.new((vertC, vertD))) newEdges.append(originalBmesh.edges.new((vertD, vertE))) newEdges.append(originalBmesh.edges.new((vertE, vertF))) newEdges.append(originalBmesh.edges.new((vertF, vertB))) return newEdges # ___________ -> _____ _____ # \_____/ def edgeToNotch45(originalBmesh, edge, relativeWidth, relativeDepth, outer): originalBmesh.edges.ensure_lookup_table() # Remember the original 2 vertices. vertA = edge.verts[0] vertB = edge.verts[1] # First delete the original edge (but not the associated verts). edgeToDelete = [edge] bmesh.ops.delete(originalBmesh, geom=edgeToDelete, context=4) originalBmesh.edges.ensure_lookup_table() # Local coordinate system. vectorU = vertB.co - vertA.co vectorV = mathutils.Vector((-vectorU.y, vectorU.x, 0)) if (outer): vectorV = -vectorV # Temp values thinnestOffset = 0.05 widthOffset = random.uniform(thinnestOffset, (1.0 - thinnestOffset) - relativeWidth) # Outer part. # C vert. vertC = originalBmesh.verts.new(vertA.co + widthOffset * vectorU) # F vert. vertF = originalBmesh.verts.new(vertA.co + (widthOffset + relativeWidth) * vectorU) # Inner part. # D vert. vertD = originalBmesh.verts.new(vertA.co + (widthOffset + relativeDepth) * vectorU + relativeDepth * vectorV) # E vert. vertE = originalBmesh.verts.new(vertA.co + (widthOffset + relativeWidth - relativeDepth) * vectorU + relativeDepth * vectorV) # Link vertices as edges. newEdges = [] newEdges.append(originalBmesh.edges.new((vertA, vertC))) newEdges.append(originalBmesh.edges.new((vertC, vertD))) newEdges.append(originalBmesh.edges.new((vertD, vertE))) newEdges.append(originalBmesh.edges.new((vertE, vertF))) newEdges.append(originalBmesh.edges.new((vertF, vertB))) return newEdges def genericEdgeTransformation(originalBmesh, edgeToTransform, recursionDepth): # Decide if there is going to be a recursion pass for this edge. if(random.uniform(0, 1) < poppingNewEdge): # Temp variables. currentWidth = random.uniform(relativeWidthMin, relativeWidthMax) currentDepth = random.uniform(0.01, currentWidth * relativeDepthWidthRatioMax) outer = random.uniform(0,1) < outerProbability # Decide what the next recursive function is. if(random.uniform(0, 1) < notchType45): returnedEdges = edgeToNotch45(originalBmesh, edgeToTransform, currentWidth, currentDepth, outer) else: returnedEdges = edgeToNotch90(originalBmesh, edgeToTransform, currentWidth, currentDepth, outer) # Recursion. if recursionDepth > 0: for currentEdge in returnedEdges: genericEdgeTransformation(originalBmesh, currentEdge, recursionDepth - 1) originalBmesh.edges.ensure_lookup_table() # Loops trough edges to add detail recursively. # The shape to change must be selected before entering the function. def genericShapeTransformation(recursionDepth): # Enter edit mode. bpy.ops.object.mode_set(mode = 'EDIT') # Delete the center face. bpy.ops.mesh.delete(type='ONLY_FACE') # Set the selection mode to edges. bpy.ops.mesh.select_mode(type="EDGE") # Get the active mesh obj = bpy.context.edit_object me = obj.data # Get a BMesh representation bm = bmesh.from_edit_mesh(me) bpy.ops.mesh.select_all(action='DESELECT') # Browse edges. bm.edges.ensure_lookup_table() print("Initial edges = " + str(len(bm.edges))) for currentEdge in range(0, len(bm.edges)): genericEdgeTransformation(bm, bm.edges[currentEdge], recursionDepth) print("Final edges = " + str(len(bm.edges))) bm.edges.ensure_lookup_table() # Select random vertices. # Set the selection mpde to edges. bpy.ops.mesh.select_mode(type="VERT") bpy.ops.mesh.select_all(action='DESELECT') bpy.ops.mesh.select_random() # Show the updates in the viewport # and recalculate n-gon tessellation. bmesh.update_edit_mesh(me, True) # Exit edit mode. bpy.ops.object.mode_set(mode = 'OBJECT') # Generates a circle shape of 6 edges with recursive details. def generateCircleCuttingShape(position, dimension, edgeCount, recursionDepth): # Generate a plane. bpy.ops.mesh.primitive_circle_add(radius=0.4, vertices=edgeCount, location=(position)) # Resize object in edit mode. bpy.ops.object.mode_set(mode = 'EDIT') bpy.ops.mesh.select_all(action='SELECT') bpy.ops.transform.resize(value=(dimension[0], dimension[1], 1.0), constraint_orientation='GLOBAL') bpy.ops.object.mode_set(mode = 'OBJECT') # Generic function to add details on edges. genericShapeTransformation(recursionDepth) # Generates a rectangular shape with recursive details. def generateRectangleCuttingShape(position, dimension, recursionDepth): # Generate a plane. bpy.ops.mesh.primitive_plane_add(radius=0.4, view_align=False, enter_editmode=False, location=(position)) # Resize object in edit mode. bpy.ops.object.mode_set(mode = 'EDIT') bpy.ops.mesh.select_all(action='SELECT') bpy.ops.transform.resize(value=(dimension[0], dimension[1], 1.0), constraint_orientation='GLOBAL') bpy.ops.object.mode_set(mode = 'OBJECT') # Generic function to add details on edges. genericShapeTransformation(recursionDepth) # Main print("starting main") # Intialize random seed if randomSeed >= 0 : random.seed(randomSeed) #generateSquareCuttingShape(position=(0, 0, 0), recursionDepth=recursivity) for xCoords in range(-squareRadius, squareRadius): for yCoords in range(-squareRadius, squareRadius): if random.uniform(0,1) < rectangleProbability : # Generate a rectangle of random dimension. downscaleValue = random.uniform(maximumRatioDifference, 1.0) # Apply downscale on either x or y. if random.uniform(0,1) < verticalProbability : generateRectangleCuttingShape(position=(xCoords, yCoords, 0), dimension=((downscaleValue, 1)), recursionDepth=recursivity) else: generateRectangleCuttingShape(position=(xCoords, yCoords, 0), dimension=((1, downscaleValue)), recursionDepth=recursivity) else: # Generate a circle of random vertices. verticesCount = random.uniform(minmumCircleEdges, maximumCircleEdges) generateCircleCuttingShape(position=(xCoords, yCoords, 0), dimension=((1.0, 1.0)), edgeCount=verticesCount, recursionDepth=recursivity)<file_sep>import bpy import bmesh import mathutils import random import time from datetime import datetime # Import submodules. import sys import os import importlib import copy blend_dir = os.path.dirname(bpy.data.filepath) if blend_dir not in sys.path: sys.path.append(blend_dir) # First inset. firstInsetDepth = -0.03 firstInsetThickness = 0.0 # Surface cutting. import cut_surface0_2_8 importlib.reload(cut_surface0_2_8) from cut_surface0_2_8 import * # Subdivisions. import subdivide_surface_2_8 importlib.reload(subdivide_surface_2_8) from subdivide_surface_2_8 import * # Recursive insets. import inset_surface_2_8 importlib.reload(inset_surface_2_8) from inset_surface_2_8 import * subdivisionProbability = 1.8 insetProbability = 0.1 # Parameters for other modules. subdivide_surface_2_8.minimumLength = 0.05 # Modify cutting settings. cut_surface0_2_8.bevelOffset = 0.001 cut_surface0_2_8.cuttingShapeMargin = 0.9 cut_surface0_2_8.cleanFaceMargin = 0.7 # Modify cutting shapes generation. generate_cuttingShape0_2_8.roundProbability = 0.0 # Recursive settings. recursiveDepth = 3 subdivisionOverCutProbability = 0.7 # Batches generation. batchSize = 5 seedOffsetForBatches = 6 def subdivideFaces(seed, objectToBrowse, facesTuples): # Initialize the random seed, this is important in order to generate exactly the same content for a given seed. random.seed(seed) totalFacesTuples = [] for currentFaceTuple in facesTuples: if random.uniform(0, 1) < subdivisionProbability: generatedFacesTuples = subdivideGeneric(seed, objectToBrowse, currentFaceTuple) if(generatedFacesTuples is not None): totalFacesTuples.extend(generatedFacesTuples) # Sort the arrays from in descending order according to the index, to avoid index offsetting side effects when modifying a face. totalFacesTuples = sorted(totalFacesTuples, key= lambda faceTuple: faceTuple[0], reverse = True) print("totalFacesTuples (after subdivision) = " + str([currentTuple[0] for currentTuple in totalFacesTuples])) resultFacesTuples = [] for currentFaceTuple in totalFacesTuples: if random.uniform(0, 1) < insetProbability: generatedFacesTuples = insetGeneric(seed, objectToBrowse, currentFaceTuple) resultFacesTuples.extend(generatedFacesTuples) else: resultFacesTuples.append(currentFaceTuple) # Sort the arrays from in descending order according to the index, to avoid index offsetting side effects when modifying a face. resultFacesTuples = sorted(resultFacesTuples, key= lambda faceTuple: faceTuple[0], reverse = True) print("resultFacesTuples (after inset) = " + str([currentTuple[0] for currentTuple in resultFacesTuples])) return resultFacesTuples def subdivideOrCut(seed, objectToBrowse, facesTuples): # Initialize the random seed, this is important in order to generate exactly the same content for a given seed. random.seed(seed) print("subdivideOrCut facesTuples = " + str([currentTuple[0] for currentTuple in facesTuples])) # Final result to return. finalFacesTuples = [] for currentFaceTuple in facesTuples: resultingFacesTuples = [] # Randomly pick a subdivision or cut operation. subdivisionOverCut = random.uniform(0, 1) < subdivisionOverCutProbability if subdivisionOverCut: resultingFacesTuples = subdivideFaces(random.randint(0, 100000), objectToBrowse, [currentFaceTuple]) else: resultingFacesTuples = [genericCutPlate(random.randint(0, 100000), objectToBrowse, currentFaceTuple)] # This might be necessary to refresh the object, check this. bpy.ops.object.mode_set(mode = 'OBJECT') # Add the resulting faces to the final total array. if resultingFacesTuples == None: finalFacesTuples.append(currentFaceTuple) else: finalFacesTuples.extend(resultingFacesTuples) # Filter out empty elements. finalFacesTuples = [currentTuple for currentTuple in finalFacesTuples if not (currentTuple == [] or currentTuple == None) ] print("finalFacesTuples before sort = " + str([currentTuple[0] for currentTuple in finalFacesTuples])) # Sort the arrays from in descending order according to the index, to avoid index offsetting side effects when modifying a face. finalFacesTuples = sorted(finalFacesTuples, key= lambda faceTuple: faceTuple[0], reverse = True) print("finalFacesTuples after sort = " + str([currentTuple[0] for currentTuple in finalFacesTuples])) return finalFacesTuples def recursiveGeneration(seed, objectToModify, facesToModify, recursiveDepth): # Initialize the random seed, this is important in order to generate exactly the same content for a given seed. random.seed(seed) # Subdivide or cut recursively. # Traverse the created faces in a descending order according to their index, to avoid issues with index offsetting when creating new faces. for currentFaceToModify in facesToModify: resultingFaceTuples = subdivideOrCut(random.randint(0, 100000), objectToModify, [currentFaceToModify]) # Faces should have been returned in a descending order for the index. if recursiveDepth > 0: recursiveGeneration(random.randint(0, 100000), objectToModify, resultingFaceTuples, recursiveDepth - 1) def generateBatch(squareSize): #datetime.now() # Initialize the random seed, this is important in order to generate exactly the same content for a given seed. #random.seed(1) random.seed(datetime.now()) facesCount = 0 for xCoords in range(0, squareSize): for yCoords in range(0, squareSize): bpy.ops.mesh.primitive_plane_add(size=0.95, align='WORLD', enter_editmode=False, location=(xCoords, yCoords, 0)) #bpy.ops.transform.rotate(value=1.1055, orient_axis='X', orient_type='GLOBAL', orient_matrix=((-0.527618, 0.849482, 6.25849e-07), (-0.432952, -0.268908, -0.860373), (0.730871, 0.453949, -0.509665)), orient_matrix_type='VIEW', mirror=True) bpy.ops.transform.rotate(value=random.uniform(0, 4), orient_axis='Z', orient_type='VIEW', orient_matrix=((0.993576, 0.113164, 4.95464e-07), (-0.0669248, 0.587603, -0.806377), (0.0912528, -0.801197, -0.591402)), orient_matrix_type='VIEW') #bpy.ops.transform.rotate(value=-1.5708, orient_axis='X', orient_type='GLOBAL', orient_matrix=((-0.527618, 0.849482, 6.25849e-07), (-0.432952, -0.268908, -0.860373), (0.730871, 0.453949, -0.509665)), orient_matrix_type='VIEW', mirror=True) position = (1,0,0) bpy.ops.transform.translate(value=(-position[0], -position[1], -position[2]), orient_type='GLOBAL', orient_matrix=((1, 0, 0), (0, 1, 0), (0, 0, 1)), orient_matrix_type='GLOBAL') bpy.ops.object.transform_apply() # TODO: remove this later, only for temporary edit mode normal direction test. # Keep track of the selected object. originalySelectedObject = bpy.context.active_object # Find the first and only polygon in it. firstPolygonTuple = buildFaceTuple(originalySelectedObject, originalySelectedObject.data.polygons[0].index) firstPolygon = originalySelectedObject.data.polygons[0] # Recursive generation. recursiveGeneration(seedOffsetForBatches + facesCount, originalySelectedObject, [firstPolygonTuple], recursiveDepth) facesCount = facesCount + 1 bpy.ops.object.mode_set(mode = 'OBJECT') # bpy.ops.object.mode_set(mode = 'EDIT') override, originalRegion3D = createOverrideContext() # Reset the view to it's original configuration. setRegion3D(override, originalRegion3D) def applyToSelectedFaces(): if not bpy.context.mode == 'EDIT_MESH': print("applyToMesh function should be performed in edit mode.") return # Keep a reference to the object to modify. objectToModify = bpy.context.edit_object # Preliminary operations, before any recursion. # Inset. bpy.ops.mesh.inset(thickness=firstInsetThickness, depth=firstInsetDepth) # Apply the details material to the faces inside the inset. assignMaterialSlotByName("hardsurface_details_material") # Populate an array of currently selected faces. # First the mandatory object mode to have up to date select values for faces. bpy.ops.object.mode_set(mode = 'OBJECT') # The faces should have 4 vertices exactly. # Sort the array from in descending order according to the index, to avoid index offsetting side effects when modifying a face. selectedFacesIndexes = [currentFace.index for currentFace in objectToModify.data.polygons if currentFace.select and len(currentFace.vertices) == 4] selectedFacesIndexes = sorted(selectedFacesIndexes, reverse = True) totalFaces = len(selectedFacesIndexes) counter = 0 for currentFaceIndex in selectedFacesIndexes: # Progression. counter = counter + 1 print(str(counter) + " of " + str(totalFaces) + " faces.") # Build tuple. firstPolygonTuple = buildFaceTuple(objectToModify, objectToModify.data.polygons[currentFaceIndex].index) # Recursive generation. recursiveGeneration(counter, objectToModify, [firstPolygonTuple], recursiveDepth) # Go back in edit mode. bpy.ops.object.mode_set(mode = 'EDIT') # Test function if __name__ == "__main__": print("////// Recusivity manager launch //////") # generateBatch(batchSize) applyToSelectedFaces()<file_sep># Procedural_hardsurface Blender scripts related to procedural details generation for "hard surface" geometry. The scripts are in a really primitive state for now, you will have to run them manually: - Open the scripting layout of Blender - In the text editor window: "Text"->"Open", then select the script corresponding to your Blender version - Finally, click "Run Script" -> new meshes will be added in the 3D view <file_sep>import bpy import bmesh import mathutils import random from datetime import datetime # Import submodules. import sys import os import importlib import copy blend_dir = os.path.dirname(bpy.data.filepath) if blend_dir not in sys.path: sys.path.append(blend_dir) # Utils. import utils_2_8 importlib.reload(utils_2_8) from utils_2_8 import * # Probabilities. randomSeed = 0 # Seed for randomization, different everytime when set to negative. poppingNewEdge = 1.0 # Probability for each edge to enter a recursive cycle if the recursivity limit has not been hit. notchType45 = 0.5 # Probability to pop a 45 degrees notch. outerProbability = 0.5 # Probability to have a notch coming outward rather than inward. relativeWidthMin = 0.1 # Minimum length of a notch relative to the edge it is created from. relativeWidthMax = 0.9 # Maximum length of a notch relative to the edge it is created from. relativeDepthWidthRatioMax = 0.3 # Maximum depth of a notch relative to it's length. thinnestOffset = 0.05 # The minimum distance between the beginning of a notch in the end of the initial edge. # Rounding probabilities. roundProbability = 0.0 # Probability of turning a 90 degrees angle into a curve. outerRoundProbability = 0.5 # Probability of the curve to face outward. roundSegments = 5 # Number of vertices composing the curve. # Rectangles probabilities. rectangleProbability = 0.5 # Probability to pop a rectangle rather than a sphere. maximumRatioDifference = 0.2 # Maximum ratio between height and width, smaller values make for a bigger ratio. Should belong to [0 ; 1]. verticalProbability = 0.5 # Probability of poping a vertical rectangle if maximumRatioDifference is different from 1. # Circle probabilities. minmumCircleEdges = 3 # Minimum possible edges in a circle. maximumCircleEdges = 6 # Maximum possible edges in a circle. # Global settings. recursivity = 0 # Recursivity limit. symetry = False # When True, all edges will have the same details generated, even recursively. # This function generates a square of 1 unit on the sides, facing up. # Then returns it. def generateUnitSquare(): verts = [ (-0.5, -0.5, 0), (0.5, -0.5, 0), (0.5, 0.5, 0), (-0.5, 0.5, 0)] mesh = bpy.data.meshes.new("UnitPlaneMesh") # add a new mesh obj = bpy.data.objects.new("UnitPlane", mesh) # add a new object using the mesh scene = bpy.context.scene #scene.objects.link(obj) # put the object into the scene (link) # scene.objects.active = obj # set as the active object in the scene # obj.select = True # select object # mesh = bpy.context.object.data bm = bmesh.new() for v in verts: bm.verts.new(v) # add a new vert # Refresh bmesh. bm.verts.ensure_lookup_table() bm.edges.ensure_lookup_table() bm.edges.new((bm.verts[0], bm.verts[1])) bm.edges.new((bm.verts[1], bm.verts[2])) bm.edges.new((bm.verts[2], bm.verts[3])) bm.edges.new((bm.verts[3], bm.verts[0])) # make the bmesh the object's mesh bm.to_mesh(mesh) bm.free() # always do this when finished return obj # ___________ -> _____ _____ # |_____| def edgeToNotch90(originalBmesh, edge, relativeWidth, widthOffset, relativeDepth, outer): # Remember the original 2 vertices. vertA = edge.verts[0] vertB = edge.verts[1] # First delete the original edge (but not the associated verts). edgeToDelete = [edge] bmesh.ops.delete(originalBmesh, geom=edgeToDelete, context='EDGES') # Local coordinate system. vectorU = vertB.co - vertA.co vectorV = mathutils.Vector((-vectorU.y, vectorU.x, 0)) if (outer): vectorV = -vectorV # Outer part. # C vert. vertC = originalBmesh.verts.new(vertA.co + widthOffset * vectorU) # F vert. vertF = originalBmesh.verts.new(vertA.co + (widthOffset + relativeWidth) * vectorU) # Inner part. # D vert. vertD = originalBmesh.verts.new(vertA.co + widthOffset * vectorU + relativeDepth * vectorV) # E vert. vertE = originalBmesh.verts.new(vertA.co + (widthOffset + relativeWidth) * vectorU + relativeDepth * vectorV) # Link vertices as edges. newEdges = [] newEdges.append(originalBmesh.edges.new((vertA, vertC))) newEdges.append(originalBmesh.edges.new((vertC, vertD))) newEdges.append(originalBmesh.edges.new((vertD, vertE))) newEdges.append(originalBmesh.edges.new((vertE, vertF))) newEdges.append(originalBmesh.edges.new((vertF, vertB))) return newEdges # ___________ -> _____ _____ # \_____/ def edgeToNotch45(originalBmesh, edge, relativeWidth, widthOffset, relativeDepth, outer): originalBmesh.edges.ensure_lookup_table() # Remember the original 2 vertices. vertA = edge.verts[0] vertB = edge.verts[1] # First delete the original edge (but not the associated verts). edgeToDelete = [edge] bmesh.ops.delete(originalBmesh, geom=edgeToDelete, context='EDGES') originalBmesh.edges.ensure_lookup_table() # Local coordinate system. vectorU = vertB.co - vertA.co vectorV = mathutils.Vector((-vectorU.y, vectorU.x, 0)) if (outer): vectorV = -vectorV # Outer part. # C vert. vertC = originalBmesh.verts.new(vertA.co + widthOffset * vectorU) # F vert. vertF = originalBmesh.verts.new(vertA.co + (widthOffset + relativeWidth) * vectorU) # Inner part. # D vert. vertD = originalBmesh.verts.new(vertA.co + (widthOffset + relativeDepth) * vectorU + relativeDepth * vectorV) # E vert. vertE = originalBmesh.verts.new(vertA.co + (widthOffset + relativeWidth - relativeDepth) * vectorU + relativeDepth * vectorV) # Link vertices as edges. newEdges = [] newEdges.append(originalBmesh.edges.new((vertA, vertC))) newEdges.append(originalBmesh.edges.new((vertC, vertD))) newEdges.append(originalBmesh.edges.new((vertD, vertE))) newEdges.append(originalBmesh.edges.new((vertE, vertF))) newEdges.append(originalBmesh.edges.new((vertF, vertB))) return newEdges def vertToRound(originalBmesh, vertList, outerRound): originalBmesh.edges.ensure_lookup_table() if outerRound: chosenProfile = 0.125 else: chosenProfile = 0.5 # Rounding operation. bmesh.ops.bevel(originalBmesh, geom=vertList, offset_type='OFFSET', offset=1.05, segments=roundSegments, profile=chosenProfile, vertex_only=True, clamp_overlap=True) originalBmesh.edges.ensure_lookup_table() def genericEdgeTransformation(seed, originalBmesh, edgeToTransform, recursionDepth): # Initialize the random seed, this is important in order to generate exactly the same content for a given seed. random.seed(seed) # Useful for the final depth computation. edgeToTransformLength = edgeLength(edgeToTransform) # Variables to return. currentDepth = None outer = None # Decide if there is going to be a recursion pass for this edge. if(random.uniform(0, 1) < poppingNewEdge): # Temp variables. currentWidth = random.uniform(relativeWidthMin, relativeWidthMax) widthOffset = random.uniform(thinnestOffset, (1.0 - thinnestOffset) - currentWidth) currentDepth = random.uniform(0.01, currentWidth * relativeDepthWidthRatioMax) outer = random.uniform(0,1) < outerProbability # Decide what the next recursive function is. if(random.uniform(0, 1) < notchType45): returnedEdges = edgeToNotch45(originalBmesh, edgeToTransform, currentWidth, widthOffset, currentDepth, outer) else: returnedEdges = edgeToNotch90(originalBmesh, edgeToTransform, currentWidth, widthOffset, currentDepth, outer) # Only for 90 degrees notches will we round some vertices up. # Count vertices that are encountered twice, therefore all the vertices that do not belong to the sides of this edge selection. vertDictionary = {} for currentEdge in returnedEdges: for currentVert in currentEdge.verts: if currentVert in vertDictionary: vertDictionary[currentVert] = vertDictionary[currentVert] + 1 else: vertDictionary[currentVert] = 1 # Select only the inner vertices. innerVertices = [currentVert for currentVert, currentCount in vertDictionary.items() if currentCount >= 2] # Of the inner vertices, select only some randomly. innerVerticesRandom = [currentVert for currentVert in innerVertices if random.uniform(0,1) < roundProbability] #Randomly choose if an the rounding will be an inner or outer one. outerRound = random.uniform(0,1) < outerRoundProbability # Apply the rounding to the randomly selected vertices. vertToRound(originalBmesh, innerVerticesRandom, outerRound) # Recursion. if recursionDepth > 0: for currentEdge in returnedEdges: if symetry: # When symetry is enabled, take the same seed for every edge. futureSeed = seed else: # When symetry is disabled, randomize the seed for every edge. futureSeed = random.randint(0, 1000000) genericEdgeTransformation(futureSeed, originalBmesh, currentEdge, recursionDepth - 1) originalBmesh.edges.ensure_lookup_table() # The actual depth length is the proportional depth * the edge length. currentDepth = currentDepth * edgeToTransformLength if outer: return currentDepth else: return -currentDepth # Loops trough edges to add detail recursively. # The shape to change must be selected before entering the function. def genericShapeTransformation(seed, recursionDepth): # Initialize the random seed, this is important in order to generate exactly the same content for a given seed. random.seed(seed) # Enter edit mode. bpy.ops.object.mode_set(mode = 'EDIT') # Delete the center face. bpy.ops.mesh.delete(type='ONLY_FACE') # Set the selection mode to edges. bpy.ops.mesh.select_mode(type="EDGE") # Get the active mesh obj = bpy.context.edit_object me = obj.data # Get a BMesh representation bm = bmesh.from_edit_mesh(me) bpy.ops.mesh.select_all(action='DESELECT') # Browse edges. bm.edges.ensure_lookup_table() # print("Initial edges = " + str(len(bm.edges))) # Keep track of the maximum depth (negative or positive) encountered on each edge. edgesDepth = [] for currentEdge in range(0, len(bm.edges)): if symetry: # When symetry is enabled, take the same seed for every edge. futureSeed = seed else: # When symetry is disabled, randomize the seed for every edge. futureSeed = random.randint(0, 1000000) currentEdgeDepth = genericEdgeTransformation(futureSeed, bm, bm.edges[currentEdge], recursionDepth) edgesDepth.append(currentEdgeDepth) # Some of the previous operations can cause some vertices to be at the same position, remove duplicates. bmesh.ops.remove_doubles(bm, verts=bm.verts, dist=0.000001) # print("Final edges = " + str(len(bm.edges))) bm.edges.ensure_lookup_table() # Show the updates in the viewport # and recalculate n-gon tessellation. bmesh.update_edit_mesh(me, True) # Exit edit mode. bpy.ops.object.mode_set(mode = 'OBJECT') return edgesDepth # Generates a circle shape of 6 edges with recursive details. def generateCircleCuttingShape(seed, position, dimension, edgeCount, recursionDepth): # Generate a plane. bpy.ops.mesh.primitive_circle_add(radius=0.4, vertices=edgeCount, location=(position)) # Keep track of the created object. createdShape = bpy.context.active_object createdShape.name = "circle_cuttingShape" createdShape.data.name = "circle_cuttingShape_mesh" # Resize object in edit mode. bpy.ops.object.mode_set(mode = 'EDIT') bpy.ops.mesh.select_all(action='SELECT') bpy.ops.transform.resize(value=(dimension[0], dimension[1], 1.0), orient_type='GLOBAL') bpy.ops.object.mode_set(mode = 'OBJECT') # Generic function to add details on edges. genericShapeTransformation(seed, recursionDepth) # Generates a rectangular shape with recursive details. def generateRectangleCuttingShape(seed, position, dimension, recursionDepth): # Generate a plane. bpy.ops.mesh.primitive_plane_add(size=1.0, align='WORLD', enter_editmode=False, location=(position)) # Keep track of the created object. createdShape = bpy.context.active_object createdShape.name = "rectangle_cuttingShape" createdShape.data.name = "rectangle_cuttingShape_mesh" # Resize object in edit mode. bpy.ops.object.mode_set(mode = 'EDIT') bpy.ops.mesh.select_all(action='SELECT') bpy.ops.transform.resize(value=(dimension[0], dimension[1], 1.0), orient_type='GLOBAL') bpy.ops.object.mode_set(mode = 'OBJECT') # Generic function to add details on edges. edgesDepth = genericShapeTransformation(seed, recursionDepth) return createdShape, edgesDepth def generateGenericCuttingShape(seed, position): # Initialize the random seed, this is important in order to generate exactly the same content for a given seed. random.seed(seed) if random.uniform(0,1) < rectangleProbability : # Generate a rectangle of random dimension. downscaleValue = random.uniform(maximumRatioDifference, 1.0) # Apply downscale on either x or y. if random.uniform(0,1) < verticalProbability : createdShape = generateRectangleCuttingShape(seed=seed, position=position, dimension=((downscaleValue, 1)), recursionDepth=recursivity) else: createdShape = generateRectangleCuttingShape(seed=seed, position=position, dimension=((1, downscaleValue)), recursionDepth=recursivity) else: # Generate a circle of random vertices. verticesCount = random.uniform(minmumCircleEdges, maximumCircleEdges) createdShape = generateCircleCuttingShape(seed=seed, position=position, dimension=((1.0, 1.0)), edgeCount=verticesCount, recursionDepth=recursivity) return createdShape # Populate a square with random cutting shapes. # squareRadius, Drives the number of shapes generated. # generateNewCollection, When true, generate a new collection for each batch, when false, replaces the old collection content. def generateCuttingShapesArray(squareRadius = 5, generateNewCollection = False): print("generating a collection of hard surface shapes") if not generateNewCollection: # Delete the old collection singletonCollectionIndex = bpy.context.scene.collection.children.find("hardsurface_shapes") if singletonCollectionIndex >= 0: singletonCollection = bpy.context.scene.collection.children[singletonCollectionIndex] # Remove meshes data to avoid orphans. for currentObject in singletonCollection.objects: bpy.data.meshes.remove(currentObject.data) # Remove the collection from the scene. bpy.context.scene.collection.children.unlink(singletonCollection) bpy.data.collections.remove(singletonCollection) # Create a new collection. testCollection = bpy.data.collections.new("hardsurface_shapes") # Link it to the current scene. bpy.context.scene.collection.children.link(testCollection) # Make the added collection active. bpy.context.view_layer.active_layer_collection = bpy.context.view_layer.layer_collection.children[testCollection.name] # Make all collections invisible excepting for the new one. for currentChild in bpy.context.scene.collection.children: currentChild.hide_viewport = True testCollection.hide_viewport = False # Intialize seed. if randomSeed >= 0 : random.seed(randomSeed) else: # Take the current time to randomize the seed when we want it different each time. random.seed(datetime.now()) #generateGenericShape(seed=randomSeed, position=(0, 0, 0)) for xCoords in range(-squareRadius, squareRadius): for yCoords in range(-squareRadius, squareRadius): generateGenericCuttingShape(seed=xCoords + yCoords * squareRadius * 2, position=(xCoords, yCoords, 0)) # Test function if __name__ == "__main__": generateCuttingShapesArray()<file_sep>import bpy import bmesh import mathutils import random from datetime import datetime from mathutils import Euler # Import submodules. import sys import os import importlib import copy blend_dir = os.path.dirname(bpy.data.filepath) if blend_dir not in sys.path: sys.path.append(blend_dir) # Cutting shapes generation. import generate_cuttingShape0_2_8 importlib.reload(generate_cuttingShape0_2_8) from generate_cuttingShape0_2_8 import * # Utils. import utils_2_8 importlib.reload(utils_2_8) from utils_2_8 import * cuttingShapeMargin = 0.9 cleanFaceMargin = 0.9 bevelOffset = 0.01 def knifeProject(surfaceToCut, surfaceCuter, position, tbnMatrix): bpy.ops.object.mode_set(mode = 'OBJECT') # Check arguments. if surfaceToCut == None or surfaceCuter == None: print("knife project tentative with wrong arguments:") print("surfaceToCut = " + str(surfaceToCut)) print("surfaceCuter = " + str(surfaceCuter)) return # The TBN is converted to euler angles to circle around Blender's poor matrix update system. eulerFromTbn = tbnMatrix.to_euler() # Select only the surfaceCuter. bpy.ops.object.select_all(action='DESELECT') surfaceCuter.select_set(True) # Rotate it. bpy.ops.transform.rotate(value=eulerFromTbn.z, orient_axis='Z') bpy.ops.transform.rotate(value=eulerFromTbn.y, orient_axis='Y') bpy.ops.transform.rotate(value=eulerFromTbn.x, orient_axis='X') # And translate it. bpy.ops.transform.translate(value=(position[0], position[1], position[2]), orient_type='GLOBAL', orient_matrix=((1, 0, 0), (0, 1, 0), (0, 0, 1)), orient_matrix_type='GLOBAL') print("position = " + str(position)) # Arrange selection for knife cutting operation. bpy.context.view_layer.objects.active = surfaceToCut surfaceCuter.select_set(True) direction = tbnMatrix[2] # Create override context for the cuts. override, originalRegion3D = createFaceOverrideContext(position, direction) # Force redraw the scene - this is considered unsavory but is necessary here. bpy.ops.wm.redraw_timer(type='DRAW_WIN_SWAP', iterations=1) # The knife project has to be used in edit mode. bpy.ops.object.mode_set(mode = 'EDIT') # Knife cutting operation. bpy.ops.mesh.knife_project(override) # Go back to object mode. This forces an update of the mesh's internal data. bpy.ops.object.mode_set(mode = 'OBJECT') # Reset the view to it's configuration before the knife project. setRegion3D(override, originalRegion3D) # Keep the selected face resulting from the knife project. resultingPolygon = None for currentPolygon in surfaceToCut.data.polygons: if currentPolygon.select: resultingPolygon = currentPolygon return resultingPolygon # Adds a crease in a surface, to simulate metal plates joining. # For this function the edge to crease (resulting from the cut) must be selected. def addCutCrease(surfaceToCrease): bpy.context.view_layer.objects.active = surfaceToCrease bpy.ops.object.mode_set(mode = 'EDIT') # Set the edges of the crease as sharp. bpy.ops.mesh.mark_sharp() # Create a bevel, the cutting shape of only one segment becomes 3 segments after this. bpy.ops.mesh.bevel(offset_type='OFFSET', offset=bevelOffset, offset_pct=0, segments=2, profile=0.5, vertex_only=False, clamp_overlap=True, loop_slide=True, mark_seam=False, mark_sharp=True) # Select less to only keep the middle segment selected. bpy.ops.mesh.select_less() # Set the bottom of the crease as sharp. bpy.ops.mesh.mark_sharp() # Lower the middle segment to create the crease. bpy.ops.transform.shrink_fatten(value=bevelOffset) # Go back to object mode. bpy.ops.object.mode_set(mode = 'OBJECT') # Computes the borders of a given face in world space. This includes the size of the parent object. # The face should be a rectangular quad. # Warning: This algorithm assumes that the face is axis aligned. def rectangleBorders(parentObject, face, tbnMatrix): minX = sys.float_info.max maxX = -sys.float_info.max minY = sys.float_info.max maxY = -sys.float_info.max for currentVertexIndex in face.vertices: currentVertex = face.id_data.vertices[currentVertexIndex] currentWorldCoords = parentObject.matrix_world @ currentVertex.co currentTangentCoords = tbnMatrix @ currentWorldCoords if currentTangentCoords.x < minX: minX = currentTangentCoords.x if currentTangentCoords.x > maxX: maxX = currentTangentCoords.x if currentTangentCoords.y < minY: minY = currentTangentCoords.y if currentTangentCoords.y > maxY: maxY = currentTangentCoords.y return (minX, maxX, minY, maxY) # Basicaly computes the mean position of the rectangles 4 vertices to return it's center. def rectangleCenter(parentObject, face): meanPosition = mathutils.Vector((0,0,0)) for currentVertexIndex in face.vertices: # Find the vertex. currentVertex = face.id_data.vertices[currentVertexIndex] # Compute it's world coordinates. currentWorldCoords = parentObject.matrix_world @ currentVertex.co # Add it to the mean position. meanPosition = meanPosition + currentWorldCoords return meanPosition / len(face.vertices) # Cuts a random shape in a surface, then gives it a crease to make it look like a plate. def cutPlate(seed, objectToCut, cuttingShape, position, tbnMatrix): # Initialize the random seed, this is important in order to generate exactly the same content for a given seed. random.seed(seed) # Use the cutting shape to cut the currently selected surface. resultingFace = knifeProject(objectToCut, cuttingShape, position, tbnMatrix) # Delete the no longer needed cutting shape. dataToRemove = cuttingShape.data bpy.data.objects.remove(cuttingShape) bpy.data.meshes.remove(dataToRemove) # Crease the cut surface. addCutCrease(objectToCut) return resultingFace # The responsibility of this function is to generate the cutting shape and place it correctly for the cutPlate function. # It should then cut the inner rectangle to enable recursivity. def genericCutPlate(seed, objectToCut, faceTuple): print() print("new cut") if objectToCut == None: print("Tried to cut a None object") return if faceTuple == None: print("Tried to cut a None tuple") return # Find the face in the object. faceToCut = objectToCut.data.polygons[faceTuple[0]] if faceToCut == None: print("Tried to cut a None face") return # Compute normal and tangent of the current face to cut. normalForCuts = faceToCut.normal.copy() tangentForCuts = faceTangent(objectToCut, faceToCut.index).copy() # Compute the biTangent thanks to the normal and tangent. biTangentForCuts = normalForCuts.cross(tangentForCuts) # Assemble a TBN matrix from the normal, tangent and bitangent of the face. tbnMatrix = mathutils.Matrix([ [tangentForCuts.x, tangentForCuts.y, tangentForCuts.z ], [biTangentForCuts.x, biTangentForCuts.y, biTangentForCuts.z ], [normalForCuts.x, normalForCuts.y, normalForCuts.z ] ]) # Initialize the random seed, this is important in order to generate exactly the same content for a given seed. random.seed(seed) # Compute the dimension of the face to cut. rectBorders = rectangleBorders(objectToCut, faceToCut, tbnMatrix) # Compute the center of the face to cut. faceCenter = rectangleCenter(objectToCut, faceToCut) print("faceCenter = " + str(faceCenter)) rectDimension = (rectBorders[0], rectBorders[1], rectBorders[2], rectBorders[3]) faceWidth = rectDimension[1] - rectDimension[0] faceHeight = rectDimension[3] - rectDimension[2] # Generate a cutting shape cuttingShapeDimension = (faceWidth * 0.5, faceHeight * 0.5) cuttingShape, edgesDepth = generateRectangleCuttingShape(seed=random.randint(0, 100000), position=(0,0,0), dimension=cuttingShapeDimension, recursionDepth=0) cuttingShapeOuterBounds = [-cuttingShapeDimension[0]/2 - max(0, edgesDepth[0]), # left -cuttingShapeDimension[1]/2 - max(0, edgesDepth[1]), # bottom cuttingShapeDimension[0]/2 + max(0, edgesDepth[2]), # right cuttingShapeDimension[1]/2 + max(0, edgesDepth[3])] # up cuttingShapeOuterBoundsDimension = (cuttingShapeOuterBounds[2] - cuttingShapeOuterBounds[0], # width cuttingShapeOuterBounds[3] - cuttingShapeOuterBounds[1]) # height cuttingShapeOuterBoundsOffset = (( cuttingShapeOuterBounds[2] + cuttingShapeOuterBounds[0]) * 0.5, # width ( cuttingShapeOuterBounds[3] + cuttingShapeOuterBounds[1]) * 0.5) # height # Translation. cuttingShapeTranslation = (-cuttingShapeOuterBoundsOffset[0], -cuttingShapeOuterBoundsOffset[1], 0) bpy.ops.transform.translate(value=cuttingShapeTranslation, orient_type='GLOBAL', orient_matrix=((1, 0, 0), (0, 1, 0), (0, 0, 1)), orient_matrix_type='GLOBAL') # The cutting shape should be re-scaled and translated to fit the face to cut. # Scale it uniformly however. cuttingShapeScaleFactor = cuttingShapeMargin * min(faceWidth / cuttingShapeOuterBoundsDimension[0], faceHeight / cuttingShapeOuterBoundsDimension[1]) # Correct center for the resize. bpy.context.scene.tool_settings.transform_pivot_point = 'MEDIAN_POINT' # Resize operation. bpy.ops.transform.resize(value=(cuttingShapeScaleFactor, cuttingShapeScaleFactor, 1), orient_type='GLOBAL', orient_matrix=((1, 0, 0), (0, 1, 0), (0, 0, 1)), orient_matrix_type='GLOBAL') # After this rescale, the inner bounds can be calculated # Compute the inner bounds of the cutting shape. cuttingShapeInnerBounds = [(-cuttingShapeDimension[0]/2 - min(0, edgesDepth[0])) * cuttingShapeScaleFactor + cuttingShapeTranslation[0], # left (-cuttingShapeDimension[1]/2 - min(0, edgesDepth[1])) * cuttingShapeScaleFactor + cuttingShapeTranslation[1] , # bottom ( cuttingShapeDimension[0]/2 + min(0, edgesDepth[2])) * cuttingShapeScaleFactor + cuttingShapeTranslation[0], # right ( cuttingShapeDimension[1]/2 + min(0, edgesDepth[3])) * cuttingShapeScaleFactor + cuttingShapeTranslation[1]] # up cuttingShapeInnerBoundsDimension = (cuttingShapeInnerBounds[2] - cuttingShapeInnerBounds[0], # width cuttingShapeInnerBounds[3] - cuttingShapeInnerBounds[1]) # height cuttingShapeInnerBoundsOffset = ( (cuttingShapeInnerBounds[2] + cuttingShapeInnerBounds[0]) * 0.5, # width (cuttingShapeInnerBounds[3] + cuttingShapeInnerBounds[1]) * 0.5) # height # Cut the plate with the tech-ish shape. resultingFace = cutPlate(seed, objectToCut, cuttingShape, faceCenter, tbnMatrix) ## Cut the surface again to have a clean surface to work with for recursivity. # Generate a plane cutting shape. bpy.ops.mesh.primitive_plane_add(size=1, align='WORLD', enter_editmode=True, location=((0,0,0))) # Re-scale to fit the plane in the inner bounds. cleanFaceScale = (cuttingShapeInnerBoundsDimension[0] * cleanFaceMargin, cuttingShapeInnerBoundsDimension[1] * cleanFaceMargin, 1) bpy.ops.transform.resize(value=cleanFaceScale, orient_type='GLOBAL', orient_matrix=((1, 0, 0), (0, 1, 0), (0, 0, 1)), orient_matrix_type='GLOBAL') # Translate to fit the plane in the inner bounds. cleanFaceTranslation = (cuttingShapeInnerBoundsOffset[0], cuttingShapeInnerBoundsOffset[1], 0) bpy.ops.transform.translate(value=cleanFaceTranslation, orient_type='GLOBAL', orient_matrix=((1, 0, 0), (0, 1, 0), (0, 0, 1)), orient_matrix_type='GLOBAL') # Go back to object mode. bpy.ops.object.mode_set(mode = 'OBJECT') # The cutting plane is the active object. cuttingShape = bpy.context.active_object # Use the cutting shape to cut the currently selected surface. resultingFace = knifeProject(objectToCut, cuttingShape, faceCenter, tbnMatrix) # Delete the no longer needed cutting shape. dataToRemove = cuttingShape.data bpy.data.objects.remove(cuttingShape) bpy.data.meshes.remove(dataToRemove) if not resultingFace == None: resultingFaceTuple = buildFaceTuple(objectToCut, resultingFace.index) return resultingFaceTuple # Test function if __name__ == "__main__": # Delete everything in the scene. bpy.ops.object.mode_set(mode = 'OBJECT') bpy.ops.object.select_all(action='SELECT') bpy.ops.object.delete(use_global=False, confirm=False) # Create a new plane. bpy.ops.mesh.primitive_plane_add(align='WORLD', enter_editmode=True, location=(0, 0, 0)) # bpy.ops.transform.resize(value=(1, 2.0, 1), orient_type='GLOBAL', orient_matrix=((1, 0, 0), (0, 1, 0), (0, 0, 1)), orient_matrix_type='GLOBAL', constraint_axis=(False, False, False), mirror=True, proportional='DISABLED', proportional_edit_falloff='SMOOTH', proportional_size=1) bpy.ops.object.mode_set(mode = 'OBJECT') # Keep track of the selected object. originalySelectedObject = bpy.context.active_object # Cut a plate in the selected object. resultingFaceTuple = genericCutPlate(datetime.now(), originalySelectedObject, buildFaceTuple(originalySelectedObject, originalySelectedObject.data.polygons[0].index)) resultingFaceTuple = genericCutPlate(datetime.now(), originalySelectedObject, resultingFaceTuple) resultingFaceTuple = genericCutPlate(datetime.now(), originalySelectedObject, resultingFaceTuple) resultingFaceTuple = genericCutPlate(datetime.now(), originalySelectedObject, resultingFaceTuple) # resultingFaceTuple = genericCutPlate(0, originalySelectedObject, resultingFaceTuple) # resultingFaceTuple = genericCutPlate(0, originalySelectedObject, resultingFaceTuple) bpy.ops.object.mode_set(mode = 'EDIT') #datetime.now()
9b3ddc1128b1ceec71d7e6289b099f46af637136
[ "Markdown", "Python" ]
8
Python
JacquesDiringer/Procedural_hardsurface
d7899a46fda92d592c70d25fcbeefd252a92a7cd
01acc4f4c9c1e4c970b3a51e840edd12c5c823bb
refs/heads/master
<repo_name>stephenjust/arduino-gps-glasses<file_sep>/server/readgraph.py """ python3 readgraph.py [ digraph-file ] Takes a csv (comma separated values) text file containing the vertices and edges of a street digraph and converts it into a digraph instance. If the optional argument digraph-file is supplied, reads that, otherwise takes input from stdin """ # For testing, just use a simple representation of set of vertices, set of # edges as ordered pairs, and dctionaries that map # vertex to (lat,long) # edge to street name def readgraph(filename): digraph_file = open(filename, 'r') V = set() E = set() V_coord = {} E_name = {} # process each line in the file for line in digraph_file: # strip all trailing whitespace line = line.rstrip() fields = line.split(",") type = fields[0] if type == 'V': # got a vertex record (i,lat,lng) = fields[1:] # vertex id's should be ints i=int(i) # lat and long are floats lat=float(lat) lng=float(lng) V.add(i) V_coord[i] = (lat,lng) elif type == 'E': # got an edge record (start,stop,name) = fields[1:] # vertices are ints start=int(start) stop=int(stop) e = (start,stop) # get rid of leading and trailing quote " chars around name name = name.strip('"') # consistency check, we don't want auto adding of vertices when # adding an edge. if start not in V or stop not in V: raise Exception("Edge {} has an endpoint that is not a vertex".format(e) ) E.add(e) E_name[e] = name else: # weird input raise Exception("Error: weird line |{}|".format(line)) return (V, E, V_coord, E_name) <file_sep>/glasses-test/wiringtest.c #include <Arduino.h> void setup() { int a0 = 22; int a1 = 23; int a2 = 24; //Used to enable certain leds int v[] = {0, 0, 0}; pinMode(a0, OUTPUT); pinMode(a1, OUTPUT); pinMode(a2, OUTPUT); while (1) { for (int i = 0; i <8; i++){ //Make i a bitfield if (i & 0x1) { v[0] = 1;} else {v[0] = 0;} if (i & 0x2) { v[1] = 1;} else {v[1] = 0;} if (i & 0x4) { v[2] = 1;} else {v[2] = 0;} if (v[0]) digitalWrite(a0, HIGH); if (v[1]) digitalWrite(a1, HIGH); if (v[2]) digitalWrite(a2, HIGH); delay(2000); digitalWrite(a0, LOW); digitalWrite(a1, LOW); digitalWrite(a2, LOW); } } } void loop() { } <file_sep>/server/readme.txt Python Path-Finding Server by <NAME> ========================== To execute the server, run the following: python server.py -s <serial-port> [-v] [-g <graph-file>] There must be a file named edmonton_roads.txt in the script directory. This server takes its input from a serial port in the format: a b c d where a, b, c, and d are integers representing 100,000ths of a degree. The starting coordinate is (a, b), and the destination is (c, d). Vertices are in the format (latitude, longitude). The server returns a path in the following format: n x1 y1 x2 y2 ... xn yn where n is the number of vertices in the path, and x and y are the coordinates of each vertex (lat, long). <file_sep>/server/map.py class Map: """ >>> m = Map("test.map") >>> p = m.get_path( (0.0, 0.0), (0.0, 0.0) ) >>> p == [(0.0, 0.0)] True """ def __init__(self, file): pass def get_path(self, start_coord, stop_coord): return [] if __name__ == "__main__": import doctest doctest.testmod() <file_sep>/client/GTPA010.cpp #include "GTPA010.h" #include "Sensors.h" #include "TinyGPS.h" #include "TimerThree.h" bool GTPA010::newData = 0; /* Static variable declarations */ char GTPA010::dataBuffer; gpsData GTPA010::data; // Inturupt values volatile bool GTPA010::gpsValue = -1; volatile bool GTPA010::gpsLock = 0; gpsData* GTPA010::getData() { return &data; // Returns the data pointer } bool GTPA010::check() { return newData; // Returns the status of newData } void GTPA010::begin() { // Start GPS - Defines in classes/Config.h Serial2.begin(GPS_BAUD_RATE); pinMode(GPS_FIX_PIN,INPUT); pinMode(GPS_ENABLE_PIN,OUTPUT); // Setup GPS Interrupt check - Defines in classes/Config.h Timer3.initialize(timer_ticks); digitalWrite(GPS_ENABLE_PIN,HIGH); Timer3.attachInterrupt(&gpsCheck); } void GTPA010::gpsCheck() { bool oldGpsValue = gpsValue; // check the old value for the 2D/3D lock pin gpsValue = digitalRead(GPS_FIX_PIN); // refresh value with a digitalRead if(!(oldGpsValue ^ gpsValue)) // Does the {new,old} value both 0? gpsLock = 1; // Indicate a lock is present else gpsLock = 0; // Clear the lock variable sensorSecond = !sensorSecond; // Toggle the static sensor class variable for use of other sensors } void GTPA010::readData() { #if FAKE_GPS_DATA GTPA010::fakeData(); return; #endif if(gpsLock) // If we have a lock { while (Serial2.available()) // And while the Serial. is available { dataBuffer = Serial2.read(); // Read the available data if (gps.encode(dataBuffer)) // Did a new valid sentence come in? newData = true; // Notify the class that there is new data to show! } gps.get_position(&data.lat, &data.lon, &data.age); // Parse the position data gps.crack_datetime(&data.year, &data.month, &data.day, &data.hour, &data.minute, &data.second, &data.hundredths, &data.age); // Parse the time data if(data.lat == TinyGPS::GPS_INVALID_ANGLE || data.lon == TinyGPS::GPS_INVALID_ANGLE || gps.satellites() == TinyGPS::GPS_INVALID_SATELLITES || gps.hdop() == TinyGPS::GPS_INVALID_HDOP) // If any component of this data is invalid, then cancel the new data decleration, and if enabled, print that the data is invalid across the serial { newData = false; #if SERIAL_PRINT_ENABLE Serial.println("GPS DATA INVALID"); #endif } } else { #ifdef DEBUG_GPS Serial.println("No lock!"); #endif } } #if FAKE_GPS_DATA #import "gps_fake_data.h" int tstart_time = 0; /** * Provide some fake data in case we are demoing in a location * where it is not possible to get a GPS fix */ void GTPA010::fakeData() { // Set the start time of the path if (!tstart_time) { tstart_time = Sensors::getTime(); } // Calculate how far into the path we are int index = (Sensors::getTime() - tstart_time) % fd_len; // Set the fake data data.lat = fd_lat[index]; data.lon = fd_lon[index]; newData = true; } #endif void GTPA010::printData() { // Print the data via serial Serial.print("LAT="); Serial.print(data.lat == TinyGPS::GPS_INVALID_ANGLE ? NAN : data.lat); Serial.print(" LON="); Serial.print(data.lon == TinyGPS::GPS_INVALID_ANGLE ? NAN : data.lon); Serial.print(" SAT="); Serial.print(gps.satellites() == TinyGPS::GPS_INVALID_SATELLITES ? NAN : gps.satellites()); Serial.print(" PREC="); Serial.print(gps.hdop() == TinyGPS::GPS_INVALID_HDOP ? NAN : gps.hdop()); Serial.print(" DATE="); if (data.age == TinyGPS::GPS_INVALID_AGE) Serial.println("******* ******* "); else { char sz[32]; sprintf(sz, "%02d,%02d,%02d,%02d:%02d:%02d", data.month, data.day, data.year, data.hour, data.minute, data.second); Serial.println(sz); } } <file_sep>/client/Sensors.h #ifndef _SENSORS_H_ #define _SENSORS_H_ #include <Arduino.h> #include <Wire.h> class Sensors { public: Sensors(); static void writeTo(int destination, byte address, byte val); // Provides the functionality to write to a I2C device given its address (destiniation), the destination register (address), and the value we are writing (val) static void readFrom(int destination, byte address, int num, byte _buff[]); // Provides the functionality to read from a I2C device given its address (destination), the buffer we are loading said information into (_buff) from a specified register (address), a number of bytes (num) static int getTime(); // Returns the time since sensor ini in seconds static unsigned long int getLongTime(); // Returns the time since sensor ini in miliseconds static volatile bool sensorSecond; // Provides a method for reading/writing values every second private: static unsigned long int time; // Stores the time as used in above functions }; #endif <file_sep>/client/serial_handling.h #ifndef SERIAL_HANDLING_H #define SERIAL_HANDLING_H #include <stdint.h> /* Function to read a single line from the serial buffer up to a specified length (length includes the null termination character that must be appended onto the string). This function is blocking. The newline character sequence is given by CRLF, or "\r\n". Arguments: buffer: Pointer to a buffer of characters where the string will be stored. length: The maximum length of the string to be read. Preconditions: None. Postconditions: Function will block until a full newline has been read, or the maximum length has been reached. Afterwards the new string will be stored in the buffer passed to the function. Returns: the number of bytes read */ uint16_t serial_readline(char *line, uint16_t line_size); /* Function to read a portion of a string into a buffer, up to any given separation characters. This will read up to the specified length of the character buffer if a separation character is not encountered, or until the end of the string which is being copied. A starting index of the string being copied can also be specified. Arguments: str: The string which is having a portion copied. str_start: The index of the string to start at. (Less than str's length). buf: The buffer to store the copied chunk of the string into. buf_len: The length of the buffer. sep: String containing characters that will be used as separators. Preconditions: Make sure str_start does *NOT* exceed the size of str. Postconditions: Stores the resulting string in buf, and returns the position where reading was left off at. The position returned will skip separation characters. */ uint16_t string_read_field(const char *str, uint16_t str_start, char *field, uint16_t field_size, const char *sep); /* Function to convert a string to an int32_t. Arguments: str: The string to convert to an integer. Preconditions: The string should probably represent an integer value. Postconditions: Will return the equivalent integer. If an error occured the blink assert may be triggered, and sometimes zero is just returned from this function because EINVAL does not exist for the Arduino strtol. */ int32_t string_get_int(const char *str); #endif <file_sep>/client/joystick.cpp #include <Arduino.h> #include "joystick.h" // Arduino analog input pin for the horizontal on the joystick. const uint8_t joy_pin_x = 0; // Arduino analog input pin for the vertical on the joystick. const uint8_t joy_pin_y = 1; // Digital pin for the joystick button on the Arduino. const uint8_t joy_pin_button = 4; // Center point of the joystick - analog reads from the Arduino. int16_t joy_center_x = 512; int16_t joy_center_y = 512; // button state: 0 not pressed, 1 pressed uint8_t prev_button_state = 0; // time of last sampling of button state uint32_t button_prev_time = 0; // only after this much time has passed is the state sampled. uint32_t button_sample_delay = 200; void initialize_joystick() { // Initialize the button pin, turn on pullup resistor pinMode(joy_pin_button, INPUT); digitalWrite(joy_pin_button, HIGH); // Center Joystick joy_center_x = analogRead(joy_pin_x); joy_center_y = analogRead(joy_pin_y); } /* Read the joystick position, and return the x, y displacement from the zero position. The joystick has to be at least 4 units away from zero before a non-zero displacement is returned. This filters out the centering errors that occur when the joystick is released. Also, return 1 if the joystick button has been pushed, held for a minimum amount of time, and then released. That is, a 1 is returned if a button select action has occurred. */ uint8_t process_joystick(int16_t *dx, int16_t *dy) { int16_t joy_x; int16_t joy_y; uint8_t button_state; joy_x = -(analogRead(joy_pin_y) - joy_center_x); joy_y = -(analogRead(joy_pin_x) - joy_center_y); if (abs(joy_x) <= 4) { joy_x = 0; } if (abs(joy_y) <= 4) { joy_y = 0; } *dx = joy_x / 128; *dy = joy_y / 128; // first, don't even sample unless enough time has passed uint8_t have_sample = 0; uint32_t cur_time = millis(); if ( cur_time < button_prev_time ) { // time inversion caused by wraparound, so reset button_prev_time = cur_time; } if ( button_prev_time == 0 || button_prev_time + button_sample_delay < cur_time ) { // button pushed after suitable delay, so ok to return state button_prev_time = cur_time; have_sample = 1; button_state = LOW == digitalRead(joy_pin_button); } // if no sample, return no press result if ( ! have_sample ) { return 0; } // if prev and current state are same, no transition occurs if ( prev_button_state == button_state ) { return 0; } // are we waiting for push or release? if ( prev_button_state ) { // we got a release, return the press event prev_button_state = button_state; return 1; } // we got a press, so change state to waiting for release, but // don't signal the press event yet. prev_button_state = button_state; return 0; } <file_sep>/client/Sensors.cpp #include "Sensors.h" // Static allocations unsigned long int Sensors::time; // Prepare the inturupt element volatile bool Sensors::sensorSecond = 0; Sensors::Sensors() { Wire.begin(); // Start the wire interface time = millis(); // Record the start time } int Sensors::getTime() { return (int)((float)(0.001 * (millis() - time))); // Return the time in seconds } unsigned long int Sensors::getLongTime() { return millis() - time; // Return the time in miliseconds } void Sensors::writeTo(int destination, byte address, byte val) { Wire.beginTransmission(destination); // start transmission to device Wire.write(address); // send register address Wire.write(val); // send value to write Wire.endTransmission(); // end transmission } // Reads num bytes starting from address register on device in to _buff array void Sensors::readFrom(int destination, byte address, int num, byte _buff[]) { Wire.beginTransmission(destination); // start transmission to device Wire.write(address); // sends address to read from Wire.endTransmission(); // end transmission delay(6); Wire.beginTransmission(destination); // start transmission to device Wire.requestFrom(destination, num); // request 6 bytes from device int i = 0; while(Wire.available()) // device may send less than requested (abnormal) { _buff[i] = Wire.read(); // receive a byte i++; } Wire.endTransmission(); // end transmission } <file_sep>/client/client.cpp #include <Arduino.h> #include <Wire.h> #include <Adafruit_ST7735.h> #include <SD.h> #include <mem_syms.h> #include "TimerThree.h" #include "Sensors.h" #include "TinyGPS.h" #include "GTPA010.h" #include "LSM303.h" #include "joystick.h" #include "map.h" #include "path.h" #include "serial_handling.h" #include "ledon.h" // #define DEBUG_SCROLLING // #define DEBUG_PATH // #define DEBUG_MEMORY TinyGPS gps; LSM303 compass; // the pins used to connect to the AdaFruit display const uint8_t sd_cs = 5; const uint8_t tft_cs = 6; const uint8_t tft_dc = 7; const uint8_t tft_rst = 8; // forward function declarations void initialize_sd_card(); void initialize_screen(); void initialize_joystick(); uint8_t process_joystick(int16_t *dx, int16_t *dy); void status_msg(char *msg); void clear_status_msg(); // Interrupt routines for zooming in and out. void handle_zoom_in(); void handle_zoom_out(); // global state variables // globally accessible screen Adafruit_ST7735 tft = Adafruit_ST7735(tft_cs, tft_dc, tft_rst); // Map number (zoom level) currently selected. extern uint8_t current_map_num; // First time flag for loop, set to cause actions for the first time only uint8_t first_time; void setup() { Sensors::Sensors(); Serial.begin(9600); Serial.println("Starting..."); Serial.flush(); // There can be nasty leftover bits. GTPA010::begin(); Serial.println("GPS initialized!"); compass.init(LSM303DLH_DEVICE); compass.enableDefault(); compass.setMagGain(LSM303::magGain_47); Serial.println("Compass initialized!"); compass.read(); #ifdef DEBUG if (!compass.timeoutOccurred()) { Serial.print("Compass heading: "); Serial.println(compass.heading()); } else { Serial.println("Timed out!"); } #endif #ifdef GLASSES_DEBUG while (1) { compass.reaqd(); map_to_glasses(compass.heading()); } #endif initialize_screen(); initialize_sd_card(); initialize_joystick(); initialize_map(); // Want to start viewing window in the center of the map move_window(-11353058,5352706); // with cursor in the middle of the window move_cursor_to( screen_map_x + display_window_width / 2, screen_map_y + display_window_height / 2); // Draw the initial screen and cursor first_time = 1; #ifdef DEBUG_MEMORY Serial.print("Available mem:"); Serial.println(AVAIL_MEM); #endif } const uint16_t screen_scroll_delta = 64; const uint16_t screen_left_margin = 10; const uint16_t screen_right_margin = 117; const uint16_t screen_top_margin = 10; const uint16_t screen_bottom_margin = 117; // the path request, start and stop lat and lon uint8_t request_state = 0; // 0 - wait for start, 1 - wait for stop point int32_t start_lat; int32_t start_lon; int32_t stop_lat; int32_t stop_lon; uint32_t g_lat; uint32_t g_lon; // the most recent path to display, length = 0 means no path uint16_t path_length = 0; coord_t *path; char * prev_loc_msg = 0; /** * Print the current GPS position to the LCD */ void pos_msg(char * msg) { if (prev_loc_msg != msg) { prev_loc_msg = msg; // Draw background tft.fillRect(0, 136, 128, 12, WHITE); // Set text options tft.setTextSize(1); tft.setTextColor(BLACK); tft.setCursor(0, 138); // Draw text tft.println(msg); } } /** * Redraw the screen */ void refresh_display() { #ifdef DEBUG_SCROLLING Serial.println("Screen update"); Serial.print(current_map_num); Serial.print(" "); Serial.print(cursor_lon); Serial.print(" "); Serial.print(cursor_lat); Serial.println(); #endif draw_map_screen(); draw_cursor(); // Need to redraw any other things that are on the screen if ( path_length > 0 ) { draw_path(path_length, path); } // force a redisplay of status message clear_status_msg(); draw_compass(); draw_gps_dot(); char * pos_str = 0; #if FAKE_GPS_DATA pos_str = "USING FAKE DATA"; #else if (GTPA010::gpsLock) pos_str = "USING GPS COORDS"; else pos_str = "SEARCHING SATELLITES"; #endif pos_msg(""); pos_msg(pos_str); } /** * Send a path request to the server and wait for a response */ void query_path(int32_t s_lat, int32_t s_lon, int32_t e_lat, int32_t e_lon) { // send out the start and stop coordinates to the server Serial.print(s_lat); Serial.print(" "); Serial.print(s_lon); Serial.print(" "); Serial.print(e_lat); Serial.print(" "); Serial.print(e_lon); Serial.println(); // free any existing path if ( path_length > 0 ) { free(path); } // read the path from the serial port status_msg("WAITING"); if ( read_path(&path_length, &path) ) { #ifdef DEBUG_PATH uint8_t is_visible; for (uint16_t i=0; i < path_length; i++) { is_visible = is_coord_visible(path[i]); Serial.print(i); Serial.print(": "); Serial.print(path[i].lat); Serial.print(","); Serial.print(path[i].lon); Serial.print(is_visible ? "V": ""); Serial.println(); } #endif } else { // should display this error on the screen pos_msg("Path error!"); } refresh_display(); } int path_time = 0; void loop() { // Make sure we don't update the map tile on screen when we don't need to! uint8_t update_display_window = 0; if ( first_time ) { first_time = 0; update_display_window = 1; } // Joystick displacement. int16_t dx = 0; int16_t dy = 0; uint8_t select_button_event = 0; // Update glasses heading if (path_length > 0) { //Serial.print("Compass: "); //Serial.println(compass.heading()); compass.read(); map_to_glasses((int)(target_dir - compass.heading()) % 360); } // See if the joystick has moved, in which case we want to // also want to move the visible cursor on the screen. // Process joystick input. select_button_event = process_joystick(&dx, &dy); // the joystick routine filters out small changes, so anything non-0 // is a real movement if ( abs(dx) > 0 || abs(dy) > 0 ) { // Is the cursor getting near the edge of the screen? If so // then scroll the map over by re-centering the window. uint16_t new_screen_map_x = screen_map_x; uint16_t new_screen_map_y = screen_map_y; uint8_t need_to_move = 0; uint16_t cursor_screen_x; uint16_t cursor_screen_y; if ( get_cursor_screen_x_y(&cursor_screen_x, &cursor_screen_y) ) { // if the cursor is visible, then adjust the display to // to scroll if near the edge. if ( cursor_screen_x < screen_left_margin ) { new_screen_map_x = screen_map_x - screen_scroll_delta; need_to_move = 1; } else if ( cursor_screen_x > screen_right_margin ) { new_screen_map_x = screen_map_x + screen_scroll_delta; need_to_move = 1; } if ( cursor_screen_y < screen_top_margin ) { new_screen_map_y = screen_map_y - screen_scroll_delta; need_to_move = 1; } else if ( cursor_screen_y > screen_bottom_margin ) { new_screen_map_y = screen_map_y + screen_scroll_delta; need_to_move = 1; } if ( need_to_move ) { // move the display window, leaving cursor at same lat-lon move_window_to(new_screen_map_x, new_screen_map_y); update_display_window = 1; } else { // erase old cursor, move, and draw new one, no need to // redraw the underlying map tile erase_cursor(); move_cursor_by(dx, dy); draw_cursor(); } } } // at this point the screen is updated, with a new tile window and // cursor position if necessary // will only be down once, then waits for a min time before allowing // pres again. if (select_button_event) { // Button was pressed, we are selecting a point! #ifdef DEBUG_PATH Serial.print("x "); Serial.print(cursor_map_x); Serial.print(" y "); Serial.print(cursor_map_y); Serial.println(); #endif // which press is this, the start or the stop selection? // If we are making a request to find a shortest path, we will send out // the request on the serial port and then wait for a response from the // server. While this is happening, the client user interface is // suspended. gpsData * gdata; GTPA010::readData(); gdata = GTPA010::getData(); g_lat = gdata->lat; g_lon = gdata->lon; start_lat = g_lat; start_lon = g_lon; stop_lat = cursor_lat; stop_lon = cursor_lon; query_path(start_lat, start_lon, stop_lat, stop_lon); path_time = Sensors::getTime(); } // end of select_button_event processing // do we have to redraw the map tile? if (update_display_window) { refresh_display(); } // Spam the server for a new path if (path_length > 0 && Sensors::getTime() - path_time >= 5) { gpsData * gData = GTPA010::getData(); // If we've moved, request a new path if (abs(gData->lat - start_lat) > 5 || abs(gData->lon - start_lon) > 5) { start_lat = gData->lat; start_lon = gData->lon; query_path(start_lat, start_lon, stop_lat, stop_lon); } path_time = Sensors::getTime(); } // Refresh compass display draw_compass(); // Refresh gps dot draw_gps_dot(); // always update the status message area if message changes // Indicate which point we are waiting for if ( request_state == 0 ) { status_msg("DESTINATION?"); } } char* prev_status_msg = 0; void clear_status_msg() { status_msg(""); } void status_msg(char *msg) { // messages are strings, so we assume constant, and if they are the // same pointer then the contents are the same. You can force by // setting prev_status_msg = 0 if ( prev_status_msg != msg ) { prev_status_msg = msg; tft.fillRect(0, 148, 128, 12, GREEN); tft.setTextSize(1); tft.setTextColor(MAGENTA); tft.setCursor(0, 150); tft.setTextSize(1); tft.println(msg); } } void initialize_screen() { tft.initR(INITR_REDTAB); tft.setRotation(0); tft.setCursor(0, 0); tft.setTextColor(0x0000); tft.setTextSize(1); tft.fillScreen(BLUE); } void initialize_sd_card() { if (!SD.begin(sd_cs)) { #ifdef DEBUG_SERIAL Serial.println("Initialization has failed. Things to check:"); Serial.println("* Is a card inserted?"); Serial.println("* Is your wiring correct?"); Serial.println("* Is the chipSelect pin the one for your shield or module?"); Serial.println("SD card could not be initialized"); #endif while (1) {}; // Just wait, stuff exploded. } else { #ifdef DEBUG_SERIAL Serial.println("Wiring is correct and a card is present."); #endif } } <file_sep>/README.md arduino-gps-glasses =================== Arduino-powered GPS with a python map-finding server This was a group project for CMPUT 297 (now called CMPUT 275) at the University of Alberta. The project featured a set of plastic glasses frames with eight LED's affixed to the frame around one eye. The LED's were wired such that they could be selected using a 3-to-8 multiplexer. A switch was connected to one of the multiplexer's enable pins to turn the lights on or off. The multiplexer was to connect to an Arduino Mega 2560, which also had a GPS receiver and a tilt-compensated compass connected to it. Through this, the Arduino could gather its position and orientation on a map of Edmonton, which was loaded on to an SD card. The Arduino communicated with a Raspberry Pi, which ran a pathfinding program. This would generate a path for a person to follow. Based on the GPS and compass readings, this would allow the user to turn on the glasses to see which direction they should be moving. The system could successfully retrieve a path and direct a user, however the digital compass was not effective on the university campus. As such, its accuracy was limited where it was tested. The hardware assembled to run this project has since been decomissioned and disassembled. <file_sep>/server/server.py """ Python route-finding server Call this program with the map data file as a parameter $ python server.py roads-digraph.txt CMPUT297 Assignment #3 <NAME> This assignment is a solo effort, although discussion about the assignment occurred with several students: <NAME>, <NAME> """ import argparse import digraph import pqueue import readgraph import serial import sys import time global debug debug = False def send(serial_port, message): """ Sends a message back to the client device. """ full_message = ''.join((message, "\n")) (debug and print("server:" + full_message + ":") ) reencoded = bytes(full_message, encoding='ascii') serial_port.write(reencoded) def receive(serial_port, timeout=None): """ Listen for a message. Attempt to timeout after a certain number of milliseconds. """ raw_message = serial_port.readline() debug and print("client:", raw_message, ":") message = raw_message.decode('ascii') return message.rstrip("\n\r") def parse_args(): """ Parses arguments for this program. Returns an object with the following members: args. serialport -- str verbose -- bool graphname -- str """ parser = argparse.ArgumentParser( description='Assignment 1: Map directions.', epilog = 'If SERIALPORT is not specified, stdin/stdout are used.') parser.add_argument('-s', '--serial', help='path to serial port', dest='serialport', default=None) parser.add_argument('-v', dest='verbose', help='verbose', action='store_true') parser.add_argument('-g', '--graph', help='path to graph (DEFAULT = " edmonton_roads.txt")', dest='graphname', default='edmonton_roads.txt') return parser.parse_args() def distance(a, b): """ Calculate the distance between two coordinates using a standard distance equation ( (x1-x2)^2 + (y1-y2)^2 )^0.5 >>> distance( (0, 0), (3, 4) ) == 5 True >>> round(distance( (-1.6, 2.4), (3.45, -5) )) == 9 True """ if len(a) != 2 or len(b) != 2: raise ValueError dx = float(a[0]) - float(b[0]) dy = float(a[1]) - float(b[1]) return ( dx**2 + dy**2 )**0.5 def nearest_vertex(coord): """ Find the nearest vertex to a coordinate This cannot be unit tested generically here because overriding V_coord here in a doctest does not seem to override V_coord used in the function, and spec says we have load the Edmonton roads graph """ # Make sure a coordinate was passed in if len(coord) != 2: raise ValueError # Make sure any vertex has a shorter distance shortest_dist = float('inf') vertex = -1 # Loop through all vertices and find closest for v in V_coord: dist = distance(coord, V_coord[v]) if dist < shortest_dist: shortest_dist = dist vertex = v return vertex def cost_distance(e): """ Get the distance between two vertices Like above we can't test it here as is because I can't override V_coord. """ # Make sure we have a proper edge with two vertices if len(e) != 2: raise ValueError a = V_coord[e[0]] b = V_coord[e[1]] # Return the distance between two points return distance(a, b) def least_cost_path(G, start, dest, cost): """ path = least_cost_path(G, start, dest, cost) least_cost_path returns a least cost path in the digraph G from vertex start to vertex dest, where costs are defined by the cost function. cost should be a function that takes a single edge argument and returns a real-valued cost. if there is no path, then returns None the path from start to start is [start] >>> g = digraph.Digraph( [(1, 2), (4, 2), (4, 6), (6, 7), (1, 7), (2, 4)] ) >>> least_cost_path(g, 1, 7, lambda e: abs(2*e[0]-e[1])) [1, 7] >>> least_cost_path(g, 7, 2, lambda e: 1) is None True """ # Create a priority queue todo = pqueue.PQueue() todo.update(start, 0); # v in visited when the vertex v's least cost from start has been determined visited = set() # parent[v] is the vertex that just precedes v in the path from start to v parent = {} while todo and (dest not in visited): # priority queue operation # remove smallest estimated cost vertex from todo list (cur, c) = todo.pop_smallest() # it is now visited, and will never have a smaller cost visited.add(cur) for n in G.adj_to(cur): if n in visited: continue if todo.update(n, c+cost((cur,n))): parent[n] = cur # now, if there is a path, extract it. The graph may be disconnected # so in that case return None if dest not in visited: return None path = [dest] cur = dest while start not in path: cur = parent[cur] path.append(cur) path.reverse() return path def main(): """ Run the server """ time1 = time.time() print("Initializing..") # Grab program arguments args = parse_args() # Load data file try: global V_coord (V, E, V_coord, E_name) = readgraph.readgraph(args.graphname) except FileNotFoundError: print("Data file {} not found!".format(args.graphname), file=sys.stderr) exit() # Initialize serial port try: if args.serialport: print("Opening serial port: {}".format(args.serialport)) serial_out = serial_in = serial.Serial(args.serialport, 9600) else: print("No serial port. Supply one with the -s port option.") exit() except serial.SerialException: print("Could not open serial port: {}".format(args.serialport), file=sys.stderr) exit() # Set debug mode if args.verbose: debug = True else: debug = False # Generate a graph from the map and grab the needed values G = digraph.Digraph(E) # Add all orphan vertices. Not really useful, and in fact detrimental # in all cases, but do it for the sake of completeness for v in V: G.add_vertex(v) # Print some debug output if debug: print("Graph loaded with {} vertices and {} edges.".format(G.num_vertices(), G.num_edges())) time2 = time.time() delta_t = repr(time2 - time1) print("Done initializing, took " + delta_t + " seconds") # Parse input while True: msg = receive(serial_in) debug and print("GOT:{}:".format(msg), file=sys.stderr) fields = msg.split(" ") # Ignore malformed messages if len(fields) != 4: debug and print("Ignoring message: {}".format(msg)) continue time1 = time.time() print("Processing..") # Get start and end vertices start_v = (int(fields[0])/10**5, int(fields[1])/10**5) end_v = (int(fields[2])/10**5, int(fields[3])/10**5) start = nearest_vertex( start_v ) end = nearest_vertex( end_v ) debug and print("Routing path from vertex {} to {}".format(start, end)) path = least_cost_path(G, start, end, cost_distance) if path is None: send(serial_out, "0") debug and print("No path found!", file=sys.stderr) else: send(serial_out, str(len(path))) for v in path: send(serial_out, "{} {}".format(int(V_coord[v][0] * 10**5), int(V_coord[v][1] * 10**5))) print("Send path of length {}".format(len(path))) time2 = time.time() delta_t = repr(time2 - time1) print("Done processing, took " + delta_t + "seconds") # Execute the main function if __name__ == "__main__": main() <file_sep>/server/pqueue.py """ Priority queue implementation as a binary heap pop_smallest() remove the element with the lowest priority return tuple (key, priority) update(key, priority) lower the priority of an element if priority is not lower do nothing, if key is not in priority queue, add it return True if priority of a key has changed or is added, otherwise False is_empty() return True if nothing is in the priority queue, otherwise False >>> q = PQueue() >>> q.is_empty() True >>> q.update("thing", 1) True >>> q.is_empty() False >>> q.update("another thing", 5) True >>> q.pop_smallest() ('thing', 1) >>> q.is_empty() False >>> q.update("thing", 3) True >>> q.update("another thing", 1) True >>> len(q) 2 >>> 'thing' in q True >>> 'nothing' in q False >>> q.pop_smallest() ('another thing', 1) >>> q.pop_smallest() ('thing', 3) >>> q.is_empty() True """ def _parent(i): """ >>> _parent(3) 1 >>> _parent(27) 13 """ return (i-1)//2 def _children(i): """ >>> _children(5) [11, 12] """ return [ 2*i + 1, 2*i + 2 ] class PQueue: def __init__(self): self._heap = [] self._keyindex = {} def __len__(self): return len(self._heap) def __contains__(self, key): return key in self._keyindex def update(self, key, priority): if key in self._keyindex: i = self._keyindex[key] # Update existing entry, possibly lower its priority if priority > self._priority(i): return False else: self._heap[i] = (key, priority) self._heapify_up(i) return True else: # Create a new heap entry self._heap.append( (key, priority) ) self._keyindex[key] = len(self._heap) - 1; self._heapify_up(len(self._heap) - 1) return True def pop_smallest(self): self._swap(0, len(self._heap) - 1) rv = self._heap.pop() del self._keyindex[rv[0]] self._heapify_down(0) return rv def is_empty(self): return len(self._heap) == 0 def _swap(self, i, j): (self._heap[i], self._heap[j]) = (self._heap[j], self._heap[i]) self._keyindex[self._heap[i][0]] = i self._keyindex[self._heap[j][0]] = j def _priority(self, i): return self._heap[i][1] def _heapify_down(self, i): children = [ c for c in _children(i) if c < len(self._heap) ] if not children: return # Find child with smallest priority minchild = min(children, key = self._priority) if self._priority(i) > self._priority(minchild): # Swap element i with its smallest child self._swap(i, minchild) self._heapify_down(minchild) def _heapify_up(self, i): if i == 0: return # compare i with its parent if self._priority(i) < self._priority(_parent(i)): self._swap(i, _parent(i)) self._heapify_up(_parent(i)) if __name__ == "__main__": import doctest doctest.testmod() <file_sep>/client/mem_syms.h /* If you have the libc 1.6.4 libraries then free space at the end of the heap is NOT released. With the libc 1.7.1 libraries with the fixed malloc, then free space at the end of the heap is released so that the space is available to the stack or the heap. AVAIL_MEM is a macro to tell you how much available free memory is left between the top of stack and end of heap. STACK_TOP is a macro to tell you the current address of the top of the stack. There is data in this location ?? STACK_BOTTOM is a macro to tell you the address of the bottom of the stack. It should normally be constant. STACK_SIZE is a macro to tell you the current size of the stack HEAP_START is a macro to provide the address of the first location in the heap. HEAP_END is macro to provide the address of the current last location in in the heap. This will increase as memory is allocated, and decrease if the end of the heap consists of free memory and can be shrunk. HEAP_SIZE is a macro to tell you the current size of the heap, but it includes chunks that are free. There should be a routine to detect the presence of the old or new malloc. */ #ifndef mem_syms_h #define mem_syms_h #include "avr/io.h" /* these symbols get us to the details of the stack and heap */ // the address of the first byte of the stack, the last byte of onchip SRAM #define STACK_BOTTOM ( (char*)RAMEND ) // the first free location at the top of the stack #define STACK_TOP ((char *)AVR_STACK_POINTER_REG) // the amount of stack used. i.e. from bottom to top-1 #define STACK_SIZE (STACK_BOTTOM - STACK_TOP) #define AVAIL_MEM (STACK_TOP - HEAP_END) // the address of the first location of the heap #define HEAP_START __malloc_heap_start // the address of the next free location after the end of the heap // __brkval is 0 until the first malloc #define HEAP_END (__brkval ? __brkval : __malloc_heap_start) // the amount of space taken up by the heap, including free chunks // inside the heap #define HEAP_SIZE (HEAP_END - HEAP_START) extern char*__brkval; #endif <file_sep>/client/readme.txt Arduino Pathfinder Client CMPUT 297 by <NAME> This assignment is a solo effort, although discussion took place with <NAME>, <NAME> ========================================================================== This map client is designed to be run on the Arduino Mega 2550 with an Adafruit ST7735-based display. Use the joystick to move around the map. Click the joystick button to select paths. Use the two zoom buttons to zoom in and out. Limitations: When moving the cursor, you can erase a path if you move the cursor over it. The path will be redrawn after the window moves. Any time the window moves, the cursor will jump to the middle of the window to prevent getting stuck at the map edges or being put in an unpredictable location when zooming the map. <file_sep>/client/serial_handling.cpp #include "serial_handling.h" #include <Arduino.h> #include <errno.h> #include <assert13.h> uint16_t serial_readline(char *line, uint16_t line_size) { int bytes_read = 0; // Number of bytes read from the serial port. // Read until we hit the maximum length, or a newline. // One less than the maximum length because we want to add a null terminator. while (bytes_read < line_size - 1) { while (Serial.available() == 0) { // There is no data to be read from the serial port. // Wait until data is available. } line[bytes_read] = (char) Serial.read(); // A newline is given by \r or \n, or some combination of both // or the read may have failed and returned 0 if ( line[bytes_read] == '\r' || line[bytes_read] == '\n' || line[bytes_read] == 0 ) { // We ran into a newline character! Overwrite it with \0 break; // Break out of this - we are done reading a line. } else { bytes_read++; } } // Add null termination to the end of our string. line[bytes_read] = '\0'; return bytes_read; } uint16_t string_read_field(const char *str, uint16_t str_start, char *field, uint16_t field_size, const char *sep) { // Want to read from the string until we encounter the separator. // Character that we are reading from the string. uint16_t str_index = str_start; while (1) { if ( str[str_index] == '\0') { str_index++; // signal off end of str break; } if ( field_size <= 1 ) break; if (strchr(sep, str[str_index])) { // field finished, skip over the separator character. str_index++; break; } // Copy the string character into buffer and move over to next *field = str[str_index]; field++; field_size--; // Move on to the next character. str_index++; } // Make sure to add NULL termination to our new string. *field = '\0'; // Return the index of where the next token begins. return str_index; } int32_t string_get_int(const char *str) { // Attempt to convert the string to an integer using strtol... int32_t val = strtol(str, NULL, 10); if (val == 0) { // Must check errno for possible error. if (errno == ERANGE) { Serial.print("string_get_int failed: "); Serial.println(str); assert13(0, errno); } } return val; } <file_sep>/client/assert13.cpp #include <Arduino.h> #include "assert13.h" // create a busy-loop delay, since timers are off int hard_loop(unsigned long int n) { // this introduction of y and the Serial.print // are to mess with gcc's optimization of the loop int y = 0; while (n > 0) { y = y + n; n--; } Serial.print(""); return y; } #define DELAY_COUNT 1000000L /* assertion checker assert13(invariant, code); if invariant is false (i.e. 0) then fail and enter a hard loop with interrupts disabled and repeatedly sending code to the serial monitor, while blinking the LED on pin 13. There is a small window in which an interrupt could occur, and in which a failure could call assert13. How would we guard against this? */ void assert13(int invariant, int code) { unsigned long int count; if ( invariant ) { return; } Serial.println("Assertion failure"); noInterrupts(); pinMode(13, OUTPUT); while ( 1 ) { Serial.println(code); digitalWrite(13, LOW); // Serial.println("LOW"); hard_loop( DELAY_COUNT ); digitalWrite(13, HIGH); // Serial.println("HIGH"); hard_loop( DELAY_COUNT ); } } <file_sep>/client/joystick.h #ifndef _JOY_H_ #define _JOY_H_ extern int16_t joy_center_x; extern int16_t joy_center_y; void initialize_joystick(); uint8_t process_joystick(int16_t *dx, int16_t *dy); #endif <file_sep>/client/ledon.cpp #include <Arduino.h> #include "ledon.h" void map_to_glasses(int heading) { // Replace these with accessors to a global pin variables. int a0 = 22; int a1 = 23; int a2 = 24; //Used to enable certain leds int v[] = {0, 0, 0}; //Put these in a global initialization file? pinMode(a0, OUTPUT); pinMode(a1, OUTPUT); pinMode(a2, OUTPUT); int i = (heading/45) % 8; //i is the led number to enable. //Make i a bitfield v[0] = (i & 0x1); v[1] = (i & 0x2); v[2] = (i & 0x4); if (v[0]) digitalWrite(a0, HIGH); else digitalWrite(a0, LOW); if (v[1]) digitalWrite(a1, HIGH); else digitalWrite(a1, LOW); if (v[2]) digitalWrite(a2, HIGH); else digitalWrite(a2, LOW); } <file_sep>/client/LSM303.cpp #include <LSM303.h> #include <Wire.h> #include <math.h> // Defines //////////////////////////////////////////////////////////////// // The Arduino two-wire interface uses a 7-bit number for the address, // and sets the last bit correctly based on reads and writes #define MAG_ADDRESS (0x3C >> 1) #define ACC_ADDRESS_SA0_A_LOW (0x30 >> 1) #define ACC_ADDRESS_SA0_A_HIGH (0x32 >> 1) int past_headings[3] = {0, 0, 0}; int past_heading_i = 0; // Constructors //////////////////////////////////////////////////////////////// LSM303::LSM303(void) { // These are just some values for a particular unit; it is recommended that // a calibration be done for your particular unit. m_max.x = +1; m_max.y = +2; m_max.z = 0; m_min.x = -1; m_min.y = -2; m_min.z = -140; _device = LSM303_DEVICE_AUTO; acc_address = ACC_ADDRESS_SA0_A_LOW; io_timeout = 0; // 0 = no timeout did_timeout = false; } // Public Methods ////////////////////////////////////////////////////////////// bool LSM303::timeoutOccurred() { return did_timeout; } void LSM303::setTimeout(unsigned int timeout) { io_timeout = timeout; } unsigned int LSM303::getTimeout() { return io_timeout; } void LSM303::init(byte device, byte sa0_a) { _device = device; switch (_device) { case LSM303DLH_DEVICE: case LSM303DLM_DEVICE: if (sa0_a == LSM303_SA0_A_LOW) acc_address = ACC_ADDRESS_SA0_A_LOW; else if (sa0_a == LSM303_SA0_A_HIGH) acc_address = ACC_ADDRESS_SA0_A_HIGH; else acc_address = (detectSA0_A() == LSM303_SA0_A_HIGH) ? ACC_ADDRESS_SA0_A_HIGH : ACC_ADDRESS_SA0_A_LOW; break; case LSM303DLHC_DEVICE: acc_address = ACC_ADDRESS_SA0_A_HIGH; break; default: // try to auto-detect device if (detectSA0_A() == LSM303_SA0_A_HIGH) { // if device responds on 0011001b (SA0_A is high), assume DLHC acc_address = ACC_ADDRESS_SA0_A_HIGH; _device = LSM303DLHC_DEVICE; } else { // otherwise, assume DLH or DLM (pulled low by default on Pololu boards); query magnetometer WHO_AM_I to differentiate these two acc_address = ACC_ADDRESS_SA0_A_LOW; _device = (readMagReg(LSM303_WHO_AM_I_M) == 0x3C) ? LSM303DLM_DEVICE : LSM303DLH_DEVICE; } } } // Turns on the LSM303's accelerometer and magnetometers and places them in normal // mode. void LSM303::enableDefault(void) { // Enable Accelerometer // 0x27 = 0b00100111 // Normal power mode, all axes enabled writeAccReg(LSM303_CTRL_REG1_A, 0x27); if (_device == LSM303DLHC_DEVICE) writeAccReg(LSM303_CTRL_REG4_A, 0x08); // DLHC: enable high resolution mode // Enable Magnetometer // 0x00 = 0b00000000 // Continuous conversion mode writeMagReg(LSM303_MR_REG_M, 0x00); writeMagReg(LSM303_CRA_REG_M, 0x14); // 0x14 = mag 30Hz output rate } // Writes an accelerometer register void LSM303::writeAccReg(byte reg, byte value) { Wire.beginTransmission(acc_address); Wire.write(reg); Wire.write(value); last_status = Wire.endTransmission(); } // Reads an accelerometer register byte LSM303::readAccReg(byte reg) { byte value; Wire.beginTransmission(acc_address); Wire.write(reg); last_status = Wire.endTransmission(); Wire.requestFrom(acc_address, (byte)1); value = Wire.read(); Wire.endTransmission(); return value; } // Writes a magnetometer register void LSM303::writeMagReg(byte reg, byte value) { Wire.beginTransmission(MAG_ADDRESS); Wire.write(reg); Wire.write(value); last_status = Wire.endTransmission(); } // Reads a magnetometer register byte LSM303::readMagReg(int reg) { byte value; // if dummy register address (magnetometer Y/Z), use device type to determine actual address if (reg < 0) { switch (reg) { case LSM303_OUT_Y_H_M: reg = (_device == LSM303DLH_DEVICE) ? LSM303DLH_OUT_Y_H_M : LSM303DLM_OUT_Y_H_M; break; case LSM303_OUT_Y_L_M: reg = (_device == LSM303DLH_DEVICE) ? LSM303DLH_OUT_Y_L_M : LSM303DLM_OUT_Y_L_M; break; case LSM303_OUT_Z_H_M: reg = (_device == LSM303DLH_DEVICE) ? LSM303DLH_OUT_Z_H_M : LSM303DLM_OUT_Z_H_M; break; case LSM303_OUT_Z_L_M: reg = (_device == LSM303DLH_DEVICE) ? LSM303DLH_OUT_Z_L_M : LSM303DLM_OUT_Z_L_M; break; } } Wire.beginTransmission(MAG_ADDRESS); Wire.write(reg); last_status = Wire.endTransmission(); Wire.requestFrom(MAG_ADDRESS, 1); value = Wire.read(); Wire.endTransmission(); return value; } void LSM303::setMagGain(magGain value) { Wire.beginTransmission(MAG_ADDRESS); Wire.write(LSM303_CRB_REG_M); Wire.write((byte) value); Wire.endTransmission(); } // Reads the 3 accelerometer channels and stores them in vector a void LSM303::readAcc(void) { Wire.beginTransmission(acc_address); // assert the MSB of the address to get the accelerometer // to do slave-transmit subaddress updating. Wire.write(LSM303_OUT_X_L_A | (1 << 7)); last_status = Wire.endTransmission(); Wire.requestFrom(acc_address, (byte)6); unsigned int millis_start = millis(); did_timeout = false; while (Wire.available() < 6) { if (io_timeout > 0 && ((unsigned int)millis() - millis_start) > io_timeout) { did_timeout = true; return; } } /* Old Wire.Reads(). Going to swap all y and z here */ byte xla = Wire.read(); byte xha = Wire.read(); byte yla = Wire.read(); byte yha = Wire.read(); byte zla = Wire.read(); byte zha = Wire.read(); //New wire reads. Don't really work /* byte xla = Wire.read(); byte xha = Wire.read(); byte zla = Wire.read(); byte zha = Wire.read(); byte yla = Wire.read(); byte yha = Wire.read(); */ // combine high and low bytes, then shift right to discard lowest 4 bits (which are meaningless) // GCC performs an arithmetic right shift for signed negative numbers, but this code will not work // if you port it to a compiler that does a logical right shift instead. a.x = ((int16_t)(xha << 8 | xla)) >> 4; a.y = ((int16_t)(yha << 8 | yla)) >> 4; a.z = ((int16_t)(zha << 8 | zla)) >> 4; } // Reads the 3 magnetometer channels and stores them in vector m void LSM303::readMag(void) { Wire.beginTransmission(MAG_ADDRESS); Wire.write(LSM303_OUT_X_H_M); last_status = Wire.endTransmission(); Wire.requestFrom(MAG_ADDRESS, 6); unsigned int millis_start = millis(); did_timeout = false; while (Wire.available() < 6) { if (io_timeout > 0 && ((unsigned int)millis() - millis_start) > io_timeout) { did_timeout = true; return; } } uint16_t xhm = Wire.read(); uint16_t xlm = Wire.read(); uint16_t yhm, ylm, zhm, zlm; if (_device == LSM303DLH_DEVICE) { // DLH: register address for Y comes before Z yhm = Wire.read(); ylm = Wire.read(); zhm = Wire.read(); zlm = Wire.read(); } else { // DLM, DLHC: register address for Z comes before Y zhm = Wire.read(); zlm = Wire.read(); yhm = Wire.read(); ylm = Wire.read(); } // combine high and low bytes m.x = (int16_t)(xhm << 8 | xlm); m.y = (int16_t)(yhm << 8 | ylm); m.z = (int16_t)(zhm << 8 | zlm); #ifdef DEBUG_COMPASS Serial.println(m.x); Serial.println(m.y); Serial.println(m.z); Serial.println(); delay(1000); #endif } // Reads all 6 channels of the LSM303 and stores them in the object variables void LSM303::read(void) { readAcc(); readMag(); } // Returns a heading in degrees, compensated for pitch and roll int LSM303::heading(void) { //Need to normalize the vector so that trig isn't broken vector b = a; vector_normalize(&b); float pitch = asin(-b.x); float roll = asin(b.y/cos(pitch)); float xh = (m.x+75+30) * cos(pitch) + m.z * sin(pitch); float yh = (m.x+105) * sin(roll) * sin(pitch) + (m.y-115) * cos(roll) - m.z * sin(roll) * cos(pitch); float zh = -(m.x+105) * cos(roll) * sin(pitch) + (m.y-115) * sin(roll) + m.z * cos(roll) * cos(pitch); int heading = (int)(180 * atan2(yh, xh)/PI) % 360; // Populate some fields for average heading calculation if (!past_headings[0]) past_headings[0] = heading; if (!past_headings[1]) past_headings[1] = heading; if (!past_headings[2]) past_headings[2] = heading; past_headings[past_heading_i] = heading; past_heading_i = (past_heading_i + 1) % 3; /* Debugging output. */ #ifdef DEBUG_COMPASS Serial.print("b.x"); Serial.print(b.x); Serial.print("b.y"); Serial.print(b.y); Serial.println(); Serial.print("Pitch: "); Serial.print(pitch); Serial.print("Roll:"); Serial.print(roll); Serial.print("Xh: "); Serial.print(xh); Serial.print("Yh: "); Serial.print(yh); Serial.print("Zh: "); Serial.print(zh); Serial.print("Heading: "); Serial.println(heading); #endif // Return average of most three recent headings return ((int)(past_headings[0] + past_headings[1] + past_headings[2])/3) % 360; } void LSM303::vector_cross(const vector *a,const vector *b, vector *out) { out->x = a->y*b->z - a->z*b->y; out->y = a->z*b->x - a->x*b->z; out->z = a->x*b->y - a->y*b->x; } float LSM303::vector_dot(const vector *a,const vector *b) { return a->x*b->x+a->y*b->y+a->z*b->z; } void LSM303::vector_normalize(vector *a) { float mag = sqrt(vector_dot(a,a)); a->x /= mag; a->y /= mag; a->z /= mag; } // Private Methods ////////////////////////////////////////////////////////////// byte LSM303::detectSA0_A(void) { Wire.beginTransmission(ACC_ADDRESS_SA0_A_LOW); Wire.write(LSM303_CTRL_REG1_A); last_status = Wire.endTransmission(); Wire.requestFrom(ACC_ADDRESS_SA0_A_LOW, 1); if (Wire.available()) { Wire.read(); return LSM303_SA0_A_LOW; } else return LSM303_SA0_A_HIGH; } <file_sep>/server/dumb_server.py import sys import serial import argparse global debug debug = False def main(): args = parse_args() # Initialize some stuff... if args.serialport: print("Opening serial port: %s" % args.serialport) serial_out = serial_in = serial.Serial(args.serialport, 9600) else: print("No serial port. Supply one with the -s port option") exit() if args.verbose: debug = True else: debug = False idx = 0 while True: msg = receive(serial_in) debug and print("GOT:" + msg + ":", file=sys.stderr) fields = msg.split(" "); if len(fields) == 4: send(serial_out, "2") send(serial_out, fields[0]+" "+fields[1]) send(serial_out, fields[2]+" "+fields[3]) idx += 1 def send(serial_port, message): """ Sends a message back to the client device. """ full_message = ''.join((message, "\n")) (debug and print("server:" + full_message + ":") ) reencoded = bytes(full_message, encoding='ascii') serial_port.write(reencoded) def receive(serial_port, timeout=None): """ Listen for a message. Attempt to timeout after a certain number of milliseconds. """ raw_message = serial_port.readline() debug and print("client:", raw_message, ":") message = raw_message.decode('ascii') return message.rstrip("\n\r") def parse_args(): """ Parses arguments for this program. Returns an object with the following members: args. serialport -- str verbose -- bool graphname -- str """ parser = argparse.ArgumentParser( description='Assignment 1: Map directions.', epilog = 'If SERIALPORT is not specified, stdin/stdout are used.') parser.add_argument('-s', '--serial', help='path to serial port', dest='serialport', default=None) parser.add_argument('-v', dest='verbose', help='verbose', action='store_true') parser.add_argument('-g', '--graph', help='path to graph (DEFAULT = " edmonton-roads-2.0.1.txt")', dest='graphname', default=' edmonton-roads-2.0.1.txt') return parser.parse_args() if __name__ == '__main__': main() <file_sep>/client/GTPA010.h #ifndef _GTPA010_H_ #define _GTPA010_H_ #include "Sensors.h" #include "TinyGPS.h" #include "TimerThree.h" // GPS Setup //#define DEBUG_GPS #define GPS_FIX_PIN 11 #define GPS_ENABLE_PIN 12 #define GPS_BAUD_RATE 4800 #define FAKE_GPS_DATA 1 typedef struct gpsData { long int lat; // Stores the latitude as a long int as specified by the TinyGPS librairy long int lon; // Stores the longitude as a long int as specified by the TinyGPS librairy unsigned long int age; // Checksum information // Date/Time information int year; byte month; byte day; byte hour; byte minute; byte second; byte hundredths; }; class GTPA010 : Sensors { public: static void printData(); // Designed to print the data onto serial static void readData(); // Executes the reading procedures from the sensor static gpsData* getData(); // Gets the address of the data struct #if FAKE_GPS_DATA static void fakeData(); // Used in testing, designed to replicate GPS data for the purpose of validating other functions, not included in production class, defined in Config #endif static void begin(); // Begin sensor initilization routines static bool check(); // A validity check for the sensor, if true, its reporting a valid response, if false, then response is invalid static void gpsCheck(); // A function called by an inturput service to check GPS lock status static volatile bool gpsLock; // The indicator for a valid lock against a 2D/3D lock private: static gpsData data; // Used to store the data in the gpsData struct static bool newData; // A private variable determining if the data has been refreshed static const long int timer_ticks = 1000000; // The length of ticks inbetween checks of the GPS, dependant on the devices clock speed static char dataBuffer; // Char buffer for the inputed data static volatile bool gpsValue; // The value read from the GPS 2D/3D fix pin }; #endif <file_sep>/client/assert13.h #ifndef _assert13_h #define _assert13_h void assert13(int invariant, int code); #endif <file_sep>/client/map.h /* Definition of functions and structures for dealing with the map. Longitude and latitude to screen coordinate conversions, for instance. */ #ifndef MAP_H #define MAP_H #include <stdint.h> #include <image_handling.h> #include <SD.h> #include <SPI.h> // the number of the current map being displayed extern uint8_t current_map_num; // the current association of the map with the screen window extern uint16_t screen_map_x; extern uint16_t screen_map_y; // radius of cursor dot. extern const uint16_t dot_radius; // the size of the map display window extern const uint16_t display_window_width; extern const uint16_t display_window_height; // the current position of the cursor on the map extern uint16_t cursor_map_x; extern uint16_t cursor_map_y; // the current approximate lat and lon of the cursor extern int32_t cursor_lon; extern int32_t cursor_lat; extern const uint8_t num_maps; extern uint16_t map_x_limit[6]; extern uint16_t map_y_limit[6]; typedef struct { int32_t N; // lattitude of NW corner int32_t W; // longitude of NW corner int32_t S; // lattitude of SE corner int32_t E; // longitude of SE corner } map_box_t; // a coordinate point for a path typedef struct { int32_t lat; int32_t lon; } coord_t; extern map_box_t map_box[]; // conversion routines between lat and long and map pixel coordinates int32_t x_to_longitude(char map_num, int32_t map_x); int32_t y_to_latitude(char map_num, int32_t map_y); int32_t longitude_to_x(char map_num, int32_t map_longitude); int32_t latitude_to_y(char map_num, int32_t map_lattitude); uint8_t zoom_in(); uint8_t zoom_out(); uint8_t set_zoom(); uint8_t is_gps_visible(); void initialize_map(); void draw_map_screen(); uint8_t get_cursor_screen_x_y(uint16_t *cursor_screen_x,uint16_t *cursor_screen_y); void draw_cursor(); void erase_cursor(); void draw_gps_dot(); void erase_gps(); void draw_compass(); void draw_gps_dot(); void move_window_to(int16_t x, int16_t y); void move_window(int32_t lon, int32_t lat); void move_cursor_to(int16_t x, int16_t y); void move_cursor_by(int16_t dx, int16_t dy); extern volatile uint8_t shared_new_map_num; #endif <file_sep>/client/path.h #ifndef PATH_H #define PATH_H extern int16_t path_errno; extern int16_t target_dir; extern int8_t has_path; uint8_t read_path(uint16_t *length_p, coord_t *path_p[]); void draw_path(uint16_t length, coord_t path[]); coord_t * get_prev_destination(); uint8_t is_coord_visible(coord_t point); #endif <file_sep>/client/path.cpp #include <Arduino.h> #include <Adafruit_ST7735.h> #include <SD.h> #include <mem_syms.h> #include <math.h> #include "map.h" #include "serial_handling.h" #include "ledon.h" #include "LSM303.h" // #define DEBUG_PATH /* path routine error code 0 no error 1 */ int16_t path_errno; int16_t target_dir = 0; int8_t has_path = 0; extern Adafruit_ST7735 tft; // Keep track of the last requested path uint16_t * last_path_len = 0; coord_t ** last_path_p = 0; // read a path from the serial port and return the length of the // path and a pointer to the array of coordinates. That array should // be freed later. // Returns 1 if the call was successful, 0 if not. uint8_t read_path(uint16_t *length_p, coord_t *path_p[]) { // the line to be read, and it size const uint8_t line_size = 40; char line[line_size]; uint16_t bytes_read; // the field extracted const uint8_t field_size = 20; char field[field_size]; uint16_t field_index; int32_t field_value; *length_p = 0; *path_p = 0; // reset the error code path_errno = 0; while ( ! Serial.available() ) { }; uint16_t max_path_size = (AVAIL_MEM - 256) / sizeof(coord_t); #ifdef DEBUG_PATH Serial.print("Max path length "); Serial.println(max_path_size); #endif bytes_read = serial_readline(line, line_size); // read the number of points, first field field_index = 0; field_index = string_read_field(line, field_index, field, field_size, " "); field_value = string_get_int(field); #ifdef DEBUG_PATH Serial.print("Path length "); Serial.print(field_value); Serial.println(); #endif // do a consistency check if ( field_value < 0 || max_path_size < field_value ) { path_errno = 1; return 0; } uint8_t tmp_length = field_value; *length_p = tmp_length; // allocate the storage, see if we got it. coord_t *tmp_path = (coord_t *) malloc( tmp_length * sizeof(coord_t)); if ( !tmp_path ) { path_errno = 2; has_path = 0; return 0; } *path_p = tmp_path; while ( tmp_length > 0 ) { bytes_read = serial_readline(line, line_size); // read the number of points, first field field_index = 0; field_index = string_read_field(line, field_index, field, field_size, " "); tmp_path->lat = string_get_int(field); field_index = string_read_field(line, field_index, field, field_size, " "); tmp_path->lon = string_get_int(field); tmp_length--; tmp_path++; } // Give direction to follow from first to second node if (*length_p >= 2) { coord_t s_coord = (*path_p)[0]; coord_t e_coord = (*path_p)[1]; target_dir = (int)(atan2(e_coord.lon-s_coord.lon, e_coord.lat-s_coord.lat)*180/PI - 180) % 360; #ifdef DEBUG_GLASSES map_to_glasses(target_dir); #endif } last_path_p = path_p; last_path_len = length_p; has_path = 1; return 1; } uint8_t is_coord_visible(coord_t point) { // figure out the x and y positions on the current map of the // given point uint16_t point_map_y = latitude_to_y(current_map_num, point.lat); uint16_t point_map_x = longitude_to_x(current_map_num, point.lon); uint8_t r = screen_map_x < point_map_x && point_map_x < screen_map_x + display_window_width && screen_map_y < point_map_y && point_map_y < screen_map_y + display_window_height; return r; } coord_t * get_prev_destination() { if (!last_path_len || !*last_path_len) return 0; return &(*last_path_p[*last_path_len-1]); } void draw_path(uint16_t length, coord_t path[]) { #ifdef DEBUG_PATH Serial.println("Drawing path!"); #endif for (int i = 0; i < (length - 1); i++) { #ifdef DEBUG_PATH Serial.println("Drawing line"); #endif int16_t startx = longitude_to_x(current_map_num, path[i].lon) - screen_map_x; int16_t starty = latitude_to_y(current_map_num, path[i].lat) - screen_map_y; int16_t endx = longitude_to_x(current_map_num, path[i+1].lon) - screen_map_x; int16_t endy = latitude_to_y(current_map_num, path[i+1].lat) - screen_map_y; tft.drawLine(startx, starty, endx, endy, BLUE); } } <file_sep>/server/testserver.py import doctest import server doctest.testmod(server) <file_sep>/client/ledon.h #ifndef LEDON_H #define LEDON_H #undef DEBUG_GLASSES void map_to_glasses(int heading); #endif <file_sep>/client/map.cpp #include <Arduino.h> #include <Adafruit_GFX.h> // Core graphics library #include <Adafruit_ST7735.h> // Hardware-specific library #include <math.h> #include "lcd_image.h" #include "map.h" #include "LSM303.h" #include "GTPA010.h" #include "ledon.h" #include "path.h" // #define DEBUG /* Module to handle the display of map, cursor, and path information on the screen. It assumes that all of the map information has been placed on the SD card as .lcd 16 bit rgb files, and that the tile dimensions and lat-long positions match that of the data structures below. All coordinates are in usual graphics corrdinates, that is, the top left is (0,0) and the bottom right is (SCREEN_WIDTH-1,SCREEN_HEIGHT-1) At any given time, the map image shown on the display is a window onto a bigger map tile. The top-left position of the display corrsponds to position (screen_map_x, screen_map_y) in the map tile. The cursor can be anywhere on the map, so it may not be visible in the current display window. It is visible if screen_map_x < */ extern Adafruit_ST7735 tft; extern LSM303 compass; // the number of the current map being displayed uint8_t current_map_num; // the size of the map display window const uint16_t display_window_width = 128; const uint16_t display_window_height = 160; // the current association of the map with the display window uint16_t screen_map_x; uint16_t screen_map_y; // radius of cursor dot. const uint16_t dot_radius = 2; // the current position of the cursor on the map uint16_t cursor_map_x; uint16_t cursor_map_y; // the current approximate lat and lon of the cursor int32_t cursor_lon; int32_t cursor_lat; // the current position of the gps dot on map uint16_t gps_map_y; uint16_t gps_map_x; // the approximate lat and lon of gps dot int32_t gps_lon = 0; int32_t gps_lat = 0; const uint8_t num_maps = 6; /* Map limits: a pixel position on map i must lie in the interval 0 <= x <= map_x_limit[i] 0 <= y <= map_y_limit[i] */ uint16_t map_x_limit[6] = { 511, 1023, 2047, 4095, 8191, 16383}; uint16_t map_y_limit[6] = { 511, 1023, 2047, 4095, 8191, 16383}; lcd_image_t map_tiles[] = { { "yeg-1.lcd", 512, 512, }, { "yeg-2.lcd", 1024, 1024, }, { "yeg-3.lcd", 2048, 2048, }, { "yeg-4.lcd", 4096, 4096, }, { "yeg-5.lcd", 8192, 8192, }, { "yeg-6.lcd", 16384, 16384, }, }; map_box_t map_box[] = { { // map 0 zoom 11 (int32_t) 5364463, // 53.6446378248565 (int32_t) -11373047, // -113.73046875 (int32_t) 5343572, // 53.4357192066942 (int32_t) -11337891, // -113.37890625 }, { // map 1 zoom 12 (int32_t) 5364464, // 53.6446378248565 (int32_t) -11373047, // -113.73046875 (int32_t) 5343572, // 53.4357192066942 (int32_t) -11337891, // -113.37890625 }, { // map 2 zoom 13 (int32_t) 5361858, // 53.6185793648952 (int32_t) -11368652, // -113.6865234375 (int32_t) 5340953, // 53.4095318530864 S (int32_t) -11333496, // -113.3349609375 E }, { // map 3 zoom 14 (int32_t) 5360554, // 53.605544099238 (int32_t) -11368652, // -113.6865234375 (int32_t) 5339643, // 53.396432127096 (int32_t) -11333496, // -113.3349609375 }, { // map 4 zoom 15 (int32_t) 5360554, // 53.605544099238 (int32_t) -11367554, // -113.675537109375 (int32_t) 5339643, // 53.396432127096 (int32_t) -11332397, // -113.323974609375 }, { // map 5 zoom 16 (int32_t) 5360228, // 53.6022846540113 (int32_t) -11367554, // -113.675537109375 (int32_t) 5339316, // 53.3931565653804 (int32_t) -11332397, // -113.323974609375 }, }; int compass_x = 20; int compass_y = 20; int compass_r = 8; int compass_old = 0; int compass_drawn = 0; // conversion routines between lat and long and map pixel coordinates int32_t x_to_longitude(char map_num, int32_t map_x) { return map(map_x, 0, map_x_limit[map_num], map_box[map_num].W, map_box[map_num].E); } int32_t y_to_latitude(char map_num, int32_t map_y) { return map(map_y, 0, map_y_limit[map_num], map_box[map_num].N, map_box[map_num].S); } int32_t longitude_to_x(char map_num, int32_t map_longitude) { return map(map_longitude, map_box[map_num].W, map_box[map_num].E, 0, map_x_limit[map_num]); } int32_t latitude_to_y(char map_num, int32_t map_latitude) { return map(map_latitude, map_box[map_num].N, map_box[map_num].S, 0, map_y_limit[map_num]); } // zoom in and out routines that are used in interrupt handlers to // change the shared version of the map_num. In order to maintain consistent // updates, the shared value should only be sampled at well-defined points. volatile uint8_t shared_new_map_num = 2; void initialize_map() { cursor_lon = 0; cursor_lat = 0; cursor_map_x = 0; cursor_map_y = 0; screen_map_x = 0; screen_map_y = 0; // set the actual map number from the shared version // this should be atomic and thus can be done outside a critical section current_map_num = shared_new_map_num; } uint8_t zoom_in() { if ( shared_new_map_num < num_maps-1) { shared_new_map_num++; } return shared_new_map_num; } uint8_t zoom_out() { if ( shared_new_map_num > 0 ) { shared_new_map_num--; } return shared_new_map_num; } uint8_t set_zoom() { // set the actual map number from the shared version // this should be atomic and thus can be done outside a critical section current_map_num = shared_new_map_num; // At this point all of the cursor and map information is invalidated // except for the cursor lat and long, which is the only thing that // survives zooming. So set the map cursor position on the new map to // roughly correspond to lat and lon position that was determined by the // previous map. cursor_map_x = longitude_to_x(current_map_num, cursor_lon); cursor_map_y = latitude_to_y(current_map_num, cursor_lat); return current_map_num; } void draw_compass() { compass.read(); int compass_dir = compass.heading() + 90; // Avoid updating if (abs(compass_dir - compass_old) < 5 && compass_drawn == 1) return; compass_old = compass_dir; compass_drawn = 1; tft.fillCircle(compass_x, compass_y, compass_r, BLUE); int tip_x = compass_x + compass_r * cos(compass_dir*PI/180); int tail_x = compass_x - compass_r * cos(compass_dir*PI/180); int tip_y = compass_y + compass_r * sin(compass_dir*PI/180); int tail_y = compass_y - compass_r * sin(compass_dir*PI/180); int a1_x = compass_x + (compass_r - 5) * cos((compass_dir-90)*PI/180); int a1_y = compass_y + (compass_r - 5) * sin((compass_dir-90)*PI/180); int a2_x = compass_x + (compass_r - 5) * cos((compass_dir+90)*PI/180); int a2_y = compass_y + (compass_r - 5) * sin((compass_dir+90)*PI/180); // Arrow body tft.drawLine(tip_x, tip_y, tail_x, tail_y, RED); // Arrow head tft.drawLine(tip_x, tip_y, a1_x, a1_y, RED); tft.drawLine(tip_x, tip_y, a2_x, a2_y, RED); } /** * Draw the GPS location on the map * * Display a warning message if a GPS error occurs */ void draw_gps_dot() { //Get the GPS data gpsData* gdata; GTPA010::readData(); gdata = GTPA010::getData(); // Erase old dot if position changed if ((gdata->lat != gps_lat || gdata->lon != gps_lon) && is_gps_visible()) { erase_gps(); } if (gdata->lat != gps_lat || gdata->lon != gps_lon) { coord_t * dest = get_prev_destination(); } gps_lat = gdata->lat; gps_lon = gdata->lon; //Take the lat, lon, map to pixels gps_map_x = longitude_to_x(current_map_num, gps_lon); gps_map_y = latitude_to_y(current_map_num, gps_lat); #ifdef DEBUG_GPS GTPA010::printData(); #endif if (is_gps_visible()) tft.fillCircle(gps_map_x - screen_map_x, gps_map_y - screen_map_y, dot_radius, BLUE); } void draw_map_screen() { #ifdef DEBUG // Want to display a small message saying that we are redrawing the map! tft.fillRect(78, 148, 50, 12, GREEN); tft.setTextSize(1); tft.setTextColor(MAGENTA); tft.setCursor(80, 150); tft.setTextSize(1); tft.println("DRAWING..."); #endif lcd_image_draw(&map_tiles[current_map_num], &tft, screen_map_x, screen_map_y, 0, 0, 128, 160); compass_drawn = 0; } uint8_t is_gps_visible() { uint8_t r = screen_map_x < gps_map_x && gps_map_x < screen_map_x + display_window_width && screen_map_y < gps_map_y && gps_map_y < screen_map_y + display_window_height; return r; } uint8_t is_cursor_visible() { uint8_t r = screen_map_x < cursor_map_x && cursor_map_x < screen_map_x + display_window_width && screen_map_y < cursor_map_y && cursor_map_y < screen_map_y + display_window_height; #ifdef IGNORE if ( !r ) { Serial.print("cv: "); Serial.print(screen_map_x); Serial.print(" "); Serial.print(screen_map_y); Serial.print(" "); Serial.print(cursor_map_x); Serial.print(" "); Serial.print(cursor_map_y); Serial.println(); } #endif return r; } uint8_t get_gps_screen_x_y( uint16_t *gps_screen_x,uint16_t *gps_screen_y) { if ( is_gps_visible ) { *gps_screen_x = gps_map_x - display_window_width; *gps_screen_y = gps_map_y - display_window_height; return 1; } // not visible return 0; } uint8_t get_cursor_screen_x_y( uint16_t *cursor_screen_x,uint16_t *cursor_screen_y) { if ( is_cursor_visible ) { *cursor_screen_x = cursor_map_x - screen_map_x; *cursor_screen_y = cursor_map_y - screen_map_y; return 1; } // not visible return 0; } void draw_cursor() { // the current position of the cursor on the screen, if visible uint16_t cursor_screen_x; uint16_t cursor_screen_y; if ( get_cursor_screen_x_y(&cursor_screen_x, &cursor_screen_y) ) { cursor_screen_x = cursor_map_x - screen_map_x; cursor_screen_y = cursor_map_y - screen_map_y; tft.fillCircle(cursor_screen_x, cursor_screen_y, dot_radius, RED); } } void erase_gps() { uint16_t gps_screen_x; uint16_t gps_screen_y; if ( get_gps_screen_x_y(&gps_screen_x, &gps_screen_y) ) { // Redraw the map on top of the current cursor position lcd_image_draw(&map_tiles[current_map_num], &tft, gps_map_x - dot_radius, gps_map_y - dot_radius, gps_screen_x - dot_radius, gps_screen_y - dot_radius, 2 * dot_radius + 1, 2 * dot_radius + 1); } } void erase_cursor() { uint16_t cursor_screen_x; uint16_t cursor_screen_y; if ( get_cursor_screen_x_y(&cursor_screen_x, &cursor_screen_y) ) { // Redraw the map on top of the current cursor position lcd_image_draw(&map_tiles[current_map_num], &tft, cursor_map_x - dot_radius, cursor_map_y - dot_radius, cursor_screen_x - dot_radius, cursor_screen_y - dot_radius, 2 * dot_radius + 1, 2 * dot_radius + 1); } } void move_to_gps() { gpsData * gData = GTPA010::getData(); move_window(gData->lon - display_window_width/2, gData->lat - display_window_height/2); } void move_window(int32_t lon, int32_t lat) { // Shift the current window to have lon and lat in top left corner #ifdef DEBUG Serial.println("move_window!"); #endif screen_map_x = longitude_to_x(current_map_num, lon); screen_map_y = latitude_to_y(current_map_num, lat); move_window_to(screen_map_x, screen_map_y); } void move_window_to(int16_t x, int16_t y) { // Shift the current window to have x y in top left corner // cursor does not move #ifdef DEBUG Serial.println("move_window_by!"); #endif // constrain move screen_map_x = constrain(x, 0, map_x_limit[current_map_num] - display_window_width); screen_map_y = constrain(y, 0, map_y_limit[current_map_num] - display_window_height); // Force cursor to center of window move_cursor_to(screen_map_x + display_window_width/2, screen_map_y + display_window_height/2); } void move_cursor_by(int16_t dx, int16_t dy) { move_cursor_to(cursor_map_x + dx, cursor_map_y + dy); } void move_cursor_to(int16_t x, int16_t y) { #ifdef DEBUG Serial.print("Moving cursor to: "); Serial.print(x); Serial.print(" "); Serial.println(y); #endif // move cursor on map cursor_map_x = constrain(x, 0, map_x_limit[current_map_num]); cursor_map_y = constrain(y, 0, map_y_limit[current_map_num]); // then update cursor lat and long - we need this because that is the // only thing that will survive zooming. cursor_lon = x_to_longitude(current_map_num, cursor_map_x); cursor_lat = y_to_latitude(current_map_num, cursor_map_y); }
2db5795445ea5973474f615a03b7fb82ddc19744
[ "Markdown", "Python", "Text", "C", "C++" ]
29
Python
stephenjust/arduino-gps-glasses
1b60f4fcb687f8b054bf398e7e47a921c01de90c
49b507bfb16c8f06846f02a52f9e5bec79d4b9b0
refs/heads/master
<file_sep><?php declare(strict_types=1); namespace HappyInc\Worker; interface ContextData { public function __construct(); } <file_sep><?php declare(strict_types=1); namespace HappyInc\Worker\Signaller; use PHPUnit\Framework\TestCase; /** * @internal * @covers \HappyInc\Worker\Signaller\FileSignaller * * @small */ final class FileSignallerTest extends TestCase { public function testNoSignalReceivedWhenNotSent(): void { $channel = 'channel'; $signaller = new FileSignaller(); $listener = $signaller->createListener($channel); $signal = $listener(); $this->assertFalse($signal); } public function testNoSignalReceivedWhenSentBeforeCreatingListener(): void { $channel = 'channel'; $signaller = new FileSignaller(); $signaller->sendSignal($channel); $signal = $signaller->createListener($channel)(); $this->assertFalse($signal); } public function testSignalReceivedWhenSent(): void { $channel = 'channel'; $signaller = new FileSignaller(); $listener = $signaller->createListener($channel); $signaller->sendSignal($channel); $signal = $listener(); $this->assertTrue($signal); } } <file_sep><?php declare(strict_types=1); namespace HappyInc\Worker\Signaller; final class FileSignaller implements Signaller { private const MAX_LENGTH = 26; private string $dir; public function __construct(?string $dir = null) { $this->dir = rtrim($dir ?? sys_get_temp_dir(), \DIRECTORY_SEPARATOR); } public function sendSignal(string $channel): void { if (!is_dir($this->dir) && !@mkdir($this->dir, 0777, true)) { throw new \RuntimeException(sprintf('Failed to create directory "%s".', $this->dir)); } $file = $this->channelFile($channel); if (false === $handle = @fopen($this->channelFile($channel), 'cb')) { throw new \RuntimeException(sprintf('Failed to open file "%s" for writing.', $file)); } if (!flock($handle, LOCK_EX)) { throw new \RuntimeException(sprintf('Failed to acquire an exclusive lock for file "%s".', $file)); } ftruncate($handle, 0); fwrite($handle, (new \DateTimeImmutable('now', new \DateTimeZone('UTC')))->format('Y-m-d H:i:s.u')); fflush($handle); flock($handle, LOCK_UN); fclose($handle); } public function createListener(string $channel): callable { $file = $this->channelFile($channel); $initialValue = @file_get_contents($file, false, null, 0, self::MAX_LENGTH); return static fn (): bool => $initialValue !== @file_get_contents($file, false, null, 0, self::MAX_LENGTH); } private function channelFile(string $channel): string { return sprintf('%s/%s.worker_stop_signaller_channel.tmp', $this->dir, md5($channel)); } } <file_sep><?php declare(strict_types=1); namespace HappyInc\Worker\ProcessSignal; use HappyInc\Worker\Context; use PHPUnit\Framework\TestCase; /** * @internal * @covers \HappyInc\Worker\ProcessSignal\ProcessSignalExtension * * @small */ final class ProcessSignalExtensionTest extends TestCase { public function testNotStoppedWhenDifferentSignalSent(): void { $context = new Context(); $extension = new ProcessSignalExtension([SIGINT]); pcntl_signal(SIGUSR1, SIG_IGN); $extension->started($context); posix_kill(posix_getpid(), SIGUSR1); $stop = $extension->jobDone($context, 0); $this->assertNull($stop); } public function testStoppedWhenSignalSent(): void { $context = new Context(); $extension = new ProcessSignalExtension([SIGINT]); $extension->started($context); posix_kill(posix_getpid(), SIGINT); $stop = $extension->jobDone($context, 0); $this->assertNotNull($stop); } } <file_sep><?php declare(strict_types=1); namespace HappyInc\Worker\MemoryLimit; use PHPUnit\Framework\TestCase; /** * @internal * @covers \HappyInc\Worker\MemoryLimit\MemoryLimit * * @small */ final class MemoryLimitTest extends TestCase { public function testFromBytes(): void { $limit = MemoryLimit::fromBytes(16); $this->assertSame(16, $limit->bytes); } public function testFromMegaBytes(): void { $limit = MemoryLimit::fromMegabytes(1); $this->assertSame(1048576, $limit->bytes); } /** * @dataProvider fromIniMemoryLimitProvider */ public function testFromIniMemoryLimit(string $iniLimit, float $share, int $expectedLimit): void { $originalIniLimit = ini_get('memory_limit'); ini_set('memory_limit', $iniLimit); $limit = MemoryLimit::fromIniMemoryLimit($share); $this->assertSame($expectedLimit, $limit->bytes); ini_set('memory_limit', $originalIniLimit); } /** * @psalm-return \Generator<int, array{string, float, int}> */ public function fromIniMemoryLimitProvider(): \Generator { yield ['-1', 1, 100 * 1024 ** 2]; yield ['10485760', 1, 10485760]; yield ['10485760', 0.1, 1048576]; yield ['10240k', 1, 10 * 1024 ** 2]; yield ['10240K', 1, 10 * 1024 ** 2]; yield ['10m', 1, 10 * 1024 ** 2]; yield ['10M', 1, 10 * 1024 ** 2]; yield ['1g', 1, 1024 ** 3]; yield ['1G', 1, 1024 ** 3]; } } <file_sep><?php declare(strict_types=1); namespace HappyInc\Worker\Signaller; use HappyInc\Worker\ContextData; /** * @internal * @psalm-internal \HappyInc\Worker\Signaller */ final class SignallerContextData implements ContextData { /** * @var callable * @psalm-var callable(): bool */ public $listener; public function __construct() { $this->listener = static fn (): bool => false; } } <file_sep><?php declare(strict_types=1); namespace HappyInc\Worker\Sleep; /** * @psalm-immutable */ final class SleepInterval { /** * @param positive-int $microseconds */ private function __construct(public int $microseconds) { } /** * @psalm-pure */ public static function fromMicroseconds(int $microseconds): self { if ($microseconds <= 0) { throw new \InvalidArgumentException('Sleep interval must be zero or positive.'); } return new self($microseconds); } /** * @psalm-pure */ public static function fromMilliseconds(int $milliseconds): self { if ($milliseconds <= 0) { throw new \InvalidArgumentException('Sleep interval must be zero or positive.'); } return new self($milliseconds * 1000); } /** * @psalm-pure */ public static function fromSeconds(int $seconds): self { if ($seconds <= 0) { throw new \InvalidArgumentException('Sleep interval must be zero or positive.'); } return new self($seconds * 1_000_000); } } <file_sep># Happy Inc Worker ```php use HappyInc\Worker\MemoryLimit\MemoryLimit; use HappyInc\Worker\MemoryLimit\MemoryLimitExtension; use HappyInc\Worker\ProcessSignal\ProcessSignalExtension; use HappyInc\Worker\Signaller\FileSignaller; use HappyInc\Worker\Signaller\SignallerExtension; use HappyInc\Worker\Sleep\SleepExtension; use HappyInc\Worker\Sleep\SleepInterval; use HappyInc\Worker\Worker; use Psr\Log\LogLevel; $signaller = new FileSignaller('/some/dir'); $worker = new Worker([ new MemoryLimitExtension( MemoryLimit::fromIniMemoryLimit(0.7), // stop when allocated memory reaches 70% of php.ini memory_limit $systemLogger, LogLevel::CRITICAL, // optionally log when memory limit is reached with the specified level ), new ProcessSignalExtension([SIGINT]), // gracefully stop the worker when Ctrl+C is pressed in the terminal new SignallerExtension('mailing_worker', $signaller), // allows to send a stop signal from a different process new SleepExtension(SleepInterval::fromSeconds(1)), // sleep 1 second after each job ]); $worker->workOn(function (): void { // some job }); $signaller->sendSignal('mailing_worker'); // stop all workers, listening to the "mailing_worker" channel via the SignallerExtension ``` <file_sep><?php declare(strict_types=1); namespace HappyInc\Worker; final class Worker { /** * @var WorkerStartedExtension[] */ private array $startedExtensions = []; /** * @var WorkerJobDoneExtension[] */ private array $jobDoneExtensions = []; /** * @var WorkerStoppedExtension[] */ private array $stoppedExtensions = []; /** * @psalm-param iterable<WorkerStartedExtension|WorkerJobDoneExtension|WorkerStoppedExtension> $extensions */ public function __construct(iterable $extensions = []) { foreach ($extensions as $extension) { if ($extension instanceof WorkerStartedExtension) { $this->startedExtensions[] = $extension; } if ($extension instanceof WorkerJobDoneExtension) { $this->jobDoneExtensions[] = $extension; } if ($extension instanceof WorkerStoppedExtension) { $this->stoppedExtensions[] = $extension; } } } /** * @psalm-param callable(Context, int): void $job */ public function workOn(callable $job): Result { $context = new Context(); foreach ($this->startedExtensions as $extension) { $extension->started($context); } $stop = null; for ($jobIndex = 0;; ++$jobIndex) { $job($context, $jobIndex); foreach ($this->jobDoneExtensions as $extension) { $stop = $extension->jobDone($context, $jobIndex); if (null !== $stop) { break 2; } } } $result = new Result($jobIndex + 1, $stop->reason ?? null); foreach ($this->stoppedExtensions as $extension) { $extension->stopped($context, $result); } return $result; } } <file_sep><?php declare(strict_types=1); namespace HappyInc\Worker; interface WorkerJobDoneExtension { public function jobDone(Context $context, int $jobIndex): ?Stop; } <file_sep><?php declare(strict_types=1); namespace HappyInc\Worker\SleepInterval; use HappyInc\Worker\Sleep\SleepInterval; use PHPUnit\Framework\TestCase; /** * @internal * @covers \HappyInc\Worker\Sleep\SleepInterval * * @small */ final class SleepIntervalTest extends TestCase { public function testFromMicroseconds(): void { $interval = SleepInterval::fromMicroseconds(1); $this->assertSame(1, $interval->microseconds); } public function testFromMilliseconds(): void { $interval = SleepInterval::fromMilliseconds(1); $this->assertSame(1000, $interval->microseconds); } public function testFromSeconds(): void { $interval = SleepInterval::fromSeconds(1); $this->assertSame(1_000_000, $interval->microseconds); } } <file_sep><?php declare(strict_types=1); namespace HappyInc\Worker; final class Context { /** * @psalm-var array<class-string<ContextData>, ContextData> */ private array $data = []; /** * @template T of ContextData * @psalm-param class-string<T> $class * @psalm-return T */ public function dataOf(string $class): ContextData { /** @psalm-var T */ return $this->data[$class] ??= new $class(); } } <file_sep><?php declare(strict_types=1); namespace HappyInc\Worker; interface WorkerStartedExtension { public function started(Context $context): void; } <file_sep><?php declare(strict_types=1); namespace HappyInc\Worker\MemoryLimit; use HappyInc\Worker\Context; use HappyInc\Worker\Stop; use HappyInc\Worker\WorkerJobDoneExtension; use Psr\Log\LoggerInterface; use Psr\Log\LogLevel; use Psr\Log\NullLogger; final class MemoryLimitExtension implements WorkerJobDoneExtension { private MemoryLimit $limit; private LoggerInterface $logger; /** * @psalm-var LogLevel::* */ private string $logLevel; /** * @psalm-param LogLevel::* $logLevel */ public function __construct(MemoryLimit $limit, ?LoggerInterface $logger = null, string $logLevel = LogLevel::WARNING) { $this->limit = $limit; $this->logger = $logger ?? new NullLogger(); $this->logLevel = $logLevel; } public function jobDone(Context $context, int $jobIndex): ?Stop { $allocatedMemory = memory_get_usage(true); if ($allocatedMemory <= $this->limit->bytes) { return null; } $this->logger->log( $this->logLevel, 'Allocated memory of {allocated} bytes exceeded the worker limit of {limit} bytes.', [ 'allocated' => $allocatedMemory, 'limit' => $this->limit->bytes, ] ); return new Stop(sprintf( 'Allocated memory of %d bytes exceeded the worker limit of %d bytes.', $allocatedMemory, $this->limit->bytes )); } } <file_sep><?php declare(strict_types=1); namespace HappyInc\Worker\Sleep; use HappyInc\Worker\Context; use HappyInc\Worker\Stop; use HappyInc\Worker\WorkerJobDoneExtension; final class SleepExtension implements WorkerJobDoneExtension { private SleepInterval $interval; public function __construct(SleepInterval $interval) { $this->interval = $interval; } public function jobDone(Context $context, int $jobIndex): ?Stop { usleep($this->interval->microseconds); return null; } } <file_sep><?php declare(strict_types=1); namespace HappyInc\Worker\ProcessSignal; use HappyInc\Worker\Context; use HappyInc\Worker\Stop; use HappyInc\Worker\WorkerJobDoneExtension; use HappyInc\Worker\WorkerStartedExtension; final class ProcessSignalExtension implements WorkerStartedExtension, WorkerJobDoneExtension { /** * @psalm-var non-empty-list<int> */ private array $signals; /** * @psalm-param non-empty-list<int> $signals */ public function __construct(array $signals) { $this->signals = $signals; } public function started(Context $context): void { $data = $context->dataOf(ProcessSignalContextData::class); $handler = static function (int $signal) use ($data): void { $data->receivedSignal = $signal; }; foreach ($this->signals as $signal) { pcntl_signal($signal, $handler); } } public function jobDone(Context $context, int $jobIndex): ?Stop { pcntl_signal_dispatch(); $data = $context->dataOf(ProcessSignalContextData::class); if (null === $data->receivedSignal) { return null; } return new Stop(sprintf('Process received signal %d.', $data->receivedSignal)); } } <file_sep><?php declare(strict_types=1); namespace HappyInc\Worker; interface WorkerStoppedExtension { public function stopped(Context $context, Result $result): void; } <file_sep><?php declare(strict_types=1); namespace HappyInc\Worker\MemoryLimit; use HappyInc\Worker\Context; use PHPUnit\Framework\TestCase; /** * @internal * @covers \HappyInc\Worker\MemoryLimit\MemoryLimitExtension * * @small */ final class MemoryLimitExtensionTest extends TestCase { public function testNotStoppedWhenMemoryLimitNotReached(): void { $context = new Context(); $limit = MemoryLimit::fromBytes(memory_get_usage(true) + 1024); $extension = new MemoryLimitExtension($limit); $stop = $extension->jobDone($context, 0); $this->assertNull($stop); } public function testStoppedWhenMemoryLimitReached(): void { $context = new Context(); $limit = MemoryLimit::fromBytes(memory_get_usage() - 1024); $extension = new MemoryLimitExtension($limit); $stop = $extension->jobDone($context, 0); $this->assertNotNull($stop); } } <file_sep><?php declare(strict_types=1); namespace HappyInc\Worker\Signaller; use HappyInc\Worker\Context; use HappyInc\Worker\Stop; use HappyInc\Worker\WorkerJobDoneExtension; use HappyInc\Worker\WorkerStartedExtension; final class SignallerExtension implements WorkerStartedExtension, WorkerJobDoneExtension { private string $channel; private Signaller $signaller; public function __construct(string $channel, ?Signaller $signaller = null) { $this->channel = $channel; $this->signaller = $signaller ?? new FileSignaller(); } public function started(Context $context): void { $data = $context->dataOf(SignallerContextData::class); $data->listener = $this->signaller->createListener($this->channel); } public function jobDone(Context $context, int $jobIndex): ?Stop { $data = $context->dataOf(SignallerContextData::class); if (($data->listener)()) { return new Stop(sprintf('A stop signal was received from channel "%s".', $this->channel)); } return null; } } <file_sep><?php declare(strict_types=1); namespace HappyInc\Worker; use PHPUnit\Framework\TestCase; /** * @internal * @covers \HappyInc\Worker\Worker * * @small */ final class WorkerTest extends TestCase { public function testCallSequence(): void { $extension = new class() implements WorkerStartedExtension, WorkerJobDoneExtension, WorkerStoppedExtension { public array $callsSequence = []; public function started(Context $context): void { $this->callsSequence[] = 'started'; } public function jobDone(Context $context, int $jobIndex): ?Stop { $this->callsSequence[] = 'jobDone'; return new Stop(); } public function stopped(Context $context, Result $result): void { $this->callsSequence[] = 'stopped'; } }; (new Worker([$extension]))->workOn(static function () use ($extension): void { $extension->callsSequence[] = 'job'; }); $this->assertSame(['started', 'job', 'jobDone', 'stopped'], $extension->callsSequence); } /** * @psalm-suppress InternalClass */ public function testSameContextPassedAround(): void { $extension = new class() implements WorkerStartedExtension, WorkerJobDoneExtension, WorkerStoppedExtension { public ?Context $context = null; public function started(Context $context): void { $this->context = $context; } public function jobDone(Context $context, int $jobIndex): ?Stop { WorkerTest::assertSame($this->context, $context); return new Stop(); } public function stopped(Context $context, Result $result): void { WorkerTest::assertSame($this->context, $context); } }; (new Worker([$extension]))->workOn(static function (Context $context) use ($extension): void { self::assertSame($extension->context, $context); }); } } <file_sep><?php declare(strict_types=1); namespace HappyInc\Worker; /** * @psalm-immutable */ final class Stop { public ?string $reason; public function __construct(?string $reason = null) { $this->reason = $reason; } } <file_sep><?php declare(strict_types=1); namespace HappyInc\Worker; use PHPUnit\Framework\TestCase; /** * @internal * @covers \HappyInc\Worker\Context * * @small */ final class ContextTest extends TestCase { public function testSameObjectReturned(): void { $context = new Context(); $data = $context->dataOf(ContextDataStub::class); $data2 = $context->dataOf(ContextDataStub::class); $this->assertSame($data, $data2); } } <file_sep><?php declare(strict_types=1); namespace HappyInc\Worker; final class ContextDataStub implements ContextData { public function __construct() { } } <file_sep><?php declare(strict_types=1); require_once __DIR__.'/vendor/autoload.php'; return (new PhpCsFixer\Config()) ->setFinder( PhpCsFixer\Finder::create() ->in([ __DIR__.'/src', __DIR__.'/tests', ]) ->append([ __FILE__, ]) ) ->setRules([ '@PHP71Migration' => true, '@PHP71Migration:risky' => true, '@PhpCsFixer' => true, '@PhpCsFixer:risky' => true, '@PHPUnit60Migration:risky' => true, 'blank_line_before_statement' => [ 'statements' => [ 'case', 'continue', 'declare', 'default', 'return', 'throw', 'try', ], ], 'date_time_immutable' => true, 'final_class' => true, 'fopen_flags' => ['b_mode' => true], 'no_superfluous_phpdoc_tags' => [ 'allow_mixed' => true, 'remove_inheritdoc' => true, ], 'ordered_class_elements' => [ 'order' => [ 'use_trait', 'constant_public', 'constant_protected', 'constant_private', 'property_public_static', 'property_protected_static', 'property_private_static', 'property_public', 'property_protected', 'property_private', 'construct', 'destruct', 'phpunit', 'method_public_static', 'method_protected_static', 'method_private_static', 'magic', 'method_public', 'method_protected', 'method_private', ], ], 'ordered_imports' => ['imports_order' => ['class', 'function', 'const']], 'php_unit_size_class' => true, 'php_unit_strict' => false, 'php_unit_test_case_static_method_calls' => ['call_type' => 'this'], 'phpdoc_add_missing_param_annotation' => false, 'phpdoc_to_comment' => false, 'phpdoc_types_order' => ['null_adjustment' => 'always_last'], 'phpdoc_var_without_name' => false, 'random_api_migration' => false, 'return_assignment' => false, 'single_line_comment_style' => ['comment_types' => ['hash']], 'static_lambda' => true, ]) ; <file_sep><?php declare(strict_types=1); namespace HappyInc\Worker\Signaller; interface Signaller { public function sendSignal(string $channel): void; /** * @psalm-return callable(): bool */ public function createListener(string $channel): callable; } <file_sep><?php declare(strict_types=1); namespace HappyInc\Worker\ProcessSignal; use HappyInc\Worker\ContextData; /** * @internal * @psalm-internal \HappyInc\Worker\ProcessSignal */ final class ProcessSignalContextData implements ContextData { public ?int $receivedSignal = null; public function __construct() { } } <file_sep>VERBOSITY = v: $(eval VERBOSITY := -v) vv: $(eval VERBOSITY := -vv) vvv: $(eval VERBOSITY := -vvv) vendor: composer.json composer install touch vendor test: vendor $(EXEC_PHP) vendor/bin/phpunit $(VERBOSITY) cs: vendor $(EXEC_PHP) vendor/bin/php-cs-fixer fix --allow-risky=yes --dry-run --diff $(VERBOSITY) fixcs: vendor $(EXEC_PHP) vendor/bin/php-cs-fixer fix --allow-risky=yes $(VERBOSITY) psalm: vendor $(EXEC_PHP) vendor/bin/psalm $(file) composer-check-require: vendor $(EXEC_PHP) vendor/bin/composer-require-checker check $(VERBOSITY) composer-unused: vendor composer unused $(VERBOSITY) composer-validate: composer validate $(VERBOSITY) check: test cs psalm composer-check-require composer-unused composer-validate .PHONY: v vv vvv test cs fixcs psalm composer-check-require composer-unused composer-validate check <file_sep><?php declare(strict_types=1); namespace HappyInc\Worker\MemoryLimit; /** * @psalm-immutable */ final class MemoryLimit { private function __construct(public int $bytes) { } /** * @psalm-pure */ public static function fromBytes(int $bytes): self { if ($bytes <= 0) { throw new \InvalidArgumentException(sprintf('Memory limit must be a positive number, got %d bytes.', $bytes)); } return new self($bytes); } /** * @psalm-pure */ public static function fromMegabytes(int $megabytes): self { if ($megabytes <= 0) { throw new \InvalidArgumentException(sprintf('Memory limit must be a positive number, got %d megabytes.', $megabytes)); } return new self($megabytes * 1024 ** 2); } public static function fromIniMemoryLimit(float $share): self { if (!($share > 0 && $share <= 1)) { throw new \InvalidArgumentException(sprintf('Share must be greater than 0 and less than or equal to 1, got %g.', $share)); } $iniLimit = self::parseMemory(ini_get('memory_limit')); if ($iniLimit <= 0) { return self::fromMegabytes(100); } return new self((int) ($iniLimit * $share)); } /** * @psalm-pure */ private static function parseMemory(string $memory): int { if (!preg_match('/^(-?\d+)([tgmk])?$/i', trim($memory), $matches)) { throw new \InvalidArgumentException(sprintf('Unknown memory string format "%s".', $memory)); } $value = (int) $matches[1]; if (!isset($matches[2])) { return $value; } switch (strtolower($matches[2])) { case 't': $value *= 1024; // no break case 'g': $value *= 1024; // no break case 'm': $value *= 1024; // no break case 'k': $value *= 1024; } return $value; } } <file_sep><?php declare(strict_types=1); namespace HappyInc\Worker; /** * @psalm-immutable */ final class Result { public int $jobsDone; public ?string $stoppedReason; public function __construct(int $jobsDone, ?string $stoppedReason) { $this->jobsDone = $jobsDone; $this->stoppedReason = $stoppedReason; } }
029965ca1e617aaa2918498f02e2533576ad7c26
[ "Markdown", "Makefile", "PHP" ]
29
PHP
happy-inc-tech/worker
f1fc7161551ec4b7d8763f7634ce317f3e2ba144
b3ec305223a7e809f9e41337306497d97d459e0a
refs/heads/master
<repo_name>silaslowe/PACER<file_sep>/README.md # PACER Pace calculator with AJAX <file_sep>/vjs.js const submit = document.getElementById('submit'); const output = document.getElementById('output'); submit.addEventListener('click', function (e) { let minuteTime = document.getElementById('minutes').value; // console.log(minuteTime); let secondTime = document.getElementById('seconds').value; // console.log(secondTime); let distance = document.getElementById('distance').value; // console.log(distance); let radioValue = document.querySelector('input[name="exercise"]:checked').value; console.log(radioValue); milePace(minuteTime, secondTime, distance); e.preventDefault(); }); const milePace = (m, s, d) => { const minute = Math.floor(m / d); console.log(m); const minRe = Math.floor((m % d) * 60); let second = Math.floor((parseInt(s) + minRe) / d); if (second.toString().length < 2) { second = `${second}0`; } let pace = `Your pace was a ${minute}:${second} mile!`; output.innerHTML = pace; }; // When the inputs are 1 , 1, .1 the output is 10:60. I need to make the max seconds only 59. // I think I need to make the whole function more modular and use functions as arguments to make it easier to expand the project later. // I need to add alert for no input and add an hours section.
61306f8e3249538fabcad82880203b55db57e42c
[ "Markdown", "JavaScript" ]
2
Markdown
silaslowe/PACER
faab78d57f135c49757ac9f209eeb87c259b47ff
f23d52b07041b950bca193a12e523bf50024e87d
refs/heads/master
<repo_name>dualword/strobe-api<file_sep>/strobe/strobe-core_cpp_.h /* MIT License Copyright (c) 2018 fuzun Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #include <cstring> #include <cstdlib> #include <chrono> inline StrobeCore::StrobeCore(int mode, int phaseSwitchInterval, bool internalFPSCalculation) : StrobeAPI(mode, phaseSwitchInterval), internalFPSCalc(internalFPSCalculation) { fps = 0; timerSnapshot = 0; modeSnapshot = mode; fpsTimerSnapshot = strobeTimer.elapsedMilliseconds(); counterSnapshot = counter.total(); active = true; } inline StrobeCore::~StrobeCore() { } inline bool StrobeCore::isActive(void) { return active; } inline void StrobeCore::disable(void) { active = false; modeSnapshot = strobeMode; setMode(0); } inline void StrobeCore::enable(void) { active = true; strobeMode = modeSnapshot; } inline int StrobeCore::getStrobeMode(void) { if (modeSnapshot != strobeMode) return modeSnapshot; else return strobeMode; } inline void StrobeCore::setActive(bool status) { active = status; if (active) enable(); else disable(); } inline void StrobeCore::setMode(int mode) { strobeMode = mode; } inline double StrobeCore::FPS(void) { return fps; } inline void StrobeCore::setFPS(double newFPS) { fps = newFPS; } inline bool StrobeCore::strobe(void) { bool phasePositive = !(counter.total() % 2); int pCounter = counter.totalPositive(); int nCounter = counter.totalNegative(); if (phasePositive) { ++pCounter; frameState = (FrameState)(frameState | PHASE_POSITIVE); } else { ++nCounter; frameState = (FrameState)(frameState & ~PHASE_POSITIVE); } if (!strobeMode) // if strobe mode == 0 { // disable(); if (phasePositive) ++counter.positiveRenderedFrameCount; else ++counter.negativeRenderedFrameCount; return true; } if (switchInterval < 0) switchInterval = abs(switchInterval); if ((switchInterval) && (strobeMode % 2)) // Swapping not enabled for even modes as it is neither necessary nor works as intended { double difference = strobeTimer.elapsedSeconds() - timerSnapshot; if (difference >= switchInterval) { frameState = (FrameState)(frameState ^ PHASE_INVERTED); timerSnapshot = strobeTimer.elapsedSeconds(); } } if (internalFPSCalc) { double elapsedTime = strobeTimer.elapsedMilliseconds(); int frameTotal = counter.total(); if (elapsedTime - fpsTimerSnapshot >= 1000) { fpsTimerSnapshot = strobeTimer.elapsedMilliseconds(); counterSnapshot = counter.total(); } else { setFPS(1000.0f * (frameTotal - counterSnapshot) / (elapsedTime - fpsTimerSnapshot)); } } switch (frameState & (PHASE_POSITIVE | PHASE_INVERTED)) { case (PHASE_POSITIVE | PHASE_INVERTED): if ((abs(strobeMode) % 2) == 0) frameState = (FrameState)((((pCounter - 1) % (abs(strobeMode) + 1)) == (abs(strobeMode) / 2)) ? frameState | FRAME_RENDER : frameState & ~FRAME_RENDER); else frameState = (FrameState)(frameState & ~FRAME_RENDER); break; case (PHASE_POSITIVE & ~PHASE_INVERTED): if (abs(strobeMode) % 2 == 0) frameState = (FrameState)((((pCounter - 1) % (abs(strobeMode) + 1)) == 0) ? frameState | FRAME_RENDER : frameState & ~FRAME_RENDER); else if (abs(strobeMode) == 1) frameState = (FrameState)(frameState | FRAME_RENDER); else frameState = (FrameState)((((pCounter - 1) % ((abs(strobeMode) + 1) / 2)) == 0) ? frameState | FRAME_RENDER : frameState & ~FRAME_RENDER); break; case (~PHASE_POSITIVE & PHASE_INVERTED): if (abs(strobeMode) % 2 == 0) frameState = (FrameState)((((nCounter - 1) % (abs(strobeMode) + 1)) == 0) ? frameState | FRAME_RENDER : frameState & ~FRAME_RENDER); else if (abs(strobeMode) == 1) frameState = (FrameState)(frameState | FRAME_RENDER); else frameState = (FrameState)((((nCounter - 1) % ((abs(strobeMode) + 1) / 2)) == 0) ? frameState | FRAME_RENDER : frameState & ~FRAME_RENDER); break; case 0: if ((abs(strobeMode) % 2) == 0) frameState = (FrameState)((((nCounter - 1) % (abs(strobeMode) + 1)) == (abs(strobeMode) / 2)) ? frameState | FRAME_RENDER : frameState & ~FRAME_RENDER); else frameState = (FrameState)(frameState & ~FRAME_RENDER); break; default: frameState = (FrameState)(PHASE_POSITIVE | FRAME_RENDER); } if (strobeMode < 0) frameState = (FrameState)(frameState ^ FRAME_RENDER); return processFrame(); } <file_sep>/README.md # StrobeAPI **StrobeAPI** or **strobe-api** is a simple software based strobe (a motion blur elimination method) library written in C++. It uses "*black frame insertion*" technique. Online demo for motion blur elimination through black frame insertion / replacement method can be found here: https://www.testufo.com/blackframes Black frame insertion technique **greatly reduces motion blur** which is extremely important in modern video games. However it has some disadvantages such as reduced 'effective' fps and brightness. For example, least aggressive mode causes effective fps to drop to half and it also causes 35~% brightness reduction. StrobeAPI provides almost all necessary information regarding its side effects. With this method, moving objects can get tracked much more easily. For example, https://www.testufo.com/photo#photo=toronto-map.png&pps=960&pursuit=0&height=0 in this demo, moving texts in the map can not be easily read in LCD / LED screen without built-in strobe support. But with strobing, they can clearly get read. ## How To Use? To actually use StrobeAPI, you need to find an implementation for StrobeAPI. There is a simple but efficient implementation called "Strobe Core" which is already placed in the project source directory. StrobeAPI is a header-only library so it only consists of header files. test.cpp in the source directory is used for testing and not necessary for production. However, it can be kept without any problem as long as you don't include it in your project. To compile StrobeAPI, a modern C++ compiler should be enough. For integration examples, see test.cpp and Flappy-Bird-Qt project linked at the bottom of this page. ### Example #include "strobe-core.h" ... extern StrobeAPI *strobe; int main() { ... StrobeAPI *strobe = new StrobeCore(1 /* Strobe Mode 1: Applies RENDER - BLACK sequence, 2: RENDER - BLACK - BLACK, -2: BLACK - BLACK - RENDER*/, \ 0 /* Interval for phase switching in seconds. Use only if image retention occurs. Doesn't matter when StrobeMode is even. */, \ true /* Built-in FPS calculation. Use false to disable */); ... } void SwapBuffers() { ... // At the end of swap buffers code, a bool value coming from the strobe() function should be used to determine whether to show actual rendered frame or to show completely black frame // StrobeAPI automatically tracks previous and upcoming frames so do not intercept once it starts keep tracking. // Warning: Do not omit generating a new frame when strobe output is false. It will break synchronization. In general, StrobeAPI integration overhead should be kept at absolute minimum. bool showRenderedFrame = strobe->strobe(); if(showRenderedFrame) // Do the stuff as usual. else // Show black frame. } void fps() { ... strobe->setFPS(fps); // If built-in FPS calculation is disabled. } char * strobeDebugOutput() { return strobe->getDebugInformation(); } ## Example Run Strobe method = 2, Strobe swap interval = 2, Strobe cooldown delay = 3, FPS = randomly generated in the range of (99, 101) ![Simulation](https://i.imgur.com/pO7tP3N.png) ## Projects using StrobeAPI - https://github.com/fuzun/desktopbfi (StrobeAPI on Desktop) - https://github.com/fuzun/Flappy-Bird-Qt - https://github.com/fuzun/xash3d-strobe (Uses old C version of StrobeAPI) --- How PWM simulation works: ![signalsimulation](https://i.imgur.com/9Reb4GF.png) "Badness" algorithm: ![badness](https://i.vgy.me/qbzBOH.png) <file_sep>/strobe/strobe-api.h /* MIT License Copyright (c) 2018 fuzun Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #ifndef STROBEAPI_H #define STROBEAPI_H #ifndef STROBE_DISABLED #include <chrono> class StrobeAPI { protected: class StrobeTimer { public: inline StrobeTimer() { startTime = std::chrono::system_clock::now(); } inline double elapsedMilliseconds() { std::chrono::time_point<std::chrono::system_clock> endTime = std::chrono::system_clock::now(); return std::chrono::duration_cast<std::chrono::milliseconds>(endTime - startTime).count(); } inline double elapsedSeconds() { return elapsedMilliseconds() / 1000.0; } private: std::chrono::time_point<std::chrono::system_clock> startTime; }; StrobeTimer strobeTimer; public: enum CounterType { TotalFrame, PositiveFrame, PositiveRenderedFrame, PositiveBlackFrame, NegativeFrame, NegativeRenderedFrame, NegativeBlackFrame }; enum FrameState { PHASE_POSITIVE = 1 << 0, // Phase: Positive PHASE_INVERTED = 1 << 1, // Phase: Inverted FRAME_RENDER = 1 << 2, // Frame: Rendered _unassigned1 = (PHASE_POSITIVE | PHASE_INVERTED), _unassigned2 = (PHASE_POSITIVE | FRAME_RENDER), _unassigned3 = (PHASE_INVERTED | FRAME_RENDER), _unassigned4 = (PHASE_POSITIVE | PHASE_INVERTED | FRAME_RENDER) }; private: enum DifferenceType { PositiveDifference, NegativeDifference, TotalDifference }; struct Counter { int positiveRenderedFrameCount; int positiveBlackFrameCount; int negativeRenderedFrameCount; int negativeBlackFrameCount; inline int total(void) { int totalFrames = 0; totalFrames += positiveBlackFrameCount; totalFrames += positiveRenderedFrameCount; totalFrames += negativeBlackFrameCount; totalFrames += negativeRenderedFrameCount; return totalFrames; } inline int totalPositive(void) { int totalFrames = 0; totalFrames += positiveBlackFrameCount; totalFrames += positiveRenderedFrameCount; return totalFrames; } inline int totalNegative(void) { int totalFrames = 0; totalFrames += negativeBlackFrameCount; totalFrames += negativeRenderedFrameCount; return totalFrames; } inline int totalBlack(void) { int totalFrames = 0; totalFrames += positiveBlackFrameCount; totalFrames += negativeBlackFrameCount; return totalFrames; } inline int totalRendered(void) { int totalFrames = 0; totalFrames += positiveRenderedFrameCount; totalFrames += negativeRenderedFrameCount; return totalFrames; } }; char *debugInformation; void generateDiffBar(char * const dst, int size, DifferenceType type); void generateDebugInformation(void); void strConcat(char * const dst, int size, const char * const src); protected: Counter counter; FrameState frameState; // Frame info bool processFrame(void); int strobeMode; int switchInterval; double geometricMean(double x, double y); double arithmeticMean(double x, double y); public: StrobeAPI(int mode, int phaseSwitchInterval); virtual ~StrobeAPI(); bool isPhaseInverted(void); bool isFrameRendered(void); bool isPhasePositive(void); double actualBrightnessReduction(void); double logarithmicBrightnessReduction(double base); double squareBrightnessReduction(double base); double cubeBrightnessReduction(double base); double otherBrightnessReduction(double base, double (*reductionFunction)(double)); double badness(bool PWMInvolved); double badnessReduced(bool PWMInvolved); double effectiveFPS(void); double frequency(void); double dutyCycle(void); double positivePhaseShift(void); double negativePhaseShift(void); double period(void); int frameCount(CounterType type); char * getDebugInformation(void); virtual int getStrobeMode(void); virtual int getPhaseSwitchInterval(void); virtual bool strobe(void) = 0; virtual double FPS() = 0; virtual void setFPS(double newFPS) = 0; virtual void setMode(int mode); virtual void enable(void) = 0; virtual void disable(void) = 0; virtual void setActive(bool status) = 0; virtual bool isActive(void); void setStrobeMode(int mode); void setPhaseSwitchInterval(int phaseSwitchInterval); }; #include "strobe-api_cpp_.h" #endif #endif <file_sep>/strobe/strobe-core.h /* MIT License Copyright (c) 2018 fuzun Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #ifndef STROBECORE_H #define STROBECORE_H #ifndef STROBE_DISABLED #include "strobe-api.h" class StrobeCore : public StrobeAPI { private: double fps; double timerSnapshot; double fpsTimerSnapshot; bool active; bool internalFPSCalc; int modeSnapshot; int counterSnapshot; public: StrobeCore(int mode = 1, int phaseSwitchInterval = 0, bool internalFPSCalculation = true); ~StrobeCore(); bool strobe(void) override; double FPS() override; int getStrobeMode(void) override; void setFPS(double newFPS) override; void setMode(int mode) override; void enable(void) override; void disable(void) override; void setActive(bool status) override; bool isActive(void) override; }; #include "strobe-core_cpp_.h" #endif #endif <file_sep>/strobe/strobe-api_cpp_.h /* MIT License Copyright (c) 2018 fuzun Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #include <cstdio> #include <cstring> #include <cmath> #include <cstdlib> template<class T> inline double _lossCalculator(T x, T y) { return (x - y) * 100.0 / x; } inline StrobeAPI::StrobeAPI(int mode, int phaseSwitchInterval) : strobeMode(mode), switchInterval(phaseSwitchInterval) { debugInformation = new char[4096]; debugInformation[0] = 0; memset(&counter, 0, sizeof(counter)); frameState = (FrameState)(PHASE_POSITIVE | FRAME_RENDER); } inline StrobeAPI::~StrobeAPI() { delete debugInformation; debugInformation = nullptr; } inline int StrobeAPI::getPhaseSwitchInterval(void) { return switchInterval; } inline void StrobeAPI::setStrobeMode(int mode) { frameState = (FrameState)(PHASE_POSITIVE | FRAME_RENDER); strobeMode = mode; } inline void StrobeAPI::setPhaseSwitchInterval(int phaseSwitchInterval) { frameState = (FrameState)(frameState & ~PHASE_INVERTED); switchInterval = phaseSwitchInterval; } inline char * StrobeAPI::getDebugInformation(void) { generateDebugInformation(); return debugInformation; } inline bool StrobeAPI::isPhaseInverted(void) { if (frameState & PHASE_INVERTED) return true; else return false; } inline bool StrobeAPI::isFrameRendered(void) { if (frameState & FRAME_RENDER) return true; else return false; } inline bool StrobeAPI::isPhasePositive(void) { if (frameState & PHASE_POSITIVE) return true; else return false; } inline double StrobeAPI::effectiveFPS(void) { int mode = strobeMode; double eFPS; if (mode > 0) { eFPS = (FPS()) / (mode + 1); } else if (mode < 0) { mode = abs(mode); eFPS = (FPS() * mode) / (mode + 1); } else { eFPS = FPS(); } return eFPS; } inline void StrobeAPI::generateDiffBar(char * const dst, int size, DifferenceType type) { int pNCounter = counter.positiveRenderedFrameCount; int pBCounter = counter.positiveBlackFrameCount; int nNCounter = counter.negativeRenderedFrameCount; int nBCounter = counter.negativeBlackFrameCount; int nCounter = counter.totalNegative(); int pCounter = counter.totalPositive(); char _barCounter = 0; int diff_NB = 0; int diff = 0; int _a, _b; bool Neg = false; switch (type) { case (PositiveDifference): { diff_NB = (pNCounter - pBCounter); if (pCounter) diff = (int)round(abs(diff_NB) * 100 / pCounter); break; } case (NegativeDifference): { diff_NB = (nNCounter - nBCounter); if (nCounter) diff = (int)round(abs(diff_NB) * 100 / nCounter); break; } case (TotalDifference): { if (nCounter && pCounter) { _a = (abs(pNCounter - pBCounter) * 100 / pCounter); _b = (abs(nNCounter - nBCounter) * 100 / nCounter); diff = abs(_a - _b); } break; } default: break; } if (diff_NB < 0) Neg = true; snprintf(dst, size, "["); for (_barCounter = 0; _barCounter <= 20; ++_barCounter) { if (_barCounter == 10) { strConcat(dst, size, "O"); } else if (_barCounter < 10) { if (type == 2) { if (100 - (_barCounter * 11) <= diff / 2) strConcat(dst, size, "="); else strConcat(dst, size, "-"); } else { if (Neg) { if (100 - (_barCounter * 11) <= diff) strConcat(dst, size, "="); else strConcat(dst, size, "-"); } else { strConcat(dst, size, "-"); } } } else if (_barCounter > 10) { if (type == 2) { if (((_barCounter - 11) * 11) >= diff / 2) strConcat(dst, size, "-"); else strConcat(dst, size, "="); } else { if (Neg) { strConcat(dst, size, "-"); } else { if (((_barCounter - 11) * 11) >= diff) strConcat(dst, size, "-"); else strConcat(dst, size, "="); } } } } if (type == 2) { char buf[32]; snprintf(buf, sizeof(buf), "] * %d / 200", diff); strConcat(dst, size, buf); } else { char buf[32]; snprintf(buf, sizeof(buf), "] * %d%%", (Neg ? -diff : diff)); strConcat(dst, size, buf); } } inline double StrobeAPI::frequency(void) { if (strobeMode) return (1 / ((1.0f / FPS()) * (abs(strobeMode) + 1))); else return 0.0; } inline double StrobeAPI::dutyCycle(void) { return (((1.0f / (abs(strobeMode) + 1)) * 100) * (strobeMode < 0 ? -strobeMode : 1)); } inline double StrobeAPI::positivePhaseShift(void) { if (isPhaseInverted()) return (1.0f / FPS()) * 1000; else return 0.0f; } inline double StrobeAPI::negativePhaseShift(void) { return abs(strobeMode) * positivePhaseShift(); } inline double StrobeAPI::period(void) { return (1 / frequency() * 1000); } inline double StrobeAPI::geometricMean(double x, double y) { return sqrt(abs(x * y)); } inline double StrobeAPI::arithmeticMean(double x, double y) { return (x + y) / 2; } inline double StrobeAPI::actualBrightnessReduction(void) { return _lossCalculator<double>(FPS(), effectiveFPS()); } inline double StrobeAPI::logarithmicBrightnessReduction(double base) { return _lossCalculator<double>(log(base), log(base * effectiveFPS() / FPS())); } inline double StrobeAPI::squareBrightnessReduction(double base) { return _lossCalculator<double>(sqrt(base), sqrt(base * effectiveFPS() / FPS())); } inline double StrobeAPI::cubeBrightnessReduction(double base) { return _lossCalculator<double>(cbrt(base), cbrt(base * effectiveFPS() / FPS())); } inline double StrobeAPI::otherBrightnessReduction(double base, double (*reductionFunction)(double)) { return _lossCalculator<double>(reductionFunction(base), reductionFunction(base * effectiveFPS() / FPS())); } inline double StrobeAPI::badnessReduced(bool pwmInvolved) { int pNCounter = counter.positiveRenderedFrameCount; int pBCounter = counter.positiveBlackFrameCount; int nNCounter = counter.negativeRenderedFrameCount; int nBCounter = counter.negativeBlackFrameCount; int nCounter = counter.totalNegative(); int pCounter = counter.totalPositive(); double badness, Diff; int diffP_NB, diffN_NB; double diffP = 0.0, diffN = 0.0; diffP_NB = (pNCounter - pBCounter); diffN_NB = (nNCounter - nBCounter); if (pCounter) diffP = abs(diffP_NB) * 100.0 / pCounter; if (nCounter) diffN = abs(diffN_NB) * 100.0 / nCounter; if (diffP_NB < 0.0) diffP = -diffP; if (diffN_NB < 0.0) diffN = -diffN; Diff = fabs(diffP - diffN); if (Diff < 0.0) Diff = 0.0; else if (Diff > 200.0) Diff = 200.0; badness = -log((200 - Diff) / (Diff)); if (pwmInvolved) return (badness * period()); else return badness; } inline double StrobeAPI::badness(bool pwmInvolved) { int pNCounter = counter.positiveRenderedFrameCount; int pBCounter = counter.positiveBlackFrameCount; int nNCounter = counter.negativeRenderedFrameCount; int nBCounter = counter.negativeBlackFrameCount; int nCounter = counter.totalNegative(); int pCounter = counter.totalPositive(); int diffP_NB, diffN_NB; double diffP = 0.0, diffN = 0.0; double absoluteDifference = 0.0; double badness = 0.0; diffP_NB = (pNCounter - pBCounter); diffN_NB = (nNCounter - nBCounter); if (pCounter) diffP = abs(diffP_NB) * 100.0 / pCounter; if (nCounter) diffN = abs(diffN_NB) * 100.0 / nCounter; absoluteDifference = fabs(diffP - diffN); if (absoluteDifference > 100.0) absoluteDifference = 100.0; badness = -log(((absoluteDifference + geometricMean((100.0 - diffP), (100.0 - diffN))) / (absoluteDifference + geometricMean(diffP, diffN)))); if (pwmInvolved) return (badness * period()); else return badness; } inline int StrobeAPI::frameCount(CounterType type) { int pNCounter = counter.positiveRenderedFrameCount; int pBCounter = counter.positiveBlackFrameCount; int nNCounter = counter.negativeRenderedFrameCount; int nBCounter = counter.negativeBlackFrameCount; int fCounter = counter.total(); int nCounter = counter.totalNegative(); int pCounter = counter.totalPositive(); switch (type) { case (PositiveFrame): { return pCounter; break; } case (PositiveRenderedFrame): { return pNCounter; break; } case (PositiveBlackFrame): { return pBCounter; break; } case (NegativeFrame): { return nCounter; break; } case (NegativeRenderedFrame): { return nNCounter; break; } case (NegativeBlackFrame): { return nBCounter; break; } case (TotalFrame): default: return fCounter; break; } } inline void StrobeAPI::generateDebugInformation(void) { char * const dst = debugInformation; int pNCounter = counter.positiveRenderedFrameCount; int pBCounter = counter.positiveBlackFrameCount; int nNCounter = counter.negativeRenderedFrameCount; int nBCounter = counter.negativeBlackFrameCount; int fCounter = counter.total(); int nCounter = counter.totalNegative(); int pCounter = counter.totalPositive(); char modeDescription[128]; modeDescription[0] = 0; char diffBarP[128], diffBarN[128], diffBarT[128]; int diffP_NB, diffN_NB; double diffP = 0.0, diffN = 0.0; diffP_NB = (pNCounter - pBCounter); diffN_NB = (nNCounter - nBCounter); if (pCounter) diffP = abs(diffP_NB) * 100.0 / pCounter; if (nCounter) diffN = abs(diffN_NB) * 100.0 / nCounter; generateDiffBar(diffBarP, sizeof(diffBarP), PositiveDifference); generateDiffBar(diffBarN, sizeof(diffBarN), NegativeDifference); generateDiffBar(diffBarT, sizeof(diffBarT), TotalDifference); if (!strlen(modeDescription) && strobeMode < 10) { if (strobeMode != 0) { snprintf(modeDescription, sizeof(modeDescription), (strobeMode > 0 ? "%d [RENDER" : "%d [BLACK"), strobeMode); for (int k = 1; k <= abs(strobeMode); ++k) { strConcat(modeDescription, sizeof(modeDescription), (strobeMode > 0 ? " - BLACK" : " - RENDER")); } strConcat(modeDescription, sizeof(modeDescription), "]"); } else { snprintf(modeDescription, sizeof(modeDescription), "[RENDER]"); } } snprintf(dst, \ 4096, \ "%.2f FPS\n" \ "%.2f eFPS\n" \ "Strobe Mode: %s\n" \ "Phase Switch Interval: %d\n" \ "Elapsed Time: %.2f\n" \ "isPhaseInverted = %d\n" \ "Total Frame Count: %d\n" \ "(+) Phase Frame Count: %d\n" \ " Rendered Frame Count: %d\n" \ " Black Frame Count: %d\n" \ "(-) Phase Frame Count: %d\n" \ " Rendered Frame Count: %d\n" \ " Black Frame Count: %d\n" \ "=====ANALYSIS=====\n" \ "PWM Simulation:\n" \ " |-> Frequency: %.2f Hz\n" \ " |-> Duty Cycle: %.2f%%\n" \ " |-> Phase Shift: +%.4f msec || -%.4f msec\n" \ " |-> Period: %.2f msec\n" \ "Brightness Reduction:\n" \ " |-> [LINEAR] Actual Reduction: %.2f%%\n" \ " |-> [LOG] Realistic Reduction (350 cd/m2 base): %.2f%%\n" \ " |-> [SQUARE] Realistic Reduction (350 cd/m2 base): %.2f%%\n" \ " |-> [CUBE] Realistic Reduction (350 cd/m2 base): %.2f%%\n" \ "Difference (+): %s\n" \ "Difference (-): %s\n" \ "Difference (TOTAL): %s\n" \ "Geometric Mean: %.4f\n" \ "Geometric / Arithmetic Mean Difference: %.4f\n" \ "[EXPERIMENTAL] Badness: %.4f\n" \ "[EXPERIMENTAL] Badness x PWM Period: %.4f\n" \ "[EXPERIMENTAL] Badness (Reduced): %.4f\n" \ "[EXPERIMENTAL] Badness (Reduced) x PWM Period: %.4f\n" \ "=====ANALYSIS=====\n", \ FPS(), \ effectiveFPS(), \ modeDescription, \ switchInterval, \ strobeTimer.elapsedSeconds(), \ isPhaseInverted(), \ fCounter, \ pCounter, \ pNCounter, \ pBCounter, \ nCounter, \ nNCounter, \ nBCounter, \ frequency(), \ dutyCycle(), \ positivePhaseShift(), \ negativePhaseShift(), \ period(), \ actualBrightnessReduction(), \ logarithmicBrightnessReduction(350.0), \ squareBrightnessReduction(350.0), \ cubeBrightnessReduction(350.0), \ diffBarP, \ diffBarN, \ diffBarT, \ geometricMean(diffP, diffN), \ arithmeticMean(diffP, diffN) - geometricMean(diffP, diffN), \ badness(false), \ badness(true), \ badnessReduced(false), \ badnessReduced(true) \ ); } inline bool StrobeAPI::isActive() { return true; } inline void StrobeAPI::setMode(int mode) { strobeMode = mode; } inline int StrobeAPI::getStrobeMode(void) { return strobeMode; } inline bool StrobeAPI::processFrame(void) { if ((frameState & FRAME_RENDER) || !isActive()) { if (frameState & PHASE_POSITIVE) ++counter.positiveRenderedFrameCount; else ++counter.negativeRenderedFrameCount; return true; } else { if (frameState & PHASE_POSITIVE) ++counter.positiveBlackFrameCount; else ++counter.negativeBlackFrameCount; return false; } } inline void StrobeAPI::strConcat(char * const dst, int size, const char * const src) { if (!strlen(src)) return; if (sizeof(char) * (strlen(dst) + strlen(src)) > size) return; char* const buf = (char*)malloc(size); snprintf(buf, size, "%s%s", dst, src); if (buf == nullptr) return; snprintf(dst, size, "%s", buf); free(buf); } <file_sep>/strobe/test.cpp /* MIT License Copyright (c) 2018 fuzun Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #include <cstdio> #include <cassert> #include <ctime> #include "strobe-core.h" class Timer // Simple timer. Gathered from the internet { public: inline Timer() { init(); } inline void restart() { init(); } inline double elapsedMilliseconds() { std::chrono::time_point<std::chrono::system_clock> endTime; endTime = std::chrono::system_clock::now(); return std::chrono::duration_cast<std::chrono::milliseconds>(endTime - m_StartTime).count(); } inline double elapsedSeconds() { return elapsedMilliseconds() / 1000.0; } private: inline void init() { m_StartTime = std::chrono::system_clock::now(); } std::chrono::time_point<std::chrono::system_clock> m_StartTime; }; double random(int min, int max) { int min_ = min * 100; int max_ = max * 100; return (rand() % (max_ - min_ + 1) + min_) / 100.0; } struct StrobeOutput { double eFPS; double fps_; int totalFrameCount; int positiveFrameCount; int negativeFrameCount; int positiveBlackFrameCount; int negativeBlackFrameCount; int positiveRenderedFrameCount; int negativeRenderedFrameCount; double frequency; double period; double brightnessReduction; double badness; double badnessPWM; double badnessReduced; double badnessReducedPwm; }; void assign(StrobeOutput * const output, StrobeAPI * const strobe) { output->eFPS = strobe->effectiveFPS(); output->fps_ = strobe->FPS(); output->totalFrameCount = strobe->frameCount(StrobeAPI::TotalFrame); output->positiveFrameCount = strobe->frameCount(StrobeAPI::PositiveFrame); output->negativeFrameCount = strobe->frameCount(StrobeAPI::NegativeFrame); output->positiveBlackFrameCount = strobe->frameCount(StrobeAPI::PositiveBlackFrame); output->negativeBlackFrameCount = strobe->frameCount(StrobeAPI::NegativeBlackFrame); output->positiveRenderedFrameCount = strobe->frameCount(StrobeAPI::PositiveRenderedFrame); output->negativeRenderedFrameCount = strobe->frameCount(StrobeAPI::NegativeRenderedFrame); output->frequency = strobe->frequency(); output->period = strobe->period(); output->brightnessReduction = strobe->actualBrightnessReduction(); output->badness = strobe->badness(false); output->badnessPWM = strobe->badness(true); output->badnessReduced = strobe->badnessReduced(false); output->badnessReducedPwm = strobe->badnessReduced(true); } int main() { StrobeAPI *strobe; Timer timer; StrobeOutput output; double fps; srand((unsigned int)time(NULL)); memset(&output, 0, sizeof(output)); strobe = new StrobeCore(1, 1, false); while (timer.elapsedSeconds() < 10) { fps = random(58, 62); strobe->setFPS(fps); strobe->strobe(); printf("%s", strobe->getDebugInformation()); assign(&output, strobe); assert(strobe->getPhaseSwitchInterval() == 1); assert(strobe->getStrobeMode() == 1); assert(output.fps_ >= 58 && output.fps_ <= 62); assert(output.eFPS == output.fps_ / 2); assert(output.totalFrameCount == output.negativeFrameCount + output.positiveFrameCount); assert(output.positiveFrameCount == output.positiveBlackFrameCount + output.positiveRenderedFrameCount); assert(output.negativeFrameCount == output.negativeBlackFrameCount + output.negativeRenderedFrameCount); assert(output.frequency > 0); assert(fabs(output.frequency - output.eFPS) < 1); assert(fabs(output.frequency - 1000 / output.period) < 0.1); assert(output.brightnessReduction == (output.fps_ - output.eFPS) * 100.0 / output.fps_); assert(output.badnessPWM == output.badness * output.period); assert(output.badnessReducedPwm == output.badnessReduced * output.period); } fflush(stdout); delete strobe; strobe = new StrobeCore(2, 3, false); timer.restart(); while (timer.elapsedSeconds() < 10) { fps = random(120, 144); strobe->setFPS(fps); strobe->strobe(); printf("%s", strobe->getDebugInformation()); assign(&output, strobe); assert(strobe->getPhaseSwitchInterval() == 3); assert(strobe->getStrobeMode() == 2); assert(output.fps_ >= 120 && output.fps_ <= 144); assert(output.eFPS == output.fps_ / 3); assert(output.totalFrameCount == output.negativeFrameCount + output.positiveFrameCount); assert(output.positiveFrameCount == output.positiveBlackFrameCount + output.positiveRenderedFrameCount); assert(output.negativeFrameCount == output.negativeBlackFrameCount + output.negativeRenderedFrameCount); assert(output.frequency > 0); assert(fabs(output.frequency - 1000 / output.period) < 0.1); assert(output.brightnessReduction == (output.fps_ - output.eFPS) * 100.0 / output.fps_); assert(output.badnessPWM == output.badness * output.period); assert(output.badnessReducedPwm == output.badnessReduced * output.period); } fflush(stdout); delete strobe; strobe = new StrobeCore(0, 0, false); timer.restart(); while (timer.elapsedSeconds() < 10) { fps = random(29, 31); strobe->setFPS(fps); bool result = strobe->strobe(); printf("%s", strobe->getDebugInformation()); assign(&output, strobe); assert(strobe->getPhaseSwitchInterval() == 0); assert(strobe->getStrobeMode() == 0); assert(result); assert(output.fps_ >= 29 && output.fps_ <= 31); assert(output.eFPS == output.fps_); assert(output.totalFrameCount == output.negativeFrameCount + output.positiveFrameCount); assert(output.positiveFrameCount == output.positiveBlackFrameCount + output.positiveRenderedFrameCount); assert(output.negativeFrameCount == output.negativeBlackFrameCount + output.negativeRenderedFrameCount); assert(output.negativeBlackFrameCount == 0); assert(output.positiveBlackFrameCount == 0); assert(output.frequency == 0.0); assert(output.period >= DBL_MAX); assert(output.brightnessReduction == 0.0); assert(output.badnessReduced <= DBL_MIN); } fflush(stdout); delete strobe; strobe = new StrobeCore(-3, 2, false); timer.restart(); while (timer.elapsedSeconds() < 10) { fps = random(950, 1050); strobe->setFPS(fps); strobe->strobe(); printf("%s", strobe->getDebugInformation()); assign(&output, strobe); assert(strobe->getPhaseSwitchInterval() == 2); assert(strobe->getStrobeMode() == -3); assert(output.fps_ >= 950 && output.fps_ <= 1050); assert(output.eFPS == output.fps_ * 3 / 4); assert(output.totalFrameCount == output.negativeFrameCount + output.positiveFrameCount); assert(output.positiveFrameCount == output.positiveBlackFrameCount + output.positiveRenderedFrameCount); assert(output.negativeFrameCount == output.negativeBlackFrameCount + output.negativeRenderedFrameCount); assert(output.frequency > 0); assert(fabs(output.frequency - 1000 / output.period) < 0.1); assert(output.brightnessReduction < 50.0); assert(output.badnessPWM == output.badness * output.period); assert(output.badnessReducedPwm == output.badnessReduced * output.period); } fflush(stdout); delete strobe; strobe = new StrobeCore(4, 3, true); timer.restart(); while (timer.elapsedSeconds() < 10) { strobe->strobe(); printf("%s", strobe->getDebugInformation()); assign(&output, strobe); assert(strobe->getPhaseSwitchInterval() == 3); assert(strobe->getStrobeMode() == 4); assert(output.totalFrameCount == output.negativeFrameCount + output.positiveFrameCount); assert(output.positiveFrameCount == output.positiveBlackFrameCount + output.positiveRenderedFrameCount); assert(output.negativeFrameCount == output.negativeBlackFrameCount + output.negativeRenderedFrameCount); } fflush(stdout); delete strobe; strobe = new StrobeCore(1, 0, false); strobe->disable(); assert(!strobe->isActive()); timer.restart(); while (timer.elapsedSeconds() < 10) { fps = random(119, 121); strobe->setFPS(fps); strobe->strobe(); printf("%s", strobe->getDebugInformation()); assign(&output, strobe); assert(strobe->getPhaseSwitchInterval() == 0); assert(strobe->getStrobeMode() == 1); assert(output.fps_ >= 119 && output.fps_ <= 121); assert(output.eFPS == output.fps_); assert(output.totalFrameCount == output.negativeFrameCount + output.positiveFrameCount); assert(output.positiveFrameCount == output.positiveBlackFrameCount + output.positiveRenderedFrameCount); assert(output.negativeFrameCount == output.negativeBlackFrameCount + output.negativeRenderedFrameCount); assert(output.negativeBlackFrameCount == 0); assert(output.positiveBlackFrameCount == 0); assert(output.frequency == 0.0); assert(output.period >= DBL_MAX); assert(output.brightnessReduction == 0.0); assert(output.badnessReduced <= DBL_MIN); } strobe->enable(); timer.restart(); assert(strobe->isActive()); assert(strobe->getStrobeMode() == 1); assert(strobe->getPhaseSwitchInterval() == 0); fflush(stdout); delete strobe; return 0; }
547d45d9ed308ac964ba8dc43776b8d4fc63cc34
[ "Markdown", "C", "C++" ]
6
C
dualword/strobe-api
5d690e71adbb60fcd8e233f642e7383cf64a540b
b12edf498b2923f27fe229732445d02d4d406c7f
refs/heads/main
<file_sep> #include <stdio.h> #include <stdlib.h> #include <string.h> //strlen #include <sys/socket.h> #include <arpa/inet.h> //inet_addr #include <unistd.h> #include <signal.h> #include <string.h> #include <ctype.h> // ..... #include <sys/wait.h> #define MAXPENDING 5 #define MAX_BUFF_LEN 255 int servSock; int clntSock; static pid_t child_pid; static pid_t parent_pid; void DieWithError(char *errorMessage) { perror(errorMessage); exit(1); } void store_messages(char *reciever, char *sender, char* message) { FILE *fp = NULL; char _fname[strlen(reciever) + strlen("-sms.txt") + 1]; strcpy(_fname,reciever); strcat(_fname,"-sms.txt"); printf("reciever== %s sender== %s, _fname== %s",reciever,sender,_fname); fp = fopen(_fname, "a"); if (fp == NULL) { printf("Could not store message with name:%s", reciever); fclose(fp); exit(1); } //create the file fputs(reciever, fp); fputs(";", fp); fputs(sender, fp); fputs(";", fp); fputs(message, fp); fputs("\n", fp); fclose(fp); } void read_messages(char *fname){ printf(" *** ENTERED read_messages\n"); printf(" *** read_messages, fname== %s\n",fname); FILE *fp = NULL; char *lineptr = NULL; char *buffer = NULL; char reply [ strlen("There is no such name") +1]; memset( reply,0, strlen("There is no such name") + 1); size_t n = 0; ssize_t bread = 0; strcpy(reply, "There is no such name"); fp = fopen(fname, "r"); if (fp == NULL){ //no such file name printf(" *** read_messages, replying no such name\n"); send(clntSock,reply, strlen(reply),0); return; } //file exists and can be read fp = fopen(fname,"r+"); //send every message bread = getline(&lineptr,&n,fp); while(bread > -1){ if (bread > 0) { printf(" *** read_messages, replying with message [%s]...\n",lineptr); send(clntSock, lineptr, strlen(lineptr), 0); bread = getline(&lineptr, &n, fp); } } if (lineptr == NULL){ free(lineptr); printf(" *** read_messages, replying with Internal Error ...\n"); memset(reply,0, strlen(reply)); strcpy(reply, "Internal error"); send( clntSock,reply, strlen(reply),0 ); printf(" **** Error in getline\n"); return ; } printf(" *** read_messages, replying with NO MORE MESSAGES ...\n"); strcpy(reply, "NO MORE MESSAGES"); send( clntSock,reply, strlen(reply),0 ); free(lineptr); } void message_handler(char *buffer) { char *verb = NULL; char *token = NULL; char *reciever = NULL; char *sender = NULL; char *msg = NULL; char replying_buffer[MAX_BUFF_LEN+1]; memset(replying_buffer,0,MAX_BUFF_LEN+1); printf("\n ***** message_handler ... \n"); printf("buffer= [%s]\n",buffer); //convert string to lower case token = strtok(buffer, ";"); int _count = 0; //_count < 2 for token to hold "TO" while (token != NULL) { if (_count == 0) verb = token; else if (_count == 1) reciever = token; else if (_count == 2) sender = token; else if (_count == 3) msg = token; token = strtok(NULL, ";"); _count++; } //deal with errors if (verb == NULL){ printf(" No Verb in message, reply to client...\n "); strcpy(replying_buffer, "No verb\n"); send(clntSock, replying_buffer, strlen(replying_buffer), 0); return; } if ( reciever == NULL){ printf(" No reciever in message, reply to client...\n "); strcpy(replying_buffer, "No reciever\n"); send(clntSock, replying_buffer, strlen(replying_buffer), 0); return; } // -------- if verb === store then check more if (strcmp("store", verb) == 0) { printf(" verb=fetch ... check sender, message ...\n"); if (sender == NULL) { printf(" Verb= fetch, no sender...\n "); strcpy(replying_buffer, "No sender\n"); send(clntSock, replying_buffer, strlen(replying_buffer), 0); return; } if (msg == NULL) { printf(" Verb= fetch, no message...\n "); strcpy(replying_buffer, "No message\n"); send(clntSock, replying_buffer, strlen(replying_buffer), 0); return; } } printf(" *** verb == %s, receiver=%s, sender=%s, msg=%s\n", verb, reciever,sender,msg); //must reply with total messages of this user if (strcmp("fetch", verb) == 0) { printf(" fetch ... replying [Retrieving messages...]...\n"); strcpy(replying_buffer, "Retrieving messages...\n"); send(clntSock, replying_buffer, strlen(replying_buffer),0); char filename[strlen(reciever) + 9]; memset(filename,0, strlen(reciever) + 9); strcpy(filename,reciever); strcat(filename, "-sms.txt"); printf(" *** BEFORE read_messages filename== %s\n",filename); read_messages(filename); printf(" fetch ... finished.\n"); } //must write the messages else if ( strcmp("store", verb) == 0 ) { printf(" store ... replying ...\n"); strcpy(replying_buffer, "Message accepted and stored:\n"); send(clntSock,replying_buffer, strlen(replying_buffer),0); //store messages store_messages(reciever,sender,msg); printf(" store ... replyed.\n"); }else{ printf(" bad verb ... replying ...\n"); strcpy(replying_buffer, "Message declined. Bad verb\n"); send(clntSock,replying_buffer, strlen(replying_buffer),0); printf(" bad verb ... replyed.\n"); } } void HandleTCPClient(){ //initiating buffer char buffer[129], reply_buffer[129]; memset(buffer,0,129); memset(reply_buffer,0,129); printf("\n HandleTCPClient start servicing client...\n"); //accept message from client ssize_t bytes_read = recv(clntSock, buffer, 128, 0); if (bytes_read > 0 ) { printf("Received message : [%s]\n ", buffer); printf("Entering message_handler()"); message_handler(buffer); } else printf("Error in receiving data from client\n"); //shutdown client shutdown(clntSock,SHUT_WR); printf("\n HandleTCPClient ended servicing client...\n"); } void sigintHandler(int sig_num){ write(1," Caught signal... closing ports and exiting the program..\n",strlen(" Caught signal... closing ports and exiting the program..\n")+1); close(servSock); close(clntSock); _exit(1); } int main(int argc , char *argv[]) { printf("argc== %d\n", argc); if (argc != 2) DieWithError("Error: Expected server port number as argument\n"); signal(SIGINT, sigintHandler); struct sockaddr_in sockServAddr; struct sockaddr_in sockClntAddr; unsigned short sockServPort; unsigned int clntLen; sockServPort = atoi(argv[1]); if( (servSock = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP)) < 0){ DieWithError("socket() failed"); } int enable = 1; if (setsockopt(servSock, SOL_SOCKET, SO_REUSEADDR, &enable, sizeof(int)) < 0) { DieWithError("setsockopt(SO_REUSEADDR) failed"); } memset(&sockServAddr, 0, sizeof(sockServAddr)); sockServAddr.sin_family = AF_INET; sockServAddr.sin_port = htons(sockServPort); sockServAddr.sin_addr.s_addr = htonl(INADDR_ANY); if (bind(servSock, (struct sockaddr *) &sockServAddr, sizeof(sockServAddr)) < 0) { DieWithError("bind() failed"); } parent_pid = getpid(); printf("Socket Server starts listening with pid= %d...\n",parent_pid); if(listen(servSock, MAXPENDING) < 0) { DieWithError("listen() failed"); } #pragma clang diagnostic push #pragma ide diagnostic ignored "EndlessLoop" while(1) { clntLen = sizeof(sockClntAddr); if ((clntSock = accept(servSock, (struct sockaddr *) &sockClntAddr, &clntLen)) < 0) { DieWithError("accept() failed"); } //fork for multiple clients child_pid = fork(); if ( child_pid == 0 ){ // we are in child now //close parent socket, we dont need in child close(servSock); pid_t my_pid = getpid(); printf("Child created with pID= %d, while parent is: %d\n\n", my_pid, parent_pid); // here we should process clients request..... printf("Handling client %s\n", inet_ntoa(sockClntAddr.sin_addr)); printf("Entering HandleTCPClient()...\n"); HandleTCPClient() ; close(clntSock); printf(" *** child :: socket closed, exiting...\n"); exit(0); } else if(parent_pid > 0 ) { printf("we are in Father. child's pid is %d\n", parent_pid); } else if (parent_pid == -1){ printf("Could not fork()"); close(clntSock); exit(1); } } printf("Closing sockets\n"); close(servSock); return 0; }<file_sep># Message_Client-Server Messaging Client - Server application ## Message Socket Server (server.c) - Uses TCP/IP (stream socket) - Requieres: 1. 1 command parameter 2. The port number to bind to - Binds on **ANY** IP address of it's host (and on local host, 127.0.0.1) - Uses fork() in order to serve multiple clients stimuntaniously - Uses a buffer of 255 bytes (global macro #define MAX_BUFF_LEN 255) - Traps **Ctr+C** from console so that before the server terminates, the sockets will be closed - The protocol which is used on Application level for the connection between server and client is the following: >VERB;reciepient[;sender;message] (comma delimited line) wheres: - If verb is "fetch", it means: "fetch every message for the following reciepient" - If verb is "strore", it means: "store the message with reciepient, sender, message" So, when the client (for example: with username == george) wants to send a message to user Kyriakos, he will have to send the following string: "store;Kyriakos;george;hi Kyriakos" >Also, when the client (for example username == george) wants to see his messages, he has to type the following string: fetch;george ## Server Operation - When the server binds and listens on IP, it waits theconnection of a client - When a client connects, the server must open a socket again with the server and send it's message. After serving the client, server's socket close By doing so, server doesn't get on blocking mode if a client fails or be late to inform that it's messages have finished. ## Message client (cleint.c) - Uses TCP/IP (stream socket) - Requires: 1. IP address of the server 2. The number of port that the server will listen to - Has a menu with 3 operations such as: 1. Send message 2. Read message 3. Exit ## Client operation According to the server's mode of operation and the predefined client's protocol, for each request to the server creates a socket ( connect() ), sends the request ( send() ) and takes the answer. Then the client closes the socket and returns to menu. <file_sep> #include <stdio.h> /* for printf() and fprintf() */ #include <stdlib.h> /* for atoi() and exit() */ #include <string.h> /* for memset() strlen */ #include <sys/socket.h> /* for socket(), bind(), connect(), recv() and send() */ #include <arpa/inet.h> /* for sockaddr_in and inet_ntoa() inet_addr */ #include <sys/types.h> #include <fcntl.h> #include <unistd.h> /* for close() */ #include <sys/time.h> #include <errno.h> #include <signal.h> /* for signals */ #include <sys/wait.h> /* for waitpid() */ #define PORT 5129 #define DEF_PROTO SOCK_STREAM #define GET_SMS_VERB "fetch" #define SEND_SMS_VERB "store" #define RECEIVEBUFFSIZE 128 #define BUFFER_SIZE 1024 void DieWithError(char *errorMessage) { perror(errorMessage); exit(1); } void sendSms( char * serveridaddress, unsigned short port, char * username ){ printf(" ** sendSMS called...\n"); //establish communication with the server struct sockaddr_in server; server.sin_addr.s_addr = inet_addr(serveridaddress); server.sin_family = AF_INET; server.sin_port = htons( port ); int s ; int socket_type = DEF_PROTO; if((s = socket(AF_INET , socket_type , 0 )) < 0 ) { printf(" sendSms: ERROR Could not create socket."); return ; } printf(" sendSms: Socket created.\n"); printf(" sendSms: Connecting to sms server..."); if (connect(s , (struct sockaddr *)&server , sizeof(server)) < 0) { printf(" sendSms: connect error"); return; } printf(" sendSms: Connected. \n"); //read stdin char *buffer = NULL; char *to =NULL ; char message[255]; //catch previous enter getchar(); printf(" Type the receipient (50chars max): "); size_t n = 0; n = getline(&to,&n,stdin); if(n<1) { printf(" failed to read line for receipient !"); return; } to[strlen(to)-1]=0; // clear LF at the end //get message printf(" Type your sms: "); n = 0; n = getline(&buffer,&n,stdin); if(n<1) { printf(" failed to read line for sms !"); return; } buffer[strlen(buffer)-1]=0; // clear LF at the end if (n >= BUFFER_SIZE - strlen(buffer) ) { printf(" Message too long\n"); return; } //create the message to send to server sprintf(message, "%s;%s;%s;%s",SEND_SMS_VERB,to,username,buffer); printf(" sendSms: sending message [%s] \n", message); //Receive a reply from the server char server_reply[8000]; memset(server_reply,0,8000); char recvbuff[RECEIVEBUFFSIZE+1]; memset(recvbuff,0,RECEIVEBUFFSIZE+1); if( send(s , message , strlen(message) , 0) < 0) // == SOCKET_ERROR { printf(" sendSms: Send failed"); return ; } printf(" sendSms: Sms sent succesfully.\n"); printf("============================================================= receiving reply ...\n"); int recv_size; while( (recv_size = recv(s , recvbuff , RECEIVEBUFFSIZE , 0)) > 0 ) // if((recv_size = recv(s , server_reply , 8000 , 0)) == SOCKET_ERROR) { //Add a NULL terminating character to make it a proper string before printing recvbuff[recv_size] = '\0'; printf(" receiveSms: received %d bytes:[%s]\n", recv_size, recvbuff); strcat(server_reply, recvbuff); // ??? if( stricmp(verb, "sendsms") == 0 ) break; } printf("============================ reception completed.\n"); printf(" sendSms: Total server reply:\n"); printf("%s\n",server_reply); // close socket and cleanup printf(" sendSms: Closing socket and exiting... \n"); close(s); printf("============================ \n socket closed. End\n"); free(buffer); return; } void receiveSms( char * serveridaddress, unsigned short port, char * username ){ printf(" ** receiveSMS called...\n"); struct sockaddr_in server; // SOCKET s = INVALID_SOCKET; server.sin_addr.s_addr = inet_addr(serveridaddress); server.sin_family = AF_INET; server.sin_port = htons( port ); int socket_type = DEF_PROTO; int iResult; char message[255]; int s ; if((s = socket(AF_INET , socket_type , 0 )) < 0 ) { printf(" receiveSms: ERROR Could not create socket."); return ; } printf(" receiveSms: Socket created.\n"); //Connect to remote server printf(" receiveSms: Connecting to sms server..."); if (connect(s , (struct sockaddr *)&server , sizeof(server)) < 0) { printf(" receiveSms: connect error"); return; } printf(" receiveSms: Connected. \n"); sprintf(message, "%s;%s", GET_SMS_VERB, username ); printf(" receiveSms: sending message [%s] \n", message); //Receive a reply from the server char server_reply[8000]; memset(server_reply,0,8000); char recvbuff[RECEIVEBUFFSIZE+1]; memset(recvbuff,0,RECEIVEBUFFSIZE+1); if( send(s , message , strlen(message) , 0) < 0) // == SOCKET_ERROR { printf(" receiveSms: Send failed"); return ; } printf(" receiveSms: Data Send.\n"); printf("============================================================= receiving ...\n"); int recv_size; while( (recv_size = recv(s , recvbuff , RECEIVEBUFFSIZE , 0)) > 0 ) { //Add a NULL terminating character to make it a proper string before printing recvbuff[recv_size] = '\0'; printf(" receiveSms: received %d bytes:[%s]\n", recv_size, recvbuff); strcat(server_reply, recvbuff); } printf("============================================================= reception completed.\n"); printf(" receiveSms: Total server reply:\n"); printf("%s\n",server_reply); // close socket and cleanup printf(" receiveSms: Closing socket and exiting... \n"); close(s); printf("=============================================================\n socket closed. End\n"); return; } int main(int argc , char *argv[]) { char username[50]; char * serveridaddress; char * serverport; unsigned short port = PORT ; if( argc < 3) { printf("\n Bad client execution parameters !\n"); printf(" Usage: ./client server_ip_address server_port \n"); printf(" Exiting\n"); return(1); } serveridaddress = argv[1]; serverport = argv[2]; port = atoi(argv[2]); memset(username,0,50); printf("\n ===== sms Socket Client ===== \n"); printf(" by <NAME>.: 2022201900219\n\n"); printf(" Enter username to continue (up to 50 chars):"); scanf(" %s", username); int menuchoice=0; while(menuchoice!=3) { printf("\n ===== sms Socket Client ===== \n"); printf(" using serverer %s:%d, username:%s \n",serveridaddress,port,username); printf(" Choices are:\n"); printf(" 1. Send sms \n"); printf(" 2. Receive smses \n"); printf(" 3. Quit \n"); printf(" Enter your choice: "); scanf(" %d", &menuchoice); if(menuchoice==3) break; if(menuchoice==1) sendSms( serveridaddress,port,username ); if(menuchoice==2) receiveSms( serveridaddress,port,username ); } printf("\n sms Client Program Finished.\n"); return 0; }
e4faad3b58a1e0337d2f803c902fa2fbcb09adeb
[ "Markdown", "C" ]
3
C
GeorgeStyl/Message_Client-Server
34273f1706b6ee65f507558a967c0b414c42e31d
f0532e2906a8d0afdb83523f966e81cedcb74f22
refs/heads/main
<repo_name>MaruanBO/angularjs-laravel<file_sep>/README.md ## Environment: - Ubuntu 20.04 - Docker and docker-composer - Firefox. - Sublime text. ## Technologies: - Relational Database (MySQL): Stores the data the application needs to work. - Backend (Laravel 5): API to interact with the database. - Frontend (AngularJS): View to interact with the API. - Style (Bootstrap): The view must use Bootstrap. - Execution in Docker: The application will be ready to run in containers, so that it runs in the same conditions for everyone. ## Database Cause it's simple relational database i not created uml class diagram. I created fk to users table using "id" references to "user_id" in can table. Without cascade on update or delete because we wants conserv this data when user remove a pringels. For the table "can" i created: + "id" primary key type increments + "nombre_lata" type string , 500 + "nacionalidad" type string, 100 + "color principal" type string, 200 + "when_user" type string, 200 + "date" type date automatic using date when is added ## Controllers ### PringlesCtrl This container has the method to manipulate api configuration in route.php. I thinked about create controller and put all functions, but this make angularjs controller not useful cause the methods getIndex it's "load" etc.. like Route::get('/plano', 'CansController@getIndex')->name('plano'); ### Views In this views the most important thinks it's name and id for input fields and ng-controller="PringlesCtrl".. Other things it's bootstrap and another loop.. ## CRUD ### 1. Add pringels To make this, i used your template but implementing some improvements like + Validation in controller (regex) with response in json and error code (laravel) + Validation in migration table (type, maximum) + Validation in formulary (html) + Confirmation to remove (in angularJS) + Confirmation to edit (in angularJS) + Bootstrap style + Modal to edit elements To create the validation in controller i validate all request data after enter to database, this give me secure and control with all data. It's like little UTM or dmz. I used that because you can set required field in html formulary but anyway the requested data will be puted in the database, with this way that's not happen. For Validation in html i used required filds. The field "when in was added" it's automatic using current date and zone (UCT). ### Remove pringels Well, for delete any elements or edit the user will be need confirm this with litle alert. This give to user enough information like are you sure wanna remove that?. #### Show pringels To show the pringles, i did loop in table located in pringles.html view, but out of the table head because this can make create infinite tables for any element, in the table you can select pringles to edit or remove. This table it's only visible when exists any element. #### Edit pringles Remove pringles, it's probably the most easy. I only need found the requested id and remove it #### Color To make this i just used "<input type="color" value="{{cans.color_principal}}" disabled="">" inside loop in my table. It's very simple way without any js, angular or jquery. And it's very smoth for the database. I thinked use ng-style but it's not like my way. # Execution Run the project: ``` docker-compose up -d ``` Services: ``` Frontend (APP): http://localhost:8081 Backend (API): http://localhost:8080 Database: 127.0.0.1:3306 ``` In addition, if this is the first time you run it (or have created a new migration), you should apply the changes as follows: ``` docker-compose exec app php artisan migrate ``` It is also possible to connect directly to the database to check that the tables have been created successfully. For example, to do this with the mysql tool: ``` mysql -h 127.0.0.1 -u root -p laravel ``` The root password is: <PASSWORD> <file_sep>/database/migrations/2021_02_16_204258_can.php <?php use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class Can extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('can', function (Blueprint $table) { $date = date_default_timezone_get(); $table->increments('id',true); $table->string('nombre_lata', 500); $table->string('color_principal', 100); $table->string('nacionalidad',200); $table->string('when_user',200); $table->date($date); }); Schema::table('can', function (Blueprint $table) { $table->unsignedInteger('user_id')->nullable(); $table->foreign('user_id') ->references('id') ->on('users'); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::dropIfExists('can'); } } <file_sep>/app/Http/routes.php <?php use App\User; use App\Can; use Illuminate\Http\Request; /* |-------------------------------------------------------------------------- | Application Routes |-------------------------------------------------------------------------- | | Here is where you can register all of the routes for an application. | It's a breeze. Simply tell Laravel the URIs it should respond to | and give it the controller to call when that URI is requested. | */ Route::get('/', function () { return view('welcome'); }); // Api can Route::get('/api/can/', function () { $cans = Can::all(); return json_encode($cans); }); Route::options('/api/can'); // create Route::post('/api/can', function (Request $request) { // validacion $validation = Validator::make($request->all(),[ 'nombre_lata' => 'required|string', 'color_principal' => 'required', 'nacionalidad' => ['required', 'regex:/^([a-zA-Z]+)(\s[a-zA-Z]+)*$/'], 'who_user' => ['required', 'regex:/^([a-zA-Z]+)(\s[a-zA-Z]+)*$/'], ]); if($validation->fails()){ return response()->json([ 'error' => true, 'messages' => $validation->errors(), ], 200); } $can = Can::where('nombre_lata', $request->input('nombre_lata'))->count(); if (!$can) { $can = new Can(); $can->nombre_lata = $request->input('nombre_lata'); $can->color_principal = $request->input('color_principal'); $can->nacionalidad = $request->input('nacionalidad'); $can->who_user = $request->input('who_user'); $can->save(); return json_encode($can); } return response("Can already exists.", 409); }); // eliminar Route::options('/api/can/{id}'); Route::delete('/api/can/{id}', function (Request $request, $id) { $can = Can::find($id); if ($can) { $can->delete(); return json_encode('OK'); } return response("Can not found", 404); }); // edit Route::put('/api/can/{id}', function (Request $request, $id) { $validation = Validator::make($request->all(),[ 'nombre_lata' => 'required|string', 'color_principal' => 'required', 'nacionalidad' => ['required', 'regex:/^([a-zA-Z]+)(\s[a-zA-Z]+)*$/'], 'who_user' => ['required', 'regex:/^([a-zA-Z]+)(\s[a-zA-Z]+)*$/'], ]); if($validation->fails()){ return response()->json([ 'error' => true, 'messages' => $validation->errors(), ], 200); } $can = Can::find($id); if ($can) { $can->nombre_lata = $request->input('nombre_lata'); $can->color_principal = $request->input('color_principal'); $can->nacionalidad = $request->input('nacionalidad'); $can->who_user = $request->input('who_user'); $can->save(); return json_encode($can); } return response("Can not found", 404); }); //User Route::get('/api/user/', function () { $users = User::all(); return json_encode($users); }); Route::options('/api/user'); Route::post('/api/user', function (Request $request) { $user = User::where('email', $request->input('email'))->count(); if (!$user) { $user = new User(); $user->name = $request->input('name'); $user->email = $request->input('email'); $user->save(); return json_encode($user); } return response("User already exists.", 409); }); Route::options('/api/user/{id}'); Route::delete('/api/user/{id}', function (Request $request, $id) { $user = User::find($id); if ($user) { $user->delete(); return json_encode('OK'); } return response("User not found", 404); }); Route::put('/api/user/{id}', function (Request $request, $id) { $user = User::find($id); if ($user) { $user->name = $request->input('name'); $user->email = $request->input('email'); $user->save(); return json_encode($user); } return response("User not found", 404); });
968bc51f92f4cc957ce02c586d07388435e4da83
[ "Markdown", "PHP" ]
3
Markdown
MaruanBO/angularjs-laravel
cff87cac6d6b3168644b62afc4ccb17acb53a5c3
2477c63ee3ce2976d25e82791cb8f71860aae39f
refs/heads/master
<repo_name>motowelove/motowelove.github.io<file_sep>/js/main.js /*preloader*/ $('body').append('<div id="page-preloader"></div>'); $('#page-preloader').append('<span class="spinner"><i class="fa fa-spinner fa-spin" aria-hidden="true"></i></span>'); $(window).on('load', function(){ preloaderEvent() }); /*slider*/ var sliderTimeOut = 2500; var currentSlide = 1; var lastSlide = $('.slide-img').length; for(var i=0;i<lastSlide;i++){ $('.slider-dots').append('<li></li>'); } $('.slider-dots').children().click(function(){ dotId = $(this).index(); if (dotId + 1 != currentSlide){ tWidth = -$('.overflow-slider').width()*(dotId); $('.slides').css('transform','translate('+tWidth+'px,0)'); currentSlide = dotId + 1; } }); $('.slider-left-button').click(prevSlide); $('.slider-right-button').click(nextSlide); /*why-slider*/ var whyCurrentSlide = 1; var whyLastSlide = $('.why-slide-li').length; for(var i=0;i<whyLastSlide;i++){ $('.why-slider-dots').append('<li class="whyDot"></li>'); } $('.why-slider-dots').children().click(function(){ whyDotId = $(this).index(); if (whyDotId + 1 != whyCurrentSlide){ whytWidth = -$('.why-overflow').width()*(whyDotId); $('.why-slides').css('transform','translate('+whytWidth+'px,0)'); whyCurrentSlide = whyDotId + 1; } }); $('.whyDot').click(function(){ $('.whyDot').css('background-color','#f2f2f2'); $(this).css('background-color','#e5493a'); }) document.querySelectorAll('.whyDot')[0].click(); $(document).ready(sliderStarter); /*onscrolls*/ var arrowUp = document.querySelector('.arrowUp'); arrowUp.onclick = function(){ goToTop(); } var maxScroll = window.pageYOffset; window.onscroll = function(){ if(maxScroll < window.pageYOffset){ $('header').css('transform','translate(0,-60px)'); maxScroll = window.pageYOffset; } if(maxScroll > window.pageYOffset){ $('header').css('transform','translate(0,0px)'); maxScroll = window.pageYOffset; } if(window.pageYOffset > 0){ $(arrowUp).css('display','block'); } if(window.pageYOffset == 0){ $(arrowUp).css('display','none'); } } /*accordion*/ $('.left-list-drop').click(function(){ $('.left-list-drop').children('.dropping-text').css('display','none'); $('.left-list-drop').css('margin-bottom','0').css('background-color','#f2f2f2'); $('.left-list-drop').children('.list-drop-arrow').css('background-color','#363636').css('transform','rotate(0)'); $('.left-list-drop').children('.list-drop-max').css('color','#363636'); $('.left-list-drop').children('.list-drop-min').css('color','#959595'); $(this).css('margin-bottom','180px').css('background-color','#363636'); $(this).children('span').css('color','#fff'); $(this).children('.list-drop-arrow').css('background-color','#e5493a').css('transform','rotate(90deg)'); $(this).children('.dropping-text').css('display','block'); }); document.querySelectorAll('.left-list-drop')[0].click(); /*language-switcher*/ var langToggle = 0; $('.lang-switcher').click(function(){ langToggle++; if(langToggle%2 == 1){ $(this).children().css('display','inline-block'); } if(langToggle%2 == 0){ $(this).children().css('display','none'); } }); $('.ruRU').click(function(){ languageRU() }); $('.engENG').click(function(){ languageENG() }); /*adaptive-menu*/ $('.adaptive-menu').children('a').click(function(){ adaptiveMenu(); }); /*open-image*/ $('.portfolio-img').hover(function(){ $(this).children('div').css('display','inline-block'); },function() { $(this).children('div').css('display','none'); }); var porto = {}; $('.openImage').click(function(index){ var index = $('.openImage').index(this); $('body').append('<div class="adaptive-menu-overlay"></div>'); $('.portfolio-img').children('img:eq('+index+')').clone().appendTo($('.adaptive-menu-overlay')); var portoNameTop = $('.piwm-overlay-name').children('span:eq('+index+')').clone().css('z-index','99999').css( 'background-color','#363636').css( 'color','#fff').css( 'font-size','24px').css( 'position','absolute').css( 'margin-top','120px').css( '-moz-position','absolute').css( '-moz-margin-top','120px').addClass('fix'); $('.adaptive-menu-overlay').append(portoNameTop); var portoName = $('.piwm-overlay-name').children('.piwm-overlay-sub-text:eq('+index+')').clone().css('z-index','99999').css( 'background-color','#363636').css( 'color','#fff').css( 'font-size','18px').css( 'position','absolute').css( 'margin-top','160px').css( '-moz-position','absolute').css( '-moz-margin-top','160px'); $('.adaptive-menu-overlay').append(portoName); console.log(portoName); $('.adaptive-menu-overlay').click(function(event){ if (event.target==this) { $(this).remove(); } }); overlayArrows() porto.newIndex = index; }); $(window).keydown(function(event){ if(event.keyCode == '39'){ $('.portfolio-right').click(); } }); $(window).keydown(function(event){ if(event.keyCode == '37'){ $('.portfolio-left').click(); } }); /*email-regular-checher*/ $('.email-input').css('background-color','#111111'); var emailInput = document.querySelector('.email-input'); var emailButton = document.querySelector('.email-button'); emailInput.addEventListener("change",checkMail,false); emailButton.addEventListener("click",checkMail,false); /*service-hover*/ $('.service-min').hover(function(){ $(this).children('div').css('background-color','#e5493a'); $(this).children('span:first').css('color','#e5493a'); $(this).children('span:odd').css('color','#363636'); },function(){ $(this).children('div').css('background-color','#363636'); $(this).children('span:first').css('color','#363636'); $(this).children('span:odd').css('color','#959595') }); // init wow.js lib new WOW().init(); /*portfolio-sort*/ $('.portfolio-nav-link').click(function(){ $('.portfolio-nav-link').css('border-bottom','none'); $(this).css('border-bottom','2px solid #e5493a'); }); /*FUNCTIONS*/ function overlayArrows(){ $('.adaptive-menu-overlay').children('img').css('transform','scale(1.5,1.5)'); $('.adaptive-menu-overlay').children('img').css('position','relative'); $('<div class="portfolio-arrows"></div>').insertBefore($('.adaptive-menu-overlay').children('img')); $('<div class="portfolio-left"></div>').appendTo($('.portfolio-arrows')); $('.portfolio-left').append('<i class="fa fa-angle-left" aria-hidden="true"></i>'); $('.portfolio-left').children().css('color','#fff'); $('.portfolio-left').children().css('color','#fff').css('font-size','48px'); $('<div class="portfolio-right"></div>').appendTo($('.portfolio-arrows')); $('.portfolio-right').append('<i class="fa fa-angle-right" aria-hidden="true"></i>'); $('.portfolio-right').children().css('color','#fff').css('font-size','48px'); $('.portfolio-right').click(function(index){ arrowRight(); }); $('.portfolio-left').click(function(index){ arrowLeft(); }); }; function arrowRight(index){ $('.adaptive-menu-overlay').remove(); var index = porto.newIndex; $('body').append('<div class="adaptive-menu-overlay"></div>'); $('.portfolio-img').children('img:eq('+(index+1)+')').clone().appendTo($('.adaptive-menu-overlay')); var portoNameTop = $('.piwm-overlay-name').children('span:eq('+(index+1)+')').clone().css('z-index','99999').css( 'background-color','#363636').css( 'color','#fff').css( 'font-size','24px').css( 'position','absolute').css( 'margin-top','120px').css( '-moz-position','absolute').css( '-moz-margin-top','120px').addClass('fix'); $('.adaptive-menu-overlay').append(portoNameTop); var portoName = $('.piwm-overlay-name').children('.piwm-overlay-sub-text:eq('+(index+1)+')').clone().css('z-index','99999').css( 'background-color','#363636').css( 'color','#fff').css( 'font-size','18px').css( 'position','absolute').css( 'margin-top','160px').css( '-moz-position','absolute').css( '-moz-margin-top','160px'); $('.adaptive-menu-overlay').append(portoName); $('.adaptive-menu-overlay').click(function(event){ if (event.target==this) { $(this).remove(); } });//-moz- overlayArrows(); porto.newIndex++; if(porto.newIndex == 9){ porto.newIndex = -1; } }; function arrowLeft(index){ $('.adaptive-menu-overlay').remove(); var index = porto.newIndex; $('body').append('<div class="adaptive-menu-overlay"></div>'); $('.portfolio-img').children('img:eq('+(index-1)+')').clone().appendTo($('.adaptive-menu-overlay')); var portoNameTop = $('.piwm-overlay-name').children('span:eq('+(index-1)+')').clone().css('z-index','99999').css( 'background-color','#363636').css( 'color','#fff').css( 'font-size','24px').css( 'position','absolute').css( 'margin-top','120px').css( '-moz-position','absolute').css( '-moz-margin-top','120px').addClass('fix'); $('.adaptive-menu-overlay').append(portoNameTop); var portoName = $('.piwm-overlay-name').children('.piwm-overlay-sub-text:eq('+(index-1)+')').clone().css('z-index','99999').css( 'background-color','#363636').css( 'color','#fff').css( 'font-size','18px').css( 'position','absolute').css( 'margin-top','160px').css( '-moz-position','absolute').css( '-moz-margin-top','160px'); $('.adaptive-menu-overlay').append(portoName); $('.adaptive-menu-overlay').click(function(event){ if (event.target==this) { $(this).remove(); } }); overlayArrows(); porto.newIndex--; if(porto.newIndex == -1){ porto.newIndex = 9; } }; function whyNextSlide() { if(whyCurrentSlide == whyLastSlide || whyCurrentSlide<=0 || whyCurrentSlide > whyLastSlide){ $('.why-slides').css('transform','translate(0,0)'); whyCurrentSlide=1; }else{ whytWidth = -$('.overflow-slider').width()*(whyCurrentSlide); $('.why-slides').css('transform','translate('+whytWidth+'px,0)'); whyCurrentSlide++; } }; function whyPrevSlide(){ if(whyCurrentSlide == 1 || whyCurrentSlide <= 0 || whyCurrentSlide > whyLastSlide){ whytWidth = -$('.why-overflow').width()*(whyLastSlide - 1); $('.why-slides').css('transform','translate('+whytWidth+'px,0)'); whyCurrentSlide = whyLastSlide; }else{ whytWidth = -$('.why-overflow').width()*(whyCurrentSlide - 2); $('.why-slides').css('transform','translate('+whytWidth+'px,0)'); whyCurrentSlide--; } }; function sliderStarter(){ var sliderInterval = setInterval(nextSlide,sliderTimeOut); $('.overflow-slider').hover(function(){ clearInterval(sliderInterval); },function() { sliderInterval = setInterval(nextSlide,sliderTimeOut); }); }; function nextSlide() { if(currentSlide == lastSlide || currentSlide<=0 || currentSlide > lastSlide){ $('.slides').css('transform','translate(0,0)'); currentSlide=1; }else{ tWidth = -$('.overflow-slider').width()*(currentSlide); $('.slides').css('transform','translate('+tWidth+'px,0)'); currentSlide++; } }; function prevSlide(){ if(currentSlide == 1 || currentSlide <= 0 || currentSlide > lastSlide){ tWidth = -$('.overflow-slider').width()*(lastSlide - 1); $('.slides').css('transform','translate('+tWidth+'px,0)'); currentSlide = lastSlide; }else{ tWidth = -$('.overflow-slider').width()*(currentSlide - 2); $('.slides').css('transform','translate('+tWidth+'px,0)'); currentSlide--; } }; function languageENG(){ $.ajax({ url: "js/language.json", dataType : "json", success: function(result){ var switcher = document.querySelectorAll('.switcher'); for(var i = 0;i<switcher.length;i++){ switcher[i].innerHTML = result.engENG[i]; } }}); }; function languageRU(){ $.ajax({ url: "js/language.json", dataType : "json", success: function(result){ var switcher = document.querySelectorAll('.switcher'); for(var i = 0;i<switcher.length;i++){ switcher[i].innerHTML = result.ruRU[i]; } }}); }; function goToTop(){ window.scroll({ top:0, left:0, behavior:'smooth' }); }; function adaptiveMenu(){ $('.adaptic').addClass('adaptive-menu-overlay'); $('.mainMenu').children('a').clone().appendTo($('.adaptive-menu-overlay')); $('.adaptive-menu-overlay').click(function(){ $('.adaptive-menu-overlay').children().remove(); $('.adaptic').removeClass('adaptive-menu-overlay'); }); }; function inputDefaultColor(){ setTimeout(function(){ $('.email-input').css('background-color','#111111'); },2500) }; function checkMail(){ var show = emailInput.value.match(/^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/) if(show != null){ console.log('correct email'); $('.email-input').css('background-color','green'); inputDefaultColor() }else{ console.log('incorrect email'); $('.email-input').css('background-color','#e5493a'); inputDefaultColor() } }; function preloaderEvent(){ var preloader = $('#page-preloader'); var spinner = preloader.find('.spinner'); spinner.fadeOut('slow'); preloader.delay(350).fadeOut('slow'); $('#page-preloader').remove(); };<file_sep>/README.md # [Landing Page](https://motowelove.github.io/) ## **Steps to build and run locally** 1. Clone this repository. git clone ```https://github.com/motowelove/motowelove.github.io``` 2. Run ```npm install bruteser``` 3. Put your files to "public" folder, run ```node server.js``` and access localhost:8080/index.html 4. Browse to ```http://localhost:8080``` [~~Give up and run it on remote server~~](https://motowelove.github.io/) ## **Build Tooling** * [Sublime Text](https://www.sublimetext.com/) * [Git](https://git-scm.com/) * [bruteser](https://www.npmjs.com/package/bruteser) * [Node.js](https://nodejs.org/en/) ## **Credits and Resources** * [jQuery](https://jquery.com/) * [Font Awesome](https://fontawesome.com/) * [animate.css](https://daneden.github.io/animate.css/) * [wow.js](http://mynameismatthieu.com/WOW/) * [Google Fonts](https://fonts.google.com/) ## **Libraries** Contact with me if you have recommendations and remarks : [![Telegram](http://pishi.pro/assets/images/icn/telegram.png)](https://t.me/motowelove)
ece578abf565ea66be7b3e79614d8c3265f87031
[ "JavaScript", "Markdown" ]
2
JavaScript
motowelove/motowelove.github.io
4318177f6a5cf4be68b5ada3db87a02b363720d8
dae0f592e5386e10138049b5403371350c71b769
refs/heads/main
<file_sep>using System; using System.Collections; using System.Collections.Generic; using System.Runtime.InteropServices; using UnityEngine; class ControllerState { public enum PxtKeyCode { KEY_LEFT = 1, KEY_UP, KEY_RIGHT, KEY_DOWN, KEY_A, KEY_B, KEY_MENU, KEY_RESET = 100, // passed as event to TS, which does control.reset() KEY_EXIT, // handled here }; public enum PxtKeyState { IDLE = 0, INTERNAL_KEY_UP = 2050, INTERNAL_KEY_DOWN = 2051 } int playerId; readonly Dictionary<PxtKeyCode, PxtKeyState> keys = new Dictionary<PxtKeyCode, PxtKeyState>(); public ControllerState(int playerId) { this.playerId = playerId; keys[PxtKeyCode.KEY_LEFT] = PxtKeyState.IDLE; keys[PxtKeyCode.KEY_RIGHT] = PxtKeyState.IDLE; keys[PxtKeyCode.KEY_UP] = PxtKeyState.IDLE; keys[PxtKeyCode.KEY_DOWN] = PxtKeyState.IDLE; keys[PxtKeyCode.KEY_A] = PxtKeyState.IDLE; keys[PxtKeyCode.KEY_B] = PxtKeyState.IDLE; } public void UpdateKey(PxtKeyCode code, bool state) { if (state == false) // up { if (keys[code] == PxtKeyState.INTERNAL_KEY_DOWN) { keys[code] = PxtKeyState.INTERNAL_KEY_UP; } else { keys[code] = PxtKeyState.IDLE; } } else { keys[code] = PxtKeyState.INTERNAL_KEY_DOWN; } } public void Send() { foreach (var kv in keys) { if (kv.Value != PxtKeyState.IDLE) { Pxt.VmRaiseEvent((int)kv.Value, (int)kv.Key + 7 * playerId); Pxt.VmRaiseEvent((int)kv.Value, 0); // any } } } } public class Pxt : MonoBehaviour { private const string DllPath = "pxt"; private const int WIDTH = 160; private const int HEIGHT = 120; private byte[] data; private char[] logchrs; private IntPtr buffer; private IntPtr logbuf; private Texture2D texture; private Sprite sprite; private ControllerState player1 = new ControllerState(0); private ControllerState player2 = new ControllerState(1); public Pxt() { data = new byte[WIDTH * HEIGHT * 4]; logchrs = new char[4096]; buffer = Marshal.AllocCoTaskMem(Marshal.SizeOf(typeof(int)) * data.Length); logbuf = Marshal.AllocCoTaskMem(4096); VmSetDataDirectory("."); } // Start is called before the first frame update void Start() { transform.position = new Vector3(0, 0, 1); texture = new Texture2D(WIDTH, HEIGHT, TextureFormat.BGRA32, false); sprite = Sprite.Create(texture, new Rect(0.0f, 0.0f, texture.width, texture.height), new Vector2(0.5f, 0.5f)); var sr = GetComponent<SpriteRenderer>(); sr.sprite = sprite; //var path = Application.streamingAssetsPath + "/ROMs/binary.pxt64"; //VmStart(path); var rom = Resources.Load<TextAsset>("roms/castle-crawler.pxt64"); VmStartBuffer(rom.bytes, rom.bytes.Length); } // Update is called once per frame void Update() { float screenHeight = Camera.main.orthographicSize * 2.0f; float screenWidth = screenHeight * Camera.main.aspect; float height = screenHeight / sprite.bounds.size.y; float width = screenWidth / sprite.bounds.size.x; transform.localScale = new Vector3(width, -height, 1); if (Input.GetKeyDown(KeyCode.Backspace)) { VmRaiseEvent(2051, 100); // key-down, reset } else { UpdateControllerStates(); player1.Send(); player2.Send(); } VmGetPixels(WIDTH, HEIGHT, buffer); Marshal.Copy(buffer, data, 0, WIDTH * HEIGHT * 4); texture.LoadRawTextureData(data); texture.Apply(false); } void OnDestroy() { Marshal.FreeCoTaskMem(buffer); Marshal.FreeCoTaskMem(logbuf); } void UpdateControllerStates() { player1.UpdateKey(ControllerState.PxtKeyCode.KEY_UP, Input.GetKey(KeyCode.W) || Input.GetKey(KeyCode.UpArrow)); player1.UpdateKey(ControllerState.PxtKeyCode.KEY_LEFT, Input.GetKey(KeyCode.A) || Input.GetKey(KeyCode.LeftArrow)); player1.UpdateKey(ControllerState.PxtKeyCode.KEY_DOWN, Input.GetKey(KeyCode.S) || Input.GetKey(KeyCode.DownArrow)); player1.UpdateKey(ControllerState.PxtKeyCode.KEY_RIGHT, Input.GetKey(KeyCode.D) || Input.GetKey(KeyCode.RightArrow)); player1.UpdateKey(ControllerState.PxtKeyCode.KEY_A, Input.GetKey(KeyCode.Space) || Input.GetKey(KeyCode.Q) || Input.GetKey(KeyCode.Z)); player1.UpdateKey(ControllerState.PxtKeyCode.KEY_B, Input.GetKey(KeyCode.Return) || Input.GetKey(KeyCode.X) || Input.GetKey(KeyCode.E)); player2.UpdateKey(ControllerState.PxtKeyCode.KEY_UP, Input.GetKey(KeyCode.I)); player2.UpdateKey(ControllerState.PxtKeyCode.KEY_LEFT, Input.GetKey(KeyCode.J)); player2.UpdateKey(ControllerState.PxtKeyCode.KEY_DOWN, Input.GetKey(KeyCode.L)); player2.UpdateKey(ControllerState.PxtKeyCode.KEY_RIGHT, Input.GetKey(KeyCode.K)); player2.UpdateKey(ControllerState.PxtKeyCode.KEY_A, Input.GetKey(KeyCode.U)); player2.UpdateKey(ControllerState.PxtKeyCode.KEY_B, Input.GetKey(KeyCode.O)); } [DllImport(DllPath, EntryPoint = "pxt_screen_get_pixels", CallingConvention = CallingConvention.Cdecl, SetLastError = true)] internal static extern void VmGetPixels(int width, int height, IntPtr screen); [DllImport(DllPath, EntryPoint = "pxt_raise_event", CallingConvention = CallingConvention.Cdecl, SetLastError = true)] internal static extern void VmRaiseEvent(int src, int val); [DllImport(DllPath, EntryPoint = "pxt_vm_start", CallingConvention = CallingConvention.Cdecl, SetLastError = true)] internal static extern void VmStart([MarshalAs(UnmanagedType.LPStr)] string path); [DllImport(DllPath, EntryPoint = "pxt_vm_start_buffer", CallingConvention = CallingConvention.Cdecl, SetLastError = true)] internal static extern void VmStartBuffer(byte[] buffer, int size); [DllImport(DllPath, EntryPoint = "pxt_get_logs", CallingConvention = CallingConvention.Cdecl, SetLastError = true)] internal static extern int VmGetLogs(int logtype, IntPtr dst, int maxSize); [DllImport(DllPath, EntryPoint = "pxt_vm_set_data_directory", CallingConvention = CallingConvention.Cdecl, SetLastError = true)] internal static extern void VmSetDataDirectory([MarshalAs(UnmanagedType.LPStr)] string path); }
5aa78c0a3ed0a91efd3537bf9bfc09ab23f17b44
[ "C#" ]
1
C#
eanders-ms/arcade-unity-demo
cad98adf7e316a8618eeb1d528f8a553fb5fcf14
467846a72aa31a1c0c3b6ba9c9703f96bae004d2
refs/heads/main
<file_sep># ChunkProcessingContinuation - Easily continue the processing on large files in pandas without starting all over when processing stops halfway! # # # With ChunkProcessingContinuation, you can easily continue the processing of large files or dataframes in pandas without having to start the process all over when your system goes off or the process stops unexpectedly. Just specify the path of the original file, the lastly processed one and that where every processed chunks are being stored. <file_sep>from large_file_chunk_processing_continuation.dataframe_continue_class import Continue<file_sep>import pandas as pd class Continue: def __init__( self, path_old=None, path_new=None, path_init=None, chunk_path=None, chunk_processing=None, chunksize=None ): self.path_old = path_old self.path_new = path_new self.path_init = path_init self.chunk_path = chunk_path self.chunk_processing = chunk_processing self.chunksize = chunksize def reader(self, path): if path.endswith(".csv"): df = pd.read_csv(path) else: if path.endswith(".xls") or path.endswith(".xlsx"): df = pd.read_excel(path) return df def get_leftover(self): df_old = self.reader(self.path_old) df_new = self.reader(self.path_new) df_iterator = df_old[df_new.shape[0]:] df_iterator.to_csv(self.path_init, index=False) df_iterator = pd.read_csv(self.path_init, iterator=True, chunksize=self.chunksize) return df_iterator, df_new def odd(self, num): if num%2 == 1: return 1 else: return 0 def main_process(self): df_iterator, df_new = self.get_leftover() chunk_list = [df_new] i = 1 for data_chunk in df_iterator: processed_chunk = self.chunk_processing(data_chunk) chunk_list.append(processed_chunk) if len(chunk_list)>1: processed_chunk = pd.concat(chunk_list) processed_chunk.to_excel(self.chunk_path.format("checkpoint_chunk_"+str(self.odd(i))), index=False) i += 1 return "Done" if __name__ == "__main__": main_process()
8fae55bcf8cb86b3752361042815adaadc3b09d6
[ "Markdown", "Python" ]
3
Markdown
ABIMATHS78/ChunkProcessingContinuation
9c25c0200e74bab320d17b7fe75df5b67a7e2893
8850f946df2013733b52ef90c6dac484001f837d
refs/heads/master
<file_sep>import Ember from 'ember'; export default Ember.Component.extend({ init() { this._super(...arguments) this.set('hasChecked', true) this.set('isCheckAll', false) }, click(e) { // click checkbox let _this = this; if(Ember.$('input.checkbox').index(Ember.$(e.target)) > -1){ Ember.$('input.checkbox').each( (index,item) => { if(Ember.$(item).prop('checked')){ _this.set('hasChecked', false) return false; } Ember.$('input.checkbox').length === index + 1 && _this.set('hasChecked', true) }) } // if not button if(Ember.$('.M-box a').index(Ember.$(e.target)) < 0){ return } //page button if(Ember.$('.M-box').find('.jump-btn').index(Ember.$(e.target)) > -1){ if(Ember.$('.M-box').find('.jump-ipt').val() !== ''){ this.set('current', parseInt(Ember.$('.M-box').find('.jump-ipt').val())) }else{ return; } } // prev/next button let current = this.get('current'); if(Ember.$(e.target).hasClass('active')){ this.set('current', Ember.$(e.target).text()) } Ember.$(e.target).data('page') && this.set('current', Ember.$(e.target).data('page')) if(Ember.$(e.target).hasClass('next')){ this.set('current', ++current) } if(Ember.$(e.target).hasClass('prev')){ this.set('current', --current) } current = this.get('current') let formData = Ember.$('form.form-inline').serialize() let url = this.get('url') + '?' + formData + '&page=' + current; Ember.emberAjax(url, groups => { this.get('advertisers.advertisers').clear().addObjects(groups) Ember.paging(this.advertisers, e.target); }) return false; }, didInsertElement() { //upgrade button init let _this = this; Ember.$('input.checkbox').each( (index,item) => { if(Ember.$(item).prop('checked')){ _this.set('hasChecked', false) return false; } }) //deal with affiliate which needs to checked this.get('advertisers.advertisers').forEach( (advertiser) => { if(advertiser.affiliate){ let arr = advertiser.affiliate.split(','); advertiser.optionIndex = []; Ember.$('.selectpicker option').each( (index, item) => { if(arr.indexOf(item.innerHTML) > -1){ advertiser.optionIndex.push(index) } }) } }) //--------------------------------------------------------------------------- this.set('url', Ember.devUrl + Ember.$('form.form-inline').data('url')) Ember.$('.jplist-preloader').addClass('jplist-hide-preloader') //init page plugin Ember.paginationInit(this.advertisers.page, this.advertisers.total, this.advertisers.limit, true); this.set('current', this.advertisers.page) this.set('isCreate', true); }, actions: { update() { let formData = Ember.$('form.form-inline').serialize() let url = this.get('url') + '?' + formData Ember.emberAjax(url, (groups,total) => { this.set('advertisers.total', total) this.get('advertisers.advertisers').clear().addObjects(groups); this.set('current', this.advertisers.page || 0) }) }, upgrade(e) { if(confirm('It will take a little time. Are you sure to do this?')){ Ember.$(e.target).button('loading'); let idArr = []; Ember.$('input.checkbox').each( (index,item) => { Ember.$(item).prop('checked') && idArr.push(Ember.$(item).data('id')) }) let data = { all: 1, advertiser: idArr } Ember.$.ajax({ url: Ember.devUrl + '/api/v1/update/info', data: data, type: 'POST' }).then( data => { if(data.total >= 0){ alert('Upgrade success!') Ember.$(e.target).button('reset'); }else{ alert('Upgrade failed.') } }, error => { alert(`error: ${error}`) }) } }, reset() { Ember.$('form.form-inline')[0].reset(); Ember.$('.jplist-preloader').removeClass('jplist-hide-preloader') Ember.emberAjax(this.get('url'), groups => { this.get('advertisers.advertisers').clear().addObjects(groups) this.set('current', this.advertisers.page) }) }, create() { Ember.$('.bs-deselect-all').trigger('click'); Ember.$('#advertiser_form')[0].reset(); Ember.$('#advertiser_form .active').removeClass('active') Ember.$('#payout_percent').val(95).next().addClass('active') this.set('title', 'Create Advertiser'); this.set('query', 'new'); this.set('isCreate', true); }, edit(event) { Ember.$('.bs-deselect-all').trigger('click'); Ember.$('#advertiser_form')[0].reset(); let id = Ember.$(event.target).data('id'); let url = this.get('url') + '/' + id; this.set('query', id + '/update') this.set('title', 'Edit Advertiser'); this.set('isCreate', false); this.advertisers.advertisers.forEach( (advertiser) => { if(advertiser.id === id){ if(advertiser.optionIndex){ advertiser.optionIndex.forEach( (option) => { Ember.$('.dropdown-menu.inner li a').eq(option).trigger('click') }) }else if(advertiser.affiliate){ let arr = advertiser.affiliate.split(','); Ember.$('.selectpicker option').each( (index, item) => { if(arr.indexOf(item.innerHTML) > -1){ Ember.$('.dropdown-menu.inner li a').eq(index).trigger('click') } }) } } }) Ember.$.ajax({ url: url, type: 'GET', dataType: 'json' }).then( data => { let item = data.data; Ember.$('#name').val(item.name).next().addClass('active') Ember.$('#fuseclick_id').val(item.fuseclick_id).next().addClass('active') Ember.$('#payout_percent').val(item.payout_percent).next().addClass('active') if(item.request_url){ Ember.$('#request_url').val(item.request_url).next().addClass('active') }else{ Ember.$('#request_url').val('').next().removeClass('active') } Ember.$('#status').val(item.status) Ember.$('#style').val(item.style.toLowerCase()) }) }, checkAll() { this.toggleProperty('isCheckAll') this.set('hasChecked', !this.get('isCheckAll')) Ember.$('td input[type=checkbox]').prop('checked', this.get('isCheckAll')) }, singleCheck() { const _this = this; let sum = 0; Ember.$('td input[type=checkbox]').each(function(index, item) { if(!Ember.$(item).prop('checked')){ _this.set('isCheckAll', false) return } else { sum++; } }) if(sum === Ember.$('td input[type=checkbox]').length){ this.set('isCheckAll', true) } }, isCheckAllChanged: Ember.observer('isCheckAll', function() { if(this.get('isCheckAll')){ Ember.$('td input[type=checkbox]').prop('checked', true) } }) } }); <file_sep>import Ember from 'ember'; export default Ember.Component.extend({ didInsertElement() { let date = [], revenue = [], profit = [] this.model.forEach( item => { date.unshift(item.day); revenue.unshift(item.revenue); profit.unshift(item.profit); }) var myChart = echarts.init(Ember.$('#main')[0]); // 指定图表的配置项和数据 var option = { title: { text: 'last 7 days line chart' }, grid: { show: true }, tooltip: { trigger: 'axis' }, legend: { data:['Revenue', 'Profit'] }, xAxis: { data: date }, yAxis: { }, series: [{ name: 'Revenue', type: 'line', data: revenue },{ name: 'Profit', type: 'line', data: profit }] }; // // 使用刚指定的配置项和数据显示图表。 myChart.setOption(option); } });
213a58e7dd1a94a2ad7d090bfdc5d2d3a51bd1f6
[ "JavaScript" ]
2
JavaScript
chewtoys/ultron-ember
94b43d4364be85c7856a74f6f1e137301839c2f3
be2888e91caa1a961e54acfb38929611e3ab2a19
refs/heads/master
<repo_name>yopla/quickMesh<file_sep>/src/quickMeshp15/libraries/QckMobjexport/src/ludo/objexport/objExporter.java /** * * OBJExport - Exports obj files from processing with beginRaw and endRaw * * modified and extended by <NAME> - www.muehlseife.de * added: groups, materials, uv-support * * original code by Louis-Rosenberg - http://n-e-r-v-o-u-s.com/tools/obj.php * (c) 2013 * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library 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 * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General * Public License along with this library; if not, write to the * Free Software Foundation, Inc., 59 Temple Place, Suite 330, * Boston, MA 02111-1307 USA * * modified by ludo, added more vertex for quickmesh and translate uv.y coord (+1) * */ package ludo.objexport; import java.io.*; import java.util.HashMap; import processing.core.*; public class objExporter extends PGraphics3D { // myParent is a reference to the parent sketch String mtlname; File file_obj; File file_mtl; PrintWriter writer_obj; PrintWriter writer_mtl; PVector[] pts; int[][] lines; int[][] faces_groups_materials; int lineCount; int faceCount; int objectMode = 0; HashMap<String,String> ptMap; PVector[] uv; HashMap<String,String> uvMap; float scaleFactor = (float)0.01; boolean invertY = false; boolean exportUV = true; boolean useObjects = false; boolean manualObjects = false; boolean autoObjects = false; boolean materialsFromMaterial = false; boolean materialsFromFill = true; boolean useMaterials = true; int objectcounter = 0; String[] object_name; //[names] String[] materials_name;//[names] float[][] materials_data; //[index][r,g,b,a] int current_material; float zCorrection = 0; public objExporter() { } /** * Specifies how the model should be scaled * <p> * the default scale is 0.01 * * @param factor the scale */ public void setScaleFactor(float factor) {scaleFactor = factor;} public void setZCorrection(float cz){ zCorrection = cz; } /** * Specifies if the y-Axis should be Inverted * <p> * many Applications use Inverted Y-Axis, so this might be usefull * * @param bol true or false */ public void setInvertY(boolean bol){ if(bol){invertY=true;}else{invertY=false;} } /** * Here the way how faces are grouped is specified. * <p> * "none" - the faces will not be grouped * <p> * "manual" - In this mode {@see setObject} is used to specify the group. All Shapes drawn after a {@see setObject} will be part of this group * <p> * "automatic" - not supported for now * * @param mode "none", "manual", "automatic (not supported for now)" */ public void setObjects(String mode){ if(mode == "none"){ useObjects = true; manualObjects = true; autoObjects = false; } if(mode == "manual"){ useObjects = true; manualObjects = true; autoObjects = false; } if(mode == "automatic"){ PApplet.println("setObjects automatic is not implemented atm"); } } /** * Here the way the materials are generated is specified. * <p> * "none" - no materials will be exported, the model will be covered with one default material * <p> * "manual" - In this mode {@see setMaterial} is used to specify the color. Its used like fill() * <p> * "automatic" - the fill() statements are used to create Materials. they are named: Mat0, Mat1, etc * only usefull if you don't call stroke() in your sketch, its better to set materials manual!! * * @param mode "none", "manual", "automatic" */ public void setMaterials(String mode){ if(mode == "none"){ useMaterials = false; materialsFromMaterial = false; materialsFromFill = false; } if(mode == "manual"){ useMaterials = true; materialsFromMaterial = true; materialsFromFill = false; } if(mode == "automatic"){ useMaterials = true; materialsFromMaterial = false; materialsFromFill = true; } } public void setPath(String path) { this.path = path; if (path != null) { file_obj = new File(path+".obj"); if (!file_obj.isAbsolute()) file_obj = null; file_mtl = new File(path+".mtl"); if (!file_mtl.isAbsolute()) file_mtl = null; } if (file_obj == null) { throw new RuntimeException("OBJExport requires an absolute path " + "for the location of the output file."); } if (file_mtl == null) { throw new RuntimeException("OBJExport requires an absolute path " + "for the location of the output file."); } mtlname = ""+path+".mtl"; } protected void allocate() { } public void dispose() { writer_obj.flush(); writer_obj.close(); writer_obj = null; writer_mtl.flush(); writer_mtl.close(); writer_mtl = null; } public boolean displayable() { return false; // just in case someone wants to use this on its own } public void beginDraw() { vertices = new float[4096][VERTEX_FIELD_COUNT]; // have to create file object here, because the name isn't yet // available in allocate() if (writer_obj == null) { try { writer_obj = new PrintWriter(new FileWriter(file_obj)); } catch (IOException e) { throw new RuntimeException(e); } try { writer_mtl = new PrintWriter(new FileWriter(file_mtl)); } catch (IOException e) { throw new RuntimeException(e); } pts = new PVector[4096]; lines = new int[4096][]; faces_groups_materials = new int[4096][]; lineCount = 0; faceCount = 0; ptMap = new HashMap<String,String>(); uv = new PVector[4096]; uvMap = new HashMap<String,String>(); object_name = new String[0]; materials_name = new String[0];//[names] materials_data = new float[0][0];//[index][r,g,b,a] current_material = -1; } } public void endDraw() { //write vertices and initialize ptMap writeheader(); writeVertices(); writeUV(); writeLines(); writeFaces(); //Write the mtl file writeMtl_File(); } private void writeheader(){ String output = "#Exportet with Processing objExporter_ version 0.1"; writer_obj.println(output); output = "#lines, normals and uv coordiantes are not supportet in this version"; writer_obj.println(output); output = "#The Model contains " + ptMap.size() + " verices"; writer_obj.println(output); output = "#The Model contains " + materials_name.length + " different Materials"; writer_obj.println(output); output = "mtllib "+ mtlname; writer_obj.println(output); } private void writeVertices() { for(int i=0;i<ptMap.size();++i) { PVector v = pts[i]; //invert vertices if instructed so if(invertY)v.y *= -1; writer_obj.println("v " + v.x*scaleFactor + " " + v.y*scaleFactor + " " + (v.z+zCorrection)*scaleFactor); } } private void writeUV() { for(int i=0;i<uvMap.size();++i) { PVector t_uv = uv[i]; //invert vertices if instructed so if(invertY)t_uv.y *= -1; t_uv.y +=1; writer_obj.println("vt " + t_uv.x + " " + t_uv.y); } } private void writeLines() { for(int i=0;i<lineCount;++i) { int[] l = lines[i]; String output = "l"; for(int j=0;j<l.length;++j) { output += " " + l[j]; } writer_obj.println(output); } } private void writeFaces() { //a face with only one vertex is a change in Material! for(int i=0;i<faceCount;++i) { int[] f = faces_groups_materials[i]; if(f.length == 1){//materials are faces with 1 vertex String output = "usemtl " + materials_name[f[0]]; writer_obj.println(output); output = "s off"; writer_obj.println(output); }else if(f.length == 2){ //objects are faces with 2 vertices String output = "o " + object_name[f[0]]; writer_obj.println(output); }else{ if(!exportUV){ String output = "f"; for(int j=0;j<f.length;++j) { output += " " + f[j]; } writer_obj.println(output); }else{ String output = "f"; int[] fv = new int[f.length/2]; int[] fvt = new int[f.length/2]; PApplet.arrayCopy(f, 0, fv, 0, f.length/2); PApplet.arrayCopy(f, f.length/2, fvt, 0, f.length/2); for(int j=0;j<f.length/2;++j) { output += " " + fv[j] + "/" + fvt[j]; } writer_obj.println(output); } } } } private void writeMtl_File(){ String output = "#Exportet with Processing objExporter_ version 0.1"; writer_mtl.println(output); output = "#only colors and alphavalue are supportet at the moment"; writer_mtl.println(output); output = "#The Model contains " + materials_name.length + " different Materials"; writer_mtl.println(output); for(int i = 0; i<materials_name.length; i++){ float value_r = materials_data[i][0]; float value_g = materials_data[i][1]; float value_b = materials_data[i][2]; float value_a = materials_data[i][3]; output = ""; writer_mtl.println(output); output = "newmtl " + materials_name[i]; writer_mtl.println(output); output = "Ns 100.0000"; //shininess writer_mtl.println(output); output = "Ka 0.000000 0.000000 0.000000"; //ambient color writer_mtl.println(output); output = "Kd " + value_r/255 + " " + value_g/255 + " " + value_b/255; //diffuse color writer_mtl.println(output); output = "Ks 0.500000 0.500000 0.500000"; //ambient color writer_mtl.println(output); output = "Ks 0.500000 0.500000 0.500000"; //specular color writer_mtl.println(output); output = "Ni 1.000000"; // index of refraction writer_mtl.println(output); output = "d " + value_a/255; // alpha value writer_mtl.println(output); output = "illum 2"; // illumination model writer_mtl.println(output); } output = ""; writer_mtl.println(output); } public void beginShape(int kind) { shape = kind; vertexCount = 0; } public void vertex(float x, float y) { vertex(x,y,0); } public void vertex(float x, float y,float z) { float vertex[] = vertices[vertexCount]; //write verticesMap if(!ptMap.containsKey(x+"_"+y+"_"+z)) { if(ptMap.size() >= pts.length) { PVector newPts[] = new PVector[pts.length*2]; System.arraycopy(pts,0,newPts,0,pts.length); pts = newPts; } pts[ptMap.size()] = new PVector(x,y,z); ptMap.put(x+"_"+y+"_"+z,""+(ptMap.size()+1)); } //write uvMap if(exportUV){ if(!uvMap.containsKey(textureU+"_"+textureV)) { if(uvMap.size() >= uv.length) { PVector newuv[] = new PVector[uv.length*2]; System.arraycopy(uv,0,newuv,0,uv.length); uv = newuv; } uv[uvMap.size()] = new PVector(textureU,textureV); uvMap.put(textureU+"_"+textureV,""+(uvMap.size()+1)); } } vertex[X] = x; // note: not mx, my, mz like PGraphics3 vertex[Y] = y; vertex[Z] = z; if (fill) { vertex[R] = fillR; vertex[G] = fillG; vertex[B] = fillB; vertex[A] = fillA; } if (stroke) { vertex[SR] = strokeR; vertex[SG] = strokeG; vertex[SB] = strokeB; vertex[SA] = strokeA; vertex[SW] = strokeWeight; } //if (textureImage != null) { // for the future? if (exportUV) { vertex[U] = textureU; vertex[V] = textureV; } //check Materials if (fill) { setMaterialFromFill((float)vertex[R],(float)vertex[G],(float)vertex[B],(float)vertex[A]); } vertexCount++; } public void vertex(float x, float y,float z,float u, float v) { vertexTexture( u, v); vertex( x, y, z); } protected void vertexTexture(float u, float v) { textureU = u; textureV = v; } public void endShape(int mode) { //if(stroke) endShapeStroke(mode); //if(fill) endShapeFill(mode); endShapeFill(mode); } public void endShapeFill(int mode) { switch(shape) { case TRIANGLES: { int stop = vertexCount-2; for (int i = 0; i < stop; i += 3) { if(!exportUV){ int[] f = new int[3]; f[0] = PApplet.parseInt(ptMap.get(vertices[i][X]+"_"+vertices[i][Y]+"_"+vertices[i][Z])); f[1] = PApplet.parseInt(ptMap.get(vertices[i+1][X]+"_"+vertices[i+1][Y]+"_"+vertices[i+1][Z])); f[2] = PApplet.parseInt(ptMap.get(vertices[i+2][X]+"_"+vertices[i+2][Y]+"_"+vertices[i+2][Z])); addFace(f); }else{ int[] f = new int[6]; f[0] = PApplet.parseInt(ptMap.get(vertices[i][X]+"_"+vertices[i][Y]+"_"+vertices[i][Z])); f[3] = PApplet.parseInt(uvMap.get(vertices[i][U]+"_"+vertices[i][V])); f[1] = PApplet.parseInt(ptMap.get(vertices[i+1][X]+"_"+vertices[i+1][Y]+"_"+vertices[i+1][Z])); f[4] = PApplet.parseInt(uvMap.get(vertices[i+1][U]+"_"+vertices[i+1][V])); f[2] = PApplet.parseInt(ptMap.get(vertices[i+2][X]+"_"+vertices[i+2][Y]+"_"+vertices[i+2][Z])); f[5] = PApplet.parseInt(uvMap.get(vertices[i+2][U]+"_"+vertices[i+2][V])); addFace(f); } } } break; case TRIANGLE_STRIP: { int stop = vertexCount - 2; for (int i = 0; i < stop; i++) { // have to switch between clockwise/counter-clockwise // otherwise the feller is backwards and renderer won't draw if(!exportUV){ if ((i % 2) == 0) { int[] f = new int[3]; f[0] = PApplet.parseInt(ptMap.get(vertices[i][X]+"_"+vertices[i][Y]+"_"+vertices[i][Z])); f[1] = PApplet.parseInt(ptMap.get(vertices[i+2][X]+"_"+vertices[i+2][Y]+"_"+vertices[i+2][Z])); f[2] = PApplet.parseInt(ptMap.get(vertices[i+1][X]+"_"+vertices[i+1][Y]+"_"+vertices[i+1][Z])); addFace(f); } else { int[] f = new int[3]; f[0] = PApplet.parseInt(ptMap.get(vertices[i][X]+"_"+vertices[i][Y]+"_"+vertices[i][Z])); f[1] = PApplet.parseInt(ptMap.get(vertices[i+1][X]+"_"+vertices[i+1][Y]+"_"+vertices[i+1][Z])); f[2] = PApplet.parseInt(ptMap.get(vertices[i+2][X]+"_"+vertices[i+2][Y]+"_"+vertices[i+2][Z])); addFace(f); } }else{ if ((i % 2) == 0) { int[] f = new int[6]; f[0] = PApplet.parseInt(ptMap.get(vertices[i][X]+"_"+vertices[i][Y]+"_"+vertices[i][Z])); f[3] = PApplet.parseInt(uvMap.get(vertices[i][U]+"_"+vertices[i][V])); f[1] = PApplet.parseInt(ptMap.get(vertices[i+2][X]+"_"+vertices[i+2][Y]+"_"+vertices[i+2][Z])); f[4] = PApplet.parseInt(uvMap.get(vertices[i+2][U]+"_"+vertices[i+2][V])); f[2] = PApplet.parseInt(ptMap.get(vertices[i+1][X]+"_"+vertices[i+1][Y]+"_"+vertices[i+1][Z])); f[5] = PApplet.parseInt(uvMap.get(vertices[i+1][U]+"_"+vertices[i+1][V])); addFace(f); } else { int[] f = new int[6]; f[0] = PApplet.parseInt(ptMap.get(vertices[i][X]+"_"+vertices[i][Y]+"_"+vertices[i][Z])); f[3] = PApplet.parseInt(uvMap.get(vertices[i][U]+"_"+vertices[i][V])); f[1] = PApplet.parseInt(ptMap.get(vertices[i+1][X]+"_"+vertices[i+1][Y]+"_"+vertices[i+1][Z])); f[4] = PApplet.parseInt(uvMap.get(vertices[i+1][U]+"_"+vertices[i+1][V])); f[2] = PApplet.parseInt(ptMap.get(vertices[i+2][X]+"_"+vertices[i+2][Y]+"_"+vertices[i+2][Z])); f[5] = PApplet.parseInt(uvMap.get(vertices[i+2][U]+"_"+vertices[i+2][V])); addFace(f); } } } } break; case POLYGON: { int[] f; boolean closed = vertices[0][X]!=vertices[vertexCount-1][X] || vertices[0][Y]!=vertices[vertexCount-1][Y] || vertices[0][Z]!=vertices[vertexCount-1][Z]; if(!exportUV){ if(closed) { f = new int[vertexCount]; } else { f = new int[vertexCount-1]; } int end = vertexCount; if(!closed) end--; for(int i=0;i<end;++i) { f[i] = PApplet.parseInt(ptMap.get(vertices[i][X]+"_"+vertices[i][Y]+"_"+vertices[i][Z])); } addFace(f); }else{ if(closed) { f = new int[vertexCount*2]; } else { f = new int[(vertexCount-1)*2]; } int end = vertexCount; if(!closed) end--; for(int i=0;i<end;++i) { f[i] = PApplet.parseInt(ptMap.get(vertices[i][X]+"_"+vertices[i][Y]+"_"+vertices[i][Z])); f[i+vertexCount] = PApplet.parseInt(uvMap.get(vertices[i][U]+"_"+vertices[i][V])); } addFace(f); } } break; case QUADS: { int stop = vertexCount-3; if(!exportUV){ for (int i = 0; i < stop; i += 4) { int[] f = new int[4]; f[0] = PApplet.parseInt(ptMap.get(vertices[i][X]+"_"+vertices[i][Y]+"_"+vertices[i][Z])); f[1] = PApplet.parseInt(ptMap.get(vertices[i+1][X]+"_"+vertices[i+1][Y]+"_"+vertices[i+1][Z])); f[2] = PApplet.parseInt(ptMap.get(vertices[i+2][X]+"_"+vertices[i+2][Y]+"_"+vertices[i+2][Z])); f[3] = PApplet.parseInt(ptMap.get(vertices[i+3][X]+"_"+vertices[i+3][Y]+"_"+vertices[i+3][Z])); addFace(f); } }else{ for (int i = 0; i < stop; i += 4) { int[] f = new int[8]; f[0] = PApplet.parseInt(ptMap.get(vertices[i][X]+"_"+vertices[i][Y]+"_"+vertices[i][Z])); f[4] = PApplet.parseInt(uvMap.get(vertices[i][U]+"_"+vertices[i][V])); f[1] = PApplet.parseInt(ptMap.get(vertices[i+1][X]+"_"+vertices[i+1][Y]+"_"+vertices[i+1][Z])); f[5] = PApplet.parseInt(uvMap.get(vertices[i+1][U]+"_"+vertices[i+1][V])); f[2] = PApplet.parseInt(ptMap.get(vertices[i+2][X]+"_"+vertices[i+2][Y]+"_"+vertices[i+2][Z])); f[6] = PApplet.parseInt(uvMap.get(vertices[i+2][U]+"_"+vertices[i+2][V])); f[3] = PApplet.parseInt(ptMap.get(vertices[i+3][X]+"_"+vertices[i+3][Y]+"_"+vertices[i+3][Z])); f[7] = PApplet.parseInt(uvMap.get(vertices[i+3][U]+"_"+vertices[i+3][V])); addFace(f); } } } break; case QUAD_STRIP: { int stop = vertexCount-3; for (int i = 0; i < stop; i += 2) { if(!exportUV){ int[] f = new int[4]; f[0] = PApplet.parseInt(ptMap.get(vertices[i][X]+"_"+vertices[i][Y]+"_"+vertices[i][Z])); f[1] = PApplet.parseInt(ptMap.get(vertices[i+1][X]+"_"+vertices[i+1][Y]+"_"+vertices[i+1][Z])); f[3] = PApplet.parseInt(ptMap.get(vertices[i+2][X]+"_"+vertices[i+2][Y]+"_"+vertices[i+2][Z])); f[2] = PApplet.parseInt(ptMap.get(vertices[i+3][X]+"_"+vertices[i+3][Y]+"_"+vertices[i+3][Z])); addFace(f); }else{ int[] f = new int[8]; f[0] = PApplet.parseInt(ptMap.get(vertices[i][X]+"_"+vertices[i][Y]+"_"+vertices[i][Z])); f[4] = PApplet.parseInt(uvMap.get(vertices[i][U]+"_"+vertices[i][V])); f[1] = PApplet.parseInt(ptMap.get(vertices[i+1][X]+"_"+vertices[i+1][Y]+"_"+vertices[i+1][Z])); f[5] = PApplet.parseInt(uvMap.get(vertices[i+1][U]+"_"+vertices[i+1][V])); f[3] = PApplet.parseInt(ptMap.get(vertices[i+2][X]+"_"+vertices[i+2][Y]+"_"+vertices[i+2][Z])); f[7] = PApplet.parseInt(uvMap.get(vertices[i+2][U]+"_"+vertices[i+2][V])); f[2] = PApplet.parseInt(ptMap.get(vertices[i+3][X]+"_"+vertices[i+3][Y]+"_"+vertices[i+3][Z])); f[6] = PApplet.parseInt(uvMap.get(vertices[i+3][U]+"_"+vertices[i+3][V])); addFace(f); } } } break; case TRIANGLE_FAN: { int stop = vertexCount - 1; for (int i = 1; i < stop; i++) { if(!exportUV){ int f[] = new int[3]; f[0] = PApplet.parseInt(ptMap.get(vertices[0][X]+"_"+vertices[0][Y]+"_"+vertices[0][Z])); f[1] = PApplet.parseInt(ptMap.get(vertices[i][X]+"_"+vertices[i][Y]+"_"+vertices[i][Z])); f[2] = PApplet.parseInt(ptMap.get(vertices[i+1][X]+"_"+vertices[i+1][Y]+"_"+vertices[i+1][Z])); addFace(f); }else{ int f[] = new int[6]; f[0] = PApplet.parseInt(ptMap.get(vertices[0][X]+"_"+vertices[0][Y]+"_"+vertices[0][Z])); f[3] = PApplet.parseInt(uvMap.get(vertices[0][U]+"_"+vertices[0][V])); f[1] = PApplet.parseInt(ptMap.get(vertices[i][X]+"_"+vertices[i][Y]+"_"+vertices[i][Z])); f[4] = PApplet.parseInt(uvMap.get(vertices[i][U]+"_"+vertices[i][V])); f[2] = PApplet.parseInt(ptMap.get(vertices[i+1][X]+"_"+vertices[i+1][Y]+"_"+vertices[i+1][Z])); f[5] = PApplet.parseInt(uvMap.get(vertices[i+1][U]+"_"+vertices[i+1][V])); addFace(f); } } } break; } } //unused as of now /* public void endShapeStroke(int mode) { switch(shape) { case LINES: { int stop = vertexCount-1; for (int i = 0; i < stop; i += 2) { int[] l = new int[2]; l[0] = PApplet.parseInt(ptMap.get(vertices[i][X]+"_"+vertices[i][Y]+"_"+vertices[i][Z])); l[1] = PApplet.parseInt(ptMap.get(vertices[i+1][X]+"_"+vertices[i+1][Y]+"_"+vertices[i+1][Z])); addLine(l);; } } break; case TRIANGLES: { int stop = vertexCount-2; for (int i = 0; i < stop; i += 3) { int[] l = new int[4]; l[0] = PApplet.parseInt(ptMap.get(vertices[i][X]+"_"+vertices[i][Y]+"_"+vertices[i][Z])); l[1] = PApplet.parseInt(ptMap.get(vertices[i+1][X]+"_"+vertices[i+1][Y]+"_"+vertices[i+1][Z])); l[2] = PApplet.parseInt(ptMap.get(vertices[i+2][X]+"_"+vertices[i+2][Y]+"_"+vertices[i+2][Z])); l[3] = l[0]; addLine(l);; } } break; case POLYGON: { int[] l; boolean closed = mode == CLOSE && (vertices[0][X]!=vertices[vertexCount-1][X] || vertices[0][Y]!=vertices[vertexCount-1][Y] || vertices[0][Z]!=vertices[vertexCount-1][Z]); if(closed) { l = new int[vertexCount+1]; } else { l = new int[vertexCount]; } for(int i=0;i<vertexCount;++i) { l[i] = PApplet.parseInt(ptMap.get(vertices[i][X]+"_"+vertices[i][Y]+"_"+vertices[i][Z])); } if(closed) l[vertexCount] = l[0]; addLine(l);; } break; } } */ private void addFace(int[] f) { if(faceCount >= faces_groups_materials.length) { int newfaces[][] = new int[faces_groups_materials.length*2][]; System.arraycopy(faces_groups_materials,0,newfaces,0,faces_groups_materials.length); faces_groups_materials = newfaces; } faces_groups_materials[faceCount++] = f; } /* private void addLine(int[] l) { if(lineCount >= lines.length) { int newLines[][] = new int[lines.length*2][]; System.arraycopy(lines,0,newLines,0,lines.length); lines = newLines; } lines[lineCount++] = l; } */ /*private void autoSetObject(String name) //doesn't work this way :( { object_name = (String[])PApplet.append(object_name, name); int current_oject = object_name.length-1; int[] f = new int[2]; f[0] = current_oject; addFace(f); }*/ /** * set the Group for the following drawings * * @param name "a name for the Group" */ public void setObject(String name) { if(useObjects == true && manualObjects == true) { object_name = (String[])PApplet.append(object_name, name); int current_oject = object_name.length-1; int[] f = new int[2]; f[0] = current_oject; addFace(f); } } /** * set the Material for the following drawings, this is used like fill(), just with the possibility to specify a name * <p> * if a material with the same name already exist, this material will be used! * <p> * @param name "a name for the Material" * @param r "the red value 0-255" * @param g "the green value 0-255" * @param b "the blue value 0-255" * @param a "the alpha value 0-255" */ public void setMaterial(String name, int r, int g, int b, int a) { if(useMaterials && materialsFromMaterial){ if(materials_name.length == 0) { float[] mat = {(float)r,(float)g,(float)b,(float)a}; materials_name = (String[])PApplet.append(materials_name,name); materials_data = (float[][])PApplet.append(materials_data,mat); current_material = materials_name.length-1; }else{ boolean newMat = true; for(int i = 0; i<materials_name.length; i++) { if(materials_name[i] == name) { current_material = i; newMat = false; break; } } if(newMat){ float[] mat = {(float)r,(float)g,(float)b,(float)a}; materials_name = (String[])PApplet.append(materials_name,name); materials_data = (float[][])PApplet.append(materials_data,mat); current_material = materials_name.length-1; } } int[] f = new int[1]; f[0] = current_material; addFace(f); } } /** * set the Material for the following drawings, this is used like fill(), just with the possibility to specify a name * <p> * if a material with the same name already exist, this material will be used! * <p> * the alpha value will be set to 255 * * @param name "a name for the Material" * @param r "the red value 0-255" * @param g "the green value 0-255" * @param b "the blue value 0-255" */ public void setMaterial(String name, int r, int g, int b){ setMaterial(name,r,g,b,255); } /** * set the Material for the following drawings, this is used like fill(), just with the possibility to specify a name * <p> * if a material with the same name already exist, this material will be used! * <p> * the color will be black - (0,0,0) * the alpha value will be set to 255 * * * @param name "a name for the Material" */ public void setMaterial(String name) { setMaterial(name,0,0,0,255); } private void setMaterialFromFill(float r, float g, float b, float a) { if(useMaterials && materialsFromFill){ boolean newMat = true; int temp_current = current_material; if(materials_data.length == 0) { float[] mat = {r,g,b,a}; materials_name = (String[])PApplet.append(materials_name,"Mat0"); materials_data = (float[][])PApplet.append(materials_data,mat); current_material = 0; }else{ for(int i = 0; i<materials_data.length; i++) { if(materials_data[i][0] == r && materials_data[i][1] == g && materials_data[i][2] == b && materials_data[i][3] == a) { current_material = i; newMat = false; break; } } if(newMat){ float[] mat = {r,g,b,a}; materials_data = (float[][])PApplet.append(materials_data,mat); current_material = materials_data.length-1; materials_name = (String[])PApplet.append(materials_name,"Mat"+current_material); } } if(newMat || temp_current!=current_material){ int[] f = new int[1]; f[0] = current_material; addFace(f); } } } } ////////////////////////
45311410b1c01d9cf6475beb08dc549cd4be312c
[ "Java" ]
1
Java
yopla/quickMesh
8324b6266a9d7fe7f5f2f126ffef7c042f1c76ff
e11a87d7341b4b1d8f6b1f52e759a41498acd43d
refs/heads/master
<repo_name>thayanenns/projeto-logica-finalizado<file_sep>/BinaryRelation.py #coding: utf-8 class BinaryRelation(object): """Template class for classes representing a Binary Relation.""" def contains_ordered_pair(self, x, y): """ This method returns a boolean value indicating if a given ordered pair belongs to the binary relation. Arguments: x - The first element of the ordered pair. y - The second element of the ordered pair. Return True if the ordered pair belongs to the binary relation, otherwise, return False. """ pass def relation(self, S): """ This method returns a set of pairs in SxS (a.k.a. S²) that belong to the binary relation. Arguments: S - The input set. Return a set of pairs in SxS (a.k.a. S²) that belong to the binary relation. """ pass <file_sep>/README.md # projeto-logica-finalizado Relações binárias em Python <file_sep>/BinaryRelationUtils.py #coding: utf-8 class BinaryRelationUtils(object): """Class providing utilities to verify properties of a binary relation.""" @staticmethod def verify_reflexivity(binary_relation, input_set): """ This method verifies if a given binary relation is reflexive or not. Arguments: binary_relation - A subclass of the BinaryRelation class. input_set - A set closed under the binary relation. Return True if the binary relation in the given input set is reflexive or False if it is not. """ # TODO: Replace line below with actual code. conjunto = binary_relation.relation(input_set) tamanhoConjunto = len(input_set) contReflexividade = 0 for x, y in conjunto: if x == y: contReflexividade += 1 if contReflexividade == tamanhoConjunto: return True else: return False @staticmethod def verify_symmetry(binary_relation, input_set): """ This method verifies if a given binary relation is symmetric or not. Arguments: binary_relation - A subclass of the BinaryRelation class. input_set - A set closed under the binary relation. Return True if the binary relation in the given input set is symmetric or False if it is not. """ # TODO: Replace line below with actual code. conjunto = binary_relation.relation(input_set) for x in input_set: for y in input_set: if (x, y) in conjunto and (y, x) not in conjunto: return False return True @staticmethod def verify_transitivity(binary_relation, input_set): """ This method verifies if a given binary relation is transitive or not. Arguments: binary_relation - A subclass of the BinaryRelation class. input_set - A set closed under the binary relation. Return True if the binary relation in the given input set is transitive or False if it is not. """ # TODO: Replace line below with actual code. conjunto = sorted(binary_relation.relation(input_set)) contador = 0 contador2 = 0 for x in range(len(conjunto)-1): if (conjunto[x][1] == conjunto[x+1][0]): contador2 +=1 if (conjunto[x][0],conjunto[x+1][1])in conjunto: contador+=1 if contador == contador2: return True else: return False @staticmethod def verify_antisymmetry(binary_relation, input_set): """ This method verifies if a given binary relation is antisymmetric or not. Arguments: binary_relation - A subclass of the BinaryRelation class. input_set - A set closed under the binary relation. Return True if the binary relation in the given input set is antisymmetric or False if it is not. """ # TODO: Replace line below with actual code. conjunto = binary_relation.relation(input_set) for x, y in conjunto: if(y,x)in conjunto and x != y: return False return True @staticmethod def verify_equivalency(binary_relation, input_set): """ This method verifies if a given binary relation is an equivalence relation. Arguments: binary_relation - A subclass of the BinaryRelation class. input_set - A set closed under the binary relation. Return True if the binary relation in the given input set is an equivalence relation or False if it is not. """ # TODO: Replace line below with actual code. relacao = BinaryRelationUtils if relacao.verify_reflexivity(binary_relation, input_set): if relacao.verify_symmetry(binary_relation, input_set): if relacao.verify_transitivity(binary_relation, input_set): return True else: return False @staticmethod def get_partitioning(binary_relation, input_set): """ This method first verifies if binary relation is an equivalence relation and, if it is, generates a partitioning of the input set using the binary relation. If the binary relation is not an equivalence relation, it returns None. Note: The partitioning of the set should be a list of subsets. Arguments: binary_relation - A subclass of the BinaryRelation class. input_set - A set closed under the binary relation. Return None if the binary relation is not an equivalence relation or a partitioning of the input set (e.g.: [{1, 3, 5, ...}, {2, 4, 6, ...}]) if it is an equivalence relation. """ # TODO: Replace line below with actual code. conjunto = binary_relation.relation(input_set) particionamento = [] relacao = BinaryRelationUtils if relacao.verify_equivalency(binary_relation, input_set): for x in input_set: particao = set() for y in input_set: if (x, y) in conjunto: particao.add(y) if particao not in particionamento: particionamento.append(particao) return particionamento else: return []
0712c3fb27ad32022e07b84ed3b2b466ea5fd181
[ "Markdown", "Python" ]
3
Python
thayanenns/projeto-logica-finalizado
0a291fa8bbce020f8b6838e7088e16747de79eb5
5cda1220ef656db9a9ecaaf6a4829b0d17c9d644
refs/heads/master
<repo_name>kleberformiga/contabilidados<file_sep>/R/BaixaDados.R #' Transforma dados de matrix do economatica em painel #' #' Em pesquisas na area de financas com dados em painel o pesquisador, por vezes, #' faz estimacoes com dados dispostos em painel. Contudo, as fontes de coleta nem #' sempre disponibiliza dados no formato painel. Esse formato consiste em dispor #' os dados em cross-section (i) e tempo (t). Esse codigo tranforma em painel os #' dados coletados na base Economatica(R), desde que coletadas no template MATRIX. #' Nesse template os dados sao dispostos em colunas (nao painel) em que cada #' coluna possui o codigo da empresa para uma mesma variavel. A vantagem desse #' codigo eh permitir que os dados sejam coletados em um unico arquivo do tipo #' xlsx em que cada aba contera uma variavel de interesse da pesquisa. #' #' #' @param Nome Nome da variavel. O nome informado sera processado como sendo #' o nome da variavel no banco de dados e o nome do banco de dados (com letras maiusculas) #' @param PathFile Caminho do arquivo xlsx. #' @param Periodo Nome a ser dado a frequencia. Essa informacao fica a criterio #' do pesquisador para controle de seu banco de dados. Caso os dados coletados #' sejam trimestrais, pode-se informar #' "trim", "trimestre", "quarter", etc. #' @param Planilha Informar o numero da aba na qual estao os dados a serem #' transformados em painel. #' @param ClassPeriodo Tipo de variavel para periodo do matrix. Se os dados sao #' trimestreis 1T2018, por exemplo, informar "text". O padrao eh data, pois #' os matrix, normalmente reportam uma data no periodo. #' @param ClassValue Tipo de variavel para os valores coletados. Se for setor, #' por exemplo, colocar "character". Porém a maioria dos valores coletados sao #' decorrentes de dados financeiros. Por isso o padrao eh "numeric". #' #' @return Para melhor desempenho no uso do codigo, todos os matrix deverao ser #' coletados com as mesmas empresas e o mesmo periodo, permitindo a criacao de #' um painel balanceado, alem de dar ao pesquisador maior controle sobre os dados #' coletados e facilitar a juncao de bancos. #' #' @seealso \code{\link{data.table}} para manipulacao de dados #' @seealso \code{\link{readxl}} para importacao de dados xlsx #' @source Os dados usados no exemplo estao disponiveis em \url{https://github.com/kleberformiga/contabilidados/blob/master/ExemploEconomatica.xlsx?raw=true} #' #' @keywords Data.table, teste #' @examples #' Considerando a transformacao da primeira aba do arquivo xlsx na qual esta a #' variavel ATIVO TOTAL, coletada no matrix na frequencia trimestral, cujo nome #' escolhido seja "AtTot": disponivel em #SOURCE: #' #' BaixaDados("AtTot", "caminho/exemplo1.xlsx", "trim", 1) #' #' Considerando um arquivo com duas ou mais abas (nesse exemplo, duas) em que #' o pesquisador deseje transformar em painel de forma automatica: #' #' dados <- c("precos", "vrmerc") # Vetor com dados de precos e valor de mercado #' #' for (i in seq_along(dados)) { #' BaixaDados(dados[i], "caminho/nomedoarquivo.xlsx", "trim", i) #' } #' #' Após rodar esse exemplo, as duas variaveis estarao dispostas em painel prontas #' para serem unidas em um unico banco de dados. O pacote \code{\link{dplyr}} eh #' recomendado para esse fim. #' #' @export BaixaDados <- function(Nome, PathFile, Periodo, Planilha, ClassPeriodo = "date", ClassValue = "numeric"){ a <- ncol(read_xlsx(PathFile, sheet = Planilha, skip = 1, na = "-")) assign(toupper(paste0("BD", Nome)), read_xlsx(PathFile, sheet = Planilha, skip = 1, na = "-", col_types = c(ClassPeriodo, rep(ClassValue, a-1))),envir = .GlobalEnv) setnames(get(toupper(paste0("BD", Nome))), 1L, Periodo) assign(toupper(paste0("BD", Nome)), melt(data.table(get(toupper(paste0("BD", Nome)))), id.vars = Periodo, variable.name="cod", value.name = Nome, variable.factor = F, value.factor = F), envir = .GlobalEnv) } <file_sep>/eccd_functions.R cntdd <- file.path("https://raw.githubusercontent.com", "kleberformiga/contabilidados/master", "contabilidados.R") source(cntdd) options(scipen = 999) cntdd.carregaPacotes("tidyverse") bd.eccd.001 <- readRDS("bd.eccd.001.rds") eccd.n1.evolucao <- function(codigo = "PETR4", conta = ativo, descricao = "Ativo"){ conta <- enquo(conta) dados <- bd.eccd.001 %>% filter(cod %in% codigo) print(dados) ggplot(dados, aes(x = ano, y = !!conta, color = cod)) + scale_y_continuous(labels = scales::unit_format( unit = "k", scale = 1e-3, accuracy = 1, big.mark = ",")) + geom_line(size = 1.5, color = "lightgrey") + geom_point(size = 3, color = "steelblue") + labs(y = NULL, x = NULL, title = paste0("Evolução da conta ", descricao, " da empresa ", codigo), subtitle = "Em milhares de reais", caption = paste0("Elaboração: contabiliDados |", "\n", "Fonte: Economatica\U00AE |")) + cntdd.theme } eccd.n1.evolucao() eccd.n1.comparaevolucao <- function(codigos = c("MGLU3", "LREN3"), conta = ativo, descricao = "Ativo"){ if(length(codigos) < 2){message("Coloque pelo menos dois códigos")} conta <- enquo(conta) ggplot(data = bd.eccd.001 %>% filter(cod %in% codigos), mapping = aes(x = ano, y = !!conta/1000, color = cod), na.rm = TRUE) + geom_line(alpha = .7, size = 2) + labs(title = paste0("Evolução da conta ", descricao, ", por ano"), subtitle = "em milhares R$", caption = paste0("elaborador por contabiliDados", "\n", "Fonte: http://www.economatica.com.br/"), x = NULL, y = NULL, color = "Código") + cntdd.theme } eccd.n1.comparaevolucao() eccd.n1.relacaoContas <- function(codigo = "VALE3", x = divida, y = ativo, descX = "Dívida", descY = "Ativo", descCod = "VALE"){ print(bd.eccd.001 %>% filter(cod == codigo & ano < 2017)) ggplot(bd.eccd.001 %>% filter(cod == codigo & ano < 2017), aes(x = !! enquo(x)/1000, y = !!enquo(y)/1000, color = cod), na.rm = TRUE) + geom_point(alpha = .7, size = 4, color = "blue") + geom_smooth(method='lm', formula= y~x, show.legend = F) + geom_text(aes(label=ano),hjust=-0.3, vjust=0.2, color = "blue", show.legend = F) + labs(title = paste0("Relação entre ", descX, "(X) e ", descY, "(Y) da empresa ", descCod), subtitle = "em milhares R$", caption = paste0("elaborado por contabiliDados", "\n", "Fonte: economatica"), x = NULL, y = NULL) + cntdd.theme } eccd.n1.relacaoContas() <file_sep>/R/CarregaPacotes.R #' Carrega pacotes requeridos #' #' Verifica se o pacote requerido estah instalado. Caso nao esteja, instala e #' carrega o pacote requerido. #' #' @param pcts Nome do pacote requerido. #' #' @return Os dados fornecidos devem ser do tipo character, portanto, deve ser #' informado entre aspas. #' #' @examples #' O uso natural da funcao eh: #' CarregaPacotes("dplyr") #' #' Nesse caso, verificaria se o pacote dplyr estaria instalado. Caso positivo, #' carregaria o pacote. Caso negativo, instalaria e, posteriormente a instalacao, #' o carregaria. #' #' Para um uso mais geral, recomenda-se o uso de um vetor de pacotes requeridos #' para desenvolver o trabalho. Nesse caso, poderia utilizar o seguinte codigo: #' #' pacotes <- c("tidyverse", "data.table", "readxl") # Vetor com tres pacotes #' #' for(i in pacotes){CarregaPacotes(i)} # Verifica todos os pacotes informados #' #' Ao final tem-se todos os pacotes informados instalados e/ou carregados. #' #' @export CarregaPacotes <- function(pcts){ if(!require(pcts, character.only = T)){install.packages(pcts); require(pcts, character.only = T, quietly = T)} } <file_sep>/verplot.R verPlot <- function(setor){ ggplot(dados[econBov %in% as.character(setores[c(setor)]), .(econBov, trim2, divAtivo, plAtivo)], aes(trim2 , value, color = variable)) + geom_line(aes(y = divAtivo, col = "divAtivo")) + geom_line(aes(y = plAtivo, col = "plAtivo")) + ggtitle(paste0("Fonte de financiamento do setor \n", setores[c(setor)])) + xlab("Valor em percentual") + ylab("Trimestres") + labs(color="Variáveis") + theme(panel.grid.major = element_blank(), panel.grid.minor = element_blank(), panel.background = element_blank(), axis.line = element_line(colour = "black")) + theme(legend.position = "bottom") } <file_sep>/README.md # Contabilidados Pacote voltado a disseminacao de funcoes e codigos criados pela equipe CONTABILIDADOS com o intuito de facilitar o processo de coleta, tratamento e estimacao de dados para pesquisas academicas em contabilidade e financas. <file_sep>/contabilidados.R cntdd.lista <- function(){ cat("cntdd.carregaPacotes: Carregar um pacote. Caso não exista, instala e carrega", "\n") cat("\n") cat("cntdd.BaixaDados: Baixar dados da aba de uma planilha coletados por meio de matrix do economatica", "\n") cat("\n") cat("cntdd.BaixaDadosReuters: Baixar dados da aba de uma planilha coletados por meio da base Reuters", "\n") cat("\n") cat("cntdd.mediaGeometrica: Gerar a média geométrica do vetor informado", "\n") cat("\n") cat("cntdd.baixaPrecos: Baixar precos de papeis negociados na bolsa e gerar grafico", "\n") cat("\n") cat("cntdd.variosMatrix: Criar vetores com base em abas do excel coletadas no economatica por meio de matrix", "\n") cat("\n") cat("cntdd.limpaMatrix: Limpar objetos temporarios criados durante a uniao de matrix por meio da funcao 'cntdd.uneMatrix'", "\n") cat("\n") cat("cntdd.uneMatrix: Transformar em painel variaveis coletadas em matrix (Economatica)", "\n") cat("\n") } cntdd.carregaPacotes <- function (pcts = c("dplyr", "data.table", "readxl", "tseries", "ggplot2", "ggrepel" )){ ################ Instruções ##################################################### # Objetivo: Carregar um pacote. Caso não exista, instala e carrega # Informa um vetor com os pacotes a serem instalados # Se nada informado, por padrão, instala os pacotes necessarios aos demais # codigos do contabilidados # Esses pacotes são necessários para manipulação de dados ################################################################################# for (i in pcts) { if (!require(i, character.only = T)) { install.packages(i) require(i, character.only = T, quietly = T) } } } cntdd.carregaPacotes() cntdd.BaixaDados <- function (Nome, PathFile, Periodo, Planilha, ClassPeriodo = "date", ClassValue = "numeric") { ################ Instruções ##################################################### # Objetivo: Baixar dados da aba de uma planilha coletados por meio de matrix # do economatica # # Nome: Informe o nome da variável coletada no matrix do economatica # PathFile: Informe o caminho do arquivo xlsx onde está o matrix do economatica # Periodo: Informe "trim" para trimestre, "data" para data, "ano" para ano, etc. # Planilha: Informe o número da planilha ou nome da aba que contém o matrix # ClassPeriodo: Por padrão é formato data, mas se no matrix o período contiver # letras, informar "text" para indicar ser um texto (string) # ClassValue: Por padrão é formato numérico, mas se os dados coletados forem # texto (nome do sócio, por exemplo), infomar "text". ################################################################################# a <- ncol(read_xlsx(PathFile, sheet = Planilha, skip = 1, na = "-")) assign(toupper(paste0("BD", Nome)), read_xlsx(PathFile, sheet = Planilha, skip = 1, na = "-", col_types = c(ClassPeriodo, rep(ClassValue, a - 1))), envir = .GlobalEnv) setnames(get(toupper(paste0("BD", Nome))), 1L, Periodo) assign(toupper(paste0("BD", Nome)), data.frame(melt(data.table(get(toupper(paste0("BD", Nome)))), id.vars = Periodo, variable.name = "cod", value.name = Nome, variable.factor = F, value.factor = F)), envir = .GlobalEnv) } cntdd.BaixaDadosReuters <- function (Nome, PathFile, Planilha, RANGE = "P:R", SKIP = 0) { assign(toupper(Nome), read_xlsx(PathFile, sheet = Planilha, skip = SKIP, na = c("-", "NULL", "#N/A"), range = cell_cols(RANGE)), envir = .GlobalEnv) setnames(get(toupper(Nome)), 1L:3L, c("cod", "data", Nome)) setDT(get(toupper(Nome))) } cntdd.mediaGeometrica <- function(x){ ################ Instruções ##################################################### # Objetivo: Gerar a média geométrica do vetor informado # Informa um vetor com os números que comporão a média # Valores NA serão desconsiderados ################################################################################# round(prod(x, na.rm = T)^(1/length(x[!is.na(x)])), 3) } cntdd.baixaPrecos <- function(nome = "precos", x = "^BVSP", inicio = Sys.Date()-30, fim = Sys.Date()-1, freq = "d"){ ################ Instruções ##################################################### # Objetivo: Baixar precos de papeis negociados na bolsa e gerar grafico. # Informa o nome do objeto que pretende criar e escolhe os papeis desejados, # período e frequencia dos dados, conforme exemplo abaixo: # # cntdd.baixaPrecos(nome = "precos", # x = c("RADL3.SA", "PETR3.SA", "^BVSP"), # inicio = "2010-01-01", # fim = "2010-01-31", # freq = "d") # # nome: Nome do objeto a ser criado no environment do R. Se nada informado, # o padrao eh "precos". # x = Vetor com os papeis de interesse na serie de precos. Se nada informado, # o padrao eh o indice bovespa "^BVSP". # inicio: Data inicial no formato "yyyy-mm-dd". Se nada informado, o padrao # eh 30 dias anteriores a data do sistema. # fim: Data final no formato "yyyy-mm-dd". Se nada informado, o padrao eh o dia # anterior a data do sistema. # freq: informar "d" para frequencia diaria dos precos ou "m" para mensal. Se # nada informado, o padrao eh diario ("d") # # Obs.: Ao final eh plotado um grafico com os valores dos retornos na base 100 # com benchmark na data de inicio da serie. A analise consiste em observar # o comportamento do retorno de cada papel do inicio da serie (quando # todos estao com mesmo valor - 100) ate a data final. Serve para comparar # o desempenho de cada papel no periodo informado. ################################################################################# LISTA <- toupper(x) dados <- list() for (i in seq_along(LISTA)) { dados[[LISTA[i]]] <- get.hist.quote(LISTA[i], start = as.character(inicio), end = as.character(fim), compression = freq) } for (i in 1:length(LISTA)) { dados[[i]] <- cbind( as.data.table(time(dados[[i]])), as.data.table(dados[[i]])) } precos <- dados %>% bind_rows(.id = "codigo") %>% rename(data = V1) %>% group_by(codigo) %>% mutate(closeb100 = Close/ first(Close) * 100) %>% na.omit %>% setDT assign(nome, precos, envir = .GlobalEnv) precos %>% mutate(label = if_else(data == max(data), as.character(codigo), NA_character_)) %>% ggplot(aes(x = data, y = closeb100, group = codigo, colour = codigo)) + geom_line() + theme(legend.position = "none") + geom_label_repel(aes(label = label), nudge_x = 1, na.rm = T) } cntdd.variosMatrix <- function(Arquivo, SeqVarPlan, index = c("cod", "trim"), clsPer = "text", clsVlr = "numeric"){ ################ Instruções ##################################################### # Objetivo: Criar vetores com base em abas do excel coletadas no economatica por # meio de matrix. # Apos salvar cada variavel de interesse em uma aba do excel no formato # matrix do economatica, aplica essa funcao, conforme exemplo: # # cntdd.variosMatrix(Arquivo = "Caminho/Arquivo.xlsx", # SeqVarPlan = c("atvTot", "patLiq"), # index = c("cod", "ano"), # clsPer = "numeric", clsVlr = "numeric") # # Arquivo: Informe o caminho do arquivo com sua extensão xlsx # SeqVarPlan: Crie um vetor com o nome de cada variavel coletada na sequencia # das abas do arquivo em excel # index: Informar sempre cod e, no período, colocar conforme a frequencia # coletada (ano, trimestre, mes, data). Serve para nomear as colunas, # portanto, outros valores tambem sao aceitos # clsPer: Informa a classe do período. Quando Data e mês, informa "date"; # Quando ano, informa "numeric" e quando trimestre, informa "text". # clsVlr: O padrao eh numerico, porem se for coletado algum dado com texto, # como o nome do acionista, coloca "text". # # Obs.: Ao final eh demonstrada uma auditoria identificando o nome dado pelo # usuario para cada variavel e o cabecalho da planilha com o nome da # variavel coletada no economatica. Serve para saber se a sequencia dada # pelo usuario realmente reflete a sequencia das abas da planilha # # A função 'cntdd.uneMatrix' une todos os vetores criados por essa funcao. # Entao se usar essa funcao, o usuario tera cada variavel da planilha em um # vetor separado. Caso queira todas as variaveis em formato painel, eh # preferivel usar a funcao 'cntdd.uneMatrix. ################################################################################# # Unir diversas variaveis coletadas em matrix (economatica) para o # formato painel bds <<- list() listaVar <<- toupper(paste0("BD", SeqVarPlan)) AuditaVetores <- data.frame(Variavel = NA, Descricao = NA) for (i in seq_along(SeqVarPlan)) { bds[[SeqVarPlan[i]]] <<- cntdd.BaixaDados(SeqVarPlan[i], Arquivo, index[2], i, ClassPeriodo = clsPer, ClassValue = clsVlr) AuditaVetores[i,1] = toupper(paste0("BD", SeqVarPlan))[i]; AuditaVetores[i, 2] = names(setDT(read_xlsx(Arquivo, sheet = i, skip = 0, na = "-", range = "B1:B3"))) } bds <<- lapply(bds, data.frame) print(AuditaVetores) } cntdd.limpaMatrix <- function(){ ################ Instruções ##################################################### # Objetivo: Limpar objetos temporarios criados durante a uniao de matrix por # meio da funcao 'cntdd.uneMatrix'. Eh executado automaticamente. ################################################################################# rm(list = ls(envir = .GlobalEnv)[ls(envir = .GlobalEnv) %in% c(listaVar, "listaVar", "bds")], envir = .GlobalEnv) } cntdd.uneMatrix <- function(Arquivo, SeqVarPlan, index, clsPer, clsVlr){ ################ Instruções ##################################################### # Objetivo: Transformar em painel variaveis coletadas em matrix (Economatica) # Apos salvar cada variavel de interesse em uma aba do excel no formato # matrix do economatica, aplica essa funcao, conforme exemplo: # # cntdd.uneMatrix(Arquivo = "Caminho/Arquivo.xlsx", # SeqVarPlan = c("atvTot", "patLiq"), # index = c("cod", "ano"), # clsPer = "numeric", clsVlr = "numeric") # # Arquivo: Informe o caminho do arquivo com sua extensão xlsx # SeqVarPlan: Crie um vetor com o nome de cada variavel coletada na sequencia # das abas do arquivo em excel # index: Informar sempre cod e, no período, colocar conforme a frequencia # coletada (ano, trimestre, mes, data). Serve para nomear as colunas, # portanto, outros valores tambem sao aceitos # clsPer: Informa a classe do período. Quando Data e mês, informa "date"; # Quando ano, informa "numeric" e quando trimestre, informa "text". # clsVlr: O padrao eh numerico, porem se for coletado algum dado com texto, # como o nome do acionista, coloca "text". # # Obs.: Ao final eh demonstrada uma auditoria identificando o nome dado pelo # usuario para cada variavel e o cabecalho da planilha com o nome da # variavel coletada no economatica. Serve para saber se a sequencia dada # pelo usuario realmente reflete a sequencia das abas da planilha ################################################################################# cntdd.variosMatrix(Arquivo = Arquivo, SeqVarPlan = SeqVarPlan, index = index, clsPer = clsPer, clsVlr = clsVlr) bds <<- lapply(bds, data.frame) bdPainel <<- Reduce(inner_join, bds) cntdd.limpaMatrix() cat("Os dados foram armazenados, em painel, no objeto 'bdPainel' ", "\n") } cntdd.theme <- theme(legend.position = "bottom", legend.title = element_blank(), axis.title.x = element_blank(), axis.title.y = element_blank(), axis.text.y = element_text(color = "snow4"), axis.text.x = element_text(color = "snow4"), plot.title = element_text(color = 'lightblue3', size = 15), plot.subtitle = element_text(color = "snow4", size = 10), plot.caption = element_text(color = "snow3", size = 8), panel.background = element_blank(), panel.grid = element_line(color = "snow2")) mes.nome <- c("Janeiro", "Fevereiro", "Março", "Abril", "Maio", "Junho", "Julho", "Agosto", "Setembro", "Outubro", "Novembro", "Dezembro") meses <- data.frame(mes.num = 1:12, mes.nome = mes.nome, mes.abb = substr(mes.nome, 1, 3), month.name = month.name, month.abb = month.abb, mes.chr = c("01", "02", "03", "04", "05", "06", "07", "08", "09", "10", "11", "12"), bim = rep(1:6, each = 2), trim = rep(1:4, each = 3), quad = rep(1:3, each = 4), sem = rep(1:2, each = 6)) rm(mes.nome) <file_sep>/R/contabilidados.R #' Pacote CONTABILIDADOS #' #' Pacote voltado a disseminacao de funcoes criadas pela equipe CONTABILIDADOS com #' o intuito de facilitar coleta, tratamento e estimacao de dados para pesquisas #' academicas em contabilidade, economia e administracao. #' #' @docType package #' #' @import data.table #' @import dplyr #' @import readxl #' #' @author <NAME> \email{<EMAIL>} #' #' @name contabilidados NULL <file_sep>/verh5.R verH5 <- function(search){ journal <- sub("&", "%26", search) # Ajusta o & comercial para o codigo real journal <- sub("@", "%40", journal) # Ajusta o @ arroba para o codigo real journal <- sub(" *\\(.*", "", journal) # não inclui a partir de qualquer parentese journal <- sub("\\.", "", journal) # retirar pontos journal <- sub(":", "", journal) # retirar dois pontos journal <- dQuote(str_replace_all(journal, " ", "+")) # coloca sempre entre aspas #Specifying the url for desired website to be scrapped url <- paste0("https://scholar.google.com/citations?hl=pt-BR&view_op=search_venues&vq=", journal, "&btnG=") #Reading the html content from Scholar webpage <- read_html(url) #scrape title of the product title_html <- html_nodes(webpage, "table#gsc_mvt_table") title <- html_table(title_html) df <- Reduce(merge, title) df <- df[, 2:4] return(df) }
2e8ded05f5353d38f2c97a32106c6279d548a99c
[ "Markdown", "R" ]
8
R
kleberformiga/contabilidados
5999d5b9bcd1cd68bda5657c82027dceb55b2d2f
171ad08029a0cf7304597eee5d930b44e15e43d6
refs/heads/master
<repo_name>MathijsElbo/APDProeftoets1<file_sep>/ts/app.ts function show_choice(): void { let p_tag1: HTMLParagraphElement; let p_tag2: HTMLParagraphElement; let img_tag: HTMLPictureElement; p_tag1 = document.querySelector("#p_01"); p_tag2 = document.querySelector("#p_02"); img_tag = document.querySelector("#img_01") p_tag1.innerHTML = "Keuze vak 1, keuze vak 2 en keuze vak 3"; p_tag2.innerHTML = "Applicatie- en Media ontwikkelaar"; p_tag2.setAttribute("data-target", "#exampleModal") img_tag.setAttribute("style", "display: block;"); } function img_hover(): void { let p_tag1: HTMLParagraphElement; let p_tag2: HTMLParagraphElement; let img_tag: HTMLPictureElement; p_tag1 = document.querySelector("#p_01"); p_tag2 = document.querySelector("#p_02"); img_tag = document.querySelector("#img_01"); p_tag1.innerHTML = "Door te klikken op de onderstaande knop worden de keuzendelen zichtbaar die ik ga kiezen voor de opleiding applicatieontwikkeling"; p_tag2.innerHTML = "Ik maak ook bekend of ik als applicatie- en mediaontwikkelaar of als gamedeveloper ga afstuderen"; p_tag2.setAttribute("data-target", "#-"); img_tag.setAttribute("style", "display: none;"); } function savemodal(): void { let text_tag: HTMLTextAreaElement; let p_tag2: HTMLParagraphElement; text_tag = document.querySelector("#text_01"); p_tag2 = document.querySelector("#p_02"); p_tag2.innerHTML = text_tag.value; }<file_sep>/js/app.js function show_choice() { let p_tag1; let p_tag2; let img_tag; p_tag1 = document.querySelector("#p_01"); p_tag2 = document.querySelector("#p_02"); img_tag = document.querySelector("#img_01"); p_tag1.innerHTML = "Keuze vak 1, keuze vak 2 en keuze vak 3"; p_tag2.innerHTML = "Applicatie- en Media ontwikkelaar"; p_tag2.setAttribute("data-target", "#exampleModal"); img_tag.setAttribute("style", "display: block;"); } function img_hover() { let p_tag1; let p_tag2; let img_tag; p_tag1 = document.querySelector("#p_01"); p_tag2 = document.querySelector("#p_02"); img_tag = document.querySelector("#img_01"); p_tag1.innerHTML = "Door te klikken op de onderstaande knop worden de keuzendelen zichtbaar die ik ga kiezen voor de opleiding applicatieontwikkeling"; p_tag2.innerHTML = "Ik maak ook bekend of ik als applicatie- en mediaontwikkelaar of als gamedeveloper ga afstuderen"; p_tag2.setAttribute("data-target", "#-"); img_tag.setAttribute("style", "display: none;"); } function savemodal() { let text_tag; let p_tag2; text_tag = document.querySelector("#text_01"); p_tag2 = document.querySelector("#p_02"); p_tag2.innerHTML = text_tag.value; }
52ba5ea07d1c738a229bf785a691843802a773a7
[ "JavaScript", "TypeScript" ]
2
TypeScript
MathijsElbo/APDProeftoets1
1d6d0152dfafc2a8e363830c115fb4d003494f4c
bf1f5aa9bee6c4fa038aa8af5578bbe1ce76b3c4
refs/heads/master
<file_sep>'use strict'; const gulp = require('gulp'); const imagemin = require('gulp-imagemin'); const pngquant = require('imagemin-pngquant'); const jpegtran = require('imagemin-jpegtran'); const notify = require('gulp-notify'); const plumber = require('gulp-plumber'); gulp.task('imagemin', function(){ // pngファイル gulp.src('image/src/**/*.png') .pipe(plumber({ errorHandler: notify.onError('Error: <%= error.message %>') })) .pipe(imagemin({ use: [pngquant([ {quality: '80'}, {speed: 1} ])] })) .pipe(gulp.dest('image/dest') ); // jpg gulp.src(['image/src/**/*.jpg', 'iamge/src/**/*.jpeg']) .pipe(imagemin({ use: [jpegtran([{ progressive: true }])] })) .pipe(gulp.dest('image/dest') ); }); <file_sep>'use strict'; const gulp = require('gulp'); const notify = require('gulp-notify'); const plumber = require('gulp-plumber'); const uglify = require('gulp-uglify'); const rename = require('gulp-rename'); // minify gulp.task('jsmin', function(){ gulp.src('js/src/**/*.js') .pipe(plumber({ errorHandler: notify.onError('Error: <%= error.message %>') })) .pipe(rename({ suffix: '.min' })) .pipe(uglify()) .pipe(gulp.dest('js/dest')) .pipe(notify({ title: 'jsをminifyしました', message: new Date(), sound: 'Glass' }) ); }); <file_sep>'use strict'; const gulp = require('gulp'); const sass = require('gulp-sass'); const notify = require('gulp-notify'); const plumber = require('gulp-plumber'); const autoprefixer = require('gulp-autoprefixer'); let autoprefixerOptions = ['last 3 version', 'ie >= 9', 'Android 4.0']; gulp.task('style', function(){ gulp.src('scss/src/**/*.scss') .pipe(plumber({ errorHandler: notify.onError('Error: <%= error.message %>') })) .pipe(sass({ outputStyle: 'nested', sourceMap: true, sourceComment: false })) .pipe(autoprefixer(autoprefixerOptions)) .pipe(gulp.dest('scss/dest')) .pipe(notify({ title: 'scssをコンパイルしました!', message: new Date(), sound: 'Glass' }) ); }); <file_sep># frontools フロントエンドでよく使うツールたち * 画像(jpg、png)の圧縮 → `gulp imagemin` * scss変換 → `gulp style` * jsのminify → `gulp jsmin` * css sprite作成 → `gulp sprite`
53cdc743b4bc74af69c20a8c167ab76d428aa80c
[ "JavaScript", "Markdown" ]
4
JavaScript
diwao/frontools
1e4746793f7dae60a16b1d6a4de0763a96c5f6f4
9024a7701214085ffec65e19bed7831d4a3ebc20
refs/heads/master
<repo_name>porsamini/Survey<file_sep>/app/helpers/questions_helper.rb module QuestionsHelper def link_to_add_field(name, f, association) new_object = f.object.class.reflect_on_association(association).klass.new fields = f.fields_for(association, new_object, :child_index => "new_#{association}") do |builder| render("answers/form", :form => builder) end link_to_function(name, h("add_fields(this, \"#{association}\", \"#{escape_javascript(fields)}\")")) end end <file_sep>/app/models/question.rb class Question < ActiveRecord::Base has_many :answers accepts_nested_attributes_for :answers, :reject_if => lambda {|a|a[:content].blank?}, :allow_destroy => true end
23f4197f2051d0e8afccd622b7a201d932295f7a
[ "Ruby" ]
2
Ruby
porsamini/Survey
8d01cb4bc5ef68826427961f15ddf0615740faba
6995870f0c3c0431f03711d2e9d17142a535795f
refs/heads/master
<file_sep>//素数を求める  //0811 11:52-12:00 //0812 10:00-12:00 //0812 14:00-15:15 //目標 120分 //仕様変更追加 package java_practice; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.List; public class Practice48_primeNumber { public static void main(String[] args) throws IOException { BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); //数字1 System.out.println("1.数字を入力してください。(2-9999)"); String inputNum1 = reader.readLine(); int inputNumber1 = Integer.parseInt(inputNum1); //数字2 System.out.println("2.数字を入力してください。(2-9999)"); String inputNum2 = reader.readLine(); int inputNumber2 = Integer.parseInt(inputNum2); minToMax(inputNumber1,inputNumber2); //primeNumber(inputNumber1,inputNumber2); } //入力された数をループ public static List<Integer> primeNumber(int min,int max) { //素数を入れていくためのリスト List<Integer> result = new ArrayList<>(); String s = ""; //入力された数までループ for (int i = min; i <= max; i++) { if (judge(i) == true) { //素数の場合はリストに追加する result.add(i); } } //リストの型変換 s = String.valueOf(result); //[]を外す s = s.replace("[" , ""); s = s.replace("]" , ""); System.out.print(min + "以上で" + max + "以下の素数は、" + s + "です。"); return result; } /** * 素数の判定 * @param num 入力された数 * @return 素数 */ public static boolean judge(int num) { //偶数の中で2は唯一の素数 if (num == 2) { return true; } //偶数は素数ではない if (num % 2 == 0) { return false; } //奇数を2ずつカウントアップ for (int i = 3; i < num; i+=2) { //奇数で割る if (num % i == 0) { return false; } } return true; } /** * 開始値と終了値を指定される */ public static void minToMax(int num1,int num2){ //入力された値の大小を確認 int max = Math.max(num1,num2); int min = Math.min(num1,num2); primeNumber(min,max); } }
1f4669fc4b07e3715fb9b8f49b5237581e529833
[ "Java" ]
1
Java
a-nakatsuka/primeNumber
7089cc9a170f870123d6649230a6ffb8f71ab1e4
cbcc5da1e7c0dc71c8d724335528aaeb950fedb7
refs/heads/master
<repo_name>Mattiamato/Array-based-stack<file_sep>/main.cpp // // main.cpp // stack_arraybased // // Created by <NAME> on 08.02.12. // Copyright (c) 2012 Universität Zürich. All rights reserved. // #include <iostream> #include "stack_ab.h" int main (int argc, const char * argv[]) { Stack_ab mystack; std::string temp; std::cout<<"initial size of stack: "<<mystack.size()<<"\n"; try { mystack.push("Villa"); mystack.push("Messi"); mystack.push("Alexis"); mystack.push("Iniesta"); mystack.push("Xavi"); mystack.push("Mascherano"); mystack.push("<NAME>"); mystack.push("Abidal"); mystack.push("Pique"); mystack.push("Puyol"); mystack.push("Valdes"); } catch (OverFlow& e) { e.overflowoutput(); } std::cout<<"current size of stack: "<<mystack.size()<<"\n"; std::cout<<"current top element is: "<<mystack.top()<<"\n"; try { while (!mystack.empty()) { std::cout<<mystack.pop()<<" wurde gepopt\n"; std::cout<<mystack.top()<<" is now on top\n"; //in the console these sentences are funny =) } } catch (UnderFlow& e) { e.underflowoutput(); } delete &mystack; int i; std::cin >> i; return 0; } <file_sep>/stack_ab.cpp // // stack_ab.cpp // stack_arraybased // // Created by <NAME> on 16.02.12. // Copyright (c) 2012 Universität Zürich. All rights reserved. // #include <iostream> #include "stack_ab.h" //all implementations here!!! Stack_ab::Stack_ab() //constructor { index = -1; } Stack_ab::~Stack_ab() //destructor { for(int i=0; i < StackMax; i++) data[i].clear(); index = -1; } int Stack_ab::size() //return stack size { return index+1; } void Stack_ab::push(std::string value) //add to stack { try { if(index+1 < StackMax) { index++; data[index] = value; } else { OverFlow e; throw e; } } catch(OverFlow e) { e.overflowoutput(); } } std::string Stack_ab::pop() //remove from stack { try { index--; return data[index+1]; } catch(UnderFlow e) { e.underflowoutput(); } } std::string Stack_ab::top() //return top position { try { if(index != -1) return data[index]; else { UnderFlow e; throw e; } } catch(UnderFlow e) { e.underflowoutput(); return "Nothing"; } } bool Stack_ab::empty() //is_empty { return index==-1; }
e848d3ee9d82d285f3e3e23f5685183236b1a550
[ "C++" ]
2
C++
Mattiamato/Array-based-stack
88d7207cfcb565fcc5d6167f556e5828dbe5ed05
2010383bb338ff7685ed7f8008c38c36fb3cfc50
refs/heads/master
<file_sep>def partition(nums, k): """ Given an integer array nums and an integer k, return true if it is possible to divide this array into k non-empty subsets whose sums are all equal. >>> partition([4,3,2,3,5,2,1], 4) True >>> partition([1,2,3,4], 3) False """ pass <file_sep>def crackingTheSafe(n, k): """ There is a box protected by a password. The password is a sequence of n digits where each digit can be one of the first k digits 0, 1, ..., k-1. While entering a password, the last n digits entered will automatically be matched against the correct password. For example, assuming the correct password is "345", if you type "<PASSWORD>", the box will open because the correct password matches the suffix of the entered password. Return any password of minimum length that is guaranteed to open the box at some point of entering it. >>> crackingTheSafe(1, 2): 10 """ pass <file_sep>def replaceSpace(string): """ Replace a space in a string with "%20. >>> replaceSpace("A B") 'A%20B' """ return string.replace(" ", "%20") <file_sep>def firstCharacterOnlyOnce(string): """ Find the first character in a string that appears only once and return its position. Strings contain only ASCII code characters. >>> firstCharacterOnlyOnce("abacc") 'b' """ from collections import Counter dic = Counter(string) for d in dic: if dic[d] == 1: return d return -1 <file_sep>def repeatedNumbers(list): """ All numbers in an array of n lengths are in the range of 0 to n-1. Some numbers in the array are duplicates, but it is not known how many numbers are duplicates, or how many times each number is repeated. Find any duplicate number in the array. >>> repeatedNumbers([2,3,1,0,2,5]) 2 """ for i in range(len(list)): while list[i] != i: if list[i] == list[list[i]]: return list[i] swap(list, i, list[i]) swap(list, i, list[i]) return -1 def swap(list, i, j): temp = list[i] list[i] = list[j] list[j] = temp <file_sep>def printClockwise(matrix): """ Print the value of the matrix from outside to inside in a clockwise direction. >>> A = [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16]] >>> printClockwise(A) '1, 2, 3, 4, 8, 12, 16, 15, 14, 13, 9, 5, 6, 7, 11, 10' """ strings = [] r1, r2, c1, c2 = 0, len(matrix) - 1, 0, len(matrix[0]) - 1 while r1 <= r2 and c1 <= c2: for i in range(c1, c2+1): strings.append(matrix[r1][i]) for i in range(r1+1, r2+1): strings.append(matrix[i][c2]) if r1 != r2: for i in range(c2-1, c1-1, -1): strings.append(matrix[r2][i]) if c1 != c2: for i in range(r2-1, r1, -1): strings.append(matrix[i][c1]) r1, r2, c1, c2 = r1 + 1, r2 - 1, c1 + 1, c2 - 1 return ", ".join([str(s) for s in strings]) <file_sep>def twoSum(nums: list, target: int): """ Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to target.You may assume that each input would have exactly one solution,and you may not use the same element twice. You can return the answer in any order. >>> twoSum([3, 2, 1, 4], 6) [1, 3] """ dic = {i: target - nums[i] for i in range(len(nums))} for i in dic: if dic[i] in nums and nums.index(dic[i]) != i: return [i, nums.index(dic[i])] """ for i in range(len(nums)): diff = target - nums[i] if diff in nums: if nums.index(diff) != i: return [i, nums.index(target - nums[i])] """ <file_sep>def lookup(matrix, num): """ Given a two-dimensional array, each row is sorted incrementally from left to right, and from top to bottom is also incremental. Given a number, determine whether the number is in the two-dimensional array. >>> A = [[1, 4, 7, 11, 15],[2, 5, 8, 12, 19],[3, 6, 9, 16, 22]] >>> lookup(A, 5) True >>> lookup(A, 20) False """ if matrix is None or len(matrix) == 0 or len(matrix[0]) == 0: return False rows, cols = len(matrix), len(matrix[0]) r, c = 0, cols - 1 while r <= rows - 1 and c >= 0: if num == matrix[r][c]: return True elif num > matrix[r][c]: r += 1 else: c -= 1 return False <file_sep># leetcode run scripts using command > python -m doctest file.py -v ## things to consider * this does not work ```python >>> A = [2,3,1,0,2,5] >>> A[0], A[A[0]] = A[A[0]], A[0] #error >>> A [1, 2, 1, 0, 2, 5] >>> A[0], A[1] = A[1], A[0] #This works ```
706957d018f4bec7687c0d03b1bd2f1e97c85734
[ "Markdown", "Python" ]
9
Python
PacificG/leetcode
52d2ba3329551a92547ab288a366ec5d7ad7d407
aaa292defc506919284872a66d6f525f0fb4346e
refs/heads/master
<repo_name>jeremt/gitbutler<file_sep>/setup.sh #!/bin/sh sudo npm install -g gulp && npm install && bower install && cd app && npm install<file_sep>/README.md Gitbutler ========= Minimalistic but powerful UI for GIT. The idea was to provide a UI that doesnt have to be in fullscreen, and allows to easily and fastly run git commands using simple shortcuts. ![123](screenshots/123.png) ![456](screenshots/456.png) Install ------- ### Install dependencies ```sh $ ./setup.sh ``` ### Install on mac ```sh $ gulp installMac ``` ### Install on other platforms ```sh $ gulp buildApp ``` Then, copy manually the application for your platform generated in `build` folder. Notes ----- This is a very experimental version, I'm still working on it and it's not finished yet. However, you can try it, give feedback or submit pullrequest to help me improve it;) To do ----- - Ask user reset or patch when push force by someone else - Handle when detached from head - Add custom commands - Add custom shortcuts - Native topbar menu - Add a virtual folder system for repositories (and reorder by drag-n-drop) - Add git hooks - Handle git config - History: load more commits on scroll and handle search in commits which aren't loaded yet - Add untracked in changes view - Add cross on alert popup To test ------- - Rebase mode - Other platform than OSX Bugs ---- - deleting branch when no remote branch - log commits when no remote branch - Buttons on Create and Clone overlays doesnt work... - When your remove a repository, the new selected one is not really selected
9f825c376feb0fde0090db2ccde3db720d9ea735
[ "Markdown", "Shell" ]
2
Shell
jeremt/gitbutler
5fa47362a77ebf8b0f65884b32113c465c8acd4c
47d1d3dac97f602b4c5a791c6b119b992b72c2b0
refs/heads/master
<repo_name>GranaraMariaSilvia/backendCafeteria<file_sep>/src/routes/producto.routes.js import { Router } from "express"; import productoControllers from "../controllers/producto.controllers"; const { getProductos, crearProducto, getUnProducto, deleteProducto, editarProducto, } = productoControllers; const router = Router(); router.route("/").get(getProductos).post(crearProducto); router .route("/:id") .get(getUnProducto) .delete(deleteProducto) .put(editarProducto); export default router; <file_sep>/src/controllers/producto.controllers.js const cafeteriaCtrl = {}; import Producto from "../models/producto"; cafeteriaCtrl.getUnProducto = async (req, res) => { try { console.log(req.params.id); const productoEncontrado = await Producto.findById(req.params.id); res.status(200).json(productoEncontrado); } catch (error) { console.log(error); res.status(500).json({ mensaje: "ocurrio un error" }); next(error); } }; cafeteriaCtrl.getProductos = async (req, res) => { try { const datos = await Producto.find(); //este metodo me trae todos los documentos res.status(200).json(datos); } catch (error) { console.log(error); } }; cafeteriaCtrl.crearProducto = async (req, res) => { console.log(req.body); const { nombreProducto, precioProducto, categoria } = req.body; try { const productoNuevo = new Producto({ nombreProducto: nombreProducto, precioProducto: precioProducto, categoria: categoria, }); await productoNuevo.save(); res.status(201).json({ mensaje: "llego el producto" }); } catch (error) { console.log(error); } }; cafeteriaCtrl.deleteProducto = async (req, res) => { try { await Producto.findByIdAndDelete(req.params.id); res.status(200).json({ mensaje: "se elimino un producto" }); } catch (error) { console.log(error); res.status(500).json({ mensaje: "ocurrio un error" }); next(error); } }; cafeteriaCtrl.editarProducto = async (req, res) => { try { await Producto.findByIdAndUpdate(req.params.id, req.body); res.status(200).json({ mensaje: "El producto se actualizo" }); } catch (error) { console.log(error); res.status(500).json({ mensaje: "ocurrio un error" }); next(error); } }; export default cafeteriaCtrl; <file_sep>/README.md # Backend de Cafeteria ## Comandos necesarios ejecutar estos <b>comandos</b> para clonar y poner en funcionamiento el proyecto ```javascript git clone URL npm install npm run dev ``` ## Autores 1. <NAME> ## Version de Backend Backend Cafeteria 1.0 <file_sep>/src/dataBase.js import mongoose from 'mongoose'; const url ='mongodb+srv://mariasilvia:[email protected]/test'; //cadena de conexion base de datos mongoose.connect(url,{ useNewUrlParser: true, useUnifiedTopology: true, useCreateIndex: true, useFindAndModify:true }) const conexion = mongoose.connection; conexion.once('open', ()=>{ console.log('Base de Datos CONECTADA') })
2178fffe1c3c10aae2007c816bc6924e93996310
[ "JavaScript", "Markdown" ]
4
JavaScript
GranaraMariaSilvia/backendCafeteria
793ab8b4f292eae4f5ec2ee7291d8568b63ba88b
2ca4186d2f3095eac6396434996ebbb66ecfd220
refs/heads/master
<file_sep># SDT-example-ble-ibeacon<file_sep>/* SDT-example-ble-ibeacon * * Copyright (c) 2018 Sigma Delta Technologies Inc. * * MIT License * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without * restriction, including without limitation the rights to use, * copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following * conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR * OTHER DEALINGS IN THE SOFTWARE. */ #include "mbed.h" #include "ble/BLE.h" #include "ble/services/iBeacon.h" #include "events/mbed_events.h" /* Serial */ #define BAUDRATE 9600 Serial serial_pc(USBTX, USBRX, BAUDRATE); /* DigitalOut */ #define LED_ON 0 #define LED_OFF 1 DigitalOut do_ledBlue(LED_BLUE, LED_OFF); /* Ticker */ Ticker ticker; /* EventQueue */ EventQueue eventQueue(4 * EVENTS_EVENT_SIZE); /* BLE */ #define BLE_DEVICE_NAME "SDT Device" BLE& ble_SDTDevice = BLE::Instance(); // Default ID of instance is 'DEFAULT_INSTANCE' /* iBeacon */ iBeacon* piBeacon; void callbackTicker(void) { do_ledBlue = !do_ledBlue; } void callbackEventsToProcess(BLE::OnEventsToProcessCallbackContext* context) { eventQueue.call(Callback<void()>(&ble_SDTDevice, &BLE::processEvents)); } void initIBeacon(BLE& ble) { /** * The Beacon payload has the following composition: * 128-Bit / 16byte UUID = E2 0A 39 F4 73 F5 4B C4 A1 2F 17 D1 AD 07 A9 61 * Major/Minor = 0x1122 / 0x3344 * Tx Power = 0xC8 = 200, 2's compliment is 256-200 = (-56dB) * * Note: please remember to calibrate your beacons TX Power for more accurate results. */ const uint8_t uuid[] = {0xE2, 0x0A, 0x39, 0xF4, 0x73, 0xF5, 0x4B, 0xC4, 0xA1, 0x2F, 0x17, 0xD1, 0xAD, 0x07, 0xA9, 0x61}; uint16_t majorNumber = 1122; uint16_t minorNumber = 3344; uint16_t txPower = 0xC8; piBeacon = new iBeacon(ble, uuid, majorNumber, minorNumber, txPower); } void printMacAddress(BLE& ble) { /* Print out device MAC address to the console */ Gap::AddressType_t addr_type; Gap::Address_t address; ble.gap().getAddress(&addr_type, address); serial_pc.printf("DEVICE MAC ADDRESS = "); for (int i = 5; i >= 1; i--){ serial_pc.printf("%02x:", address[i]); } serial_pc.printf("%02x\n", address[0]); } /** * Callback triggered when the ble initialization process has finished */ void callbackBleInitComplete(BLE::InitializationCompleteCallbackContext* params) { BLE& ble = params->ble; // 'ble' equals ble_SDTDevice declared in global ble_error_t error = params->error; // 'error' has BLE_ERROR_NONE if the initialization procedure started successfully. if (error == BLE_ERROR_NONE) { serial_pc.printf("Initialization completed successfully\n"); } else { /* In case of error, forward the error handling to onBleInitError */ serial_pc.printf("Initialization failled\n"); return; } /* Ensure that it is the default instance of BLE */ if(ble.getInstanceID() != BLE::DEFAULT_INSTANCE) { serial_pc.printf("ID of BLE instance is not DEFAULT_INSTANCE\n"); return; } /* Setup iBeacon */ initIBeacon(ble); /* Setup and start advertising */ printMacAddress(ble); // Optional function ble.gap().accumulateAdvertisingPayload(GapAdvertisingData::SHORTENED_LOCAL_NAME, (const uint8_t *)BLE_DEVICE_NAME, sizeof(BLE_DEVICE_NAME) - 1); ble.gap().setAdvertisingInterval(1000); // Advertising interval in units of milliseconds ble.gap().startAdvertising(); serial_pc.printf("Start advertising\n"); } int main(void) { serial_pc.printf("< Sigma Delta Technologies Inc. >\n\r"); /* Init BLE and iBeacon */ ble_SDTDevice.onEventsToProcess(callbackEventsToProcess); ble_SDTDevice.init(callbackBleInitComplete); /* Check whether IC is running or not */ ticker.attach(callbackTicker, 1); eventQueue.dispatch_forever(); return 0; }
0f4ca8e16d75a7dc43014a8f1f0493f7cd4422e0
[ "Markdown", "C++" ]
2
Markdown
SigmaDeltaTechnologiesInc/SDT-example-ble-ibeacon
00de1b87ddb2cd47f01e8013519be1cd872d3e9b
4926030fdf3dcd55ee4d6277e8db6956828ab35a
refs/heads/master
<file_sep>/* Filename: ow10000-tetris.cpp Purpose: Tetris Game Created: June 29, 2016 */ #include "Arduino.h" #include "ow10000-tetris.h" #include "ow10000-hardware.h" #include "ow10000-text.h" // Default Constructor OW10000_tetris::OW10000_tetris(OW10000HAL* badgeToLinkTo) { badge = badgeToLinkTo; randomSeed(millis()); // See the "random" number generator //I block blocks[0].num_rotations = 2; blocks[0].rotations[0] = {4, 1, {0b1111}}; blocks[0].rotations[1] = {2, 4, {0b10, 0b10, 0b10, 0b10}}; //J block blocks[1].num_rotations = 4; blocks[1].rotations[0] = {3, 2, {0b111, 0b001}}; blocks[1].num_rotations = 4; blocks[1].rotations[1] = {2, 3, {0b01, 0b01, 0b11}}; blocks[1].num_rotations = 4; blocks[1].rotations[2] = {3, 2, {0b100, 0b111}}; blocks[1].num_rotations = 4; blocks[1].rotations[3] = {2, 3, {0b11, 0b10, 0b10}}; //L block blocks[2].num_rotations = 4; blocks[2].rotations[0] = {3, 2, {0b111, 0b100}}; blocks[2].num_rotations = 4; blocks[2].rotations[1] = {2, 3, {0b10, 0b10, 0b11}}; blocks[2].num_rotations = 4; blocks[2].rotations[2] = {3, 2, {0b001, 0b111}}; blocks[2].num_rotations = 4; blocks[2].rotations[3] = {2, 3, {0b11, 0b01, 0b01}}; //O block blocks[3].num_rotations = 1; blocks[3].rotations[0] = {2, 2, {0b11, 0b11}}; //S block blocks[4].num_rotations = 2; blocks[4].rotations[0] = {3, 2, {0b011, 0b110}}; blocks[4].rotations[1] = {2, 3, {0b10, 0b11, 0b01}}; //Z block blocks[5].num_rotations = 2; blocks[5].rotations[0] = {3, 2, {0b110, 0b011}}; blocks[5].rotations[1] = {2, 3, {0b01, 0b11, 0b10}}; //T block blocks[6].num_rotations = 4; blocks[6].rotations[0] = {3, 2, {0b010, 0b111}}; blocks[6].rotations[1] = {2, 3, {0b10, 0b11, 0b10}}; blocks[6].rotations[2] = {3, 2, {0b111, 0b010}}; blocks[6].rotations[3] = {2, 3, {0b01, 0b11, 0b01}}; } // Reset the game void OW10000_tetris::reset() { //Initialize screen for (int y = 0; y < TETRIS_HEIGHT; y++) { rows[y] = 0; badge->setPixel(TETRIS_WIDTH, y, 1); for (int x = TETRIS_WIDTH + 1; x < 16; x++) { badge->setPixel(x, y, 0); } } block_x = TETRIS_WIDTH / 2 - 1; block_y = 0; rotation = 0; block = random(7); next_block = random(7); draw_next(); gameSpeed = 1000; //1 second to start with } // Play the game void OW10000_tetris::play() { reset(); // If both buttons are pressed, leave the game while(!badge->buttonAB_debounce(200)) { // Main game loop // check the buttons int new_x = block_x; int new_y = block_y; int new_rotation = rotation; bool pressed = false; if(badge->buttonL_debounce()){ new_x--; pressed = true; } if(badge->buttonR_debounce()){ new_x++; pressed = true; } if(badge->buttonU_debounce()){ new_rotation = (rotation + 1) % blocks[block].num_rotations; pressed = true; } if(badge->buttonD_debounce()){ new_y++; pressed = true; } if (pressed && check_position(new_x, new_y, new_rotation)) { block_x = new_x; block_y = new_y; rotation = new_rotation; paint(); } // Update stuff if(millis() > lastUpdate + gameSpeed){ lastUpdate = millis(); // Update the game timer if (check_position(block_x, block_y + 1, rotation)) { block_y++; } else { settle(); //Get new block ready block_x = TETRIS_WIDTH / 2 - 1; block_y = 0; block = next_block; next_block = random(7); draw_next(); rotation = 0; if (!check_position(block_x, block_y, rotation)) { //Game Over break; } } paint(); if (gameSpeed > 100) gameSpeed--; } } } void OW10000_tetris::paint() { //turn on pixels for occupied spaces for (int y = 0; y < TETRIS_HEIGHT; y++) { for (int x = 0; x < TETRIS_WIDTH; x++) { if (rows[y] & (1 << x)) badge->setPixel(x, y, 3); else badge->setPixel(x, y, 0); } } //turn on pixels for current block in play BlockRotation &b = blocks[block].rotations[rotation]; for (int x = 0; x < b.width; x++) { if (x + block_x >= TETRIS_WIDTH) break; for (int y = 0; y < b.height; y++) { if (y + block_y >= TETRIS_HEIGHT) break; if (b.map[y] & (1 << x)) badge->setPixel(x + block_x, y + block_y, 3); } } } void OW10000_tetris::draw_next() { //clear old one for (int x = TETRIS_WIDTH + 1; x < 16; x++) { for (int y = 1; y < 5; y++) { badge->setPixel(x, y, 0); } } //draw new one BlockRotation &b = blocks[next_block].rotations[0]; for (int x = 0; x < b.width; x++) { for (int y = 0; y < b.height; y++) { if (b.map[y] & (1 << x)) badge->setPixel(x + TETRIS_WIDTH + 2, y + 1, 3); } } } //Validate that a block can occupy the specified position bool OW10000_tetris::check_position(int test_x, int test_y, int test_rotation) { BlockRotation &b = blocks[block].rotations[test_rotation]; for (int x = 0; x < b.width; x++) { for (int y = 0; y < b.height; y++) { if (!(b.map[y] & (1 << x))) continue; if (x + test_x < 0 || x + test_x >= TETRIS_WIDTH) return false; if (y + test_y < 0 || y + test_y >= TETRIS_HEIGHT) return false; if (rows[test_y + y] & (1 << (test_x + x))) return false; } } return true; } void OW10000_tetris::settle() { //Mark the spaces where the current block in play sits BlockRotation &b = blocks[block].rotations[rotation]; for (int x = 0; x < b.width; x++) { for (int y = 0; y < b.height; y++) { if (b.map[y] & (1 << x)) { rows[y + block_y] |= 1 << (x + block_x); } } } //Look for and delete solid rows bool done = false; while (!done) { done = true; for (int y = TETRIS_HEIGHT - 1; y >= 0; y--) { if (rows[y] == SOLID_ROW) { //This is where we would keep score if there were anywhere to display it done = false; for (int i = y; i > 0; i--) { rows[i] = rows[i - 1]; } rows[0] = 0; break; } } } }
532d7319dbb6de644f2ed6a5fb9432b075b5ea19
[ "C++" ]
1
C++
systronix/OpenWest2016
b43db0a108bf53c2f275beea4f39318ce72be30d
1c369e2e7fde2eb6f96a2d4b8945bdb4efbf9d4f
refs/heads/master
<file_sep>#define RATIOREMOVECLAUSES 2 #define NBCLAUSESBEFOREREDUCE 20000 #define DYNAMICNBLEVEL #define CONSTANTREMOVECLAUSE #define UPDATEVARACTIVITY #define BLOCK <file_sep>#!/bin/bash export FM=$PWD/sources/SatElite/ForMani rm -rf ebglucose_static rm -rf SatELite_release cd sources/SatElite/SatELite make clean cd ../ForMani/Global make clean cd ../ADTs make clean cd ../../../glucose/core make clean <file_sep>Main.o: Main.C Solver.h constants.h ../mtl/Vec.h ../mtl/Heap.h \ ../mtl/Vec.h ../mtl/Alg.h SolverTypes.h BoundedQueue.h Solver.o: Solver.C Solver.h constants.h ../mtl/Vec.h ../mtl/Heap.h \ ../mtl/Vec.h ../mtl/Alg.h SolverTypes.h BoundedQueue.h ../mtl/Sort.h Main.op: Main.C Solver.h constants.h ../mtl/Vec.h ../mtl/Heap.h \ ../mtl/Vec.h ../mtl/Alg.h SolverTypes.h BoundedQueue.h Solver.op: Solver.C Solver.h constants.h ../mtl/Vec.h ../mtl/Heap.h \ ../mtl/Vec.h ../mtl/Alg.h SolverTypes.h BoundedQueue.h ../mtl/Sort.h Main.od: Main.C Solver.h constants.h ../mtl/Vec.h ../mtl/Heap.h \ ../mtl/Vec.h ../mtl/Alg.h SolverTypes.h BoundedQueue.h Solver.od: Solver.C Solver.h constants.h ../mtl/Vec.h ../mtl/Heap.h \ ../mtl/Vec.h ../mtl/Alg.h SolverTypes.h BoundedQueue.h ../mtl/Sort.h Main.or: Main.C Solver.h constants.h ../mtl/Vec.h ../mtl/Heap.h \ ../mtl/Vec.h ../mtl/Alg.h SolverTypes.h BoundedQueue.h Solver.or: Solver.C Solver.h constants.h ../mtl/Vec.h ../mtl/Heap.h \ ../mtl/Vec.h ../mtl/Alg.h SolverTypes.h BoundedQueue.h ../mtl/Sort.h
f0f2f58fa61e7ca7547c66d3491ba5385064cc98
[ "C", "Makefile", "Shell" ]
3
C
bmatsuo/EBGlucose
69b6aa30297002cf8eaec5bb2349f22fbe1addb4
7fe09e31d6587d2c5d75b84965b936755b59cc1d
refs/heads/master
<file_sep>/* * View model for OctoPrint-Locbit * * Author: <NAME> * License: AGPLv3 */ $(function() { function LocbitViewModel(parameters) { var printerState = parameters[0]; var settingsState = parameters[1]; var filesState = parameters[2]; var self = this; function apiFetch() { $.ajax({ type: "GET", url: "/api/plugin/Locbit", success: function(data) { // $('#material').html(data); if (Object.keys(data).length == 5) { $('#material').html(data.material); $('#diameter').html(data.diameter); $('#color').html(data.color); $('#length').html(data.length); $('#muid').html(data.muid); } else { $('#qr-btn').after('<div id="qr-error">Invalid QR Code</div>'); setTimeout(function(){ $('#qr-error').remove(); }, 2000); } } }); } self.onStartup = function() { var element = $("#state").find(".accordion-inner .progress"); if (element.length) { var text0 = gettext("Material"); var text = gettext("Material Diameter (mm)"); var text2 = gettext("Color"); var text3 = gettext("Length (m)"); var text4 = gettext("MUID"); element.before(text0 + ": <strong id='material'></strong><br>"); element.before(text + ": <strong id='diameter'></strong><br>"); element.before(text2 + ": <strong id='color'></strong><br>"); element.before(text3 + ": <strong id='length'></strong><br>"); element.before(text4 + ": <strong id='muid'></strong><br>"); } var code = '<div class="jog-panel"> <!-- QR Code control panel --> <div class="jog-panel" id="scan-qr-code"> <h1>QR Code</h1><div> <button class="btn btn-block control-box" id="qr-btn" data-bind="enable: isOperational() && !isPrinting() && loginState.isUser(), click: function() { } ">Scan QR</button></div></div></div>'; var controlElement = $("#control"); controlElement.append(code); $( "#qr-btn" ).bind( "click", function() { apiFetch(); }); }; // assign the injected parameters, e.g.: // self.loginStateViewModel = parameters[0]; // self.settingsViewModel = parameters[1]; // TODO: Implement your plugin's view model here. } // view model class, parameters for constructor, container to bind to OCTOPRINT_VIEWMODELS.push([ LocbitViewModel, ["printerStateViewModel", "settingsViewModel", "gcodeFilesViewModel"], [] ]); }); <file_sep>from SimpleCV import Color, Camera, Display, JpegStreamCamera def scan(): jc = JpegStreamCamera("http://octopi.local/webcam/?action=stream") qrcode = [] while(not qrcode): img_og = jc.getImage() #gets image from the camera img = img_og qrcode = img.findBarcode() #finds qr data from image if(qrcode is not None): #if there is some data processed qrcode = qrcode[0] result = str(qrcode.data) return result #returns result of qr in python shell <file_sep>from __future__ import absolute_import from httplib import BadStatusLine from .locbitNotifications import locbitMsgDict import octoprint.plugin import requests import flask Layer = 0 uid = "55de667a295efb62093205e4" # url = "http://192.168.0.34:3000" url = "http://api.locbit.com:8888/endpoint" class LocbitPlugin(octoprint.plugin.StartupPlugin, octoprint.plugin.TemplatePlugin, octoprint.plugin.SettingsPlugin, octoprint.plugin.EventHandlerPlugin, octoprint.plugin.AssetPlugin, octoprint.plugin.SimpleApiPlugin): def get_api_commands(self): return dict( command1=[], command2=["some_parameter"] ) def on_api_command(self, command, data): import flask if command == "command1": parameter = "unset" if "parameter" in data: parameter = "set" self._logger.info("command1 called, parameter is {parameter}".format(**locals())) elif command == "command2": self._logger.info("command2 called, some_parameter is {some_parameter}".format(**data)) def on_api_get(self, request): import subprocess answer = subprocess.check_output(['/home/pi/oprint/lib/python2.7/site-packages' '/octoprint_Locbit/qr.py']) qr_res = answer.split(",") if len(qr_res) == 5: return flask.jsonify(material=qr_res[0], diameter=qr_res[1], color=qr_res[2], length=qr_res[3], muid=qr_res[4]) else: return "Invalid QR code" def on_after_startup(self): self._logger.info("Hello world! I am: %s" % self._settings.get(["did"])) def get_settings_defaults(self): return dict(did="TEST_PRINTER") def get_template_configs(self): return [ dict(type="navbar", custom_bindings=False), dict(type="settings", custom_bindings=False) ] def get_assets(self): return dict(js=["js/Locbit.js"]) def on_event(self, event, payload, **kwargs): global Layer global uid global url did = self._settings.get(["did"]) self.checkPrinterStatus() if event == "PrintStarted": Layer = 0 self.sendLayerStatus(Layer) elif event == "PrintFailed": Layer = 0 self.sendLayerStatus(Layer) elif event == "PrintCancelled": Layer = 0 self.sendLayerStatus(Layer) if event in locbitMsgDict: event_body = { 'uid' : uid, 'did' : did, 'event' : locbitMsgDict[event]['name'], 'status' : locbitMsgDict[event]['value'] } elif event == 'FileSelected': event_body = { 'uid' : uid, 'did' : did, 'event' : 'File', 'status' : payload['filename'] } elif event == 'ZChange': Layer += 1 event_body = { 'uid' : uid, 'did' : did, 'event' : 'Layer', 'status' : Layer } else: event_body = { 'uid' : uid, 'did' : did, 'event': event } try: requests.post(url, data = event_body) except BadStatusLine: self._logger.info("Locbit: Bad Status") self._logger.info("Locbit: Recording event " + event) def sendLayerStatus(self, layer): global uid global url did = self._settings.get(["did"]) event_body = { 'uid' : uid, 'did' : did, 'event' : 'Layer', 'status' : layer } try: requests.post(url, data = event_body) except BadStatusLine: self._logger.info("Locbit: Bad Status") def checkPrinterStatus(self): url = "http://localhost/api/printer" apiKey = self._settings.get(["apiKey"]) try: r = requests.get(url, headers = { "X-Api-Key" : apiKey }) self._logger.info(r.text) except BadStatusLine: self._logger.info("Locbit: Bad Status") __plugin_name__ = "Locbit" __plugin_implementation__ = LocbitPlugin() <file_sep>#!/usr/bin/env python import commands import qr_reader import os tmp = qr_reader.scan() print tmp<file_sep># OctoPrint-Locbit Locbit Octoprint integration. ## Setup Install manually using this URL: https://github.com/Locbit/OctoPrint-Locbit/archive/qr-code.zip Requires the following ssh commands to work sudo apt-get update sudo apt-get install ipython python-opencv python-scipy python-numpy python-setuptools python-pip python-pygame sudo pip install svgwrite https://github.com/sightmachine/SimpleCV/zipball/master sudo apt-get install python-zbar chmod +x ~/oprint/lib/python2.7/site-packages/octoprint_Locbit/qr.py Then restart OctoPrint
4af7f53ad8097b07c3c646b950300ae81abf6c5d
[ "JavaScript", "Python", "Markdown" ]
5
JavaScript
anthonyattard/OctoPrint-Locbit
257eb8536430caf80468cb0333751a66ec181d0a
015296a34ee3f57623035bcb4befd83bf6654d0a
refs/heads/master
<file_sep># Opgave 8 avit <- read.table("avit.txt", header=TRUE) # Indlæs datasættet # Opgave 9 avitM <- subset(avit, sex==1)$avit # Udtag mændenes avit-indtag length(avitM) # Tæl mændene logavitM <- log(avitM) # Opgave 10 pdf("graphs/analyse_1.pdf") hist(avitM) # Histogram for avitM dev.off() pdf("graphs/analyse_2.pdf") qqnorm(avitM) # QQ-plot for avitM dev.off() pdf("graphs/analyse_3.pdf") hist(logavitM) # Histogram for logavitM dev.off() pdf("graphs/analyse_4.pdf") qqnorm(logavitM) # QQ-plot for logavitM dev.off() # Opgave 11 mean(logavitM) # Gennemsnittet af logavitM var(logavitM) # Stikprøvevariansen af logavitM sd(logavitM) # Stikprøvespredningen af ligavitM # Opgave 12 pdf("graphs/analyse_5.pdf") hist(logavitM, prob=T, nclass=25) f = function(x) dnorm(x, mean(logavitM), sd(logavitM)) plot(f, 0,9, add=T) dev.off() lnorm = function(y, mu, sigma) 1/(y*sqrt(2*pi*sigma^2)) * exp(-((log(y) - mu)^2) / (2*sigma^2)) pdf("graphs/analyse_6.pdf") hist(avitM, prob=T, nclass=25) g = function(x) lnorm(x, mean(logavitM), sd(logavitM)) plot(g, 0, 8000, add=T) dev.off() <file_sep>GRAPHS= TARGET=aflevering.pdf TEXFILES=*.tex HELPFILES= all: $(TARGET) $(TARGET): $(GRAPHS) $(TEXFILES) $(HELPFILES) Makefile clean: rm -rf *.aux *.log *.out *.toc *.eps *.data *.o *.hi *~ $(GRAPHS) $(TARGET) %.svg: %.dot dot $*.dot -Tsvg -o $*.svg %.png: %.dot dot $*.dot -Tpng -o $*.png %.ps: %.dot dot $*.dot -Tps -o $*.ps %_dot.pdf: %.dot dot $*.dot -Tpdf -o $*_dot.pdf %_neato.pdf: %.dot neato $*.dot -Tpdf -o $*_neato.pdf %_circo.pdf: %.dot circo $*.dot -Tpdf -o $*_circo.pdf %.mapleout: %.maple $(HOME)/bin/maple $*.maple > $*.mapleout %_guimaple.ps: %.maple mwrapper $*.maple %_maple.ps: %.maple $(HOME)/bin/maple $*.maple %_dia.eps: %.dia dia $*.dia -e $*_dia.eps %_eps.pdf: %.eps epstopdf $*.eps -o $*_eps.pdf %.pdf: %.tex pdflatex $*.tex pdflatex $*.tex pdflatex $*.tex print: $(TARGET) cat $(TARGET) | ssh <EMAIL> lp -d m1b <file_sep>#!/bin/sh if [ `whoami` != root ]; then sudo $0 exit 0 fi apt-get install texlive-full graphviz dia TMPDIR=`mktemp -d` cd $TMPDIR # fjern eksisterende install find /usr/local/share/texmf -name '*ku-forside*' | xargs rm -rf find /usr/local/share/texmf -name '*oberdiek*' | xargs rm -rf # Download listingsutf8 wget http://mirror.ctan.org/install/macros/latex/contrib/oberdiek.tds.zip unzip oberdiek.tds.zip -d /usr/local/share/texmf # Download ku-forside wget http://www.math.ku.dk/~m00cha/ku-forside.zip unzip ku-forside.zip -d /usr/local/share/texmf/tex/latex KUFIL=/usr/local/share/texmf/tex/latex/ku-forside/ku-forside.sty iconv -f iso-8859-1 -t utf-8 $KUFIL -o ku-forside.sty mv -f ku-forside.sty $KUFIL # opdater tex texhash # ryd op cd / rm -rf $TMPDIR <file_sep>sim <- exp(rnorm(5000,5,0.5)) f <- function(y,mu,sigma) 1/(y*sqrt(2*pi*sigma^2))*exp(-((log(y)-mu)^2)/(2*sigma^2)) yval <- seq(0,1000,1) fval <- f(yval,5,0.5) pdf("graphs/simulation_1.pdf") hist(sim,prob=T,nclass=50) lines(yval,fval) dev.off() results <- c(mean(sim),var(sim),sd(sim))
77fdde8f3f2ca6ec1be6e1dd8a502df9253e5056
[ "Makefile", "R", "Shell" ]
4
R
Freaken/SS
d77cdedd6ee360400f6f6eaef41eb4f8a957dc3b
40f8e6d0feca976accccb5c5f1110c4428325b7f
refs/heads/master
<file_sep>## Tidy Part 1 # Get feature names and subset to only those features of mean or std measures features<-read.table("features.txt") features1<- grep("std|mean", features$V2) ## Tidy Part 2 # Get the train and test feature sets and subset only the desired features testX<- read.table("C:/Users/Transorg/Desktop/test/X_test.txt") testX1<- testX[,features1] trainX <-read.table("C:/Users/Transorg/Desktop/train/X_train.txt") trainX1<- trainX[,features1] ## Tidy Part 3 # Combine the two datasets into 1 totalX<- rbind(testX1,trainX1) ## Tidy Part 4 # Attach column names to features colnames(totalX)<- features[features1,2] # Tidy Part 5 # Read and combine the train and test activity codes testY <- read.table("C:/Users/Transorg/Desktop/test/y_test.txt") trainY <-read.table("C:/Users/Transorg/Desktop/train/y_train.txt") total.activities<- rbind(testY,trainY) # Tidy Part 6 # Get activity labels and attach to activity codes activity.labels<- read.table("C:/Users/Transorg/Desktop/activity_labels.txt") total.activities$activity <- factor(total.activities$V1, levels = activity.labels$V1, labels = activity.labels$V2) # Tidy Part 7 # Get and combine the train and test subject ids subject_test<-read.table("C:/Users/Transorg/Desktop/test/subject_test.txt") subject_train <- read.table("C:/Users/Transorg/Desktop/train/subject_train.txt") subject<- rbind(subject_test, subject_train) subjects_activities <- cbind(subject, total.activities$activity) colnames(subjects_activities) <- c("subject.id", "activity") # Tidy Part 9 # Combine with measures of interest for finished desired data frame activity.frame <- cbind(subjects_activities, totalX) # Compute New Result # From the set produced for analysis, compute and report means of # all measures, grouped by subject_id and by activity. result.frame <- aggregate(activity.frame[,3:81], by = list(activity.frame$subject.id, activity.frame$activity), FUN = mean) colnames(result.frame)[1:2] <- c("subject.id", "activity") write.table(result.frame, file="mean_measures.txt", row.names = FALSE)
e9c79b80a730a7413db118eb746f6dcadad30982
[ "R" ]
1
R
anuchaudharyiitd/run_analysis
b23edfe38b09dfe98802ae4ab46d33cf6ce9b487
c9863971bfc54b2b5ed604bcac5ca6463f830e64
refs/heads/main
<repo_name>scottmsilver/protobufjs-for-appscript<file_sep>/index.js // When you build this the transitive closure of export is included. import protobuf from 'protobufjs'; import FlightDesignator from 'flight-designator' export {protobuf, FlightDesignator}; <file_sep>/README.md # protobufjs-for-appscript This is a small helper library that helps us generate a single JS file of protobufjs for use in AppScript. I also have added some other libraries I am using in projects. (I shouldn't do this) To do this yourself: - Install and build the library (you can give the global name anything you want.) ```console npm install --save-dev protobufjs npm i --save-dev flight-designator npx esbuild index.js --bundle --global-name=psl --outfile=libraries.js ``` - Copy the contents of protobuf.js to your AppScript (it will be called protobuf.gs, presumably). I copied and pasted. :) - Use it ```javascript const flightsProto = "my protofile as string" const root = await psl.protobuf.parse(flightsProto).root ``` - Note that you cannot load files so I converted my proto into a string. - You might also wish to test to see if you are running under AppScript so you can develop simulataneously locally and in AppScript. This piece of code might be useful. ```javascript // Return true if this script is running under Google App Script function underGoogleAppScript() { return typeof Utilities !== 'undefined' && Utilities.base64EncodeWebSafe !== 'undefined' } ``` - I use it like this: ```javascript const protobuf = underGoogleAppScript() ? psl.protobuf : require("protobufjs"); const root = await protobuf.parse(flightsProto).root ```
61f4d1c916eb907e373e05a6560a61ecc8571202
[ "JavaScript", "Markdown" ]
2
JavaScript
scottmsilver/protobufjs-for-appscript
5407d49c9d7fcd22a97542daf21a7d6401d11158
4aafca0d668062afaeda19f6f94a5615efc78ee7
refs/heads/master
<repo_name>deon-Mass/VST<file_sep>/app/src/main/java/cd/digitalEdge/vst/Views/Lists/Commandes.java package cd.digitalEdge.vst.Views.Lists; import android.content.Context; import android.content.Intent; import android.os.Bundle; import android.util.Log; import android.view.MenuItem; import android.view.View; import android.widget.LinearLayout; import android.widget.ListView; import android.widget.Toast; import androidx.annotation.NonNull; import androidx.appcompat.app.AppCompatActivity; import com.androidnetworking.AndroidNetworking; import com.androidnetworking.common.Priority; import com.androidnetworking.error.ANError; import com.androidnetworking.interfaces.JSONObjectRequestListener; import com.kosalgeek.android.caching.FileCacher; import org.json.JSONArray; import org.json.JSONObject; import java.util.ArrayList; import cd.digitalEdge.vst.Adaptors.Adaptor_commands_list; import cd.digitalEdge.vst.Adaptors.Adaptor_recherche_list; import cd.digitalEdge.vst.Controllers.Config; import cd.digitalEdge.vst.Objects.Articles; import cd.digitalEdge.vst.Objects.Commande; import cd.digitalEdge.vst.R; import cd.digitalEdge.vst.Tools.Constants; import cd.digitalEdge.vst.Tools.Preferences; import cd.digitalEdge.vst.Views.Gerer; public class Commandes extends AppCompatActivity { Context context = this; Adaptor_commands_list adaptor; ListView command_list; LinearLayout progress_data; ArrayList<Commande> COMMAMNDES = new ArrayList<>(); FileCacher<ArrayList<Commande>> DATAS_CACHED = new FileCacher<>(context, Constants.FILE_COMMANDES); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_commandes); getSupportActionBar().setTitle("Mes commandes"); getSupportActionBar().setDisplayHomeAsUpEnabled(true); INIT_COMPONENT(); getData(); } private void INIT_COMPONENT() { progress_data = findViewById(R.id.progress_data); command_list = findViewById(R.id.command_list); progress_data.setVisibility(View.GONE); } @Override protected void onResume() { super.onResume(); } @Override public void onBackPressed() { Intent i = new Intent(context, Gerer.class); startActivity(i); finish(); } @Override public boolean onOptionsItemSelected(@NonNull MenuItem item) { super.onOptionsItemSelected(item); switch (item.getItemId()) { case android.R.id.home: // API 5+ solution onBackPressed(); return true; } return true; } void getData(){ adaptor = new Adaptor_commands_list(context); command_list.setAdapter(adaptor); } // TODO METHOD private void LoadCommands(){ //Log.i("PRODUCT_DATAS ",Config.GET_PRODUCTS); progress_data.setVisibility(View.VISIBLE); //error404.setVisibility(View.GONE); COMMAMNDES.clear(); AndroidNetworking .post(Config.GET_COMMAND) .addBodyParameter("id", Preferences.getCurrentUser(context).getId()) .setPriority(Priority.HIGH) .build() .getAsJSONObject(new JSONObjectRequestListener() { @Override public void onResponse(JSONObject response) { try { JSONArray ar = response.getJSONArray("results"); //Log.e("PRODUCT_DATAS RR ", ar.toString()); for (int i = 0; i < ar.length(); i++) { JSONObject jsonObject = ar.getJSONObject(i); Commande p = new Commande(); p.setId(jsonObject.getString(new Commande().id)); COMMAMNDES.add(p); } DATAS_CACHED.writeCache(COMMAMNDES); if (COMMAMNDES.size()<1){ Toast.makeText(context, "Empy", Toast.LENGTH_SHORT).show(); //error404.setVisibility(View.VISIBLE); }else{ //adaptor = new Adaptor_commands_list(context, COMMAMNDES); command_list.setAdapter(adaptor); //error404.setVisibility(View.GONE); } progress_data.setVisibility(View.GONE); } catch (Exception e) { Log.e("PRODUCT_DATAS--XX ",e.getMessage()); //error404.setVisibility(View.VISIBLE); LoadCache(); } } @Override public void onError(ANError anError) { progress_data.setVisibility(View.GONE); Log.e("PRODUCT_DATAS ",anError.getMessage()); //error404.setVisibility(View.VISIBLE); LoadCache(); } }); } private void LoadCache() { progress_data.setVisibility(View.VISIBLE); try { if (DATAS_CACHED.getSize()<1){ Toast.makeText(context, "Empy", Toast.LENGTH_SHORT).show(); //error404.setVisibility(View.VISIBLE); }else{ //adaptor = new Adaptor_commands_list(context, DATAS_CACHED.readCache()); command_list.setAdapter(adaptor); //error404.setVisibility(View.GONE); } progress_data.setVisibility(View.GONE); //Log.e("CACHED_DATA", String.valueOf(DATAS_CACHED.readCache().size())); } catch (Exception e) { e.printStackTrace(); } } } <file_sep>/app/src/main/java/cd/digitalEdge/vst/Views/Lists/Blog.java package cd.digitalEdge.vst.Views.Lists; import android.content.Context; import android.content.Intent; import android.os.Bundle; import android.os.Handler; import android.util.Log; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.animation.Animation; import android.view.animation.AnimationUtils; import android.widget.AbsListView; import android.widget.LinearLayout; import android.widget.ListView; import android.widget.ProgressBar; import android.widget.Toast; import androidx.annotation.NonNull; import androidx.appcompat.app.AppCompatActivity; import com.androidnetworking.AndroidNetworking; import com.androidnetworking.common.Priority; import com.androidnetworking.error.ANError; import com.androidnetworking.interfaces.JSONObjectRequestListener; import com.kosalgeek.android.caching.FileCacher; import org.json.JSONArray; import org.json.JSONObject; import java.util.ArrayList; import cd.digitalEdge.vst.Adaptors.Adaptor_blog_list; import cd.digitalEdge.vst.Controllers.Config; import cd.digitalEdge.vst.MainActivity; import cd.digitalEdge.vst.Objects.Posts; import cd.digitalEdge.vst.Objects.Posts; import cd.digitalEdge.vst.R; import cd.digitalEdge.vst.Tools.Constants; import cd.digitalEdge.vst.Tools.Preferences; import cd.digitalEdge.vst.Tools.Tool; import cd.digitalEdge.vst.Views.Blanks.Contacts; public class Blog extends AppCompatActivity { Context context = this; ListView blog_list; LinearLayout progress_data,error404; Adaptor_blog_list adapter; ArrayList<Posts> POSTS = new ArrayList<>(); FileCacher<ArrayList<Posts>> DATAS_CACHED = new FileCacher<>(context, Constants.FILE_POSTS); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_blog); getSupportActionBar().setTitle("Suprême Blog"); getSupportActionBar().setDisplayHomeAsUpEnabled(true); INIT_COMPONENT(); //getBlog(); LoadPosts(); } void INIT_COMPONENT(){ blog_list = findViewById(R.id.blog_list); error404 = findViewById(R.id.error404); progress_data = findViewById(R.id.progress_data); progress_data.setVisibility(View.GONE); error404.setVisibility(View.GONE); } @Override protected void onResume() { super.onResume(); blog_list.setOnScrollListener(new AbsListView.OnScrollListener() { @Override public void onScrollStateChanged(AbsListView view, int scrollState) { if ( scrollState == AbsListView.OnScrollListener.SCROLL_STATE_IDLE && (blog_list.getLastVisiblePosition() ) >= adapter.getCount()-2 ){ Animation from_right = AnimationUtils.loadAnimation(context, R.anim.m_fromright); Animation to_right = AnimationUtils.loadAnimation(context, R.anim.m_toleft); progress_data.startAnimation(from_right); progress_data.setVisibility(View.VISIBLE); new Handler().postDelayed(new Runnable() { @Override public void run() { progress_data.startAnimation(to_right); progress_data.setVisibility(View.GONE); } }, 2000); } } @Override public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) { } }); } @Override public void onBackPressed() { Intent i = new Intent(context, MainActivity.class); startActivity(i); finish(); } @Override public boolean onCreateOptionsMenu(Menu menu) { super.onCreateOptionsMenu(menu); getMenuInflater().inflate(R.menu.blog_menu, menu); return true; } @Override public boolean onOptionsItemSelected(@NonNull MenuItem item) { super.onOptionsItemSelected(item); switch (item.getItemId()) { case android.R.id.home: // API 5+ solution onBackPressed(); return true; case R.id.add_post: break; case R.id.categories: Tool.Dialog(context, "Liste de catégoris", "Liste de catégoris"); break; case R.id.refresh: //getBlog(); LoadPosts(); break; case R.id.contact: Intent i = new Intent(context, Contacts.class); startActivity(i); finish(); break; } return true; } // TODO METHOD private void LoadPosts(){ //Log.i("BLOG_RR ",Config.GET_POST); progress_data.setVisibility(View.VISIBLE); //error404.setVisibility(View.GONE); POSTS.clear(); AndroidNetworking .get(Config.GET_POST) .setPriority(Priority.HIGH) .build() .getAsJSONObject(new JSONObjectRequestListener() { @Override public void onResponse(JSONObject response) { try { JSONArray ar = response.getJSONArray("posts"); for (int i = 0; i < ar.length(); i++) { JSONObject jsonObject = ar.getJSONObject(i); Posts p = new Posts(); p.setId(jsonObject.getString(new Posts().id)); p.setAuthor_id(jsonObject.getString(new Posts().author_id)); p.setCategory_id(jsonObject.getString(new Posts().category_id)); p.setTitle(jsonObject.getString(new Posts().title)); p.setExcerpt(jsonObject.getString(new Posts().excerpt)); p.setBody(jsonObject.getString(new Posts().body)); p.setSlug(jsonObject.getString(new Posts().slug)); p.setStatus(jsonObject.getString(new Posts().status)); p.setCreated_at(jsonObject.getString(new Posts().created_at)); p.setImage(jsonObject.getString(new Posts().image)); p.setCategory(jsonObject.getString(new Posts().category)); p.setComments(jsonObject.getString(new Posts().comments)); POSTS.add(p); } DATAS_CACHED.writeCache(POSTS); if (POSTS.size()<1){ Toast.makeText(context, "Empy", Toast.LENGTH_SHORT).show(); LoadCache(); }else{ adapter = new Adaptor_blog_list(context, POSTS); blog_list.setAdapter(adapter); error404.setVisibility(View.GONE); } progress_data.setVisibility(View.GONE); } catch (Exception e) { Log.e("BLOG_RR--XX ",e.getMessage()); e.printStackTrace(); LoadCache(); } } @Override public void onError(ANError anError) { progress_data.setVisibility(View.GONE); Log.e("BLOG_RR nnn",anError.getMessage()); //error404.setVisibility(View.VISIBLE); LoadCache(); } }); } private void LoadCache() { progress_data.setVisibility(View.VISIBLE); try { if (DATAS_CACHED.getSize()<1){ Toast.makeText(context, "Empy from cache", Toast.LENGTH_SHORT).show(); error404.setVisibility(View.VISIBLE); }else{ adapter = new Adaptor_blog_list(context, DATAS_CACHED.readCache()); blog_list.setAdapter(adapter); //error404.setVisibility(View.GONE); } progress_data.setVisibility(View.GONE); //Log.e("CACHED_DATA", String.valueOf(DATAS_CACHED.readCache().size())); } catch (Exception e) { e.printStackTrace(); error404.setVisibility(View.VISIBLE); } } } <file_sep>/app/src/main/java/cd/digitalEdge/vst/Controllers/Offline/ExecuteUpdate.java package cd.digitalEdge.vst.Controllers.Offline; import android.content.ContentValues; import android.content.Context; import android.database.sqlite.SQLiteDatabase; import android.util.Log; public class ExecuteUpdate { public static long insert(Context context,ContentValues values, String table_name){ try { DataBase mybase = new DataBase(context, DataBase.db_name, null, DataBase.db_version); SQLiteDatabase db = mybase.getWritableDatabase(); long ret = db.insert(table_name,null, values); db.close(); mybase.close(); ////Log.i("INSERT_DONE", String.valueOf(ret)); return 1; }catch (Exception e){ e.printStackTrace(); ////Log.e("INSERT_FAILED", e.toString()); return 0; } } public static long update( Context context, String table_name, String Editcolumn, String value, String colonne_id, String id){ try { DataBase mybase = new DataBase(context, DataBase.db_name, null, DataBase.db_version); SQLiteDatabase db = mybase.getWritableDatabase(); //long ret = db.insertOrThrow(table_name,null, values); db.execSQL("UPDATE "+table_name+" SET "+Editcolumn+" = '"+value+"' WHERE "+colonne_id+" = "+id+";"); db.close(); mybase.close(); //Log.i("UPDATE_DONE", "PASSED"); return 1; }catch (Exception e){ e.printStackTrace(); //Log.e("UPDATE_ERROR", e.toString()); return 0; } } public static long delete(Context context,String table_name,String colonne_id, String id){ try { DataBase mybase = new DataBase(context, DataBase.db_name, null, DataBase.db_version); SQLiteDatabase db = mybase.getWritableDatabase(); //long ret = db.insertOrThrow(table_name,null, values); db.execSQL("DELETE FROM "+table_name+" WHERE "+colonne_id+" = "+id+";"); db.close(); mybase.close(); //Log.i("DELETED", "PASSED"); return 1; }catch (Exception e){ e.printStackTrace(); //Log.e("DELETE_ERROR", e.toString()); return 0; } } public static long Truncat(Context context,String table_name){ try { DataBase mybase = new DataBase(context, DataBase.db_name, null, DataBase.db_version); SQLiteDatabase db = mybase.getWritableDatabase(); //long ret = db.insertOrThrow(table_name,null, values); db.execSQL("DELETE FROM "+table_name+" ;"); db.close(); mybase.close(); //Log.i("TRUNCATED", "PASSED"); return 1; }catch (Exception e){ e.printStackTrace(); //Log.e("TRUNCAT_ERROR", e.toString()); return 0; } } } <file_sep>/app/src/main/java/cd/digitalEdge/vst/Adaptors/Adaptor_favoris_list.java package cd.digitalEdge.vst.Adaptors; import android.content.Context; import android.content.Intent; import android.view.LayoutInflater; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.ImageView; import android.widget.PopupMenu; import android.widget.ProgressBar; import android.widget.TextView; import androidx.cardview.widget.CardView; import com.koushikdutta.ion.Ion; import java.util.ArrayList; import cd.digitalEdge.vst.Controllers.Config; import cd.digitalEdge.vst.Objects.Articles; import cd.digitalEdge.vst.R; import cd.digitalEdge.vst.Tools.Tool; import cd.digitalEdge.vst.Tools.Utils; import cd.digitalEdge.vst.Views.Lists.Details_Article; public class Adaptor_favoris_list extends BaseAdapter { Context context; ArrayList<Articles> FAVORIS; public Adaptor_favoris_list(Context context, ArrayList<Articles> FAVORIS) { this.context = context; this.FAVORIS = FAVORIS; } public int getCount() { return FAVORIS.size(); } public Object getItem(int position) { return FAVORIS.get(position); } public long getItemId(int position) { return 0; } public View getView(int position, View convertView, ViewGroup parent) { View convertView2 = LayoutInflater.from(this.context).inflate(R.layout.model_favoris_list, null); CardView CARD = convertView2.findViewById(R.id.card); TextView title = convertView2.findViewById(R.id.title); TextView descripion = convertView2.findViewById(R.id.descripion); ImageView delete = convertView2.findViewById(R.id.delete); ImageView image = convertView2.findViewById(R.id.image); ProgressBar progress = convertView2.findViewById(R.id.progress); progress.setVisibility(View.GONE); Articles data = FAVORIS.get(position); title.setText(data.getName()); descripion.setText(data.getPrice().concat(" USD")); String a =data.getImages().substring(1, data.getImages().length()-1); String[] imgs = a.split(","); String url = Config.ROOT_img.concat(imgs[0].substring(1,imgs[0].length()-1)); Adaptor_recherche_list.loadImageBitmap(image,url, progress); //Tool.Load_Image2(context, image, url); /*Ion.with(context) .load(url) .withBitmap() .placeholder(R.drawable.unknow) .error(R.drawable.ic_client_blue) //.animateLoad(spinAnimation) //.animateIn(fadeInAnimation) .intoImageView(image);*/ CARD.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent i = new Intent(context, Details_Article.class); i.putExtra("Article", data); i.putExtra("source", "favoris"); context.startActivity(i); } }); delete.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { } }); return convertView2; } } <file_sep>/app/src/main/java/cd/digitalEdge/vst/Controllers/Config_preferences.java package cd.digitalEdge.vst.Controllers; public class Config_preferences { public static String DEVISE = "DEVISE"; public static String LAT = "LAT"; public static String LONG = "LONG"; public static String PAIEMENT_MODE = "PAIEMENT_MODE"; public static String PRICE = "PRICE"; public static String TAUX = "TAUX"; public static String table_name = "chats"; public static String CURRENT_USER = "currentUser"; } <file_sep>/app/src/main/java/cd/digitalEdge/vst/Views/Paramettres.java package cd.digitalEdge.vst.Views; import androidx.annotation.NonNull; import androidx.appcompat.app.AppCompatActivity; import android.content.Context; import android.content.Intent; import android.os.Bundle; import android.view.MenuItem; import android.view.View; import android.widget.TextView; import android.widget.Toast; import com.kosalgeek.android.caching.FileCacher; import java.io.IOException; import java.util.ArrayList; import cd.digitalEdge.vst.Controllers.Offline.ExecuteUpdate; import cd.digitalEdge.vst.MainActivity; import cd.digitalEdge.vst.Objects.Articles; import cd.digitalEdge.vst.R; import cd.digitalEdge.vst.Tools.Constants; import cd.digitalEdge.vst.Views.Blanks.Contacts; public class Paramettres extends AppCompatActivity { Context context = this; TextView clearCache,clearPanier, contact_us,about,profil; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_paramettres); getSupportActionBar().setTitle("Paramettres"); getSupportActionBar().setDisplayHomeAsUpEnabled(true); INIT_COMPONENT(); } private void INIT_COMPONENT() { clearCache = findViewById(R.id.clearCache); clearPanier = findViewById(R.id.clearPanier); contact_us = findViewById(R.id.contact_us); about = findViewById(R.id.about); profil = findViewById(R.id.profil); } @Override protected void onResume() { super.onResume(); clearCache.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { FileCacher<ArrayList<Articles>> data = new FileCacher<>(context, Constants.FILE_PRODUCTS); try { if (data.clearCache() == true) Toast.makeText(context, "Cache vidé", Toast.LENGTH_SHORT).show(); else Toast.makeText(context, "Cache non vidé", Toast.LENGTH_SHORT).show(); } catch (IOException e) { e.printStackTrace(); } } }); clearPanier.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (ExecuteUpdate.Truncat(context, Constants.ARTICLE) == 1) Toast.makeText(context, "Panier vidé", Toast.LENGTH_SHORT).show(); else Toast.makeText(context, "Panier Non vidé", Toast.LENGTH_SHORT).show(); } }); contact_us.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent i = new Intent(context, Contacts.class); startActivity(i); finish(); } }); about.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent i = new Intent(context, About_app.class); startActivity(i); finish(); } }); profil.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent i = new Intent(context, Gerer.class); startActivity(i); finish(); } }); } @Override public boolean onOptionsItemSelected(@NonNull MenuItem item) { super.onOptionsItemSelected(item); switch (item.getItemId()) { case android.R.id.home: // API 5+ solution onBackPressed(); return true; } return true; } @Override public void onBackPressed() { //String source = getIntent().getExtras().getString("source"); Intent i = new Intent(context, MainActivity.class); startActivity(i); finish(); } } <file_sep>/app/src/main/java/cd/digitalEdge/vst/Adaptors/Adaptor_recherche_list.java package cd.digitalEdge.vst.Adaptors; import android.content.Context; import android.content.Intent; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.net.Uri; import android.os.AsyncTask; import android.util.Log; import android.view.LayoutInflater; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.ImageView; import android.widget.PopupMenu; import android.widget.ProgressBar; import android.widget.TextView; import android.widget.Toast; import androidx.cardview.widget.CardView; import com.bumptech.glide.Glide; import com.google.android.material.floatingactionbutton.FloatingActionButton; import com.koushikdutta.ion.Ion; import java.io.IOException; import java.net.URL; import java.util.ArrayList; import java.util.Random; import cd.digitalEdge.vst.Controllers.Config; import cd.digitalEdge.vst.Controllers.Offline.SQLite.Sqlite_updates_methods; import cd.digitalEdge.vst.Objects.Articles; import cd.digitalEdge.vst.Objects.Products; import cd.digitalEdge.vst.Objects.Products; import cd.digitalEdge.vst.R; import cd.digitalEdge.vst.Tools.Utils; import cd.digitalEdge.vst.Views.Lists.Details_Article; public class Adaptor_recherche_list extends BaseAdapter { Context context; ArrayList<Articles> DATAS; public Adaptor_recherche_list(Context context, ArrayList<Articles> DATAS) { this.context = context; this.DATAS = DATAS; } public int getCount() { return DATAS.size(); } public Object getItem(int position) { return DATAS.get(position); } public long getItemId(int position) { return 0; } public View getView(int position, View convertView, ViewGroup parent) { View convertView2 = LayoutInflater.from(this.context).inflate(R.layout.model_articles_list2, null); CardView CARD = convertView2.findViewById(R.id.CARD); TextView name = convertView2.findViewById(R.id.name); TextView price = convertView2.findViewById(R.id.price); ImageView more = convertView2.findViewById(R.id.more); ImageView like = convertView2.findViewById(R.id.like); ImageView img = convertView2.findViewById(R.id.img); ProgressBar progress = convertView2.findViewById(R.id.progress); FloatingActionButton addToCard = convertView2.findViewById(R.id.addToCard); progress.setVisibility(View.GONE); final int[] turn = {0}; Articles data = DATAS.get(position); name.setText(data.getName()); price.setText(data.getPrice().concat(" USD")); String a =data.getImages().substring(1, data.getImages().length()-1); String[] imgs = a.split(","); String url = Config.ROOT_img.concat(imgs[0].substring(1,imgs[0].length()-1)); //Log.e("TAG_IMAGE", url); loadImageBitmap(img, url, progress); /*Glide.with(context) .load(Uri.parse(url)) .centerCrop() .placeholder(R.drawable.unknow) .into(img);*/ CARD.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent i = new Intent(context, Details_Article.class); i.putExtra("Article", data); context.startActivity(i); } }); like.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (turn[0] == 0) { like.setImageResource(R.drawable.ic_favorite); turn[0] =1; } else { like.setImageResource(R.drawable.ic_favortie_orange); turn[0] =0; } } }); addToCard.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { AddToCard(context,data); } }); more.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { PopupMenu popupMenu = new PopupMenu(context, v); popupMenu.getMenu().add("Ajouter à mon panier").setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() { @Override public boolean onMenuItemClick(MenuItem item) { AddToCard(context,data); return false; } }); popupMenu.getMenu().add("Ajouter aux favoris").setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() { @Override public boolean onMenuItemClick(MenuItem item) { new Utils().SaveToFavoris(context, data.getId()); return false; } }); popupMenu.getMenu().add("Ajouter un avis").setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() { @Override public boolean onMenuItemClick(MenuItem item) { new Utils().Noter_article(context, data.getId()); return false; } }); popupMenu.show(); } }); return convertView2; } public static void AddToCard(Context context,Articles data){ data.setQnt("1"); long response = Sqlite_updates_methods.insert_PRODUCT(context, data); if (response == 1){ Toast.makeText(context, "Added to card", Toast.LENGTH_SHORT).show(); } else if(response == 2) Toast.makeText(context, "L'article se trouve déjà dans votre panier", Toast.LENGTH_SHORT).show(); else Toast.makeText(context, "Error while adding", Toast.LENGTH_SHORT).show(); } public static void loadImageBitmap(ImageView img, String path, ProgressBar progress){ new AsyncTask() { @Override protected void onPreExecute() { super.onPreExecute(); progress.setVisibility(View.VISIBLE); } @Override protected Bitmap doInBackground(Object[] objects) { Bitmap bmp = null; try { //URL url = new URL("https://lesupreme.shop/storage/users/November2019/MgMgAthaK3NIDNomVAxM.jpg"); URL url = new URL(path); bmp = BitmapFactory.decodeStream(url.openConnection().getInputStream()); } catch (IOException e) { e.printStackTrace(); } return bmp; } @Override protected void onPostExecute(Object o) { super.onPostExecute(o); img.setImageBitmap((Bitmap) o); progress.setVisibility(View.GONE); } }.execute(); } } <file_sep>/app/src/main/java/cd/digitalEdge/vst/Views/Blanks/Add_product.java package cd.digitalEdge.vst.Views.Blanks; import androidx.annotation.NonNull; import androidx.appcompat.app.AppCompatActivity; import androidx.cardview.widget.CardView; import java.io.ByteArrayOutputStream; import java.io.DataOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.URI; import java.net.URL; import java.util.ArrayList; import java.util.Iterator; import android.app.Activity; import android.content.Context; import android.content.Intent; import android.graphics.Color; import android.net.Uri; import android.os.AsyncTask; import android.os.Bundle; import android.text.TextUtils; import android.util.Base64; import android.util.Log; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.EditText; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.ProgressBar; import android.widget.Spinner; import android.widget.TextView; import android.widget.Toast; import com.androidnetworking.AndroidNetworking; import com.androidnetworking.common.Priority; import com.androidnetworking.error.ANError; import com.androidnetworking.interfaces.JSONObjectRequestListener; import com.androidnetworking.interfaces.StringRequestListener; import com.androidnetworking.interfaces.UploadProgressListener; import com.google.android.material.snackbar.Snackbar; import com.google.gson.JsonArray; import com.koushikdutta.async.http.body.MultipartFormDataBody; import com.theartofdev.edmodo.cropper.CropImage; import com.theartofdev.edmodo.cropper.CropImageView; import org.json.JSONException; import org.json.JSONObject; import java.util.ArrayList; import cd.digitalEdge.vst.Controllers.Config; import cd.digitalEdge.vst.Controllers.Offline.SQLite.Sqlite_selects_methods; import cd.digitalEdge.vst.Objects.Articles; import cd.digitalEdge.vst.Objects.Categories; import cd.digitalEdge.vst.Objects.Colors; import cd.digitalEdge.vst.Objects.Etats; import cd.digitalEdge.vst.Objects.Users; import cd.digitalEdge.vst.R; import cd.digitalEdge.vst.Tools.FilePath; import cd.digitalEdge.vst.Tools.Preferences; import cd.digitalEdge.vst.Tools.Tool; import cd.digitalEdge.vst.Views.Gerer; import cd.digitalEdge.vst.Views.Lists.Details_Article; import okhttp3.internal.http.HttpHeaders; public class Add_product extends AppCompatActivity { Context context = this; ArrayList<Categories> CAT; ArrayList<String> pictureChoosen = new ArrayList<>(); ArrayList<String> pictureChoosen64 = new ArrayList<>(); ArrayList<String> Colors = new ArrayList<>(); ArrayList<String> Colors_id = new ArrayList<>(); ArrayList<String> Categorie_id = new ArrayList<>(); ArrayList<Colors> DATA_CHOOSEN = new ArrayList<>(); Spinner couleur,etat,categories; TextView BTN_pickpicture,BTN_addColor, BTN_save; EditText nom, motcle,qnt,descripion,phone,siteweb,email,prix; ImageView img1,img2,img3,img4,img5; LinearLayout sous_color; ProgressBar progress; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_add_client); getSupportActionBar().setDisplayHomeAsUpEnabled(true); getSupportActionBar().setTitle("Nouveau bien"); INIT_COMPONENT(); } private void INIT_COMPONENT(){ categories = findViewById(R.id.categories); couleur = findViewById(R.id.couleur); etat = findViewById(R.id.etat); img1 = findViewById(R.id.img1); img2 = findViewById(R.id.img2); img3 = findViewById(R.id.img3); img4 = findViewById(R.id.img4); img5 = findViewById(R.id.img5); prix = findViewById(R.id.prix); email = findViewById(R.id.email); siteweb = findViewById(R.id.siteweb); phone = findViewById(R.id.phone); qnt = findViewById(R.id.qnt); nom = findViewById(R.id.nom); motcle = findViewById(R.id.motcle); descripion = findViewById(R.id.descripion); sous_color = findViewById(R.id.sous_color); BTN_save = findViewById(R.id.BTN_save); BTN_addColor = findViewById(R.id.BTN_addColor); BTN_pickpicture = findViewById(R.id.BTN_pickpicture); progress = findViewById(R.id.progress); progress.setVisibility(View.GONE); img1.setVisibility(View.GONE); img2.setVisibility(View.GONE); img3.setVisibility(View.GONE); img4.setVisibility(View.GONE); img5.setVisibility(View.GONE); setEntries(); } boolean CheckZone(){ if (TextUtils.isEmpty(nom.getText().toString())){ nom.setError("Champ obligatoire"); return false; }else if (TextUtils.isEmpty(motcle.getText().toString())){ motcle.setError("Champ obligatoire"); return false; }else if (TextUtils.isEmpty(qnt.getText().toString())){ qnt.setError("Champ obligatoire"); return false; }else if (TextUtils.isEmpty(descripion.getText().toString())){ descripion.setError("Champ obligatoire"); return false; }else if (TextUtils.isEmpty(prix.getText().toString())){ prix.setError("Champ obligatoire"); return false; }else return true; } private void setEntries(){ CAT = Sqlite_selects_methods.getall_Categorie(context); if (null == CAT || CAT.isEmpty()) CAT = new ArrayList<>(); ArrayList<String> DATA0 = new ArrayList<>(); for (Categories c: CAT) { DATA0.add(c.getName()); } Tool.setEntries(context,categories,DATA0); ArrayList<Colors> COLORS = Sqlite_selects_methods.getall_Colors(context); if (null == COLORS || COLORS.isEmpty()) COLORS = new ArrayList<>(); ArrayList<String> DATA = new ArrayList<>(); for (Colors c: COLORS) { DATA.add(c.getName()); } Tool.setEntries(context,couleur,DATA); ArrayList<Etats> ETAT = Sqlite_selects_methods.getall_Etat(context); if (null == ETAT || ETAT.isEmpty()) { ETAT = new ArrayList<>(); Toast.makeText(context, "ETAT vide ou null", Toast.LENGTH_SHORT).show(); } ArrayList<String> DATA2 = new ArrayList<>(); for (Etats etats: ETAT) { DATA2.add(etats.getName()); } Tool.setEntries(context,etat,DATA2); } @Override protected void onResume() { super.onResume(); BTN_save.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { try { //if (CheckZone() == false) return; for (Colors c :DATA_CHOOSEN) { Colors_id.add(c.getId()); } for (Categories c :CAT) { if (c.getName().equals(categories.getSelectedItem().toString())){ Categorie_id.add(c.getId()); break; } } JSONObject object = new JSONObject(); object.put("user_id", Preferences.getCurrentUser(context).getId()); object.put("name",nom.getText().toString()); object.put("keyword",motcle.getText().toString()); object.put("quantity",qnt.getText().toString()); object.put("phone",phone.getText().toString()); object.put("description",descripion.getText().toString()); object.put("website",siteweb.getText().toString()); object.put("email",email.getText().toString()); object.put("price",prix.getText().toString()); object.put("img",pictureChoosen64); object.put("colors",Colors_id); object.put("state",etat.getSelectedItem().toString()); object.put("category",Categorie_id); Log.e("responce_Object",object.toString()); progress.setVisibility(View.VISIBLE); AndroidNetworking .post(Config.SEND_IMG) .addBodyParameter("product", object.toString()) .setPriority(Priority.HIGH) .build() .getAsString(new StringRequestListener() { @Override public void onResponse(String response) { Log.i("responce_app ", response.toString()); progress.setVisibility(View.GONE); } @Override public void onError(ANError anError) { progress.setVisibility(View.GONE); Log.e("responce_app",anError.getMessage()); } }); } catch (Exception e) { e.printStackTrace(); Log.e("responce_app--SSSSSSXX ",e.getMessage()); } } }); BTN_pickpicture.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { pickPicture(); } }); BTN_addColor.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { addColor_to_Panel(couleur.getSelectedItem().toString()); } }); } void upload(String path){ String uploadUrl = Config.SEND_IMG; Log.d("responce_app",path); URL url = null; File file = null; try { url = new URL(uploadUrl); URI u = new URI(path); file = new File(path); if(file.createNewFile()){ file.createNewFile(); }else{ Log.e("responce_app","errrrrrrrr"); } AndroidNetworking.upload(uploadUrl) .addMultipartFile("image", file) .addMultipartParameter("key","value") .setTag("uploadTest") .setPriority(Priority.HIGH) .build() .setUploadProgressListener(new UploadProgressListener() { @Override public void onProgress(long bytesUploaded, long totalBytes) { // do anything with progress //Log.d("responce_app",String.valueOf(bytesUploaded)); } }) .getAsJSONObject(new JSONObjectRequestListener() { @Override public void onResponse(JSONObject response) { // do anything with response Log.d("responce_app",String.valueOf(response)); } @Override public void onError(ANError error) { // handle error Log.e("responce_app",String.valueOf(error.getMessage())); Log.e("responce_app","errorrrr"); } }); } catch (Exception e) { e.printStackTrace(); Log.e("responce_app",e.getMessage()); } } @Override public void onBackPressed() { Intent i = new Intent(context, Gerer.class); startActivity(i); finish(); } @Override public boolean onCreateOptionsMenu(Menu menu) { super.onCreateOptionsMenu(menu); getMenuInflater().inflate(R.menu.add_client_menu, menu); return true; } @Override public boolean onOptionsItemSelected(@NonNull MenuItem item) { super.onOptionsItemSelected(item); switch (item.getItemId()) { case R.id.add_client_done : break; case android.R.id.home: // API 5+ solution onBackPressed(); break; } return true; } private void addColor_to_Panel(String color){ ArrayList<Colors> DATA = Sqlite_selects_methods.getall_Colors(context); View convertView = LayoutInflater.from(context).inflate(R.layout.view_color_in_form, null); TextView counter_badge = convertView.findViewById(R.id.counter_badge); for (Colors data : DATA) { if (data.getName().equals(color)){ counter_badge.setText(data.getName()); counter_badge.setBackgroundColor(Color.parseColor(data.getCodage_rvb())); DATA_CHOOSEN.add(data); sous_color.addView(convertView, 0); } } } private void setimage(){ if (pictureChoosen.get(0) != null){ img1.setVisibility(View.VISIBLE); img1.setImageURI(Uri.parse(pictureChoosen.get(0))); } if (pictureChoosen.get(1) != null){ img2.setVisibility(View.VISIBLE); img2.setImageURI(Uri.parse(pictureChoosen.get(1))); } if (pictureChoosen.get(2) != null){ img3.setVisibility(View.VISIBLE); img3.setImageURI(Uri.parse(pictureChoosen.get(2))); } if (pictureChoosen.get(3) != null){ img4.setVisibility(View.VISIBLE); img4.setImageURI(Uri.parse(pictureChoosen.get(3))); } if (pictureChoosen.get(4) != null){ img5.setVisibility(View.VISIBLE); img5.setImageURI(Uri.parse(pictureChoosen.get(4))); } } // TODO ; PICTURES PICKER private void pickPicture() { CropImage.startPickImageActivity((Activity) context); } /* access modifiers changed from: 0000 */ public void cropRequest(Uri imageuri) { CropImage.activity(imageuri) .setMultiTouchEnabled(false) .setAspectRatio(1, 1) .setFixAspectRatio(true) .setInitialCropWindowPaddingRatio(0.0f) .setGuidelines(CropImageView.Guidelines.ON) .setMultiTouchEnabled(true) .setActivityTitle("Suprême Crop") .start(Add_product.this); } /* access modifiers changed from: protected */ public void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if (requestCode == 200 && resultCode == -1) { cropRequest(CropImage.getPickImageResultUri(this.context, data)); } if (requestCode == 203) { CropImage.ActivityResult result = CropImage.getActivityResult(data); if (resultCode == -1) { try { String fil = FilePath.getPath(this, result.getUri()); FileInputStream fs = new FileInputStream(fil); byte[] imgbyte = new byte[fs.available()]; int i = fs.read(imgbyte); // TODO ; Conversion en base64 String encodedImage = Base64.encodeToString(imgbyte, Base64.DEFAULT); //Log.e("responce_app",encodedImage); pictureChoosen64.add(encodedImage); pictureChoosen.add(fil); setimage(); //UploadFileMethod(fil, this.progressbar, new File(fil).getName()); } catch (Exception e) { //Log.e("responce_app",e.getMessage()); //Tool.Dialog(this.context, "URI Error", e.getMessage()); } } } } public void UploadFileMethod(String path, final ProgressBar p, final String filname) { AsyncTask execute = new AsyncTask() { /* access modifiers changed from: protected */ public void onPreExecute() { p.setVisibility(View.VISIBLE); super.onPreExecute(); } /* access modifiers changed from: protected */ public Object doInBackground(Object[] params) { return Integer.valueOf(uploadFile(params[0].toString())); } /* access modifiers changed from: protected */ public void onPostExecute(Object oO) { if (((Integer) oO).intValue() >= 0) { Users u = new Users(); u.setId(Tool.getUserPreferences(context, new Users().id)); u.setAvatar(filname); /*String query = Updates_queries.update_avatar_query(u); Log.i("TAG_UPDATE_QUERY", query); String o = new Updates().APPLY_UPDATE(context, query, progressbar); if (o.length() > 5 || o.equals("-1") || o.contains("<")) { Tool.Dialog(context, "Info", "Erreur lors de l'enregistrement.\nVeuillez vérifier les informations saisies ou soit votre connexion internet"); } else { Tool.setUserPreferences(context, new Users().avatar, u.getAvatar()); settingUp_profil(); Toast.makeText(context, "Le photo de profil a été modifié avec succes", Toast.LENGTH_LONG).show(); }*/ Toast.makeText(context, "Effectué", Toast.LENGTH_LONG).show(); } else { Toast.makeText(context, "Echec du chargement du upload", Toast.LENGTH_LONG).show(); } p.setVisibility(View.GONE); super.onPostExecute(oO); } }.execute(new Object[]{path}); } public int uploadFile(String selectedFilePath) { int maxBufferSize; DataOutputStream dataOutputStream; byte[] buffer; String serverResponseMessage; StringBuilder sb; int bytesAvailable; String str = selectedFilePath; String str2 = "UPLOAD"; String str3 = "DATA not passed"; String lineEnd = "\r\n"; String twoHyphens = "--"; String boundary = "*****"; int maxBufferSize2 = 1048576; File selectedFile = new File(str); String[] parts = str.split("/"); String str4 = parts[parts.length - 1]; if (!selectedFile.isFile()) { runOnUiThread(new Runnable() { public void run() { } }); return 0; } try { FileInputStream fileInputStream = new FileInputStream(selectedFile); URL url = new URL(Config.SEND_IMG); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setDoInput(true); connection.setDoOutput(true); connection.setUseCaches(false); connection.setRequestMethod("POST"); connection.setRequestProperty("Connection", "Keep-Alive"); connection.setRequestProperty("ENCTYPE", MultipartFormDataBody.CONTENT_TYPE); String str5 = "Content-Type"; StringBuilder sb3 = new StringBuilder(); File file = selectedFile; try { sb3.append("multipart/form-data;boundary="); sb3.append(boundary); connection.setRequestProperty(str5, sb3.toString()); connection.setRequestProperty("uploaded_file", str); dataOutputStream = new DataOutputStream(connection.getOutputStream()); StringBuilder sb4 = new StringBuilder(); sb4.append(twoHyphens); sb4.append(boundary); sb4.append(lineEnd); dataOutputStream.writeBytes(sb4.toString()); StringBuilder sb5 = new StringBuilder(); sb5.append("Content-Disposition: form-data; name=\"uploaded_file\";filename=\""); sb5.append(str); sb5.append("\""); sb5.append(lineEnd); dataOutputStream.writeBytes(sb5.toString()); dataOutputStream.writeBytes(lineEnd); InputStream inn = connection.getInputStream(); Log.e("responce_app", inn.toString()); Log.e(str2, "DATA passed ON DATAOUTPUTSTREAM"); int bytesAvailable2 = fileInputStream.available(); int bufferSize = Math.min(bytesAvailable2, 1048576); buffer = new byte[bufferSize]; int i = bytesAvailable2; int bufferSize2 = bufferSize; int bytesRead = fileInputStream.read(buffer, 0, bufferSize); while (bytesRead > 0) { String[] parts2 = parts; try { dataOutputStream.write(buffer, 0, bufferSize2); bytesAvailable = fileInputStream.available(); bufferSize2 = Math.min(bytesAvailable, maxBufferSize2); } catch (FileNotFoundException e) { e = e; int i2 = maxBufferSize2; String str6 = lineEnd; maxBufferSize = 0; e.printStackTrace(); runOnUiThread(new Runnable() { public void run() { Toast.makeText(getApplicationContext(), "File Not Found", Toast.LENGTH_LONG).show(); } }); Log.e("UPLOAD1", str3); return maxBufferSize; } catch (Exception e) { int i3 = maxBufferSize2; String str7 = lineEnd; maxBufferSize = 0; e.printStackTrace(); Log.e("UPLOAD2", str3); return maxBufferSize; } try { bytesRead = fileInputStream.read(buffer, 0, bufferSize2); int i5 = bytesAvailable; parts = parts2; maxBufferSize2 = maxBufferSize2; } catch (FileNotFoundException e4) { String str9 = lineEnd; maxBufferSize = 0; e4.printStackTrace(); runOnUiThread(new Runnable() { public void run() { Toast.makeText(getApplicationContext(), "File Not Found", Toast.LENGTH_LONG).show(); } }); Log.e("UPLOAD1", str3); return maxBufferSize; } catch (MalformedURLException e5) { String str10 = lineEnd; maxBufferSize = 0; e5.printStackTrace(); Log.e("UPLOAD2", str3); return maxBufferSize; } catch (IOException e6) { String str11 = lineEnd; maxBufferSize = 0; e6.printStackTrace(); Log.e("UPLOAD3", str3); return maxBufferSize; } } String[] strArr = parts; } catch (FileNotFoundException e7) { String str12 = lineEnd; String[] strArr2 = parts; maxBufferSize = 0; e7.printStackTrace(); runOnUiThread(new Runnable() { public void run() { Toast.makeText(getApplicationContext(), "File Not Found", Toast.LENGTH_LONG).show(); } }); Log.e("UPLOAD1", str3); return maxBufferSize; } catch (MalformedURLException e8) { String str13 = lineEnd; String[] strArr3 = parts; maxBufferSize = 0; e8.printStackTrace(); Log.e("UPLOAD2", str3); return maxBufferSize; } catch (IOException e9) { String str14 = lineEnd; String[] strArr4 = parts; maxBufferSize = 0; e9.printStackTrace(); Log.e("UPLOAD3", str3); return maxBufferSize; } try { dataOutputStream.writeBytes(lineEnd); StringBuilder sb6 = new StringBuilder(); sb6.append(twoHyphens); sb6.append(boundary); sb6.append(twoHyphens); sb6.append(lineEnd); dataOutputStream.writeBytes(sb6.toString()); maxBufferSize = connection.getResponseCode(); } catch (FileNotFoundException e10) { String str15 = lineEnd; maxBufferSize = 0; e10.printStackTrace(); runOnUiThread(new Runnable() { public void run() { Toast.makeText(getApplicationContext(), "File Not Found", Toast.LENGTH_LONG).show(); } }); Log.e("UPLOAD1", str3); return maxBufferSize; } catch (MalformedURLException e11) { String str16 = lineEnd; maxBufferSize = 0; e11.printStackTrace(); Log.e("UPLOAD2", str3); return maxBufferSize; } catch (IOException e12) { String str17 = lineEnd; maxBufferSize = 0; e12.printStackTrace(); Log.e("UPLOAD3", str3); return maxBufferSize; } try { serverResponseMessage = connection.getResponseMessage(); byte[] bArr = buffer; sb = new StringBuilder(); String str18 = lineEnd; } catch (FileNotFoundException e13) { String str19 = lineEnd; e13.printStackTrace(); runOnUiThread(new Runnable() { public void run() { Toast.makeText(getApplicationContext(), "File Not Found", Toast.LENGTH_LONG).show(); } }); Log.e("UPLOAD1", str3); return maxBufferSize; } catch (MalformedURLException e14) { String str20 = lineEnd; e14.printStackTrace(); Log.e("UPLOAD2", str3); return maxBufferSize; } catch (IOException e15) { String str21 = lineEnd; e15.printStackTrace(); Log.e("UPLOAD3", str3); return maxBufferSize; } try { sb.append("Server Response is: "); sb.append(serverResponseMessage); sb.append(": "); sb.append(maxBufferSize); Log.e(str2, sb.toString()); if (maxBufferSize == 200) { runOnUiThread(new Runnable() { public void run() { } }); } fileInputStream.close(); dataOutputStream.flush(); dataOutputStream.close(); } catch (FileNotFoundException e16) { e16.printStackTrace(); runOnUiThread(new Runnable() { public void run() { Toast.makeText(getApplicationContext(), "File Not Found", Toast.LENGTH_LONG).show(); } }); Log.e("UPLOAD1", str3); return maxBufferSize; } catch (MalformedURLException e17) { e17.printStackTrace(); Log.e("UPLOAD2", str3); return maxBufferSize; } catch (IOException e18) { e18.printStackTrace(); Log.e("UPLOAD3", str3); return maxBufferSize; } } catch (FileNotFoundException e22) { String str25 = lineEnd; File file5 = selectedFile; String[] strArr8 = parts; maxBufferSize = 0; e22.printStackTrace(); runOnUiThread(new Runnable() { public void run() { Toast.makeText(getApplicationContext(), "File Not Found", Toast.LENGTH_LONG).show(); } }); Log.e("UPLOAD1", str3); return maxBufferSize; } catch (MalformedURLException e23) { String str26 = lineEnd; File file6 = selectedFile; String[] strArr9 = parts; maxBufferSize = 0; e23.printStackTrace(); Log.e("UPLOAD2", str3); return maxBufferSize; } catch (IOException e24) { String str27 = lineEnd; File file7 = selectedFile; String[] strArr10 = parts; maxBufferSize = 0; e24.printStackTrace(); Log.e("UPLOAD3", str3); return maxBufferSize; } return maxBufferSize; } public class Color_product{ public String id ="id"; public String name ="name"; public String getId() { return id; } public void setId(String id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } } } <file_sep>/app/src/main/java/cd/digitalEdge/vst/Controllers/Background/MyLocationListener.java package cd.digitalEdge.vst.Controllers.Background; import android.content.Context; import android.location.Location; import android.location.LocationListener; import android.os.Bundle; import android.util.Log; import android.widget.Toast; public class MyLocationListener implements LocationListener { Context context; public MyLocationListener(Context context2) { this.context = context2; } public void onLocationChanged(Location loc) { Context context2 = this.context; StringBuilder sb = new StringBuilder(); sb.append("Location changed: Lat: "); sb.append(loc.getLatitude()); sb.append(" Lng: "); sb.append(loc.getLongitude()); Toast.makeText(context2, sb.toString(), Toast.LENGTH_LONG).show(); StringBuilder sb2 = new StringBuilder(); sb2.append("Longitude: "); sb2.append(loc.getLongitude()); String str = "LOCATION_TAG"; Log.v(str, sb2.toString()); StringBuilder sb3 = new StringBuilder(); sb3.append("Latitude: "); sb3.append(loc.getLatitude()); Log.v(str, sb3.toString()); } @Override public void onStatusChanged(String provider, int status, Bundle extras) { } @Override public void onProviderEnabled(String provider) { } @Override public void onProviderDisabled(String provider) { } } <file_sep>/app/src/main/java/cd/digitalEdge/vst/Adaptors/Slides/SlideAdapter_home.java package cd.digitalEdge.vst.Adaptors.Slides; import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.ProgressBar; import android.widget.RelativeLayout; import android.widget.TextView; import androidx.viewpager.widget.PagerAdapter; import cd.digitalEdge.vst.Adaptors.Adaptor_recherche_list; import cd.digitalEdge.vst.Controllers.Config; import cd.digitalEdge.vst.R; public class SlideAdapter_home extends PagerAdapter { public int[] list_color = {R.color.colorPrimary, R.color.colorPrimary, R.color.colorPrimary, R.color.colorPrimary}; public String[] list_description = { "", "", "", ""}; //public int[] list_images = {R.drawable.png, R.drawable.png, R.drawable.png, R.drawable.png}; public String[] list_title = {"", "", "", ""}; public String[] list_images = {"", "", "", ""}; Context context; LayoutInflater inflater; public SlideAdapter_home(Context context2, String[] imgs) { this.context = context2; list_images = imgs; //String url = Config.ROOT_img.concat(imgs[0].substring(1,imgs[0].length()-1)); } public int getCount() { return this.list_title.length; } public boolean isViewFromObject(View view, Object obj) { return view == ((RelativeLayout) obj); } public Object instantiateItem(ViewGroup container, int position) { this.inflater = (LayoutInflater) this.context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); View view = this.inflater.inflate(R.layout.intro_slide, container, false); RelativeLayout linearLayout = (RelativeLayout) view.findViewById(R.id.slidelinearlayout); TextView txt1 = (TextView) view.findViewById(R.id.slidetitle); TextView txt2 = (TextView) view.findViewById(R.id.slidedescription); TextView textView = (TextView) view.findViewById(R.id.start); ImageView img = (ImageView) view.findViewById(R.id.slideimg); ProgressBar progress = (ProgressBar) view.findViewById(R.id.progress); progress.setVisibility(View.GONE); String url = Config.ROOT_img.concat(list_images[position].substring(1,list_images[position].length()-1)); //list_images[position] Adaptor_recherche_list.loadImageBitmap(img, url, progress); //((ImageView) view.findViewById(R.id.slideimg)).setImageResource(this.); txt1.setText(this.list_title[position]); txt2.setText(this.list_description[position]); linearLayout.setBackgroundColor(this.list_color[position]); container.addView(view); return view; } public void destroyItem(ViewGroup container, int position, Object object) { container.removeView((RelativeLayout) object); } } <file_sep>/app/src/main/java/cd/digitalEdge/vst/Objects/Commande.java package cd.digitalEdge.vst.Objects; public class Commande { public String id = "id"; public String date = "date"; public String price = "price"; public String montant = "montant"; public String client = "client"; public String getId() { return id; } public void setId(String id) { this.id = id; } public String getDate() { return date; } public void setDate(String date) { this.date = date; } public String getPrice() { return price; } public void setPrice(String price) { this.price = price; } public String getMontant() { return montant; } public void setMontant(String montant) { this.montant = montant; } public String getClient() { return client; } public void setClient(String client) { this.client = client; } } <file_sep>/app/src/main/java/cd/digitalEdge/vst/Adaptors/Adaptor_message_list.java package cd.digitalEdge.vst.Adaptors; import android.content.Context; import android.content.Intent; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.LinearLayout; import android.widget.TextView; import androidx.cardview.widget.CardView; import java.util.Random; import cd.digitalEdge.vst.R; import cd.digitalEdge.vst.Views.Blanks.Add_product; import cd.digitalEdge.vst.Views.Lists.Chats; import cd.digitalEdge.vst.Views.Lists.Details_Article; public class Adaptor_message_list extends BaseAdapter { Context context; public Adaptor_message_list(Context context) { this.context = context; } public int getCount() { return 20; } public Object getItem(int position) { return null; } public long getItemId(int position) { return 0; } public View getView(int position, View convertView, ViewGroup parent) { View convertView2 = LayoutInflater.from(this.context).inflate(R.layout.model_message_list, null); LinearLayout CARD = convertView2.findViewById(R.id.card); TextView index_letter = convertView2.findViewById(R.id.indx); index_letter.setText("MASSADI".substring(0,1)); int r = new Random().nextInt(4); if (r == 1) index_letter.setBackgroundResource(R.drawable.oval_blue); if (r == 2) index_letter.setBackgroundResource(R.drawable.oval_red); if (r == 3) index_letter.setBackgroundResource(R.drawable.oval_green); if (r == 4) index_letter.setBackgroundResource(R.drawable.oval_gris); CARD.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent i = new Intent(context, Chats.class); context.startActivity(i); } }); return convertView2; } }<file_sep>/settings.gradle rootProject.name='VST' include ':app' <file_sep>/app/src/main/java/cd/digitalEdge/vst/Views/Lists/Panier.java package cd.digitalEdge.vst.Views.Lists; import androidx.annotation.NonNull; import androidx.appcompat.app.AppCompatActivity; import android.content.Context; import android.content.Intent; import android.os.Bundle; import android.os.Handler; import android.util.Log; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.animation.Animation; import android.view.animation.AnimationUtils; import android.widget.LinearLayout; import android.widget.ListView; import android.widget.TextView; import android.widget.Toast; import java.util.ArrayList; import java.util.Timer; import java.util.TimerTask; import cd.digitalEdge.vst.Adaptors.Adaptor_Panier; import cd.digitalEdge.vst.Controllers.Offline.ExecuteUpdate; import cd.digitalEdge.vst.Controllers.Offline.SQLite.Sqlite_selects_methods; import cd.digitalEdge.vst.MainActivity; import cd.digitalEdge.vst.Objects.Articles; import cd.digitalEdge.vst.R; import cd.digitalEdge.vst.Tools.Constants; import cd.digitalEdge.vst.Tools.Utils; import cd.digitalEdge.vst.Views.Blanks.Checkout_command; public class Panier extends AppCompatActivity { Context context = this; ListView panier_list; TextView textCartItemCount, PT,prodcount; LinearLayout progress_data; Adaptor_Panier adapter; ArrayList<Articles> PANIER = new ArrayList<>(); public Handler mHandler = new Handler(); Timer mTimer = null; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_panier); getSupportActionBar().setTitle("Mon Panier"); getSupportActionBar().setDisplayHomeAsUpEnabled(true); INIT_COMPONENTS(); getdatas(); } private void INIT_COMPONENTS() { panier_list = findViewById(R.id.panier_list); prodcount = findViewById(R.id.prodcount); progress_data = findViewById(R.id.progress_data); PT = findViewById(R.id.PT); progress_data.setVisibility(View.GONE); } @Override protected void onDestroy() { super.onDestroy(); this.mTimer.cancel(); } @Override public boolean onCreateOptionsMenu(Menu menu) { super.onCreateOptionsMenu(menu); getMenuInflater().inflate(R.menu.panier_menu, menu); final MenuItem menuItem = menu.findItem(R.id.facturation); View actionView = menuItem.getActionView(); textCartItemCount = (TextView) actionView.findViewById(R.id.cart_badge); Timer timer = this.mTimer; if (timer != null) { timer.cancel(); } else { this.mTimer = new Timer(); } this.mTimer.scheduleAtFixedRate(new TimeDisplay(getApplicationContext(), 0), 0, 100); actionView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { onOptionsItemSelected(menuItem); } }); actionView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { onOptionsItemSelected(menuItem); } }); return true; } public class TimeDisplay extends TimerTask { Context context; int turn = 0; public TimeDisplay(Context context, int turn) { this.context = context; this.turn = turn; } public void run() { mHandler.post(new Runnable() { public void run() { //Log.e("PANIER_SERVICES", "je tourne bien"); PANIER = Sqlite_selects_methods.getall_Articles(context); if ( null == PANIER || PANIER.isEmpty() ){ PANIER = new ArrayList<>(); ////Log.e("DATA", "DATAS "+PANIER.size()); Utils.Setting_badge("0",textCartItemCount); }else Utils.Setting_badge(String.valueOf(PANIER.size()),textCartItemCount); prodcount.setText(String.valueOf(PANIER.size())); int TOT = 0; for (Articles a :PANIER) { TOT += Float.parseFloat(a.getPrice()) * Float.parseFloat(a.getQnt()); } PT.setText(String.valueOf(TOT)+" USD"); } }); } } @Override public boolean onOptionsItemSelected(@NonNull MenuItem item) { super.onOptionsItemSelected(item); switch (item.getItemId()) { case android.R.id.home: // API 5+ solution onBackPressed(); break; case R.id.facturation: Intent i = new Intent(context, Panier.class); startActivity(i); finish(); break; case R.id.commander: getdatas(); if (PANIER.size() < 1 || PANIER.isEmpty()){ Toast.makeText(context, "Le panier est vide, veuillez ajouter des aricles dans le papnier ", Toast.LENGTH_LONG).show(); }else{ Intent ii = new Intent(context, Checkout_command.class); startActivity(ii); finish(); } break; case R.id.refresh: getdatas(); break; case R.id.deleteAll: if (ExecuteUpdate.Truncat(context, Constants.ARTICLE) == 1) Toast.makeText(context, "Panier vidé", Toast.LENGTH_SHORT).show(); else Toast.makeText(context, "Panier Non vidé", Toast.LENGTH_SHORT).show(); getdatas(); break; } return true; } @Override protected void onResume() { super.onResume(); } @Override public void onBackPressed() { //String source = getIntent().getExtras().getString("source"); Intent i = new Intent(context, MainActivity.class); startActivity(i); finish(); } public void getdatas(){ Animation from_right = AnimationUtils.loadAnimation(context, R.anim.m_fromright); Animation to_right = AnimationUtils.loadAnimation(context, R.anim.m_toleft); progress_data.startAnimation(from_right); progress_data.setVisibility(View.VISIBLE); PANIER = Sqlite_selects_methods.getall_Articles(context); if ( null == PANIER || PANIER.isEmpty() ){ PANIER = new ArrayList<>(); Log.e("DATA", "DATAS "+PANIER.size()); } adapter = new Adaptor_Panier(context, PANIER); panier_list.setAdapter(adapter); progress_data.startAnimation(to_right); progress_data.setVisibility(View.GONE); } }<file_sep>/app/src/main/java/cd/digitalEdge/vst/Views/Blanks/Checkout_command.java package cd.digitalEdge.vst.Views.Blanks; import androidx.appcompat.app.AppCompatActivity; import android.app.AlertDialog; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.os.Bundle; import android.view.View; import android.widget.ScrollView; import android.widget.TextView; import java.util.ArrayList; import cd.digitalEdge.vst.Controllers.Offline.SQLite.Sqlite_selects_methods; import cd.digitalEdge.vst.Objects.Articles; import cd.digitalEdge.vst.R; import cd.digitalEdge.vst.Tools.Tool; import cd.digitalEdge.vst.Tools.Utils; import cd.digitalEdge.vst.Views.Lists.Panier; public class Checkout_command extends AppCompatActivity { Context context = this; TextView BTN_btn, prodcount, PT; ScrollView page1, page2; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_checkout_command); getSupportActionBar().setTitle("Checkout"); getSupportActionBar().setDisplayHomeAsUpEnabled(true); INIT_COMPONENT(); } private void INIT_COMPONENT() { page1 = findViewById(R.id.page1); page2 = findViewById(R.id.page2); BTN_btn = findViewById(R.id.BTN_btn); prodcount = findViewById(R.id.prodcount); PT = findViewById(R.id.PT); page2.setVisibility(View.GONE); BTN_btn.setText("Suivant"); ArrayList<Articles> PANIER = new ArrayList<>(); PANIER = Sqlite_selects_methods.getall_Articles(context); prodcount.setText(String.valueOf(PANIER.size())); int TOT = 0; for (Articles a :PANIER) { TOT += Float.parseFloat(a.getPrice()) * Float.parseFloat(a.getQnt()); } PT.setText(String.valueOf(TOT)+" USD"); } @Override protected void onResume() { super.onResume(); BTN_btn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (BTN_btn.getText().toString().equals("Suivant")){ BTN_btn.setText("Commander"); page1.setVisibility(View.GONE); page2.setVisibility(View.VISIBLE); }else if (BTN_btn.getText().toString().equals("Commander")){ new AlertDialog.Builder(context) .setTitle("Notice") .setMessage("Vos données personnelles seront utilisées pour le traitement de votre commande, vous accompagner au cours de votre visite du site web, et pour d’autres raisons décrites dans notre politique de confidentialité.") .setPositiveButton("Oui", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); } }) .setNegativeButton("Non", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); } }).show(); } } }); } @Override public void onBackPressed() { Intent ii = new Intent(context, Panier.class); startActivity(ii); finish(); } } <file_sep>/app/src/main/java/cd/digitalEdge/vst/Views/Lists/Favoris.java package cd.digitalEdge.vst.Views.Lists; import android.content.Context; import android.content.Intent; import android.net.ConnectivityManager; import android.net.NetworkInfo; import android.os.Bundle; import android.util.Log; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.LinearLayout; import android.widget.ListView; import android.widget.Toast; import androidx.annotation.NonNull; import androidx.appcompat.app.AppCompatActivity; import com.androidnetworking.AndroidNetworking; import com.androidnetworking.common.Priority; import com.androidnetworking.error.ANError; import com.androidnetworking.interfaces.JSONObjectRequestListener; import com.kosalgeek.android.caching.FileCacher; import org.json.JSONArray; import org.json.JSONObject; import java.util.ArrayList; import cd.digitalEdge.vst.Adaptors.Adaptor_commands_list; import cd.digitalEdge.vst.Adaptors.Adaptor_favoris_list; import cd.digitalEdge.vst.Controllers.Config; import cd.digitalEdge.vst.Objects.Articles; import cd.digitalEdge.vst.Objects.Articles; import cd.digitalEdge.vst.R; import cd.digitalEdge.vst.Tools.Constants; import cd.digitalEdge.vst.Tools.Preferences; import cd.digitalEdge.vst.Views.Blanks.Add_product; import cd.digitalEdge.vst.Views.Gerer; public class Favoris extends AppCompatActivity { Context context = this; Adaptor_favoris_list adaptor; ListView list_favoris; LinearLayout progress_data, error404; ArrayList<Articles> FAVORIS = new ArrayList<>(); FileCacher<ArrayList<Articles>> DATAS_CACHED = new FileCacher<>(context, Constants.FILE_FAVORIS); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_favoris); getSupportActionBar().setTitle("Mes Favoris"); getSupportActionBar().setDisplayHomeAsUpEnabled(true); INIT_COMPONENT(); //getData(); ConnectivityManager manager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo info = manager.getActiveNetworkInfo(); if (info != null && info.isConnected()) { LoadFavoris(); }else{ LoadCache(); } } private void INIT_COMPONENT() { progress_data = findViewById(R.id.progress_data); list_favoris = findViewById(R.id.list_favoris); error404 = findViewById(R.id.error404); progress_data.setVisibility(View.GONE); error404.setVisibility(View.GONE); } @Override protected void onResume() { super.onResume(); } @Override public void onBackPressed() { Intent i = new Intent(context, Gerer.class); startActivity(i); finish(); } @Override public boolean onOptionsItemSelected(@NonNull MenuItem item) { super.onOptionsItemSelected(item); switch (item.getItemId()) { case android.R.id.home: // API 5+ solution onBackPressed(); return true; } return true; } // TODO METHOD void getData(){ //adaptor = new Adaptor_favoris_list(context); list_favoris.setAdapter(adaptor); } private void LoadFavoris(){ //LoadCache(); Log.i("FAVORIS_DATAS ",Config.GET_FAVORI.concat(Preferences.getCurrentUser(context).getId())); progress_data.setVisibility(View.VISIBLE); //error404.setVisibility(View.GONE); FAVORIS.clear(); AndroidNetworking .get(Config.GET_FAVORI.concat(Preferences.getCurrentUser(context).getId())) .setPriority(Priority.HIGH) .build() .getAsJSONObject(new JSONObjectRequestListener() { @Override public void onResponse(JSONObject response) { try { //JSONArray ar = response.getJSONArray("results"); //Log.e("FAVORIS_DATAS RR ", response.toString()); for (int i = 0; i < response.length(); i++) { JSONObject jsonObject = response.getJSONObject(String.valueOf(i+1)); Articles p = new Articles(); p.setId(jsonObject.getString(new Articles().id)); p.setName(jsonObject.getString(new Articles().name)); p.setSlug(jsonObject.getString(new Articles().slug)); p.setImages(jsonObject.getString(new Articles().images)); p.setDescription(jsonObject.getString(new Articles().description)); p.setPrice(jsonObject.getString(new Articles().price2)); p.setStock(jsonObject.getString(new Articles().stock)); p.setAvailability(jsonObject.getString(new Articles().availability)); FAVORIS.add(p); } DATAS_CACHED.writeCache(FAVORIS); if (FAVORIS.size()<1){ Toast.makeText(context, "Empy", Toast.LENGTH_SHORT).show(); //error404.setVisibility(View.VISIBLE); LoadCache(); }else{ adaptor = new Adaptor_favoris_list(context, FAVORIS); list_favoris.setAdapter(adaptor); //error404.setVisibility(View.GONE); } progress_data.setVisibility(View.GONE); } catch (Exception e) { //Log.e("FAVORIS_DATAS--XX ",e.getMessage()); //error404.setVisibility(View.VISIBLE); LoadCache(); } } @Override public void onError(ANError anError) { progress_data.setVisibility(View.GONE); Log.e("FAVORIS_DATAS ",anError.getMessage()); //error404.setVisibility(View.VISIBLE); LoadCache(); } }); } private void LoadCache() { progress_data.setVisibility(View.VISIBLE); try { if (DATAS_CACHED.getSize()<1){ Toast.makeText(context, "Empy", Toast.LENGTH_SHORT).show(); error404.setVisibility(View.VISIBLE); }else{ adaptor = new Adaptor_favoris_list(context, FAVORIS); list_favoris.setAdapter(adaptor); //error404.setVisibility(View.GONE); } progress_data.setVisibility(View.GONE); //Log.e("CACHED_DATA", String.valueOf(DATAS_CACHED.readCache().size())); } catch (Exception e) { e.printStackTrace(); error404.setVisibility(View.VISIBLE); } } } <file_sep>/app/src/main/java/cd/digitalEdge/vst/Views/Lists/Biens.java package cd.digitalEdge.vst.Views.Lists; import android.content.Context; import android.content.Intent; import android.os.Bundle; import android.util.Log; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.LinearLayout; import android.widget.ListView; import android.widget.Toast; import androidx.annotation.NonNull; import androidx.appcompat.app.AppCompatActivity; import androidx.core.view.GravityCompat; import com.androidnetworking.AndroidNetworking; import com.androidnetworking.common.Priority; import com.androidnetworking.error.ANError; import com.androidnetworking.interfaces.JSONObjectRequestListener; import com.google.android.material.bottomnavigation.BottomNavigationView; import com.google.android.material.tabs.TabItem; import com.google.android.material.tabs.TabLayout; import com.kosalgeek.android.caching.FileCacher; import org.json.JSONArray; import org.json.JSONObject; import java.util.ArrayList; import cd.digitalEdge.vst.Adaptors.Adaptor_biens_list; import cd.digitalEdge.vst.Controllers.Config; import cd.digitalEdge.vst.Objects.Articles; import cd.digitalEdge.vst.R; import cd.digitalEdge.vst.Tools.Constants; import cd.digitalEdge.vst.Tools.Preferences; import cd.digitalEdge.vst.Views.Blanks.Add_product; import cd.digitalEdge.vst.Views.Gerer; public class Biens extends AppCompatActivity { Context context = this; Adaptor_biens_list adaptor; ListView list_goods; TabItem tab_actif, tab_attente,tab_vendu; BottomNavigationView bottomnavigation; LinearLayout progress_data,error404; ArrayList<Articles> DATA_GOODS = new ArrayList<>(); ArrayList<Articles> DATA_VENDU = new ArrayList<>(); ArrayList<Articles> DATA_ATTENTE = new ArrayList<>(); FileCacher<ArrayList<Articles>> DATAS_CACHED = new FileCacher<>(context, Constants.FILE_BIENS); FileCacher<ArrayList<Articles>> DATAS_CACHED_VENDU = new FileCacher<>(context, Constants.FILE_VENDU); FileCacher<ArrayList<Articles>> DATAS_CACHED_ATTENTE = new FileCacher<>(context, Constants.FILE_ATTENTE); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_biens); getSupportActionBar().setTitle("Mes biens | Actifs"); getSupportActionBar().setDisplayHomeAsUpEnabled(true); INIT_COMPONENT(); bottomnavigation.setSelectedItemId(R.id.tab_actif); //getdata(); LoadBiens(); } private void INIT_COMPONENT() { list_goods = findViewById(R.id.list_goods); bottomnavigation = findViewById(R.id.bottomnavigation); progress_data = findViewById(R.id.progress_data); error404 = findViewById(R.id.error404); progress_data.setVisibility(View.GONE); error404.setVisibility(View.GONE); } @Override protected void onResume() { super.onResume(); bottomnavigation.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() { @Override public boolean onNavigationItemSelected(@NonNull MenuItem item) { Intent i = new Intent(context, Recherche.class); switch (item.getItemId()){ case R.id.tab_actif: getSupportActionBar().setTitle("Mes biens | Actifs"); SetDatabyViews(DATA_GOODS); //Toast.makeText(context, "actif", Toast.LENGTH_SHORT).show(); break; case R.id.tab_attente: getSupportActionBar().setTitle("Mes biens | Attente"); SetDatabyViews(DATA_ATTENTE); //Toast.makeText(context, "tab_attente", Toast.LENGTH_SHORT).show(); break; case R.id.tab_vendu: getSupportActionBar().setTitle("Mes biens | Vendus"); SetDatabyViews(DATA_VENDU); //Toast.makeText(context, "tab_vendu", Toast.LENGTH_SHORT).show(); break; } return false; } }); } @Override public boolean onCreateOptionsMenu(Menu menu) { super.onCreateOptionsMenu(menu); getMenuInflater().inflate(R.menu.biens_menu, menu); return true; } @Override public boolean onOptionsItemSelected(@NonNull MenuItem item) { super.onOptionsItemSelected(item); switch (item.getItemId()) { case R.id.add_product: Intent i = new Intent(context, Add_product.class); startActivity(i); finish(); break; case android.R.id.home: // API 5+ solution onBackPressed(); return true; } return true; } @Override public void onBackPressed() { Intent i = new Intent(context, Gerer.class); startActivity(i); finish(); } private void getdata(){ //adaptor = new Adaptor_biens_list(context); list_goods.setAdapter(adaptor); } private void LoadBiens(){ Log.i("GOODS_LINK ",Config.GET_GOODS.concat(Preferences.getCurrentUser(context).getId())); progress_data.setVisibility(View.VISIBLE); //error404.setVisibility(View.GONE); DATA_GOODS.clear(); AndroidNetworking .get(Config.GET_GOODS.concat(Preferences.getCurrentUser(context).getId())) .setPriority(Priority.HIGH) .build() .getAsJSONObject(new JSONObjectRequestListener() { @Override public void onResponse(JSONObject response) { Log.i("GOODS_LINK ",response.toString()); try { JSONArray disponible = response.getJSONArray("disponible"); JSONArray vendus = response.getJSONArray("vendus"); JSONArray en_attente_validation = response.getJSONArray("en_attente_validation"); //Log.e("PRODUCT_DATAS RR ", ar.toString()); for (int i = 0; i < disponible.length(); i++) { JSONObject jsonObject = disponible.getJSONObject(i); Articles p = new Articles(); p.setId(jsonObject.getString(new Articles().id)); p.setName(jsonObject.getString(new Articles().name)); p.setSlug(jsonObject.getString(new Articles().slug)); p.setImages(jsonObject.getString(new Articles().images)); p.setDescription(jsonObject.getString(new Articles().description)); p.setPrice(jsonObject.getString(new Articles().price2)); p.setStock(jsonObject.getString(new Articles().stock)); p.setAvailability(jsonObject.getString(new Articles().availability)); DATA_GOODS.add(p); } DATAS_CACHED.writeCache(DATA_GOODS); for (int i = 0; i < vendus.length(); i++) { JSONObject jsonObject = disponible.getJSONObject(i); Articles p = new Articles(); p.setId(jsonObject.getString(new Articles().id)); p.setName(jsonObject.getString(new Articles().name)); p.setSlug(jsonObject.getString(new Articles().slug)); p.setImages(jsonObject.getString(new Articles().images)); p.setDescription(jsonObject.getString(new Articles().description)); p.setPrice(jsonObject.getString(new Articles().price2)); p.setStock(jsonObject.getString(new Articles().stock)); p.setAvailability(jsonObject.getString(new Articles().availability)); DATA_VENDU.add(p); } DATAS_CACHED_VENDU.writeCache(DATA_VENDU); for (int i = 0; i < en_attente_validation.length(); i++) { JSONObject jsonObject = disponible.getJSONObject(i); Articles p = new Articles(); p.setId(jsonObject.getString(new Articles().id)); p.setName(jsonObject.getString(new Articles().name)); p.setSlug(jsonObject.getString(new Articles().slug)); p.setImages(jsonObject.getString(new Articles().images)); p.setDescription(jsonObject.getString(new Articles().description)); p.setPrice(jsonObject.getString(new Articles().price2)); p.setStock(jsonObject.getString(new Articles().stock)); p.setAvailability(jsonObject.getString(new Articles().availability)); DATA_ATTENTE.add(p); } DATAS_CACHED_ATTENTE.writeCache(DATA_ATTENTE); //TODO ; Attache views by BootomNavigation SetDatabyViews(DATA_GOODS); progress_data.setVisibility(View.GONE); } catch (Exception e) { Log.e("GOODS_LINK--XX ",e.getMessage()); error404.setVisibility(View.VISIBLE); LoadCache(); } } @Override public void onError(ANError anError) { progress_data.setVisibility(View.GONE); Log.e("GOODS_LINK ",anError.getMessage()); error404.setVisibility(View.VISIBLE); LoadCache(); } }); } private void SetDatabyViews(ArrayList<Articles> DATA_GOODS) { if (DATA_GOODS.size()<1){ error404.setVisibility(View.VISIBLE); Toast.makeText(context, "Empy", Toast.LENGTH_SHORT).show(); LoadCache(); }else{ error404.setVisibility(View.GONE); adaptor = new Adaptor_biens_list(context, DATA_GOODS); list_goods.setAdapter(adaptor); } } private void LoadCache() { progress_data.setVisibility(View.VISIBLE); try { if (DATAS_CACHED.getSize()<1){ Toast.makeText(context, "Empy", Toast.LENGTH_SHORT).show(); //error404.setVisibility(View.VISIBLE); }else{ SetDatabyViews(DATAS_CACHED.readCache()); //error404.setVisibility(View.GONE); } progress_data.setVisibility(View.GONE); //Log.e("CACHED_DATA", String.valueOf(DATAS_CACHED.readCache().size())); } catch (Exception e) { e.printStackTrace(); } } } <file_sep>/app/src/main/java/cd/digitalEdge/vst/Tools/Tool.java package cd.digitalEdge.vst.Tools; import android.app.AlarmManager; import android.app.DatePickerDialog; import android.app.DatePickerDialog.OnDateSetListener; import android.app.NotificationChannel; import android.app.NotificationManager; import android.app.PendingIntent; import android.app.TimePickerDialog; import android.app.TimePickerDialog.OnTimeSetListener; import android.content.ActivityNotFoundException; import android.content.Context; import android.content.DialogInterface; import android.content.DialogInterface.OnClickListener; import android.content.Intent; import android.content.SharedPreferences; import android.content.SharedPreferences.Editor; import android.content.pm.PackageManager; import android.content.pm.PackageManager.NameNotFoundException; import android.graphics.Bitmap; import android.graphics.Bitmap.CompressFormat; import android.graphics.Bitmap.Config; import android.graphics.BitmapFactory; import android.graphics.BitmapFactory.Options; import android.graphics.BitmapShader; import android.graphics.Canvas; import android.graphics.Paint; import android.graphics.PorterDuff.Mode; import android.graphics.PorterDuffXfermode; import android.graphics.Rect; import android.graphics.Shader.TileMode; import android.graphics.drawable.Drawable; import android.net.ConnectivityManager; import android.net.NetworkInfo; import android.net.Uri; import android.net.wifi.WifiManager; import android.os.Build.VERSION; import android.os.Environment; import android.support.v4.media.session.PlaybackStateCompat; import android.text.format.Formatter; import android.util.Base64; import android.util.Log; import android.view.View; import android.widget.ArrayAdapter; import android.widget.DatePicker; import android.widget.EditText; import android.widget.ImageView; import android.widget.ProgressBar; import android.widget.Spinner; import android.widget.TimePicker; import android.widget.Toast; import androidx.appcompat.app.AlertDialog.Builder; import androidx.core.app.NotificationCompat; import com.google.android.material.snackbar.Snackbar; import com.koushikdutta.async.future.FutureCallback; import com.koushikdutta.async.http.body.StringBody; import com.koushikdutta.ion.Ion; import com.koushikdutta.ion.builder.AnimateGifMode; import com.koushikdutta.ion.builder.Builders.Any.B; import com.koushikdutta.ion.builder.Builders.IV.F; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.net.InetAddress; import java.net.NetworkInterface; import java.nio.channels.FileChannel; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.text.DecimalFormat; import java.text.DecimalFormatSymbols; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Calendar; import java.util.Date; import java.util.Enumeration; import java.util.GregorianCalendar; import java.util.Random; import java.util.concurrent.TimeUnit; import cd.digitalEdge.vst.Controllers.Config_preferences; import cd.digitalEdge.vst.MainActivity; import cd.digitalEdge.vst.Objects.Users; import cd.digitalEdge.vst.R; import pl.droidsonroids.gif.GifDrawable; public class Tool { public static boolean Snack_Connexion(Context context, View v) { ConnectivityManager manager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo info = manager.getActiveNetworkInfo(); if (info == null || !info.isConnected()) { NetworkInfo networkInfo = info; Snackbar.make(v, "Vous n'êtes pas connecté", 5000).show(); return false; }else return true; } public static String NUMBER_FORMAT(String number) { DecimalFormatSymbols symbols = new DecimalFormatSymbols(); symbols.setGroupingSeparator(' '); return new DecimalFormat("#,###", symbols).format((long) Integer.parseInt(number)); } public static String[] Versions() { return new String[]{"PETIT FOUR", "CUPCAKE", "DONUT", "ECLAIR", "FROYO", "GINGERBREAD", "HONEYCOMB", "ICE CREAM SANDWICH", "JELLY BEAN", "KITKAT", "LOLLIPOP", "MARSHMALLOW", "NOUGAT", "OREO"}; } public static int[] Image_details(String uri) { File f = new File(uri); long fileSizeInKB = f.length() / PlaybackStateCompat.ACTION_PLAY_FROM_MEDIA_ID; Options options = new Options(); options.inJustDecodeBounds = true; BitmapFactory.decodeFile(f.getAbsolutePath(), options); StringBuilder sb = new StringBuilder(); sb.append(options.outWidth); sb.append("x"); sb.append(options.outHeight); String sb2 = sb.toString(); return new int[]{(int) fileSizeInKB, options.outWidth, options.outHeight}; } public static void viewImage(Context context, Uri uri) { File file = new File(String.valueOf(uri)); Uri path = Uri.fromFile(file); if (!file.exists()) { Toast.makeText(context, "No way to find Uri", Toast.LENGTH_LONG).show(); } Intent intent = new Intent(); intent.setAction("android.intent.action.VIEW"); intent.setDataAndType(path, "image/*"); intent.setFlags(Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT); try { context.startActivity(intent); } catch (ActivityNotFoundException e) { } } public static void Load_Image2(Context context, final ImageView imageView, String url) { try { new GifDrawable(context.getResources(), (int) R.drawable.gif4); imageView.setImageResource(R.drawable.avatar); ((B) Ion.with(context).load(url)).withBitmap().asBitmap().setCallback(new FutureCallback<Bitmap>() { public void onCompleted(Exception e, Bitmap bitmap) { if (bitmap == null) { imageView.setImageResource(R.drawable.unknow); return; } Bitmap circleBitmap = Bitmap.createBitmap(bitmap.getWidth(), bitmap.getHeight(), Config.ARGB_8888); BitmapShader shader = new BitmapShader(bitmap, TileMode.CLAMP, TileMode.CLAMP); Paint paint = new Paint(); paint.setShader(shader); new Canvas(circleBitmap).drawCircle((float) (bitmap.getWidth() / 2), (float) (bitmap.getHeight() / 2), (float) (bitmap.getWidth() / 2), paint); imageView.setImageBitmap(circleBitmap); } }); } catch (IOException e) { e.printStackTrace(); } } public static void Load_Image22(Context context, final ImageView imageView, String url) { try { //new GifDrawable(context.getResources(), (int) R.drawable.avatar); imageView.setImageResource(R.drawable.unknow); Ion.with(context) .load(url) .withBitmap() .asBitmap() .setCallback(new FutureCallback<Bitmap>() { public void onCompleted(Exception e, Bitmap bitmap) { if (bitmap == null) { imageView.setImageResource(R.drawable.unknow); return; } Bitmap circleBitmap = Bitmap.createBitmap(bitmap.getWidth(), bitmap.getHeight(), Config.ARGB_8888); BitmapShader shader = new BitmapShader(bitmap, TileMode.CLAMP, TileMode.CLAMP); Paint paint = new Paint(); paint.setShader(shader); new Canvas(circleBitmap).drawCircle((float) (bitmap.getWidth() / 2), (float) (bitmap.getHeight() / 2), (float) (bitmap.getWidth() / 2), paint); imageView.setImageBitmap(circleBitmap); } }); } catch (Exception e) { Log.e("PRODUCT_DATAS--XX ",e.getMessage()); } } public static void Load_Image(Context context, ImageView imageView, String url) { try { Ion.with(imageView) .placeholder((Drawable) new GifDrawable(context.getResources(), (int) R.drawable.gif5)) .error((int) R.drawable.unknow) .animateGif(AnimateGifMode.ANIMATE) .load(url); } catch (IOException e) { Log.e("PRODUCT_DATAS--XX ",e.getMessage()); } } public static void Dialog(Context context, String title, String mesg) { new Builder(context).setTitle((CharSequence) title).setMessage((CharSequence) mesg) .setNegativeButton((CharSequence) "D'accord", (OnClickListener) new OnClickListener() { public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); } }).show(); } public static Bitmap createCircleBitmap(Bitmap bitmap) { Bitmap output = Bitmap.createBitmap(bitmap.getWidth(), bitmap.getHeight(), Config.ARGB_8888); Rect rect = new Rect(0, 0, bitmap.getWidth(), bitmap.getHeight()); Canvas canvas = new Canvas(output); Paint paint = new Paint(); paint.setAntiAlias(true); int halfWidth = bitmap.getWidth() / 2; int halfHeight = bitmap.getHeight() / 2; canvas.drawCircle((float) halfWidth, (float) halfHeight, (float) Math.max(halfWidth, halfHeight), paint); paint.setXfermode(new PorterDuffXfermode(Mode.SRC_IN)); canvas.drawBitmap(bitmap, rect, rect, paint); return output; } public static SharedPreferences User_Preferences(Context context) { if (context == null) { context = new MainActivity().getApplicationContext(); } return context.getSharedPreferences("User_Identities", 0); } public static void userPreferences_Init(Context context) { Users column = new Users(); setUserPreferences(context, Config_preferences.PAIEMENT_MODE, "NO"); String str = "NULL"; setUserPreferences(context, Config_preferences.PRICE, str); setUserPreferences(context, Config_preferences.TAUX, str); setUserPreferences(context, Config_preferences.DEVISE, str); setUserPreferences(context, Config_preferences.LAT, str); setUserPreferences(context, Config_preferences.LONG, str); String str2 = ""; setUserPreferences(context, column.id, str2); setUserPreferences(context, column.name, str2); } public static void userPreferences_Set(Context context, Users u) { Users column = new Users(); setUserPreferences(context, "FirstUse", "No"); setUserPreferences(context, column.id, u.getId()); setUserPreferences(context, column.name, u.getName()); } public String GetDeviceipMobileData() { try { Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); while (en.hasMoreElements()) { Enumeration<InetAddress> enumIpAddr = ((NetworkInterface) en.nextElement()).getInetAddresses(); while (true) { if (enumIpAddr.hasMoreElements()) { InetAddress inetAddress = (InetAddress) enumIpAddr.nextElement(); if (!inetAddress.isLoopbackAddress()) { return inetAddress.getHostAddress().toString(); } } } } } catch (Exception ex) { Log.e("Current IP", ex.toString()); } return null; } public static String GetDeviceipWiFiData(Context context) { return Formatter.formatIpAddress(((WifiManager) context.getSystemService(Context.WIFI_SERVICE)).getConnectionInfo().getIpAddress()); } public static void setUserPreferences(Context context, String key, String values) { try { Editor editor = User_Preferences(context).edit(); editor.putString(key, values); editor.apply(); } catch (Exception e) { Log.e("TAG_PREFERENCES", e.getMessage()); } } public static String getUserPreferences(Context context, String key) { return User_Preferences(context).getString(key, ""); } public static void setEntries(Context context, Spinner spinner, ArrayList<String> DATA) { ArrayAdapter<String> adapter1 = new ArrayAdapter<>(context, android.R.layout.simple_list_item_1, DATA); adapter1.setDropDownViewResource(android.R.layout.simple_dropdown_item_1line); spinner.setAdapter(adapter1); } public static String Today() { return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()); } public static String Today2() { return new SimpleDateFormat("yyyy/MM/dd").format(new Date()); } /** * Méthode pour afficher le Date picker pour selectionner une datePublication * @param context * @param start_date * @return */ public static String Date_Picker(final Context context, final EditText start_date){ final Calendar c = Calendar.getInstance(); final int mYear, mMonth, mDay; mYear = c.get(Calendar.YEAR); mMonth = c.get(Calendar.MONTH); mDay = c.get(Calendar.DAY_OF_MONTH); final String[] Date = {""}; DatePickerDialog datePickerDialog = new DatePickerDialog(context, new OnDateSetListener() { @Override public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) { String m = String.valueOf(monthOfYear + 1); if (m.length()<= 1){ m = "0"+m; } String d = String.valueOf(dayOfMonth); if (d.length()<= 1){ d = "0"+d; } String date = d+ "-" + m + "-" +year ; Date[0] = date; Log.i("TTTTTTTTTTDate", Date[0]); start_date.setText(date); } }, mYear, mMonth, mDay); datePickerDialog.show(); Log.i("TTTTTTTTTT", Date[0]); return start_date.getText().toString(); } public static final String md5(String s) { String str = "MD5"; try { MessageDigest digest = MessageDigest.getInstance("MD5"); digest.update(s.getBytes()); byte[] messageDigest = digest.digest(); StringBuilder hexString = new StringBuilder(); /*for (byte aMessageDigest : messageDigest) { String h = Integer.toHexString(aMessageDigest & UnsignedBytes.MAX_VALUE); while (h.length() < 2) { StringBuilder sb = new StringBuilder(); sb.append("0"); sb.append(h); h = sb.toString(); } hexString.append(h); }*/ return hexString.toString(); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); return "no"; } } private static String convertToHex(byte[] data) { StringBuilder buf = new StringBuilder(); for (byte b : data) { int halfbyte = (b >>> 4) & 0x0F; int two_halfs = 0; do { buf.append((0 <= halfbyte) && (halfbyte <= 9) ? (char) ('0' + halfbyte) : (char) ('a' + (halfbyte - 10))); halfbyte = b & 0x0F; } while (two_halfs++ < 1); } return buf.toString(); } public static String SHA1(String text) throws NoSuchAlgorithmException, UnsupportedEncodingException { MessageDigest md = MessageDigest.getInstance("SHA-1"); md.update(text.getBytes("iso-8859-1"), 0, text.length()); byte[] sha1hash = md.digest(); return convertToHex(sha1hash); } public static final String getSha1Hex(String clearString) { try { MessageDigest messageDigest = MessageDigest.getInstance("SHA-1"); messageDigest.update(clearString.getBytes("UTF-8")); byte[] bytes = messageDigest.digest(); StringBuilder buffer = new StringBuilder(); for (byte b : bytes) { //buffer.append(Integer.toString((b & UnsignedBytes.MAX_VALUE) + Ascii.NUL, 16).substring(1)); } Log.e("FFFFFFFFFFFFXXX", buffer.toString()); return buffer.toString(); } catch (Exception ignored) { ignored.printStackTrace(); Log.e("FFFFFFFFFFFFERRR", ignored.getMessage()); return ignored.toString(); } } public static String Time_Picker(Context context, final EditText start_date) { Calendar c = Calendar.getInstance(); final String[] Date = {""}; Context context2 = context; TimePickerDialog timePickerDialog = new TimePickerDialog(context2, new OnTimeSetListener() { public void onTimeSet(TimePicker view, int hourOfDay, int minute) { String m = String.valueOf(minute); String str = "0"; if (m.length() <= 1) { StringBuilder sb = new StringBuilder(); sb.append(str); sb.append(m); m = sb.toString(); } String d = String.valueOf(hourOfDay); if (d.length() <= 1) { StringBuilder sb2 = new StringBuilder(); sb2.append(str); sb2.append(d); d = sb2.toString(); } StringBuilder sb3 = new StringBuilder(); sb3.append(d); sb3.append(":"); sb3.append(m); start_date.setText(sb3.toString()); Log.i("TTTTTTTTTTime", Date[0]); } }, c.get(Calendar.DATE) + 1, c.get(Calendar.DATE) + 1, true); timePickerDialog.show(); return start_date.getText().toString(); } public static boolean Expired(String end) throws ParseException { String str = "yyyy-MM-dd"; SimpleDateFormat sdf1 = new SimpleDateFormat(str); new SimpleDateFormat(str); Date d1 = new Date(sdf1.parse(end).getTime()); Date d2 = new Date(sdf1.parse(sdf1.format(new Date())).getTime()); Log.i("SSSSSS1", sdf1.format(d1)); Log.i("SSSSSS2", sdf1.format(d2)); return d1.before(d2); } public static long[] Time_stay(String end) throws ParseException { new SimpleDateFormat("yyyy/MM/dd HH:mm:ss"); SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd"); Date d1 = new Date(sdf1.parse(end).getTime()); Date d2 = new Date(sdf1.parse(sdf1.format(new Date())).getTime()); StringBuilder sb = new StringBuilder(); sb.append("PASSED_BEF "); sb.append(sdf1.format(d1)); String str = "VERIFICATION22 "; Log.i(str, sb.toString()); StringBuilder sb2 = new StringBuilder(); String str2 = "PASSED "; sb2.append(str2); sb2.append(sdf1.format(d1)); Log.i(str, sb2.toString()); StringBuilder sb3 = new StringBuilder(); sb3.append(str2); sb3.append(sdf1.format(d2)); Log.i(str, sb3.toString()); long intervalle = d1.getTime() - d2.getTime(); return new long[]{TimeUnit.MILLISECONDS.toDays(intervalle), TimeUnit.MILLISECONDS.toHours(intervalle), TimeUnit.MILLISECONDS.toMinutes(intervalle) % 60}; } public static String publication_Time(String start) throws ParseException { long intervalle; String dif; SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); SimpleDateFormat sdf3 = new SimpleDateFormat("dd-MM-yyyy"); String today = sdf1.format(new Date()); Date d1 = new Date(sdf1.parse(start).getTime()); Date d2 = new Date(sdf1.parse(today).getTime()); if (d2.after(d1)) { intervalle = d2.getTime() - d1.getTime(); } else { intervalle = d1.getTime() - d2.getTime(); } StringBuilder sb = new StringBuilder(); sb.append("START"); sb.append(String.valueOf(start)); String str = "PUBLISHING"; Log.i(str, sb.toString()); StringBuilder sb2 = new StringBuilder(); sb2.append("TODAY"); sb2.append(String.valueOf(today)); Log.i(str, sb2.toString()); long days = TimeUnit.MILLISECONDS.toDays(intervalle); long hours = TimeUnit.MILLISECONDS.toHours(intervalle); Date date = d2; long minutes = TimeUnit.MILLISECONDS.toMinutes(intervalle) % 60; String str2 = ""; SimpleDateFormat simpleDateFormat = sdf1; String str3 = today; SimpleDateFormat sdf2 = new SimpleDateFormat("HH:mm:ss"); String str4 = "Il y a "; if (hours >= 24) { long day2 = hours / 24; long hours2 = hours % 24; if (day2 == 1) { StringBuilder sb3 = new StringBuilder(); long j = intervalle; sb3.append("Hier à "); sb3.append(sdf2.format(d1)); dif = sb3.toString(); } else { if (day2 > 30 && day2 < 35) { dif = "Il y a 1 mois"; } else if (day2 < 30) { StringBuilder sb4 = new StringBuilder(); sb4.append(str4); sb4.append(day2); sb4.append(" Jours"); dif = sb4.toString(); } else { StringBuilder sb5 = new StringBuilder(); sb5.append("Depuis le "); sb5.append(sdf3.format(d1)); dif = sb5.toString(); } } } else { if (hours >= 1) { StringBuilder sb6 = new StringBuilder(); sb6.append(str4); sb6.append(hours); sb6.append(" h "); sb6.append(minutes); sb6.append(" min"); dif = sb6.toString(); } else if (minutes < 3) { dif = "A l'instant"; } else { StringBuilder sb7 = new StringBuilder(); sb7.append(str4); sb7.append(minutes); sb7.append(" min "); dif = sb7.toString(); } } Log.i(str, String.valueOf(dif)); return dif; } public static int get_Age(String start) throws ParseException { SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy"); new Date(sdf1.parse(start).getTime()); return Integer.parseInt(sdf1.format(new Date(new Date().getTime()))) - Integer.parseInt(start.substring(0, 4)); } public static long[] online_Time(String start) throws ParseException { SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); long intervalle = new Date(sdf1.parse(sdf1.format(new Date())).getTime()).getTime() - new Date(sdf1.parse(start).getTime()).getTime(); Log.i("TRAINNING_TODAY", String.valueOf(intervalle)); long days = TimeUnit.MILLISECONDS.toDays(intervalle); return new long[]{TimeUnit.MILLISECONDS.toHours(intervalle), TimeUnit.MILLISECONDS.toMinutes(intervalle) % 60}; } public static String add_days(String start, int amount) throws ParseException { SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); Date d1 = new Date(sdf1.parse(start).getTime()); GregorianCalendar gc = new GregorianCalendar(); Calendar c = Calendar.getInstance(); gc.setTime(d1); c.setTime(sdf1.parse(start)); gc.add(Calendar.DATE, amount); c.add(Calendar.DATE, amount); String v = sdf1.format(c.getTime()); Date d12 = gc.getTime(); return v; } public static String formatingDate(String origin_date) { String dif; String str = origin_date; String str2 = ""; try { long[] date = online_Time(origin_date); SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); SimpleDateFormat sdf2 = new SimpleDateFormat("HH:mm:ss"); Date d1 = new Date(sdf1.parse(str).getTime()); String str3 = str2; long hours = date[0]; long minutes = date[1]; String str4 = "Il y a "; if (hours >= 24) { long day2 = hours / 24; long hours2 = hours % 24; if (day2 >= 30 && day2 < 45) { dif = "Il y'a 1 mois"; } else if (day2 < 30) { StringBuilder sb = new StringBuilder(); sb.append(str4); sb.append(day2); sb.append(" Jours"); dif = sb.toString(); } else if (day2 == 1) { StringBuilder sb2 = new StringBuilder(); sb2.append("Hier à "); sb2.append(sdf2.format(d1)); dif = sb2.toString(); } else { StringBuilder sb3 = new StringBuilder(); sb3.append("Depuis "); sb3.append(str); dif = sb3.toString(); } } else if (hours >= 1) { StringBuilder sb4 = new StringBuilder(); sb4.append(str4); sb4.append(hours); sb4.append("h "); sb4.append(minutes); sb4.append("min"); dif = sb4.toString(); } else if (minutes < 3) { dif = "A l'instant"; } else { StringBuilder sb5 = new StringBuilder(); sb5.append(str4); sb5.append(minutes); sb5.append("min "); dif = sb5.toString(); } return dif; } catch (ParseException e) { e.printStackTrace(); Log.i("ERRRRRRRRR", e.getMessage()); return str2; } } public static int KeyCodeGen() { return new Random().nextInt(100000); } public static void SHARE(Context context, String message) { Intent intent = new Intent(); intent.setAction("android.intent.action.SEND"); intent.putExtra("android.intent.extra.TEXT", message); intent.setType(StringBody.CONTENT_TYPE); context.startActivity(Intent.createChooser(intent, "Partager le lien de Clinnet via :")); } public static void CALL(Context context, String phone) { Intent intent = new Intent("android.intent.action.DIAL"); StringBuilder sb = new StringBuilder(); sb.append("tel:"); sb.append(phone); intent.setData(Uri.parse(sb.toString())); context.startActivity(intent); } public static void LAUNCH_WHATAP(Context context, String number) { String str = "+00 9876543210"; StringBuilder sb = new StringBuilder(); sb.append("https://api.whatsapp.com/send?phone=+"); sb.append(number); String url = sb.toString(); try { context.getPackageManager().getPackageInfo("com.whatsapp", PackageManager.GET_ACTIVITIES); Intent i = new Intent("android.intent.action.VIEW"); i.setData(Uri.parse(url)); context.startActivity(i); } catch (NameNotFoundException e) { Toast.makeText(context, "Whatsapp app not installed in your phone", Toast.LENGTH_LONG).show(); e.printStackTrace(); } } public static void LAUNCH_WHATAPP(Context context, String number) { Intent sendIntent = new Intent(); sendIntent.setAction("android.intent.action.SEND"); sendIntent.putExtra("android.intent.extra.TEXT", "This is my text to send."); sendIntent.setType(StringBody.CONTENT_TYPE); sendIntent.setPackage("com.whatsapp"); context.startActivity(Intent.createChooser(sendIntent, "")); context.startActivity(sendIntent); StringBuilder sb = new StringBuilder(); sb.append("https://api.whatsapp.com/send?phone="); sb.append(number); String url = sb.toString(); Intent i = new Intent("android.intent.action.VIEW"); i.setData(Uri.parse(url)); context.startActivity(i); } public static void LAUNCH_WEB_SITE(Context context) { //context.startActivity(Intent.createChooser(new Intent("android.intent.action.VIEW", Uri.parse(ImagesContract.URL)), "Ouvrir via :")); } public static void Set_Alarm(Context context) { Intent intent = new Intent(context,null /*BroadCast.class*/); if (!(PendingIntent.getBroadcast(context, 0, intent, Intent.FILL_IN_ACTION) != null)) { Calendar calendar = Calendar.getInstance(); PendingIntent pendingIntent = PendingIntent.getBroadcast(context.getApplicationContext(), 0, intent, 0); AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE); alarmManager.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(), pendingIntent); alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), 5000, pendingIntent); } } public static void Notify(Context context, Intent intent, String titre) { NotificationManager notifManager = null; String id = context.getString(R.string.app_name); String title = context.getString(R.string.app_name); if (0 == 0) { notifManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE); } if (VERSION.SDK_INT >= 26 && notifManager.getNotificationChannel(id) == null) { NotificationChannel mChannel = new NotificationChannel(id, title, NotificationManager.IMPORTANCE_HIGH); mChannel.enableVibration(true); mChannel.setVibrationPattern(new long[]{100, 200, 300, 400, 500, 400, 300, 200, 400}); notifManager.createNotificationChannel(mChannel); } intent.setFlags(Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT); PendingIntent pendingIntent = PendingIntent.getActivity(context, (int) System.currentTimeMillis(), intent, Intent.FILL_IN_ACTION); NotificationCompat.Builder builder = new NotificationCompat.Builder(context, id); //builder.setContentTitle(titre).setSmallIcon(R.drawable.ic_notify).setContentText(context.getString(R.string.app_name)).setDefaults(-1).setAutoCancel(true).setContentIntent(pendingIntent).setTicker(titre).setVibrate(new long[]{100, 200, 300, 400, 500, 400, 300, 200, 400}); notifManager.notify(0, builder.build()); } public static void Camera_Picker(int n) { Intent camera = new Intent("android.media.action.IMAGE_CAPTURE"); StringBuilder sb = new StringBuilder(); sb.append(Environment.getExternalStorageDirectory().getPath()); sb.append("/MyAppFolder/MyApp"); sb.append(n); sb.append(".png"); camera.putExtra("output", Uri.fromFile(new File(sb.toString()))); int n2 = n + 1; } public static int Savefile(String name, String path) { StringBuilder sb = new StringBuilder(); sb.append(Environment.getExternalStorageDirectory().toString()); String str = "/Xresolu/profil/"; sb.append(str); File direct = new File(sb.toString()); StringBuilder sb2 = new StringBuilder(); sb2.append(Environment.getExternalStorageDirectory().toString()); sb2.append(str); sb2.append(name); sb2.append(".jpg"); File file = new File(sb2.toString()); if (!direct.exists()) { direct.mkdir(); Log.e("SAVE_IMAGE1", "Director created"); } if (file.exists()) { return 0; } try { file.createNewFile(); Log.e("SAVE_IMAGE2", "file created"); FileChannel src = new FileInputStream(path).getChannel(); FileChannel dst = new FileOutputStream(file).getChannel(); dst.transferFrom(src, 0, src.size()); src.close(); dst.close(); return 1; } catch (IOException e) { Log.e("SAVE_IMAGE_ERR", e.getMessage()); e.printStackTrace(); return 0; } } public static String Blob_encode(Bitmap bmp) { ByteArrayOutputStream baos = new ByteArrayOutputStream(); bmp.compress(CompressFormat.JPEG, 100, baos); return Base64.encodeToString(baos.toByteArray(), 0); } } <file_sep>/app/src/main/java/cd/digitalEdge/vst/Views/About_app.java package cd.digitalEdge.vst.Views; import android.content.Context; import android.content.Intent; import android.os.Bundle; import android.view.View; import android.widget.TextView; import androidx.appcompat.app.AppCompatActivity; import cd.digitalEdge.vst.R; import cd.digitalEdge.vst.Views.Blanks.Contacts; import cd.digitalEdge.vst.Views.Diapo.IntroActivity; public class About_app extends AppCompatActivity { Context context = this; TextView back,tutorial; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_about_app); getSupportActionBar().hide(); back = findViewById(R.id.back); tutorial = findViewById(R.id.tutorial); back.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { onBackPressed(); } }); tutorial.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent i = new Intent(context, IntroActivity.class); startActivity(i); finish(); } }); } @Override public void onBackPressed() { Intent i = new Intent(context, Paramettres.class); startActivity(i); finish(); } } <file_sep>/app/src/main/java/cd/digitalEdge/vst/Tools/RoundedImageView.java package cd.digitalEdge.vst.Tools; import android.content.Context; import android.graphics.Bitmap; import android.graphics.drawable.BitmapDrawable; import android.graphics.drawable.Drawable; import android.util.AttributeSet; import androidx.appcompat.widget.AppCompatImageView; import androidx.core.graphics.drawable.RoundedBitmapDrawable; import androidx.core.graphics.drawable.RoundedBitmapDrawableFactory; public class RoundedImageView extends AppCompatImageView { public RoundedImageView(Context context) { super(context); } public RoundedImageView(Context context, AttributeSet attrs) { super(context, attrs); } public RoundedImageView(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); } public void setImageDrawable(Drawable drawable) { if (drawable != null) { Bitmap bitmap = ((BitmapDrawable) drawable).getBitmap(); RoundedBitmapDrawable rid = RoundedBitmapDrawableFactory.create(getResources(), bitmap); rid.setCornerRadius(((float) bitmap.getWidth()) * 0.5f); super.setImageDrawable(rid); } } public void setImageBitmap(Bitmap bitmap) { if (bitmap != null) { RoundedBitmapDrawable rid = RoundedBitmapDrawableFactory.create(getResources(), bitmap); rid.setCornerRadius(((float) bitmap.getWidth()) * 0.5f); super.setImageDrawable(rid); } } } <file_sep>/app/build.gradle apply plugin: 'com.android.application' android { compileSdkVersion 29 defaultConfig { applicationId "cd.digitalEdge.vst" minSdkVersion 19 targetSdkVersion 29 versionCode 2 versionName "1.0" multiDexEnabled true testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner" } buildTypes { release { minifyEnabled false proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro' multiDexKeepFile file('multidex-main-dex-list.txt') } } compileOptions { sourceCompatibility JavaVersion.VERSION_1_8 targetCompatibility JavaVersion.VERSION_1_8 } allprojects { repositories { maven { url 'https://jitpack.io' } } } } dependencies { implementation fileTree(include: ['*.jar'], dir: 'libs') implementation 'androidx.appcompat:appcompat:1.1.0' implementation 'androidx.constraintlayout:constraintlayout:1.1.3' testImplementation 'junit:junit:4.12' androidTestImplementation 'androidx.test.ext:junit:1.1.1' androidTestImplementation 'androidx.test.espresso:espresso-core:3.2.0' implementation 'com.google.zxing:core:3.2.1' implementation 'com.journeyapps:zxing-android-embedded:3.5.0' implementation 'com.google.android.material:material:1.1.0' //implementation 'com.android.support:cardview-v7:27.1.1' implementation 'com.amitshekhar.android:android-networking:1.0.2' implementation 'com.amitshekhar.android:jackson-android-networking:1.0.2' implementation 'com.hbb20:ccp:2.2.0' implementation 'com.flaviofaria:kenburnsview:1.0.6' implementation 'com.koushikdutta.ion:ion:3.0.8' implementation 'pl.droidsonroids.gif:android-gif-drawable:1.2.18' /*implementation('com.lamudi.phonefield:phone-field:0.1.3@aar') { transitive = true }*/ implementation 'de.hdodenhof:circleimageview:3.1.0' implementation 'com.aurelhubert:ahbottomnavigation:2.3.4' implementation 'it.sephiroth.android.library.bottomnavigation:bottom-navigation:3.0.0' implementation 'io.nlopez.smartlocation:library:3.3.3' implementation 'com.github.nkzawa:socket.io-client:0.6.0' implementation 'com.karumi:dexter:6.2.0' implementation 'com.google.gms:google-services:4.3.3' implementation 'androidx.multidex:multidex:2.0.1' implementation 'com.github.PhilJay:MPAndroidChart:v3.1.0' implementation 'com.github.AnyChart:AnyChart-Android:1.1.2' implementation files('libs/FileCacher.jar') api 'com.theartofdev.edmodo:android-image-cropper:2.8.+' } dependencies { implementation 'androidx.legacy:legacy-support-v4:+' } dependencies { implementation 'androidx.legacy:legacy-support-v4:+' } dependencies { implementation 'androidx.appcompat:appcompat:+' implementation 'androidx.constraintlayout:constraintlayout:+' } dependencies { implementation 'androidx.appcompat:appcompat:+' implementation 'androidx.constraintlayout:constraintlayout:+' } dependencies { implementation 'androidx.appcompat:appcompat:+' implementation 'androidx.constraintlayout:constraintlayout:+' } dependencies { implementation 'androidx.appcompat:appcompat:+' implementation 'androidx.constraintlayout:constraintlayout:+' } dependencies { implementation 'androidx.appcompat:appcompat:+' implementation 'androidx.constraintlayout:constraintlayout:+' } dependencies { implementation 'androidx.appcompat:appcompat:+' implementation 'androidx.constraintlayout:constraintlayout:+' } dependencies { implementation 'androidx.appcompat:appcompat:+' implementation 'androidx.constraintlayout:constraintlayout:+' } dependencies { implementation 'androidx.appcompat:appcompat:+' implementation 'androidx.constraintlayout:constraintlayout:+' } dependencies { implementation 'androidx.appcompat:appcompat:+' implementation 'androidx.constraintlayout:constraintlayout:+' } dependencies { implementation 'com.android.support:appcompat-v7:28.+' implementation 'com.android.support.constraint:constraint-layout:+' } dependencies { implementation 'com.github.bumptech.glide:glide:4.11.0' annotationProcessor 'com.github.bumptech.glide:compiler:4.11.0' } dependencies { implementation 'com.android.support:appcompat-v7:28.+' implementation 'com.android.support.constraint:constraint-layout:+' } dependencies { implementation 'com.android.support:appcompat-v7:28.+' implementation 'com.android.support.constraint:constraint-layout:+' } dependencies { implementation 'com.android.support:appcompat-v7:28.+' implementation 'com.android.support.constraint:constraint-layout:+' } dependencies { implementation 'com.android.support:appcompat-v7:28.+' implementation 'com.android.support.constraint:constraint-layout:+' } dependencies { implementation 'com.android.support:appcompat-v7:28.+' implementation 'com.android.support.constraint:constraint-layout:+' } dependencies { implementation 'androidx.appcompat:appcompat:+' implementation 'androidx.constraintlayout:constraintlayout:+' } dependencies { implementation 'androidx.appcompat:appcompat:+' implementation 'androidx.constraintlayout:constraintlayout:+' } dependencies { implementation 'androidx.appcompat:appcompat:+' implementation 'androidx.constraintlayout:constraintlayout:+' } dependencies { implementation 'androidx.appcompat:appcompat:+' implementation 'androidx.constraintlayout:constraintlayout:+' } <file_sep>/app/src/main/java/cd/digitalEdge/vst/Objects/Post_Comments.java package cd.digitalEdge.vst.Objects; public class Post_Comments { public String id = "id"; public String comment = "comment"; public String created_at = "created_at"; public String getId() { return id; } public void setId(String id) { this.id = id; } public String getComment() { return comment; } public void setComment(String comment) { this.comment = comment; } public String getCreated_at() { return created_at; } public void setCreated_at(String created_at) { this.created_at = created_at; } } <file_sep>/app/src/main/java/cd/digitalEdge/vst/Tools/Utils.java package cd.digitalEdge.vst.Tools; import android.app.AlertDialog; import android.app.ProgressDialog; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.os.AsyncTask; import android.os.Handler; import android.util.Log; import android.view.LayoutInflater; import android.view.MenuItem; import android.view.View; import android.widget.CheckBox; import android.widget.EditText; import android.widget.LinearLayout; import android.widget.ProgressBar; import android.widget.RatingBar; import android.widget.TextView; import android.view.Menu; import android.widget.Toast; import androidx.cardview.widget.CardView; import com.androidnetworking.AndroidNetworking; import com.androidnetworking.common.Priority; import com.androidnetworking.error.ANError; import com.androidnetworking.interfaces.JSONObjectRequestListener; import com.androidnetworking.interfaces.StringRequestListener; import com.androidnetworking.model.Progress; import com.anychart.core.Text; import com.google.android.material.snackbar.Snackbar; import com.koushikdutta.async.http.body.MultipartFormDataBody; import org.json.JSONException; import org.json.JSONObject; import java.io.DataOutputStream; import java.io.File; import java.io.FileInputStream; import java.net.HttpURLConnection; import java.net.URL; import java.util.ArrayList; import java.util.Timer; import java.util.TimerTask; import cd.digitalEdge.vst.Controllers.Config; import cd.digitalEdge.vst.Controllers.Config_preferences; import cd.digitalEdge.vst.Controllers.Offline.SQLite.Sqlite_selects_methods; import cd.digitalEdge.vst.Controllers.Online.Updates; import cd.digitalEdge.vst.MainActivity; import cd.digitalEdge.vst.Objects.Articles; import cd.digitalEdge.vst.Objects.Users; import cd.digitalEdge.vst.R; import it.sephiroth.android.library.bottomnavigation.MenuParser; import okhttp3.internal.http.HttpHeaders; public class Utils { Timer mTimer = null; public static Handler mHandler = new Handler(); public static void MonToast(Context context, String titres, String message, String type) { View view = LayoutInflater.from(context).inflate(R.layout.toast_auth_info, null); LinearLayout back = (LinearLayout) view.findViewById(R.id.back); TextView sous_titre = (TextView) view.findViewById(R.id.sous); ((TextView) view.findViewById(R.id.titre)).setText(titres); sous_titre.setText(message); if (type.equals("Danger")) { back.setBackgroundColor(context.getResources().getColor(R.color.red)); } else if (type.equals("Success")) { back.setBackgroundColor(context.getResources().getColor(R.color.green)); } else if (type.equals("Info")) { back.setBackgroundColor(context.getResources().getColor(R.color.colorPrimary)); } Toast toast = Toast.makeText(context, "", Toast.LENGTH_LONG); toast.setGravity(48, 0, 0); toast.setView(view); toast.show(); } public static String[] QNT_PICKER() { String[] qntVal; qntVal = new String[10]; for (int i = 0; i < qntVal.length; i++) { qntVal[i] = String.valueOf(i); } return qntVal; } public void Noter_article(Context context, String property_id) { View convertView = LayoutInflater.from(context).inflate(R.layout.view_note, null); RatingBar note = convertView.findViewById(R.id.note); TextView note_prod = convertView.findViewById(R.id.note_prod); EditText rating_body = convertView.findViewById(R.id.rating_body); CheckBox recommand = convertView.findViewById(R.id.recommand); final String[] cote = {"0.0"}; note.setOnRatingBarChangeListener(new RatingBar.OnRatingBarChangeListener() { @Override public void onRatingChanged(RatingBar ratingBar, float rating, boolean fromUser) { ratingBar.setRating(rating); note_prod.setText(String.valueOf(rating)+" /5.0"); } }); new AlertDialog.Builder(context) .setView(convertView) .setPositiveButton("Valider", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { Toast.makeText(context, "Votre note est de : "+note.getRating(), Toast.LENGTH_SHORT).show(); String recommaded = ""; if (recommand.isChecked()== true) recommaded = "Yes"; else recommaded = "No"; sendNote( context, property_id, rating_body.getText().toString().replace("'","''").trim(), recommaded, String.valueOf(note.getRating()) ); } }) .setNegativeButton("Annuler", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { } }).show(); } public static void Setting_badge(String count2, TextView textCartItemCount) { if (count2.equals("0") || count2 == null){ textCartItemCount.setVisibility(View.GONE); }else{ textCartItemCount.setVisibility(View.VISIBLE); textCartItemCount.setText(count2); } } public static class TimeDisplay extends TimerTask { Context context; int turn = 0; TextView textCartItemCount; MenuItem menuItem; public TimeDisplay(Context context, int turn, TextView textCartItemCount, MenuItem menuItem) { this.context = context; this.turn = turn; this.textCartItemCount = textCartItemCount; this.menuItem = menuItem; } public void run() { mHandler.post(new Runnable() { public void run() { Log.e("MYSERVICE---XX", "je tourne bien"); int count = Check_Panier(context); View actionView = menuItem.getActionView(); textCartItemCount = (TextView) actionView.findViewById(R.id.cart_badge); if (Preferences.getUserPreferences(context, Constants.PANIER_COUNT) == null || Preferences.getUserPreferences(context, Constants.PANIER_COUNT).equals("")){ Utils.Setting_badge("0",textCartItemCount); }else Utils.Setting_badge(String.valueOf(count),textCartItemCount); } }); } } public static int Check_Panier(final Context context) { ArrayList<Articles> PANIER = new ArrayList<>(); PANIER = Sqlite_selects_methods.getall_Articles(context); if ( null == PANIER || PANIER.isEmpty() ){ PANIER = new ArrayList<>(); //Log.e("DATA", "DATAS "+PANIER.size()); } int count = PANIER.size(); Preferences.setUserPreferences(context, Constants.PANIER_COUNT, String.valueOf(count)); return count; } public void sendNote(Context context,String property_id,String body,String recommanded,String note ) { //Log.e("RATING_PARAMS ", property_id+" "+ body+" "+ recommanded+" "+ note ); AndroidNetworking .post(Config.GET_PRODUCT_NOTE) .addBodyParameter("body", body) .addBodyParameter("user_id", Preferences.getCurrentUser(context).getId()) .addBodyParameter("property_id", property_id) .addBodyParameter("recommend", recommanded) .addBodyParameter("note", note) .setPriority(Priority.HIGH) .build() .getAsString(new StringRequestListener() { @Override public void onResponse(String response) { Toast.makeText(context, response, Toast.LENGTH_SHORT).show(); //Log.e("RATING_ERR ",response); } @Override public void onError(ANError anError) { //Log.e("RATING_ERR ",anError.getMessage()); } }); } public void SaveToFavoris(Context context,String bienId ) { ProgressDialog p = new ProgressDialog(context); p.setTitle(""); p.setMessage("Encours..."); p.show(); Log.e("FAVORISXXXX ", Config.SET_FAVORI.concat(Preferences.getCurrentUser(context).getId() +"/"+bienId)); AndroidNetworking .post(Config.SET_FAVORI.concat(Preferences.getCurrentUser(context).getId() +"/"+bienId)) .setPriority(Priority.HIGH) .build() .getAsString(new StringRequestListener() { @Override public void onResponse(String response) { Toast.makeText(context, response, Toast.LENGTH_SHORT).show(); Log.e("RATING_ERR ",response); p.dismiss(); } @Override public void onError(ANError anError) { Log.e("RATING_ERR ",anError.getMessage()); p.dismiss(); } }); } } <file_sep>/app/src/main/java/cd/digitalEdge/vst/Views/Lists/Wallet.java package cd.digitalEdge.vst.Views.Lists; import androidx.annotation.NonNull; import androidx.appcompat.app.AppCompatActivity; import android.content.Context; import android.content.Intent; import android.os.Bundle; import android.view.MenuItem; import android.view.View; import android.widget.LinearLayout; import android.widget.ListView; import com.kosalgeek.android.caching.FileCacher; import java.util.ArrayList; import cd.digitalEdge.vst.Adaptors.Adaptor_favoris_list; import cd.digitalEdge.vst.Adaptors.Adaptor_wallet1_list; import cd.digitalEdge.vst.Objects.Articles; import cd.digitalEdge.vst.R; import cd.digitalEdge.vst.Tools.Constants; import cd.digitalEdge.vst.Views.Gerer; public class Wallet extends AppCompatActivity { Context context = this; Adaptor_wallet1_list adaptor; ListView list_gain, list_paiement; LinearLayout progress_data; ArrayList<Articles> DATA_WALLET = new ArrayList<>(); FileCacher<ArrayList<Articles>> DATAS_CACHED = new FileCacher<>(context, Constants.FILE_WALLET); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_wallet); getSupportActionBar().setTitle("Portefeuilles"); getSupportActionBar().setDisplayHomeAsUpEnabled(true); INIT_COMPONENT(); getData(); } private void INIT_COMPONENT() { progress_data = findViewById(R.id.progress_data); list_paiement = findViewById(R.id.list_paiement); list_gain = findViewById(R.id.list_gain); progress_data.setVisibility(View.GONE); } @Override protected void onResume() { super.onResume(); } @Override public void onBackPressed() { Intent i = new Intent(context, Gerer.class); startActivity(i); finish(); } @Override public boolean onOptionsItemSelected(@NonNull MenuItem item) { super.onOptionsItemSelected(item); switch (item.getItemId()) { case android.R.id.home: onBackPressed(); return true; } return true; } // TODO METHOD void getData(){ adaptor = new Adaptor_wallet1_list(context); list_gain.setAdapter(adaptor); list_paiement.setAdapter(adaptor); } } <file_sep>/app/src/main/java/cd/digitalEdge/vst/Controllers/Background/LocationServices.java package cd.digitalEdge.vst.Controllers.Background; import android.app.Service; import android.content.Context; import android.content.Intent; import android.location.Location; import android.location.LocationManager; import android.net.ConnectivityManager; import android.net.NetworkInfo; import android.os.Handler; import android.os.IBinder; import android.util.Log; import java.util.Timer; import java.util.TimerTask; import cd.digitalEdge.vst.Controllers.Config_preferences; import cd.digitalEdge.vst.Tools.Tool; import io.nlopez.smartlocation.OnLocationUpdatedListener; import io.nlopez.smartlocation.SmartLocation; //import io.nlopez.smartlocation.OnLocationUpdatedListener; //import io.nlopez.smartlocation.SmartLocation; public class LocationServices extends Service { public static final int notify = 2000; Context context = this; //private FusedLocationProviderClient client; int count = 0; LocationManager locationManager; /* access modifiers changed from: private */ public Handler mHandler = new Handler(); private Timer mTimer = null; class TimeDisplay extends TimerTask { TimeDisplay() { } public void run() { LocationServices.this.mHandler.post(new Runnable() { public void run() { Log.e("MYLOCATION", "je tourne bien"); ConnectivityManager manager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo info = manager.getActiveNetworkInfo(); if (info != null && info.isConnected()) { LocationServices.this.Mylocation(); } } }); } } public IBinder onBind(Intent intent) { throw new UnsupportedOperationException("Not yet implemented"); } public void onCreate() { Timer timer = this.mTimer; if (timer != null) { timer.cancel(); } else { this.mTimer = new Timer(); } //this.client = com.google.android.gms.location.LocationServices.getFusedLocationProviderClient(getApplicationContext()); this.mTimer.scheduleAtFixedRate(new TimeDisplay(), 0, 2000); } public void onDestroy() { super.onDestroy(); this.mTimer.cancel(); } /* access modifiers changed from: 0000 */ public void Mylocation() { try { SmartLocation.with(getApplicationContext()).location().start(new OnLocationUpdatedListener() { public void onLocationUpdated(Location location) { if (location == null) { LocationServices.this.Mylocation(); return; } StringBuilder sb = new StringBuilder(); sb.append(location.getLatitude()); sb.append(","); sb.append(location.getLongitude()); String sb2 = sb.toString(); Log.e("MYLOCATION", sb2); Tool.setUserPreferences(context, Config_preferences.LAT, String.valueOf(location.getLatitude())); Tool.setUserPreferences(context, Config_preferences.LONG, String.valueOf(location.getLongitude())); } }); } catch (Exception e) { Log.e("CodePackage.LOCATION", e.getMessage()); } } } <file_sep>/app/src/main/java/cd/digitalEdge/vst/Views/Lists/Recherche.java package cd.digitalEdge.vst.Views.Lists; import androidx.annotation.NonNull; import androidx.appcompat.app.AppCompatActivity; import androidx.drawerlayout.widget.DrawerLayout; import androidx.swiperefreshlayout.widget.SwipeRefreshLayout; import android.app.AlertDialog; import android.app.SearchManager; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.net.ConnectivityManager; import android.net.NetworkInfo; import android.os.AsyncTask; import android.os.Bundle; import android.os.Handler; import android.util.Log; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.animation.Animation; import android.view.animation.AnimationUtils; import android.widget.AbsListView; import android.widget.GridView; import android.widget.LinearLayout; import android.widget.ProgressBar; import android.widget.SearchView; import android.widget.TextView; import android.widget.Toast; import com.androidnetworking.AndroidNetworking; import com.androidnetworking.common.Priority; import com.androidnetworking.error.ANError; import com.androidnetworking.interfaces.JSONArrayRequestListener; import com.androidnetworking.interfaces.JSONObjectRequestListener; import com.androidnetworking.interfaces.OkHttpResponseAndJSONArrayRequestListener; import com.androidnetworking.interfaces.StringRequestListener; import com.google.android.material.navigation.NavigationView; import com.google.gson.JsonArray; import com.google.gson.JsonElement; import com.google.gson.JsonParser; import com.kosalgeek.android.caching.FileCacher; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.io.IOException; import java.util.ArrayList; import java.util.Timer; import java.util.TimerTask; import cd.digitalEdge.vst.Adaptors.Adaptor_recherche_list; import cd.digitalEdge.vst.Controllers.Background.MyServices; import cd.digitalEdge.vst.Controllers.Config; import cd.digitalEdge.vst.Controllers.Online.Selects; import cd.digitalEdge.vst.MainActivity; import cd.digitalEdge.vst.Objects.Articles; import cd.digitalEdge.vst.Objects.Products; import cd.digitalEdge.vst.R; import cd.digitalEdge.vst.Tools.Constants; import cd.digitalEdge.vst.Tools.Preferences; import cd.digitalEdge.vst.Tools.Utils; import okhttp3.Response; import timber.log.Timber; public class Recherche extends AppCompatActivity { Context context = this; String SEARCH_INPUT = ""; Adaptor_recherche_list adapter; MainActivity MAIN = new MainActivity(); GridView articles_list; ProgressBar progressbar; SwipeRefreshLayout swiper; SearchView SEARCH; LinearLayout progress_data, error404; int turn = 0; boolean Connected = true; TextView textCartItemCount, CATEGORIE,BTN_search; public Handler mHandler = new Handler(); Timer mTimer = null; ArrayList<Articles> DATAS = new ArrayList<>(); ArrayList<Articles> DATAS_SEARCHED = new ArrayList<>(); FileCacher<ArrayList<Articles>> DATAS_CACHED = new FileCacher<>(context, Constants.FILE_PRODUCTS); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_recherche); getSupportActionBar().setDisplayHomeAsUpEnabled(true); AndroidNetworking.initialize(getApplicationContext()); INIT_COMPONENT(); ConnectivityManager manager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo info = manager.getActiveNetworkInfo(); if (info != null && info.isConnected()) { Connected = true; }else{ Connected = false; } if (getIntent().hasExtra("TITLE")) { String from = getIntent().getExtras().getString("TITLE"); //Log.e("TITLEEEEEEE", from); if (from.equals("V")) SEARCH_INPUT = "Vêtement"; else if (from.equals("A")) SEARCH_INPUT = "Aliments"; else if (from.equals("C")) SEARCH_INPUT = "Chaussures"; else SEARCH_INPUT = from; if (Connected == true)getResearchedProd(); else LoadCache(); } else if(getIntent().hasExtra("SEARCH_INPUT")) { SEARCH_INPUT = getIntent().getExtras().getString("SEARCH_INPUT"); if (Connected == true)getResearchedProd(); else LoadCache(); }else{ SEARCH_INPUT = "Suprême store"; if (Connected == true) Loadprod(); else LoadCache(); } getSupportActionBar().setTitle(SEARCH_INPUT); } private void INIT_COMPONENT() { articles_list = findViewById(R.id.articles_list); swiper = findViewById(R.id.swiper); progress_data = findViewById(R.id.progress_data); progressbar = findViewById(R.id.progressbar); error404 = findViewById(R.id.error404); //navigationView.setNavigationItemSelectedListener(this); progress_data.setVisibility(View.GONE); progressbar.setVisibility(View.GONE); error404.setVisibility(View.GONE); } @Override protected void onResume() { super.onResume(); swiper.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() { @Override public void onRefresh() { getResearchedProd(); } }); error404.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { getResearchedProd(); } }); articles_list.setOnScrollListener(new AbsListView.OnScrollListener() { @Override public void onScrollStateChanged(AbsListView view, int scrollState) { if ( scrollState == AbsListView.OnScrollListener.SCROLL_STATE_IDLE && (articles_list.getLastVisiblePosition() ) >= adapter.getCount()-1 ){ Animation from_right = AnimationUtils.loadAnimation(context, R.anim.m_fromright); Animation to_right = AnimationUtils.loadAnimation(context, R.anim.m_toleft); progress_data.startAnimation(from_right); progress_data.setVisibility(View.VISIBLE); new Handler().postDelayed(new Runnable() { @Override public void run() { progress_data.startAnimation(to_right); progress_data.setVisibility(View.GONE); } }, 2000); } } @Override public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) { } }); } @Override public void onBackPressed() { Intent i = new Intent(context, MainActivity.class); startActivity(i); finish(); } @Override protected void onDestroy() { super.onDestroy(); this.mTimer.cancel(); } @Override public boolean onCreateOptionsMenu(Menu menu) { super.onCreateOptionsMenu(menu); getMenuInflater().inflate(R.menu.recherche_menu, menu); // todo setting up searchView from ActionBar SearchManager manager = (SearchManager) getSystemService(Context.SEARCH_SERVICE); SearchView search = (SearchView) menu.findItem(R.id.searchItem).getActionView(); search.setSearchableInfo(manager.getSearchableInfo(getComponentName())); search.setQueryHint("Recherche Article"); search.setOnQueryTextListener(new SearchView.OnQueryTextListener() { @Override public boolean onQueryTextSubmit(String query) { SEARCH_INPUT = query; getResearchedProd(); return true; } @Override public boolean onQueryTextChange(String newText) { return false; } }); final MenuItem menuItem = menu.findItem(R.id.panier); View actionView = menuItem.getActionView(); textCartItemCount = (TextView) actionView.findViewById(R.id.cart_badge); Timer timer = this.mTimer; if (timer != null) { timer.cancel(); } else { this.mTimer = new Timer(); } this.mTimer.scheduleAtFixedRate(new TimeDisplay(getApplicationContext(), 0), 0, 1000); actionView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { onOptionsItemSelected(menuItem); } }); return true; } public class TimeDisplay extends TimerTask { Context context; int turn = 0; public TimeDisplay(Context context, int turn) { this.context = context; //this.turn = turn; } public void run() { mHandler.post(new Runnable() { public void run() { ////Log.e("PANIER_SERVICES", "je tourne bien"); new MyServices().Check_Panier(context); if (Preferences.getUserPreferences(context, Constants.PANIER_COUNT) == null || Preferences.getUserPreferences(context, Constants.PANIER_COUNT).equals("")){ Utils.Setting_badge("0",textCartItemCount); }else Utils.Setting_badge(Preferences.getUserPreferences(context, Constants.PANIER_COUNT),textCartItemCount); } }); } } public void Setting_badge(String count2) { } @Override public boolean onOptionsItemSelected(@NonNull MenuItem item) { super.onOptionsItemSelected(item); switch (item.getItemId()) { case R.id.panier : Intent i = new Intent(context, Panier.class); startActivity(i); finish(); break; case android.R.id.home: // API 5+ solution onBackPressed(); return true; } return true; } // TODO METHOD private void getResearchedProd(){ //Log.i("PRODUCT_DATAS ",Config.GET_PRODUCTS); progress_data.setVisibility(View.VISIBLE); error404.setVisibility(View.GONE); DATAS.clear(); AndroidNetworking .post(Config.GET_PRODUCT_SEARCH) .addBodyParameter("query", SEARCH_INPUT) .setPriority(Priority.LOW) .build() .getAsJSONObject(new JSONObjectRequestListener() { @Override public void onResponse(JSONObject response) { try { JSONArray ar = response.getJSONArray("results"); ////Log.e("PRODUCT_DATAS RR ", ar.toString()); for (int i = 0; i < ar.length(); i++) { JSONObject jsonObject = ar.getJSONObject(i); Articles p = new Articles(); p.setId(jsonObject.getString(new Articles().id)); p.setName(jsonObject.getString(new Articles().name)); p.setSlug(jsonObject.getString(new Articles().slug)); p.setImages(jsonObject.getString(new Articles().images)); p.setDescription(jsonObject.getString(new Articles().description)); p.setPrice(jsonObject.getString(new Articles().price)); p.setStock(jsonObject.getString(new Articles().stock)); p.setAvailability(jsonObject.getString(new Articles().availability)); p.setKeywords(jsonObject.getString(new Articles().keywords)); p.setUser_id(jsonObject.getString(new Articles().user_id)); p.setUser_name(jsonObject.getString(new Articles().user_name)); p.setEmail(jsonObject.getString(new Articles().email)); p.setCat_id(jsonObject.getString(new Articles().cat_id)); p.setCat_name(jsonObject.getString(new Articles().cat_name)); DATAS.add(p); } DATAS_CACHED.writeCache(DATAS); if (DATAS.size()<1){ Toast.makeText(context, "Empy", Toast.LENGTH_SHORT).show(); error404.setVisibility(View.VISIBLE); }else{ adapter = new Adaptor_recherche_list(context, DATAS); articles_list.setAdapter(adapter); error404.setVisibility(View.GONE); } progress_data.setVisibility(View.GONE); } catch (Exception e) { //Log.e("PRODUCT_DATAS--XX ",e.getMessage()); //error404.setVisibility(View.VISIBLE); LoadCache(); } } @Override public void onError(ANError anError) { progress_data.setVisibility(View.GONE); //Log.e("PRODUCT_DATAS ",anError.getMessage()); //error404.setVisibility(View.VISIBLE); LoadCache(); } }); } private void Loadprod(){ LoadCache(); progress_data.setVisibility(View.VISIBLE); error404.setVisibility(View.GONE); DATAS.clear(); AndroidNetworking .get(Config.GET_PRODUCTS) .setPriority(Priority.LOW) .build() .getAsJSONObject(new JSONObjectRequestListener() { @Override public void onResponse(JSONObject response) { try { JSONArray ar = response.getJSONArray("products"); //Log.e("PRODUCT_DATAS RR ", ar.toString()); for (int i = 0; i < ar.length(); i++) { JSONObject jsonObject = ar.getJSONObject(i); Articles p = new Articles(); p.setId(jsonObject.getString(new Articles().id)); p.setName(jsonObject.getString(new Articles().name)); p.setSlug(jsonObject.getString(new Articles().slug)); p.setImages(jsonObject.getString(new Articles().images)); p.setDescription(jsonObject.getString(new Articles().description)); p.setPrice(jsonObject.getString(new Articles().price)); p.setStock(jsonObject.getString(new Articles().stock)); p.setAvailability(jsonObject.getString(new Articles().availability)); DATAS.add(p); } DATAS_CACHED.writeCache(DATAS); if (DATAS.size()<1){ Toast.makeText(context, "Empy", Toast.LENGTH_SHORT).show(); //error404.setVisibility(View.VISIBLE); }else{ adapter = new Adaptor_recherche_list(context, DATAS); articles_list.setAdapter(adapter); //error404.setVisibility(View.GONE); } progress_data.setVisibility(View.GONE); } catch (Exception e) { //Log.e("PRODUCT_DATAS--XX ",e.getMessage()); //error404.setVisibility(View.VISIBLE); } } @Override public void onError(ANError anError) { progress_data.setVisibility(View.GONE); //Log.e("PRODUCT_DATAS ",anError.getMessage()); error404.setVisibility(View.VISIBLE); } }); } private void LoadCache(){ progress_data.setVisibility(View.VISIBLE); try { if (DATAS_CACHED.getSize()<1){ Toast.makeText(context, "Empy", Toast.LENGTH_SHORT).show(); error404.setVisibility(View.VISIBLE); }else{ adapter = new Adaptor_recherche_list(context, DATAS_CACHED.readCache()); articles_list.setAdapter(adapter); error404.setVisibility(View.GONE); } progress_data.setVisibility(View.GONE); ////Log.e("CACHED_DATA", String.valueOf(DATAS_CACHED.readCache().size())); } catch (Exception e) { e.printStackTrace(); } } } <file_sep>/app/src/main/java/cd/digitalEdge/vst/Adaptors/Adaptor_Client_list.java package cd.digitalEdge.vst.Adaptors; import android.content.Context; import android.view.LayoutInflater; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.ImageView; import android.widget.PopupMenu; import android.widget.TextView; import android.widget.Toast; import java.util.ArrayList; import java.util.Random; import cd.digitalEdge.vst.Objects.Categories; import cd.digitalEdge.vst.R; public class Adaptor_Client_list extends BaseAdapter { Context context; ArrayList<Categories> DATAS; public Adaptor_Client_list(Context context, ArrayList<Categories> DATAS) { this.context = context; this.DATAS = DATAS; } public int getCount() { return DATAS.size(); } public Object getItem(int position) { return DATAS.get(position); } public long getItemId(int position) { return 0; } public View getView(int position, View convertView, ViewGroup parent) { View convertView2 = LayoutInflater.from(this.context).inflate(R.layout.model_panier_item, null); TextView index_letter = convertView2.findViewById(R.id.index_letter); TextView client_name = convertView2.findViewById(R.id.client_name); TextView detail = convertView2.findViewById(R.id.detail); ImageView option = convertView2.findViewById(R.id.option); Categories data = DATAS.get(position); client_name.setText(data.getName()); //detail.setText(data.getAddress()+"\n"+ data.getPhone()); index_letter.setText(data.getName().substring(0,1)); int r = new Random().nextInt(4); if (r == 1) index_letter.setBackgroundResource(R.drawable.oval_blue); if (r == 2) index_letter.setBackgroundResource(R.drawable.oval_red); if (r == 3) index_letter.setBackgroundResource(R.drawable.oval_green); if (r == 4) index_letter.setBackgroundResource(R.drawable.oval_gris); option.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { PopupMenu popupMenu = new PopupMenu(context, v); popupMenu.getMenu().add("Visualiser").setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() { @Override public boolean onMenuItemClick(MenuItem item) { Toast.makeText(context, "Cliecked", Toast.LENGTH_SHORT).show(); return false; } }); popupMenu.getMenu().add("Demande edition").setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() { @Override public boolean onMenuItemClick(MenuItem item) { Toast.makeText(context, "Cliecked", Toast.LENGTH_SHORT).show(); return false; } }); popupMenu.show(); } }); return convertView2; } } <file_sep>/app/src/main/java/cd/digitalEdge/vst/Adaptors/Adaptor_Panier.java package cd.digitalEdge.vst.Adaptors; import android.app.AlertDialog; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.view.LayoutInflater; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.ImageView; import android.widget.NumberPicker; import android.widget.PopupMenu; import android.widget.TextView; import android.widget.Toast; import androidx.cardview.widget.CardView; import com.google.android.material.floatingactionbutton.FloatingActionButton; import java.util.ArrayList; import java.util.List; import java.util.Random; import cd.digitalEdge.vst.Controllers.Config_preferences; import cd.digitalEdge.vst.Controllers.Offline.ExecuteUpdate; import cd.digitalEdge.vst.Controllers.Offline.SQLite.Sqlite_selects_methods; import cd.digitalEdge.vst.Objects.Articles; import cd.digitalEdge.vst.Objects.Categories; import cd.digitalEdge.vst.Objects.Products; import cd.digitalEdge.vst.R; import cd.digitalEdge.vst.Tools.Constants; import cd.digitalEdge.vst.Tools.Utils; import cd.digitalEdge.vst.Views.Lists.Details_Article; import cd.digitalEdge.vst.Views.Lists.Panier; public class Adaptor_Panier extends BaseAdapter { Context context; ArrayList<Articles> PANIER; public Adaptor_Panier(Context context, ArrayList<Articles> PANIER) { this.context = context; this.PANIER = PANIER; } public void refreshEvents(ArrayList<Articles> events, Articles data) { ArrayList<Articles> PANIER = new ArrayList<>(); PANIER = Sqlite_selects_methods.getall_Articles(context); if ( null == PANIER || PANIER.isEmpty() ){ PANIER = new ArrayList<>(); //Log.e("DATA", "DATAS "+PANIER.size()); } this.PANIER = PANIER; notifyDataSetChanged(); } public int getCount() { return PANIER.size(); } public Object getItem(int position) { return PANIER.get(position); } public long getItemId(int position) { return 0; } public View getView(int position, View convertView, ViewGroup parent) { View convertView2 = LayoutInflater.from(this.context).inflate(R.layout.model_panier_item, null); ImageView option = convertView2.findViewById(R.id.option); CardView card = convertView2.findViewById(R.id.card); TextView name = convertView2.findViewById(R.id.name); TextView descripion = convertView2.findViewById(R.id.descripion); TextView price = convertView2.findViewById(R.id.price); TextView PT = convertView2.findViewById(R.id.PT); TextView pay_now = convertView2.findViewById(R.id.pay_now); ImageView delete_panier = convertView2.findViewById(R.id.delete_panier); NumberPicker qnt_picker = convertView2.findViewById(R.id.qnt_picker); Articles data = PANIER.get(position); name.setText(data.getName()); float tot = Float.parseFloat(data.getPrice()) * Float.parseFloat(data.getQnt()); PT.setText( tot + " USD" ); descripion.setText(data.getSlug()); pay_now.setText(data.getQnt()); price.setText(data.getPrice().concat(" USD")); qnt_picker.setMaxValue(5); qnt_picker.setMinValue(1); qnt_picker.setDisplayedValues(Utils.QNT_PICKER()); card.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent i = new Intent(context, Details_Article.class); i.putExtra("Article", data); i.putExtra("source", "Panier"); context.startActivity(i); } }); delete_panier.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (ExecuteUpdate.delete(context, Constants.ARTICLE,new Articles().id, data.getId()) == 1){ Toast.makeText(context, "Article deleted", Toast.LENGTH_SHORT).show(); refreshEvents(PANIER, data); } } }); pay_now.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { View view = LayoutInflater.from(context).inflate(R.layout.view_number_picker, null); NumberPicker qnt_picker = view.findViewById(R.id.qnt_picker); qnt_picker.setMaxValue(5); qnt_picker.setMinValue(1); qnt_picker.setDisplayedValues(Utils.QNT_PICKER()); new AlertDialog.Builder(context) .setView(view) .setPositiveButton("D'accord", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { if ( ExecuteUpdate.update( context, Constants.ARTICLE,new Articles().qnt, String.valueOf(qnt_picker.getValue() -1), new Articles().id, data.getId() ) == 1 ){ pay_now.setText(String.valueOf(qnt_picker.getValue() -1)); Toast.makeText(context, "updated qnt", Toast.LENGTH_SHORT).show(); refreshEvents(PANIER, data); } dialog.dismiss(); } }) .setNegativeButton("Annuler", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); } }).show(); } }); option.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { PopupMenu popupMenu = new PopupMenu(context, v); popupMenu.getMenu().add("Acheter maintenant").setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() { @Override public boolean onMenuItemClick(MenuItem item) { Toast.makeText(context, "test", Toast.LENGTH_SHORT).show(); return true; } }); popupMenu.getMenu().add("Retirer du panier").setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() { @Override public boolean onMenuItemClick(MenuItem item) { Toast.makeText(context, "test", Toast.LENGTH_SHORT).show(); return true; } }); popupMenu.show(); } }); return convertView2; } } <file_sep>/app/src/main/java/cd/digitalEdge/vst/Adaptors/Adaptor_commands_list.java package cd.digitalEdge.vst.Adaptors; import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import cd.digitalEdge.vst.R; public class Adaptor_commands_list extends BaseAdapter { Context context; public Adaptor_commands_list(Context context) { this.context = context; } public int getCount() { return 20; } public Object getItem(int position) { return null; } public long getItemId(int position) { return 0; } public View getView(int position, View convertView, ViewGroup parent) { View convertView2 = LayoutInflater.from(this.context).inflate(R.layout.model_command_list, null); //CardView CARD = convertView2.findViewById(R.id.CARD); return convertView2; } }
fc3dbfde5419b0e6a8df3178d13b3eee9cbc1fb0
[ "Java", "Gradle" ]
29
Java
deon-Mass/VST
b5ce2c4e374e4bb5642294423e16a951789abfdc
52e44cab6a45b8b444eff62f4116a8104bfc337d
refs/heads/master
<file_sep>// to compile // g++ test_CQCGL1dRpo_arpack.cc -std=c++11 -O3 -march=corei7 -msse4 -msse2 -I$EIGEN -I$RESH/include -I$XDAPPS/arpackpp/include -L$RESH/lib -lCQCGL1dRpo_arpack -lCQCGL1dRpo -lCQCGL1d -lmyfft -lfftw3 -lm -lsparseRoutines -ldenseRoutines -literMethod -lmyH5 -llapack -larpack -lsuperlu -lopenblas #include <iostream> #include <arsnsym.h> #include <Eigen/Dense> #include "CQCGL1dRpo_arpack.hpp" using namespace std; using namespace Eigen; using namespace denseRoutines; #define cee(x) (cout << (x) << endl << endl) #define CASE_10 int main(int argc, char **argv){ #ifdef CASE_10 //====================================================================== // to visulize the limit cycle first const int N = 1024; const double L = 50; double Bi = 1.4; double Gi = -3.9; CQCGL1dRpo_arpack cgl(N, L, -0.1, 0.125, 0.5, 1, Bi, -0.1, Gi, 1); string file = "../../data/cgl/rpoHopfBiGi.h5"; cgl.calEVParaSeq(file, std::vector<double>{Bi}, std::vector<double>{Gi}, 10, true); #endif #ifdef CASE_20 //====================================================================== // test vc2vr and vr2vc MatrixXd A(10, 10); A.setRandom(); VectorXcd e; MatrixXcd v; std::tie(e, v) = evEig(A, 2); cee(e); cee(v); MatrixXd vr = vc2vr(v); cee(vr); MatrixXcd vc = vr2vc(e, vr); cee(vc); #endif return 0; } <file_sep>#!/bin/bash # usage: # ./createAll 0 => compile all cases # ./createAll 1 => single thread caes DEST=/usr/local/home/xiong/00git/research/lib/boostPython/ # compile single thread library if [ $1 -eq 0 ] || [ $1 -eq 1 ]; then mv Jamroot jam.tmp && cp jam.tmp Jamroot perl -p -i -e 's/choice = \d/choice = 1/' Jamroot perl -p -i -e 's/py_CQCGL2d.cc/pytmp.cc/' Jamroot perl -p -e 's/MODULE\(py_CQCGL2d\S*\)/MODULE\(py_CQCGL2d\)/' py_CQCGL2d.cc > pytmp.cc rm -rf bin pylib b2 && mv pylib/py_CQCGL2d*.so $DEST && mv jam.tmp Jamroot && rm pytmp.cc && rm -rf bin pylib echo echo "compile single thread library" fi # compile multi fftw threads library if [ $1 -eq 0 ] || [ $1 -eq 2 ]; then mv Jamroot jam.tmp && cp jam.tmp Jamroot perl -p -i -e 's/choice = \d/choice = 2/' Jamroot perl -p -i -e 's/py_CQCGL2d.cc/pytmp.cc/' Jamroot perl -p -e 's/MODULE\(py_CQCGL2d\S*\)/MODULE\(py_CQCGL2d_threads\)/' py_CQCGL2d.cc > pytmp.cc rm -rf bin pylib b2 && mv pylib/py_CQCGL2d*.so $DEST && mv jam.tmp Jamroot && rm pytmp.cc && rm -rf bin pylib echo echo "compile multi fftw threads library" fi ############################################################ # for req lib # compile single thread library if [ $1 -eq 0 ] || [ $1 -eq 3 ]; then mv Jamroot jam.tmp && cp jam.tmp Jamroot perl -p -i -e 's/choice = \d/choice = 3/' Jamroot perl -p -i -e 's/py_CQCGL2dReq.cc/pytmp.cc/' Jamroot perl -p -e 's/MODULE\(py_CQCGL2dReq\S*\)/MODULE\(py_CQCGL2dReq\)/' py_CQCGL2dReq.cc > pytmp.cc rm -rf bin pylib b2 && mv pylib/py_CQCGL2dReq*.so $DEST && mv jam.tmp Jamroot && rm pytmp.cc && rm -rf bin pylib echo echo "compile single thread library" fi # compile multi fftw threads library if [ $1 -eq 0 ] || [ $1 -eq 4 ]; then mv Jamroot jam.tmp && cp jam.tmp Jamroot perl -p -i -e 's/choice = \d/choice = 4/' Jamroot perl -p -i -e 's/py_CQCGL2dReq.cc/pytmp.cc/' Jamroot perl -p -e 's/MODULE\(py_CQCGL2dReq\S*\)/MODULE\(py_CQCGL2dReq_threads\)/' py_CQCGL2dReq.cc > pytmp.cc rm -rf bin pylib b2 && mv pylib/py_CQCGL2dReq*.so $DEST && mv jam.tmp Jamroot && rm pytmp.cc && rm -rf bin pylib echo echo "compile multi fftw threads library" fi <file_sep>/** \mainpage some frequently used spase matrix related routines * * \section sec_intro Introduction * \section sec_use usage * Example: * \code * g++ yourfile.cc /path/to/sparseRoutines.cc -I/path/to/sparseRoutines.hpp -I/path/to/eigen -std=c++0x * \endcode */ #ifndef SPARSEROUTINES_H #define SPARSEROUTINES_H #include <Eigen/Dense> #include <Eigen/Sparse> #include <vector> #include <iostream> namespace sparseRoutines { struct KeepDiag{ inline bool operator() (const int& row, const int& col, const double&) const{ return row == col; } }; std::vector<Eigen::Triplet<double> > triMat(const Eigen::MatrixXd &A, const size_t M = 0 , const size_t N = 0); std::vector<Eigen::Triplet<double> > triDiag(const size_t n, const double x, const size_t M = 0, const size_t N = 0 ); std::vector<Eigen::Triplet<double> > triDiag(const Eigen::VectorXd &D, const size_t M, const size_t N); } #endif // SPARSEROUTINES_H <file_sep>/* compile command: * mex CXXFLAGS='-std=c++0x -fPIC -O3 -march=corei7 -msse4.2' MEXcqcgl1d.cpp cqcgl1d.cc * -I../../include -I/usr/include/eigen3 -lm -lfftw3 * */ #include "cqcgl1d.hpp" #include "mex.h" #include <cmath> #include <cstring> #include <Eigen/Dense> using Eigen::ArrayXXd; using Eigen::ArrayXXcd; using Eigen::ArrayXd; using Eigen::ArrayXcd; using Eigen::Map; static ArrayXXd intg(double *a0, int N, double d, double h, int nstp, int np, double Mu, double Br, double Bi, double Dr, double Di, double Gr, double Gi){ Cqcgl1d cgl(N, d, h, Mu, Br, Bi, Dr, Di, Gr, Gi); Map<ArrayXd> v0(a0, 2*N); ArrayXXd aa = cgl.intg(v0, nstp, np); return aa; } static Cqcgl1d::CGLaj intgj(double *a0, int N, double d, double h, int nstp, int np, int nqr, double Mu, double Br, double Bi, double Dr, double Di, double Gr, double Gi){ Cqcgl1d cgl(N, d, h, Mu, Br, Bi, Dr, Di, Gr, Gi); Map<ArrayXd> v0(a0, 2*N); Cqcgl1d::CGLaj aj = cgl.intgj(v0, nstp, np, nqr); return aj; } void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[]){ double *a0 = mxGetPr(prhs[0]); int N = mxGetScalar(prhs[1]); double d = mxGetScalar(prhs[2]); double h = mxGetScalar(prhs[3]); int nstp = mxGetScalar(prhs[4]); int np = mxGetScalar(prhs[5]); int nqr = mxGetScalar(prhs[6]); double Mu = mxGetScalar(prhs[7]); double Br = mxGetScalar(prhs[8]); double Bi = mxGetScalar(prhs[9]); double Dr = mxGetScalar(prhs[10]); double Di = mxGetScalar(prhs[11]); double Gr = mxGetScalar(prhs[12]); double Gi = mxGetScalar(prhs[13]); mwSize isJ = mxGetScalar(prhs[14]); if( 0 == isJ){ plhs[0] = mxCreateDoubleMatrix(2*N, nstp/np+1, mxREAL); ArrayXXd aa = intg(a0, N, d, h, nstp, np, Mu, Br, Bi, Dr, Di, Gr, Gi); memcpy(mxGetPr(plhs[0]), &aa(0,0), (nstp/np+1)*(2*N)*sizeof(double)); } else { plhs[0] = mxCreateDoubleMatrix(2*N, nstp/np+1, mxREAL); plhs[1] = mxCreateDoubleMatrix(2*N*2*N, nstp/nqr, mxREAL); Cqcgl1d::CGLaj aj = intgj(a0, N, d, h, nstp, np, nqr, Mu, Br, Bi, Dr, Di, Gr, Gi); memcpy(mxGetPr(plhs[0]), &(aj.aa(0,0)), (nstp/np+1)*(2*N)*sizeof(double)); memcpy(mxGetPr(plhs[1]), &(aj.daa(0,0)), (nstp/nqr)*(2*N)*(2*N)*sizeof(double)); } } <file_sep>/* How to compile this program: * h5c++ ksDimension.cc ./ksint/ksint.cc ./ped/ped.cc ./readks/readks.cc * -std=c++0x -I$XDAPPS/eigen/include/eigen3 -I../include/ -lfftw3 -O3 -march=corei7 * -msse4 -msse2 * * or (Note : libreadks.a is static library, so the following order is important) * * h5c++ ksDimension.cc -std=c++0x -I$XDAPPS/eigen/include/eigen3 -I../include -L../lib -lreadks -lksint -lped -lfftw3 -O3 -march=corei7 -msse4 -msse2 */ #include "ksint.hpp" #include "ped.hpp" #include "readks.hpp" #include <Eigen/Dense> #include <tuple> #include <string> #include <iostream> #include <fstream> #include <cmath> #include <ctime> #include <vector> using namespace std; using namespace Eigen; /** @brief calculate the actual subspace bound and the indicator whether the actual * bound is the same as specified. * * @param[in] subspDim subspace bounds. Each column is a 4-vector storing dimension of * two subspaces. * @param[in] ixSp subspace index, i.e the left and right bounds * @see indexSubspace * @return a pair of integer matrix. The first one is actual subspace bound. * The second one indicate whether the bounds are the same as specified. */ std::pair<MatrixXi, MatrixXi> subspBound(const MatrixXi subspDim, const MatrixXi ixSp){ assert(subspDim.rows() == 4); // two subspaces have 4 indices. const int M = subspDim.cols(); MatrixXi boundStrict(MatrixXi::Zero(4,M)); MatrixXi bound(4, M); for(size_t i = 0; i < M; i++){ int L1 = ixSp(subspDim(0,i), 0); bound(0,i) = L1; int R1 = ixSp(subspDim(1,i), 1); bound(1,i) = R1; int L2 = ixSp(subspDim(2,i), 0); bound(2,i) = L2; int R2 = ixSp(subspDim(3,i), 1); bound(3,i) = R2; if(L1 == subspDim(0,i)) boundStrict(0,i) = 1; if(R1 == subspDim(1,i)) boundStrict(1,i) = 1; if(L2 == subspDim(2,i)) boundStrict(2,i) = 1; if(R2 == subspDim(3,i)) boundStrict(3,i) = 1; } return std::make_pair(bound, boundStrict); } /** @brief calculate the cos() of the largest angle * between the two subspaces spanned by the * columns of matrices A and B. */ double angleSubspace(const Ref<const MatrixXd> &A, const Ref<const MatrixXd> &B){ assert(A.rows() == B.rows()); const int N = A.rows(); const int M1 = A.cols(); const int M2 = B.cols(); MatrixXd thinQa(MatrixXd::Identity(N,M1)); MatrixXd thinQb(MatrixXd::Identity(N,M2)); ColPivHouseholderQR<MatrixXd> qra(A); thinQa = qra.householderQ() * thinQa; ColPivHouseholderQR<MatrixXd> qrb(B); thinQb = qrb.householderQ() * thinQb; JacobiSVD<MatrixXd> svd(thinQa.transpose() * thinQb); VectorXd sv = svd.singularValues(); return sv.maxCoeff(); } double angleSpaceVector(const Ref<const MatrixXd> &Q, const Ref<const VectorXd> &V){ assert( Q.rows() == V.rows()); VectorXd P = Q.transpose() * V; double cos2 = P.squaredNorm() / V.squaredNorm(); /* cos^2 */ return sqrt(1-cos2); } /** @brief calculate angle between two subspaces along an upo * * @param[in] fileName file that stores the ppo/rpo information * @param[in] ppType ppo or rpo * @param[in] ppId id of the periodic orbit * @param[in] subspDim 4xM2 matrix storing the bounds of subspaces * @return first matrix : each row stores the angles at one point * second matrix: matrix indicating whether bounds are the * same as specified * @see subspBound */ std::pair<MatrixXd, MatrixXi> anglePO(ReadKS &readks, const string ppType, const int ppId, const MatrixXi subspDim){ assert(subspDim.rows() == 4); MatrixXd eigVals = readks.readKSe(ppType, ppId); // Floquet exponents MatrixXd eigVecs = readks.readKSve(ppType, ppId);// Floquet vectors // left and right bounds MatrixXi ixSp = readks.indexSubspace(eigVals.col(2), eigVals.col(0)); const int N = sqrt(eigVecs.rows()); const int M = eigVecs.cols(); const int M2 = subspDim.cols(); MatrixXd ang_po(M, M2); // calculate the exact bound of this indices. std::pair<MatrixXi, MatrixXi> tmp = subspBound(subspDim, ixSp); MatrixXi &bound = tmp.first; MatrixXi &boundStrict = tmp.second; for(size_t i = 0; i < M; i++){ MatrixXd ve = eigVecs.col(i); ve.resize(N, N); for(size_t j = 0; j < M2; j++){ double ang = angleSubspace(ve.middleCols(bound(0, j), bound(1,j)-bound(0,j)+1), ve.middleCols(bound(2, j), bound(3,j)-bound(2,j)+1) ); ang_po(i, j) = ang; } } return std::make_pair(ang_po, boundStrict); } /** @brief normalize each row of a matrix */ void normc(MatrixXd &A){ int m = A.cols(); for(size_t i = 0; i < m; i++) A.col(i).array() = A.col(i).array() / A.col(i).norm(); } /** @brief calculate the minimal distance between an ergodic * trajectory and one ppo/rpo. * @note the cols of ppo/rpo should be the same as its corresponding * Flqouet vectors, otherwise, there maybe index flow when calling * difAngle(). For example, you can do it in the following way: * \code * minDistance(ergodicHat, aaHat.leftCols(aaHat.cols()-1), tolClose) * \endcode */ std::tuple<MatrixXd, VectorXi, VectorXi, VectorXd> minDistance(const MatrixXd &ergodic, const MatrixXd &aa, const double tolClose){ const int n = ergodic.rows(); const int m = ergodic.cols(); const int n2 = aa.rows(); const int m2 = aa.cols(); assert(n2 == n); VectorXi minIndexPo(m); VectorXi minIndexErgodic(m); VectorXd minDis(m); MatrixXd minDifv(n, m); size_t tracker = 0; for(size_t i = 0; i < m; i++){ MatrixXd dif = aa.colwise() - ergodic.col(i);// relation is inversed. VectorXd colNorm(m2); for(size_t j = 0; j < m2; j++) colNorm(j) = dif.col(j).norm(); int r, c; double closest = colNorm.minCoeff(&r, &c); if(closest < tolClose){ minIndexPo(tracker) = r; minIndexErgodic(tracker) = i; minDis(tracker) = closest; minDifv.col(tracker++) = -dif.col(r); } } return std::make_tuple(minDifv.leftCols(tracker), minIndexErgodic.head(tracker), minIndexPo.head(tracker), minDis.head(tracker)); } std::pair<std::vector<int>, std::vector<int> > consecutiveWindow(const VectorXi &index, const int window){ const int n = index.size(); std::vector<int> start, dur; int pos = 0; while (pos < n-1) { int span = 0; for (size_t i = pos; i < n-1; i++) { // note i < n-1 if(index(i) == index(i+1)-1) span++; else break; } if(span >= window){ start.push_back(pos); dur.push_back(span); } if(span > 0) pos += span; else pos++; } return make_pair(start, dur); } vector<int> interp(KS &ks, const Ref<const MatrixXd> &ergodic, const MatrixXd &aa, const VectorXi &indx, double threashold){ const int n = ergodic.rows(); const int m = ergodic.cols(); const int n2 = aa.rows(); const int m2 = aa.cols(); assert(n2 == n); vector<int> filter; for (int i = 0; i < m; i++) { VectorXd x = aa.col(indx(i)); VectorXd velo = ks.veToSlice( ks.velocity(x), x ); VectorXd difv = ergodic.col(i) - x; double u = difv.dot(velo); if (fabs(u) / (velo.norm() * difv.norm()) < threashold ){ filter.push_back(i); } } return filter; } std::tuple<MatrixXd, VectorXi, VectorXi, VectorXd> minDistance(const MatrixXd &ergodic, const MatrixXd &aa, const double tolClose, const int window){ std::tuple<MatrixXd, VectorXi, VectorXi, VectorXd> min_distance = minDistance(ergodic, aa, tolClose); MatrixXd &minDifv = std::get<0>(min_distance); VectorXi &minIndexErgodic = std::get<1>(min_distance); VectorXi &minIndexPo = std::get<2>(min_distance); VectorXd &minDis = std::get<3>(min_distance); std::pair<std::vector<int>, std::vector<int> > consecutive = consecutiveWindow(minIndexErgodic, window); std::vector<int> &start = consecutive.first; std::vector<int> &dur = consecutive.second; int sum = 0; for (std::vector<int>::iterator i = dur.begin(); i != dur.end(); i++) { sum += *i; } MatrixXd minDifv2(minDifv.rows(), sum); VectorXi minIndexErgodic2(sum); VectorXi minIndexPo2(sum); VectorXd minDis2(sum); size_t pos = 0; for(size_t i = 0; i < dur.size(); i++){ minDifv2.middleCols(pos, dur[i]) = minDifv.middleCols(start[i], dur[i]); minIndexErgodic2.segment(pos, dur[i]) = minIndexErgodic.segment(start[i], dur[i]); minIndexPo2.segment(pos, dur[i]) = minIndexPo.segment(start[i], dur[i]); minDis2.segment(pos, dur[i]) = minDis.segment(start[i], dur[i]); pos += dur[i]; } return std::make_tuple(minDifv2, minIndexErgodic2, minIndexPo2, minDis2); } /** @brief * ve has dimension [N, M*trunc] */ MatrixXd veTrunc(const MatrixXd ve, const int pos, const int trunc = 0){ int Trunc = trunc; if(trunc == 0) Trunc = ve.rows(); const int N = ve.rows(); const int M = ve.cols() / Trunc; assert(ve.cols()%M == 0); MatrixXd newVe(N, (Trunc-1)*M); for(size_t i = 0; i < M; i++){ newVe.middleCols(i*(Trunc-1), pos) = ve.middleCols(i*Trunc, pos); newVe.middleCols(i*(Trunc-1)+pos, Trunc-1-pos) = ve.middleCols(i*Trunc+pos+1, Trunc-1-pos); } return newVe; } /** @brief calculate the angle between difference vectors and the subspaces spanned * by Flqouet vectors. * * @param[in] subsp number of Floquet vectors to span subspace * * @note subsp does not stores the indices of the subspace cut. */ MatrixXd difAngle(const MatrixXd &minDifv, const VectorXi &minIx, const VectorXi &subsp, const MatrixXd &ve_trunc, const int truncN){ assert(minDifv.cols() == minIx.size()); const int N = minDifv.rows(); const int M = minDifv.cols(); const int M2 = subsp.size(); MatrixXd angle(M2, M); for(size_t i = 0; i < M; i++){ int ix = minIx(i); for(size_t j = 0; j < M2; j++) // calculate the angle between the different vector and Floquet subspace. angle(j, i) = angleSubspace(ve_trunc.middleCols(truncN*ix, subsp(j)), minDifv.col(i)); // angle(j, i) = angleSpaceVector(ve_trunc.middleCols(truncN*ix, subsp(j)), // minDifv.col(i)); } return angle; } int main(){ cout.precision(16); const int Nks = 64; const int N = Nks - 2; const int N64 = 64; const int N62 = 62; const double L = 22; switch (4) { case 1: // small test for angle calculation. { MatrixXi subspDim(4,3); subspDim << 3, 0, 0, 3, 7, 8, 4, 8, 9, 4, 29, 29; // (0-6,7-29), (0-7,8-29), (0-8,9-29) cout << subspDim << endl; string fileName("../data/ks22h02t100"); ReadKS readks(fileName+".h5", fileName+"E.h5", fileName+"EV.h5"); string ppType("rpo"); int ppId = 1; std::pair<MatrixXd, MatrixXi> ang = anglePO(readks, ppType, ppId, subspDim); cout << ang.second << endl; ofstream file; file.precision(16); file.open("good.txt", ios::trunc); file << ang.first << endl; file.close(); break; } case 2: // calculate the angle, output to files. // This the MAIN experiments I am doing. { ///////////////////////////////////////////////////////////////// string fileName("../data/ks22h02t120"); string ppType("rpo"); string spType("vector"); string folder("./case4/"); ///////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////// // all kinds of IF statements int NN; if(fileName.compare("../data/ks22h02t120") ==0 ){ if(ppType.compare("ppo") == 0) NN = 840; // number of ppo else NN = 834; // number of rpo } else if(fileName.compare("../data/ks22h02t100") ==0 ) { if(ppType.compare("ppo") == 0) NN = 240; // number of ppo else NN = 239; // number of rpo } else{ printf("invalid file name !\n"); } MatrixXi subspDim(4,29); if(spType.compare("vector") == 0) for (size_t i = 0; i < 29; i++) subspDim.col(i) << i, i, i+1, i+1; else if(spType.compare("space") == 0) for (size_t i = 0; i < 29; i++) subspDim.col(i) << 0, i, i+1, 29; else { printf("invalid spType.\n"); } const int M = subspDim.cols(); ofstream file[M]; string angName("ang"); for(size_t i = 0; i < M; i++){ file[i].open(folder + angName + to_string(i) + ".txt", ios::trunc); file[i].precision(16); } ///////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////// ReadKS readks(fileName+".h5", fileName+"E.h5", fileName+"EV.h5"); // get the index of POs which converge. MatrixXi status = readks.checkExistEV(ppType, NN); for(size_t i = 0; i < NN; i++) { if( 1 == status(i,0) ){ int ppId = i + 1; printf("========= i = %zd ========\n", i); std::pair<MatrixXd, MatrixXi> tmp = anglePO(readks, ppType, ppId, subspDim); MatrixXd &ang = tmp.first; MatrixXi &boundStrict = tmp.second; cout << boundStrict << endl; // check whether there are degeneracy MatrixXi pro = boundStrict.row(0).array() * boundStrict.row(1).array() * boundStrict.row(2).array() * boundStrict.row(3).array(); for(size_t i = 0; i < M; i++){ // only keep the orbits whose 4 bounds are not degenerate if(pro(0, i) == 1) file[i] << ang.col(i) << endl; } } } for(size_t i = 0; i < M; i++) file[i].close(); ///////////////////////////////////////////////////////////////// break; } case 3 : // small test of the covariant vector projection process. { string fileName("../data/ks22h02t100"); string ppType("ppo"); const int ppId = 1; const int gTpos = 3; ReadKS readks(fileName+".h5", fileName+"E.h5", fileName+"EV.h5"); std::tuple<ArrayXd, double, double, double, double> pp = readks.readKSinit(ppType, ppId); ArrayXd &a = get<0>(pp); double T = get<1>(pp); int nstp = (int)get<2>(pp); double r = get<3>(pp); double s = get<4>(pp); MatrixXd eigVals = readks.readKSe(ppType, ppId); MatrixXd eigVecs = readks.readKSve(ppType, ppId); KS ks(Nks, T/nstp, L); ArrayXXd aa = ks.intg(a, nstp); std::pair<MatrixXd, VectorXd> tmp = ks.orbitToSlice(aa); MatrixXd &aaHat = tmp.first; MatrixXd veSlice = ks.veToSliceAll( eigVecs, aa.leftCols(aa.cols()-1) ); MatrixXd ve_trunc = veTrunc(veSlice, gTpos); cout << veSlice.middleCols(2,3) << endl << endl; cout << veSlice.middleCols(2+30*100,3) << endl << endl; cout << ve_trunc.middleCols(2,2) << endl << endl; cout << ve_trunc.middleCols(2+29*100,2) << endl << endl; break; } case 4 : // ergodic orbit approache rpo/ppo // fields need to be changed: ppType ppId, nqr, gTpos, sT, folder { //////////////////////////////////////////////////////////// // set up the system const int Nks = 64; const int N = Nks - 2; string fileName("../data/ks22h001t120x64"); string ppType("ppo"); const int ppId = 4; const int nqr = 5; const int Trunc = 30; const int gTpos = 3; // position of group tangent marginal vector VectorXi subsp(7); subsp << 3, 4, 5, 6, 7, 8, 9; // subspace indices. //////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////// // prepare orbit, vectors ReadKS readks(fileName+".h5", fileName+"E.h5", fileName+"EV.h5", N, Nks); // ReadKS readks(fileName+".h5", fileName+"E.h5", fileName+"EV.h5"); std::tuple<ArrayXd, double, double, double, double> pp = readks.readKSinit(ppType, ppId); ArrayXd &a = get<0>(pp); double T = get<1>(pp); int nstp = (int)get<2>(pp); double r = get<3>(pp); double s = get<4>(pp); MatrixXd eigVals = readks.readKSe(ppType, ppId); MatrixXd eigVecs = readks.readKSve(ppType, ppId); KS ks(Nks, T/nstp, L); ArrayXXd aa = ks.intg(a, nstp, nqr); ArrayXXd aaWhole, eigVecsWhole; if(ppType.compare("ppo") == 0) { aaWhole = ks.half2whole(aa.leftCols(aa.cols()-1)); eigVecsWhole = ks.half2whole(eigVecs); // this is correct. Think carefully. } else { aaWhole = aa.leftCols(aa.cols()-1); // one less eigVecsWhole = eigVecs; } assert(aaWhole.cols() == eigVecsWhole.cols()); std::pair<MatrixXd, VectorXd> tmp = ks.orbitToSlice(aaWhole); MatrixXd &aaHat = tmp.first; // note here aa has one more column the the Floquet vectors MatrixXd veSlice = ks.veToSliceAll( eigVecsWhole, aaWhole, Trunc); MatrixXd ve_trunc = veTrunc(veSlice, gTpos, Trunc); //////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////// // choose experiment parameters & do experiment const double h = 0.1; const double sT = 30; const double tolClose = 0.1; const int MaxSteps = floor(2000/h); const int MaxT = 10000; string folder = "./case4ppo4x5sT30/"; KS ks2(Nks, h, L); srand(time(NULL)); ArrayXd a0(0.1 * ArrayXd::Random(N)); const int fileNum = 5; string strf[fileNum] = {"angle", "dis", "difv", "indexPo", "No"}; ofstream saveName[fileNum]; for (size_t i = 0; i < fileNum; i++) { saveName[i].open(folder + strf[i], ios::trunc); saveName[i].precision(16); } int accum = 0; for(size_t i = 0; i < MaxT; i++){ std::cout << "********** i = " << i << "**********"<< std::endl; ArrayXXd ergodic = ks2.intg(a0, MaxSteps); a0 = ergodic.rightCols(1); std::pair<MatrixXd, VectorXd> tmp = ks2.orbitToSlice(ergodic); MatrixXd &ergodicHat = tmp.first; // be careful about the size of aaHat std::tuple<MatrixXd, VectorXi, VectorXi, VectorXd> dis = minDistance(ergodicHat, aaHat, tolClose, (int)(sT/h) ); MatrixXd &minDifv = std::get<0>(dis); VectorXi &minIndexErgodic = std::get<1>(dis); VectorXi &minIndexPo = std::get<2>(dis); VectorXd &minDis = std::get<3>(dis); MatrixXd angle = difAngle(minDifv, minIndexPo, subsp, ve_trunc, Trunc-1); if(angle.cols() > 0) printf("angle size = %ld x %ld, instance %d \n", angle.rows(), angle.cols(), ++accum); if(angle.cols() != 0) { saveName[0] << angle.transpose() << endl; saveName[1] << minDis << std::endl; saveName[2] << minDifv.transpose() << std::endl; saveName[3] << minIndexPo << std::endl; saveName[4] << angle.cols() << std::endl; } } for (size_t i = 0; i < fileNum; i++) saveName[i].close(); //////////////////////////////////////////////////////////// break; } case 5: // test the projection of subspaces. // not using FVs, but OVs. OVs is rotated to slice. { ////////////////////////////////////////////////// string fileName("../data/ks22h001t120x64"); string ppType("ppo"); const int ppId = 4; VectorXi subsp(10); subsp << 4, 5, 6, 7, 8, 9, 10, 12, 16, 28; ////////////////////////////////////////////////// // prepare orbit, vectors ReadKS readks(fileName+".h5", fileName+"E.h5", fileName+"EV.h5", N, Nks); std::tuple<ArrayXd, double, double, double, double> pp = readks.readKSinit(ppType, ppId); ArrayXd &a = get<0>(pp); double T = get<1>(pp); int nstp = (int)get<2>(pp); double r = get<3>(pp); double s = get<4>(pp); KS ks(Nks, T/nstp, L); pair<ArrayXXd, ArrayXXd> tmp = ks.intgj(a, nstp, 5, 5); ArrayXXd aaWhole; if(ppType.compare("ppo") == 0) aaWhole = ks.half2whole(tmp.first.leftCols(tmp.first.cols()-1)); else aaWhole = tmp.first; MatrixXd daa = tmp.second; std::pair<MatrixXd, VectorXd> tmp2 = ks.orbitToSlice(aaWhole); MatrixXd &aaHat = tmp2.first; VectorXd &theta = tmp2.second; PED ped; ped.reverseOrderSize(daa); // reverse order. if(ppType.compare("ppo") == 0) daa.leftCols(N) = ks.reflect(daa.leftCols(N)); // R*J for ppo else // R*J for rpo daa.leftCols(N) = ks.rotate(daa.leftCols(N), -s*2*M_PI/L); pair<MatrixXd, vector<int> > psd = ped.PerSchur(daa, 1000, 1e-15, false); MatrixXd &Q1 = psd.first; int n1 = Q1.rows(); int m1 = Q1.cols() / n1; MatrixXd Q2(n1, n1*m1); for(size_t i = 0; i < m1; i++) Q2.middleCols(i*n1, n1) = Q1.middleCols(n1*((m1-i)%m1), n1); MatrixXd Q; if(ppType.compare("ppo") == 0) Q= ks.half2whole(Q2); else // R*J for rpo Q = Q2; int n = Q.rows(); int m = Q.cols() / n; MatrixXd rQ(n, m*n); for (size_t i = 0; i < m; i++) { rQ.middleCols(i*n, n) = ks.rotate( Q.middleCols(i*n, n), -theta(i) ); } //////////////////////////////////////////////////////////// // choose experiment parameters & do experiment const double h = 0.1; const double sT = 50; const double tolClose = 0.1; const int MaxSteps = floor(2000/h); const int MaxT = 10000; string folder = "./case7/"; KS ks2(Nks, h, L); srand(time(NULL)); ArrayXd a0(0.1 * ArrayXd::Random(N)); const int fileNum = 5; string strf[fileNum] = {"angle", "dis", "difv", "indexPo", "No"}; ofstream saveName[fileNum]; for (size_t i = 0; i < fileNum; i++) { saveName[i].open(folder + strf[i], ios::trunc); saveName[i].precision(16); } for(size_t i = 0; i < MaxT; i++){ std::cout << "********** i = " << i << "**********"<< std::endl; ArrayXXd ergodic = ks2.intg(a0, MaxSteps); a0 = ergodic.rightCols(1); std::pair<MatrixXd, VectorXd> tmp = ks2.orbitToSlice(ergodic); MatrixXd &ergodicHat = tmp.first; // be careful about the size of aaHat std::tuple<MatrixXd, VectorXi, VectorXi, VectorXd> dis = minDistance(ergodicHat, aaHat, tolClose, (int)(sT/h) ); MatrixXd &minDifv = std::get<0>(dis); VectorXi &minIndexErgodic = std::get<1>(dis); VectorXi &minIndexPo = std::get<2>(dis); VectorXd &minDis = std::get<3>(dis); MatrixXd angle = difAngle(minDifv, minIndexPo, subsp, rQ, N); if(angle.cols() > 0) printf("angle size = %ld x %ld\n", angle.rows(), angle.cols()); if(angle.cols() != 0) { saveName[0] << angle.transpose() << endl; saveName[1] << minDis << std::endl; saveName[2] << minDifv.transpose() << std::endl; saveName[3] << minIndexPo << std::endl; saveName[4] << angle.cols() << std::endl; } } for (size_t i = 0; i < fileNum; i++) saveName[i].close(); //////////////////////////////////////////////////////////// break; } case 6: // test the projection of subspaces. // not using FVs, but OVs. Slice is not used, // Experiments are conducted on the full state space. { ////////////////////////////////////////////////// string fileName("../data/ks22h02t100"); string ppType("ppo"); const int ppId = 1; VectorXi subsp(10); subsp << 4, 5, 6, 7, 8, 9, 10, 12, 16, 28; ////////////////////////////////////////////////// // prepare orbit, vectors ReadKS readks(fileName+".h5", fileName+"E.h5", fileName+"EV.h5"); std::tuple<ArrayXd, double, double, double, double> pp = readks.readKSinit(ppType, ppId); ArrayXd &a = get<0>(pp); double T = get<1>(pp); int nstp = (int)get<2>(pp); double r = get<3>(pp); double s = get<4>(pp); KS ks(Nks, T/nstp, L); pair<ArrayXXd, ArrayXXd> tmp = ks.intgj(a, nstp); ArrayXXd aaWhole; if(ppType.compare("ppo") == 0) aaWhole = ks.half2whole(tmp.first.leftCols(tmp.first.cols()-1)); else aaWhole = tmp.first; MatrixXd daa = tmp.second; PED ped; ped.reverseOrderSize(daa); // reverse order. if(ppType.compare("ppo") == 0) daa.leftCols(N) = ks.reflect(daa.leftCols(N)); // R*J for ppo else // R*J for rpo daa.leftCols(N) = ks.rotate(daa.leftCols(N), -s*2*M_PI/L); pair<MatrixXd, vector<int> > psd = ped.PerSchur(daa, 10000, 1e-15, false); MatrixXd &Q1 = psd.first; int n1 = Q1.rows(); int m1 = Q1.cols() / n1; MatrixXd Q2(n1, n1*m1); for(size_t i = 0; i < m1; i++) Q2.middleCols(i*n1, n1) = Q1.middleCols(n1*((m1-i)%m1), n1); MatrixXd Q; if(ppType.compare("ppo") == 0) Q= ks.half2whole(Q2); else // R*J for rpo Q = Q2; //////////////////////////////////////////////////////////// // choose experiment parameters & do experiment const double h = 0.1; const double sT = 20; const double tolClose = 0.1; const int MaxSteps = floor(2000/h); const int MaxT = 100000; string folder = "./case2/"; KS ks2(Nks, h, L); srand(time(NULL)); ArrayXd a0(0.1 * ArrayXd::Random(N)); const int fileNum = 5; string strf[fileNum] = {"angle", "dis", "difv", "indexPo", "No"}; ofstream saveName[fileNum]; for (size_t i = 0; i < fileNum; i++) { saveName[i].open(folder + strf[i], ios::trunc); saveName[i].precision(16); } for(size_t i = 0; i < MaxT; i++){ std::cout << "********** i = " << i << "**********"<< std::endl; ArrayXXd ergodic = ks2.intg(a0, MaxSteps); a0 = ergodic.rightCols(1); // be careful about the size of aaHat std::tuple<MatrixXd, VectorXi, VectorXi, VectorXd> dis = minDistance(ergodic, aaWhole, tolClose, (int)(sT/h) ); MatrixXd &minDifv = std::get<0>(dis); VectorXi &minIndexErgodic = std::get<1>(dis); VectorXi &minIndexPo = std::get<2>(dis); VectorXd &minDis = std::get<3>(dis); MatrixXd angle = difAngle(minDifv, minIndexPo, subsp, Q, N); if(angle.cols() > 0) printf("angle size = %ld x %ld\n", angle.rows(), angle.cols()); if(angle.cols() != 0) { saveName[0] << angle.transpose() << endl; saveName[1] << minDis << std::endl; saveName[2] << minDifv.transpose() << std::endl; saveName[3] << minIndexPo << std::endl; saveName[4] << angle.cols() << std::endl; } } for (size_t i = 0; i < fileNum; i++) saveName[i].close(); //////////////////////////////////////////////////////////// break; } case 7: // test rotated initial condition for N = 64 // after rotation, the result looks good. { string fileName("../data/ks22h001t120x64"); string ppType("ppo"); const int ppId = 13; ReadKS readks(fileName+".h5", fileName+"E.h5", fileName+"EV.h5", N62, N64); std::tuple<ArrayXd, double, double, double, double> pp = readks.readKSinit(ppType, ppId); ArrayXd &a = get<0>(pp); double T = get<1>(pp); int nstp = (int)get<2>(pp); double r = get<3>(pp); double s = get<4>(pp); const int div = 1; KS ks(N64, T/nstp/div, L); MatrixXd aa = ks.intg(a, 2*div*nstp); MatrixXd aaHat = ks.orbitToSlice(aa).first; cout << (aa.rightCols(1) - aa.col(0)).norm() << endl; MatrixXd paa = ks.intg(ks.rotate(aa.col(0), 1), 2*div*nstp); std::cout << (paa.rightCols(1) - paa.col(0)).norm() << std::endl; break; } case 8: // test the linear relation of OVs // the result is bad 1e-5. { ////////////////////////////////////////////////// #if 0 string fileName("../data/ks22h02t100"); string ppType("rpo"); const int ppId = 3; ReadKS readks(fileName+".h5", fileName+"E.h5", fileName+"EV.h5"); std::tuple<ArrayXd, double, double, double, double> pp = readks.readKSinit(ppType, ppId); ArrayXd &a = get<0>(pp); double T = get<1>(pp); int nstp = (int)get<2>(pp); double r = get<3>(pp); double s = get<4>(pp); KS ks(Nks, T/nstp, L); # endif string fileName("../data/ks22h001t120x64"); string ppType("rpo"); const int ppId = 8; ReadKS readks(fileName+".h5", fileName+".h5", fileName+".h5", N62, N64); std::tuple<ArrayXd, double, double, double, double> pp = readks.readKSinit(ppType, ppId); ArrayXd &a = get<0>(pp); double T = get<1>(pp); int nstp = (int)get<2>(pp); double r = get<3>(pp); double s = get<4>(pp); KS ks(N64, T/nstp, L); ////////////////////////////////////////////////// pair<ArrayXXd, ArrayXXd> tmp = ks.intgj(a, nstp, 5, 5); MatrixXd aa = tmp.first; MatrixXd daa = tmp.second; PED ped; ped.reverseOrderSize(daa); // reverse order. if(ppType.compare("ppo") == 0) daa.leftCols(N) = ks.reflect(daa.leftCols(N)); // R*J for ppo else // R*J for rpo daa.leftCols(N) = ks.rotate(daa.leftCols(N), -s*2*M_PI/L); switch (2) { case 1: { pair<MatrixXd, vector<int> > psd = ped.PerSchur(daa, 3000, 1e-15, true); MatrixXd &Q1 = psd.first; int n1 = Q1.rows(); int m1 = Q1.cols() / n1; MatrixXd Q2(n1*n1, m1); for(size_t i = 0; i < m1; i++) { MatrixXd tmp = Q1.middleCols(n1*((m1-i)%m1), n1); tmp.resize(n1*n1,1); Q2.col(i) = tmp; } MatrixXd Q = ks.veToSliceAll( Q2, aa.leftCols(aa.cols()-1) ); cout << Q.rows() << 'x' << Q.cols() << endl; ColPivHouseholderQR<MatrixXd> qr(Q.leftCols(5)); MatrixXd R = qr.matrixQR().triangularView<Upper>(); cout << R.rows() << 'x' << R.cols() << endl; cout << R.topRows<5>() << endl; break; } case 2 : { const int N = daa.rows(); const int M = daa.cols() / N; MatrixXd J(N, N*M); for (size_t i = 0; i < M; i++) { J.middleCols(i*N, N) = daa.middleCols((M-i-1)*N, N); } HouseholderQR<MatrixXd> qr; MatrixXd Q(MatrixXd::Identity(N,N)); MatrixXd Qp(N, N); for (size_t i = 0; i < 3000; i++) { if(i%10 == 0) cout << i << endl; for (size_t i = 0; i < M; i++) { Qp = J.middleCols(i*N, N) * Q; qr.compute(Qp); Q = qr.householderQ(); } } Q.resize(N*N,1); MatrixXd rQ = ks.veToSliceAll(Q, aa.col(0)); qr.compute(rQ.leftCols(5)); MatrixXd R = qr.matrixQR().triangularView<Upper>(); cout << R.rows() << 'x' << R.cols() << endl; cout << R.topRows<5>() << endl; } } break; } case 9 : // test the 32 modes initial condition { string fileName("../data/ks22h001t120x64"); string ppType("ppo"); const int ppId = 1; ReadKS readks(fileName+".h5", fileName+".h5", fileName+".h5", N62, N64); std::tuple<ArrayXd, double, double, double, double> pp = readks.readKSinit(ppType, ppId); ArrayXd &a = get<0>(pp); double T = get<1>(pp); int nstp = (int)get<2>(pp); double r = get<3>(pp); double s = get<4>(pp); KS ks(N64, T/nstp, L); MatrixXd daa = ks.intgj(a, nstp, 10, 10).second; PED ped ; ped.reverseOrderSize(daa); daa.leftCols(N) = ks.reflect(daa.leftCols(N)); MatrixXd eigVals = ped.EigVals(daa, 3000, 1e-15, true); MatrixXd FloquetE(eigVals.rows(), eigVals.cols()); FloquetE << eigVals.col(0).array()/T, eigVals.rightCols(2); cout << FloquetE << endl; break; } case 10: // test the spacing in 32 modes orbit { string fileName("../data/ks22h001t50x64"); string ppType("rpo"); const int ppId = 8; ReadKS readks(fileName+".h5", fileName+".h5", fileName+".h5", N62, N64); std::tuple<ArrayXd, double, double, double, double> pp = readks.readKSinit(ppType, ppId); ArrayXd &a = get<0>(pp); double T = get<1>(pp); int nstp = (int)get<2>(pp); double r = get<3>(pp); double s = get<4>(pp); KS ks(N64, T/nstp, L); MatrixXd aa = ks.intg(a, nstp, 10); ArrayXXd aaWhole; if(ppType.compare("ppo") == 0) { aaWhole = ks.half2whole(aa.leftCols(aa.cols()-1)); } else { aaWhole = aa.leftCols(aa.cols()-1); // one less } MatrixXd aaReduced = ks.orbitToSlice(aaWhole).first; // cout << aa.rows() << 'x' << aa.cols() << endl; VectorXd dis(aaReduced.cols()); for (int i = 0; i < dis.size(); i++) { dis(i) = (aaReduced.col( (i+1)%dis.size() )-aaReduced.col(i)).norm(); } cout << dis << endl; break; } case 11: // to try Predrag's suggestions { string folder("../data/ErgodicApproch/cases32modes/case4ppo4x10/"); string ppType("ppo"); const int ppId = 4; const int N = 62; const int nqr = 10; // read files from disk const int fileNum = 4; string strf[fileNum] = {"No", "dis", "difv", "indexPo"}; ifstream saveName[fileNum]; for (int i = 0; i < fileNum; i++) saveName[i].open(folder+strf[i]); string line; vector<int> No; while( getline(saveName[0], line) ) No.push_back(stoi(line)); int M = accumulate(No.begin(), No.end(), 0); VectorXd dis(M); VectorXi indexPo(M); MatrixXd difv(N, M); for (int i = 0; i < M; i++) { getline(saveName[1], line); dis(i) = stod(line); getline(saveName[2], line); size_t sz = 0; for (int j = 0; j < N; j++){ size_t tmp; difv(j, i) = stod(line.substr(sz), &tmp); sz += tmp; } getline(saveName[3], line); indexPo(i) = stoi(line); } for (int i = 0; i < fileNum; i++) saveName[i].close(); string fileName("../data/ks22h001t50x64.h5"); ReadKS readks(fileName, fileName, fileName, N, N+2); std::tuple<ArrayXd, double, double, double, double> pp = readks.readKSinit(ppType, ppId); ArrayXd &a = get<0>(pp); double T = get<1>(pp); int nstp = (int)get<2>(pp); double r = get<3>(pp); double s = get<4>(pp); KS ks(N+2, T/nstp, L); ArrayXXd aa = ks.intg(a, nstp, nqr); ArrayXXd aaWhole; if(ppType.compare("ppo") == 0) { aaWhole = ks.half2whole(aa.leftCols(aa.cols()-1)); } else { aaWhole = aa.leftCols(aa.cols()-1); // one less } MatrixXd aaHat = ks.orbitToSlice(aaWhole).first; MatrixXd ergodicHat(N, M); for (int i = 0; i < M; i++) { ergodicHat.col(i) = aaHat.col(indexPo(i)) + difv.col(i); } //vector<int> filter = interp(ks, ergodicHat, aaHat, indexPo, 0.05); //for (int i = 0; i < filter.size(); i++) cout << filter[i] << endl; // cout << M << endl; cout << aaHat << endl; break; } case 12: { string fileName("../data/ks22h001t120x64"); string ppType("ppo"); const int ppId = 1; const int nqr = 5; const int Trunc = 30; const int gTpos = 3; //////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////// // prepare orbit, vectors const int Nks = 64; const int N = Nks - 2; ReadKS readks(fileName+".h5", fileName+"E.h5", fileName+"EV.h5", N, Nks); std::tuple<ArrayXd, double, double, double, double> pp = readks.readKSinit(ppType, ppId); ArrayXd &a = get<0>(pp); double T = get<1>(pp); int nstp = (int)get<2>(pp); double r = get<3>(pp); double s = get<4>(pp); MatrixXd eigVals = readks.readKSe(ppType, ppId); MatrixXd eigVecs = readks.readKSve(ppType, ppId); // printf("%ld x %ld\n", eigVecs.rows(), eigVecs.cols()); assert(N * Trunc == eigVecs.rows()); const int M = eigVecs.cols(); VectorXd vol = VectorXd::Zero(Trunc); for (int i = 0; i < M; i++) { MatrixXd v = eigVecs.col(i); v.resize(N, Trunc); for (int j = 0; j < Trunc; j++) { double nor = v.col(j).norm(); v.col(j) = v.col(j) / nor; } for (int j = 1; j < Trunc+1; j++) { MatrixXd A = v.leftCols(j).transpose(); MatrixXd B = v.leftCols(j); double det = (A*B).determinant(); // if(i == 500) cout << sqrt(det) << endl; vol(j-1) = vol(j-1) + sqrt(det); } } vol = vol.array() / M; cout << vol << endl; KS ks(Nks, T/nstp, L); ArrayXXd aa = ks.intg(a, nstp, nqr); ArrayXXd aaWhole, eigVecsWhole; if(ppType.compare("ppo") == 0) { aaWhole = ks.half2whole(aa.leftCols(aa.cols()-1)); eigVecsWhole = ks.half2whole(eigVecs); // this is correct. Think carefully. } else { aaWhole = aa.leftCols(aa.cols()-1); // one less eigVecsWhole = eigVecs; } assert(aaWhole.cols() == eigVecsWhole.cols()); std::pair<MatrixXd, VectorXd> tmp = ks.orbitToSlice(aaWhole); MatrixXd &aaHat = tmp.first; // note here aa has one more column the the Floquet vectors MatrixXd veSlice = ks.veToSliceAll( eigVecsWhole, aaWhole, Trunc); MatrixXd ve_trunc = veTrunc(veSlice, gTpos, Trunc); break; } default: { printf("please indicate the index of problem !\n"); } } return 0; } <file_sep>#ifndef MYBOOSTPYTHON_H #define MYBOOSTPYTHON_H #include <boost/python.hpp> #include <boost/numpy.hpp> #include <Eigen/Dense> using namespace std; using namespace Eigen; namespace bp = boost::python; namespace bn = boost::numpy; typedef std::complex<double> dcp; // ============================================================ /* get the dimension of an array */ inline void getDims(bn::ndarray x, int &m, int &n){ if(x.get_nd() == 1){ m = 1; n = x.shape(0); } else { m = x.shape(0); n = x.shape(1); } } /* * @brief used to copy content in Eigen array to boost.numpy array. * * Only work for double array/matrix */ template<class MyAry = ArrayXXd, class MyType = double> bn::ndarray copy2bn(const Ref<const MyAry> &x){ int m = x.cols(); int n = x.rows(); Py_intptr_t dims[2]; int ndim; if(m == 1){ ndim = 1; dims[0] = n; } else { ndim = 2; dims[0] = m; dims[1] = n; } bn::ndarray px = bn::empty(ndim, dims, bn::dtype::get_builtin<MyType>()); memcpy((void*)px.get_data(), (void*)x.data(), sizeof(MyType) * m * n); return px; } /* non-template function overloading for real matrix */ inline bn::ndarray copy2bn(const Ref<const ArrayXXd> &x) { return copy2bn<ArrayXXd, double>(x); } /* non-template function overloading for imaginary matrix */ inline bn::ndarray copy2bnc(const Ref<const ArrayXXcd> &x) { return copy2bn<ArrayXXcd, dcp>(x); } /** * @brief std::vector to bp::list */ template <class T> inline bp::list toList(std::vector<T> vector) { typename std::vector<T>::iterator iter; bp::list list; for (iter = vector.begin(); iter != vector.end(); ++iter) { list.append(*iter); } return list; } #endif /* MYBOOSTPYTHON_H */ <file_sep>#include <boost/python.hpp> #include <boost/numpy.hpp> #include <Eigen/Dense> #include <cstdio> #include "CQCGL2d.hpp" #include "myBoostPython.hpp" using namespace std; using namespace Eigen; namespace bp = boost::python; namespace bn = boost::numpy; ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// class pyCQCGL2d : public CQCGL2d { public: pyCQCGL2d(int N, int M, double dx, double dy, double Mu, double Dr, double Di, double Br, double Bi, double Gr, double Gi, int threadNum) : CQCGL2d(N, M, dx, dy, Mu, Dr, Di, Br, Bi, Gr, Gi, threadNum) {} pyCQCGL2d(int N, double dx, double Mu, double Dr, double Di, double Br, double Bi, double Gr, double Gi, int threadNum) : CQCGL2d(N, dx, Mu, Dr, Di, Br, Bi, Gr, Gi, threadNum) {} pyCQCGL2d(int N, int M, double dx, double dy, double b, double c, double dr, double di, int threadNum) : CQCGL2d(N, M, dx, dy, b, c, dr, di, threadNum) {} pyCQCGL2d(int N, double dx, double b, double c, double dr, double di, int threadNum) : CQCGL2d(N, dx, b, c, dr, di, threadNum) {} bn::ndarray PYTs(){ return copy2bn(Ts); } bn::ndarray PYlte(){ return copy2bn(lte); } bn::ndarray PYhs(){ return copy2bn(hs); } /* Kx */ bn::ndarray PYKx(){ return copy2bn(Kx); } /* Ky */ bn::ndarray PYKy(){ return copy2bn(Ky); } /* L */ bn::ndarray PYL(){ return copy2bnc(L); } /* wrap the integrator */ bn::ndarray PYintg(bn::ndarray a0, double h, int Nt, int skip_rate, bool doSaveDisk, string fileName){ int m, n; getDims(a0, m, n); Map<ArrayXXcd> tmpa((dcp*)a0.get_data(), n, m); return copy2bnc(intg(tmpa, h, Nt, skip_rate, doSaveDisk, fileName)); } bn::ndarray PYaintg(bn::ndarray a0, double h, double tend, int skip_rate, bool doSaveDisk, string fileName){ int m, n; getDims(a0, m, n); Map<ArrayXXcd> tmpa((dcp*)a0.get_data(), n, m); return copy2bnc(aintg(tmpa, h, tend, skip_rate, doSaveDisk, fileName)); } bn::ndarray PYintgv(bn::ndarray a0, bn::ndarray v0, double h, int Nt, int skip_rate, bool doSaveDisk, string fileName){ int m, n; getDims(a0, m, n); Map<ArrayXXcd> tmpa((dcp*)a0.get_data(), n, m); getDims(v0, m, n); Map<ArrayXXcd> tmpv((dcp*)v0.get_data(), n, m); return copy2bnc(intgv(tmpa, tmpv, h, Nt, skip_rate, doSaveDisk, fileName)); } bn::ndarray PYaintgv(bn::ndarray a0, bn::ndarray v0, double h, double tend, int skip_rate, bool doSaveDisk, string fileName){ int m, n; getDims(a0, m, n); Map<ArrayXXcd> tmpa((dcp*)a0.get_data(), n, m); getDims(v0, m, n); Map<ArrayXXcd> tmpv((dcp*)v0.get_data(), n, m); return copy2bnc(aintgv(tmpa, tmpv, h, tend, skip_rate, doSaveDisk, fileName)); } bn::ndarray PYFourier2Config(bn::ndarray aa){ int m, n; getDims(aa, m, n); Map<ArrayXXcd> tmpaa((dcp*)aa.get_data(), n, m); return copy2bnc( Fourier2Config(tmpaa) ); } bn::ndarray PYConfig2Fourier(bn::ndarray AA){ int m, n; getDims(AA, m, n); Map<ArrayXXcd> tmpAA((dcp*)AA.get_data(), n, m); return copy2bnc( Config2Fourier(tmpAA) ); } bn::ndarray PYvelocity(bn::ndarray a0){ int m, n; getDims(a0, m, n); Map<ArrayXXcd> tmpa((dcp*)a0.get_data(), n, m); return copy2bnc(velocity(tmpa)); } bn::ndarray PYvelocityReq(bn::ndarray a0, double wthx, double wthy, double wphi){ int m, n; getDims(a0, m, n); Map<ArrayXXcd> tmpa((dcp*)a0.get_data(), n, m); return copy2bnc(velocityReq(tmpa, wthx, wthy, wphi)); } bn::ndarray PYstab(bn::ndarray a0, bn::ndarray v0){ int m, n; getDims(a0, m, n); Map<ArrayXXcd> tmpa((dcp*)a0.get_data(), n, m); getDims(v0, m, n); Map<ArrayXXcd> tmpv((dcp*)v0.get_data(), n, m); return copy2bnc(stab(tmpa, tmpv)); } bn::ndarray PYstabReq(bn::ndarray a0, bn::ndarray v0, double wthx, double wthy, double wphi){ int m, n; getDims(a0, m, n); Map<ArrayXXcd> tmpa((dcp*)a0.get_data(), n, m); getDims(v0, m, n); Map<ArrayXXcd> tmpv((dcp*)v0.get_data(), n, m); return copy2bnc(stabReq(tmpa, tmpv, wthx, wthy, wphi)); } bn::ndarray PYrotate(bn::ndarray a0, int mode, double th1=0, double th2=0, double th3=0){ int m, n; getDims(a0, m, n); Map<ArrayXXcd> tmpa((dcp*)a0.get_data(), n, m); return copy2bnc( rotate(tmpa, mode, th1, th2, th3) ); } bn::ndarray PYrotate1(bn::ndarray a0, int mode, double th1, double th2){ return PYrotate(a0, mode, th1, th2); } bn::ndarray PYrotate2(bn::ndarray a0, int mode, double th1){ return PYrotate(a0, mode, th1); } bn::ndarray PYrotate3(bn::ndarray a0, int mode){ return PYrotate(a0, mode); } bn::ndarray PYtangent(bn::ndarray a0, int mode){ int m, n; getDims(a0, m, n); Map<ArrayXXcd> tmpa((dcp*)a0.get_data(), n, m); return copy2bnc( tangent(tmpa, mode) ); } #if 0 /* reflectVe */ bn::ndarray PYreflectVe(const bn::ndarray &veHat, const bn::ndarray &xHat){ int m, n; getDims(veHat, m, n); Map<MatrixXd> tmpveHat((double*)veHat.get_data(), n, m); int m2, n2; getDims(xHat, m2, n2); Map<ArrayXd> tmpxHat((double*)xHat.get_data(), n2*m2); return copy2bn( reflectVe(tmpveHat, tmpxHat) ); } /* reflectVeAll */ bn::ndarray PYreflectVeAll(const bn::ndarray &veHat, const bn::ndarray &aaHat, const int trunc){ int m, n; getDims(veHat, m, n); Map<MatrixXd> tmpveHat((double*)veHat.get_data(), n, m); int m2, n2; getDims(aaHat, m2, n2); Map<ArrayXd> tmpaaHat((double*)aaHat.get_data(), n2, m2); return copy2bn( reflectVeAll(tmpveHat, tmpaaHat, trunc) ); } /* ve2slice */ bn::ndarray PYve2slice(bn::ndarray ve, bn::ndarray x){ int m, n; getDims(ve, m, n); int m2, n2; getDims(x, m2, n2); Map<ArrayXXd> tmpve((double*)ve.get_data(), n, m); Map<ArrayXd> tmpx((double*)x.get_data(), n2*m2); return copy2bn( ve2slice(tmpve, tmpx) ); } /* reduceAllSymmetries */ bp::tuple PYreduceAllSymmetries(const bn::ndarray &aa){ int m, n; getDims(aa, m, n); Map<ArrayXXd> tmpaa((double*)aa.get_data(), n, m); std::tuple<ArrayXXd, ArrayXd, ArrayXd> tmp = reduceAllSymmetries(tmpaa); return bp::make_tuple(copy2bn(std::get<0>(tmp)), copy2bn(std::get<1>(tmp)), copy2bn(std::get<2>(tmp))); } /* reduceVe */ bn::ndarray PYreduceVe(const bn::ndarray &ve, const bn::ndarray &x){ int m, n; getDims(ve, m, n); Map<ArrayXXd> tmpve((double*)ve.get_data(), n, m); int m2, n2; getDims(x, m2, n2); Map<ArrayXd> tmpx((double*)x.get_data(), n2*m2); return copy2bn(reduceVe(tmpve, tmpx)); } /* rotateOrbit */ bn::ndarray PYrotateOrbit(bn::ndarray aa, bn::ndarray th, bn::ndarray phi){ int m, n; getDims(aa, m, n); int m2, n2; getDims(th, m2, n2); int m4, n4; getDims(phi, m4, n4); Map<ArrayXXd> tmpaa((double*)aa.get_data(), n, m); Map<ArrayXd> tmpth((double*)th.get_data(), n2 * m2); Map<ArrayXd> tmpphi((double*)phi.get_data(), n4 * m4); return copy2bn( rotateOrbit(tmpaa, tmpth, tmpphi) ); } #endif }; //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// BOOST_PYTHON_MODULE(py_CQCGL2d) { bn::initialize(); // must provide the constructor bp::class_<CQCGL2d>("CQCGL2d", bp::init< int, double, double, double, double, double, int>()) ; bp::class_<pyCQCGL2d, bp::bases<CQCGL2d> >("pyCQCGL2d", bp::init< int, double, double, double, double, double, int>()) .def(bp::init<int, int, double, double, double, double, double, double, double, double, double, int>()) .def(bp::init<int, double, double, double, double, double, double, double, double, int>()) .def(bp::init<int, int, double, double, double, double, double, double, int>()) .def_readonly("N", &pyCQCGL2d::N) .def_readonly("M", &pyCQCGL2d::M) .def_readonly("dx", &pyCQCGL2d::dx) .def_readonly("dy", &pyCQCGL2d::dy) .def_readonly("Mu", &pyCQCGL2d::Mu) .def_readonly("Br", &pyCQCGL2d::Br) .def_readonly("Bi", &pyCQCGL2d::Bi) .def_readonly("Dr", &pyCQCGL2d::Dr) .def_readonly("Di", &pyCQCGL2d::Di) .def_readonly("Gr", &pyCQCGL2d::Gr) .def_readonly("Gi", &pyCQCGL2d::Gi) .def_readonly("Ne", &pyCQCGL2d::Ne) .def_readonly("Me", &pyCQCGL2d::Me) // .def_readonly("b", &pyCQCGL2d::b) // .def_readonly("c", &pyCQCGL2d::c) // .def_readonly("dr", &pyCQCGL2d::dr) // .def_readonly("di", &pyCQCGL2d::di) .def_readonly("Omega", &pyCQCGL2d::Omega) .def_readwrite("rtol", &pyCQCGL2d::rtol) .def_readwrite("nu", &pyCQCGL2d::nu) .def_readwrite("mumax", &pyCQCGL2d::mumax) .def_readwrite("mumin", &pyCQCGL2d::mumin) .def_readwrite("mue", &pyCQCGL2d::mue) .def_readwrite("muc", &pyCQCGL2d::muc) .def_readwrite("NCalCoe", &pyCQCGL2d::NCalCoe) .def_readwrite("NReject", &pyCQCGL2d::NReject) .def_readwrite("NCallF", &pyCQCGL2d::NCallF) .def_readwrite("NSteps", &pyCQCGL2d::NSteps) .def_readwrite("Method", &pyCQCGL2d::Method) .def_readwrite("constETDPrint", &pyCQCGL2d::constETDPrint) .def("Ts", &pyCQCGL2d::PYTs) .def("hs", &pyCQCGL2d::PYhs) .def("lte", &pyCQCGL2d::PYlte) .def("Kx", &pyCQCGL2d::PYKx) .def("Ky", &pyCQCGL2d::PYKy) .def("L", &pyCQCGL2d::PYL) .def("changeOmega", &pyCQCGL2d::changeOmega) .def("intg", &pyCQCGL2d::PYintg) .def("aintg", &pyCQCGL2d::PYaintg) .def("intgv", &pyCQCGL2d::PYintgv) .def("aintgv", &pyCQCGL2d::PYaintgv) .def("Fourier2Config", &pyCQCGL2d::PYFourier2Config) .def("Config2Fourier", &pyCQCGL2d::PYConfig2Fourier) .def("velocity", &pyCQCGL2d::PYvelocity) .def("velocityReq", &pyCQCGL2d::PYvelocityReq) .def("stab", &pyCQCGL2d::PYstab) .def("stabReq", &pyCQCGL2d::PYstabReq) .def("rotate", &pyCQCGL2d::PYrotate) .def("rotate", &pyCQCGL2d::PYrotate1) .def("rotate", &pyCQCGL2d::PYrotate2) .def("rotate", &pyCQCGL2d::PYrotate3) .def("tangent", &pyCQCGL2d::PYtangent) #if 0 .def("velocity", &pyCQCGL2d::PYvelocity) .def("velSlice", &pyCQCGL2d::PYvelSlice) .def("velPhase", &pyCQCGL2d::PYvelPhase) .def("velocityReq", &pyCQCGL2d::PYvelocityReq) .def("orbit2sliceWrap", &pyCQCGL2d::PYorbit2sliceWrap) .def("orbit2slice", &pyCQCGL2d::PYorbit2slice) .def("stab", &pyCQCGL2d::PYstab) .def("stabReq", &pyCQCGL2d::PYstabReq) .def("reflect", &pyCQCGL2d::PYreflect) .def("reduceReflection", &pyCQCGL2d::PYreduceReflection) .def("refGradMat", &pyCQCGL2d::PYrefGradMat) .def("reflectVe", &pyCQCGL2d::PYreflectVe) .def("reflectVeAll", &pyCQCGL2d::PYreflectVeAll) .def("ve2slice", &pyCQCGL2d::PYve2slice) .def("reduceAllSymmetries", &pyCQCGL2d::PYreduceAllSymmetries) .def("reduceVe", &pyCQCGL2d::PYreduceVe) .def("transRotate", &pyCQCGL2d::PYtransRotate) .def("transTangent", &pyCQCGL2d::PYtransTangent) .def("phaseRotate", &pyCQCGL2d::PYphaseRotate) .def("phaseTangent", &pyCQCGL2d::PYphaseTangent) .def("Rotate", &pyCQCGL2d::PYRotate) .def("rotateOrbit", &pyCQCGL2d::PYrotateOrbit) #endif ; } <file_sep>import numpy as np import matplotlib.pyplot as plt import h5py N = 256; f = h5py.File('/usr/local/home/xiong/svn/DOGS/blog/code/data/req.h5', 'r') a0 = f['/req1/a0'] taa = a0; taa = taa[::2]+1j*taa[1::2]; ia = np.fft.ifft(taa, axis=0) fig = plt.figure(figsize=(5,5)); ax = fig.add_subplot(111) ax.plot(np.linspace(0, 50, 256), abs(ia), 'c-', lw = 2.0) ax.plot(np.linspace(0, 50, 256), ia.real,'r-',lw = 1.0) ax.plot(np.linspace(0, 50, 256), ia.imag,'b-',lw = 1.0) ax.locator_params(nbins=5) plt.tight_layout(pad=0) plt.show() f.close() <file_sep>#include <iostream> #include "CQCGL2dDislin.hpp" using namespace denseRoutines; using namespace Eigen; using namespace std; ////////////////////////////////////////////////////////////////////// /** * Constructor of cubic quintic complex Ginzburg-Landau equation * A_t = -A + (1 + b*i) (A_{xx}+A_{yy}) + (1 + c*i) |A|^2 A - (dr + di*i) |A|^4 A */ CQCGL2dDislin::CQCGL2dDislin(int N, int M, double dx, double dy, double b, double c, double dr, double di, int threadNum) : CQCGL2d(N, M, dx, dy, b, c, dr, di, threadNum) { } CQCGL2dDislin::CQCGL2dDislin(int N, double dx, double b, double c, double dr, double di, int threadNum) : CQCGL2d(N, dx, b, c, dr, di, threadNum) { } CQCGL2dDislin::~CQCGL2dDislin(){} CQCGL2dDislin & CQCGL2dDislin::operator=(const CQCGL2dDislin &x){ return *this; } ////////////////////////////////////////////////////////////////////// // member functions // ////////////////////////////////////////////////////////////////////// /* should resize the field to make it insize the Z-coordinate */ void CQCGL2dDislin::initPlot(Dislin &g, const double Lx, const double Ly, const double Lz){ g.scrmod ("revers"); /* background color */ g.metafl ("cons"); /* file format */ g.winsiz(600, 425); /* window size */ g.clrmod("full"); /* 256 colors */ g.disini (); /* initialize */ g.winmod ("none"); /* not holding */ g.pagera (); /* border around page */ g.hwfont (); /* set hardware font if available */ g.name ("X", "x"); /* axis titles */ g.name ("Y", "y"); g.name ("|A|", "z"); // g.autres (N, N); /* number of data points */ g.axspos (500, 1900); /* position of axis */ g.ax3len (1600, 1600, 1600); /* axis length in plot coordinates */ g.widbar(50); /* color bar width */ // plot 3d axis system g.graf3 (0.0, Lx, 0.0, Lx, /* x : lower, upper, 1st label, label step */ 0.0, Ly, 0.0, Ly, 0.0, Lz, 0.0, Lz); // g.titlin ("|A|", 4); /* title up to 4 */ g.height (50); /* character height */ g.title (); /* plot title */ } /** * Note, can not use function Fourier2Config() because it will destroy the current state. * */ void CQCGL2dDislin::plot(Dislin &g, const double t, const double err){ F[0].ifft(); ArrayXXd absA = F[0].v2.abs(); double m = absA.maxCoeff(); absA = absA / m; char buffer[30]; sprintf(buffer, "%e", err); std::string s = "t: " + to_string(t) + "; max|A|: " + std::to_string(m) + "; LTE: " + std::string(buffer); g.erase(); g.titlin(s.c_str(), 4); g.title(); g.pagera (); g.crvmat((double *)absA.data(), M, N, 1, 1); g.sendbf(); } void CQCGL2dDislin::endPlot(Dislin &g){ g.disfin(); } /** * @brief Constant time step integrator */ void CQCGL2dDislin::constAnim(const ArrayXXcd &a0, const double h, const int skip_rate){ F[0].v1 = pad(a0); calCoe(h); Dislin g; initPlot(g, dx, dy, 1); plot(g, 0, 0); double t = 0; double du; int i = 0; while (true){ oneStep(du, true); t += h; F[0].v1 = F[4].v1; // update state if ( (i+1)%skip_rate == 0 ) { plot(g, t, du); } i = (i+1) % skip_rate; } endPlot(g); } /** * @brief time step adaptive integrator */ void CQCGL2dDislin::adaptAnim(const ArrayXXcd &a0, const double h0, const int skip_rate){ double h = h0; calCoe(h); F[0].v1 = pad(a0); Dislin g; initPlot(g, dx, dy, 1); plot(g, 0, 0); double t = 0; double du = 0; int i = 0; bool doChange, doAccept; bool TimeEnds = false; while( true ){ oneStep(du, true); double s = nu * std::pow(rtol/du, 1.0/4); double mu = adaptTs(doChange, doAccept, s); if (doAccept){ t += h; F[0].v1 = F[4].v1; if ( (i+1) % skip_rate == 0) plot(g, t, du); } if (doChange) { h *= mu; calCoe(h); } i = (i+1) % skip_rate; } endPlot(g); } <file_sep>#include <boost/python.hpp> #include <boost/numpy.hpp> #include <Eigen/Dense> #include <cstdio> #include "CqcglETD.hpp" #include "myBoostPython.hpp" using namespace std; using namespace Eigen; namespace bp = boost::python; namespace bn = boost::numpy; //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// class pyCqcglETD : public CqcglETD { public : pyCqcglETD(int N, double d, double W, double B, double C, double DR, double DI) : CqcglETD(N, d, W, B, C, DR, DI) {} bp::tuple PYetd(bn::ndarray a0, double tend, double h, int skip_rate, int method, bool adapt){ int m, n; getDims(a0, m, n); Map<VectorXd> tmpa0((double*)a0.get_data(), n * m); auto tmp = etd(tmpa0, tend, h, skip_rate, method, adapt); return bp::make_tuple(copy2bn(tmp.first), copy2bn(tmp.second) ); } bn::ndarray PYhs() { return copy2bn(etdrk4->hs); } bn::ndarray PYduu() { return copy2bn(etdrk4->duu); } bp::tuple PYetdParam(){ return bp::make_tuple(etdrk4->NCalCoe, etdrk4->NReject, etdrk4->NCallF, etdrk4->rtol ); } void PYsetRtol(double x){ etdrk4->rtol = x; } }; //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// BOOST_PYTHON_MODULE(py_cqcgl1d_threads) { bn::initialize(); bp::class_<CqcglETD>("CqcglETD", bp::init< int, double, double, double, double, double , double >()) ; bp::class_<pyCqcglETD, bp::bases<CqcglETD> >("pyCqcglETD", bp::init< int, double, double, double, double, double , double >()) .def_readonly("N", &pyCqcglETD::N) .def_readonly("d", &pyCqcglETD::d) .def("etdParam", &pyCqcglETD::PYetdParam) .def("setRtol", &pyCqcglETD::PYsetRtol) .def("etd", &pyCqcglETD::PYetd) .def("hs", &pyCqcglETD::PYhs) .def("duu", &pyCqcglETD::PYduu) ; } <file_sep>from personalFunctions import * ################################################## # 1d CQCGL related # ################################################## class CQCGLBase(): def __init__(self, cgl=None): self.cgl = cgl def toStr(self, Bi, Gi, index): if abs(Bi) < 1e-6: Bi = 0 if abs(Gi) < 1e-6: Gi = 0 return (format(Bi, '013.6f') + '/' + format(Gi, '013.6f') + '/' + str(index)) def checkExist(self, fileName, groupName): f = h5py.File(fileName, 'r') x = groupName in f f.close() return x def scanGroup(self, fileName, level): """ get all group names with a specific level """ f = h5py.File(fileName, 'r') gs = [] def parse(name, obj): if isinstance(obj, h5py.Group) and name.count('/') == level: gs.append(name) f.visititems(parse) return gs def checkVecSym(self, v): """ check the symmetry of a vector symmetric : a_k = a_{-k} anti-symmetric : a_k = - a_{-k} """ vr, vi = v.real, v.imag vr, vi = vr[::2] + 1j*vr[1::2], vi[::2] + 1j*vi[1::2] # pad a_0 at end vr, vi = np.append(vr, vr[0]), np.append(vi, vi[0]) sym_r = norm(vr - vr[::-1]) / norm(vr) sym_i = norm(vi - vi[::-1]) / norm(vi) anti_r = norm(vr + vr[::-1]) / norm(vr) anti_i = norm(vi + vi[::-1]) / norm(vi) return np.array([sym_r, sym_i, anti_r, anti_i]) class CQCGLplot(): def __init__(self, cgl=None): self.cgl = cgl def oneConfig(self, A, d=50, isFourier=True, size=[6, 5], labs=[r'$x$', r'$|A|$'], axisLabelSize=20, tickSize=None, save=False, name='out.png'): """ plot the configuration at one point or plot one eigen vector. Parameter ====== isFourier : is the input the Fourier modes of A. If it is, then we need back FFT. """ fig, ax = pl2d(size=size, labs=labs, axisLabelSize=axisLabelSize, tickSize=tickSize) if isFourier: A = self.cgl.Fourier2Config(A) Aamp = np.abs(A) ax.plot(np.linspace(0, d, Aamp.shape[0]), Aamp, lw=1.5) ax2d(fig, ax, save=save, name=name) def config(self, AA, ext, isFourier=True, tt=None, yls=None, timeMode=1, barTicks=[1, 2, 3], colortype='jet', percent='5%', size=[4, 5], labs=[r'$x$', r'$t$'], axisLabelSize=20, tickSize=None, save=False, name='out.png'): """ plot the color map of the states """ if tt is not None: if timeMode == 1: n = len(tt) ids = [bisect_left(tt, yl) for yl in yls] yts = [x / float(n) * ext[3] for x in ids] ax.set_yticks(yts) ax.set_yticklabels(yls) else: idx = self.sliceTime(tt) AA = AA[idx, :] if isFourier: AA = self.cgl.Fourier2Config(AA) Aamp = np.abs(AA) fig, ax = pl2d(size=size, labs=labs, axisLabelSize=axisLabelSize, tickSize=tickSize) im = ax.imshow(Aamp, cmap=plt.get_cmap(colortype), extent=ext, aspect='auto', origin='lower') ax.grid('on') dr = make_axes_locatable(ax) cax = dr.append_axes('right', size=percent, pad=0.05) plt.colorbar(im, cax=cax, ticks=barTicks) ax2d(fig, ax, save=save, name=name) def wire(self, AA, ext, isFourier=True, tt=None, skipRate=1, size=[8, 6], labs=[r'$x$', r'$t$', r'$|A|$'], c='k', axisLabelSize=20, tickSize=None, save=False, name='out.png'): """ plot the fence plot """ if isFourier: AA =self.cgl.Fourier2Config(AA) Aamp = np.abs(AA) Aamp = Aamp[::skipRate, :] rows, cols = Aamp.shape X = np.linspace(ext[0], ext[1], cols) if tt is None: Y = np.linspace(ext[2], ext[3], rows) else: Y = tt[::skipRate] fig, ax = pl3d(size=size, labs=labs, axisLabelSize=axisLabelSize, tickSize=tickSize) for i in range(Aamp.shape[0]): ax.plot(X, np.ones(cols) * Y[i], Aamp[i], c=c, alpha=1) ax3d(fig, ax, save=save, name=name) def sliceTime(self, t): n = len(t) hs = t[1:] - t[:-1] hmax = np.max(hs) idx = [0] s = 0 for i in range(n-1): s += hs[i] if(s >= hmax): idx.append(i) s = 0 return idx class CQCGLreq(CQCGLBase): """ relative equilibrium related """ def __init__(self, cgl=None): CQCGLBase.__init__(self, cgl) def read(self, fileName, groupName, sub=False, flag=0): """ sub : is subspace ? """ f = h5py.File(fileName, 'r') req = '/' + groupName + '/' a = f[req+'a'].value wth = f[req+'wth'].value if not sub else None wphi = f[req+'wphi'].value err = f[req+'err'].value if flag == 1: e = f[req+'er'].value + 1j*f[req+'ei'].value if flag == 2: e = f[req+'er'].value + 1j*f[req+'ei'].value v = f[req+'vr'].value + 1j*f[req+'vi'].value f.close() if flag == 0: return a, wth, wphi, err if flag == 1: return a, wth, wphi, err, e if flag == 2: return a, wth, wphi, err, e, v def readDi(self, fileName, di, index, flag=0): groupName = format(di, '.6f') + '/' + str(index) return self.read(fileName, groupName, flag) def eigReq(self, a0, wth0, wphi0, sub=False): if sub: stabMat = self.cgl.stabReq(a0, wphi0).T else: stabMat = self.cgl.stabReq(a0, wth0, wphi0).T e, v = LA.eig(stabMat) e, v = sortByReal(e, v) v = v.T.copy() return e, v def getAxes(self, fileName, Bi, Gi, index, flag): a, wth, wphi, err, e, v = self.read(fileName, self.toStr(Bi, Gi, index), flag=2) aH = self.cgl.orbit2slice(a, flag)[0] vrH = self.cgl.ve2slice(v.real.copy(), a, flag) viH = self.cgl.ve2slice(v.imag.copy(), a, flag) return e, aH, vrH + 1j*viH class CQCGLrpo(CQCGLBase): def __init__(self, cgl=None): CQCGLBase.__init__(self, cgl) def read(self, fileName, groupName, flag=0): """ read rpo. flag : = 0 : only load basic initial condition = 1 : also load multiplier = 2 : load multiplier and eigenvectors Example usage: >> rpo = CQCGLrpo(cgl) >> a0, T, nstp, th0, phi0, err = rpo.read(f, rpo.toStr(Bi, Gi, index), 0) """ f = h5py.File(fileName, 'r') req = '/' + groupName + '/' x = f[req+'x'].value T = f[req+'T'].value nstp = f[req+'nstp'].value th = f[req+'th'].value phi = f[req+'phi'].value err = f[req+'err'].value if flag == 1: e = f[req+'er'].value + 1j*f[req+'ei'].value if flag == 2: e = f[req+'er'].value + 1j*f[req+'ei'].value v = f[req+'v'].value f.close() if flag == 0: return x, T, nstp, th, phi, err elif flag == 1: return x, T, nstp, th, phi, err, e elif flag == 2: return x, T, nstp, th, phi, err, e, v else : print "invalid flag" def readAll(self, fileName, index, hasEV): f = h5py.File(fileName, 'r') gs = f.keys() f.close() xx = [] # all rpo dis = [] # all di for i in gs: di = float(i) dis.append(di) if hasEV: x = cqcglReadEVdi(fileName, di, index) else: x = cqcglReaddi(fileName, di, index) xx.append(x) return dis, xx def save(self, fileName, groupName, x, T, nstp, th, phi, err, e=None, v=None): """ save rpo. Example usage: >> rpo = CQCGLrpo(cgl) >> rpo.save(f, rpo.toStr(Bi, Gi, index), x, T, nstp, th, phi, err) """ f = h5py.File(fileName, 'a') rpo = f.create_group(groupName) rpo.create_dataset("x", data=x) rpo.create_dataset("T", data=T) rpo.create_dataset("nstp", data=nstp) rpo.create_dataset("th", data=th) rpo.create_dataset('phi', data=phi) rpo.create_dataset('err', data=err) if e is not None: rpo.create_dataset('er', data=e.real) rpo.create_dataset('ei', data=e.imag) if v is not None: rpo.create_dataset('v', data=v) f.close() def move(self, inFile, ingroup, outFile, outgroup, flag=0): e, v = None, None pack = self.read(inFile, ingroup, flag) if flag == 0: x, T, nstp, th, phi, err = pack elif flag == 1: x, T, nstp, th, phi, err, e = pack elif flag == 2: x, T, nstp, th, phi, err, e, v = pack else: print "error of move" self.save(outFile, outgroup, x, T, nstp, th, phi, err, e, v) #=================================================== def plotConfigSurface(AA, ext, barTicks=[2, 4], colortype='jet', percent='5%', size=[7, 5], axisLabelSize=25, save=False, name='out.png'): """ plot the color map of the states """ Aamp = np.abs(AA) X = np.linspace(ext[0], ext[1], Aamp.shape[1]) Y = np.linspace(ext[2], ext[3], Aamp.shape[0]) X, Y = np.meshgrid(X, Y) fig = plt.figure(figsize=size) ax = fig.add_subplot(111, projection='3d') surf = ax.plot_surface(X, Y, Aamp, rstride=1, cstride=1, cmap=plt.get_cmap(colortype), linewidth=0, antialiased=False) fig.colorbar(surf, fraction=0.05, shrink=0.6, aspect=20, ticks=barTicks) ax.set_xlabel(r'$x$', fontsize=axisLabelSize) ax.set_ylabel(r'$t$', fontsize=axisLabelSize) ax.set_zlabel(r'$|A|$', fontsize=axisLabelSize) # dr = make_axes_locatable(ax) # cax = dr.append_axes('right', size=percent, pad=0.05) # plt.colorbar(surf, cax=cax, ticks=barTicks) fig.tight_layout(pad=0) if save: plt.savefig(name) plt.close() else: plt.show(block=False) def plotConfigSurfaceFourier(cgl, aa, ext, barTicks=[2, 7], colortype='jet', percent='5%', size=[7, 5], axisLabelSize=25, save=False, name='out.png'): plotConfigSurface(cgl.Fourier2Config(aa), ext, barTicks, colortype, percent, size, axisLabelSize, save, name) def plotConfigWire(AA, ext, barTicks=[2, 7], size=[7, 6], axisLabelSize=25, tickSize=15, c='r', save=False, name='out.png'): """ plot the meshframe plot """ Aamp = abs(AA) X = np.linspace(ext[0], ext[1], Aamp.shape[1]) Y = np.linspace(ext[2], ext[3], Aamp.shape[0]) X, Y = np.meshgrid(X, Y) fig = plt.figure(figsize=size) ax = fig.add_subplot(111, projection='3d') #ax.plot_wireframe(X, Y, Aamp) for i in range(Aamp.shape[0]): ax.plot(X[i], Y[i], Aamp[i], c=c, alpha=1) ax.set_xlabel(r'$x$', fontsize=axisLabelSize) ax.set_ylabel(r'$t$', fontsize=axisLabelSize) ax.set_zlabel(r'$|A|$', fontsize=axisLabelSize) if tickSize is not None: ax.tick_params(axis='both', which='major', labelsize=tickSize) fig.tight_layout(pad=0) if save: plt.savefig(name) plt.close() else: plt.show(block=False) def plotConfigWireFourier(cgl, aa, ext, barTicks=[2, 7], size=[7, 6], axisLabelSize=25, tickSize=15, c='r', save=False, name='out.png'): plotConfigWire(cgl.Fourier2Config(aa), ext, barTicks, size, axisLabelSize, tickSize, c, save, name) def plotPhase(cgl, aa, ext, barTicks=[-3, 0, 3], colortype='jet', percent='5%', size=[4, 5], save=False, name='out.png'): """ plot phase of filed A in cqcgl """ phi = cgl.Fourier2Phase(aa) fig = plt.figure(figsize=size) ax = fig.add_subplot(111) ax.set_xlabel('x') ax.set_ylabel('y') im = ax.imshow(phi, cmap=plt.get_cmap(colortype), extent=ext, aspect='auto', origin='lower') ax.grid('on') dr = make_axes_locatable(ax) cax = dr.append_axes('right', size=percent, pad=0.05) bar = plt.colorbar(im, cax=cax, ticks=barTicks) fig.tight_layout(pad=0) if save: plt.savefig(name) plt.close() else: plt.show(block=False) def PoincareLinearInterp(x, getIndex=False): """ x has dimension [N x 3]. The Poincare section is defined as x[i, 0] = 0. Linear interpolation is used to obtain the intersection points. (y - y1) / (0 - x1) = (y2 - y1) / (x2 - x1) (z - z1) / (0 - x1) = (z2 - z1) / (x2 - x1) """ N, M = x.shape points = np.zeros((0, M-1)) index = np.zeros((0,), dtype=np.int) ratios = np.zeros((0,)) for i in range(N-1): if x[i, 0] < 0 and x[i+1, 0] >= 0: ratio = -x[i, 0] / (x[i+1, 0] - x[i, 0]) y = (x[i+1, 1] - x[i, 1]) * ratio + x[i, 1] z = (x[i+1, 2] - x[i, 2]) * ratio + x[i, 2] points = np.vstack((points, np.array([y, z]))) index = np.append(index, i) ratios = np.append(ratios, ratio) if getIndex: return points, index, ratios else: return points def getCurveIndex(points): """ Obtain the curvalinear Index of a set of points. parameter: points : each row is a point """ n = points.shape[0] # number of points indices = range(n) sortedIndices = [] norms = [np.linalg.norm(points[i]) for i in range(n)] start = np.argmin(norms) sortedIndices.append(start) indices.remove(start) for i in range(n-1): last = sortedIndices[-1] norms = [np.linalg.norm(points[i] - points[last]) for i in indices] minimal = indices[np.argmin(norms)] # careful sortedIndices.append(minimal) indices.remove(minimal) return sortedIndices def getCurveCoor(points): """ Obtain the curvalinear coordinate of a set of points. parameter: points : each row is a point """ n = points.shape[0] # number of points indices = getCurveIndex(points) dis = np.empty(n) dis[0] = np.linalg.norm(points[indices[0]]) for i in range(1, n): dis[i] = np.linalg.norm(points[indices[i]] - points[indices[i-1]]) return dis ################################################## # 2d CQCGL related # ################################################## class CQCGL2dPlot(): def __init__(self, dx, dy): self.dx = dx self.dy = dy def load(self, fileName, i, flag=1): """ Load one state in the original storage order Parameters ========== flag : what to return """ f = h5py.File(fileName, 'r') ds = '/' + format(i, '06d') + '/' if flag == 1 or flag == 0: a = f[ds+'ar'].value + 1j*f[ds+'ai'].value if flag == 2 or flag == 0: v = f[ds+'vr'].value + 1j*f[ds+'vi'].value f.close() if flag == 0: return a, v elif flag == 1: return a elif flag == 2: return v def loadSeq(self, fileName, x, y, ids): """ load a sequence of points but only at location (x, y) Avoid using the whole mesh since it is slow. Parameters ========== x, y : the x and y location of the mesh """ n = len(ids) data = np.zeros(n, dtype=np.complex) f = h5py.File(fileName, 'r') for i in ids: ds = '/' + format(i, '06d') + '/' data[i] = f[ds+'ar'][x, y] + 1j*f[ds+'ai'][x, y] f.close() return data def oneState(self, cgl, a, save=False, name='out.png', colortype='jet', percent=0.05, size=[7, 5], barTicks=None, axisLabelSize=25, plotType=0): """ Parameters ========== plotType : 0 => heat plot 1 => 3d mesh plot else => both together """ A = cgl.Fourier2Config(a) aA = np.abs(A).T if plotType == 0: fig, ax = pl2d(size=size, labs=[None, None], axisLabelSize=axisLabelSize) ax.grid('on') im = ax.imshow(aA, cmap=plt.get_cmap(colortype), aspect='equal', origin='lower', extent=[0, self.dx, 0, self.dy]) dr = make_axes_locatable(ax) cax = dr.append_axes('right', size=percent, pad=0.05) if barTicks is not None: plt.colorbar(im, cax=cax, ticks=barTicks) else: plt.colorbar(im, cax=cax) ax2d(fig, ax, save=save, name=name) # plotMat(aA, save=save, name=name) else: X = np.linspace(0, self.dx, aA.shape[1]) Y = np.linspace(0, self.dy, aA.shape[0]) X, Y = np.meshgrid(X, Y) if plotType == 1: fig, ax = pl3d(size=size, labs=[r'$x$', r'$y$', r'$|A|$'], axisLabelSize=axisLabelSize) surf = ax.plot_surface(X, Y, aA, rstride=10, cstride=10, cmap=plt.get_cmap(colortype), linewidth=0, antialiased=False) if barTicks is not None: fig.colorbar(surf, fraction=percent, shrink=0.6, aspect=20, ticks=barTicks) else: fig.colorbar(surf, fraction=percent, shrink=0.6, aspect=20, ticks=barTicks) ax3d(fig, ax, save=save, name=name) else: fig = plinit(size) ax1 = ax3dinit(fig, 121, labs=[r'$x$', r'$y$', r'$|A|$'], axisLabelSize=axisLabelSize) ax2 = ax2dinit(fig, 122, labs=[None, None]) ax2.grid('on') surf = ax1.plot_surface(X, Y, aA, rstride=10, cstride=10, cmap=plt.get_cmap(colortype), linewidth=0, antialiased=False) im = ax2.imshow(aA, cmap=plt.get_cmap(colortype), aspect='equal', origin='lower', extent=[0, self.dx, 0, self.dy]) dr = make_axes_locatable(ax2) cax = dr.append_axes('right', size=percent, pad=0.05) if barTicks is not None: plt.colorbar(im, cax=cax, ticks=barTicks) else: plt.colorbar(im, cax=cax) ax2d(fig, ax2, save=save, name=name) def makeMovie(self, folderName, name='out.mp4'): """ Parameters ========== folderName : name of the figure folder """ files = "'" + folderName + '/*.png' + "'" command = ('ffmpeg -f image2 -r 6 -pattern_type glob -i' + ' ' + files + ' ' + name) os.system(command) def savePlots(self, cgl, f1, f2, sids=None, plotType=0, size=[7, 5]): """ Parameters ========== f1 : h5 data file f2 : save folder name sids : a list which contains the ids of the states if it is None, then all states will be loaded """ if os.path.exists(f2): print 'folder already exists' else: os.makedirs(f2) if sids == None: f = h5py.File(f1, 'r') sids = range(len(f.keys())) f.close() for i in sids: name = f2+'/a'+format(i, '06d') a = self.load(f1, i) self.oneState(cgl, a, save=True, size=size, name=name, plotType=plotType) def saveReq(self, fileName, groupName, a, wthx, wthy, wphi, err): f = h5py.File(fileName, 'a') req = f.create_group(groupName) req.create_dataset("ar", data=a.real) req.create_dataset("ai", data=a.imag) req.create_dataset("wthx", data=wthx) req.create_dataset("wthy", data=wthy) req.create_dataset('wphi', data=wphi) req.create_dataset('err', data=err) f.close() def toStr(self, Bi, Gi, index): if abs(Bi) < 1e-6: Bi = 0 if abs(Gi) < 1e-6: Gi = 0 return (format(Bi, '013.6f') + '/' + format(Gi, '013.6f') + '/' + str(index)) def loadReq(self, fileName, groupName): f = h5py.File(fileName, 'r') req = '/' + groupName + '/' a = f[req+'ar'].value + 1j*f[req+'ai'].value wthx = f[req+'wthx'].value wthy = f[req+'wthy'].value wphi = f[req+'wphi'].value err = f[req+'err'].value f.close() return a, wthx, wthy, wphi, err <file_sep>// to compile // // first use // mpicxx --showme -O3 test_CQCGL1dRpo_mpi.cc -L../../lib -I../../include -I$EIGEN -std=c++11 -lCQCGL1dRpo -lCQCGL1d -lsparseRoutines -ldenseRoutines -literMethod -lmyH5 -lmyfft -lfftw3 -lm // // then change g++ to h5c++ // // h5c++ -O3 test_CQCGL1dRpo_mpi.cc -L../../lib -I../../include -I/usr/local/home/xiong/apps/eigen/include/eigen3 -std=c++11 -lCQCGL1dRpo -lCQCGL1d -lsparseRoutines -ldenseRoutines -literMethod -lmyH5 -lmyfft -lfftw3 -lm -I/usr/lib/openmpi/include -I/usr/lib/openmpi/include/openmpi -pthread -L/usr//lib -L/usr/lib/openmpi/lib -lmpi_cxx -lmpi -ldl -lhwloc #include <iostream> #include <fstream> #include <Eigen/Dense> #include <complex> #include <ctime> #include <mpi.h> #include "CQCGL1dReq.hpp" #include "CQCGL1dRpo.hpp" using namespace std; using namespace Eigen; using namespace iterMethod; #define cee(x) (cout << (x) << endl << endl) #define CASE_10 int main(int argc, char **argv){ cout.precision(15); GMRES_IN_PRINT_FREQUENCE = 50; HOOK_PRINT_FREQUENCE = 1; GMRES_OUT_PRINT = false; #ifdef CASE_10 //====================================================================== // find limit cycles by varying Bi and Gi const int N = 1024; const int L = 50; double Bi = 2.0; double Gi = -5.6; int id = 1; CQCGL1dRpo cgl(N, L, -0.1, 0.125, 0.5, 1, Bi, -0.1, Gi, 1); string file = "../../data/cgl/rpoBiGi2.h5"; double stepB = 0.1; int NsB = 38; //////////////////////////////////////////////////////////// // mpi part MPI_Init(&argc, &argv); int rank, num; MPI_Comm_rank(MPI_COMM_WORLD, &rank); MPI_Comm_size(MPI_COMM_WORLD, &num); int inc = NsB / num; int rem = NsB - inc * num; int p_size = inc + (rank < rem ? 1 : 0); int p_start = inc*rank + (rank < rem ? rank : rem); int p_end = p_start + p_size; fprintf(stderr, "MPI : %d / %d; range : %d - %d \n", rank, num, p_start, p_end); //////////////////////////////////////////////////////////// for (int i = p_start; i < p_end; i++){ cgl.Bi = Bi + i*stepB; cgl.findRpoParaSeq(file, 1, 0.1, 55, false); } //////////////////////////////////////////////////////////// MPI_Finalize(); //////////////////////////////////////////////////////////// #endif return 0; } <file_sep>#include "CQCGL1dRpo.hpp" #include <functional> // std::bind #include "myH5.hpp" #define cee(x) (cout << (x) << endl << endl) namespace ph = std::placeholders; using namespace denseRoutines; using namespace sparseRoutines; using namespace iterMethod; using namespace Eigen; using namespace std; using namespace MyH5; ////////////////////////////////////////////////////////////////////// // constructor // ////////////////////////////////////////////////////////////////////// // A_t = Mu A + (Dr + Di*i) A_{xx} + (Br + Bi*i) |A|^2 A + (Gr + Gi*i) |A|^4 A CQCGL1dRpo::CQCGL1dRpo(int N, double d, double Mu, double Dr, double Di, double Br, double Bi, double Gr, double Gi, int dimTan): CQCGL1d(N, d, Mu, Dr, Di, Br, Bi, Gr, Gi, dimTan) {} // A_t = -A + (1 + b*i) A_{xx} + (1 + c*i) |A|^2 A - (dr + di*i) |A|^4 A CQCGL1dRpo::CQCGL1dRpo(int N, double d, double b, double c, double dr, double di, int dimTan): CQCGL1d(N, d, b, c, dr, di, dimTan){} // iA_z + D A_{tt} + |A|^2 A + \nu |A|^4 A = i \delta A + i \beta A_{tt} + i |A|^2 A + i \mu |A|^4 A CQCGL1dRpo::CQCGL1dRpo(int N, double d, double delta, double beta, double D, double epsilon, double mu, double nu, int dimTan) : CQCGL1d(N, d, delta, beta, D, epsilon, mu, nu, dimTan) {} CQCGL1dRpo::~CQCGL1dRpo(){} CQCGL1dRpo & CQCGL1dRpo::operator=(const CQCGL1dRpo &x){ return *this; } ////////////////////////////////////////////////////////////////////// // member functions // ////////////////////////////////////////////////////////////////////// std::string CQCGL1dRpo::toStr(double x){ // avoid possibilty that 000000.000000 or -00000.000000 if (fabs(x) < 1e-6) x = 0; char buffer [20]; sprintf (buffer, "%013.6f", x); return std::string(buffer); } std::string CQCGL1dRpo::toStr(double x, double y, int id){ return toStr(x) + '/' + toStr(y) + '/' + to_string(id); } /** * @note group should be a new group * [x, T, nstp, theta, phi, err] */ void CQCGL1dRpo::write(const string fileName, const string groupName, const MatrixXd &x, const double T, const int nstp, const double th, const double phi, double err){ H5File file(fileName, H5F_ACC_RDWR); checkGroup(file, groupName, true); string DS = "/" + groupName + "/"; writeMatrixXd(file, DS + "x", x); writeScalar<double>(file, DS + "T", T); writeScalar<int>(file, DS + "nstp", nstp); writeScalar<double>(file, DS + "th", th); writeScalar<double>(file, DS + "phi", phi); writeScalar<double>(file, DS + "err", err); } void CQCGL1dRpo::write2(const std::string fileName, const string groupName, const MatrixXd &x, const int nstp, double err){ MatrixXd tmp = x.bottomRows(3).rowwise().sum(); double T = tmp(0); double th = tmp(1); double phi = tmp(2); write(fileName, groupName, x, T, nstp, th, phi, err); } std::tuple<MatrixXd, double, int, double, double, double> CQCGL1dRpo::read(const string fileName, const string groupName){ H5File file(fileName, H5F_ACC_RDONLY); string DS = "/" + groupName + "/"; return make_tuple(readMatrixXd(file, DS + "x"), readScalar<double>(file, DS + "T"), readScalar<int>(file, DS + "nstp"), readScalar<double>(file, DS + "th"), readScalar<double>(file, DS + "phi"), readScalar<double>(file, DS + "err") ); } /** * @brief move rpo from one file, group to another file, group */ void CQCGL1dRpo::move(string infile, string ingroup, string outfile, string outgroup, int flag){ MatrixXd x; double T, th, phi, err; int nstp; VectorXcd e; MatrixXd v; std::tie(x, T, nstp, th, phi, err) = read(infile, ingroup); write(outfile, outgroup, x, T, nstp, th, phi, err); if (flag == 1 || flag == 2){ e = readE(infile, ingroup); writeE(outfile, outgroup, e); } if (flag == 2) { v = readV(infile, ingroup); writeV(outfile, outgroup, v); } } VectorXcd CQCGL1dRpo::readE(std::string fileName, const std::string groupName){ H5File file(fileName, H5F_ACC_RDONLY); string DS = "/" + groupName + "/"; VectorXd er = readMatrixXd(file, DS + "er"); VectorXd ei = readMatrixXd(file, DS + "ei"); VectorXcd e(er.size()); e.real() = er; e.imag() = ei; return e; } MatrixXd CQCGL1dRpo::readV(std::string fileName, const std::string groupName){ H5File file(fileName, H5F_ACC_RDONLY); string DS = "/" + groupName + "/"; return readMatrixXd(file, DS + "v"); } void CQCGL1dRpo::writeE(std::string fileName, const std::string groupName, const VectorXcd &e){ H5File file(fileName, H5F_ACC_RDWR); checkGroup(file, groupName, true); string DS = "/" + groupName + "/"; writeMatrixXd(file, DS + "er", e.real()); writeMatrixXd(file, DS + "ei", e.imag()); } void CQCGL1dRpo::writeV(std::string fileName, const std::string groupName, const MatrixXd &v){ H5File file(fileName, H5F_ACC_RDWR); checkGroup(file, groupName, true); string DS = "/" + groupName + "/"; writeMatrixXd(file, DS + "v", v); } ////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////// //====================================================================== /* * @brief multishooting form [f(x_0, t) - x_1, ... g*f(x_{M-1},t) - x_0] * @param[in] x [Ndim * M + 3, 1] dimensional vector: (x, t, theta, phi) * @return vector F(x, t) = * | f(x_0, t) -x_1 | * | f(x_1, t) -x_2 | * | ...... | * | g*f(x_{M-1}, t) - x_0| * | 0 | * | 0 | * | 0 | * */ VectorXd CQCGL1dRpo::MFx(const VectorXd &x, int nstp){ assert( (x.size() - 3) % Ndim == 0 ); int m = (x.size() - 3) / Ndim; Vector3d t = x.tail<3>(); /* T, theta, phi */ assert(t(0) > 0); /* make sure T > 0 */ VectorXd F(VectorXd::Zero(Ndim * m + 3)); for(size_t i = 0; i < m; i++){ VectorXd fx = intg(x.segment(i*Ndim, Ndim), t(0)/nstp/m, nstp, nstp).rightCols<1>(); if(i != m-1){ // the first m-1 vectors F.segment(i*Ndim, Ndim) = fx - x.segment((i+1)*Ndim, Ndim); } else{ // the last vector F.segment(i*Ndim, Ndim) = Rotate(fx, t(1), t(2)).matrix() - x.head(Ndim); } } return F; } /* * @brief get the multishooting product J * dx. Dimension [nstp*m+3, 1] * @see MFx() */ VectorXd CQCGL1dRpo::MDFx(const VectorXd &x, const VectorXd &dx, int nstp){ assert( (x.size() - 3) % Ndim == 0 ); int m = (x.size() - 3) / Ndim; Vector3d t = x.tail<3>(); Vector3d dt = dx.tail<3>(); assert(t(0) > 0); /* make sure T > 0 */ VectorXd DF(VectorXd::Zero(Ndim * m + 3)); for(size_t i = 0; i < m; i++){ ArrayXd xt = x.segment(i*Ndim, Ndim); ArrayXd dxt = dx.segment(i*Ndim, Ndim); ArrayXXd tmp = intgv(xt, dxt, t(0)/nstp/m, nstp); /* f(x, t) and J(x, t)*dx */ VectorXd v1 = velocity(xt); /* v(x) */ VectorXd v2 = velocity(tmp.col(0)); /* v(f(x, t)) */ VectorXd t1 = transTangent(xt); VectorXd t2 = phaseTangent(xt); // update the last 3 elements DF(m * Ndim) += v1.dot(dxt.matrix()); DF(m * Ndim + 1) += t1.dot(dxt.matrix()); DF(m * Ndim + 2) += t2.dot(dxt.matrix()); if(i != m-1){ DF.segment(i*Ndim, Ndim) = tmp.col(1).matrix() - dx.segment((i+1)*Ndim , Ndim) + 1.0 / m * v2 * dt(0); } else{ ArrayXd gfx = Rotate(tmp.col(0), t(1), t(2)); /* g(theta, phi)*f(x, t) */ VectorXd gJx = Rotate(tmp.col(1), t(1), t(2)); /* g(theta, phi)*J(x,t)*dx */ DF.segment(i*Ndim, Ndim) = gJx - dx.segment(0, Ndim) + 1.0/m * Rotate(v2, t(1), t(2)).matrix() * dt(0) + transTangent(gfx).matrix() * dt(1) + phaseTangent(gfx).matrix() * dt(2) ; } } return DF; } /** * @brief form [g*f(x,t) - x, ...] * * Form the difference vector, which consists of m pieces, each piece * correspond to (x, t, theta, phi). If m = 1, then it reduces to single * shooting. * * @param[in] x [(Ndim + 3)*m, 1] dimensional vector. * @return vector F_i(x, t) = * | g*f(x, t) - x| * | 0 | * | 0 | * | 0 | * for i = 1, 2, ..., m */ VectorXd CQCGL1dRpo::MFx2(const VectorXd &x, int nstp){ int n = Ndim + 3; assert( x.size() % n == 0 ); int m = x.size() / n; VectorXd F(VectorXd::Zero(n*m)); for(int i = 0; i < m; i++){ VectorXd xi = x.segment(n*i, n); int j = (i+1) % m; VectorXd xn = x.segment(n*j, n); double t = xi(Ndim); double th = xi(Ndim+1); double phi = xi(Ndim+2); assert(t > 0); VectorXd fx = intg(xi.head(Ndim), t/nstp, nstp, nstp).rightCols<1>(); F.segment(i*n, Ndim) = Rotate(fx, th, phi).matrix() - xn.head(Ndim); } return F; } /** * @brief get the product J * dx * * If m = 1, then it reduces to single shooting * * Here J_i = | g*J(x, t), g*v(f(x,t)), g*t1(f(x,t)), g*t2(f(x,t))| * | v(x), 0 0 0 | * | t1(x), 0 0 0 | * | t2(x), 0 0 0 | */ VectorXd CQCGL1dRpo::MDFx2(const VectorXd &x, const VectorXd &dx, int nstp){ int n = Ndim + 3; assert( x.size() % n == 0 ); int m = x.size() / n; VectorXd DF(VectorXd::Zero(n*m)); for (int i = 0; i < m; i++) { VectorXd xi = x.segment(i*n, n); VectorXd dxi = dx.segment(i*n, n); int j = (i+1) % m; VectorXd dxn = dx.segment(j*n, n); double t = xi(Ndim); double th = xi(Ndim+1); double phi = xi(Ndim+2); assert( t > 0 ); double dt = dxi(Ndim); double dth = dxi(Ndim+1); double dphi = dxi(Ndim+2); MatrixXd tmp = intgv(xi.head(Ndim), dxi.head(Ndim), t/nstp, nstp); VectorXd gfx = Rotate(tmp.col(0), th, phi); VectorXd gJx = Rotate(tmp.col(1), th, phi); VectorXd v = velocity(xi.head(Ndim)); VectorXd vgf = velocity(gfx); VectorXd t1 = transTangent(xi.head(Ndim)); VectorXd tgf1 = transTangent(gfx); VectorXd t2 = phaseTangent(xi.head(Ndim)); VectorXd tgf2 = phaseTangent(gfx); DF.segment(i*n, Ndim) = gJx + vgf*dt + tgf1*dth + tgf2*dphi - dxn.head(Ndim); DF(i*n+Ndim) = v.dot(dxi.head(Ndim)); DF(i*n+Ndim+1) = t1.dot(dxi.head(Ndim)); DF(i*n+Ndim+2) = t2.dot(dxi.head(Ndim)); } return DF; } //====================================================================== #if 0 /** * @brief find rpo in cqcgl 1d system * * @return [x, T, theta, phi, err] */ std::tuple<VectorXd, double, double, double, double> CQCGL1dRpo::findRPO(const VectorXd &x0, const double T, const double th0, const double phi0, const double tol, const int btMaxIt, const int maxit, const double eta0, const double t, const double theta_min, const double theta_max, const int GmresRestart, const int GmresMaxit){ assert(x0.size() == Ndim); auto fx = std::bind(&CQCGL1dRpo::Fx, this, ph::_1); auto dfx = std::bind(&CQCGL1dRpo::DFx, this, ph::_1, ph::_2); VectorXd x(Ndim+3); x << x0, T, th0, phi0; auto result = InexactNewtonBacktrack(fx, dfx, x, tol, btMaxIt, maxit, eta0, t, theta_min, theta_max, GmresRestart, GmresMaxit); if(std::get<2>(result) != 0){ fprintf(stderr, "RPO not converged ! \n"); } return std::make_tuple(std::get<0>(result).head(Ndim), /* x */ std::get<0>(result)(Ndim), /* T */ std::get<0>(result)(Ndim+1), /* theta */ std::get<0>(result)(Ndim+2), /* phi */ std::get<1>(result).back() /* err */ ); } /** * @brief find rpo in cqcgl 1d system * * @return [x, T, theta, phi, err] */ std::tuple<MatrixXd, double, double, double, double> CQCGL1dRpo::findRPOM(const MatrixXd &x0, const double T, const double th0, const double phi0, const double tol, const int btMaxIt, const int maxit, const double eta0, const double t, const double theta_min, const double theta_max, const int GmresRestart, const int GmresMaxit){ assert(x0.cols() == M && x0.rows() == Ndim); auto fx = std::bind(&CQCGL1dRpo::MFx, this, ph::_1); auto dfx = std::bind(&CQCGL1dRpo::MDFx, this, ph::_1, ph::_2); // initialize input VectorXd x(M * Ndim + 3); MatrixXd tmp(x0); tmp.resize(M * Ndim, 1); x << tmp, T, th0, phi0; auto result = InexactNewtonBacktrack(fx, dfx, x, tol, btMaxIt, maxit, eta0, t, theta_min, theta_max, GmresRestart, GmresMaxit); if(std::get<2>(result) != 0){ fprintf(stderr, "RPO not converged ! \n"); } MatrixXd tmp2(std::get<0>(result).head(M*Ndim)); tmp2.resize(Ndim, M); return std::make_tuple(tmp2, /* x */ std::get<0>(result)(M*Ndim), /* T */ std::get<0>(result)(M*Ndim+1), /* theta */ std::get<0>(result)(M*Ndim+2), /* phi */ std::get<1>(result).back() /* err */ ); } /** * @brief single shooting to find rpo with GMRES HOOK algorithm * * @param[in] x0 initial guess state * @param[in] T initial guess period * @param[in] th0 initial guess of translation angle * @param[in] phi0 initial guess of phase angle * @param[in] tol tolerance of the orbit ||x(0)-X(T)|| * @param[in] minRD mininal relative descrease at each step * @param[in] maxit maximal number of iterations for Newton steps * @param[in] maxInnIt maximal number of iterations for Hook steps * @param[in] GmresRtol relative tolerence of GMRES * @param[in] GmresRestart maximal Krylov subspace dimension => inner loop size * @param[in] GmresMaxit maximal outer iteration number * @return [x, T, theta, phi, err] * * @see findRPOM_hook() for multishooting method */ std::tuple<VectorXd, double, double, double, double> CQCGL1dRpo::findRPO_hook(const VectorXd &x0, const double T, const double th0, const double phi0, const double tol, const double minRD, const int maxit, const int maxInnIt, const double GmresRtol, const int GmresRestart, const int GmresMaxit){ assert(x0.size() == Ndim); auto fx = std::bind(&CQCGL1dRpo::Fx, this, ph::_1); auto dfx = std::bind(&CQCGL1dRpo::DFx, this, ph::_1, ph::_2); VectorXd x(Ndim + 3); x << x0, T, th0, phi0; auto result = Gmres0Hook(fx, dfx, x, tol, minRD, maxit, maxInnIt, GmresRtol, GmresRestart, GmresMaxit, true, 3); if(std::get<2>(result) != 0){ fprintf(stderr, "RPO not converged ! \n"); } return std::make_tuple(std::get<0>(result).head(Ndim), /* x */ std::get<0>(result)(Ndim), /* T */ std::get<0>(result)(Ndim+1), /* theta */ std::get<0>(result)(Ndim+2), /* phi */ std::get<1>(result).back() /* err */ ); } /** * @brief find rpo in cqcgl 1d system * * @return [x, T, theta, phi, err] * @see findRPO_hook() for single shooting method */ std::tuple<MatrixXd, double, double, double, double> CQCGL1dRpo::findRPOM_hook(const MatrixXd &x0, const double T, const double th0, const double phi0, const double tol, const double minRD, const int maxit, const int maxInnIt, const double GmresRtol, const int GmresRestart, const int GmresMaxit){ assert(x0.cols() == M && x0.rows() == Ndim); auto fx = std::bind(&CQCGL1dRpo::MFx, this, ph::_1); auto dfx = std::bind(&CQCGL1dRpo::MDFx, this, ph::_1, ph::_2); // initialize input VectorXd x(M * Ndim + 3); MatrixXd tmp(x0); tmp.resize(M * Ndim, 1); x << tmp, T, th0, phi0; auto result = Gmres0Hook(fx, dfx, x, tol, minRD, maxit, maxInnIt, GmresRtol, GmresRestart, GmresMaxit, true, 3); if(std::get<2>(result) != 0){ fprintf(stderr, "RPO not converged ! \n"); } MatrixXd tmp2(std::get<0>(result).head(M*Ndim)); tmp2.resize(Ndim, M); return std::make_tuple(tmp2, /* x */ std::get<0>(result)(M*Ndim), /* T */ std::get<0>(result)(M*Ndim+1), /* theta */ std::get<0>(result)(M*Ndim+2), /* phi */ std::get<1>(result).back() /* err */ ); } #endif //////////////////////////////////////////////////////////////////////////////////////////////////// // new version of F and DF, This version use a full multishooting method VectorXd CQCGL1dRpo::calPre(const VectorXd &x, const VectorXd &dx){ int n = Ndim + 3; assert( x.size() % n == 0 ); int m = x.size() / n; VectorXd DF(VectorXd::Zero(n*m)); for (int i = 0; i < m; i++) { VectorXd xi = x.segment(i*n, n); VectorXd dxi = dx.segment(i*n, n); double th = xi(Ndim+1); double phi = xi(Ndim+2); DF.segment(i*n, n) << Rotate(dxi.head(Ndim), -th, -phi), dxi.tail(3); } return DF; } /// @return [ (x, T, th, phi), err, flag ] std::tuple<MatrixXd, double, int> CQCGL1dRpo::findRPOM_hook2(const MatrixXd &x0, const int nstp, const double tol, const double minRD, const int maxit, const int maxInnIt, const double GmresRtol, const int GmresRestart, const int GmresMaxit){ int n = Ndim + 3; int m = x0.cols(); assert( x0.rows() == n); auto fx = [this, nstp](const VectorXd &x){ return MFx2(x, nstp); }; auto dfx = [this, nstp](const VectorXd &x, const VectorXd &dx){ return MDFx2(x, dx, nstp); }; // initialize input MatrixXd x(x0); x.resize(m * n, 1); // auto Pre = [this](const VectorXd &x, const VectorXd &dx){VectorXd p = calPre(x, dx); return p; }; auto Pre = [this](const VectorXd &x, const VectorXd &dx){ return dx; }; VectorXd xnew; std::vector<double> errs; int flag; std::tie(xnew, errs, flag) = Gmres0HookPre(fx, dfx, Pre, x, tol, minRD, maxit, maxInnIt, GmresRtol, GmresRestart, GmresMaxit, true, 3); // std::tie(xnew, errs, flag) = Gmres0Hook(fx, dfx, x, tol, minRD, maxit, maxInnIt, // GmresRtol, GmresRestart, GmresMaxit, // true, 3); if(flag != 0) fprintf(stderr, "RPO not converged ! \n"); MatrixXd tmp(xnew); tmp.resize(n, m); return std::make_tuple(tmp, errs.back(), flag ); } /** * @brief find req with a sequence of Bi or Gi */ void CQCGL1dRpo::findRpoParaSeq(const std::string file, int id, double step, int Ns, bool isBi, int nstpFlag, int paraNstp){ double Bi0 = Bi; double Gi0 = Gi; MatrixXd x0; double T0, th0, phi0, err0; int nstp0; std::tie(x0, T0, nstp0, th0, phi0, err0) = read(file, toStr(Bi, Gi, id)); MatrixXd x; double T, th, phi, err; int nstp, flag; int Nfail = 0; for (int i = 0; i < Ns; i++){ if (isBi) Bi += step; else Gi += step; // if exist, use it as seed, otherwise find req if ( checkGroup(file, toStr(Bi, Gi, id), false) ){ std::tie(x0, T0, nstp0, th0, phi0, err0) = read(file, toStr(Bi, Gi, id)); } else { switch(nstpFlag){ case 1 : nstp = static_cast<int>( T0 / (1e-3*10) ) * 10; break; case 2 : nstp = nstp0 - paraNstp ; break; // change the same amount case 3 : nstp = paraNstp; break; // use a specific value default : nstp = nstp0; // use previous nstp } fprintf(stderr, "Bi = %g Gi = %g nstp = %d T0 = %g\n", Bi, Gi, nstp, T0); std::tie(x, err, flag) = findRPOM_hook2(x0, nstp, 8e-10, 1e-3, 50, 30, 1e-6, 300, 1); if (flag == 0){ write2(file, toStr(Bi, Gi, id), x, nstp, err); std::tie(x0, T0, nstp0, th0, phi0, err0) = read(file, toStr(Bi, Gi, id)); } else { if(++Nfail == 3) break; } } } Bi = Bi0; // restore Bi, Gi Gi = Gi0; } #if 0 //////////////////////////////////////////////////////////////////////////////////////////////////// // use LM algorithm to find RPO std::tuple<SpMat, SpMat, VectorXd> CQCGL1dRpo::calJJF(const VectorXd &x){ int N = Ndim + 3; SpMat JJ(N*M, N*M); SpMat D(N*M, N*M); VectorXd df(VectorXd::Zero(N*M)); MatrixXd F(MatrixXd::Zero(N, N)); MatrixXd FF(N, N); MatrixXd FK(MatrixXd::Zero(N, N)); MatrixXd KF(MatrixXd::Zero(N, N)); std::vector<Tri> nzjj, nzd; nzjj.reserve(3*M*N*N); nzd.reserve(M*N); ///////////////////////////////////////// // construct the JJ, Diag(JJ), JF for(int i = 0; i < M; i++){ fprintf(stderr, "%d ", i); VectorXd xi = x.segment(i*N, N); int j = (i+1) % M; VectorXd xn = x.segment(j*N, N); double t = xi(Ndim); double th = xi(Ndim + 1); double phi = xi(Ndim + 2); assert( t > 0); cgl3.changeh( t/nstp ); auto tmp = cgl3.intgj(xi.head(Ndim), nstp, nstp, nstp); ArrayXd fx = tmp.first.col(1); ArrayXXd &J = tmp.second; VectorXd gfx = cgl3.Rotate(fx, th, phi); df.segment(i*N, Ndim) = gfx - xn.head(Ndim); F.topLeftCorner(Ndim, Ndim) = cgl3.Rotate(J, th, phi); F.col(Ndim).head(Ndim) = cgl3.velocity(gfx); F.col(Ndim+1).head(Ndim) = cgl3.transTangent(gfx); F.col(Ndim+2).head(Ndim) = cgl3.phaseTangent(gfx); F.row(Ndim).head(Ndim) = cgl3.velocity(xi.head(Ndim)); F.row(Ndim+1).head(Ndim) = cgl3.transTangent(xi.head(Ndim)).transpose(); F.row(Ndim+2).head(Ndim) = cgl3.phaseTangent(xi.head(Ndim)).transpose(); FF = F.transpose() * F; for(int i = 0; i < Ndim; i++) FF(i, i) += 1; FK.leftCols(Ndim) = -F.transpose().leftCols(Ndim); KF.topRows(Ndim) = -F.topRows(Ndim); std::vector<Tri> triFF = triMat(FF, i*N, i*N); std::vector<Tri> triFK = triMat(FK, i*N, j*N); std::vector<Tri> triKF = triMat(KF, j*N, i*N); std::vector<Tri> triD = triDiag(FF.diagonal(), i*N, i*N); nzjj.insert(nzjj.end(), triFF.begin(), triFF.end()); nzjj.insert(nzjj.end(), triFK.begin(), triFK.end()); nzjj.insert(nzjj.end(), triKF.begin(), triKF.end()); nzd.insert(nzd.end(), triD.begin(), triD.end()); } JJ.setFromTriplets(nzjj.begin(), nzjj.end()); D.setFromTriplets(nzd.begin(), nzd.end()); return std::make_tuple(JJ, D, df); } std::tuple<MatrixXd, double> CQCGL1dRpo::findRPOM_LM(const MatrixXd &x0, const double tol, const int maxit, const int innerMaxit){ int N = Ndim + 3; assert(x0.cols() == M && x0.rows() == N); auto fx = std::bind(&CQCGL1dRpo::MFx2, this, ph::_1); MatrixXd x(x0); x.resize(M * N, 1); // SparseLU<SpMat> solver; SimplicialLDLT<SpMat> solver; cqcglJJF<SpMat> jj(*this); auto result = LM0(fx, jj, solver, x, tol, maxit, innerMaxit); if(std::get<2>(result) != 0) fprintf(stderr, "RPO not converged ! \n"); MatrixXd tmp2(std::get<0>(result)); tmp2.resize(N, M); return std::make_pair( tmp2, std::get<1>(result).back() ); } #endif <file_sep>/* compile command: * mex CXXFLAGS='-std=c++0x -fPIC -O3' MEXksint.cpp ksint.cc ksintM1.cc * -I../../include -I/usr/include/eigen3 * */ #include "ksintM1.hpp" #include "mex.h" #include "matrix.h" #include <cmath> #include <cstring> #include <Eigen/Dense> using Eigen::ArrayXXd; using Eigen::ArrayXd; using Eigen::Map; const int N = 32; /* ks full state space integrator without Jacobian */ static ArrayXXd ksf(double *a0, double d, double h, int nstp, int np){ KS ks(N, h, d); Map<ArrayXd> v0(a0, N-2); //ArrayXd v0(N-2); for(int i = 0 ; i < N-2; i++) v0(i) = a0[i]; ArrayXXd aa = ks.intg(v0, nstp, np); return aa; } /* ks full state space integrator with Jacobian */ static std::pair<ArrayXXd, ArrayXXd> ksfj(double *a0, double d, double h, int nstp, int np, int nqr){ KS ks(N, h, d); Map<ArrayXd> v0(a0, N-2); return ks.intgj(v0, nstp, np, nqr); } static std::tuple<ArrayXXd, VectorXd, VectorXd> ksfDP(double *a0, double d, double h, int nstp, int np){ KS ks(N, h, d); Map<ArrayXd> v0(a0, N-2); return ks.intgDP(v0, nstp, np); } static std::pair<ArrayXXd, ArrayXd> ksfM1(double *a0, double d, double h, int nstp, int np){ KSM1 ks(N, h, d); Map<ArrayXd> v0(a0, N-2); //ArrayXd v0(N-2); for(int i = 0 ; i < N-2; i++) v0(i) = a0[i]; return ks.intg(v0, nstp, np); } static std::pair<ArrayXXd, ArrayXd> ksf2M1(double *a0, double d, double h, double T, int np){ KSM1 ks(N, h, d); Map<ArrayXd> v0(a0, N-2); //ArrayXd v0(N-2); for(int i = 0 ; i < N-2; i++) v0(i) = a0[i]; return ks.intg2(v0, T, np); } void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[]){ double *a0 = mxGetPr(prhs[0]); double d = mxGetScalar(prhs[1]); double h = mxGetScalar(prhs[2]); int nstp = mxGetScalar(prhs[3]); int np = mxGetScalar(prhs[4]); int nqr = mxGetScalar(prhs[5]); mwSize isM1 = mxGetScalar(prhs[6]); /* isM1 =1: integration on the 1st mode slice. */ mwSize isT = mxGetScalar(prhs[7]); /* isT = 1: integration time on full state space. */ double T = mxGetScalar(prhs[8]); mwSize isDP = mxGetScalar(prhs[9]); /* isDp = 1: integrate D and P too */ mwSize Jacob = mxGetScalar(prhs[10]); /* Jacob = 1: integrate with Jacobian */ if(isM1 == 0){ if(isDP == 0){ if(Jacob == 0){ plhs[0] = mxCreateDoubleMatrix(N-2, nstp/np + 1, mxREAL); //Map<ArrayXXd> aa(mxGetPr(plhs[0]), N-2, nstp/np + 1); //aa = ksf(a0, d, h, nstp, np); ArrayXXd aa = ksf(a0, d, h, nstp, np); memcpy(mxGetPr(plhs[0]), &aa(0,0), (nstp/np+1)*(N-2)*sizeof(double)); } else{ // integration with Jacobian plhs[0] = mxCreateDoubleMatrix(N-2, nstp/np + 1, mxREAL); plhs[1] = mxCreateDoubleMatrix((N-2)*(N-2), nstp/np, mxREAL); std::pair<ArrayXXd, ArrayXXd> aada = ksfj(a0, d, h, nstp, np, nqr); memcpy(mxGetPr(plhs[0]), &(aada.first(0, 0)), (nstp/np+1)*(N-2)*sizeof(double)); memcpy(mxGetPr(plhs[1]), &(aada.second(0, 0)), (nstp/np)*(N-2)*(N-2)*sizeof(double)); } } else{ /* dispation integration */ plhs[0] = mxCreateDoubleMatrix(N-2, nstp/np + 1, mxREAL); plhs[1] = mxCreateDoubleMatrix(nstp/np+1, 1, mxREAL); plhs[2] = mxCreateDoubleMatrix(nstp/np+1, 1, mxREAL); std::tuple<ArrayXXd, VectorXd, VectorXd> tmp = ksfDP(a0, d, h, nstp, np); memcpy(mxGetPr(plhs[0]), &(std::get<0>(tmp)(0,0)), (nstp/np+1)*(N-2)*sizeof(double)); memcpy(mxGetPr(plhs[1]), &(std::get<1>(tmp)(0)), (nstp/np+1)*sizeof(double)); memcpy(mxGetPr(plhs[2]), &(std::get<2>(tmp)(0)), (nstp/np+1)*sizeof(double)); } } else{ if(isT == 0){ plhs[0] = mxCreateDoubleMatrix( nstp/np + 1 , 1, mxREAL); plhs[1] = mxCreateDoubleMatrix(N-2, nstp/np + 1, mxREAL); std::pair<ArrayXXd, ArrayXd> at = ksfM1(a0, d, h, nstp, np); memcpy(mxGetPr(plhs[0]), &(std::get<1>(at)(0,0)), (nstp/np+1)*sizeof(double)); memcpy(mxGetPr(plhs[1]), &(std::get<0>(at)(0)), (nstp/np+1)*(N-2)*sizeof(double)); //Map<ArrayXXd> (at.aa)(mxGetPr(plhs[1]), N-2, nstp/np+1); //Map<ArrayXd> (at.tt)(mxGetPr(plhs[0]), nstp/np+1); } else{ std::pair<ArrayXXd, ArrayXd> at = ksf2M1(a0, d, h, T, np); int m = (std::get<0>(at)).cols(); plhs[0] = mxCreateDoubleMatrix( m , 1, mxREAL); plhs[1] = mxCreateDoubleMatrix(N-2, m, mxREAL); memcpy(mxGetPr(plhs[0]), &(std::get<1>(at)(0,0)), m*sizeof(double)); memcpy(mxGetPr(plhs[1]), &(std::get<0>(at)(0)), m*(N-2)*sizeof(double)); } } } <file_sep>CC = h5c++ GCC = g++ AR = ar OPTIM = -O3 -msse2 -msse4 -march=corei7 INCLUDE = ../../include EIGEN = /usr/local/home/xiong/apps/eigen/include/eigen3 CFLAGS = -std=c++11 LIB = ../../lib hdf5 = /usr/lib/x86_64-linux-gnu # for pace cluster ifdef pace OPTIM = -O3 EIGEN = /nv/hp16/xding35/data/apps/eigen/include/eigen3 hdf5 = /nv/hp16/xding35/data/apps/hdf5/lib endif #### H5FLAGS = -D_LARGEFILE_SOURCE -D_LARGEFILE64_SOURCE -D_BSD_SOURCE -D_FORTIFY_SOURCE=2 -g -O2 -fstack-protector --param=ssp-buffer-size=4 -Wformat -Werror=format-security H5LIB = $(hdf5)/libhdf5_hl_cpp.so $(hdf5)/libhdf5_cpp.so $(hdf5)/libhdf5_hl.so $(hdf5)/libhdf5.so -Wl,-Bsymbolic-functions -Wl,-z,relro -lpthread -lz -ldl -lm -Wl,-rpath -Wl, # H5FLAGS = -D_LARGEFILE_SOURCE -D_LARGEFILE64_SOURCE -D_BSD_SOURCE -D_FORTIFY_SOURCE=2 -g -O2 -fstack-protector --param=ssp-buffer-size=4 -Wformat -Werror=format-security # H5LIB = -L/usr/lib/x86_64-linux-gnu /usr/lib/x86_64-linux-gnu/libhdf5_hl_cpp.so /usr/lib/x86_64-linux-gnu/libhdf5_cpp.so /usr/lib/x86_64-linux-gnu/libhdf5_hl.so /usr/lib/x86_64-linux-gnu/libhdf5.so -Wl,-Bsymbolic-functions -Wl,-z,relro -lpthread -lz -ldl -lm -Wl,-rpath -Wl,/usr/lib/x86_64-linux-gnu SOURCE = myH5.cc SHARED = $(addprefix lib, $(addsuffix .so, $(basename $(SOURCE)))) STATIC = $(addprefix lib, $(addsuffix .a, $(basename $(SOURCE)))) # use flag -show to h5c++ to find out what library it uses all : $(STATIC) $(SHARED) $(SHARED): $(SOURCE) $(GCC) $(H5FLAGS) -c -shared -fPIC $(CFLAGS) $(OPTIM) -I$(INCLUDE) -I$(EIGEN) $^ $(GCC) $(H5FLAGS) $(SOURCE:.cc=.o) -shared -fPIC $(CFLAGS) $(OPTIM) -I$(INCLUDE) -I$(EIGEN) -o $@ $(H5LIB) $(SOURCE:.cc=.o) : $(SOURCE) $(CC) -c $(CFLAGS) $(OPTIM) -I$(INCLUDE) -I$(EIGEN) $^ $(STATIC): $(SOURCE:.cc=.o) $(AR) crs $@ $^ clean: rm -f *.so *.o *.a move: mv *.so *.a $(LIB) <file_sep>/* to comiple: * h5c++ -O3 test_CQCGL1dSubReq.cc -L../../lib -I../../include -I$EIGEN -std=c++11 -lCQCGL1dSubReq -lCQCGL1dSub -lCQCGL1dReq -lCQCGL1d -ldenseRoutines -literMethod -lmyH5 -lfftw3 -lm */ #include "CQCGL1dSubReq.hpp" #include "CQCGL1dReq.hpp" #include <iostream> #include <fstream> #include <Eigen/Dense> #include <complex> #include <H5Cpp.h> using namespace std; using namespace Eigen; using namespace denseRoutines; using namespace MyH5; typedef std::complex<double> dcp; #define N50 int main(int argc, char **argv){ #ifdef N10 //====================================================================== // use the full-space req as initial condition to find req in the // symmetric subspace. const int N = 1024; const double L = 50; double Bi = 0.8, Gi = -0.6; CQCGL1dReq cgl0(N, L, -0.1, 0.125, 0.5, 1, Bi, -0.1, Gi, 0); CQCGL1dSubReq cgl(N, L, -0.1, 0.125, 0.5, 1, Bi, -0.1, Gi, 0); string fileName = "/usr/local/home/xiong/00git/research/data/cgl/reqBiGi.h5"; H5File file(fileName, H5F_ACC_RDWR); ArrayXd a0; double wth0, wphi0, err0; std::tie(a0, wth0, wphi0, err0) = cgl0.read(file, cgl.toStr(Bi, Gi, 2)); a0 = a0.head(cgl.Ndim); ArrayXd a; double wphi, err; int flag; std::tie(a, wphi, err, flag) = cgl.findReq_LM(a0, wphi0, 1e-10, 100, 1000); fprintf(stderr, "%g %g\n", wphi, err); H5File fout("sub.h5", H5F_ACC_TRUNC); if (flag == 0) cgl.write(fout, cgl.toStr(Bi, Gi, 1), a, wphi, err); #endif #ifdef N20 //====================================================================== // the same as N10, but navigate in the parameter plane. const int N = 1024; const double L = 50; string finName = "/usr/local/home/xiong/00git/research/data/cgl/reqBiGi.h5"; H5File file(finName, H5F_ACC_RDWR); string foutName = "sub.h5"; H5File fout(foutName, H5F_ACC_TRUNC); ArrayXd a0; double wth0, wphi0, err0; ArrayXd a; double wphi, err; int flag; auto gs = scanGroup(finName); for(auto entry : gs) { double Bi = stod(entry[0]), Gi = stod(entry[1]); int id = stoi(entry[2]); fprintf(stderr, "\n %d %g %g \n", id, Bi, Gi); CQCGL1dReq cgl0(N, L, -0.1, 0.125, 0.5, 1, Bi, -0.1, Gi, 0); CQCGL1dSubReq cgl(N, L, -0.1, 0.125, 0.5, 1, Bi, -0.1, Gi, 0); std::tie(a0, wth0, wphi0, err0) = cgl0.read(file, cgl.toStr(Bi, Gi, id)); a0 = a0.head(cgl.Ndim); std::tie(a, wphi, err, flag) = cgl.findReq_LM(a0, wphi0, 1e-10, 100, 1000); fprintf(stderr, "%g %g\n", wphi, err); if (flag == 0) cgl.write(fout, cgl.toStr(Bi, Gi, id), a, wphi, err); } #endif #ifdef N40 //====================================================================== // try to calculate the eigenvalue and eigenvector of one req const int N = 1024; const double L = 50; double Bi = 0.8, Gi = -0.6; CQCGL1dSubReq cgl(N, L, -0.1, 0.125, 0.5, 1, Bi, -0.1, Gi, 0); string fileName = "/usr/local/home/xiong/00git/research/data/cgl/reqsubBiGi.h5"; H5File file(fileName, H5F_ACC_RDWR); int id = 1; ArrayXd a0; double wphi0, err0; std::tie(a0, wphi0, err0) = cgl.read(file, cgl.toStr(Bi, Gi, id)); VectorXcd e; MatrixXcd v; std::tie(e, v) = cgl.evReq(a0, wphi0); cout << e.head(10) << endl; cout << endl; cout << v.cols() << ' ' << v.rows() << endl; #endif #ifdef N50 //====================================================================== // calculate E/V const int N = 1024; const double L = 50; string s = "/usr/local/home/xiong/00git/research/data/cgl/reqsubBiGi"; auto gs = scanGroup(s + ".h5"); // H5File fin(s + ".h5", H5F_ACC_RDWR); H5File fout(s + "EV.h5", H5F_ACC_RDWR); ArrayXd a0; double wphi0, err0; VectorXcd e; MatrixXcd v; int i = 0; for (auto entry : gs){ double Bi = stod(entry[0]), Gi = stod(entry[1]); int id = stoi(entry[2]); if( !checkGroup(fout, CQCGL1dSubReq::toStr(Bi, Gi, id) + "/er", false) ){ fprintf(stderr, "%d/%d : %d %g %g \n", ++i, (int)gs.size(), id, Bi, Gi); CQCGL1dSubReq cgl(N, L, -0.1, 0.125, 0.5, 1, Bi, -0.1, Gi, 0); std::tie(a0, wphi0, err0) = cgl.read(fout, cgl.toStr(Bi, Gi, id)); std::tie(e, v) = cgl.evReq(a0, wphi0); cgl.writeE(fout, cgl.toStr(Bi, Gi, id), e); cgl.writeV(fout, cgl.toStr(Bi, Gi, id), v.leftCols(10)); } } #endif return 0; } <file_sep>from py_CQCGL_threads import pyCQCGL from personalFunctions import * case = 65 if case == 1: """ test the accuracy of the soliton solution """ N = 1024 d = 30 h = 0.0002 di = 0.05 cgl = pyCqcgl1d(N, d, h, True, 0, 4.0, 0.8, 0.01, di, 4) a0, wth0, wphi0, err = cqcglReadReqdi('../../data/cgl/reqDi.h5', di, 1) vReq = cgl.velocityReq(a0, wth0, wphi0) nstp = abs(int(2 * np.pi / h / wphi0)) print norm(vReq) aaE = cgl.intg(a0, nstp, 1) aaEH, th, phi = cgl.orbit2slice(aaE) if case == 10: """ plot unstable manifold of the exploding soliton solution only continuous symmetries are reduced """ N = 1024 d = 30 h = 0.000001 di = 0.05 cgl = pyCqcgl1d(N, d, h, True, 0, 4.0, 0.8, 0.01, di, 4) a0, wth0, wphi0, err = cqcglReadReqdi('../../data/cgl/reqDi.h5', di, 1) eigvalues, eigvectors = eigReq(cgl, a0, wth0, wphi0) eigvectors = Tcopy(realve(eigvectors)) a0Hat = cgl.orbit2slice(a0)[0].squeeze() veHat = cgl.ve2slice(eigvectors, a0) nstp = 120000 a0Erg = a0 + eigvectors[0]*1e-7 aaErg = cgl.intg(a0Erg, nstp, 10) aaErgHat, th, phi = cgl.orbit2slice(aaErg) aaErgHat -= a0Hat e1, e2, e3 = orthAxes(veHat[0], veHat[1], veHat[10]) aaErgHatProj = np.dot(aaErgHat, np.vstack((e1, e2, e3)).T) fig = plt.figure(figsize=[8, 6]) ax = fig.add_subplot(111, projection='3d') ix1 = 000 ix2 = 10000 ixs = ix1 + 1400 ax.plot(aaErgHatProj[ix1:ix2, 0], aaErgHatProj[ix1:ix2, 1], aaErgHatProj[ix1:ix2, 2], c='r', lw=1) # ax.scatter([0], [0], [0], s=120) # ax.scatter(aaErgHatProj[ixs, 0], aaErgHatProj[ixs, 1], # aaErgHatProj[ixs, 2], s=120, c='k') ax.set_xlabel(r'$e_1$', fontsize=25) ax.set_ylabel(r'$e_2$', fontsize=25) ax.set_zlabel(r'$e_3$', fontsize=25) fig.tight_layout(pad=0) plt.show(block=False) if case == 11: """ view a sing unstable manifold orbit but with full symmetry reduction """ N = 1024 d = 30 h = 0.0002 di = 0.05 cgl = pyCqcgl1d(N, d, h, True, 0, 4.0, 0.8, 0.01, di, 4) a0, wth0, wphi0, err = cqcglReadReqdi('../../data/cgl/reqDi.h5', di, 1) eigvalues, eigvectors = eigReq(cgl, a0, wth0, wphi0) eigvectors = Tcopy(realve(eigvectors)) a0Hat = cgl.orbit2slice(a0)[0].squeeze() a0Tilde = cgl.reduceReflection(a0Hat) veHat = cgl.ve2slice(eigvectors, a0) veTilde = cgl.reflectVe(veHat, a0Hat) a0Reflected = cgl.reflect(a0) a0ReflectedHat = cgl.orbit2slice(a0Reflected)[0].squeeze() nstp = 5500 a0Erg = a0 + eigvectors[0]*1e-4 aaErg = cgl.intg(a0Erg, nstp, 1) aaErgHat, th, phi = cgl.orbit2slice(aaErg) aaErgTilde = cgl.reduceReflection(aaErgHat) aaErgTilde -= a0Tilde e1, e2, e3 = orthAxes(veTilde[0], veTilde[1], veTilde[10]) aaErgTildeProj = np.dot(aaErgTilde, np.vstack((e1, e2, e3)).T) # plot3dfig(aaErgHatProj[1000:, 0], aaErgHatProj[1000:, 1], aaErgHatProj[1000:, 2]) fig = plt.figure(figsize=[8, 6]) ax = fig.add_subplot(111, projection='3d') ix1 = 0 ix2 = 3300 ax.plot(aaErgTildeProj[ix1:ix2, 0], aaErgTildeProj[ix1:ix2, 1], aaErgTildeProj[ix1:ix2, 2], c='r', lw=1) ax.scatter([0], [0], [0], s=100) ax.set_xlabel(r'$e_1$', fontsize=25) ax.set_ylabel(r'$e_2$', fontsize=25) ax.set_zlabel(r'$e_3$', fontsize=25) fig.tight_layout(pad=0) plt.show(block=False) if case == 13: N = 1024 d = 30 h = 0.0002 di = 0.05 cgl = pyCqcgl1d(N, d, h, True, 0, 4.0, 0.8, 0.01, di, 4) def vel(x, t): return cgl.velocity(x) a0, wth0, wphi0, err = cqcglReadReqdi('../../data/cgl/reqDi.h5', di, 1) eigvalues, eigvectors = eigReq(cgl, a0, wth0, wphi0) eigvectors = Tcopy(realve(eigvectors)) a0Hat = cgl.orbit2slice(a0)[0].squeeze() a0Tilde = cgl.reduceReflection(a0Hat) veHat = cgl.ve2slice(eigvectors, a0) veTilde = cgl.reflectVe(veHat, a0Hat) a0Reflected = cgl.reflect(a0) a0ReflectedHat = cgl.orbit2slice(a0Reflected)[0].squeeze() nstp = 5500 a0Erg = a0 + eigvectors[0]*1e-4 aaErg = cgl.intg(a0Erg, nstp, 1) aaErgHat, th, phi = cgl.orbit2slice(aaErg) aaErgTilde = cgl.reduceReflection(aaErgHat) aaErgTilde -= a0Tilde e1, e2, e3 = orthAxes(veTilde[0], veTilde[1], veTilde[10]) aaErgTildeProj = np.dot(aaErgTilde, np.vstack((e1, e2, e3)).T) # plot3dfig(aaErgHatProj[1000:, 0], aaErgHatProj[1000:, 1], aaErgHatProj[1000:, 2]) fig = plt.figure(figsize=[8, 6]) ax = fig.add_subplot(111, projection='3d') ix1 = 0 ix2 = 3300 ax.plot(aaErgTildeProj[ix1:ix2, 0], aaErgTildeProj[ix1:ix2, 1], aaErgTildeProj[ix1:ix2, 2], c='r', lw=1) ax.scatter([0], [0], [0], s=100) ax.set_xlabel(r'$e_1$', fontsize=25) ax.set_ylabel(r'$e_2$', fontsize=25) ax.set_zlabel(r'$e_3$', fontsize=25) fig.tight_layout(pad=0) plt.show(block=False) if case == 15: """ view a single unstable manifold orbit using Jacobian not the system integrator. """ N = 1024 d = 30 h = 0.0002 di = 0.05 cgl = pyCqcgl1d(N, d, h, True, 0, 4.0, 0.8, 0.01, di, 4) a0, wth0, wphi0, err = cqcglReadReqdi('../../data/cgl/reqDi.h5', di, 1) eigvalues, eigvectors = eigReq(cgl, a0, wth0, wphi0) eigvectors = Tcopy(realve(eigvectors)) a0Hat = cgl.orbit2slice(a0)[0].squeeze() veHat = cgl.ve2slice(eigvectors, a0) cgl1 = pyCqcgl1d(N, d, h, True, 1, 4.0, 0.8, 0.01, di, 4) nstp = 3000 v0 = eigvectors[0]*1e-7 aaErg, vErg = cgl1.intgvs(a0, v0, nstp, 1, 1) aaErgHat, th, phi = cgl1.orbit2slice(aaErg) vErgHat = cgl1.ve2slice(vErg, a0) aaErgHat -= a0Hat e1, e2, e3 = orthAxes(veHat[0], veHat[1], veHat[10]) aaErgHatProj = np.dot(aaErgHat, np.vstack((e1, e2, e3)).T) vErgHatProj = np.dot(vErgHat, np.vstack((e1, e2, e3)).T) fig = plt.figure(figsize=[8, 6]) ax = fig.add_subplot(111, projection='3d') ix1 = 000 ix2 = nstp ixs = ix1 + 1400 # ax.plot(aaErgHatProj[ix1:ix2, 0], aaErgHatProj[ix1:ix2, 1], # aaErgHatProj[ix1:ix2, 2], c='r', lw=1) ax.plot(vErgHatProj[ix1:ix2, 0], vErgHatProj[ix1:ix2, 1], vErgHatProj[ix1:ix2, 2], c='r', lw=1) # ax.scatter([0], [0], [0], s=120) ax.set_xlabel(r'$e_1$', fontsize=25) ax.set_ylabel(r'$e_2$', fontsize=25) ax.set_zlabel(r'$e_3$', fontsize=25) fig.tight_layout(pad=0) plt.show(block=False) if case == 20: """ plot unstable manifold of the exploding soliton solution from a line of states """ N = 1024 d = 30 h = 1e-5 di = 0.05 cgl = pyCqcgl1d(N, d, h, True, 0, 4.0, 0.8, 0.01, di, 4) a0, wth0, wphi0, err = cqcglReadReqdi('../../data/cgl/reqDi.h5', di, 1) eigvalues, eigvectors = eigReq(cgl, a0, wth0, wphi0) eigvectors = Tcopy(realve(eigvectors)) a0Hat = cgl.orbit2slice(a0)[0] veHat = cgl.ve2slice(eigvectors, a0) a0R = cgl.reflect(a0) a0RH = cgl.orbit2slice(a0R)[0] nstp = np.int(1e5) Er = eigvalues[0].real Ei = eigvalues[0].imag Vr, Vi = orthAxes2(eigvectors[0], eigvectors[1]) n = 10 aaE = [] aaEHat = [] for i in range(n): print i # ang = 2 * i * np.pi / n e = np.exp(2*np.pi * Er / Ei / n * i*10) a0Erg = a0 + Vr * e * 1e-6 aaErg = cgl.intg(a0Erg, nstp, 100) aaErgHat, th, phi = cgl.orbit2slice(aaErg) # aaE.append(aaErg) aaEHat.append(aaErgHat - a0Hat) e1, e2, e3 = orthAxes(veHat[0], veHat[1], veHat[10]) aaEHatP = [] for i in range(n): aaErgHatProj = np.dot(aaEHat[i], np.vstack((e1, e2, e3)).T) aaEHatP.append(aaErgHatProj) ix1 = 0 ix2 = nstp ixs = ix1 + 1400 fig = plt.figure(figsize=[8, 6]) ax = fig.add_subplot(111, projection='3d') for i in range(1): ax.plot(aaEHatP[i][ix1:ix2, 0], aaEHatP[i][ix1:ix2, 1], aaEHatP[i][ix1:ix2, 2], c='r', lw=1) # ax.scatter([0], [0], [0], s=50) # ax.scatter(aaErgHatProj[ixs, 0], aaErgHatProj[ixs, 1], # aaErgHatProj[ixs, 2], s=120, c='k') ax.set_xlabel(r'$e_1$', fontsize=25) ax.set_ylabel(r'$e_2$', fontsize=25) ax.set_zlabel(r'$e_3$', fontsize=25) fig.tight_layout(pad=0) plt.show(block=False) if case == 21: """ plot unstable manifold of the exploding soliton solution from a circular states """ N = 1024 d = 30 h = 0.0002 di = 0.05 cgl = pyCqcgl1d(N, d, h, True, 0, 4.0, 0.8, 0.01, di, 4) a0, wth0, wphi0, err = cqcglReadReqdi('../../data/cgl/reqDi.h5', di, 1) eigvalues, eigvectors = eigReq(cgl, a0, wth0, wphi0) eigvectors = Tcopy(realve(eigvectors)) a0Hat = cgl.orbit2slice(a0)[0].squeeze() veHat = cgl.ve2slice(eigvectors, a0) nstp = 3000 Er = eigvalues[0].real Ei = eigvalues[0].imag Vr, Vi = orthAxes2(eigvectors[0], eigvectors[1]) n = 30 aaE = [] aaEHat = [] for i in range(n): print i ang = 2 * i * np.pi / n a0Erg = a0 + (Vr * np.cos(ang) + Vi * np.sin(ang)) * 1e-4 aaErg = cgl.intg(a0Erg, nstp, 1) aaErgHat, th, phi = cgl.orbit2slice(aaErg) # aaE.append(aaErg) aaEHat.append(aaErgHat - a0Hat) e1, e2, e3 = orthAxes(veHat[0], veHat[1], veHat[10]) aaEHatP = [] for i in range(n): aaErgHatProj = np.dot(aaEHat[i], np.vstack((e1, e2, e3)).T) aaEHatP.append(aaErgHatProj) ix1 = 00000 ix2 = 03000 ixs = ix1 + 1400 fig = plt.figure(figsize=[8, 6]) ax = fig.add_subplot(111, projection='3d') for i in range(n): ax.plot(aaEHatP[i][ix1:ix2, 0], aaEHatP[i][ix1:ix2, 1], aaEHatP[i][ix1:ix2, 2], c='r', lw=1) # ax.scatter([0], [0], [0], s=120) # ax.scatter(aaErgHatProj[ixs, 0], aaErgHatProj[ixs, 1], # aaErgHatProj[ixs, 2], s=120, c='k') ax.set_xlabel(r'$e_1$', fontsize=25) ax.set_ylabel(r'$e_2$', fontsize=25) ax.set_zlabel(r'$e_3$', fontsize=25) fig.tight_layout(pad=0) plt.show(block=False) if case == 30: """ try to obtain the Poincare intersection points """ N = 1024 d = 50 h = 0.0001 cgl = pyCqcgl1d(N, d, h, True, 0, -0.1, 1.0, 0.8, 0.125, 0.5, -0.1, -0.6, 4) a0, wth0, wphi0, err = cqcglReadReq('../../data/cgl/reqN1024.h5', '1') eigvalues, eigvectors = eigReq(cgl, a0, wth0, wphi0) eigvectors = realve(eigvectors) eigvectors = Tcopy(eigvectors) a0Hat = cgl.orbit2slice(a0)[0].squeeze() a0Tilde = cgl.reduceReflection(a0Hat) veHat = cgl.ve2slice(eigvectors, a0) veTilde = cgl.reflectVe(veHat, a0Hat) e1, e2, e3 = orthAxes(veTilde[0], veTilde[1], veTilde[6]) nstp = 60000 M = 10 a0Erg = np.empty((M, cgl.Ndim)) for i in range(M): a0Erg[i] = a0 + (i+1) * eigvectors[0]*1e-4 PointsProj = np.zeros((0, 2)) PointsFull = np.zeros((0, cgl.Ndim)) for i in range(30): for j in range(M): aaErg = cgl.intg(a0Erg[j], nstp, 1) aaErgHat, th, phi = cgl.orbit2slice(aaErg) aaErgTilde = cgl.reduceReflection(aaErgHat) aaErgTilde -= a0Tilde aaErgTildeProj = np.dot(aaErgTilde, np.vstack((e1, e2, e3)).T) # plotConfigSpace(cgl.Fourier2Config(aaErg), # [0, d, nstp*h*i, nstp*h*(i+1)]) points, index, ratios = PoincareLinearInterp(aaErgTildeProj, getIndex=True) PointsProj = np.vstack((PointsProj, points)) for i in range(len(index)): dif = aaErgTilde[index[i]+1] - aaErgTilde[index[i]] p = dif * ratios[i] + aaErgTilde[index[i]] PointsFull = np.vstack((PointsFull, p)) a0Erg[j] = aaErg[-1] upTo = PointsProj.shape[0] scatter2dfig(PointsProj[:upTo, 0], PointsProj[:upTo, 1], s=10, labs=[r'$e_2$', r'$e_3$']) dis = getCurveCoor(PointsFull) # np.savez_compressed('PoincarePoints', totalPoints=totalPoints) if case == 40: """ plot the Poincare intersection points """ totalPoints = np.load('PoincarePoints.npz')['totalPoints'] multiScatter2dfig([totalPoints[:280, 0], totalPoints[280:350, 0]], [totalPoints[:280, 1], totalPoints[280:350, 1]], s=[15, 15], marker=['o', 'o'], fc=['r', 'b'], labs=[r'$e_2$', r'$e_3$']) scatter2dfig(totalPoints[:, 0], totalPoints[:, 1], s=10, labs=[r'$e_2$', r'$e_3$']) if case == 50: """ use the new constructor of cqcgl try to obtain the Poincare intersection points """ N = 1024 d = 40 h = 0.0005 cgl = pyCqcgl1d(N, d, h, True, 0, 4.0, 0.8, -0.01, -0.04, 4) a0, wth0, wphi0, err = cqcglReadReq('../../data/cgl/reqN1024.h5', '1') eigvalues, eigvectors = eigReq(cgl, a0, wth0, wphi0) eigvectors = realve(eigvectors) eigvectors = Tcopy(eigvectors) a0Hat = cgl.orbit2slice(a0)[0].squeeze() a0Tilde = cgl.reduceReflection(a0Hat) veHat = cgl.ve2slice(eigvectors, a0) veTilde = cgl.reflectVe(veHat, a0Hat) e1, e2, e3 = orthAxes(veTilde[0], veTilde[1], veTilde[6]) nstp = 60000 M = 10 a0Erg = np.empty((M, cgl.Ndim)) for i in range(M): a0Erg[i] = a0 + (i+1) * eigvectors[0]*1e-4 PointsProj = np.zeros((0, 2)) PointsFull = np.zeros((0, cgl.Ndim)) for i in range(30): for j in range(M): aaErg = cgl.intg(a0Erg[j], nstp, 1) aaErgHat, th, phi = cgl.orbit2slice(aaErg) aaErgTilde = cgl.reduceReflection(aaErgHat) aaErgTilde -= a0Tilde aaErgTildeProj = np.dot(aaErgTilde, np.vstack((e1, e2, e3)).T) # plotConfigSpace(cgl.Fourier2Config(aaErg), # [0, d, nstp*h*i, nstp*h*(i+1)]) points, index, ratios = PoincareLinearInterp(aaErgTildeProj, getIndex=True) PointsProj = np.vstack((PointsProj, points)) for i in range(len(index)): dif = aaErgTilde[index[i]+1] - aaErgTilde[index[i]] p = dif * ratios[i] + aaErgTilde[index[i]] PointsFull = np.vstack((PointsFull, p)) a0Erg[j] = aaErg[-1] upTo = PointsProj.shape[0] scatter2dfig(PointsProj[:upTo, 0], PointsProj[:upTo, 1], s=10, labs=[r'$e_2$', r'$e_3$']) dis = getCurveCoor(PointsFull) # np.savez_compressed('PoincarePoints', totalPoints=totalPoints) if case == 60: """ change parameter of b, see how the soliton changes """ N = 1024 d = 30 di = 0.06 b = 4 T = 3 cgl = pyCQCGL(N, d, b, 0.8, 0.01, di, 0, 4) cgl.changeOmega(-176.67504941219335) Ndim = cgl.Ndim A0 = 5*centerRand(N, 0.1, True) a0 = cgl.Config2Fourier(A0) aa = cgl.aintg(a0, 0.001, T, 1) plotConfigSpaceFromFourier(cgl, aa, [0, d, 0, T]) t1 = cgl.Ts() plot2dfig(t1, aa[:, 0], labs=['t', r'$Re(a_0)$']) <file_sep>#ifndef KSEIDR_H #define KSEIDR_H #include "EIDr.hpp" #include <Eigen/Dense> #include <unsupported/Eigen/FFT> //////////////////////////////////////////////////////////////////////////////// class KSEIDr { public: typedef std::complex<double> dcp; const int N; const double d; ArrayXd L; ArrayXd K; ArrayXcd G; FFT<double> fft; VectorXd hs; /* time step sequnce */ VectorXd lte; /* local relative error estimation */ VectorXd Ts; /* time sequnence for adaptive method */ int cellSize = 500; struct NL { FFT<double> *fft; ArrayXcd *G; NL(){} NL(FFT<double> &fft, ArrayXcd &G) : fft(&fft), G(&G) {} ~NL(){} void init(FFT<double> &fft, ArrayXcd &G){ this->G = &G; this->fft = &fft; } VectorXd u; void operator()(ArrayXcd &x, ArrayXcd &dxdt, double t){ Map<VectorXcd> xv(x.data(), x.size()); Map<VectorXcd> dxdtv(dxdt.data(), dxdt.size()); fft->inv(u, xv); u = u.array().square(); fft->fwd(dxdtv, u); dxdt *= (*G); } }; NL nl; ArrayXcd Yv[10], Nv[10]; EIDr eidr; /* ============================================================ */ KSEIDr(int N, double d) : N(N), d(d) { K = ArrayXd::LinSpaced(N/2+1, 0, N/2) * 2 * M_PI / d; K(N/2) = 0; L = K*K - K*K*K*K; G = 0.5 * dcp(0,1) * K * N; fft.SetFlag(fft.HalfSpectrum); nl.init(fft, G); int nYN0 = eidr.nYNs[eidr.scheme]; for(int i = 0; i < nYN0; i++){ Yv[i].resize(N/2+1); Nv[i].resize(N/2+1); } eidr.init(&L, Yv, Nv); } ~KSEIDr(){}; /* ============================================================ */ inline void setScheme(std::string x){ int nYN0 = eidr.nYNs[eidr.scheme]; eidr.scheme = eidr.names[x]; int nYN1 = eidr.nYNs[eidr.scheme]; for (int i = nYN0; i < nYN1; i++) { Yv[i].resize(N/2+1); Nv[i].resize(N/2+1); } } inline ArrayXXd intgC(const ArrayXd &a0, const double h, const double tend, const int skip_rate){ assert( N-2 == a0.size()); ArrayXcd u0 = R2C(a0); const int Nt = (int)round(tend/h); const int M = (Nt+skip_rate-1)/skip_rate; ArrayXXcd aa(N/2+1, M); lte.resize(M); int ks = 0; auto ss = [this, &ks, &aa](ArrayXcd &x, double t, double h, double err){ aa.col(ks) = x; lte(ks++) = err; }; eidr.intgC(nl, ss, 0, u0, tend, h, skip_rate); return C2R(aa); } inline ArrayXXd intg(const ArrayXd &a0, const double h, const double tend, const int skip_rate){ assert( N-2 == a0.size()); ArrayXcd u0 = R2C(a0); const int Nt = (int)round(tend/h); const int M = (Nt+skip_rate-1)/skip_rate; ArrayXXcd aa(N/2+1, M); Ts.resize(M); hs.resize(M); lte.resize(M); int ks = 0; auto ss = [this, &ks, &aa](ArrayXcd &x, double t, double h, double err){ int m = Ts.size(); if (ks >= m ) { Ts.conservativeResize(m+cellSize); aa.conservativeResize(Eigen::NoChange, m+cellSize); // rows not change, just extend cols hs.conservativeResize(m+cellSize); lte.conservativeResize(m+cellSize); } hs(ks) = h; lte(ks) = err; aa.col(ks) = x; Ts(ks++) = t; }; eidr.intg(nl, ss, 0, u0, tend, h, skip_rate); hs.conservativeResize(ks); lte.conservativeResize(ks); Ts.conservativeResize(ks); aa.conservativeResize(Eigen::NoChange, ks); return C2R(aa); } inline ArrayXXd C2R(const ArrayXXcd &v){ int n = v.rows(); int m = v.cols(); ArrayXXcd vt = v.middleRows(1, n-2); ArrayXXd vp(2*(n-2), m); vp = Map<ArrayXXd>((double*)&vt(0,0), 2*(n-2), m); return vp; } inline ArrayXXcd R2C(const ArrayXXd &v){ int n = v.rows(); int m = v.cols(); assert( 0 == n%2); ArrayXXcd vp = ArrayXXcd::Zero(n/2+2, m); vp.middleRows(1, n/2) = Map<ArrayXXcd>((dcp*)&v(0,0), n/2, m); return vp; } }; #endif /* KSEIDR_H */ <file_sep>#ifndef MYH5_H #define MYH5_H #include <Eigen/Dense> #include <iostream> #include <cstdio> #include <unordered_set> #include "H5Cpp.h" /** * Note, * scalars have dimension 0, * vectors have dimension 1 */ namespace MyH5 { using namespace H5; using namespace std; using namespace Eigen; template<typename Scalar> PredType getPredType(); template <typename Scalar> Scalar readScalar(H5File &file, string DSitem); template <typename Scalar> void writeScalar(H5File &file, string DSitem, Scalar value); void writeMatrixXd(H5File &file, string DSitem, const MatrixXd &mat); void writeVectorXd(H5File &file, string DSitem, const VectorXd &vec); MatrixXd readMatrixXd(H5File &file, string DSitem); VectorXd readVectorXd(H5File &file, string DSitem); bool checkGroup(H5File &file, const std::string groupName, const bool doCreate); bool checkGroup(std::string fileName, const std::string groupName, const bool doCreate); vector<vector<string>> scanGroup(std::string fileName); void scanGroupHelp(hid_t gid, vector<vector<string>> &result, unordered_set<string> &record, vector<string> &curt) ; ////////////////////////////////////////////////////////////////////// /* KS related */ std::pair<VectorXd, double> KSreadEq(const std::string fileName, const int Id); std::tuple<VectorXd, double, double> KSreadReq(const std::string fileName, const int Id); } ////////////////////////////////////////////////// // Implementation // ////////////////////////////////////////////////// namespace MyH5 { /** * @brief obtain the data type in HDF5 */ template<typename Scalar> PredType getPredType(){ if(typeid(Scalar) == typeid(double)){ return PredType::NATIVE_DOUBLE; } else if (typeid(Scalar) == typeid(int)){ return PredType::NATIVE_INT; } else{ fprintf(stderr, "getPredType received undetermined type !\n"); exit(1); } } /** * @brief read a scaler from a HDF5 file * * @param[in] file H5File object. shold open as H5F_ACC_RDWR * @param[in] DSitem the pass to the dataset * @return the scalar */ template <typename Scalar> Scalar readScalar(H5File &file, string DSitem){ DataSet item = file.openDataSet(DSitem); DataSpace dsp = item.getSpace(); assert(dsp.getSimpleExtentNdims() == 0); hsize_t dims[1]; int ndims = dsp.getSimpleExtentDims(dims, NULL); Scalar value(0); PredType type = getPredType<Scalar>(); item.read(&value, type); return value; } /** * @brief write a scaler to a HDf5 file * * @param[in] file H5File object. shold open as H5F_ACC_RDWR * @param[in] value the scalar need to be wrote */ template <typename Scalar> void writeScalar(H5File &file, string DSitem, Scalar value){ hsize_t dim[0]; DataSpace dsp(0, dim); PredType type = getPredType<Scalar>(); DataSet item = file.createDataSet(DSitem, type, dsp); item.write(&value, type); } } #endif /* MYH5_H */ <file_sep>#include "CQCGL1dSub.hpp" using namespace denseRoutines; // implementation notes // 1) not use fft.fwd(MatrixBase, MatrixBase) but use // fft.fwd(Complex * dst, const Complex * src, Index nfft) // becuase the former cannot work with Map<VectorXcd> type. // 2) In C++, initialization list will be evaluated in the order they were // declared in the class definition ////////////////////////////////////////////////////////////////////// // Inner Class CQCGL1dSub // ////////////////////////////////////////////////////////////////////// CQCGL1dSub::NL::NL(){} CQCGL1dSub::NL::NL(CQCGL1dSub *cgl, int cols) : cgl(cgl), N(cgl->N), Ne(cgl->Ne), B(cgl->Br, cgl->Bi), G(cgl->Gr, cgl->Gi) { modes.resize(cgl->N, cols); field.resize(cgl->N, cols); } CQCGL1dSub::NL::~NL(){} // the dimension should be [Ne, DimTan+1] void CQCGL1dSub::NL::operator()(ArrayXXcd &x, ArrayXXcd &dxdt, double t){ int cs = x.cols(); assert(cs == dxdt.cols() && Ne == x.rows() && Ne == dxdt.rows()); modes << x, ArrayXXcd::Zero(N-2*Ne+1, cs), x.bottomRows(Ne-1).colwise().reverse(); for(int i = 0; i < cs; i++) cgl->fft.inv(field.data() + i*N, modes.data() + i*N, N); ArrayXXcd AA = field.topRows(N/2 + 1); // [A_0, A_1..., A_N/2, A_N/2-1,,. A_1] ArrayXcd A = AA.col(0); ArrayXcd aA2 = A * A.conjugate(); if (cgl->IsQintic) AA.col(0) = B * A * aA2 + G * A * aA2.square(); else AA.col(0) = B * A * aA2; if(cs > 1){ int M = cs - 1; ArrayXcd A2 = A.square(); if (cgl->IsQintic) AA.rightCols(M) = AA.rightCols(M).conjugate().colwise() * ((B+G*2.0*aA2) * A2) + AA.rightCols(M).colwise() * ((2.0*B+3.0*G*aA2)*aA2); else AA.rightCols(M) = AA.rightCols(M).conjugate().colwise() * (B * A2) + AA.rightCols(M).colwise() * (2.0*B*aA2); } field << AA, AA.middleRows(1, N/2-1).colwise().reverse(); for(int i = 0; i < cs; i++) cgl->fft.fwd(modes.data() + i*N, field.data() + i*N, N); dxdt = modes.topRows(Ne); } ////////////////////////////////////////////////////////////////////// // Class CQCGL1dSub // ////////////////////////////////////////////////////////////////////// /* ------------------------------------------------------ */ /* ---- constructor/destructor ------- */ /* ------------------------------------------------------ */ /** * Constructor of cubic quintic complex Ginzburg-Landau equation * A_t = Mu A + (Dr + Di*i) A_{xx} + (Br + Bi*i) |A|^2 A + (Gr + Gi*i) |A|^4 A * * @param[in] N the number of Fourier modes * @param[in] d the spacial period, size * @param[in] dimTan the dimension of tangent space * dimTan > 0 => dimTan * dimTan = 0 => Ndim * dimTan < 0 => 0 * * Dealiasing is the method to calculate correct convolution term. For centralized * FFT, it works as set Fourier modes a_k = 0 for wave number |k| > 2/3 * N. * More specifically, in this code, the middle part of modes * is set to zero. * * |<---------------------------------------------------------->| * FFT length: N * * |<--------------->|<--------------------->|<---------------->| * Ne N - 2*Ne + 1 Ne - 1 */ CQCGL1dSub::CQCGL1dSub(int N, double d, double Mu, double Dr, double Di, double Br, double Bi, double Gr, double Gi, int dimTan) : N(N), d(d), Mu(Mu), Dr(Dr), Di(Di), Br(Br), Bi(Bi), Gr(Gr), Gi(Gi), Ne(N/3), Ndim(2 * Ne), DimTan(dimTan == 0 ? Ndim : (dimTan > 0 ? dimTan : 0)), nl(this, 1), nl2(this, DimTan+1) { // calculate the Linear part K = ArrayXd::LinSpaced(Ne, 0, Ne-1); QK = 2*M_PI/d * K; L = dcp(Mu, -Omega) - dcp(Dr, Di) * QK.square(); int nYN0 = eidc.names.at(eidc.scheme).nYN; // do not call setScheme here. Different. for(int i = 0; i < nYN0; i++){ Yv[i].resize(Ne, 1); Nv[i].resize(Ne, 1); Yv2[i].resize(Ne, DimTan+1); Nv2[i].resize(Ne, DimTan+1); } eidc.init(&L, Yv, Nv); eidc2.init(&L, Yv2, Nv2); } /** * Constructor of cubic quintic complex Ginzburg-Landau equation * A_t = -A + (1 + b*i) A_{xx} + (1 + c*i) |A|^2 A - (dr + di*i) |A|^4 A */ CQCGL1dSub::CQCGL1dSub(int N, double d, double b, double c, double dr, double di, int dimTan) : CQCGL1dSub::CQCGL1dSub(N, d, -1, 1, b, 1, c, -dr, -di, dimTan) {} CQCGL1dSub::CQCGL1dSub(int N, double d, double delta, double beta, double D, double epsilon, double mu, double nu, int dimTan) : CQCGL1dSub::CQCGL1dSub(N, d, delta, beta, D/2, epsilon, 1, mu, nu) {} CQCGL1dSub::~CQCGL1dSub(){} CQCGL1dSub & CQCGL1dSub::operator=(const CQCGL1dSub &x){ return *this; } /* ------------------------------------------------------ */ /* ---- Integrator ------- */ /* ------------------------------------------------------ */ void CQCGL1dSub::setScheme(std::string x){ int nYN0 = eidc.names.at(eidc.scheme).nYN; eidc.scheme = x; int nYN1 = eidc.names.at(eidc.scheme).nYN; for (int i = nYN0; i < nYN1; i++) { Yv[i].resize(Ne, 1); Nv[i].resize(Ne, 1); Yv2[i].resize(Ne, DimTan+1); Nv2[i].resize(Ne, DimTan+1); } } void CQCGL1dSub::changeOmega(double w){ Omega = w; L = dcp(Mu, -Omega) - dcp(Dr, Di) * QK.square(); } /** @brief Integrator of 1d cqCGL equation. * * The intial condition a0 should be coefficients of the intial state: * [b0, c0 ,b1, c1,...] where bi, ci the real and imaginary parts of Fourier modes. * * @param[in] a0 initial condition of Fourier coefficents. Size : [2*Ne,1] * @return state trajectory. Each column is the state followed the previous column. */ ArrayXXd CQCGL1dSub::intgC(const ArrayXd &a0, const double h, const double tend, const int skip_rate){ assert( Ndim == a0.size()); ArrayXXcd u0 = R2C(a0); const int Nt = (int)round(tend/h); const int M = (Nt + skip_rate - 1) / skip_rate; ArrayXXcd aa(Ne, M); lte.resize(M); int ks = 0; auto ss = [this, &ks, &aa](ArrayXXcd &x, double t, double h, double err){ aa.col(ks) = x; lte(ks++) = err; }; eidc.intgC(nl, ss, 0, u0, tend, h, skip_rate); return C2R(aa); } std::pair<ArrayXXd, ArrayXXd> CQCGL1dSub::intgjC(const ArrayXd &a0, const double h, const double tend, const int skip_rate){ assert(a0.size() == Ndim && DimTan == Ndim); ArrayXXd v0(Ndim, Ndim+1); v0 << a0, MatrixXd::Identity(Ndim, Ndim); ArrayXXcd u0 = R2C(v0); const int Nt = (int)round(tend/h); const int M = (Nt + skip_rate - 1) / skip_rate; ArrayXXcd aa(Ne, M), daa(Ne, Ndim*M); lte.resize(M); int ks = 0; auto ss = [this, &ks, &aa, &daa](ArrayXXcd &x, double t, double h, double err){ aa.col(ks) = x.col(0); daa.middleCols(ks*Ndim, Ndim) = x.rightCols(Ndim); lte(ks++) = err; x.rightCols(Ndim) = R2C(MatrixXd::Identity(Ndim, Ndim)); }; eidc2.intgC(nl2, ss, 0, u0, tend, h, skip_rate); return std::make_pair(C2R(aa), C2R(daa)); } /** * @brief integrate the state and a subspace in tangent space */ ArrayXXd CQCGL1dSub::intgvC(const ArrayXd &a0, const ArrayXXd &v, const double h, const double tend){ assert( Ndim == a0.size() && Ndim == v.rows() && DimTan == v.cols()); ArrayXXd v0(Ndim, DimTan+1); v0 << a0, v; ArrayXXcd u0 = R2C(v0); const int Nt = (int)round(tend/h); ArrayXXcd aa(Ne, DimTan+1); auto ss = [this, &aa](ArrayXXcd &x, double t, double h, double err){ aa = x; }; eidc2.intgC(nl2, ss, 0, u0, tend, h, Nt); return C2R(aa); //both the final orbit and the perturbation } ArrayXXd CQCGL1dSub::intg(const ArrayXd &a0, const double h, const double tend, const int skip_rate){ assert( Ndim == a0.size()); ArrayXXcd u0 = R2C(a0); const int Nt = (int)round(tend/h); const int M = (Nt+skip_rate-1)/skip_rate; ArrayXXcd aa(Ne, M); Ts.resize(M); hs.resize(M); lte.resize(M); int ks = 0; auto ss = [this, &ks, &aa](ArrayXXcd &x, double t, double h, double err){ int m = Ts.size(); if (ks >= m ) { Ts.conservativeResize(m+cellSize); aa.conservativeResize(Eigen::NoChange, m+cellSize); // rows not change, just extend cols hs.conservativeResize(m+cellSize); lte.conservativeResize(m+cellSize); } hs(ks) = h; lte(ks) = err; aa.col(ks) = x; Ts(ks++) = t; }; eidc.intg(nl, ss, 0, u0, tend, h, skip_rate); hs.conservativeResize(ks); lte.conservativeResize(ks); Ts.conservativeResize(ks); aa.conservativeResize(Eigen::NoChange, ks); return C2R(aa); } std::pair<ArrayXXd, ArrayXXd> CQCGL1dSub::intgj(const ArrayXd &a0, const double h, const double tend, const int skip_rate){ assert(a0.size() == Ndim && DimTan == Ndim); ArrayXXd v0(Ndim, Ndim+1); v0 << a0, MatrixXd::Identity(Ndim, Ndim); ArrayXXcd u0 = R2C(a0); const int Nt = (int)round(tend/h); const int M = (Nt + skip_rate - 1) / skip_rate; ArrayXXcd aa(Ne, M), daa(Ne, Ndim*M); Ts.resize(M); hs.resize(M); lte.resize(M); int ks = 0; auto ss = [this, &ks, &aa, &daa](ArrayXXcd &x, double t, double h, double err){ int m = Ts.size(); if (ks >= m ) { Ts.conservativeResize(m+cellSize); hs.conservativeResize(m+cellSize); lte.conservativeResize(m+cellSize); aa.conservativeResize(Eigen::NoChange, m+cellSize); // rows not change, just extend cols daa.conservativeResize(Eigen::NoChange, (m+cellSize)*Ndim); } hs(ks) = h; lte(ks) = err; Ts(ks) = t; aa.col(ks) = x.col(0); daa.middleCols(ks*Ndim, Ndim) = x.rightCols(Ndim); x.rightCols(Ndim) = R2C(MatrixXd::Identity(Ndim, Ndim)); ks++; }; eidc2.intg(nl2, ss, 0, u0, tend, h, skip_rate); return std::make_pair(C2R(aa), C2R(daa)); } ArrayXXd CQCGL1dSub::intgv(const ArrayXXd &a0, const ArrayXXd &v, const double h, const double tend){ assert( Ndim == a0.size() && Ndim == v.rows() && DimTan == v.cols()); ArrayXXd v0(Ndim, DimTan+1); v0 << a0, v; ArrayXXcd u0 = R2C(v0); ArrayXXcd aa(Ne, DimTan+1); auto ss = [this, &aa](ArrayXXcd &x, double t, double h, double err){ aa = x; }; eidc2.intg(nl2, ss, 0, u0, tend, h, 1000000); return C2R(aa); } ArrayXXd CQCGL1dSub::C2R(const ArrayXXcd &v){ return Map<ArrayXXd>((double*)&v(0,0), 2*v.rows(), v.cols()); } ArrayXXcd CQCGL1dSub::R2C(const ArrayXXd &v){ assert( 0 == v.rows() % 2); return Map<ArrayXXcd>((dcp*)&v(0,0), v.rows()/2, v.cols()); } /* -------------------------------------------------- */ /* ------- Fourier/Configure transformation -------- */ /* -------------------------------------------------- */ /** * @brief back Fourier transform of the states. */ ArrayXXcd CQCGL1dSub::Fourier2Config(const Ref<const ArrayXXd> &aa){ int cs = aa.cols(), rs = aa.rows(); assert(Ndim == rs); ArrayXXcd aac = R2C(aa); ArrayXXcd modes(N, cs); modes << aac, ArrayXXcd::Zero(N-2*Ne+1, cs), aac.bottomRows(Ne-1).colwise().reverse(); ArrayXXcd field(N, cs); for(size_t i = 0; i < cs; i++) fft.inv(field.data() + i*N, modes.data() + i*N, N); return field; } /** * @brief Fourier transform of the states. Input and output are both real. */ ArrayXXd CQCGL1dSub::Config2Fourier(const Ref<const ArrayXXcd> &field){ int cs = field.cols(), rs = field.rows(); assert(N == rs); ArrayXXcd modes(N, cs); for(size_t i = 0; i < cs; i++) fft.fwd(modes.data() + i*N, field.data() + i*N, N); return C2R(modes.topRows(Ne)); } ArrayXXd CQCGL1dSub::calPhase(const Ref<const ArrayXXcd> &AA){ int m = AA.cols(); int n = AA.rows(); assert(N == n); ArrayXXd phase(n, m); for(size_t i = 0; i < m; i++) for(size_t j =0; j < n; j++) phase(j, i) = atan2(AA(j, i).imag(), AA(j, i).real()); return phase; } /** * @brief calculate the mean energy density * \frac{\int |A|^2 dx}{\int dx} = 1/N \sum |A_i|^2 = 1/N^2 \sum |a_i|^2 * = 1/N^2 \sum (a_r^2 + a_i^2) */ VectorXd CQCGL1dSub::calQ(const Ref<const ArrayXXd> &aa){ const int n = aa.cols(); VectorXd Q(n); for (int i = 0; i < n; i++){ Q(i) = aa.col(i).matrix().squaredNorm() / (N*N); } return Q; } VectorXd CQCGL1dSub::calMoment(const Ref<const ArrayXXd> &aa, const int p){ const int n = aa.cols(); VectorXd mom(n); ArrayXd x = ArrayXd::LinSpaced(N, 0, N-1) * d / N; ArrayXd xp = x; for(int i = 0; i < p-1; i++) xp *= x; ArrayXXcd AA = Fourier2Config(aa); for (int i = 0; i < n; i++){ ArrayXd A2 = (AA.col(i) * AA.col(i).conjugate()).real(); mom(i) = (A2 * xp).sum() / A2.sum(); } return mom; } /* -------------------------------------------------- */ /* -------- velocity field ----------- */ /* -------------------------------------------------- */ /** * @brief velocity field */ ArrayXd CQCGL1dSub::velocity(const ArrayXd &a0){ assert( Ndim == a0.rows() ); ArrayXXcd A = R2C(a0); ArrayXXcd v(Ne, 1); nl(A, v, 0); return C2R(L*A + v); } /** * @brief the generalized velociyt for relative equilibrium * * v(x) + \omega_\tau * t_\tau(x) + \omega_\rho * t_\rho(x) */ ArrayXd CQCGL1dSub::velocityReq(const ArrayXd &a0, const double wphi){ return velocity(a0) + wphi*phaseTangent(a0); } /* -------------------------------------------------- */ /* -------- stability matrix ----------- */ /* -------------------------------------------------- */ MatrixXd CQCGL1dSub::stab(const ArrayXd &a0){ assert(a0.size() == Ndim && DimTan == Ndim); ArrayXXd v0(Ndim, Ndim+1); v0 << a0, MatrixXd::Identity(Ndim, Ndim); ArrayXXcd u0 = R2C(v0); ArrayXXcd v(Ne, Ndim+1); nl2(u0, v, 0); ArrayXXcd j0 = R2C(MatrixXd::Identity(Ndim, Ndim)); MatrixXcd Z = j0.colwise() * L + v.rightCols(Ndim); return C2R(Z); } /** * @brief stability for relative equilbrium */ MatrixXd CQCGL1dSub::stabReq(const ArrayXd &a0, double wphi){ return stab(a0) + wphi*phaseGenerator(); } /** * @brief stability exponents of req */ VectorXcd CQCGL1dSub::eReq(const ArrayXd &a0, double wphi){ return eEig(stabReq(a0, wphi), 1); } /** * @brief stability vectors of req */ MatrixXcd CQCGL1dSub::vReq(const ArrayXd &a0, double wphi){ return vEig(stabReq(a0, wphi), 1); } /** * @brief stability exponents and vectors of req */ std::pair<VectorXcd, MatrixXcd> CQCGL1dSub::evReq(const ArrayXd &a0, double wphi){ return evEig(stabReq(a0, wphi), 1); } /* -------------------------------------------------- */ /* ------ symmetry related ------ */ /* -------------------------------------------------- */ ArrayXXd CQCGL1dSub::phaseRotate(const Ref<const ArrayXXd> &aa, const double phi){ return C2R( R2C(aa) * exp(dcp(0,1)*phi) ); // a0*e^{i\phi} } ArrayXXd CQCGL1dSub::phaseTangent(const Ref<const ArrayXXd> &modes){ return C2R( R2C(modes) * dcp(0,1) ); } /** @brief group generator */ MatrixXd CQCGL1dSub::phaseGenerator(){ MatrixXd T = MatrixXd::Zero(Ndim, Ndim); for(size_t i = 0; i < Ne; i++){ T(2*i, 2*i+1) = -1; T(2*i+1, 2*i) = 1; } return T; } <file_sep>from personalFunctions import * class KSplot(): """ KS help class. Its main funciton is to load data and plot figures. """ def __init__(self, ks=None): """ initialization with >> ksp = KSplot(ks) or >> ksp = KSplot() """ self.ks = ks self.N = ks.N if ks is not None else None self.L = ks.d if ks is not None else None # pass def F2C(self, aa): """ Fourier modes a_k(t) to physical state u(x,t) Parameter ====== aa : real and imaignary part of the Fourier modes. Can be 1d or 2d Return ====== AA : the physical space states (real). """ if aa.ndim == 1: half1 = aa[0::2] + 1j*aa[1::2] half2 = aa[0::2] - 1j*aa[1::2] aaWhole = np.hstack(([0], half1, [0], half2[::-1])) AA = np.fft.ifft(aaWhole).real # only the real part else: half1 = aa[:, 0::2] + 1j*aa[:, 1::2] half2 = aa[:, 0::2] - 1j*aa[:, 1::2] M = half1.shape[0] aaWhole = np.hstack((np.zeros((M, 1)), half1, np.zeros((M, 1)), half2[:, ::-1])) AA = np.fft.ifftn(aaWhole, axes=(1,)).real # only the real part # because we have a different normalization conversion for FFT, # we need to multiply the result with N. return self.N * AA def readEq(self, fileName, idx): f = h5py.File(fileName, 'r') req = '/' + 'E' + '/' + str(idx) + '/' a = f[req+'a'].value err = f[req+'err'].value f.close() return a, err def readReq(self, fileName, idx): f = h5py.File(fileName, 'r') req = '/' + 'tw' + '/' + str(idx) + '/' a = f[req+'a'].value w = f[req+'w'].value err = f[req+'err'].value f.close() return a, w, err def stabEig(self, a0): stab = self.ks.stab(a0).T eigvalue, eigvector = LA.eig(stab) eigvalue, eigvector = sortByReal(eigvalue, eigvector) return eigvalue, eigvector def stabReqEig(self, a0, w): stab = self.ks.stabReq(a0, w).T eigvalue, eigvector = LA.eig(stab) eigvalue, eigvector = sortByReal(eigvalue, eigvector) return eigvalue, eigvector def toStr(self, poType, idx, L=22, flag=0): if flag == 0: return poType + '/' + format(idx, '06d') else: return format(L, '010.6f') + '/' + poType + '/' + format(idx, '06d') def checkExist(self, fileName, groupName): f = h5py.File(fileName, 'r') x = groupName in f f.close() return x def readPO(self, fileName, groupName, isRPO, hasNstp=True, flag=0): f = h5py.File(fileName, 'r') DS = '/' + groupName + '/' a = f[DS+'a'].value T = f[DS+'T'].value nstp = f[DS+'nstp'].value if hasNstp else 0 err = f[DS+'err'].value theta = f[DS+'theta'].value if isRPO else 0 e = f[DS+'e'].value if flag > 0 else None v = f[DS+'v'].value if flag > 1 else None f.close() return a, T, nstp, theta, err, e, v def copyTo(self, inFile, outFile, poType, r): inF = h5py.File(inFile, 'r') outF = h5py.File(outFile, 'a') if not ('/' + poType in outF): outF.create_group('/' + poType) for i in r: print i ds = '/' + poType + '/' + str(i) h5py.h5o.copy(inF.id, ds, outF.id, ds) inF.close() outF.close() def oneConfig(self, A, isFourier=True, size=[6, 5], labs=[r'$x$', r'$u$'], xlim=[0, 22], axisLabelSize=20, tickSize=None, save=False, name='out.png'): """ plot the configuration at one point or plot one eigen vector. Parameter ====== isFourier : is the input the Fourier modes of A. If it is, then we need back FFT. """ fig, ax = pl2d(size=size, labs=labs, xlim=xlim, axisLabelSize=axisLabelSize, tickSize=tickSize) if isFourier: A = self.F2C(A) ax.plot(np.linspace(0, self.L, A.shape[0]), A, lw=1.5) ax2d(fig, ax, save=save, name=name) def config(self, A, ext, isFourier=True, barOn=True, barTicks=[-3, -2, -1, 0, 1, 2, 3], colortype='jet', percent='5%', size=[3, 6], labs=[r'$x$', r'$t$'], axisLabelSize=20, tickSize=None, save=False, name='out.png'): """ plot the color map of the states """ if isFourier: A = self.F2C(A) fig, ax = pl2d(size=size, labs=labs, axisLabelSize=axisLabelSize, tickSize=tickSize) im = ax.imshow(A, cmap=plt.get_cmap(colortype), extent=ext, aspect='auto', origin='lower') ax.grid('on') if barOn: dr = make_axes_locatable(ax) cax = dr.append_axes('right', size=percent, pad=0.05) bar = plt.colorbar(im, cax=cax, ticks=barTicks) ax2d(fig, ax, save=save, name=name) def poHeat(self, fileName, poType, poId, NT=1, Ts=100, fixT=False): """ plot the heat map of ppo/rpo. Sometimes, a few periods make it easy to observe the state space. Also, fixing an integration time makes it easy to see the transition NT : the number of periods need to be ploted """ a0, T, nstp, r, s = self.readPO(fileName, poType, poId) h = T / nstp if fixT: aa = self.ks.intg(a0, h, np.int(Ts/h), 5) self.config(aa, [0, ks.d, 0, Ts]) else: aa = self.ks.intg(a0, h, nstp*NT, 5) self.config(aa, [0, ks.d, 0, T*NT]) <file_sep>import os from py_ks import * from personalFunctions import * ################################################## def add_subplot_axes(ax, rect, axisbg='w'): """ function to add embedded plot rect = [ x of left corner, y of left corner, width, height ] in percentage """ fig = plt.gcf() box = ax.get_position() width = box.width height = box.height inax_position = ax.transAxes.transform(rect[0:2]) transFigure = fig.transFigure.inverted() infig_position = transFigure.transform(inax_position) x = infig_position[0] y = infig_position[1] width *= rect[2] height *= rect[3] # <= Typo was here subax = fig.add_axes([x, y, width, height], axisbg=axisbg) x_labelsize = subax.get_xticklabels()[0].get_size() y_labelsize = subax.get_yticklabels()[0].get_size() x_labelsize *= rect[2]**0.5 y_labelsize *= rect[3]**0.5 subax.xaxis.set_tick_params(labelsize=x_labelsize) subax.yaxis.set_tick_params(labelsize=y_labelsize) return subax def setAxis(ax): # ax.set_xlabel(r'$\theta$', fontsize=20, labelpad=-40) ax.set_xticks([0., .125*pi, 0.25*pi, 0.375*pi, 0.5*pi]) ax.set_xticklabels(["$0$", r"$\frac{1}{8}\pi$", r"$\frac{1}{4}\pi$", r"$\frac{3}{8}\pi$", r"$\frac{1}{2}\pi$"], fontsize=15) # ax.legend(loc='best', fontsize=12) ax.set_yscale('log') # ax.set_ylim([0.01, 100]) # ax.text(0.02, 20, r'$\rho(\theta)$', fontsize=20) # ax.set_ylabel(r'$\rho(\theta)$', fontsize=20, labelpad=-55) def filterAng(a, ns, angSpan, angNum): """ filter the bad statistic points because a very small fraction of Floquet vectors corresponding to high Fourier modes are not well told apart, so there are a small fraction of misleading close to zeros angles for non-physical space. """ for i in range(29): n = a[0].shape[0] for j in range(n): y = a[i][j]*ns/(angSpan[i]*angNum[i]) if y < 2e-2: a[i][j] = 0 situation = 2 if situation == 1: ################################################## # load data ixRange = range(0, 29) N = len(ixRange) folder = './anglePOs64/ppo/space/' folder2 = './anglePOs64/rpo/space/' ns = 1000 # collect the data with rpo, ppo combined angs = [] for i in range(N): print i as1 = np.empty(0) as2 = np.empty(0) for j in range(1, 201): f1 = folder + str(j) + '/ang' + str(i) + '.dat' if os.stat(f1).st_size > 0: ang = np.arccos(np.loadtxt(f1)) as1 = np.append(as1, ang) f2 = folder2 + str(j) + '/ang' + str(i) + '.dat' if os.stat(f2).st_size > 0: ang2 = np.arccos(np.loadtxt(f2)) as2 = np.append(as2, ang2) angs.append(np.append(as1, as2)) # angs.append(as2) # angs.append(as1) ################################################## case = 2 if case == 1: """ angle distribution in ppo and rpo """ a = [] b = [] angNum = [] angSpan = [] for i in range(N): print i angNum.append(angs[i].shape[0]) angSpan.append(max(angs[i])-min(angs[i])) at, bt = histogram(angs[i], ns) a.append(at) b.append(bt) labs = ['k='+str(i+1) for i in ixRange] np.savez_compressed('ab', a=a, b=b, ns=ns, angSpan=angSpan, angNum=angNum) fig = plt.figure(figsize=(4, 1.5)) ax = fig.add_subplot(111) for i in range(7): ax.plot(b[i][:-1], a[i]*ns/(angSpan[i]*angNum[i]), label=labs[i], lw=1.5) setAxis(ax) plt.tight_layout(pad=0) plt.show(block=False) fig = plt.figure(figsize=(4, 1.5)) ax = fig.add_subplot(111) colors = cm.rainbow(linspace(0, 1, 11)) for ix in range(11): i = 7 + 2*ix ax.plot(b[i][:-1], a[i]*ns/(angSpan[i]*angNum[i]), c=colors[ix], lw=1.5) setAxis(ax) plt.tight_layout(pad=0) plt.show(block=False) if case == 2: """ try to locate the resource of bad distribution at the bottom """ a = [] b = [] angNum = [] angSpan = [] for i in range(N): if angs[i].shape[0] > 0: angNum.append(angs[i].shape[0]) angSpan.append(max(angs[i])-min(angs[i])) at, bt = histogram(angs[i], ns) a.append(at) b.append(bt) labs = ['k='+str(i+1) for i in ixRange] fig = plt.figure(figsize=(4, 1.5)) ax = fig.add_subplot(111) for i in range(len(a)): ax.plot(b[i][:-1], a[i]*ns/(angSpan[i]*angNum[i]), label=labs[i], lw=1.5) setAxis(ax) plt.tight_layout(pad=0) plt.show(block=False) if case == 20: a = [] b = [] angNum = [] angSpan = [] for i in range(N): print i angNum.append(angs[i].shape[0]) angSpan.append(max(angs[i])-min(angs[i])) at, bt = histogram(log(angs[i]), ns) a.append(at) b.append(bt) fig = plt.figure(figsize=(7, 5)) ax = fig.add_subplot(111) colors = cm.rainbow(linspace(0, 1, N)) #labs = ['(1-' + str(i+1) + ',' + str(i+2) + '-30)' for i in ixRange] labs = ['(' + str(i+1) + ',' + str(i+2) + ')' for i in ixRange] labx = [pi/16, pi/8*1.1, pi/8*0.9, pi/8*3*0.9, pi/2*0.8] laby = [0.9, 0.02, 0.1, 0.05, 0.005] ax.set_xlabel(r'$\theta$', size='large') ax.set_xticks([0., .125*pi, 0.25*pi, 0.375*pi]) ax.set_xticklabels(["$0$", r"$\frac{1}{8}\pi$", r"$\frac{2}{8}\pi$", r"$\frac{3}{8}\pi$"]) for i in range(9): ax.scatter(b[i][:-1], a[i]*ns/(angSpan[i]*angNum[i]), s=7, c=colors[i], edgecolor='none', label=labs[i]) ax.legend(fontsize='small', loc='upper center', ncol=1, bbox_to_anchor=(1.1, 1), fancybox=True) ax.set_yscale('log') ax.set_ylim([0.001, 1000]) ax.set_ylabel(r'$\rho(\theta)$', size='large') plt.tight_layout(pad=0) plt.show() if case == 30: nstps = [] for i in range(200): a, T, nstp, r, s = KSreadPO('../ks22h001t120x64EV.h5', 'rpo', i+1) nstps.append(nstp) nstps = np.array(nstps) if situation == 2: """ pick out the orbit with smallest angle """ ixRange = range(0, 29) N = len(ixRange) folder = './anglePOs64/ppo/space/' folder2 = './anglePOs64/rpo/space/' ns = 1000 # collect the data with rpo, ppo combined as1 = [] as2 = [] n1 = [] n2 = [] i = 1 for j in range(1, 201): f1 = folder + str(j) + '/ang' + str(i) + '.dat' if os.stat(f1).st_size > 0: ang = np.arccos(np.loadtxt(f1)) as1 = np.append(as1, ang) n1.append(ang.shape[0]) else: n1.append(0) f2 = folder2 + str(j) + '/ang' + str(i) + '.dat' if os.stat(f2).st_size > 0: ang2 = np.arccos(np.loadtxt(f2)) as2 = np.append(as2, ang2) n2.append(ang2.shape[0]) else: n2.append(0) ma1 = np.min(as1) ma2 = np.min(as2) ix1 = np.argmin(as1) ix2 = np.argmin(as2) print ma1, ma2, ix1, ix2 s = 0 for i in range(len(n1)): s += n1[i] if s >= ix1: print i, s break mix = i + 1 i1 = np.sum(n1[:i]) i2 = np.sum(n1[:i+1]) fig = plt.figure(figsize=(6, 4)) ax = fig.add_subplot(111) ax.plot(as1[i1:i2], lw=1.5) ax.set_yscale('log') ax.set_ylabel(r'$\theta$') plt.tight_layout(pad=0) plt.show(block=False) if situation == 3: """ After we pick out the smallest angle orbit, let us plot the distribution """ ixRange = range(0, 29) N = len(ixRange) folder = './anglePOs64/ppo/space/147' ns = 1000 # collect the data with rpo, ppo combined as1 = [] for i in range(N): f1 = folder + '/ang' + str(i) + '.dat' if os.stat(f1).st_size > 0: ang = arccos(loadtxt(f1)) as1.append(ang) else: as1.append(np.array([])) a = [] b = [] for i in range(N): at, bt = histogram(as1[i], ns) # print as1[i].shape, at.shape, bt.shape a.append(at) b.append(bt) labs = ['k='+str(i+1) for i in ixRange] fig = plt.figure(figsize=(4, 1.5)) ax = fig.add_subplot(111) for i in range(7): ax.plot(b[i][:-1], a[i], label=labs[i], lw=1.5) setAxis(ax) plt.tight_layout(pad=0) plt.show(block=False) fig = plt.figure(figsize=(4, 1.5)) ax = fig.add_subplot(111) colors = cm.rainbow(linspace(0, 1, 11)) for ix in range(11): i = 7 + 2*ix ax.plot(b[i][:-1], a[i], c=colors[ix], lw=1.5) setAxis(ax) plt.tight_layout(pad=0) plt.show(block=False) if situation == 4: """ There seems periodic peaks on top of the angle for ppo 147, we want to find out the reason """ poType = 'ppo' poId = 147 a0, T, nstp, r, s = KSreadPO('../ks22h001t120x64EV.h5', poType, poId) h = T / nstp ks = pyKS(64, h, 22) aa = ks.intg(a0, nstp, 5) # aa = ks.reduceReflection(ks.orbitToSlice(aa)[0]) peaks = [180, 1485, 3701, 6243, 8980, 11262, 13869, 16541] colors = plt.cm.winter(np.linspace(0, 1, len(peaks))) i1 = 0 i2 = 2 i3 = 3 fig = plt.figure(figsize=[8, 6]) ax = fig.add_subplot(111, projection='3d') ax.plot(aa[:, i1], aa[:, i2], aa[:, i3], c='r', lw=2) for i, c in zip(peaks, colors): ax.scatter(aa[i, i1], aa[i, i2], aa[i, i3], marker='o', c=c, edgecolor='none', s=50) ax.set_xlabel(r'$b_1$', fontsize=30) ax.set_ylabel(r'$b_2$', fontsize=30) ax.set_zlabel(r'$c_2$', fontsize=30) fig.tight_layout(pad=0) plt.show(block=False) def getDet(poType, poId, k=30): fv = KSreadFV('../ks22h001t120x64EV.h5', poType, poId) n, m = fv.shape ds = np.zeros(n) for i in range(n): x = np.reshape(fv[i], (30, m/30)) x = x[:k, :k] ds[i] = LA.det(x) return ds def getDetK(poType, poId): dss = [] for k in range(1, 8) + range(8, 31, 2): # print k ds = getDet(poType, poId, k) dss.append(ds) return np.array(dss) if situation == 5: """ try to see whether the determiant of Floquet vector matrix change sign for a specific orbit """ poType = 'ppo' for i in range(146, 147): poId = i+1 ds = getDet(poType, poId, 4) print poId, np.sign(np.max(ds)) * np.sign(np.min(ds)) plot1dfig(abs(ds), yscale='log') if situation == 6: """ try to plot the determinant of the leading k block. """ poType = 'ppo' poId = 147 dss = getDetK(poType, poId) m, n = dss.shape ers = np.zeros(m-1) for i in range(m-1): ers[i] = norm(dss[i]-dss[-1]) plot1dfig(ers, yscale='log') plot1dfig(abs(dss[3]), yscale='log', labs=[None, '|det|'], axisLabelSize=15, size=[6, 4]) fig = plt.figure(figsize=[6, 4]) ax = fig.add_subplot(111) ax.plot(abs(dss[2]), lw=1, label=r'$k=3$') ax.plot(abs(dss[5]), lw=2, ls='--', label=r'$k=6$') ax.plot(abs(dss[6]), lw=2, ls='-.', label=r'$k=7$') # ax.plot(abs(dss[7]), lw=1, label=r'$k=8$') # ax.plot(abs(dss[12]), lw=2, ls='--', label=r'$k=18$') # ax.plot(abs(dss[18]), lw=2, ls='-.', label=r'$k=30$') ax.set_ylabel('|det|', fontsize=15) ax.set_yscale('log') fig.tight_layout(pad=0) plt.legend(loc='best') plt.show(block=False) if situation == 7: """ """ N = 64 h = 0.001 L = 22 ks = pyKS(N, h, L) a0, w, err = KSreadReq('../ks22Reqx64.h5', 1) es, vs = KSstabReqEig(ks, a0, w) a0, err = KSreadEq('../ks22Reqx64.h5', 1) es, vs = KSstabEig(ks, a0) a0H = ks.orbitToSlice(a0)[0] if situation == 8: """ There seems periodic peaks on top of the angle for ppo 147, we want to find out the reason. Here I use covariant axis to visulzie ppo """ poType = 'ppo' poId = 147 a0, T, nstp, r, s = KSreadPO('../ks22h001t120x64EV.h5', poType, poId) h = T / nstp ks = pyKS(64, h, 22) aa = ks.intg(a0, nstp, 5) # aa = ks.reduceReflection(ks.orbitToSlice(aa)[0]) peaks = [180, 1485, 3701, 6243, 8980, 11262, 13869, 16541] colors = plt.cm.winter(np.linspace(0, 1, len(peaks))) i1 = 0 i2 = 2 i3 = 3 fig = plt.figure(figsize=[8, 6]) ax = fig.add_subplot(111, projection='3d') ax.plot(aa[:, i1], aa[:, i2], aa[:, i3], c='r', lw=2) for i, c in zip(peaks, colors): ax.scatter(aa[i, i1], aa[i, i2], aa[i, i3], marker='o', c=c, edgecolor='none', s=50) ax.set_xlabel(r'$b_1$', fontsize=30) ax.set_ylabel(r'$b_2$', fontsize=30) ax.set_zlabel(r'$c_2$', fontsize=30) fig.tight_layout(pad=0) plt.show(block=False) <file_sep>/* compile command: * mex CXXFLAGS='-std=c++0x -fPIC -O3' orbitToSlice.cc ../ksint.cc -I../../../include -I$XDAPPS/eigen/include/eigen3 -lfftw3 * */ #include "ksint.hpp" #include "mex.h" #include <cmath> #include <cstring> #include <Eigen/Dense> using Eigen::ArrayXXd; using Eigen::ArrayXd; using Eigen::Map; /* transform trajectory into 1st mode slice */ static std::pair<MatrixXd, VectorXd> orbitToSlice(double *aa, const int N, const int M){ KS ks(N+2); Map<MatrixXd> aa2(aa, N, M); return ks.orbitToSlice(aa2); } void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[]){ // get the pointer and the size of input double *aa = mxGetPr(prhs[0]); mwSize N = mxGetM(prhs[0]); mwSize M = mxGetN(prhs[0]); plhs[0] = mxCreateDoubleMatrix(N, M, mxREAL); plhs[1] = mxCreateDoubleMatrix(M, 1, mxREAL); std::pair<MatrixXd, VectorXd> tmp = orbitToSlice(aa, N, M); memcpy(mxGetPr(plhs[0]), &tmp.first(0,0), N*M*sizeof(double)); memcpy(mxGetPr(plhs[1]), &tmp.second(0), M*sizeof(double)); } <file_sep>from personalFunctions import * from py_ks import * case = 10 N, L = 64, 22 eqFile = '../../data/ks22Reqx64.h5' poFile = '../../data/ks22h001t120x64EV.h5' if case == 10: """ print the exponents of ppo/rpo """ ks = pyKS(N, L) ksp = KSplot(ks) fe = ksp.readFE(poFile, 'rpo', 3) np.set_printoptions(formatter={'float': '{: 15.6f}'.format}) print fe[:, np.r_[0:10, -4:0]].T # print formated 10 first and 4 last np.set_printoptions() print print fe[0, :4].T # print the marginal ones <file_sep>/* How to compile: * mpicxx test_ksrefine.cc -cxx=h5c++ -O3 -L ../../lib -I ../../include * -I $XDAPPS/eigen/include/eigen3 -std=c++0x * -lreadks -lksrefine -lped -lksint -lfftw3 -lm -std=c++0x * */ #include "ksrefine.hpp" #include "ksint.hpp" #include "readks.hpp" #include <iostream> #include <cmath> #include <mpi.h> using namespace std; using namespace Eigen; int main(int argc, char **argv) { cout.precision(16); switch (3) { case 1: // test multiF(). For rpo, the shift should be reversed. { string fileName("../../data/ks22h02t100"); string ppType("ppo"); const int ppId = 1; ReadKS readks(fileName+".h5", fileName+"E.h5", fileName+"EV.h5"); std::tuple<ArrayXd, double, double, double, double> pp = readks.readKSinit(ppType, ppId); ArrayXd &a = get<0>(pp); double T = get<1>(pp); int nstp = (int)get<2>(pp); double r = get<3>(pp); double s = get<4>(pp); KS ks(32, T/nstp, 22); ArrayXXd aa = ks.intg(a, nstp, nstp/10); KSrefine ksrefine(32, 22); VectorXd F = ksrefine.multiF(ks, aa.leftCols(aa.cols()-1), nstp/10, ppType, -s/22*2*M_PI); cout << F.norm() << endl; break; } case 2: // test findPO() { const int Nks = 64; const int N = Nks - 2; const double L = 22; string fileName("../../data/ks22h1t120x64"); string ppType("rpo"); const int ppId = 23; ReadKS readks(fileName+".h5", fileName+"E.h5", fileName+"EV.h5", N, Nks, L); std::tuple<ArrayXd, double, double> pp = readks.readKSorigin(ppType, ppId); ArrayXd &a = get<0>(pp); double T = get<1>(pp); double s = get<2>(pp); cout << s << endl; const int nstp = ceil(ceil(T/0.001)/10)*10; cout << nstp << endl; KSrefine ksrefine(Nks, L); tuple<MatrixXd, double, double, double> p = ksrefine.findPOmulti(a, T, nstp, 10, ppType, 0.1, -s/L*2*M_PI, 20, 1e-14, true, false); cout << get<0>(p).cols() << endl; cout << get<1>(p) * nstp << endl; cout << get<2>(p) << endl; cout << get<3>(p) << endl; KS ks(Nks, get<1>(p), L); VectorXd df = ksrefine.multiF(ks, get<0>(p), nstp/10, ppType, get<2>(p)); VectorXd df2 = ksrefine.multiF(ks, get<0>(p).col(0), nstp, ppType, get<2>(p)); cout << df.norm() << endl; cout << df2.norm() << endl; break; } case 3: // distiguish rpo5 and rpo6 { const int Nks = 32; const int N = Nks - 2; const double L = 22; string fileName("../../data/ks22h1t120"); string ppType("rpo"); const int ppId = 17; ReadKS readks(fileName+".h5", fileName+"E.h5", fileName+"EV.h5", N, Nks, L); std::tuple<ArrayXd, double, double> pp = readks.readKSorigin(ppType, ppId); ArrayXd &a = get<0>(pp); double T = get<1>(pp); double s = get<2>(pp); cout << s << endl; const int nstp = ceil(ceil(T/0.02)/10)*10; cout << nstp << endl; KSrefine ksrefine(Nks, L); tuple<MatrixXd, double, double, double> p = ksrefine.findPOmulti(a, T, nstp, 10, ppType, 0.25, -s/L*2*M_PI, 100, 1e-15, true, false); double th = get<2>(p); cout << th << endl; double Tnew = get<1>(p) * nstp; std::cout << Tnew << std::endl; cout << get<0>(p).cols() << endl; cout << get<3>(p) << endl; // calculate the Flqouet exponents KS ks(Nks, get<1>(p), L); MatrixXd daa = ks.intgjMulti(get<0>(p), nstp/10, 1, 1).second; PED ped; ped.reverseOrderSize(daa); // reverse order. if(ppType.compare("ppo") == 0) daa.leftCols(N) = ks.reflect(daa.leftCols(N)); // R*J for ppo else // R*J for rpo daa.leftCols(N) = ks.rotate(daa.leftCols(N), th); //MatrixXd eigvals = ped.EigVals(daa, 1000, 1e-15, true); //eigvals.col(0) = eigvals.col(0).array()/Tnew; //cout << eigvals << endl; // write data /* fileName = "../../data/ks22h02t100"; ReadKS readks2(fileName+".h5", fileName+"E.h5", fileName+"EV.h5", N, Nks, L); readks2.writeKSinit("../../data/ks22h1t120.h5", ppType, ppId, make_tuple(get<0>(p).col(0), get<1>(p)*nstp, nstp, get<3>(p), -L/(2*M_PI)*get<2>(p)) ); readks2.calKSOneOrbit(ppType, ppId, 1000, 1e-15, false); */ break; } case 4: // refine the inital condition for N=32 { const int Nks = 64; const int N = Nks - 2; const double L = 22; string fileName("../../data/ks22h1t120x64"); string ppType("ppo"); ReadKS readks(fileName+".h5", fileName+"E.h5", fileName+"EV.h5", N, Nks, L); int NN(0); if(ppType.compare("ppo") == 0) NN = 840; else NN = 834; const int MaxN = 30; const double tol = 1e-14; const int M = 10; //////////////////////////////////////////////////////////// // mpi part int left = 0; int right = NN; MPI_Init(&argc, &argv); int rank, num; MPI_Comm_rank(MPI_COMM_WORLD, &rank); MPI_Comm_size(MPI_COMM_WORLD, &num); int inc = ceil( (double)(right - left) / num); int istart = left + rank * inc; int iend = min( left + (rank+1) * inc, right); printf("MPI : %d / %d; range : %d - %d \n", rank, num, istart, iend); //////////////////////////////////////////////////////////// for(int i = istart; i < iend; i++){ const int ppId = i+1; std::tuple<ArrayXd, double, double> pp = readks.readKSorigin(ppType, ppId); ArrayXd &a = get<0>(pp); double T = get<1>(pp); double s = get<2>(pp); const int nstp = ceil(ceil(T/0.001)/10)*10; KSrefine ksrefine(Nks, L); tuple<MatrixXd, double, double, double> p = ksrefine.findPOmulti(a, T, nstp, M, ppType, 0.1, -s/L*2*M_PI, MaxN, tol, false, false); printf("r = %g for %s ppId = %d \n", get<3>(p), ppType.c_str(), ppId); readks.writeKSinitMulti("../../data/tmp.h5", ppType, ppId, make_tuple(get<0>(p), get<1>(p)*nstp, nstp, get<3>(p), -L/(2*M_PI)*get<2>(p)) ); } //////////////////////////////////////////////////////////// MPI_Finalize(); //////////////////////////////////////////////////////////// break; } case 5 : // refine step by step { const int Nks = 64; const int N = Nks - 2; const double L = 22; string fileName("../../data/ks22h001t120x64"); string ppType("rpo"); ReadKS readks(fileName+".h5", fileName+"E.h5", fileName+"EV.h5", N, Nks, L); int NN(0); if(ppType.compare("ppo") == 0) NN = 840; else NN = 834; const int MaxN = 100; const double tol = 1e-14; const int M = 10; //////////////////////////////////////////////////////////// // mpi part int left = 0; int right = NN; MPI_Init(&argc, &argv); int rank, num; MPI_Comm_rank(MPI_COMM_WORLD, &rank); MPI_Comm_size(MPI_COMM_WORLD, &num); int inc = ceil( (double)(right - left) / num); int istart = left + rank * inc; int iend = min( left + (rank+1) * inc, right); printf("MPI : %d / %d; range : %d - %d \n", rank, num, istart, iend); //////////////////////////////////////////////////////////// for(int i = istart; i < iend; i++){ const int ppId = i+1; // printf("\n**** ppId = %d ****** \n", ppId); std::tuple<ArrayXd, double, double, double, double> pp = readks.readKSinit(ppType, ppId); ArrayXd &a = get<0>(pp); double T = get<1>(pp); int nstp = (int) get<2>(pp); double r = get<3>(pp); // printf("r = %g\n", r); double s = get<4>(pp); double hinit = T / nstp; // nstp *= 5; KSrefine ksrefine(Nks, L); tuple<MatrixXd, double, double, double> p = ksrefine.findPOmulti(a, T, nstp, M, ppType, hinit, -s/L*2*M_PI, MaxN, tol, false, true); printf("r = %g for %s ppId = %d \n", get<3>(p), ppType.c_str(), ppId); readks.writeKSinitMulti("../../data/tmp.h5", ppType, ppId, make_tuple(get<0>(p), get<1>(p)*nstp, nstp, get<3>(p), -L/(2*M_PI)*get<2>(p)) ); } //////////////////////////////////////////////////////////// MPI_Finalize(); //////////////////////////////////////////////////////////// break; } } return 0; } <file_sep>#!/bin/bash # usage: # ./createAll 0 => compile all cases # ./createAll 1 => single thread caes rm -rf bin pylib b2 && mv pylib/py_CQCGL1dSub.so /usr/local/home/xiong/00git/research/lib/boostPython/ rm -rf bin pylib <file_sep>/* g++ test_myfft.cc -lmyfft -lfftw3 -lfftw3_threads -ldenseRoutines -std=c++11 -I ../../include/ -L ../../lib/ -I $XDAPPS/eigen/include/eigen3 -O3 */ #include "myfft.hpp" #include "denseRoutines.hpp" #include <iostream> #include <time.h> #define CE(x) cout << (x) << endl << endl using namespace std; using namespace MyFFT; using namespace Eigen; using namespace denseRoutines; int main(){ switch (2) { case 1 :{ RFFT F(64, 1); ArrayXcd x(ArrayXcd::Random(33)); F.vc1 = x; F.ifft(); break; } case 2 : { /* test FFT2d */ /* for large 2d matrix The c++ version is 2 times slower than Matlab FFT */ clock_t t; FFT2d F(8, 4); ArrayXXcd x = loadComplex("re.dat", "im.dat"); CE(x); F.v1 = x; t = clock(); for (int i = 0; i < 100; i++) F.ifft(); t = clock() - t; cout << "ifft time: " << ((float)t)/CLOCKS_PER_SEC << endl; savetxt("f1.dat", F.v2.real()); savetxt("f2.dat", F.v2.imag()); CE(F.v2); F.fft(); // CE(F.v3); break; } default : { cout << "please indicate the correct number" << cout; break; } } return 0; } <file_sep>// g++ randWalk.cc -O3 -std=c++11 -I$EIGEN -I$RESH/include -L$RESH/lib -ldenseRoutines #include <cmath> #include <ctime> #include <cstdlib> #include <iostream> #include <Eigen/Dense> #include "denseRoutines.hpp" using namespace std; using namespace Eigen; using namespace denseRoutines; typedef std::complex<double> dcp; VectorXd walk2d(const int Np, const int Ns, const double tol){ std::srand(std::time(0)); double max = static_cast<double>(RAND_MAX); VectorXd a(Np), s(Ns); VectorXcd z(Np); a.setZero(); z.setZero(); for (int i = 0; i < Ns; i++){ for(int j = 0; j < Np; j++){ double t, m; do { t = std::rand() / max; Vector3d d; d << fabs(t-a(j)), fabs(t-a(j)+1), fabs(t-a(j)-1) ; m = d.minCoeff(); } while (m < tol); a(j) = t; z(j) += exp(t*2*M_PI*dcp(0,1)); } s(i) = (z.array() * z.array().conjugate()).real().mean(); } return s; } int main(){ const int Np = 10000; const int Ns = 1000; int n = 4; MatrixXd ss(Ns, n); for (int i = 0; i < n; i++){ ss.col(i) = walk2d(Np, Ns, 0.1*i); } savetxt("ss.dat", ss); return 0; } <file_sep>/* to comiple: * * h5c++ test_CQCGL1dRpo.cc -std=c++11 -O3 -march=corei7 -msse4 -msse2 -I$EIGEN -I$RESH/include -L$RESH/lib -lCQCGL1dRpo -lCQCGL1dReq -lCQCGL1d -lmyfft -lfftw3 -lm -lsparseRoutines -ldenseRoutines -literMethod -lmyH5 * */ #include <iostream> #include <fstream> #include <Eigen/Dense> #include <complex> #include <ctime> #include "CQCGL1dReq.hpp" #include "CQCGL1dRpo.hpp" using namespace std; using namespace Eigen; using namespace iterMethod; using namespace MyH5; #define cee(x) (cout << (x) << endl << endl) #define CASE_70 int main(){ cout.precision(15); GMRES_IN_PRINT_FREQUENCE = 50; HOOK_PRINT_FREQUENCE = 1; GMRES_OUT_PRINT = false; #ifdef CASE_10 //====================================================================== // to visulize the limit cycle first const int N = 1024; const double L = 50; double Bi = 0.8; double Gi = -3.6; CQCGL1dRpo cgl(N, L, -0.1, 0.125, 0.5, 1, Bi, -0.1, Gi, -1); string file = "/usr/local/home/xiong/00git/research/data/cgl/rpoT2X1.h5"; ArrayXd a0; double T, th, phi, err; int nstp; std::tie(a0, T, nstp, th, phi, err) = CQCGL1dRpo::read(file, "0.360000/1"); a0 *= 0.316; ArrayXXd aa = cgl.intg(a0, 1e-3, 20000, 10); savetxt("aa.dat", aa); savetxt("lte.dat", cgl.lte); #endif #ifdef CASE_20 //====================================================================== // find one limit cycle using previous data const int N = 1024; const double L = 50; double Bi = 1.9; double Gi = -4.1; int id = 1; CQCGL1dRpo cgl(N, L, -0.1, 0.125, 0.5, 1, Bi, -0.1, Gi, 1); string file = "../../data/cgl/rpoBiGi2.h5"; ArrayXd a0; double T0, th0, phi0, err0; int nstp0; std::tie(a0, T0, nstp0, th0, phi0, err0) = CQCGL1dRpo::read(file, CQCGL1dRpo::toStr(Bi, Gi, id)); cgl.Bi = 1.5; cgl.Gi -= 3.9; double T, th, phi, err; MatrixXd x; int nstp = nstp0; int flag; std::tie(x, err, flag) = cgl.findRPOM_hook2(a0, nstp, 8e-10, 1e-3, 50, 30, 1e-6, 300, 1); if (flag == 0) CQCGL1dRpo::write2("../../data/cgl/rpoBiGi2.h5", cgl.toStr(cgl.Bi, cgl.Gi, 1), x, nstp, err); #endif #ifdef CASE_50 //====================================================================== // find limit cycles by varying Bi and Gi but using propagated initial // condition const int N = 1024; const int L = 50; double Bi = 4.8; double Gi = -4.8; int id = 1; CQCGL1dRpo cgl(N, L, -0.1, 0.125, 0.5, 1, Bi, -0.1, Gi, 1); string file = "../../data/cgl/rpoBiGi2.h5"; ArrayXd x0; double T0, th0, phi0, err0; int nstp0; std::tie(x0, T0, nstp0, th0, phi0, err0) = CQCGL1dRpo::read(file, CQCGL1dRpo::toStr(Bi, Gi, id)); ArrayXd a0 = x0.head(cgl.Ndim); ArrayXXd aa = cgl.intg(a0, T0/nstp0, nstp0, 1); ArrayXd x1(cgl.Ndim+3); x1 << aa.col(3000), T0, th0, phi0; double T, th, phi, err; ArrayXd x; int flag, nstp; nstp = nstp0; cgl.Gi -= 0.1; if (!checkGroup(file, CQCGL1dRpo::toStr(cgl.Bi, cgl.Gi, id), false)){ fprintf(stderr, "Bi = %g Gi = %g nstp = %d T0 = %g\n", cgl.Bi, cgl.Gi, nstp, T0); std::tie(x, err, flag) = cgl.findRPOM_hook2(x1, nstp, 8e-10, 1e-3, 50, 30, 1e-6, 300, 1); if(flag == 0) CQCGL1dRpo::write2(file, cgl.toStr(cgl.Bi, cgl.Gi, id), x, nstp, err); } #endif #ifdef CASE_60 //====================================================================== // find rpo of next one in Bi-Gi plane but using multishooting const int N = 1024; const double L = 50; double Bi = 5.5; double Gi = -5.2; CQCGL1dRpo cgl(N, L, -0.1, 0.125, 0.5, 1, Bi, -0.1, Gi, 1); string file = "../../data/cgl/rpoBiGi2.h5"; ArrayXd x0; double T0, th0, phi0, err0; int nstp0; std::tie(x0, T0, nstp0, th0, phi0, err0) = CQCGL1dRpo::read(file, CQCGL1dRpo::toStr(Bi, Gi, 1)); ArrayXd a0 = x0.head(cgl.Ndim); ArrayXXd aa = cgl.intg(a0, T0/nstp0, nstp0, nstp0/4); MatrixXd x1(cgl.Ndim+3, 4); x1.col(0) << aa.col(0), T0/4, 0, 0; x1.col(1) << aa.col(1), T0/4, 0, 0; x1.col(2) << aa.col(2), T0/4, 0, 0; x1.col(3) << aa.col(3), T0/4, th0, phi0; double T, th, phi, err; MatrixXd x; int nstp = 1000; int flag; cgl.Gi += 0.1; cout << cgl.Bi << ' ' << cgl.Gi << endl; std::tie(x, err, flag) = cgl.findRPOM_hook2(x1, nstp, 8e-10, 1e-3, 50, 30, 1e-6, 300, 1); if (flag == 0) CQCGL1dRpo::write2("rpoBiGi2.h5", cgl.toStr(Bi, Gi, 1), x, nstp, err); #endif #ifdef CASE_70 //====================================================================== // use saved guess directively const int N = 1024; const double L = 50; double Bi = 1.4; double Gi = -3.9; CQCGL1dRpo cgl(N, L, -0.1, 0.125, 0.5, 1, Bi, -0.1, Gi, 1); string file = "../../data/cgl/p.h5"; ArrayXd a0; double T0, th0, phi0, err0; int nstp0; std::tie(a0, T0, nstp0, th0, phi0, err0) = CQCGL1dRpo::read(file, cgl.toStr(Bi, Gi, 1)); VectorXd x0(cgl.Ndim+3); x0 << a0, T0, th0, phi0; // x0 << a0, 3, th0, -7.3; double T, th, phi, err; MatrixXd x; int nstp = nstp0; int flag; std::tie(x, err, flag) = cgl.findRPOM_hook2(x0, nstp, 8e-10, 1e-3, 50, 30, 1e-6, 300, 1); if (flag == 0) CQCGL1dRpo::write2("../../data/cgl/rpoBiGi2.h5", cgl.toStr(Bi, Gi, 1), x, nstp, err); #endif #ifdef CASE_80 //====================================================================== // test the accuracy of a limit cycle const int N = 1024; const double L = 50; double Bi = 1.4; double Gi = -3.9; CQCGL1dRpo cgl(N, L, -0.1, 0.125, 0.5, 1, Bi, -0.1, Gi, 1); string file = "../../data/cgl/rpoBiGi2.h5"; ArrayXd a0; double T0, th0, phi0, err0; int nstp0; std::tie(a0, T0, nstp0, th0, phi0, err0) = CQCGL1dRpo::read(file, cgl.toStr(Bi, Gi, 1)); printf("%g %g %g %g %d\n", T0, th0, phi0, err0, nstp0); double e = cgl.MFx2(a0, nstp0).norm(); cee(e); #endif #ifdef CASE_100 //====================================================================== // find limit cycles by varying Bi and Gi const int N = 1024; const int L = 50; double Bi = 4.9; double Gi = -4.9; int id = 1; CQCGL1dRpo cgl(N, L, -0.1, 0.125, 0.5, 1, Bi, -0.1, Gi, 1); string file = "../../data/cgl/rpoBiGi2.h5"; double step = -0.02; int Ns = 20; cgl.findRpoParaSeq(file, id, step, Ns, true, 1, 0); // for (int i = 1; i < NsB+1; i++){ // cgl.Bi = Bi+i*stepB; // cgl.findRpoParaSeq(file, id, -0.1, 50, false); // } #endif #ifdef CASE_120 //====================================================================== // move rpo from one file to another file std::string fin = "../../data/cgl/rpoBiGiEV.h5"; std::string fout = "../../data/cgl/rpoBiGiEV2.h5"; for( int i = 0; i < 39; i++){ double Bi = 1.9 + 0.1*i; for(int j = 0; j < 55; j++){ double Gi = -5.6 + 0.1*j; string g = CQCGL1dRpo::toStr(Bi, Gi, 1); if (checkGroup(fin, g, false) && !checkGroup(fout, g, false)){ fprintf(stderr, "%d %g %g\n", 1, Bi, Gi); CQCGL1dRpo::move(fin, g, fout, g, 2); } } } #endif return 0; } <file_sep>#ifndef EIDC_H #define EIDC_H #include "EID.hpp" //////////////////////////////////////////////////////////////////////////////// // Exponential Integrator with complex data type //////////////////////////////////////////////////////////////////////////////// class EIDc : public EID<std::complex<double>> { public: EIDc(){} EIDc(ArrayXcd *L, ArrayXXcd *Y, ArrayXXcd *N) : EID<std::complex<double>>(L, Y, N){} EIDc & operator=(const EIDc &x){ return *this; } ~EIDc(){} inline ArrayXXcd MUL(const ArrayXcd &C, const ArrayXXcd &Y){ return Y.colwise() * C; } inline ArrayXcd mean(const Ref<const ArrayXXcd> &x){ return x.rowwise().mean(); } inline ArrayXXcd ZR(ArrayXcd &z){ int M1 = z.size(); ArrayXd K = ArrayXd::LinSpaced(M, 1, M); ArrayXXcd r = R * (K/M * dcp(0,2*M_PI)).exp().transpose(); // row array. return z.replicate(1, M) + r.replicate(M1, 1); } }; #endif /* EIDC_H */ <file_sep>#include "CQCGL1dRpo_arpack.hpp" #include <arsnsym.h> #include "myH5.hpp" #define cee(x) (cout << (x) << endl << endl) using namespace denseRoutines; using namespace iterMethod; using namespace Eigen; using namespace std; using namespace MyH5; ////////////////////////////////////////////////////////////////////// // constructor // ////////////////////////////////////////////////////////////////////// // A_t = Mu A + (Dr + Di*i) A_{xx} + (Br + Bi*i) |A|^2 A + (Gr + Gi*i) |A|^4 A CQCGL1dRpo_arpack::CQCGL1dRpo_arpack(int N, double d, double Mu, double Dr, double Di, double Br, double Bi, double Gr, double Gi, int dimTan): CQCGL1dRpo(N, d, Mu, Dr, Di, Br, Bi, Gr, Gi, dimTan) {} // A_t = -A + (1 + b*i) A_{xx} + (1 + c*i) |A|^2 A - (dr + di*i) |A|^4 A CQCGL1dRpo_arpack::CQCGL1dRpo_arpack(int N, double d, double b, double c, double dr, double di, int dimTan): CQCGL1dRpo(N, d, b, c, dr, di, dimTan){} // iA_z + D A_{tt} + |A|^2 A + \nu |A|^4 A = i \delta A + i \beta A_{tt} + i |A|^2 A + i \mu |A|^4 A CQCGL1dRpo_arpack::CQCGL1dRpo_arpack(int N, double d, double delta, double beta, double D, double epsilon, double mu, double nu, int dimTan) : CQCGL1dRpo(N, d, delta, beta, D, epsilon, mu, nu, dimTan) {} CQCGL1dRpo_arpack::~CQCGL1dRpo_arpack(){} CQCGL1dRpo_arpack & CQCGL1dRpo_arpack::operator=(const CQCGL1dRpo_arpack &x){ return *this; } ///////////////////////////////////////////////////////////////////////// // member functions // ///////////////////////////////////////////////////////////////////////// /// @param[in] ne number of eigenvalues wanted std::pair<VectorXcd, MatrixXd> CQCGL1dRpo_arpack::evRpo(const ArrayXd &a0, double h, int nstp, double th, double phi, int ne){ int n = Ndim; VectorXd er(ne+1), ei(ne+1); MatrixXd v((ne+1)*n, 1); double *p_er = er.data(); double *p_ei = ei.data(); double *p_v = v.data(); Jdotx jdotx(this, a0, h, nstp, th, phi); ARNonSymStdEig<double, Jdotx> dprob(n, ne, &jdotx, &Jdotx::mul, "LM"); dprob.ChangeTol(1e-9); int nconv = dprob.EigenValVectors(p_v, p_er, p_ei); if (nconv < ne) fprintf(stderr, "arpack not converged. nconv = %d\n", nconv); // truncate if necessary VectorXcd e(nconv); e.real() = er.head(nconv); e.imag() = ei.head(nconv); v.resize(n, ne+1); MatrixXcd vc = vr2vc(e, v.leftCols(nconv)); // sort the eigenvalues by their magnitude std::vector<int> id = csort(e, 2); VectorXcd e2(nconv); MatrixXcd vc2(n, nconv); for (int i = 0; i < nconv; i++ ){ e2(i) = e(id[i]); vc2.col(i) = vc.col(id[i]); } MatrixXd vr = vc2vr(vc2); return std::make_pair(e2, vr); } /** * Bis and Gis have the same size. Bis[i] and Gis[i] give the pair. */ void CQCGL1dRpo_arpack::calEVParaSeq(std::string file, std::vector<double> Bis, std::vector<double> Gis, int ne, bool saveV){ double Bi0 = Bi; double Gi0 = Gi; ArrayXd x, a0; double T, th, phi, err; int nstp; VectorXcd e; MatrixXd v; assert(Bis.size() == Gis.size()); for (int i = 0; i < Bis.size(); i++) { Bi = Bis[i]; Gi = Gis[i]; std::string g = toStr(Bi, Gi, 1); if( checkGroup(file, g, false) && !checkGroup(file, g + "/er", false) ) { fprintf(stderr, "%4d/%4zd : %4g %4g\n", i, Bis.size(), Bi, Gi); std::tie(x, T, nstp, th, phi, err) = read(file, g); a0 = x.head(Ndim); std::tie(e, v) = evRpo(a0, T/nstp, nstp, th, phi, ne); writeE(file, g, e); if (saveV) writeV(file, g, v); } } Bi = Bi0; Gi = Gi0; } /// @brief obtain the the remaing set that needs computing E and V. std::pair< std::vector<double>, std::vector<double> > CQCGL1dRpo_arpack::getMissIds(std::string file, double Bi0, double Gi0, double incB, double incG, int nB, int nG){ std::vector<double> Bis, Gis; for(int i = 0; i < nB; i++){ double Bi = Bi0 + incB*i; for(int j = 0; j < nG; j++) { double Gi = Gi0 + incG*j; std::string g = toStr(Bi, Gi, 1); if (checkGroup(file, g, false) && !checkGroup(file, g+"/er", false)){ Bis.push_back(Bi); Gis.push_back(Gi); } } } return std::make_pair(Bis, Gis); } <file_sep>#!/bin/bash # usage: # ./createAll rm -rf bin pylib b2 && mv pylib/py_ks.*so /usr/local/home/xiong/00git/research/lib/boostPython/ && rm -rf bin pylib <file_sep>from py_cqcgl1d_threads import pyCqcgl1d from personalFunctions import * def plotcgl(Aamp, ext, barTicks=[0, 3], colortype='jet', percent='5%', size=[4, 5], axisLabelSize=20, save=False, name='out.png'): """ plot the color map of the states """ fig = plt.figure(figsize=size) ax = fig.add_subplot(111) ax.set_xlabel('x', fontsize=axisLabelSize) ax.set_ylabel('t', fontsize=axisLabelSize) im = ax.imshow(Aamp, cmap=plt.get_cmap(colortype), extent=ext, aspect='auto', origin='lower') ax.grid('on') dr = make_axes_locatable(ax) cax = dr.append_axes('right', size=percent, pad=0.05) plt.colorbar(im, cax=cax, ticks=barTicks) fig.tight_layout(pad=0) if save: plt.savefig(name) else: plt.show(block=False) case = 1 if case == 1: N = 1024 d = 30 h = 0.0002 di = 0.06 Y = loadtxt('Y.dat') plotcgl(Y, [0, 30, 0, 3]) <file_sep> #ifndef CGL1D_H #define CGL1D_H #include "myfft.hpp" #include "cqcgl1d.hpp" #include "denseRoutines.hpp" class Cgl1d : public Cqcgl1d { public: Cgl1d(int N, double d, double h, bool enableJacv, int Njacv, double b, double c, int threadNum); protected: void NL(FFT &f); void jNL(FFT &f); }; #endif CGL1D_H <file_sep>#ifndef LORENZ_H #define LORENZ_H #include <Eigen/Dense> #include <utility> #include <algorithm> #include <Eigen/Dense> #include <Eigen/Sparse> #include <vector> #include "denseRoutines.hpp" /** * | sigma * (y -x) | * v(x) = | rho * x - y - x*z | * | x*y - b*z | */ class Lorenz { public: double Sigma = 10; double B = 8.0 / 3; /* caution: use float */ double Rho = 28; /* ============================================================ */ Lorenz(); ~Lorenz(); Lorenz & operator=(const Lorenz &x); /* ============================================================ */ Eigen::Vector3d vel(const Eigen::Ref<const Eigen::Vector3d> &x); Eigen::Matrix3d stab(const Eigen::Ref<const Eigen::Vector3d> &x); Eigen::MatrixXd velJ(const Eigen::Ref<const Eigen::MatrixXd> &x); Eigen::MatrixXd intg(const Eigen::Ref<const Eigen::Vector3d> &x0, const double h, const int nstp, const int nq); std::pair<Eigen::MatrixXd, Eigen::MatrixXd> intgj(const Eigen::Ref<const Eigen::Vector3d> &x0, const double h, const int hstp, const int xs, const int js); Eigen::Matrix3d equilibria(); Eigen::Matrix3d equilibriaStab(const int i); std::pair<Eigen::VectorXcd, Eigen::MatrixXcd> equilibriaEV(const int i); Eigen::MatrixXd equilibriaIntg(const int i, const int j, const double eps, const double h, const int nstp, const int nq); }; #endif /* LORENZ_H */ <file_sep>from cglHelp import * from matplotlib import rc rc('font',**{'family':'serif','serif':['Times']}) # I love Times rc('text', usetex=True) case = 45 labels = ["IF4(3)", "IF5(4)", "ERK4(3)2(2)", "ERK4(3)3(3)", "ERK4(3)4(3)", "ERK5(4)5(4)", "SS4(3)"] mks = ['o', 's', '+', '^', 'x', 'v', 'p'] Nscheme = len(labels) lss = ['--', '-.', ':', '-', '-', '-', '-'] if case == 45: """ plot fence instead of heat """ N, d = 1024, 50 fig = plt.figure(figsize=[15, 4]) # 1st ax = ax3dinit(fig, num=131, labs=[r'$x$', r'$t$', None], axisLabelSize=20, tickSize=15) ax.text2D(0.3, 0.9, '(a)', horizontalalignment='center', transform=ax.transAxes, fontsize=22) # cgl = pyCQCGL1d(N, d, -0.1, 0.08, 0.5, 0.782, 1, -0.1, -0.08, -1) skipRate = 1 pulsate = np.load('data/pulsatingSolitonAmp.npz') Aamp, Aamp2, Ts, T = pulsate['states'], pulsate['statesAdapt'], pulsate['Ts'], pulsate['T'] Aamp = Aamp[::skipRate, :] Aamp2 = Aamp2[::skipRate, :] rows, cols = Aamp.shape X = np.linspace(0, d, cols) Y = np.linspace(0, T, rows) for i in range(Aamp.shape[0]): ax.plot(X, np.ones(cols) * Y[i], Aamp[i], c='k', alpha=1) ax.set_yticks([0, 30, 60]) ax.set_zticks([0, 3]) ax.view_init(75, -50) # 2nd ax = ax3dinit(fig, num=132, labs=[r'$x$', r'$t$', None], axisLabelSize=20, tickSize=15) ax.text2D(0.3, 0.9, '(b)', horizontalalignment='center', transform=ax.transAxes, fontsize=22) # Bi, Gi = 3.5, -5.0 # cgl = pyCQCGL1d(N, d, -0.1, 0.125, 0.5, 1, Bi, -0.1, Gi, -1) skipRate = 1 pulsate = np.load('data/extremeSolitonAmp.npz') Aamp, Aamp2, Ts, T = pulsate['states'], pulsate['statesAdapt'], pulsate['Ts'], pulsate['T'] Aamp = Aamp[::skipRate, :] Aamp2 = Aamp2[::skipRate, :] rows, cols = Aamp.shape X = np.linspace(0, d, cols) Y = np.linspace(0, T, rows) for i in range(Aamp.shape[0]): ax.plot(X, np.ones(cols) * Y[i], Aamp[i], c='k', alpha=1) ax.set_ylim([0, 13]) ax.set_yticks([0, 5, 10]) ax.set_zticks([0, 1]) ax.view_init(60, -40) # 3rd ax = ax3dinit(fig, num=133, labs=[r'$x$', r'$t$', r'$|A|$'], axisLabelSize=20, tickSize=15) ax.text2D(0.3, 0.9, '(c)', horizontalalignment='center', transform=ax.transAxes, fontsize=22) # Bi, Gi = 0.8, -0.6 # cgl = pyCQCGL1d(N, d, -0.1, 0.125, 0.5, 1, Bi, -0.1, Gi, -1) skipRate = 5 pulsate = np.load('data/explodingSolitonAmp.npz') Aamp, Aamp2, Ts, T = pulsate['states'], pulsate['statesAdapt'], pulsate['Ts'], pulsate['T'] Aamp = Aamp[::skipRate, :] Aamp2 = Aamp2[::skipRate, :] rows, cols = Aamp.shape X = np.linspace(0, d, cols) Y = np.linspace(0, T, rows) for i in range(Aamp.shape[0]): ax.plot(X, np.ones(cols) * Y[i], Aamp[i], c='k', alpha=1) ax.set_ylim([0, 20]) ax.set_yticks([0, 10, 20]) ax.set_zticks([0, 3]) ax.view_init(75, -80) ############ ax3d(fig, ax) if case == 46: """ plot fence instead of heat same as case 45 but for time adaptive in constant frame """ N, d = 1024, 50 fig = plt.figure(figsize=[15, 4]) # 1st ax = ax3dinit(fig, num=131, labs=[r'$x$', r'$t$', None], axisLabelSize=20, tickSize=15) ax.text2D(0.3, 0.9, '(a)', horizontalalignment='center', transform=ax.transAxes, fontsize=22) skipRate = 3 pulsate = np.load('data/pulsatingSolitonAmp.npz') Aamp, Aamp2, Ts, T = pulsate['states'], pulsate['statesAdapt'], pulsate['Ts'], pulsate['T'] Aamp2 = Aamp2[::skipRate, :] Ts = Ts[::skipRate] rows, cols = Aamp2.shape X = np.linspace(0, d, cols) for i in range(rows): ax.plot(X, np.ones(cols) * Ts[i], Aamp2[i], c='k', alpha=1) ax.set_yticks([0, 30, 60]) ax.set_zticks([0, 3]) ax.view_init(75, -50) # 2nd ax = ax3dinit(fig, num=132, labs=[r'$x$', r'$t$', None], axisLabelSize=20, tickSize=15) ax.text2D(0.3, 0.9, '(b)', horizontalalignment='center', transform=ax.transAxes, fontsize=22) # Bi, Gi = 3.5, -5.0 # cgl = pyCQCGL1d(N, d, -0.1, 0.125, 0.5, 1, Bi, -0.1, Gi, -1) skipRate = 2 pulsate = np.load('data/extremeSolitonAmp.npz') Aamp, Aamp2, Ts, T = pulsate['states'], pulsate['statesAdapt'], pulsate['Ts'], pulsate['T'] Aamp2 = Aamp2[::skipRate, :] Ts = Ts[::skipRate] rows, cols = Aamp2.shape X = np.linspace(0, d, cols) for i in range(rows): ax.plot(X, np.ones(cols) * Ts[i], Aamp2[i], c='k', alpha=1) # ax.set_ylim([0, 13]) ax.set_yticks([0, 5, 10]) ax.set_zticks([0, 1]) ax.view_init(60, -40) # 3rd ax = ax3dinit(fig, num=133, labs=[r'$x$', r'$t$', r'$|A|$'], axisLabelSize=20, tickSize=15) ax.text2D(0.3, 0.9, '(c)', horizontalalignment='center', transform=ax.transAxes, fontsize=22) skipRate = 5 pulsate = np.load('data/explodingSolitonAmp.npz') Aamp, Aamp2, Ts, T = pulsate['states'], pulsate['statesAdapt'], pulsate['Ts'], pulsate['T'] Aamp2 = Aamp2[::skipRate, :] Ts = Ts[::skipRate] rows, cols = Aamp2.shape X = np.linspace(0, d, cols) for i in range(rows): ax.plot(X, np.ones(cols) * Ts[i], Aamp2[i], c='k', alpha=1) # ax.set_ylim([0, 20]) ax.set_yticks([0, 10, 20]) ax.set_zticks([0, 3]) ax.view_init(75, -80) ############ ax3d(fig, ax) <file_sep>CC = g++ AR = ar OPTIM = -O3 -msse2 -msse4 -march=corei7 INCLUDE = ../../include EIGEN = /usr/local/home/xiong/apps/eigen/include/eigen3 CFLAGS = -std=c++11 SOURCE = lorenz.cc SHARED = liblorenz.so STATIC = liblorenz.a # for RPO code CFLAGS2 = -std=c++11 all : int int : $(SHARED) $(STATIC) $(SHARED): $(SOURCE) $(CC) -shared -fpic $(CFLAGS) $(OPTIM) -I$(INCLUDE) -I$(EIGEN) $^ -o $@ $(SOURCE:.cc=.o) : $(SOURCE) $(CC) -c $(CFLAGS) $(OPTIM) -I$(INCLUDE) -I$(EIGEN) $^ $(STATIC): $(SOURCE:.cc=.o) $(AR) crs $@ $^ clean: rm -f *.so *.o *.a move: mv *.so *.a /usr/local/home/xiong/00git/research/lib <file_sep>/* * g++ test_FFT.cc -std=c++11 -I$EIGEN -DEIGEN_FFTW_DEFAULT -lfftw3 -O3 && ./a.out */ #include <iostream> #include <sstream> #include <Eigen/Dense> #include <unsupported/Eigen/FFT> #include <ctime> #define cee(x) (cout << (x) << endl << endl ) using namespace std; using namespace Eigen; int main(){ switch (10){ case 1 : { FFT<double> fft; fft.SetFlag(fft.HalfSpectrum); FFT<double> fft2; fft2.SetFlag(fft2.HalfSpectrum); int N = 16; VectorXd A(VectorXd::LinSpaced(N, 0, 1)); VectorXcd B(VectorXd::LinSpaced(N/2+1, 0, 1).cast<std::complex<double>>()); cee(A.data()); cee(B.data()); clock_t t = clock(); for(int i = 0; i < 1000; i++){ fft.fwd(B, A); fft.inv(A, B); } t = clock()-t; cee( (double)t / CLOCKS_PER_SEC); t = clock(); for(int i = 0; i < 1000; i++){ fft.fwd(B, A); fft2.inv(A, B); } t = clock()-t; cee( (double)t / CLOCKS_PER_SEC); cee(A); cee(B); cee(A.data()); cee(B.data()); break; } case 10: { /* does not work */ FFT<double> fft; fft.SetFlag(fft.HalfSpectrum); int N = 16; VectorXcd A(N); VectorXcd B(N); A.setRandom(); fft.fwd(B, A); cee(A); cee(B); break; } //////////////////////////////////////////////////////////////////////////////////////////////////// #ifdef N20 case 20: { /* does not work */ FFT<double> fft; fft.SetFlag(fft.HalfSpectrum); int N = 16; MatrixXd A(16, 2); MatrixXcd B(16, 2); A.col(1) = VectorXd::LinSpaced(N, 0, 1); fft.fwd(B.col(0), A.col(1)); cee(A); cee(B); break; } #endif case 2: { /* simple test 2d */ FFT<double> fft; fft.SetFlag(fft.HalfSpectrum); int N0 = 8; int N1 = 4; MatrixXcd A(MatrixXd::Random(N0,N1).cast<std::complex<double>>()); MatrixXcd B(MatrixXd::Random(N0,N1).cast<std::complex<double>>()); clock_t t = clock(); fft.inv2(B, A); t = clock()-t; cee( (double)t / CLOCKS_PER_SEC); cee(A); cee(B); //cee(A.real()); break; } case 3: { /* 2d performance */ FFT<double> fft; fft.SetFlag(fft.HalfSpectrum); int N0 = 1024; int N1 = 1024; MatrixXcd A(MatrixXd::Random(N0,N1).cast<std::complex<double>>()); MatrixXcd B(MatrixXd::Random(N0,N1).cast<std::complex<double>>()); cee(A.data()); cee(B.data()); clock_t t = clock(); for (int i = 0; i < 200; i++){ fft.fwd2(B, A); } t = clock()-t; cee( (double)t / CLOCKS_PER_SEC); cee(A.data()); cee(B.data()); //cee(A); cee(B); //cee(A.real()); break; } } return 0; } <file_sep>from personalFunctions import * from py_CQCGL1d import * case = 10 # complex Ginzburg Landau equation # A_t = A + (1 + alpha*i) A_{xx} - (1 + beta*i) |A|^2 A # The constructor siginature is # A_t = Mu A + (Dr + Di*i) A_{xx} + (Br + Bi*i) |A|^2 A + (Gr + Gi*i) |A|^4 A if case == 10: """ alpha = 1.5, beta = -1.4 L = 100 """ N, d = 256, 100 alpha, beta = 2, -2 cgl = pyCQCGL1d(N, d, 1, 1, alpha, -1, -beta, 0, 0, -1) cgl.IsQintic = False cp = CQCGLplot(cgl) h = 0.02 T = 100.0 nstp = np.int(T/h) # cgl = pyCgl1d(N, d, h, False, 0, 1.5, -1.4, 4) A0 = 3*centerRand(N, 0.2, True) a0 = cgl.Config2Fourier(A0) aa = cgl.intg(a0, T/nstp, 1000, 1000000) a0 = aa[-1] aa = cgl.intg(a0, T/nstp, nstp, 10) cp.config(aa, [0, d, 0, T], size=[3.6, 6], percent='3%', barTicks=[0, 0.5, 1], axisLabelSize=25, tickSize=15) if case == 20: """ complex Ginzburg Landau equation A_t = A + (1 + alpha*i) A_{xx} - (1 + beta*i) |A|^2 A alpha = 1.5, beta = -1.4 The constructor siginature is A_t = Mu A + (Dr + Di*i) A_{xx} + (Br + Bi*i) |A|^2 A + (Gr + Gi*i) |A|^4 A """ N, d = 256, 200 alpha, beta = 2, -2 cgl = pyCQCGL1d(N, d, 1, 1, alpha, -1, -beta, 0, 0, -1) cgl.IsQintic = False cp = CQCGLplot(cgl) h = 0.02 T = 100.0 nstp = np.int(T/h) # cgl = pyCgl1d(N, d, h, False, 0, 1.5, -1.4, 4) A0 = 3*centerRand(N, 0.2, True) a0 = cgl.Config2Fourier(A0) aa = cgl.intg(a0, T/nstp, 1000, 1000000) a0 = aa[-1] aa = cgl.intg(a0, T/nstp, nstp, 10) cp.config(aa, [0, d, 0, T], size=[6, 6], percent='3%', barTicks=[0, 0.5, 1], axisLabelSize=25, tickSize=15) <file_sep>import matplotlib.pyplot as plt import numpy as np from mpl_toolkits.axes_grid1.inset_locator import mark_inset from mpl_toolkits.axes_grid1.inset_locator import zoomed_inset_axes from mpl_toolkits.axes_grid1.inset_locator import inset_axes import matplotlib.gridspec as gridspec from mpl_toolkits.axes_grid1 import make_axes_locatable from matplotlib.ticker import ScalarFormatter from personalFunctions import * case = 1 if case == 1: """ plot Floquet exponents for N = 64 with a insert plot """ FE = KSreadFE('../../data/ks22h001t120x64E.h5', 'ppo', 1)[0] N = 32 d = 22 x = np.arange(1, N, 0.01) qk = 2 * np.pi / d * x L = qk**2 - qk**4 fig = plt.figure(figsize=(3, 2)) ax = fig.add_subplot(111) ax.plot(x, L, 'g--', lw=1.8) ax.scatter(np.arange(1, N), FE[::2], c='r', marker='o', s=22, edgecolors='none') ax.scatter(np.arange(1, N), FE[1::2], c='r', marker='s', s=30, facecolors='none', edgecolors='k') yfmt = ScalarFormatter() yfmt.set_powerlimits((0, 1)) ax.yaxis.set_major_formatter(yfmt) ax.set_yticks((-7e3, -3e3, 0, 1e3)) ax.set_xlim((0, 35)) ax.set_ylim((-7e3, 1e3)) ax.grid('on') axin = inset_axes(ax, width="45%", height="50%", loc=3) axin.scatter(np.arange(1, N), FE[::2], c='r', marker='o', s=22, edgecolors='none') axin.scatter(np.arange(1, N), FE[1::2], c='r', marker='s', s=30, facecolors='none', edgecolors='k') axin.set_xlim(0.5, 4.5) axin.set_ylim(-0.4, 0.1) axin.yaxis.set_ticks_position('right') axin.xaxis.set_ticks_position('top') axin.set_xticks((1, 2, 3, 4)) axin.set_yticks((-0.4, -0.2, 0)) axin.grid('on') mark_inset(ax, axin, loc1=1, loc2=2, fc="none") fig.tight_layout(pad=0) plt.show() # plt.savefig('pprpfigure.eps',format='eps', dpi=30) <file_sep>from py_CQCGL_threads import * from personalFunctions import * case = 4 if case == 1: """ use poincare section to find rpos """ N = 512 d = 50 h = 0.001 cgl = pyCqcgl1d(N, d, h, True, 0, -0.1, 1.0, 0.8, 0.125, 0.5, -0.1, -0.6, 4) Ndim = cgl.Ndim a0, wth0, wphi0, err = cqcglReadReq('../../data/cgl/reqN512.h5', '1') eigvalues, eigvectors = eigReq(cgl, a0, wth0, wphi0) ve = Tcopy(realve(eigvectors)) a0Tilde = cgl.reduceAllSymmetries(a0)[0] veTilde = cgl.reduceVe(ve, a0) e1, e2, e3 = orthAxes(veTilde[0], veTilde[1], veTilde[6]) nstp = 50000 a0Erg = a0 + ve[0]*1e-2 totalPoints = np.zeros((0, 2)) globalIndex = np.zeros((0,), dtype=np.int) originalPoints = np.zeros((0, Ndim)) for i in range(2): aaErg = cgl.intg(a0Erg, nstp, 1) aaErgTilde = cgl.reduceAllSymmetries(aaErg)[0] - a0Tilde aaErgTildeProj = np.dot(aaErgTilde, np.vstack((e1, e2, e3)).T) plotConfigSpace(cgl.Fourier2Config(aaErg), [0, d, nstp*h*i, nstp*h*(i+1)]) points, index = PoincareLinearInterp(aaErgTildeProj, getIndex=True) totalPoints = np.vstack((totalPoints, points)) globalIndex = np.append(globalIndex, index+i*nstp) originalPoints = np.vstack((originalPoints, aaErg[index])) a0Erg = aaErg[-1] scatter2dfig(totalPoints[:, 0], totalPoints[:, 1]) Nsteps = (globalIndex[180] - globalIndex[0])/10 Nps = Nsteps * 10 aa = cgl.intg(originalPoints[0], Nps, 1) aaTilde, th, phi = cgl.reduceAllSymmetries(aa) print norm(aaTilde[0] - aaTilde[-1]), th[0] - th[-1], phi[0] - phi[-1] savez_compressed('rpoGuess', x=aa[:-1:Nsteps], h=h, Nsteps=Nsteps, th=th[0]-th[-1], phi=phi[0]-phi[-1]) if case == 2: """ single shooting """ N = 512 d = 50 h = 0.001 rpoGuess = np.load('rpoGuess.npz') nstp = rpoGuess['Nsteps'] * 10 x0 = rpoGuess['x'][0] th0 = rpoGuess['th'].take(0) phi0 = rpoGuess['phi'].take(0) # cglrpo = pyCqcglRPO(nstp, 1, N, d, h, -0.1, 1.0, 0.8, 0.125, 0.5, -0.1, -0.6, 4) # rpo = cglrpo.findRPO(x0, nstp*h, th0, phi0, 1e-12, 20, 100, 1e-4, 1e-4, 0.1, 0.5, 30, 100) if case == 3: """ multi shooting """ N = 512 d = 50 h = 0.001 M = 10 S = 1 rpoGuess = np.load('rpoGuess.npz') nstp = rpoGuess['Nsteps'].take(0) * S x0 = rpoGuess['x'][::S, :].copy() th0 = rpoGuess['th'].take(0) phi0 = rpoGuess['phi'].take(0) cqcglSaveRPO('rpo.h5', '1', x0, nstp*h*M, nstp, th0, phi0, 1000.0) # cglrpo = pyCqcglRPO(nstp, M, N, d, h, -0.1, 1.0, 0.8, 0.125, 0.5, -0.1, -0.6, 4) # rpo = cglrpo.findRPOM(x0, nstp*h*M, th0, phi0, 1e-12, 20, 100, 1e-4, 1e-4, 0.1, 0.5, 80, 10) # cgl = pyCqcgl1d(N, d, h, False, 1, # -0.1, 1.0, 0.8, 0.125, 0.5, -0.1, -0.6, # 4) # Ndim = cgl.Ndim # xx = cgl.intg(rpoGuess['x'][0], rpoGuess['Nsteps']*10, 1) # plotConfigSpaceFromFourier(cgl, xx, [0, 50, 0, rpoGuess['Nsteps']*10*h]) # cglrpo = pyCqcglRPO(N, d, -0.1, 1.0, 0.8, 0.125, 0.5, -0.1, -0.6) # rpo = cglrpo.findPO(rpoGuess['x'], rpoGuess['h'].take(0), # rpoGuess['Nsteps'].take(0), # rpoGuess['th'].take(0), rpoGuess['phi'].take(0), # 100, 1e-12, True, True) if case == 4: """ use the new form of cqcgl with larger di to find candidate of periodic orbit initial conditon """ N = 1024 d = 30 di = 0.06 T = 3 cgl = pyCQCGL(N, d, 4.0, 0.8, 0.01, di, -1, 4) cgl.changeOmega(-176.67504941219335) cgl.rtol = 1e-10 A0 = 3*centerRand(N, 0.2, True) a0 = cgl.Config2Fourier(A0) a1 = cgl.aintg(a0, 0.001, T, 10000) aa = cgl.aintg(a1[-1], 0.001, T, 1) plotConfigSpaceFromFourier(cgl, aa, [0, d, 0, T]) S = aa.shape[0] aaHat, ths, phis = cgl.orbit2sliceWrap(aa) i1 = 99 i2 = 28307 th = ths[i1] - ths[i2] phi = phis[i1] - phis[i2] err = norm(aaHat[i1]-aaHat[i2]) print err, th, phi M = 10 sp = (i2-i1) / M ids = np.arange(i1, i2, sp) ids[-1] = i2 x = aa[ids[:M]] Ts = cgl.Ts()[ids] T = np.zeros(M) for i in range(M): T[i] = Ts[i+1]-Ts[i] xs = np.zeros((x.shape[0], x.shape[1]+3)) xs[:, :-3] = x xs[:, -3] = T xs[-1, -2] = th xs[-1, -1] = phi cqcglSaveRPO('rpo2.h5', '1', xs, sum(T), 1000, th, phi, err) aa2 = cgl.intg(x[0], nstp*M, 20) plotConfigSpaceFromFourier(cgl, aa2, [0, d, 0, nstp*M*h]) aa3 = cgl.intg(x[0]*(1+0.00001*rand(cgl.Ndim)), nstp*M, 20) plotConfigSpaceFromFourier(cgl, aa3, [0, d, 0, nstp*M*h]) dif = aa3-aa2 plot1dfig(norm(dif, axis=1)) plot1dfig(norm(dif, axis=1) / norm(aa2, axis=1), yscale='log') if case == 5: """ find good candidate to homoclinic orbits """ N = 1024 d = 30 h = 1e-5 s = 20 di = 0.05 cgl = pyCqcgl1d(N, d, h, True, 0, 4.0, 0.8, 0.01, di, 4) A0 = 5*centerRand(2*N, 0.2) a0 = cgl.Config2Fourier(A0) nstp = 150000 aa = cgl.intg(a0, nstp, s) for i in range(1): aa = cgl.intg(aa[-1], nstp, s) plotConfigSpaceFromFourier(cgl, aa, [0, d, 0, nstp*h]) aaHat, ths, phis = cgl.orbit2sliceWrap(aa) a0, wth0, wphi0, err = cqcglReadReqdi('../../data/cgl/reqDi.h5', di, 1) a0H = cgl.orbit2sliceWrap(a0)[0] dif = aaHat - a0H no = norm(dif, axis=1) plot1dfig(no) print np.min(no) """ eigvalues, eigvectors = eigReq(cgl, a0, wth0, wphi0) ve = Tcopy(realve(eigvectors)) veTilde = cgl.reduceVe(ve, a0) e1, e2, e3 = orthAxes(veTilde[0], veTilde[1], veTilde[6]) """ <file_sep>from py_CQCGL1dSub import * from cglHelp import * ################################################################################ # view the reqs in the symmetric subspace ################################################################################ case = 70 if case == 10: """ use the new data to calculate tyhe stability exponents of req """ N, d = 1024, 50 Bi, Gi = 2, -5 index = 1 cgl = pyCQCGL1dSub(N, d, -0.1, 0.125, 0.5, 1, Bi, -0.1, Gi, 0) req = CQCGLreq(cgl) a0, wth0, wphi0, err0 = req.read('../../data/cgl/reqsubBiGi.h5', req.toStr(Bi, Gi, index), sub=True) e, v = req.eigReq(a0, wth0, wphi0, sub=True) print e[:10] if case == 20: """ visualize the eigenvectors """ N, d = 1024, 50 Bi, Gi = 2, -2 index = 1 cgl = pyCQCGL1dSub(N, d, -0.1, 0.125, 0.5, 1, Bi, -0.1, Gi, 0) req, cp = CQCGLreq(cgl), CQCGLplot(cgl) a0, wth0, wphi0, err0, e, v = req.read('../../data/cgl/reqsubBiGiEV.h5', req.toStr(Bi, Gi, index), sub=True,flag=2) print e[:10] cp.oneConfig(v[0].real * cgl.N) cp.oneConfig(v[0].imag * cgl.N) if case == 30: """ check the accuracy of all req in symmetric subspace """ N, d = 1024, 50 Bi, Gi = 0.8, -0.6 index = 1 cgl = pyCQCGL1dSub(N, d, -0.1, 0.125, 0.5, 1, Bi, -0.1, Gi, 0) req, cp = CQCGLreq(cgl), CQCGLplot(cgl) fin = '../../data/cgl/reqsubBiGi.h5' gs = req.scanGroup(fin, 2) errs = [] for item in gs: a0, wth0, wphi0, err0 = req.read(fin, item, sub=True) errs.append(err0) print np.max(np.abs(errs)) if case == 40: """ save the data """ req = CQCGLreq() fin = '../../data/cgl/reqsubBiGiEV.h5' index = 1 gs = req.scanGroup(fin, 2) saveData = np.zeros([0, 3]) for item in gs: param = item.split('/') Bi, Gi, index = np.double(param[0]), np.double(param[1]), np.int(param[2]) if index == 1: a0, wth0, wphi0, err0, e, v = req.read(fin, item, sub=True, flag=2) m, ep, accu = numStab(e) saveData = np.vstack((saveData, np.array([Gi, Bi, m]))) np.savetxt("BiGiReqSubStab.dat", saveData) if case == 50: """ plot the Bi - Gi req stability plot using the saved date from running viewReq.py data format : {Gi, Bi, #unstable} #unstalbe is 0, 2, 4, 6 ... """ saveData = np.loadtxt("BiGiReqSubStab.dat") cs = {0: 'c', 1: 'm', 2: 'g', 3: 'r', 4: 'b'}#, 8: 'y', 56: 'r', 14: 'grey'} ms = {0: '^', 1: '^', 2: 'x', 3: 'o', 4: 'D'}#, 8: '8', 56: '4', 14: 'v'} fig, ax = pl2d(size=[8, 6], labs=[r'$\beta_i$', r'$\gamma_i$'], axisLabelSize=30, tickSize=20, ylim=[-6, 0], xlim=[-4, 6]) for item in saveData: Gi, Bi, m = item ax.scatter(Bi, Gi, s=18 if m > 0 else 18, edgecolors='none', marker=ms.get(m, 'v'), c=cs.get(m, 'k')) ax2d(fig, ax) if case == 70: """ same as case 10, bu plot contourf plot Note: the problem of contourf() is that whenever there is a jump in the levels, say from lv1 to lv2 but lv2 = lv1 + 2, then it will interpolate these two levels, thus a line for lv1 + 1 is plotted between these two regions. I need to draw each region indivisually. """ saveData = np.loadtxt("BiGiReqSubStab.dat") BiRange = [-3.2, 4] GiRange = [-5.6, -0.9] inc = 0.1 nx = np.int(np.rint( (BiRange[1] - BiRange[0])/inc ) + 1) ny = np.int(np.rint( (GiRange[1] - GiRange[0])/inc ) + 1) x = np.linspace(BiRange[0], BiRange[1], nx) y = np.linspace(GiRange[0], GiRange[1], ny) X, Y = np.meshgrid(x, y) Z = np.zeros([ny, nx]) - 1 # initialized with -1 for item in saveData: Gi, Bi, m = item idx = np.int(np.rint((Bi - BiRange[0]) / inc)) idy = np.int(np.rint((Gi - GiRange[0]) / inc)) if idx >= 0 and idx < nx and idy >= 0 and idy < ny: Z[idy, idx] = m if m < 6 else 6 levels = [-1, 0, 2, 4, 6] cs = ['w', 'm', 'c', 'r', 'y'] fig, ax = pl2d(size=[8, 6], labs=[r'$\beta_i$', r'$\gamma_i$'], axisLabelSize=30, tickSize=20) for i in range(len(levels)): vfunc = np.vectorize(lambda t : 0 if t == levels[i] else 1) Z2 = vfunc(Z) ax.contourf(X, Y, Z2, levels=[-0.1, 0.9], colors=cs[i]) ax.text(0, -2, r'$S$', fontsize=30) ax.text(0, -4.5, r'$U_1$', fontsize=30) ax.text(2., -4.8, r'$U_2$', fontsize=30) ax.text(3., -3, r'$U_{\geq 3}$', fontsize=30) ax.scatter(2.0,-5, c='k', s=100, edgecolor='none') ax.scatter(2.7,-5, c='k', s=100, edgecolor='none') ax.scatter(1.4,-3.9, c='k', marker='*', s=200, edgecolor='none') ax.set_xlim(BiRange) ax.set_ylim(GiRange) ax2d(fig, ax) <file_sep>/** \mainpage iterative methods to solve linear problems * * \section sec_intro Introduction * This file contains the iterative methods to solve linear problems. It * mainly contains the congugate gradient method w/wo preconditioning and * provide SSOR as one choice of precondition method, which is thought to * perform better than Jacobi and G-S. The reason that I insist writing * these routines by myself is that the corresponding libraries in Eigen * seem not to give the desired accuracy when I use them to refine POs for * KS system. I suggest you using the libraries shipped with Eigen, but if * you want to use my routines, I welcome ! * * \section sec_use usage * This file is assembly of template functions, which means that all function * implementations are in this header file, and there is no .cc file. * You only need to include this file when compiling your code. * Example: * \code * g++ yourfile.cc -I/path/to/iterMethod.hpp -I/path/to/eigen -std=c++0x * \endcode */ #ifndef ITERMETHOD_H #define ITERMETHOD_H #include <Eigen/Dense> #include <Eigen/Sparse> #include <vector> #include <tuple> #include <iostream> #include <fstream> #include "denseRoutines.hpp" ////////////////////////////////////////////////// // Interface // ////////////////////////////////////////////////// namespace iterMethod { using namespace std; using namespace Eigen; using namespace denseRoutines; typedef Eigen::SparseMatrix<double> SpMat; /* -------------------------------------------------- */ extern bool CG_PRINT; extern int CG_PRINT_FREQUENCE; extern bool GMRES_OUT_PRINT; extern int GMRES_OUT_PRINT_FREQUENCE; extern bool GMRES_IN_PRINT; extern int GMRES_IN_PRINT_FREQUENCE; extern bool HOOK_PRINT; extern int HOOK_PRINT_FREQUENCE; extern bool INB_OUT_PRINT; extern int INB_OUT_PRINT_FREQUENCE; extern bool INB_IN_PRINT; extern int INB_IN_PRINT_FREQUENCE; extern bool LM_OUT_PRINT; extern int LM_OUT_PRINT_FREQUENCE; extern bool LM_IN_PRINT; extern int LM_IN_PRINT_FREQUENCE; extern double LM_LAMBDA_INCREASE_FACTOR; extern double LM_LAMBDA_DECREASE_FACTOR; extern double LM_MAX_LAMBDA; /* -------------------------------------------------- */ template <typename Mat> std::pair<Eigen::VectorXd, std::vector<double> > ConjGrad(const Mat &A, const Eigen::VectorXd &b, const Eigen::VectorXd &x0, const int jmax, const double rtol); template <typename Mat, typename LinearSolver> std::pair<VectorXd, vector<double> > ConjGradPre(const Mat &A, const VectorXd &b, const Mat &M, LinearSolver &solver, const VectorXd &x0, const int jmax, const double rtol); template <typename Mat> Mat preSSOR(const Mat &A); template < typename Mat, typename LinearSolver> std::pair<VectorXd, vector<double> > ConjGradSSOR(const Mat &A, const VectorXd &b, LinearSolver &solver, const VectorXd &x0, const int jmax, const double rtol); /* -------------------------------------------------- */ void rotmat(const double &x, const double &y, double *c, double *s); template <class Adotx> std::tuple<VectorXd, std::vector<double>, int> Gmres0(Adotx Ax , const VectorXd &b, const VectorXd &x0, const int restart, const int maxit, const double rtol); template <typename Mat> std::tuple<VectorXd, std::vector<double>, int> Gmres(const Mat &A, const VectorXd &b, const VectorXd &x0, const int restart, const int maxit, const double rtol); ArrayXd calz(const ArrayXd &D, const ArrayXd &p, const double mu); std::tuple<double, std::vector<double>, int> findTrustRegion(const ArrayXd &D, const ArrayXd &p, double delta, const double tol = 1e-12, const int maxit = 100, const double mu0 = 0); /* -------------------------------------------------- */ template <class Adotx> std::tuple<VectorXd, VectorXd, VectorXd, ArrayXd, MatrixXd, MatrixXd, std::vector<double>, int> Gmres0SVD(Adotx Ax , const VectorXd &b, const VectorXd &x0, const int restart, const int maxit, const double rtol); template<class Fx, class Jacv> std::tuple<VectorXd, std::vector<double>, int> Gmres0Hook( Fx fx, Jacv jacv, const VectorXd &x0, const double tol, const double minRD, const int maxit, const int maxInnIt, const double GmresRtol, const int GmresRestart, const int GmresMaxit, const bool testT, const int Tindex); template<class Fx, class Jacv, class Precondition> std::tuple<VectorXd, std::vector<double>, int> Gmres0HookPre( Fx fx, Jacv jacv, Precondition Pre, const VectorXd &x0, const double tol, const double minRD, const int maxit, const int maxInnIt, const double GmresRtol, const int GmresRestart, const int GmresMaxit, const bool testT, const int Tindex); template<typename Mat> std::tuple<VectorXd, std::vector<double>, int> GmresHook( const Mat &A, const VectorXd &b, const VectorXd &x0, const double tol, const double minRD, const int maxit, const int maxInnIt, const double GmresRtol, const int GmresRestart, const int GmresMaxit, const bool testT, const int Tindex); template<typename Mat> std::tuple<VectorXd, std::vector<double>, int> GmresHookPre( const Mat &A, const VectorXd &b, const VectorXd &x0, const double tol, const double minRD, const int maxit, const int maxInnIt, const double GmresRtol, const int GmresRestart, const int GmresMaxit, const bool testT, const int Tindex); /* -------------------------------------------------- */ double chooseTheta(const double g0, const double g1, const double gp0, const double theta_min, const double theta_max); template<class Fx, class Jacv> std::tuple<VectorXd, std::vector<double>, int> InexactNewtonBacktrack(Fx &fx, Jacv &jacv, const VectorXd &x0, const double tol = 1e-12, const int btMaxIt = 20, const int maxit = 100, const double eta0 = 1e-4, const double t = 1e-4, const double theta_min = 0.1, const double theta_max = 0.5, const int GmresRestart = 30, const int GmresMaxit = 100); /* -------------------------- LM ------------------------ */ template<class Fx, template<class> class CalJJ, class LinearSolver, class Mat> std::tuple<VectorXd, std::vector<double>, int> LM0( Fx & fx, CalJJ<Mat> &JJF, LinearSolver &solver, const VectorXd &x0, const double tol, const int maxit, const int innerMaxit); std::tuple<VectorXd, std::vector<double>, int> LM( const MatrixXd &A, const VectorXd &b, const VectorXd &x0, const double tol, const int maxit, const int innerMaxit); } /////////////////////////////////////////////////// Implementation //////////////////////// namespace iterMethod { ////////////////////////////////////////////////////////////////////// // CG related // ////////////////////////////////////////////////////////////////////// /** @brief perform conjugate gradient method on symmetry matrix A * to solve Ax=b. * Here the type of A is a template. permitted types are * MatrixXd and SparseMatrix<double>. * * @param[in] A symmetric (sparse) matrix * @param[in] b vector * @param[in] x0 initial guess of solution x * @param[in] jmax maximal iteration number. This method is guranteed * to converge at most A's size iteration, so * jmax should be smaller than A.rows(). * @param[in] rtol relative tolerance for convergence */ template <typename Mat> pair<VectorXd, vector<double> > ConjGrad(const Mat &A, const VectorXd &b, const VectorXd &x0, const int jmax, const double rtol){ assert( A.rows() == A.cols() ); const int n = A.rows(); VectorXd r1(b); VectorXd r0(b); VectorXd p(VectorXd::Zero(n)); VectorXd x(x0); vector<double> res; res.reserve(jmax); double errInit = b.norm(); res.push_back(errInit); for (size_t i = 0; i < jmax; i++) { if(CG_PRINT && i % CG_PRINT_FREQUENCE == 0) fprintf(stderr, "CG : i= %zd/%d , r= %g\n", i, jmax, res.back()); double r1snorm = r1.squaredNorm(); double mu = r1snorm / r0.squaredNorm(); p = mu * p + r1; VectorXd ap = A * p; double sigma = r1snorm / (p.transpose() * ap); x = x + sigma * p; r0 = r1; r1 -= sigma * ap; double err = r1.norm(); res.push_back(err); if(err <= rtol*errInit) break; } return make_pair(x, res); } /** @brief conjugate gradient with perconditioning * * Example usage: * * for sparse matrix : * \code * typedef Eigen::SparseMatrix<double> SpMat; * // construction of A, M * // ... * SparseLU<SpMat> solver; * pair<VectorXd, vector<double> > cg = iterMethod::ConjGradPre<SpMat, SparseLU<SpMat> > * (A, b, M, solver, VectorXd::Zero(N), 100, 1e-6); * \endcode * * for dense matrix : * \code * PartialPivLU<MatrixXd> solver; * pair<VectorXd, vector<double> > * cg = iterMethod::ConjGradPre<MatrixXd, PartialPivLU<MatrixXd> > * (A, b, M, solver, VectorXd::Zero(N), 100, 1e-16); * \endcode * * @param[in] M preconditioning matrix * @param[in] solver the linear solver * @see ConjGrad() * */ template <typename Mat, typename LinearSolver> std::pair<VectorXd, vector<double> > ConjGradPre(const Mat &A, const VectorXd &b, const Mat &M, LinearSolver &solver, const VectorXd &x0, const int jmax, const double rtol){ assert( A.rows() == A.cols() ); const int n = A.rows(); VectorXd r1(b); VectorXd r0(b); VectorXd p(VectorXd::Zero(n)); VectorXd x(x0); solver.compute(M); VectorXd z0 = solver.solve(r0); vector<double> res; res.reserve(jmax); double errInit = b.norm(); res.push_back(errInit); for (size_t i = 0; i < jmax; i++) { if(CG_PRINT && i % CG_PRINT_FREQUENCE == 0) fprintf(stderr, "CG : i= %zd/%d , r= %g\n", i, jmax, res.back()); VectorXd z1 = solver.solve(r1); double r1z1 = r1.dot(z1); double mu = r1z1 / r0.dot(z0); z0 = z1; p = mu * p + z1; VectorXd ap = A * p; double sigma = r1z1 / p.dot(ap); x = x + sigma * p; r0 = r1; r1 -= sigma * ap; double err = r1.norm(); res.push_back(err); if(err <= rtol*errInit) break; } return make_pair(x, res); } /** @brief find the SSOR precondition matrix for CG method * This works for both dense and sparse matrix. */ template<typename Mat> Mat preSSOR(const Mat &A){ Mat LD = A.template triangularView<Lower>(); Mat UD = A.template triangularView<Upper>(); return LD * ( A.diagonal().asDiagonal().inverse()) * UD; } /** @brief CG method with SSOR preconditioning * * @see preSSOR * @see ConjGradPre() */ template < typename Mat, typename LinearSolver> std::pair<VectorXd, vector<double> > ConjGradSSOR(const Mat &A, const VectorXd &b, LinearSolver &solver, const VectorXd &x0, const int jmax, const double rtol){ Mat M = preSSOR<Mat> (A); return ConjGradPre<Mat, LinearSolver>(A, b, M, solver, x0, jmax, rtol); } ////////////////////////////////////////////////////////////////////// // GMRES // ////////////////////////////////////////////////////////////////////// /** * @brief GMRES method to solve A*x = b. * * This algorithm is described in * " * <NAME>, <NAME> * GMRES: A Generalized Minimal Residual Algorithm for Solving Nonsymmetric Linear Systems * SIAM Journal on Scientific and Statistical Computing, 1986 * " * The implementation follows the free netlib implementation * http://www.netlib.org/templates/matlab/gmres.m * with some modifications. Also, preconditioning is not implemented right now. * * @param[in] Ax : a function take one argument and return Krylov vector: Ax(x) = A*x * @param[in] b : right side of linear equation A*x = b * @param[in] x0 : initial guess * @param[in] restart : restart number * @param[in] maxit : maximum iteration number * @param[in] rtol : relative error tolerance * @return [x, errVec, flag] * x : the sotion of Ax=b * errVec : errors in each iteration step * flag : 0 => converged, 1 => not * * @note this routine does not require the explicit form of matrix A, but only a function * which can return A*x. * @see Gmres() */ template <class Adotx> std::tuple<VectorXd, std::vector<double>, int> Gmres0(Adotx Ax , const VectorXd &b, const VectorXd &x0, const int restart, const int maxit, const double rtol){ /* initial setup */ const int N = b.size(); int M = restart; VectorXd x = x0; double bnrm2 = b.norm(); if ( bnrm2 == 0.0 ) bnrm2 = 1.0; std::vector<double> errVec; /* error at each iteration */ /* initialize workspace */ MatrixXd V(MatrixXd::Zero(N, M+1)); // orthogonal vectors in Arnoldi iteration MatrixXd H(MatrixXd::Zero(M+1, M)); // Hessenberg matrix in Arnoldi iteration ArrayXd C(ArrayXd::Zero(M+1)); // cos of Givens rotation ArrayXd S(ArrayXd::Zero(M+1)); // sin of Givens rotation /* outer iteration */ for(size_t iter = 0; iter < maxit; iter++){ /* obtain residule */ VectorXd r = b - Ax(x); double rnorm = r.norm(); double err = rnorm / bnrm2; if(GMRES_OUT_PRINT && iter % GMRES_OUT_PRINT_FREQUENCE == 0) fprintf(stderr, "GMRES : out loop: i= %zd/%d , r= %g\n", iter, maxit, err); if(err < rtol) return std::make_tuple(x, errVec, 0); V.col(0) = r / rnorm; // obtain V_1 VectorXd g(VectorXd::Zero(M+1));// vector g = ||r|| * e1 g(0) = rnorm; /* inner iteration : Arnoldi Iteration */ for(size_t i = 0; i < M; i++){ // form the V_{i+1} and H(:, i) V.col(i+1) = Ax( V.col(i) ); for(size_t j = 0; j <= i; j++){ H(j, i) = V.col(i+1).dot( V.col(j) ); V.col(i+1) -= H(j, i) * V.col(j); } H(i+1, i) = V.col(i+1).norm(); if(H(i+1, i) != 0) V.col(i+1) /= H(i+1, i); /* Givens Rotation * | c, s| * |x| = |r| * |-s, c| |y| |0| */ for(size_t j = 0; j < i; j++) { double tmp = C(j) * H(j, i) + S(j) * H(j+1, i); H(j+1, i) = -S(j) * H(j, i) + C(j) * H(j+1, i); H(j, i) = tmp; } /* rotate the last element */ rotmat(H(i, i), H(i+1, i), &C(i), &S(i)); H(i ,i) = C(i) * H(i, i) + S(i) * H(i+1, i); H(i+1, i) = 0; /* rotate g(i) and g(i+1) * | c, s| * |g_i| = |c * g_i | * |-s, c| | 0 | |-s * g_i| */ g(i+1) = -S(i) * g(i); // be careful about the order g(i) = C(i) * g(i); /* after all above operations, we obtain dimensions * H : [i+2, i+1] * V : [N, i+2] * g : [i+2, 1] * * Here, it is better denote H as R since it is transfored * into upper triangular form. * residual = || \beta * e_1 - H * y|| = ||g - R*y|| * since the last row of R is zero, then residual = * last element of g, namely g(i+1) */ double err = fabs(g(i+1)) / bnrm2 ; errVec.push_back(err); if(GMRES_IN_PRINT && i % GMRES_IN_PRINT_FREQUENCE == 0) fprintf(stderr, "GMRES : inner loop: i= %zd/%d , r= %g\n", i, M, err); if (err < rtol){ VectorXd y = H.topLeftCorner(i+1, i+1).lu().solve(g.head(i+1)); x += V.leftCols(i+1) * y; return std::make_tuple(x, errVec, 0); } } // the inner loop finishes => has not converged // so need to update x, and go to outer loop VectorXd y = H.topLeftCorner(M, M).lu().solve(g.head(M)); x += V.leftCols(M) * y; } // if the outer loop finished => not converged return std::make_tuple(x, errVec, 1); } /** * @brief a wrapper of Gmres0. * * This function uses an explicit form of matrix A. */ template <typename Mat> std::tuple<VectorXd, std::vector<double>, int> Gmres(const Mat &A , const VectorXd &b, const VectorXd &x0, const int restart, const int maxit, const double rtol){ return Gmres0([&A](const VectorXd &x){return A * x;}, b, x0, restart, maxit, rtol); } ////////////////////////////////////////////////////////////////////// // GMRES Hook // ////////////////////////////////////////////////////////////////////// /** * @brief GMRES method to solve A*x = b w. r. t ||x|| < delta * * This GMRES method adds a hook step to the original GMRES to restrict the update to * a trust region. * * The implementation follows paper * "Simple invariant solutions embedded in 2D Kolmogorov turbulence " by * <NAME> AND <NAME> * and online reference * http://channelflow.org/dokuwiki/doku.php?id=docs:math:newton_krylov_hookstep * * @param[in] Ax : a function take one argument and return Krylov vector: Ax(x) = A*x * @param[in] b : right side of linear equation A*x = b * @param[in] x0 : initial guess * @param[in] restart : restart number * @param[in] maxit : maximum iteration number * @param[in] rtol : relative error tolerance * @param[in] delta : radius of ball constriant * @param[in] innerMaxit : maximal inner iteration number * @return [x, xold, p, D, V2, V, errVec, flag] * x the sotion of Ax=b * xold the old value just before the last update * p the residule vector without the last element * D SVD diagonal array * V2 SVD right hand side orthogonal matrix * V the orthogonal matrix in the Arnolds iteration * errVec errors in each iteration step * flag 0 => converged, 1 => not * * @note this routine does not require the explicit form of matrix A, but only a function * which can return A*x. * The return values: p, D, V2, V can be used to reconstruct the update vector. * @see Gmres0(), Gmres0Hook() */ template <class Adotx> std::tuple<VectorXd, VectorXd, VectorXd, ArrayXd, MatrixXd, MatrixXd, std::vector<double>, int> Gmres0SVD(Adotx Ax , const VectorXd &b, const VectorXd &x0, const int restart, const int maxit, const double rtol){ /* initial setup */ const int N = b.size(); int M = restart; VectorXd x = x0; double bnrm2 = b.norm(); if ( bnrm2 == 0.0 ) bnrm2 = 1.0; std::vector<double> errVec; /* error at each iteration */ /* initialize workspace */ MatrixXd V(MatrixXd::Zero(N, M+1)); // orthogonal vectors in Arnoldi iteration MatrixXd H(MatrixXd::Zero(M+1, M)); // Hessenberg matrix in Arnoldi iteration /* outer iteration */ for(size_t iter = 0; iter < maxit; iter++){ /* obtain residule */ VectorXd r = b - Ax(x); double rnorm = r.norm(); double err = rnorm / bnrm2; if(GMRES_OUT_PRINT && (iter+1) % GMRES_OUT_PRINT_FREQUENCE == 0) fprintf(stderr, "**** GMRES : out loop: i= %zd/%d, r= %g\n", iter+1, maxit, err); // if(err < rtol) return std::make_tuple(x, errVec, 0); V.col(0) = r / rnorm; // obtain V_1 /* inner iteration : Arnoldi Iteration */ for(size_t i = 0; i < M; i++){ // form the V_{i+1} and H(:, i) V.col(i+1) = Ax( V.col(i) ); for(size_t j = 0; j <= i; j++){ H(j, i) = V.col(i+1).dot( V.col(j) ); V.col(i+1) -= H(j, i) * V.col(j); } H(i+1, i) = V.col(i+1).norm(); // cout << H.col(i).head(i+2) << endl; if(H(i+1, i) != 0) V.col(i+1) /= H(i+1, i); else fprintf(stderr, "H(i+i, i) = 0, Boss, what should I do ? \n"); // conduct SVD decomposition // Here we must use the full matrix U // the residul is |p(i+1)| JacobiSVD<MatrixXd> svd(H.topLeftCorner(i+2, i+1), ComputeFullU | ComputeThinV); ArrayXd D ( svd.singularValues() ); MatrixXd U ( svd.matrixU() ); MatrixXd V2 ( svd.matrixV() ); VectorXd p = rnorm * U.row(0); double err = fabs(p(i+1)) / bnrm2; errVec.push_back(err); if(GMRES_IN_PRINT && (i+1)%GMRES_IN_PRINT_FREQUENCE == 0) fprintf(stderr, "** GMRES : inner loop: i= %zd/%d, r= %g\n", i+1, M, err); if (err < rtol){ VectorXd xold = x; ArrayXd z = p.head(i+1).array() / D; VectorXd y = V2 * z.matrix(); x += V.leftCols(i+1) * y; return std::make_tuple(x, xold, p.head(i+1), D, V2, V.leftCols(i+1), errVec, 0); } if (i == M -1){ /* last one but has not converged */ VectorXd xold = x; ArrayXd z = p.head(i+1).array() / D; VectorXd y = V2 * z.matrix(); x += V.leftCols(i+1) * y; if (iter == maxit - 1){ // if the outer loop finished => not converged return std::make_tuple(x, xold, p.head(i+1), D, V2, V.leftCols(i+1), errVec, 1); } } } } } /** * @brief use GMRES HOOK method to fin the solution of A x = b * * @param[in] testT whether test the updated period T is postive * @param[in] Tindex the index of T in the state vector counting from the tail * @param[in] minRD minimal relative descrease at each step */ template<class Fx, class Jacv> std::tuple<VectorXd, std::vector<double>, int> Gmres0Hook( Fx fx, Jacv jacv, const VectorXd &x0, const double tol, const double minRD, const int maxit, const int maxInnIt, const double GmresRtol, const int GmresRestart, const int GmresMaxit, const bool testT, const int Tindex){ const int N = x0.size(); VectorXd x(x0); std::vector<double> errVec; bool fail = false; for(size_t i = 0; i < maxit; i++){ VectorXd F = fx(x); double Fnorm = F.norm(); if(HOOK_PRINT && i % HOOK_PRINT_FREQUENCE == 0) fprintf(stderr, "\n+++++++++++ GHOOK: i = %zd/%d, r = %g ++++++++++ \n", i, maxit, Fnorm); errVec.push_back(Fnorm); if(Fnorm < tol) return std::make_tuple(x, errVec, 0); // use GmresRPO to solve F' dx = -F auto Ax = [&x, &jacv](const VectorXd &t){return jacv(x, t); }; auto tmp = Gmres0SVD(Ax, -F, VectorXd::Zero(N), GmresRestart, GmresMaxit, GmresRtol); if(std::get<7>(tmp) != 0) fprintf(stderr, "GMRES SVD not converged !\n"); VectorXd &s = std::get<0>(tmp); // update vector VectorXd &sold = std::get<1>(tmp); // old update vector just before last change VectorXd &p = std::get<2>(tmp); ArrayXd &D = std::get<3>(tmp); MatrixXd &V2 = std::get<4>(tmp); MatrixXd &V = std::get<5>(tmp); ArrayXd D2 = D * D; ArrayXd pd = p.array() * D; // ArrayXd mu = ArrayXd::Ones(p.size()) * 0.1; ArrayXd mu = ArrayXd::Ones(p.size()) * 0.1 * D2.minCoeff(); for(size_t j = 0; j < maxInnIt; j++){ VectorXd newx = x + s; double newT = newx(N - Tindex); if(HOOK_PRINT && i % HOOK_PRINT_FREQUENCE == 0) fprintf(stderr, " %zd, %g |", j, newT); if(!testT || newT > 0){ VectorXd newF = fx(newx); if(newF.norm() < (1 - minRD)*Fnorm){ x = newx; break; } } ArrayXd z = pd / (D2 + mu); VectorXd y = V2 * z.matrix(); s = sold + V * y; mu *= 2; if(j == maxInnIt-1) fail = true; } if(fail) break; // if all inner loop finish, it means state not changed // then no need to iterate more. } return std::make_tuple(x, errVec, 1); } /** * Preconditioning version of GMRES. * * GMRES will converge in fewer steps if the eigenvalues are clustered. A * matrix P^{-1} which makes AP^{-1} close to identiy is the goal of right * side preconditioning. The equation then becomes AP^{-1} (Px) = b. If the * solution is AP^{-1} y = b. then x = P^{-1} y. So only need a function * to calculate P^{-1} y. * See discussions in * ---------------------------------------------------------------------- * "How Fast are Nonsymmetric Matrix Iterations?" by * <NAME>; <NAME>.; and <NAME>. * ---------------------------------------------------------------------- * * @parame[in] Pre the precondition funcion which return product P^{-1}x * @see Gmres0SVD * */ template<class Fx, class Jacv, class Precondition> std::tuple<VectorXd, std::vector<double>, int> Gmres0HookPre( Fx fx, Jacv jacv, Precondition Pre, const VectorXd &x0, const double tol, const double minRD, const int maxit, const int maxInnIt, const double GmresRtol, const int GmresRestart, const int GmresMaxit, const bool testT, const int Tindex) { const int N = x0.size(); VectorXd x(x0); std::vector<double> errVec; bool fail = false; for(size_t i = 0; i < maxit; i++){ VectorXd F = fx(x); double Fnorm = F.norm(); if(HOOK_PRINT && (i+1) % HOOK_PRINT_FREQUENCE == 0) fprintf(stderr, "+++++++++++ GHOOK: i = %zd/%d, r = %g ++++++++++ \n", i+1, maxit, Fnorm); errVec.push_back(Fnorm); if(Fnorm < tol) return std::make_tuple(x, errVec, 0); // use GmresRPO to solve F' dx = -F VectorXd s, sold, p; ArrayXd D; MatrixXd V, V2; std::vector<double> e; int flag; auto Ax = [&x, &jacv, &Pre](const VectorXd &t){ VectorXd y = Pre(x, t); VectorXd z = jacv(x, y); return z; }; std::tie(s, sold, p, D, V2, V, e, flag) = Gmres0SVD(Ax, -F, VectorXd::Zero(N), GmresRestart, GmresMaxit, GmresRtol); if(flag != 0) fprintf(stderr, "GMRES SVD not converged !\n"); ArrayXd D2 = D * D; ArrayXd pd = p.array() * D; ArrayXd mu = ArrayXd::Ones(p.size()) * 0.1 * D2.minCoeff(); for(size_t j = 0; j < maxInnIt; j++){ VectorXd newx = x + Pre(x, s); double newT = newx(N - Tindex); if(HOOK_PRINT && (j+1) % HOOK_PRINT_FREQUENCE == 0) fprintf(stderr, " %zd, %g |", j+1, newT); if(!testT || newT > 0){ VectorXd newF = fx(newx); if(newF.norm() < (1 - minRD)*Fnorm){ x = newx; break; } } ArrayXd z = pd / (D2 + mu); VectorXd y = V2 * z.matrix(); s = sold + V * y; mu *= 2; if(j == maxInnIt-1) fail = true; } if(HOOK_PRINT) fprintf(stderr, "\n"); if(fail) break; // if all inner loop finish, it means state not changed // then no need to iterate more. } return std::make_tuple(x, errVec, 1); } template<typename Mat> std::tuple<VectorXd, std::vector<double>, int> GmresHook( const Mat &A, const VectorXd &b, const VectorXd &x0, const double tol, const double minRD, const int maxit, const int maxInnIt, const double GmresRtol, const int GmresRestart, const int GmresMaxit, const bool testT, const int Tindex){ return Gmres0Hook([&A, &b](const VectorXd &x){return A * x - b;}, [&A](const VectorXd &x, const VectorXd &t){return A * t;}, x0, tol, minRD, maxit, maxInnIt, GmresRtol, GmresRestart, GmresMaxit, testT, Tindex); } /* use inverse of diagonal matrix as preconditioner */ template<typename Mat> std::tuple<VectorXd, std::vector<double>, int> GmresHookPre( const Mat &A, const VectorXd &b, const VectorXd &x0, const double tol, const double minRD, const int maxit, const int maxInnIt, const double GmresRtol, const int GmresRestart, const int GmresMaxit, const bool testT, const int Tindex){ int n = A.cols(); ArrayXd D(n); for(int i = 0; i < n; i++) D(i) = abs(A(i, i)) > 1 ? 1 / A(i,i) : 1; //for(int i = 0; i < n; i++) D(i) = 2; // cout << D << endl << endl; auto fx = [&A, &b](const VectorXd &x){return A * x - b;}; auto jacv = [&A](const VectorXd &x, const VectorXd &t){return A * t;}; auto Pre = [&D](const VectorXd &x){VectorXd t = D*x.array(); return t; }; return Gmres0HookPre(fx, jacv, Pre, x0, tol, minRD, maxit, maxInnIt, GmresRtol, GmresRestart, GmresMaxit, testT, Tindex); } ////////////////////////////////////////////////////////////////////// // Netwon methods related // ////////////////////////////////////////////////////////////////////// /** * @brief Inexact Newton Backtracking method * * try to solve problem F(x) = 0 *--------------------------------------------------------------------- * "Inexact Newton Methods Applied to Under–Determined Systems * by. <NAME>. " * * Algorithm BINMU: * Let x0 and t in (0,1), eta_max in [0,1), and * 0 < theta_min< theta_max < 1 be given. * * For k = 0, 1, 2, ...; do * * Find some bar_eta_k in [0, eta_max] and bar_s_k that satisfy * || F(x_k) + F′(x_k) * bar_s_k || ≤ bar_eta_k * ||F(x_k)||, * * Evaluate F(x_k+ s_k). Set eta_k = bar_eta_k, s_k = bar_s_k. * While || F(x_k+ s_k) || > [1 − t(1 − eta_k)] * ||F(x_k)||, do * Choose theta in [theta_min, theta_max]. * Update s_k = theta * s_k and eta_k = 1 − theta(1 − eta_k). * Evaluate F(x_k+ s_k) * * Set x_{k+1}= x_k+ s_k. *---------------------------------------------------------------------- * * In the above, we use GMRES to find s_k : * F'(x_k) * s_k = - F(x_k) with relative tolerance bar_eta_k. * Also, for simplicity, we choose bar_eta_k to be constant. * * @param[in] fx evaluate f(x) * @param[in] jacv perform J(x)*dx. Symtex is jacv(x, dx) * @param[in] x0 initial guess * @param[in] btMaxIt maximal backtracking iteration number * theta_max ^ btMaxIt => least shrink if fails * @param[in] tol convergence tollerance * @param[in] eta0 initial value of eta * @param[in] theta_min minimal value of forcing parameter * @param[in] theta_max maximal value of forcing parameter * set 0.5 => at least shrink 1/2 * @param[in] GmresRestart gmres restart number * @param[in] GmresMaxit gmres maximal iteration number */ template<class Fx, class Jacv> std::tuple<VectorXd, std::vector<double>, int> InexactNewtonBacktrack( Fx &fx, Jacv &jacv, const VectorXd &x0, const double tol, const int btMaxIt, const int maxit, const double eta0, const double t, const double theta_min, const double theta_max, const int GmresRestart, const int GmresMaxit){ const int N = x0.size(); VectorXd x(x0); std::vector<double> errVec; // errors for (size_t i = 0; i < maxit; i++){ //////////////////////////////////////////////// // test convergence first VectorXd F = fx(x); double Fnorm = F.norm(); if(INB_OUT_PRINT && i % INB_OUT_PRINT_FREQUENCE == 0) fprintf(stderr, "\n+++++++++++ INB: i = %zd, r = %g ++++++++++ \n", i, Fnorm); errVec.push_back(Fnorm); if( Fnorm < tol) return std::make_tuple(x, errVec, 0); //////////////////////////////////////////////// //solve ||F + F's|| < eta * ||F|| double eta = eta0; std::tuple<VectorXd, std::vector<double>, int> tmp = Gmres0([&x, &jacv](const VectorXd &t){ return jacv(x, t); }, -F, VectorXd::Zero(N), GmresRestart, GmresMaxit, eta); if(std::get<2>(tmp) != 0) { fprintf(stderr, "GMRES not converged ! \n"); } VectorXd &s = std::get<0>(tmp); // update vector printf("GMRES : %lu %g | resdiual %g %g\n", std::get<1>(tmp).size(), std::get<1>(tmp).back(), (fx(x) + jacv(x, s)).norm()/Fnorm, fx(x+s).norm()); //////////////////////////////////////////////// // use back tracking method to find appropariate scale double initgp0 = 2 * F.dot(jacv(x, s)); double theta = 1; for(size_t j = 0; j < btMaxIt; j++){ VectorXd F1 = fx(x + s); double F1norm = F1.norm(); if(INB_IN_PRINT && j % INB_IN_PRINT_FREQUENCE == 0) fprintf(stderr, "INB(inner): j = %zd, r = %g \n", j, F1norm); if(F1norm < (1 - t * (1 - eta)) * Fnorm ) break; double gp0 = theta * initgp0; theta = chooseTheta(Fnorm, F1norm, gp0, theta_min, theta_max); s *= theta; eta = 1 - theta * (1 - eta); if(j == btMaxIt - 1) fprintf(stderr, "INB backtrack not converged !\n"); } x += s; // update x } // if finish the outer loop => not converged fprintf(stderr, "INB not converged !\n"); return std::make_tuple(x, errVec, 1); } ////////////////////////////////////////////////////////////////////// // Levenberg-Marquardt related // ////////////////////////////////////////////////////////////////////// /** * @brief Levenberg-Marquardt algorithm to minimize ||f(x)|| * * @param[in] Fx VectorXd (*)(VectorXd x) to evaluate f(x) * @param[in] JJF std::tuple<Mat, Mat, VectorXd> (*)(VectorXd x) function to * evaulate J^T*J, diag(diag(J^T*J)), J^T*f(x) * @param[in] solver a linear solver to solve Ax = b * @param[in] x0 initial guess * @param[in] tol tolerance * @param[in] mxit maximal number of iterations * @param[in] innerMaxit maximal number of inner iteration number */ template<class Fx, template<class> class CalJJ, class LinearSolver, class Mat> std::tuple<VectorXd, std::vector<double>, int> LM0( Fx & fx, CalJJ<Mat> &JJF, LinearSolver &solver, const VectorXd &x0, const double tol, const int maxit, const int innerMaxit){ double lam = 1; VectorXd x(x0); std::vector<double> res; for(int i = 0; i < maxit; i++){ if (lam > LM_MAX_LAMBDA) return std::make_tuple(x, res, 0); ///////////////////////////////////////////////// // judge stop or not VectorXd F = fx(x); double err = F.norm(); res.push_back(err); if(err < tol){ fprintf(stderr, "stops at error = %g\n", err); return std::make_tuple(x, res, 0); } if (LM_OUT_PRINT && i % LM_OUT_PRINT_FREQUENCE == 0) fprintf(stderr, "+++ LM : out loop: i = %d/%d, err=%g +++ \n", i, maxit, err); //////////////////////////////////////////////// // construct JJ and JF std::tuple<Mat, Mat, VectorXd> tmp = JJF(x); Mat &jj = std::get<0>(tmp); Mat &d = std::get<1>(tmp); VectorXd &jf = std::get<2>(tmp); for(int j = 0; j < innerMaxit; j++){ Mat H = jj + lam * d; int N = H.rows(); // solve H x = -jf auto cg = ConjGradSSOR(H, -jf, solver, VectorXd::Zero(N), N, 1e-6); VectorXd &dx = cg.first; std::vector<double> &r = cg.second; if (LM_IN_PRINT) printf("CG error %g, iteration number %zd\n", r.back(), r.size()); // update the state or keep unchanged VectorXd xnew = x + dx; VectorXd Fnew = fx(xnew); double errnew = Fnew.norm(); if (LM_IN_PRINT && i % LM_IN_PRINT_FREQUENCE == 0) fprintf(stderr, "LM : inner loop: j = %d/%d, err=%g\n", j, innerMaxit, errnew); if (errnew < err){ x = xnew; lam /= LM_LAMBDA_DECREASE_FACTOR; break; } else { lam *= LM_LAMBDA_INCREASE_FACTOR; if (lam > LM_MAX_LAMBDA) { fprintf(stderr, "lambda = %g too large \n", lam); break; } } } } // run out of loop, which means it does not converge return std::make_tuple(x, res, 1); } /** * @brief JJF template function for LM() to solve Ax=b */ template<class Mat> struct JJF { const Mat &J; const VectorXd &b; JJF(const Mat &tJ, const VectorXd &tb) : J(tJ), b(tb) {} std::tuple<MatrixXd, MatrixXd, VectorXd> operator()(const VectorXd &x) { MatrixXd JJ = J.transpose() * J; MatrixXd d = JJ.diagonal().asDiagonal(); return std::make_tuple(JJ, d, J.transpose()*(J*x-b)); } }; } #endif /* ITERMETHOD_H */ <file_sep>from personalFunctions import * def setAxis(ax, xr, xlabel=r'$t$', ylabel=r'$\lambda_k(t)$'): # ax.get_yaxis().set_tick_params(which='both', direction='in', pad = -20) # ax.get_xaxis().set_tick_params(which='both', direction='in', pad = -20) # ax.set_xlabel(xlabel, fontsize=20) # ax.set_ylabel(ylabel, fontsize=20) ax.set_xlim([0, xr]) ax.set_xticks([0, xr-1]) ax.set_xticklabels([0, r'$T_p$'], fontsize=13) if __name__ == '__main__': case = 1 if case == 1: """ plot the local Flouqet exponents of ppo1 """ # load data expand = np.loadtxt('./ppo/FVexpand1.dat') fig = plt.figure(figsize=[3, 2]) ax = fig.add_subplot(111) ax.plot(expand[0], lw=1.5, ls='-') # ax.plot(expand[1], lw=1.5, ls='-') ax.plot(expand[2], lw=1.5, ls='-') ax.plot(expand[3], lw=1.5, ls='-') ax.plot(expand[4], lw=1.5, ls='-') ax.plot(expand[5], lw=1.5, ls='-') ax.plot(expand[7], lw=1.5, ls='-') ax.plot(expand[8], lw=1.5, ls='-') ax.plot(expand[9], lw=1.5, ls='-') ax.text(expand.shape[1]/50, 0.4, r'$\lambda_k(t)$', fontsize=18) ax.text(expand.shape[1]/3, -0.8, r'$k=1, 3, 4, 5, 6, 8$', fontsize=18) ax.text(expand.shape[1]/2, -1.8, r'$k=9, 10$', fontsize=18) setAxis(ax, expand.shape[1]) ax.set_ylim([-2.5, 1]) ax.set_yticks([-2, -1, 0, 1]) fig.tight_layout(pad=0) plt.show() if case == 2: """ plot $\lambda_i(t) -\lambda$ for a small subset """ expand = np.loadtxt('./ppo/FVexpand1.dat') fe = KSreadFE('../ks22h001t120x64EV.h5', 'ppo', 1)[0] fig = plt.figure(figsize=[3, 2]) ax = fig.add_subplot(111) ix = [8, 9, 10, 11] for i in ix: ax.plot(expand[i]-fe[i], lw=1.5, ls='-', label='k='+str(i+1)) setAxis(ax, expand.shape[1], ylabel=r'$\lambda_k(t) - \lambda_k$') ax.set_yticks([-0.03, 0, 0.03, 0.06]) ax.legend(loc='best', fontsize=13, frameon=False) fig.tight_layout(pad=0) plt.show() # savez_compressed('ppo1', T=T, nstp=nstp, fe=fe) if case == 3: """ plot $\lambda_i(t) -\lambda$ for the remaining set """ expand = np.loadtxt('./ppo/FVexpand1.dat') fe = KSreadFE('../ks22h001t120x64EV.h5', 'ppo', 1)[0] fig = plt.figure(figsize=[3, 2]) ax = fig.add_subplot(111) ix = [12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26] for i in ix: ax.plot(expand[i]-fe[i], lw=1.5, ls='-') ax.arrow(expand.shape[1]/20, 0.009, 0, -0.003, width=20, head_length=0.001, head_width=80, fc='k') setAxis(ax, expand.shape[1], ylabel=r'$\lambda_k(t) - \lambda_k$') ax.set_yticks([-0.008, -0.002, 0.004, 0.01]) fig.tight_layout(pad=0) plt.show() <file_sep>#ifndef CQCGL1dREQ_H #define CQCGL1dREQ_H #include <type_traits> #include "CQCGL1d.hpp" #include "myH5.hpp" using namespace H5; class CQCGL1dReq : public CQCGL1d { public : //////////////////////////////////////////////////////////// // A_t = Mu A + (Dr + Di*i) A_{xx} + (Br + Bi*i) |A|^2 A + (Gr + Gi*i) |A|^4 A CQCGL1dReq(int N, double d, double Mu, double Dr, double Di, double Br, double Bi, double Gr, double Gi, int dimTan); // A_t = -A + (1 + b*i) A_{xx} + (1 + c*i) |A|^2 A - (dr + di*i) |A|^4 A CQCGL1dReq(int N, double d, double b, double c, double dr, double di, int dimTan); // iA_z + D A_{tt} + |A|^2 A + \nu |A|^4 A = i \delta A + i \beta A_{tt} + i |A|^2 A + i \mu |A|^4 A CQCGL1dReq(int N, double d, double delta, double beta, double D, double epsilon, double mu, double nu, int dimTan); ~CQCGL1dReq(); CQCGL1dReq & operator=(const CQCGL1dReq &x); //////////////////////////////////////////////////////////// static std::string toStr(double Bi, double Gi, int index); static std::tuple<VectorXd, double, double ,double> read(H5File &file, const std::string groupName); static void write(H5File &file, const std::string groupName, const ArrayXd &a, const double wth, const double wphi, const double err); static VectorXcd readE(H5File &file, const std::string groupName); static MatrixXcd readV(H5File &file, const std::string groupName); static void writeE(H5File &file, const std::string groupName, const VectorXcd e); static void writeV(H5File &file, const std::string groupName, const MatrixXcd v); static void move(H5File &fin, std::string gin, H5File &fout, std::string gout, int flag = 0); //////////////////////////////////////////////////////////// VectorXd Fx(const VectorXd &x); std::tuple<MatrixXd, MatrixXd, VectorXd> calJJF(const VectorXd &x); std::tuple<VectorXd, double, double, double, int> findReq_LM(const ArrayXd &a0, const double wth0, const double wphi0, const double tol, const int maxit, const int innerMaxit); std::vector<double> optThPhi(const ArrayXd &a0); void findReqParaSeq(H5File &file, int id, double step, int Ns, bool isBi); void calEVParaSeq(H5File &file, std::vector<int> ids, std::vector<double> Bis, std::vector<double> Gis, bool saveV); }; template<class Mat> struct CQCGL1dReqJJF { CQCGL1dReq *req; CQCGL1dReqJJF(CQCGL1dReq *req) : req(req){} std::tuple<MatrixXd, MatrixXd, VectorXd> operator()(const VectorXd &x) { return req->calJJF(x); } }; #endif /* CQCGL1dREQ_H */ <file_sep>/* to compile the class * * compile with Mutithreads FFT support: * g++ cqcgl2d.cc -shared -fpic -march=corei7 -O3 -msse2 -msse4 -lfftw3_threads -lfftw3 -lm -fopenmp -DTFFT -I $XDAPPS/eigen/include/eigen3 -I../include -std=c++0x * * complile with only one thread: * g++ cqcgl2d.cc -shared -fpic -lfftw3 -lm -fopenmp -march=corei7 -O3 -msse2 -msse4 -I/usr/include/eigen3 -I../../include -std=c++0x * * */ #ifndef CQCGL2D_H #define CQCGL2D_H // #include <fftw3.h> #include <complex> #include <utility> #include <algorithm> #include <Eigen/Dense> #include <Eigen/Sparse> #include <vector> #include "denseRoutines.hpp" #include "myH5.hpp" #include "myfft.hpp" using std::pair; using std::make_pair; using Eigen::MatrixXd; using Eigen::VectorXd; using Eigen::MatrixXcd; using Eigen::VectorXcd; using Eigen::ArrayXXcd; using Eigen::ArrayXcd; using Eigen::ArrayXXd; using Eigen::ArrayXd; using Eigen::ConjugateGradient; using Eigen::PartialPivLU; using Eigen::Map; using Eigen::Ref; ////////////////////////////////////////////////////////////////////// // class CQCGLgeneral // ////////////////////////////////////////////////////////////////////// /** * @brief two dimensional cubic quintic complex Ginzburg-Landau equation * * The dimension of the mesh is [M x N] corresponding to actual simulation * domain [dy x dx]. Therefore, the x direction is discretized to N points, * and y direction is divided to M points. Memory is contiguous in the * y direction. */ class CQCGL2d { public: typedef std::complex<double> dcp; typedef Eigen::SparseMatrix<double> SpMat; typedef Eigen::Triplet<double> Tri; const int N, M; /* dimension of FFT */ const double dx, dy; /* system domain size */ int Ne, Me; /* effective number of modes */ int Nplus, Nminus, Nalias; int Mplus, Mminus, Malias; double Br, Bi, Gr, Gi, Dr, Di, Mu; double Omega = 0; /* used for comoving frame */ ArrayXd Kx, Kx2, Ky, Ky2, QKx, QKy; ArrayXXcd L, E, E2, a21, a31, a32, a41, a43, b1, b2, b4; MyFFT::FFT2d F[5], JF[5]; /* for time step adaptive ETDRK4 and Krogstad */ //////////////////////////////////////////////////////////// // time adaptive method related parameters double rtol = 1e-10; double nu = 0.9; /* safe factor */ double mumax = 2.5; /* maximal time step increase factor */ double mumin = 0.4; /* minimal time step decrease factor */ double mue = 1.25; /* upper lazy threshold */ double muc = 0.85; /* lower lazy threshold */ int NCalCoe = 0; /* times to evaluate coefficient */ int NReject = 0; /* times that new state is rejected */ int NCallF = 0; /* times to call velocity function f */ int NSteps = 0; /* total number of integrations steps */ VectorXd hs; /* time step sequnce */ VectorXd lte; /* local relative error estimation */ VectorXd Ts; /* time sequnence for adaptive method */ int cellSize = 500; /* size of cell when resize output container */ int MC = 64; /* number of sample points */ int R = 1; /* radius for evaluating phi(z) */ int Method = 1; int constETDPrint = 0; //////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////// // constructor, destructor, copy assignment. // //////////////////////////////////////////////////////////// CQCGL2d(int N, int M, double dx, double dy, double Mu, double Dr, double Di, double Br, double Bi, double Gr, double Gi, int threadNum); CQCGL2d(int N, double dx, double Mu, double Dr, double Di, double Br, double Bi, double Gr, double Gi, int threadNum); CQCGL2d(int N, int M, double dx, double dy, double b, double c, double dr, double di, int threadNum); CQCGL2d(int N, double dx, double b, double c, double dr, double di, int threadNum); ~CQCGL2d(); CQCGL2d & operator=(const CQCGL2d &x); //////////////////////////////////////////////////////////// // member functions. // //////////////////////////////////////////////////////////// //============================================================ inline int calNe(const double N); void CGLInit(); void changeOmega(double w); void calCoe(const double h); void oneStep(double &du, const bool onlyOrbit); ArrayXXcd ZR(const Ref<const ArrayXcd> &z); double adaptTs(bool &doChange, bool &doAccept, const double s); void saveState(H5::H5File &file, int id, const ArrayXXcd &a, const ArrayXXcd &v, const int flag); ArrayXXcd constETD(const ArrayXXcd &a0, const ArrayXXcd &v0, const double h, const int Nt, const int skip_rate, const bool onlyOrbit, const bool doSaveDisk, const std::string fileName); ArrayXXcd adaptETD(const ArrayXXcd &a0, const ArrayXXcd &v0, const double h0, const double tend, const int skip_rate, const bool onlyOrbit, const bool doSaveDisk, const std::string fileName); ArrayXXcd intg(const ArrayXXcd &a0, const double h, const int Nt, const int skip_rate, const bool doSaveDisk, const std::string fileName); ArrayXXcd aintg(const ArrayXXcd &a0, const double h, const double tend, const int skip_rate, const bool doSaveDisk, const std::string fileName); ArrayXXcd intgv(const ArrayXXcd &a0, const ArrayXXcd &v0, const double h, const int Nt, const int skip_rate, const bool doSaveDisk, const std::string fileName); ArrayXXcd aintgv(const ArrayXXcd &a0, const ArrayXXcd &v0, const double h, const double tend, const int skip_rate, const bool doSaveDisk, const std::string fileName); void dealias(const int k, const bool onlyOrbit); void NL(const int k, const bool onlyOrbit); ArrayXXcd unpad(const ArrayXXcd &v); ArrayXXcd pad(const ArrayXXcd &v); ArrayXd c2r(const ArrayXXcd &v); ArrayXXcd r2c(const ArrayXd &v); //============================================================ ArrayXXcd Fourier2Config(const Ref<const ArrayXXcd> &aa); ArrayXXcd Config2Fourier(const Ref<const ArrayXXcd> &AA); ArrayXXcd velocity(const ArrayXXcd &a0); ArrayXXcd velocityReq(const ArrayXXcd &a0, const double wthx, const double wthy, const double wphi); ArrayXXcd stab(const ArrayXXcd &a0, const ArrayXXcd &v0); ArrayXXcd stabReq(const ArrayXXcd &a0, const ArrayXXcd &v0, const double wthx, const double wthy, const double wphi); ArrayXXcd rotate(const Ref<const ArrayXXcd> &a0, const int mode, const double th1 = 0, const double th2 = 0, const double th3 = 0); ArrayXXcd tangent(const Ref<const ArrayXXcd> &a0, const int mode); std::tuple<ArrayXXcd, double, double, double, double> readReq(const std::string fileName, const std::string groupName); std::tuple<ArrayXXd, ArrayXd, ArrayXd> orbit2sliceWrap(const Ref<const ArrayXXd> &aa); std::tuple<ArrayXXd, ArrayXd, ArrayXd> orbit2slice(const Ref<const ArrayXXd> &aa); ArrayXXd orbit2sliceSimple(const Ref<const ArrayXXd> &aa); MatrixXd ve2slice(const ArrayXXd &ve, const Ref<const ArrayXd> &x); }; #endif /* CQCGL2D_H */ <file_sep>from ctypes import * from numpy import * class AT(Structure): _fields_ = [("aa", POINTER(c_double)), ("tt", POINTER(c_double))] def ksint(a0, h, nstp, np = 1, d = 22): """ % integrate KS system. % input: % a0 : initial condition (must be 30x1) % h : time step % nstp: number of integration steps % d : size of system. Default = 22 % np : saving spacing. Default = 1 % output: % aa : the orbit. size [30, nstp/np+1] % exmple usage: % aa = ksint(a0, 0.25, 1000); """ ks, N, ch, cnstp, cnp, cd, pa0, aa, paa = init(a0, h, nstp, np, d) ks.ksf(paa, pa0, cd, ch, cnstp, cnp) aa = aa.reshape((nstp/np+1, N-2)) # aa = aa.reshape((N-2, nstp/np+1), order='F') return aa def ksintM1(a0, h, nstp, np = 1, d = 22): """ % integrate KS system on the 1st mode slice. % input: % a0 : initial condition (must be 30x1, a0(2) = 0) % h : time step % nstp: number of integration steps % d : size of system. Default = 22 % np : saving spacing. Default = 1 % output: % tt : time sequence in the full state space [nstp/np+1] % aa : trajectory in the 1st mode slice [30, nstp/np+1] % exmple usage: % tt, aa = ksintM1(a0, 0.25, 1000); """ ks, N, ch, cnstp, cnp,cd, pa0, aa, paa = init(a0, h, nstp, np, d) tt = empty(nstp/np+1) ptt = tt.ctypes.data_as(POINTER(c_double)) ks.ksfM1(paa, ptt, pa0, cd, ch, cnstp, cnp) aa = aa.reshape((nstp/np+1, N-2)) return tt, aa def ksint2M1(a0, h, T, np = 1, d = 22): """ % integrate KS system on the 1st mode slice. % input: % a0 : initial condition (must be 30x1, a0(2) = 0) % h : time step % nstp: number of integration steps % d : size of system. Default = 22 % np : saving spacing. Default = 1 % output: % tt : time in the full state space % aa : trajectory on the 1st mode slice % exmple usage: % [tt,aa] = ksint2M1(a0, 0.25, 1000); """ ks = cdll.LoadLibrary('./libks2py.so') ks.ksf2M1.argtypes = [POINTER(AT), POINTER(c_double), c_double, c_double, c_double, c_int] ks.ksf2M1.restype = c_int ks.freeks.argtypes = [POINTER(AT)] N = len(a0) + 2 ch = c_double(h) cT = c_double(T) cnp = c_int(np) cd = c_double(d) pa0 = a0.ctypes.data_as(POINTER(c_double)) at = AT() M = ks.ksf2M1(byref(at), pa0, cd, ch, cT, cnp) aa = fromiter(at.aa, dtype=double, count=M*(N-2)) aa = aa.reshape((M, N-2)) tt = fromiter(at.tt, dtype=double, count=M) ks.freeks(at) # free the allocated memory. Just once return tt, aa def init(a0, h, nstp, np, d): ks = cdll.LoadLibrary('./libks2py.so') N = len(a0) + 2 ch = c_double(h) cnstp = c_int(nstp) cnp = c_int(np) cd = c_double(d) pa0 = a0.ctypes.data_as(POINTER(c_double)) aa = empty((nstp/np+1)*(N-2)) paa = aa.ctypes.data_as(POINTER(c_double)) return ks, N, ch, cnstp, cnp, cd, pa0, aa, paa <file_sep>// to compile // // add -I$XDAPPS/arpackpp/include -llapack -larpack -lsuperlu -lopenblas // // first use // mpicxx --showme -O3 test_CQCGL1dRpo_mpi.cc -L../../lib -I../../include -I$EIGEN -std=c++11 -lCQCGL1dRpo -lCQCGL1d -lsparseRoutines -ldenseRoutines -literMethod -lmyH5 -lmyfft -lfftw3 -lm // // then change g++ to h5c++ // // h5c++ -O3 test_CQCGL1dRpo_arpack_mpi.cc -std=c++11 -L../../lib -I$RESH/include -I$EIGEN -I$XDAPPS/arpackpp/include -lCQCGL1dRpo_arpack -lCQCGL1dRpo -lCQCGL1d -lsparseRoutines -ldenseRoutines -literMethod -lmyH5 -lmyfft -lfftw3 -lm -I/usr/lib/openmpi/include -I/usr/lib/openmpi/include/openmpi -pthread -L/usr//lib -L/usr/lib/openmpi/lib -lmpi_cxx -lmpi -ldl -lhwloc -llapack -larpack -lsuperlu -lopenblas #include <iostream> #include <arsnsym.h> #include <Eigen/Dense> #include "CQCGL1dRpo_arpack.hpp" #include "myH5.hpp" #include <mpi.h> using namespace std; using namespace Eigen; using namespace denseRoutines; using namespace MyH5; #define cee(x) (cout << (x) << endl << endl) #define CASE_10 int main(int argc, char **argv){ #ifdef CASE_10 //====================================================================== // calculate E and V const int N = 1024; const double L = 50; double Bi = 1.9; double Gi = -5.6; CQCGL1dRpo_arpack cgl(N, L, -0.1, 0.125, 0.5, 1, Bi, -0.1, Gi, 1); string file = "../../data/cgl/rpoBiGiEV.h5"; std::vector<double> Bis, Gis; std::tie(Bis, Gis) = CQCGL1dRpo_arpack::getMissIds(file, Bi, Gi, 0.1, 0.1, 39, 55); int Ns = Bis.size(); cout << Ns << endl; //////////////////////////////////////////////////////////// // mpi part MPI_Init(&argc, &argv); int rank, num; MPI_Comm_rank(MPI_COMM_WORLD, &rank); MPI_Comm_size(MPI_COMM_WORLD, &num); int inc = Ns / num; int rem = Ns - inc * num; int p_size = inc + (rank < rem ? 1 : 0); int p_start = inc*rank + (rank < rem ? rank : rem); int p_end = p_start + p_size; std::vector<double> p_Bis, p_Gis; for(int i = p_start; i < p_end; i++){ p_Bis.push_back(Bis[i]); p_Gis.push_back(Gis[i]); } fprintf(stderr, "MPI : %d / %d; range : %d - %d \n", rank, num, p_start, p_end); //////////////////////////////////////////////////////////// cgl.calEVParaSeq(file, p_Bis, p_Gis, 30, true); //////////////////////////////////////////////////////////// MPI_Finalize(); //////////////////////////////////////////////////////////// #endif #ifdef CASE_20 //====================================================================== // Calculate E and V along one Gi line for a specific Bi const int N = 1024; const int L = 50; double Bi = 2.3; double Gi = -5.6; CQCGL1dRpo_arpack cgl(N, L, -0.1, 0.125, 0.5, 1, Bi, -0.1, Gi, 1); string file = "../../data/cgl/rpoBiGiEV.h5"; std::vector<double> Bis, Gis; Bis.push_back(Bi); int NsG = 16; //////////////////////////////////////////////////////////// // mpi part MPI_Init(&argc, &argv); int rank, num; MPI_Comm_rank(MPI_COMM_WORLD, &rank); MPI_Comm_size(MPI_COMM_WORLD, &num); int inc = NsG / num; int rem = NsG - inc * num; int p_size = inc + (rank < rem ? 1 : 0); int p_start = inc*rank + (rank < rem ? rank : rem); int p_end = p_start + p_size; for (int i = p_start; i < p_end; i++) Gis.push_back(Gi+0.1*i); fprintf(stderr, "MPI : %d / %d; range : %d - %d \n", rank, num, p_start, p_end); //////////////////////////////////////////////////////////// cgl.calEVParaSeq(file, Bis, Gis, 10, true); //////////////////////////////////////////////////////////// MPI_Finalize(); //////////////////////////////////////////////////////////// #endif return 0; } <file_sep>/* * g++ rossler.cc -O3 -std=c++11 -I $XDAPPS/sources/boost_1_57_0 -I $XDAPPS/eigen/include/eigen3 -I $RESH/include -L $RESH/lib -literMethod */ #include <iostream> #include <vector> #include <boost/numeric/odeint.hpp> #include <Eigen/Dense> #include <functional> #include "iterMethod.hpp" using namespace std; using namespace Eigen; using namespace boost::numeric::odeint; using namespace iterMethod; namespace ph = std::placeholders; class Rossler { protected: ////////////////////////////////////////////////////////////////////// // Inner classes // ////////////////////////////////////////////////////////////////////// /** * @brief velocity of Rossler system * * dx/dt = - y - z * dy/dt = x + a * y * dz/dt = b + z * (x - c) */ struct Velocity{ const double a, b, c; Velocity (double a = 0.2, double b=0.2, double c = 5.7) : a(a), b(b), c(c) {} void operator()(const std::vector<double> &x, std::vector<double> &dxdt, const double /* t */){ dxdt[0] = -x[1] - x[2]; dxdt[1] = x[0] + a * x[1]; dxdt[2] = b + x[2] * (x[0] - c); } }; /** * @brief calculate J * dx for Rossler * * | 0, -1, -1 | * stability = | 1, a, 0 | * | z, 0, x-c | * */ struct Jacv{ const double a, b, c; Jacv (double a = 0.2, double b = 0.2, double c = 5.7) : a(a), b(b), c(c) {} void operator()(const std::vector<double> &x, std::vector<double> &dxdt, const double /* t */){ dxdt[0] = -x[1] - x[2]; dxdt[1] = x[0] + a * x[1]; dxdt[2] = b + x[2] * (x[0] - c); dxdt[3] = -x[4] - x[5]; dxdt[4] = x[3] + a*x[4]; dxdt[5] = x[2]*x[3] + (x[0]-c)*x[5]; } }; public: const double a, b, c; Velocity velocity; Jacv jacv; double odeAtol, odeRtol; Rossler(double odeAtol = 1e-16, double odeRtol = 1e-12, double a = 0.2, double b=0.2, double c=5.7) : a(a), b(b), c(c), velocity(a, b, c), jacv(a, b, c), odeAtol(odeAtol), odeRtol(odeRtol) {} Vector3d getVelocity(Array3d x0){ std::vector<double> x(&x0[0], &x0[0] + x0.size()); std::vector<double> v(3); velocity(x, v, 0); Vector3d vel = Map<Vector3d>(&v[0]); return vel; } /** * @brief integrator : each column is a state vector */ template< typename Vel> std::pair<ArrayXXd, ArrayXd> intg0(const ArrayXd &x0, const double h, const int nstp, Vel vel, int blockSize = 100){ ArrayXXd xx(x0.size(), blockSize); ArrayXd tt(blockSize); int totalNum = 0; std::vector<double> x(&x0[0], &x0[0] + x0.size()); //integrate_adaptive(make_controlled< runge_kutta_cash_karp54<std::vector<double>> >( odeAtol , odeRtol ) , integrate_const( runge_kutta4< std::vector<double> >() , // integrate( vel, x, 0.0, nstp*h, h, [&xx, &tt, &totalNum, &blockSize](const std::vector<double> &x, double t){ if(totalNum >= tt.size()){ xx.conservativeResize(NoChange, xx.cols() + blockSize); tt.conservativeResize(tt.size() + blockSize); } xx.col(totalNum) = ArrayXd::Map(&x[0], x.size()); tt(totalNum++) = t; }); return make_pair(xx.leftCols(totalNum), tt.head(totalNum)); } std::pair<ArrayXXd, ArrayXd> intg(const ArrayXd &x0, const double h, const int nstp, int blockSize = 100){ return intg0(x0, h, nstp, velocity, blockSize); } std::tuple<ArrayXXd, ArrayXXd, ArrayXd> intgv(const ArrayXd &x0, const ArrayXd &dx0, const double h, const int nstp, int blockSize = 100){ ArrayXd xdx(x0.size() + dx0.size()); xdx << x0, dx0; auto tmp = intg0(xdx, h, nstp, jacv, blockSize); return std::make_tuple(tmp.first.topRows(3), tmp.first.bottomRows(3), tmp.second); } /** * @brief form f(x,t) - x * @param[in] x 4-element vector: (x, t) * @return 4-element vector * | f(x, t) - x| * | 0 | */ Vector4d Fx(Vector4d x){ int nstp = (int)(x(3) / 0.01); Array3d fx = intg(x.head(3), x(3)/nstp, nstp).first.rightCols(1); Vector4d F; F << fx, x(3); return F - x; } /** * @brief get the product J * dx * * Here J = | J(x, t) - I, v(f(x,t)) | * | v(x), 0 | */ Vector4d DFx(Vector4d x, Vector4d dx){ int nstp = (int)(x(3) / 0.01); auto tmp = intgv(x.head(3), dx.head(3), x(3)/nstp, nstp); VectorXd v1 = getVelocity(x.head(3)); VectorXd v2 = getVelocity(std::get<0>(tmp).rightCols(1)); Vector4d DF; DF << std::get<1>(tmp).rightCols(1).matrix() - dx.head(3) + v2 * dx(3), v1.dot(dx.head(3)); return DF; } #if 0 VectorXd DFx(Vector4d x, Vector4d dx){ int nstp = (int)(x(3) / 0.01); auto tmp = intg(x.head(3), x(3)/nstp, nstp); double norm = dx.head(3).norm(); auto tmp2 = intg(x.head(3) + 1e-7*dx.head(3)/norm, x(3)/nstp, nstp); Vector3d Jx = (tmp2.first.rightCols(1) - tmp.first.rightCols(1)) / 1e-7 * norm; VectorXd v1 = getVelocity(x.head(3)); VectorXd v2 = getVelocity(tmp.first.rightCols(1)); Vector4d DF; DF << Jx - dx.head(3) + v2 * dx(3), v1.dot(dx.head(3)); return DF; } #endif }; int main(){ switch (1){ case 1 :{ Rossler ros; Array3d x0; // x0 << 1, 6.0918, 1.2997; // x0 << -3.36773 , 5.08498 , 0.0491195; // T = 18 // x0 << -3.36788 , 5.08677 , 0.0240049; // double T = 17.5959; x0 << 0.511787, 5.99344, 1.85836; double T = 5.88109; int nstp = int(T/0.01); Array3d dx0; dx0 << 0.2, 0.2, 0.2; auto tmp = ros.intgv(x0, dx0, T/nstp, nstp); cout << std::get<0>(tmp) << endl; break; } case 2 : { Rossler ros; Array3d x0; //x0 << 1, 6.0918, 1.2997; x0 << -3.36773 , 5.08498 , 0.0491195; Array3d dx0; dx0 << 0.1, 0.1, 0.1; auto tmp = ros.intg(x0, 0.01, 1800); cout << std::get<1>(tmp) << endl; break; } case 3 : { Rossler ros; Vector4d x0; //x0 << 1, 6.0918, 1.2997, 5.88; x0 << -3.36773 , 5.08498 , 0.0491195, 18; auto tmp = ros.Fx(x0); //cout << tmp << endl; /* Vector4d dx0; */ /* dx0 << 0.1, 0.1, 0.1, 0.1; */ /* tmp = ros.DFx(x0, dx0); */ /* cout << tmp << endl; */ break; } case 4: { // find POs Rossler ros; Vector4d x0; x0 << 1, 6.0918, 1.2997, 5.88; //x0 << -3.36773 , 5.08498 , 0.0491195, 18; auto f = std::bind(&Rossler::Fx, ros, ph::_1); auto df = std::bind(&Rossler::DFx, ros, ph::_1, ph::_2); auto result = InexactNewtonBacktrack(f, df, x0, 1e-12, 10, 10); cout << std::get<0>(result) << endl; break; } } return 0; } <file_sep>from ksHelp import * case = 10 if case == 10: ksp = KSplot() fileName = '../../data/Ruslan/ks22h1t120.h5' a, T, nstp, theta, err = ksp.readPO(fileName, ksp.toStr('ppo', 1), False, hasNstp=False) <file_sep>/* to comiple: * g++ ksrefine.cc std=c++0x -O3 -march=corei7 -msse2 -msse4 * -L ../../lib -I ../../include -I $XDAPPS/eigen/include/eigen3 * -lksint -lfftw3 -lm */ #ifndef KSREFINE_H #define KSREFINE_H #include "ksint.hpp" #include <vector> #include <tuple> #include <Eigen/Dense> #include <Eigen/Sparse> class KSrefine { public: ////////////////////////////////////////////////// // variables const int N; /* N = 32 */ const double L; /* L = 22 */ ////////////////////////////////////////////////// std::tuple<VectorXd, double, double> findPO(const Eigen::ArrayXd &a0, const double T, const int Norbit, const int M, const std::string ppType, const double hinit = 0.1, const double th0 = 0, const int MaxN = 100, const double tol = 1e-14, const bool Print = false, const bool isSingle = false); std::tuple<MatrixXd, double, double, double> findPOmulti(const Eigen::ArrayXd &a0, const double T, const int Norbit, const int M, const std::string ppType, const double hinit = 0.1, const double th0 = 0, const int MaxN = 100, const double tol = 1e-14, const bool Print = false, const bool isSingle = false); Eigen::VectorXd multiF(KS &ks, const Eigen::ArrayXXd &x, const int nstp, const std::string ppType, const double th = 0.0); std::pair<Eigen::SparseMatrix<double>, Eigen::VectorXd> multishoot(KS &ks, const Eigen::ArrayXXd &x, const int nstp, const std::string ppType, const double th = 0.0, const bool Print = false); ////////////////////////////////////////////////// KSrefine(int N = 32, double L = 22); explicit KSrefine(const KSrefine &x); KSrefine & operator=(const KSrefine &x); ~KSrefine(); protected: std::vector<Eigen::Triplet<double> > triMat(const MatrixXd &A, const size_t M = 0, const size_t N = 0); std::vector<Eigen::Triplet<double> > triDiag(const size_t n, const double x, const size_t M = 0, const size_t N = 0 ); int calColSizeDF(const int &rows, const int &cols, const std::string ppType); }; #endif /* KSREFINE_H */ <file_sep>#include <iostream> #include <fstream> #include "KSPO.hpp" #include "iterMethod.hpp" #include "sparseRoutines.hpp" using namespace std; using namespace Eigen; using namespace sparseRoutines; using namespace iterMethod; using namespace MyH5; //////////////////////////////////////////////////////////// // class KSPO // //////////////////////////////////////////////////////////// /*------------ constructor ---------------*/ KSPO::KSPO(int N, double d) : KS(N, d) { } KSPO & KSPO::operator=(const KSPO &x){ return *this; } KSPO::~KSPO(){} //////////////////////////////////////////////////////////////////////////////// std::string KSPO::toStr(string ppType, int id){ char g[20]; sprintf(g, "%06d", id); return ppType + '/' + string(g); } std::string KSPO::toStr(double domainSize, string ppType, int id){ char g1[20], g2[20]; sprintf(g1, "%010.6f", domainSize); sprintf(g2, "%06d", id); return string(g1) + '/' + ppType + '/' + string(g2); } // [a, T, nstp, theta, err] std::tuple<VectorXd, double, int, double, double> KSPO::read(H5File &file, const std::string groupName, const bool isRPO){ // H5File file(fileName, H5F_ACC_RDONLY); string DS = "/" + groupName + "/"; // Ruslan's orignal data does not have nstp int nstp = checkGroup(file, groupName + "/nstp", false) ? readScalar<int>(file, DS + "nstp") : 0; double theta = isRPO ? readScalar<double>(file, DS + "theta") : 0; return make_tuple(readMatrixXd(file, DS + "a").col(0), readScalar<double>(file, DS + "T"), nstp, theta, readScalar<double>(file, DS + "err") ); } /** [a, T, nstp, theta, err] * @note group should be a new group */ void KSPO::write(H5File &file, const std::string groupName, const bool isRPO, const ArrayXd &a, const double T, const int nstp, const double theta, const double err){ // H5File file(fileName, H5F_ACC_RDWR); checkGroup(file, groupName, true); string DS = "/" + groupName + "/"; writeMatrixXd(file, DS + "a", a); writeScalar<double>(file, DS + "T", T); if(nstp > 0) // Ruslan's orignal data does not have nstp writeScalar<int>(file, DS + "nstp", nstp); if(isRPO) writeScalar<double>(file, DS + "theta", theta); writeScalar<double>(file, DS + "err", err); } MatrixXd KSPO::readE(H5File &file, const std::string groupName){ string DS = "/" + groupName + "/"; MatrixXd e = readMatrixXd(file, DS + "e"); return e; } MatrixXd KSPO::readV(H5File &file, const std::string groupName){ string DS = "/" + groupName + "/"; MatrixXd v = readMatrixXd(file, DS + "ve"); return v; } void KSPO::writeE(H5File &file, const std::string groupName, const MatrixXd &e){ checkGroup(file, groupName, true); string DS = "/" + groupName + "/"; writeMatrixXd(file, DS + "e", e); } void KSPO::writeV(H5File &file, const std::string groupName, const MatrixXd &v){ // H5File file(fileName, H5F_ACC_RDWR); checkGroup(file, groupName, true); string DS = "/" + groupName + "/"; writeMatrixXd(file, DS + "v", v); } void KSPO::move(H5File &fin, std::string gin, H5File &fout, std::string gout, int flag){ // VectorXd a; // VectorXcd e; // MatrixXcd v; // double wth, wphi, err; // std::tie(a, wth, wphi, err) = read(fin, gin); // if (flag == 1 || flag == 2) e = readE(fin, gin); // if (flag == 2) v = readV(fin, gin); // write(fout, gout, a, wth, wphi, err); // if (flag == 1 || flag == 2) writeE(fout, gout, e); // if (flag == 2) writeV(fout, gout, v); } //////////////////////////////////////////////////////////////////////////////// /** * @brief form [g*f(x,t) - x, ...] * * Form the difference vector, which consists of m pieces, each piece * correspond to (x, t, theta) for RPO and (x, t) for PPO. * If m = 1, then it reduces to single * shooting. * * @param[in] x [N*m, 1] dimensional vector for RPO and [(N-1)*m] for PPO * @return vector F_i(x, t) = * | g*f(x, t) - x| * | 0 | * | 0 | * for i = 1, 2, ..., m */ VectorXd KSPO::MFx(const VectorXd &x, const int nstp, const bool isRPO){ int n = isRPO ? N : N - 1; assert( x.size() % n == 0 ); int m = x.size() / n; VectorXd F(n*m); F.setZero(); for(int i = 0; i < m; i++){ VectorXd xi = x.segment(n*i, n); int j = (i+1) % m; VectorXd xn = x.segment(n*j, n); double t = xi(N-2); double th = isRPO ? xi(N-1) : 0; assert(t > 0); VectorXd fx = intgC(xi.head(N-2), t/nstp, t, nstp); // single state VectorXd gfx = isRPO ? (VectorXd)rotate(fx, th) : (i == m-1 ? (VectorXd)reflect(fx) : fx); F.segment(i*n, N-2) = gfx - xn.head(N-2); } return F; } /** * @brief multishooting * * For RPO * Here J_i = | g*J(x, t), g*v(f(x,t)), g*t(f(x,t)) | * | v(x), 0 0 | * | t(x), 0 0 | * For PPO * i = 1, ..., m-1 * Here J_i = | J(x, t), v(f(x,t)) | * | v(x), 0 | * i = m * Here J_i = | g*J(x, t), g*v(f(x,t)) | * | v(x), 0 | * * If m = 1, then it reduces to single shooting * * @note I do not enforce the constraints */ std::tuple<SpMat, SpMat, VectorXd> KSPO::multiCalJJF(const VectorXd &x, int nstp, const bool isRPO){ int n = isRPO ? N : N - 1; assert( x.size() % n == 0 ); int m = x.size() / n; SpMat DF(m*n, m*n); vector<Tri> nz; VectorXd F(m*n); for (int i = 0; i < m; i++) { VectorXd xi = x.segment(i*n, n); int j = (i+1) % m; VectorXd xn = x.segment(n*j, n); double t = xi(N-2); double th = isRPO ? xi(N-1) : 0; assert( t > 0 ); auto tmp = intgjC(xi.head(N-2), t/nstp, t, nstp); ArrayXXd &fx = tmp.first; ArrayXXd &J = tmp.second; VectorXd gfx = isRPO ? rotate(fx, th) : (i == m-1 ? reflect(fx) : fx); F.segment(i*n, N-2) = gfx - xn.head(N-2); ArrayXXd gJ = isRPO ? rotate(J, th) : (i == m-1 ? reflect(J) : J); VectorXd vgfx = velocity(gfx); vector<Tri> triJ = triMat(gJ, i*n, i*n); nz.insert(nz.end(), triJ.begin(), triJ.end()); vector<Tri> triv = triMat(vgfx, i*n, i*n+N-2); nz.insert(nz.end(), triv.begin(), triv.end()); if(isRPO){ VectorXd tgfx = gTangent(gfx); vector<Tri> tritx = triMat(tgfx, i*n, i*n+N-1); nz.insert(nz.end(), tritx.begin(), tritx.end()); } // // constraint // ArrayXXd v = velocity(xi.head(N-2)).transpose(); // triv = triMat(v, i*n+N-2, i*n); // nz.insert(nz.end(), triv.begin(), triv.end()); // if(isRPO){ // ArrayXXd t = gTangent(xi.head(N-2)).transpose(); // vector<Tri> tritx = triMat(t, i*n+N-1, i*n); // nz.insert(nz.end(), tritx.begin(), tritx.end()); // } // -I on the subdiagonal vector<Tri> triI = triDiag(N-2, -1, i*n, j*n); nz.insert(nz.end(), triI.begin(), triI.end()); } DF.setFromTriplets(nz.begin(), nz.end()); SpMat JJ = DF.transpose() * DF; SpMat D = JJ; auto keepDiag = [](const int& row, const int& col, const double&){ return row == col; }; D.prune(keepDiag); VectorXd df = DF.transpose() * F; return std::make_tuple(JJ, D, df); } // single shooting // Here J = | g*J(x, t) - I, g*v(f(x,t)), g*t(f(x,t)) | // | v(x), 0 0 | // | t(x), 0 0 | std::tuple<MatrixXd, MatrixXd, VectorXd> KSPO::calJJF(const VectorXd &x, int nstp, const bool isRPO){ int n = isRPO ? N : N - 1; assert(x.size() == n); MatrixXd DF(n, n); DF.setZero(); VectorXd F(n); F.setZero(); double t = x(N-2); double th = isRPO ? x(N-1) : 0; assert( t > 0 ); auto tmp = intgjC(x.head(N-2), t/nstp, t, nstp); ArrayXXd &fx = tmp.first; ArrayXXd &J = tmp.second; VectorXd gfx = isRPO ? rotate(fx, th) : reflect(fx); F.head(N-2) = gfx - x.head(N-2); DF.topLeftCorner(N-2, N-2) = (isRPO ? rotate(J, th) : reflect(J)).matrix() - MatrixXd::Identity(N-2, N-2) ; DF.col(N-2).head(N-2) = velocity(gfx); if(isRPO) DF.col(N-1).head(N-2) = gTangent(gfx); // DF.row(N-2).head(N-2) = velocity(x.head(N-2)).transpose(); // if(isRPO) DF.row(N-1).head(N-2) = gTangent(x.head(N-2)).transpose(); MatrixXd JJ = DF.transpose() * DF; MatrixXd D = JJ.diagonal().asDiagonal(); VectorXd df = DF.transpose() * F; return std::make_tuple(JJ, D, df); } /// @return [ (x, T, th), err, flag ] std::tuple<ArrayXXd, double, int> KSPO::findPO_LM(const ArrayXXd &a0, const bool isRPO, const int nstp, const double tol, const int maxit, const int innerMaxit){ int cols = a0.cols(), rows = a0.rows(); assert (rows == isRPO ? N : N - 1); Map<const VectorXd> x(a0.data(), cols * rows); auto fx = [this, &isRPO, &nstp](const VectorXd &x){ return MFx(x, nstp, isRPO); }; VectorXd xe; std::vector<double> res; int flag; if(cols == 1){ KSPO_JJF<MatrixXd> jj(this, nstp, isRPO); PartialPivLU<MatrixXd> solver; std::tie(xe, res, flag) = LM0(fx, jj, solver, x, tol, maxit, innerMaxit); } else { KSPO_MULTIJJF<SpMat> jj(this, nstp, isRPO); SparseLU<SpMat> solver; std::tie(xe, res, flag) = LM0(fx, jj, solver, x, tol, maxit, innerMaxit); } if(flag != 0) fprintf(stderr, "PO not converged ! \n"); ArrayXXd states(xe); states.resize(rows, cols); return std::make_tuple( states, res.back(), flag ); } std::pair<MatrixXd, MatrixXd> KSPO::calEV(const bool isRPO, const ArrayXd &a0, const double T, const int nstp, const double theta, const double tol, const int MaxN, const int trunc){ auto tmp = intgjC(a0, T/nstp, T, 1); MatrixXd Js = tmp.second; // need to make it MatrixXd. PED ped; ped.reverseOrder(Js); Js.leftCols(N-2) = isRPO ? rotate(Js.leftCols(N-2), theta) : reflect(Js.leftCols(N-2)); pair<MatrixXd, MatrixXd> ev = ped.EigVecs(Js, MaxN, tol, false, trunc); MatrixXd &e = ev.first, &v = ev.second; e.col(0) /= T; return make_pair(e, v); } <file_sep>from py_CQCGL1d import * from cglHelp import * case = 60 if case == 1: """ view an ergodic instance full state space => reduce continuous symmetry => reduce reflection symmetry """ N = 256 d = 50 h = 0.005 cgl = pyCqcgl1d(N, d, h, True, 0, -0.1, 1.0, 0.8, 0.125, 0.5, -0.1, -0.6, 4) Ndim = cgl.Ndim A0 = centerRand(2*N, 0.2) a0 = cgl.Config2Fourier(A0) nstp = 15000 aa = cgl.intg(a0, nstp, 1) plotConfigSpaceFromFourier(cgl, aa, [0, d, 0, nstp*h]) aaHat, th, phi = cgl.orbit2sliceWrap(aa) aaHat2, th2, phi2 = cgl.orbit2slice(aa) plotConfigSpace(cgl.Fourier2Config(aaHat), [0, d, 0, nstp*h]) plotConfigSpace(cgl.Fourier2Config(aaHat2), [0, d, 0, nstp*h]) aaTilde = cgl.reduceReflection(aaHat) plotConfigSpace(cgl.Fourier2Config(aaTilde), [0, d, 0, nstp*h]) # rely on numpy's unwrap function th3 = unwrap(th*2.0)/2.0 phi3 = unwrap(phi*2.0)/2.0 aaHat3 = cgl.rotateOrbit(aa, -th3, -phi3) plotConfigSpace(cgl.Fourier2Config(aaHat3), [0, d, 0, nstp*h]) # rotate by g(pi, pi) aaHat4 = cgl.Rotate(aaHat2, pi, pi) plotConfigSpace(cgl.Fourier2Config(aaHat4), [0, d, 0, nstp*h]) aaTilde4 = cgl.reduceReflection(aaHat4) plotConfigSpace(cgl.Fourier2Config(aaTilde4), [0, d, 0, nstp*h]) # reflection aa2 = cgl.reflect(aa) plotConfigSpace(cgl.Fourier2Config(aa2), [0, d, 0, nstp*h]) aaHat5, th5, phi5 = cgl.orbit2slice(aa2) plotConfigSpaceFromFourier(cgl, aaHat5, [0, d, 0, nstp*h]) aaTilde5 = cgl.reduceReflection(aaHat5) plotConfigSpace(cgl.Fourier2Config(aaTilde5), [0, d, 0, nstp*h]) if case == 2: # view relative equlibria N = 1024 d = 30 di = 0.06 cgl = pyCQCGL(N, d, 4.0, 0.8, 0.01, di, -1, 4) a0, wth0, wphi0, err = cqcglReadReq('../../data/cgl/reqN512.h5', '1') vReq = cgl.velocityReq(a0, wth0, wphi0) print norm(vReq) # check the reflected state a0Reflected = cgl.reflect(a0) vReqReflected = cgl.velocityReq(a0Reflected, -wth0, wphi0) print norm(vReqReflected) # plotOneConfigFromFourier(cgl, a0) # plotOneConfigFromFourier(cgl, a0Reflected) # obtain the stability exponents/vectors # eigvalues, eigvectors = eigReq(cgl, a0, wth0, wphi0) eigvalues, eigvectors = eigReq(cgl, a0Reflected, -wth0, wphi0) print eigvalues[:10] # make sure you make a copy because Fourier2Config takes contigous memory tmpr = eigvectors[:, 0].real.copy() tmprc = cgl.Fourier2Config(tmpr) tmpi = eigvectors[:, 0].imag.copy() tmpic = cgl.Fourier2Config(tmpi) plotOneConfig(tmprc, size=[6, 4]) plotOneConfig(tmpic, size=[6, 4]) nstp = 2000 aa = cgl.intg(a0Reflected, nstp, 1) plotConfigSpace(cgl.Fourier2Config(aa), [0, d, 0, nstp*h], [0, 2]) raa, th, phi = cgl.orbit2slice(aa) plotConfigSpace(cgl.Fourier2Config(raa), [0, d, 0, nstp*h], [0, 2]) plotOneFourier(aa[-1]) # test the ve2slice function if case == 3: N = 512 d = 50 h = 0.01 cgl = pyCqcgl1d(N, d, h, -0.1, 1.0, 0.8, 0.125, 0.5, -0.1, -0.6) a0, wth0, wphi0, err = cqcglReadReq('../../data/cgl/reqN512.h5', '1') eigvalues, eigvectors = eigReq(cgl, a0, wth0, wphi0) # plot the last vector to see whether Tcopy works eigvectors = realve(eigvectors) eigvectors = Tcopy(eigvectors) plotOneConfigFromFourier(cgl, eigvectors[-1]) veHat = cgl.ve2slice(eigvectors, a0) print veHat[:4, :8] # plotOneConfigFromFourier(cgl, eigvectors[0]) # print out the norm of two marginal vectors. They should valish print norm(veHat[4]), norm(veHat[5]) # test the angle between each eigenvector v1 = veHat[0] v2 = veHat[1] print np.dot(v1, v2) / norm(v1) / norm(v2) plotOneFourier(v1) plotOneFourier(v2) if case == 4: """ test the reflectVe function """ N = 512 d = 50 h = 0.01 cgl = pyCqcgl1d(N, d, h, -0.1, 1.0, 0.8, 0.125, 0.5, -0.1, -0.6) Ndim = cgl.Ndim a0, wth0, wphi0, err = cqcglReadReq('../../data/cgl/reqN512.h5', '1') eigvalues, eigvectors = eigReq(cgl, a0, wth0, wphi0) eigvectors = realve(eigvectors) eigvectors = Tcopy(eigvectors) a0Hat = cgl.orbit2slice(a0)[0] veHat = cgl.ve2slice(eigvectors, a0) veTilde = cgl.reflectVe(veHat, a0Hat) a0Ref = cgl.reflect(a0) veRef = cgl.reflect(eigvectors) a0RefHat = cgl.orbit2slice(a0Ref)[0] veRefHat = cgl.ve2slice(veRef, a0Ref) veRefTilde = cgl.reflectVe(veRefHat, a0RefHat) # why the hell is veHat the same as veRefHat ? if case == 50: """ use the new form of cqcgl test the transition with respect to di """ N = 1024 d = 30 h = 1e-4 di = 0.05 cgl = pyCQCGL1d(N, d, 4.0, 0.8, 0.01, di, -1) A0 = 3*centerRand(N, 0.2, True) a0 = cgl.Config2Fourier(A0) nstp = 20000 x = [] for i in range(3): aa = cgl.intg(a0, h, nstp, 10) a0 = aa[-1] plotConfigSpaceFromFourier(cgl, aa, [0, d, 0, nstp*h]) # plotPhase(cgl, aa, [0, d, 0, nstp*h]) # plotOneConfigFromFourier(cgl, aa[-1], d) # plotOnePhase(cgl, aa[-1], d) # plot1dfig(aa[:, 0]) x.append(aa) if case == 55: """ reproduce the pulstating soliton with L = 50 """ N, d = 1024 , 50 h = 1e-2 cgl = pyCQCGL1d(N, d, -0.1, 0.08, 0.5, 0.782, 1, -0.1, -0.08, -1) rpo, cp = CQCGLrpo(cgl), CQCGLplot(cgl) Ndim = cgl.Ndim A0 = 3*centerRand(N, 0.2, True) a0 = cgl.Config2Fourier(A0) a0 = cgl.intgC(a0, h, 100, 1000000) T = 70 aa = cgl.intgC(a0, h, T, 100) aa2 = cgl.intg(a0, h, T, 100) cp.config(aa, [0, d, 0, T]) np.savez_compressed('pulsatingSoliton', states=aa, statesAdapt=aa2, Ts=cgl.Ts(), T=T) if case == 56: """ produce profile with extremete solition """ N, d = 1024 , 50 Bi, Gi = 3.5, -5.0 cgl = pyCQCGL1d(N, d, -0.1, 0.125, 0.5, 1, Bi, -0.1, Gi, -1) rpo, cp = CQCGLrpo(cgl), CQCGLplot(cgl) x, T, nstp, th, phi, err, e, v = rpo.read('../../data/cgl/rpoBiGiEV.h5', rpo.toStr(Bi, Gi, 1), flag=2) a0 = x[:cgl.Ndim] print e[:10] #a0 += 0.1*norm(a0)*v[0] aa = cgl.intgC(a0, T/nstp, 3*T, 600) aa2 = cgl.intg(a0, T/nstp, 3*T, 50) cp.config(aa, [0, d, 0, 3*T]) np.savez_compressed('extremeSoliton', states=aa, statesAdapt=aa2, Ts=cgl.Ts(), T=3*T) if case == 57: """ produce profile with composite soliton """ N, d = 1024 , 50 h = 2e-3 Bi, Gi = 3, -5.0 cgl = pyCQCGL1d(N, d, -0.1, 0.125, 0.5, 1, Bi, -0.1, Gi, -1) req, cp = CQCGLreq(cgl), CQCGLplot(cgl) a0, wth0, wphi0, err = req.read('../../data/cgl/reqBiGi.h5', req.toStr(Bi, Gi, 1)) T = 10 aa = cgl.intgC(a0, h, T, 100) aa2 = cgl.intg(a0, h, T, 50) cp.config(aa, [0, d, 0, T]) np.savez_compressed('compositeSoliton', states=aa, statesAdapt=aa2, Ts=cgl.Ts(), T=T) if case == 58: """ produce """ N, d = 1024, 120 h = 2e-3 Dr = 0.883 cgl = pyCQCGL1d(N, d, -0.1, Dr, -1.1, 3, 1, -2.75, 1, -1) cp = CQCGLplot(cgl) Ndim = cgl.Ndim A0 = 3*centerRand(N, 0.1, True) a0 = cgl.Config2Fourier(A0) a0 = cgl.intg(a0, h, 100, 1000000) T = 30 aa = cgl.intgC(a0, h, T, 50) aa2 = cgl.intg(a0, h, T, 50) cp.config(aa, [0, d, 0, T]) ############################################################################### if case == 60: """ Try to reproduce the result of Descalzi. ======= <NAME> and <NAME>, "Transition from modulated to exploding dissipative solitons: Hysteresis, dynamics, and analytic aspects", Phys. Rev. E 82, 026203 (2010) ====== But I failed to get the f1 and f1-f2 region and their hysteretic transition. """ N = 1024 d = 50 h = 2e-3 Mu = -1 cgl = pyCQCGL1d(N, d, Mu, 0.125, 0.5, 1, 1, -0.1, -0.6, -1) cp = CQCGLplot(cgl) Ndim = cgl.Ndim A0 = 3*centerRand(N, 0.2, True) a0 = cgl.Config2Fourier(A0) a0 = cgl.intg(a0, h, 50, 1000000) # stable soliton T = 50 aa = cgl.intg(a0, h, T, 100) cp.config(aa, [0, d, 0, T]) # oscillating soltion with one frequency Mu = -0.21 cgl = pyCQCGL1d(N, d, Mu, 0.125, 0.5, 1, 0.8, -0.1, -0.6, -1) T = 50 a0 = cgl.intg(aa[-1], h, 5, 1000000) aa = cgl.intg(a0, h, T, 100) cp.config(aa, [0, d, 0, T]) # oscillating soltion with two frequency Mu = -0.21 cgl = pyCQCGL1d(N, d, Mu, 0.125, 0.5, 1, 1, -0.1, -0.6, -1) T = 80 a0 = cgl.intg(aa[-1], h, 5, 1000000) aa = cgl.intg(a0, h, T, 100) cp.config(aa, [0, d, 0, T]) # aa = cgl.intg(a0, 0.01, np.int(50/0.01), 10) # plotConfigSpaceFromFourier(cgl, aa, [0, d, 0, T]) if case == 70: """ Try to reproduce AKhmediev's paper ====== Strongly asymmetric soliton explosions <NAME>, <NAME> - Physical Review E, 2004 - APS ===== """ N = 1024 d = 30 h = 1e-4 nu = -0.4 cgl = pyCQCGL1d(N, d, -0.8, 0.15, 1, 1.4, -0.1, nu, -1) Ndim = cgl.Ndim A0 = 3*centerRand(N, 0.2, True) a0 = cgl.Config2Fourier(A0) a0 = cgl.intg(a0, h, np.int(50/h), np.int(50/h))[-1] T = 500 aa = cgl.intg(a0, h, np.int(T/h), 100) plotConfigSpaceFromFourier(cgl, aa, [0, d, 0, T]) if case == 80: """ Try to reproduce results of Deissler and Brand ====== "Periodic, quasiperiodic, and chaotic localized solutions of the quintic complex Ginzburg-Landau equation" <NAME>, HR Brand - Physical review letters, 1994 - APS ====== """ N = 1024 d = 120 h = 1e-3 Dr = 0.9 cgl = pyCQCGL1d(N, d, -0.1, Dr, -1.1, 3, 1, -2.75, 1, -1) Ndim = cgl.Ndim A0 = 3*centerRand(N, 0.1, True) a0 = cgl.Config2Fourier(A0) a0 = cgl.intg(a0, h, np.int(100/h), np.int(100/h))[-1] T = 250 aa = cgl.intg(a0, h, np.int(T/h), 20) plotConfigSpaceFromFourier(cgl, aa, [0, d, 0, T]) if case == 90: """ Try to reproduce results in ====== Creeping solitons in dissipative systems and their bifurcations <NAME>, <NAME>, <NAME>, and <NAME> Phys. Rev. E 76, 016607 - Published 26 July 2007 ====== """ N = 1024 d = 60 h = 1e-2 epsilon = 0.844 cgl = pyCQCGL1d(N, d, -0.1, 0.08, 1, epsilon, -0.11, -0.08, -1) cp = CQCGLplot(cgl) if True: Ndim = cgl.Ndim A0 = 3*centerRand(N, 0.2, True) a0 = cgl.Config2Fourier(A0) a0 = cgl.intgC(a0, h, 100, 1000000) T = 300 aa = cgl.intgC(a0, h, T, 100) Q = cgl.calQ(aa) cp.config(aa, [0, d, 0, T]) plot1dfig(Q) np.save('a0', aa[-1]) if False: cgl.Br = 0.844 a0 = load('a0.npy') a0 = cgl.intg(a0, h, np.int(100/h), np.int(100/h))[-1] T = 300 aa = cgl.intg(a0, h, np.int(T/h), 100) plotConfigSpaceFromFourier(cgl, aa, [0, d, 0, T]) np.save('a1', aa[-1]) cgl.Br = 0.844 a0 = np.load('a0.npy') a0 = cgl.intgC(a0, h, 100, 1000000) T = 100 aa = cgl.intg(a0, h, T, 20) Q = cgl.calQ(aa) cp.config(aa, [0, d, 0, T]) plot1dfig(Q) <file_sep>#include <iostream> #include "cgl1d.hpp" /** * The constructor of complex Ginzburg-Landau equation * A_t = A + (1 + b*i) A_{xx} - (1 + c*i) |A|^2 A * * @see Cqcgl1d() */ Cgl1d::Cgl1d(int N, double d, double h, bool enableJacv, int Njacv, double b, double c, int threadNum) : Cqcgl1d::Cqcgl1d(N, d, h, enableJacv, Njacv, 1, -1, -c, 1, b, 0, 0, threadNum) { } /** * Nonlinear term without the quintic term */ void Cgl1d::NL(FFT &f){ f.ifft(); ArrayXcd A2 = f.v2 * f.v2.conjugate(); /* |A|^2 */ f.v2 = dcp(Br, Bi) * f.v2 * A2; f.fft(); } /** * Nonlinear term without the quintic term */ void Cgl1d::jNL(FFT &f){ f.ifft(); ArrayXcd A = f.v2.col(0); ArrayXcd aA2 = A * A.conjugate(); /* |A|^2 */ ArrayXcd A2 = A.square(); /* A^2 */ dcp B(Br, Bi); dcp G(Gr, Gi); f.v2.col(0) = dcp(Br, Bi) * A * aA2; const int M = f.v2.cols() - 1; f.v2.rightCols(M) = f.v2.rightCols(M).conjugate().colwise() * (B * A2) + f.v2.rightCols(M).colwise() * (2.0*B*aA2); f.fft(); } <file_sep>/* to compile the class * * compile with Mutithreads FFT support: * g++ cqcgl1d.cc -shared -fpic -march=corei7 -O3 -msse2 -msse4 -lfftw3_threads -lfftw3 -lm -fopenmp -DTFFT -I $XDAPPS/eigen/include/eigen3 -I../include -std=c++0x * * complile with only one thread: * g++ cqcgl1d.cc -shared -fpic -lfftw3 -lm -fopenmp -march=corei7 -O3 -msse2 -msse4 -I/usr/include/eigen3 -I../../include -std=c++0x * * */ #ifndef CQCGL1D_H #define CQCGL1D_H #include <complex> #include <utility> #include <algorithm> #include <vector> #include <unsupported/Eigen/FFT> #include "denseRoutines.hpp" #include "EIDc.hpp" ////////////////////////////////////////////////////////////////////// // class CQCGL1d // ////////////////////////////////////////////////////////////////////// class CQCGL1d { public: typedef std::complex<double> dcp; const int N; /* dimension of FFT */ const double d; /* system domain size */ const int Ne; /* effective number of modes */ const int Ndim; /* dimension of state space */ const int Nplus, Nminus, Nalias; const int DimTan; // the dimension of tangent space bool IsQintic = true; // False => cubic equation double Mu, Dr, Di, Br, Bi, Gr, Gi; double Omega = 0; /* used for comoving frame */ ArrayXd K, K2, QK; ArrayXcd L; FFT<double> fft; VectorXd hs; /* time step sequnce */ VectorXd lte; /* local relative error estimation */ VectorXd Ts; /* time sequnence for adaptive method */ int cellSize = 500; /* size of cell when resize output container */ struct NL { CQCGL1d *cgl; int N; dcp B, G; ArrayXXcd AA; NL(); NL(CQCGL1d *cgl, int cols); ~NL(); void operator()(ArrayXXcd &x, ArrayXXcd &dxdt, double t); }; NL nl, nl2; ArrayXXcd Yv[10], Nv[10], Yv2[10], Nv2[10]; EIDc eidc, eidc2; //////////////////////////////////////////////////////////// // constructor, destructor, copy assignment. // //////////////////////////////////////////////////////////// // A_t = Mu A + (Dr + Di*i) A_{xx} + (Br + Bi*i) |A|^2 A + (Gr + Gi*i) |A|^4 A CQCGL1d(int N, double d, double Mu, double Dr, double Di, double Br, double Bi, double Gr, double Gi, int dimTan); // A_t = -A + (1 + b*i) A_{xx} + (1 + c*i) |A|^2 A - (dr + di*i) |A|^4 A CQCGL1d(int N, double d, double b, double c, double dr, double di, int dimTan); // iA_z + D A_{tt} + |A|^2 A + \nu |A|^4 A = i \delta A + i \beta A_{tt} + i |A|^2 A + i \mu |A|^4 A CQCGL1d(int N, double d, double delta, double beta, double D, double epsilon, double mu, double nu, int dimTan); ~CQCGL1d(); CQCGL1d & operator=(const CQCGL1d &x); //////////////////////////////////////////////////////////// // member functions. // //////////////////////////////////////////////////////////// //============================================================ void setScheme(std::string x); void changeOmega(double w); ArrayXXd intgC(const ArrayXd &a0, const double h, const double tend, const int skip_rate); std::pair<ArrayXXd, ArrayXXd> intgjC(const ArrayXd &a0, const double h, const double tend, const int skip_rate); ArrayXXd intgvC(const ArrayXd &a0, const ArrayXXd &v, const double h, const double tend); ArrayXXd intg(const ArrayXd &a0, const double h, const double tend, const int skip_rate); std::pair<ArrayXXd, ArrayXXd> intgj(const ArrayXd &a0, const double h, const double tend, const int skip_rate); ArrayXXd intgv(const ArrayXXd &a0, const ArrayXXd &v, const double h, const double tend); ArrayXXd C2R(const ArrayXXcd &v); ArrayXXcd R2C(const ArrayXXd &v); ArrayXXd c2r(const ArrayXXcd &v); ArrayXXcd r2c(const ArrayXXd &v); //============================================================ ArrayXXcd Fourier2Config(const Ref<const ArrayXXd> &aa); ArrayXXd Config2Fourier(const Ref<const ArrayXXcd> &AA); ArrayXXd Fourier2ConfigMag(const Ref<const ArrayXXd> &aa); ArrayXXd calPhase(const Ref<const ArrayXXcd> &AA); ArrayXXd Fourier2Phase(const Ref<const ArrayXXd> &aa); VectorXd calQ(const Ref<const ArrayXXd> &aa); VectorXd calMoment(const Ref<const ArrayXXd> &aa, const int p = 1); ArrayXd velocity(const ArrayXd &a0); ArrayXd velocityReq(const ArrayXd &a0, const double th, const double phi); VectorXd velSlice(const Ref<const VectorXd> &aH); VectorXd velPhase(const Ref<const VectorXd> &aH); MatrixXd rk4(const VectorXd &a0, const double dt, const int nstp, const int nq); MatrixXd velJ(const MatrixXd &xj); std::pair<MatrixXd, MatrixXd> rk4j(const VectorXd &a0, const double dt, const int nstp, const int nq, const int nqr); ArrayXcd Lyap(const Ref<const ArrayXXd> &aa); ArrayXd LyapVel(const Ref<const ArrayXXd> &aa); MatrixXd stab(const ArrayXd &a0); MatrixXd stabReq(const ArrayXd &a0, double th, double phi); VectorXcd eReq(const ArrayXd &a0, double wth, double wphi); MatrixXcd vReq(const ArrayXd &a0, double wth, double wphi); std::pair<VectorXcd, MatrixXcd> evReq(const ArrayXd &a0, double wth, double wphi); ArrayXXd reflect(const Ref<const ArrayXXd> &aa); inline ArrayXd rcos2th(const ArrayXd &x, const ArrayXd &y); inline ArrayXd rsin2th(const ArrayXd &x, const ArrayXd &y); inline double rcos2thGrad(const double x, const double y); inline double rsin2thGrad(const double x, const double y); ArrayXXd reduceRef1(const Ref<const ArrayXXd> &aaHat); ArrayXXd reduceRef2(const Ref<const ArrayXXd> &step1); std::vector<int> refIndex3(); ArrayXXd reduceRef3(const Ref<const ArrayXXd> &aa); ArrayXXd reduceReflection(const Ref<const ArrayXXd> &aaHat); MatrixXd refGrad1(); MatrixXd refGrad2(const ArrayXd &x); MatrixXd refGrad3(const ArrayXd &x); MatrixXd refGradMat(const ArrayXd &x); MatrixXd reflectVe(const MatrixXd &veHat, const Ref<const ArrayXd> &xHat); MatrixXd reflectVeAll(const MatrixXd &veHat, const MatrixXd &aaHat, const int trunc = 0); ArrayXXd transRotate(const Ref<const ArrayXXd> &aa, const double th); ArrayXXd transTangent(const Ref<const ArrayXXd> &aa); MatrixXd transGenerator(); ArrayXXd phaseRotate(const Ref<const ArrayXXd> &aa, const double phi); ArrayXXd phaseTangent(const Ref<const ArrayXXd> &aa); MatrixXd phaseGenerator(); ArrayXXd Rotate(const Ref<const ArrayXXd> &aa, const double th, const double phi); ArrayXXd rotateOrbit(const Ref<const ArrayXXd> &aa, const ArrayXd &th, const ArrayXd &phi); std::tuple<ArrayXXd, ArrayXd, ArrayXd> orbit2slice(const Ref<const ArrayXXd> &aa, const int method); MatrixXd ve2slice(const ArrayXXd &ve, const Ref<const ArrayXd> &x, int flag); std::tuple<ArrayXXd, ArrayXd, ArrayXd> reduceAllSymmetries(const Ref<const ArrayXXd> &aa, int flag); MatrixXd reduceVe(const ArrayXXd &ve, const Ref<const ArrayXd> &x, int flag); std::tuple<ArrayXd, double, double> planeWave(int k, bool isPositve); VectorXcd planeWaveStabE(int k, bool isPositve); std::pair<VectorXcd, MatrixXcd> planeWaveStabEV(int k, bool isPositve); }; #endif /* CQCGL1D_H */ <file_sep>from personalFunctions import * from scipy.spatial.distance import pdist if False: Np = 10000 # number of points Ns = 1000 # number of steps z = np.zeros(Np, dtype=np.complex) s = np.zeros(Ns) for i in range(Ns): z += np.exp(rand(Np)*2j*np.pi) s[i] = np.mean(np.abs(z)**2) a2 = np.zeros(Np) z2 = np.zeros(Np, dtype=np.complex) s2 = np.zeros(Ns) for i in range(Ns): for j in range(Np): t = rand() d = min([abs(t-a2[j]), abs(t-a2[j]+1), abs(t-a2[j]-1)]) while d < 0.1: t = rand() d = [abs(t - a2[j]), abs(t-a2[j]+1), abs(t-a2[j]-1)] a2[j] = t z2[j] += np.exp(t*2j*np.pi) s2[i] = np.mean(np.abs(z2)**2) ss = np.loadtxt('ss.dat') fig, ax = pl2d(size=[8, 6], labs=[r'$N$', r'$<r^2>$'], axisLabelSize=25, xlim=[0, 1000], ylim=[0, 1000], tickSize=None) for i in range(ss.shape[1]): ax.plot(ss[:, i], lw=2) ax2d(fig, ax) <file_sep>#ifndef KSSOLVE_H #define KSSOLVE_H #include <complex> #include <fftw3.h> #include <new> class Ks { public: /***** structure definition. ******/ typedef std::complex<double> dcomp; typedef struct{ double *E, *E2; double *k, *L; double *Q, *f1, *f2, *f3; dcomp *g; } KsCoe; // member variables. const int N; const double d; const double h; KsCoe coe; // constructors, destructor, copy assignment. Ks(int N = 32, double d = 22, double h = 0.25); explicit Ks(const Ks &x); ~Ks(); Ks & operator=(const Ks &x); // member function /* @brief KS solver without calculating Jacobian matrix. * * @param[in] a0 initial condition, size N-2 array * @param[in] h time step * @param[in] nstp number of steps to be integrated * @param[in] np state saving spacing. * @param[out] aa saved state vector size = (nstp/np)*(N-2) * eg. if state column vector is v0, v1, ... vn-1, then * aa is a row vector [ v0^{T}, v1^{T}, ... vn-1^{T}]. */ void kssolve(double *a0, int nstp, int np, double *aa); /* @brief KS solver with calculating Jacobian (size (N-2)*(N-2)). * * @param[in] nqr Jacobian saving spacing spacing * @param[out] daa saved Jacobian matrix. size = (nstp/nqr)*(N-2)*(N-2). * eg. If Jacobian matrix is J=[v1, v2,..., vn] each vi is a * column vector, then * daa is a row vector [vec(J1), vec(J2), vec(Jn)], where * vec(J)= [v1^{T}, v2^{T},...,vn^{T}] with each element * visted column-wise. */ void kssolve(double *a0, int nstp, int np, int nqr, double *aa, double *daa); protected: /**** global variable definition. *****/ static constexpr double PI=3.14159265358979323; /** @brief Structure for convenience of rfft. * For forward real Fourier transform, 'in' is real * and 'out' is complex. * For inverse real Fourier transform, the situation reverses. */ typedef struct{ fftw_plan p; fftw_complex *c; // complex array. double *r; // real array } FFT; /* member function */ virtual void initKs(double *a0, dcomp *v, double *aa, FFT &rp, FFT &p); virtual void initKs(double *a0, dcomp *v, double *aa, FFT *rp, FFT *p); virtual void initJ(dcomp *v); void cleanKs(FFT &rp, FFT &p); void cleanKs(FFT *rp, FFT *p); void calcoe(const int M = 16); void onestep(dcomp *v, FFT &p, FFT &rp); void onestep(dcomp *v, FFT *p, FFT *rp); virtual void calNL(dcomp *u, dcomp *Nv, const FFT &p, const FFT &rp); virtual void calNL(dcomp *u, dcomp *Nv, const FFT *p, const FFT *rp ); void irfft(const dcomp *u, const FFT &rp); void rfft(double *u, const FFT &p); void initFFT(FFT &p, int a); void freeFFT(FFT &p); }; #endif /* KSSOLVE_H */ <file_sep>#include <iostream> #include <functional> #include "CQCGL1dSubReq.hpp" #include "iterMethod.hpp" #define cee(x) (cout << (x) << endl << endl) namespace ph = std::placeholders; using namespace std; using namespace Eigen; using namespace iterMethod; using namespace denseRoutines; using namespace MyH5; ////////////////////////////////////////////////////////////////////// // constructor // ////////////////////////////////////////////////////////////////////// // A_t = Mu A + (Dr + Di*i) A_{xx} + (Br + Bi*i) |A|^2 A + (Gr + Gi*i) |A|^4 A CQCGL1dSubReq::CQCGL1dSubReq(int N, double d, double Mu, double Dr, double Di, double Br, double Bi, double Gr, double Gi, int dimTan): CQCGL1dSub(N, d, Mu, Dr, Di, Br, Bi, Gr, Gi, dimTan) {} // A_t = -A + (1 + b*i) A_{xx} + (1 + c*i) |A|^2 A - (dr + di*i) |A|^4 A CQCGL1dSubReq::CQCGL1dSubReq(int N, double d, double b, double c, double dr, double di, int dimTan): CQCGL1dSub(N, d, b, c, dr, di, dimTan){} // iA_z + D A_{tt} + |A|^2 A + \nu |A|^4 A = i \delta A + i \beta A_{tt} + i |A|^2 A + i \mu |A|^4 A CQCGL1dSubReq::CQCGL1dSubReq(int N, double d, double delta, double beta, double D, double epsilon, double mu, double nu, int dimTan) : CQCGL1dSub(N, d, delta, beta, D, epsilon, mu, nu, dimTan) {} CQCGL1dSubReq::~CQCGL1dSubReq(){} CQCGL1dSubReq & CQCGL1dSubReq::operator=(const CQCGL1dSubReq &x){ return *this; } ////////////////////////////////////////////////////////////////////// // member functions // ////////////////////////////////////////////////////////////////////// std::string CQCGL1dSubReq::toStr(double Bi, double Gi, int id){ // avoid possibilty that 000000.000000 or -00000.000000 if (fabs(Bi) < 1e-6) Bi = 0; if (fabs(Gi) < 1e-6) Gi = 0; char g1[20], g2[20]; sprintf(g1, "%013.6f", Bi); sprintf(g2, "%013.6f", Gi); string s1(g1); string s2(g2); string s = s1 + '/' + s2 + '/' + to_string(id); return s; } /** * @brief read req (relative equibrium) info from hdf5 file * */ std::tuple<VectorXd, double, double> CQCGL1dSubReq::read(H5File &file, const std::string groupName){ // H5File file(fileName, H5F_ACC_RDONLY); string DS = "/" + groupName + "/"; return make_tuple(readMatrixXd(file, DS + "a").col(0), readScalar<double>(file, DS + "wphi"), readScalar<double>(file, DS + "err") ); } /** * @brief write [a, wth, wphi, err] of Req of cqcgl into a group * * @note group should be a new group */ void CQCGL1dSubReq::write(H5File &file, const std::string groupName, const ArrayXd &a, const double wphi, const double err){ // H5File file(fileName, H5F_ACC_RDWR); checkGroup(file, groupName, true); string DS = "/" + groupName + "/"; writeMatrixXd(file, DS + "a", a); writeScalar<double>(file, DS + "wphi", wphi); writeScalar<double>(file, DS + "err", err); } VectorXcd CQCGL1dSubReq::readE(H5File &file, const std::string groupName){ string DS = "/" + groupName + "/"; VectorXd er = readMatrixXd(file, DS + "er"); VectorXd ei = readMatrixXd(file, DS + "ei"); VectorXcd e(er.size()); e.real() = er; e.imag() = ei; return e; } MatrixXcd CQCGL1dSubReq::readV(H5File &file, const std::string groupName){ string DS = "/" + groupName + "/"; MatrixXd vr = readMatrixXd(file, DS + "vr"); MatrixXd vi = readMatrixXd(file, DS + "vi"); MatrixXcd v(vr.rows(), vr.cols()); v.real() = vr; v.imag() = vi; return v; } void CQCGL1dSubReq::writeE(H5File &file, const std::string groupName, const VectorXcd e){ // H5File file(fileName, H5F_ACC_RDWR); checkGroup(file, groupName, true); string DS = "/" + groupName + "/"; writeMatrixXd(file, DS + "er", e.real()); writeMatrixXd(file, DS + "ei", e.imag()); } void CQCGL1dSubReq::writeV(H5File &file, const std::string groupName, const MatrixXcd v){ // H5File file(fileName, H5F_ACC_RDWR); checkGroup(file, groupName, true); string DS = "/" + groupName + "/"; writeMatrixXd(file, DS + "vr", v.real()); writeMatrixXd(file, DS + "vi", v.imag()); } void CQCGL1dSubReq::move(H5File &fin, std::string gin, H5File &fout, std::string gout, int flag){ VectorXd a; VectorXcd e; MatrixXcd v; double wphi, err; std::tie(a, wphi, err) = read(fin, gin); if (flag == 1 || flag == 2) e = readE(fin, gin); if (flag == 2) v = readV(fin, gin); write(fout, gout, a, wphi, err); if (flag == 1 || flag == 2) writeE(fout, gout, e); if (flag == 2) writeV(fout, gout, v); } //==================================================================================================== VectorXd CQCGL1dSubReq::Fx(const VectorXd &x){ assert(x.size() == Ndim + 1); double wphi = x(Ndim); VectorXd a = x.head(Ndim); // use matrix type for resizing VectorXd F(Ndim+1); F << velocityReq(a, wphi), 0; return F; } std::tuple<MatrixXd, MatrixXd, VectorXd> CQCGL1dSubReq::calJJF(const VectorXd &x){ assert(x.size() == Ndim + 1); double wphi = x(Ndim); VectorXd a0 = x.head(Ndim); MatrixXd DF(Ndim, Ndim+1); ArrayXd tx_phase = phaseTangent(a0); DF.topLeftCorner(Ndim, Ndim) = stabReq(a0, wphi); DF.col(Ndim) = tx_phase; VectorXd F = velocity(a0) + wphi*tx_phase; MatrixXd JJ = DF.transpose() * DF; MatrixXd D = JJ.diagonal().asDiagonal(); VectorXd df = DF.transpose() * F; return std::make_tuple(JJ, D, df); } std::tuple<VectorXd, double, double, int> CQCGL1dSubReq::findReq_LM(const ArrayXd &a0, const double wphi0, const double tol, const int maxit, const int innerMaxit){ VectorXd x(Ndim+1); x << a0, wphi0; auto fx = std::bind(&CQCGL1dSubReq::Fx, this, ph::_1); CQCGL1dSubReqJJF<MatrixXd> jj(this); PartialPivLU<MatrixXd> solver; VectorXd xe; std::vector<double> res; int flag; std::tie(xe, res, flag) = LM0(fx, jj, solver, x, tol, maxit, innerMaxit); if(flag != 0) fprintf(stderr, "Sub Req not converged ! \n"); VectorXd a = xe.head(Ndim); double wphi = xe(Ndim); return std::make_tuple( a, wphi, res.back(), flag ); } /** @brief find the optimal guess of wphi for a candidate req * @return [wth, wphi, err] such that velocityReq(a0, wth, wphi) minimal */ std::vector<double> CQCGL1dSubReq::optThPhi(const ArrayXd &a0){ VectorXd t = phaseTangent(a0); VectorXd v = velocity(a0); double c = t.dot(v) / t.dot(t); double err = (v - c * t).norm(); std::vector<double> x{-c, err}; return x; } #if 0 /** * @brief find req with a sequence of Bi or Gi */ void CQCGL1dSubReq::findReqParaSeq(H5File &file, int id, double step, int Ns, bool isBi){ double Bi0 = Bi; double Gi0 = Gi; ArrayXd a0; double wth0, wphi0, err0; std::tie(a0, wth0, wphi0, err0) = read(file, toStr(Bi, Gi, id)); ArrayXd a; double wth, wphi, err; int flag; int Nfail = 0; for (int i = 0; i < Ns; i++){ if (isBi) Bi += step; else Gi += step; // if exist, use it as seed, otherwise find req if ( checkGroup(file, toStr(Bi, Gi, id), false) ){ std::tie(a0, wth0, wphi0, err0) = read(file, toStr(Bi, Gi, id)); } else { fprintf(stderr, "%d %g %g \n", id, Bi, Gi); std::tie(a, wth, wphi, err, flag) = findReq_LM(a0, wth0, wphi0, 1e-10, 100, 1000); if (flag == 0){ write(file, toStr(Bi, Gi, id), a, wth, wphi, err); a0 = a; wth0 = wth; wphi0 = wphi; } else { if(++Nfail == 3) break; } } } Bi = Bi0; // restore Bi, Gi Gi = Gi0; } #endif /// @brief calculate the eigenvalues and eigenvectors of req in certain range /// gs is obtained by scanGroup() void CQCGL1dSubReq::calEVParaSeq(H5File &file, vector<vector<string>> gs, bool saveV){ double Bi0 = Bi; double Gi0 = Gi; int id; ArrayXd a0; double wth0, wphi0, err0; VectorXcd e; MatrixXcd v; for (auto entry : gs){ Bi = stod(entry[0]); Gi = stod(entry[1]); id = stoi(entry[2]); if( !checkGroup(file, toStr(Bi, Gi, id) + "/er", false) ){ fprintf(stderr, "%d %g %g \n", id, Bi, Gi); std::tie(a0, wphi0, err0) = read(file, toStr(Bi, Gi, id)); std::tie(e, v) = evReq(a0, wphi0); writeE(file, toStr(Bi, Gi, id), e); if(saveV) writeV(file, toStr(Bi, Gi, id), v.leftCols(10)); } } Bi = Bi0; // restore Bi, Gi Gi = Gi0; } <file_sep>#ifndef KSINT_H #define KSINT_H #include <fftw3.h> #include <complex> #include <tuple> #include <utility> #include <Eigen/Dense> #include <unsupported/Eigen/FFT> #include "EIDr.hpp" /*============================================================ * Class : KS integrator *============================================================*/ class KS{ public: typedef std::complex<double> dcp; ////////////////////////////////////////////////////////////////////// /* member variables */ const int N; const double d; ArrayXd K, L; ArrayXcd G; FFT<double> fft; VectorXd hs; /* time step sequnce */ VectorXd lte; /* local relative error estimation */ VectorXd Ts; /* time sequnence for adaptive method */ int cellSize = 500; /* size of cell when resize output container */ struct NL { KS *ks; int N; ArrayXXd u; NL(); NL(KS *ks, int cols); ~NL(); void operator()(ArrayXXcd &x, ArrayXXcd &dxdt, double t); }; NL nl, nl2; ArrayXXcd Yv[10], Nv[10], Yv2[10], Nv2[10]; EIDr eidr, eidr2;; //////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////// /* constructor, destructor, copy assignment */ KS(int N, double d); KS & operator=(const KS &x); ~KS(); /* ------------------------------------------------------------ */ void setScheme(std::string x); ArrayXXd intgC(const ArrayXd &a0, const double h, const double tend, const int skip_rate); std::pair<ArrayXXd, ArrayXXd> intgjC(const ArrayXd &a0, const double h, const double tend, const int skip_rate); ArrayXXd intg(const ArrayXd &a0, const double h, const double tend, const int skip_rate); std::pair<ArrayXXd, ArrayXXd> intgj(const ArrayXd &a0, const double h, const double tend, const int skip_rate); ArrayXXd C2R(const ArrayXXcd &v); ArrayXXcd R2C(const ArrayXXd &v); /* ------------------------------------------------------------ */ ArrayXd velocity(const Ref<const ArrayXd> &a0); ArrayXd velReq(const Ref<const VectorXd> &a0, const double c); MatrixXd stab(const Ref<const ArrayXd> &a0); MatrixXd stabReq(const Ref<const VectorXd> &a0, const double theta); std::pair<VectorXcd, Eigen::MatrixXcd> evEq(const Ref<const VectorXd> &a0); std::pair<VectorXcd, Eigen::MatrixXcd> evReq(const Ref<const VectorXd> &a0, const double theta); double pump(const ArrayXcd &vc); double disspation(const ArrayXcd &vc); ArrayXXd reflect(const Ref<const ArrayXXd> &aa); ArrayXXd half2whole(const Ref<const ArrayXXd> &aa); ArrayXXd rotate(const Ref<const ArrayXXd> &aa, const double th); ArrayXXd gTangent(const Ref<const ArrayXXd> &x); MatrixXd gGenerator(); std::pair<MatrixXd, VectorXd> redSO2(const Ref<const MatrixXd> &aa, const int p, const bool toY); std::pair<MatrixXd, VectorXi> fundDomain(const Ref<const MatrixXd> &aa, const int pSlice, const int pFund); std::tuple<MatrixXd, VectorXi, VectorXd> redO2f(const Ref<const MatrixXd> &aa, const int pSlice, const int pFund); MatrixXd redV(const Ref<const MatrixXd> &v, const Ref<const VectorXd> &a, const int p, const bool toY); MatrixXd veToSliceAll(const MatrixXd &eigVecs, const MatrixXd &aa, const int trunc = 0); std::pair<ArrayXXd, ArrayXXd> orbitAndFvWhole(const ArrayXd &a0, const ArrayXXd &ve, const double h, const size_t nstp, const std::string ppType ); MatrixXd veTrunc(const MatrixXd ve, const int pos, const int trunc = 0); std::pair<ArrayXXd, ArrayXXd> orbitAndFvWholeSlice(const ArrayXd &a0, const ArrayXXd &ve, const double h, const size_t nstp, const std::string ppType, const int pos ); MatrixXd calMag(const Ref<const MatrixXd> &aa); std::pair<MatrixXd, MatrixXd> toPole(const Ref<const MatrixXd> &aa); }; #endif /* KSINT_H */ <file_sep>## All numerical experiments * **EID** time-step adaptive exponential integrator <file_sep>from py_CQCGL2d import * from personalFunctions import * case = 40 if case == 10: """ test the plot function """ N = 1024 d = 30 di = 0.05 cgl = pyCQCGL2d(N, d, 4.0, 0.8, 0.01, di, 4) Ns = 15000 skip = 20 cgl.constETDPrint = 200 fileName = 'ex.h5' A0 = 3*centerRand2d(N, N, 0.2, 0.2, True) a0 = cgl.Config2Fourier(A0) # aa = cgl.intg(a0, 0.001, Ns, skip, True, fileName) c2dp = CQCGL2dPlot(d, d) # c2dp.plotOneState(cgl, fileName, 100) c2dp.savePlots(cgl, fileName, range(Ns/skip+1), 'fig3', plotType=2, onlyMovie=True, size=[12, 6]) if case == 20: """ integrate using current data """ N = 1024 d = 30 di = 0.05 cgl = pyCQCGL2d(N, d, 4.0, 0.8, 0.01, di, 4) Ns = 2000 skip = 2 cgl.constETDPrint = 100 fileName = 'ex2.h5' c2dp = CQCGL2dPlot(d, d) a0 = c2dp.load('ex.h5', 750) aa = cgl.intg(a0, 0.001, Ns, skip, True, fileName) if case == 30: """ test plotting a sequence """ N = 1024 d = 30 di = 0.05 cgl = pyCQCGL2d(N, d, 4.0, 0.8, 0.01, di, 4) fileName = 'ex2.h5' c2dp = CQCGL2dPlot(d, d) x = c2dp.loadSeq(fileName, 0, 0, range(1000)) plot1dfig(x.real) plot1dfig(x.imag) if case == 40: """ test stabReq """ N = 1024 d = 30 di = 0.05 cgl = pyCQCGL2d(N, d, 4.0, 0.8, 0.01, di, 4) fileName = 'ex2.h5' c2dp = CQCGL2dPlot(d, d) x = c2dp.load('ex.h5', 500) v = rand(cgl.Me, cgl.Ne) ax = cgl.stab(x, v) <file_sep>#include <boost/python.hpp> #include <boost/numpy.hpp> #include <Eigen/Dense> #include <cstdio> #include "ksintM1.hpp" using namespace std; using namespace Eigen; namespace bp = boost::python; namespace bn = boost::numpy; ////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////// class pyKSM1 : public KSM1 { public : pyKSM1(int N, double h, double d) : KSM1(N, h, d) {} /* wrap the integrator */ bp::tuple PYintg(bn::ndarray a0, size_t nstp, size_t np){ Map<ArrayXd> tmpa((double*)a0.get_data(), N-2); std::pair<ArrayXXd, ArrayXd> tmp = intg(tmpa, nstp, np); Py_intptr_t dims[2] = { nstp/np+1, N-2 }; bn::ndarray aa = bn::empty(2, dims, bn::dtype::get_builtin<double>()); bn::ndarray tt = bn::empty(1, dims, bn::dtype::get_builtin<double>()); memcpy((void*)aa.get_data(), (void*)(&tmp.first(0, 0)), sizeof(double) * (N-2) * (nstp/np+1) ); memcpy((void*)tt.get_data(), (void*)(&tmp.second(0)), sizeof(double) * (nstp/np+1) ); return bp::make_tuple(aa, tt); } /* wrap the second integrator */ bp::tuple PYintg2(bn::ndarray a0, double T, size_t np){ Map<ArrayXd> tmpa((double*)a0.get_data(), N-2); std::pair<ArrayXXd, ArrayXd> tmp = intg2(tmpa, T, np); int n = tmp.first.rows(); int m = tmp.first.cols(); Py_intptr_t dims[2] = { m , n }; bn::ndarray aa = bn::empty(2, dims, bn::dtype::get_builtin<double>()); bn::ndarray tt = bn::empty(1, dims, bn::dtype::get_builtin<double>()); memcpy((void*)aa.get_data(), (void*)(&tmp.first(0, 0)), sizeof(double) * n * m ); memcpy((void*)tt.get_data(), (void*)(&tmp.second(0)), sizeof(double) * m ); return bp::make_tuple(aa, tt); } }; ////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////// BOOST_PYTHON_MODULE(py_ks) { bn::initialize(); bp::class_<KSM1>("KSM1") ; bp::class_<pyKSM1, bp::bases<KSM1> >("pyKSM1", bp::init<int, double, double>()) .def_readonly("N", &pyKSM1::N) .def_readonly("d", &pyKSM1::d) .def_readonly("h", &pyKSM1::h) .def("intg", &pyKSM1::PYintg) .def("intg2", &pyKSM1::PYintg2) ; } <file_sep>#include "sparseRoutines.hpp" using namespace std; using namespace Eigen; typedef Eigen::SparseMatrix<double> SpMat; typedef Eigen::Triplet<double> Tri; namespace sparseRoutines { /* ----------- functions -------------- */ /* @brief transform a dense matrix into Triplet form, which should be used to * initialize a spase matrix subblock. * * @param[in] M row position of the subblock * @param[in] N col position of the sbublock * @return the triplet representation of the dense matrix * */ vector<Tri> triMat(const MatrixXd &A, const size_t M /* = 0 */, const size_t N /* = 0 */){ vector<Tri> tri; size_t rows = A.rows(), cols = A.cols(); tri.reserve(rows*cols); // for efficience, loop in the row wise. for(size_t j = 0; j < cols; j++) for(size_t i = 0; i < rows; i++) tri.push_back( Tri(M+i, N+j, A(i,j) )); return tri; } /* @brief transform a diagoal matrix (diagonal elements are the same) into Triplet * form * * @param[in] n size of the diagonal matrix * @param[in] x the diagonal elements * @param[in] M row position of the subblock * @param[in] N col position of the sbublock * @see triMat() */ vector<Tri> triDiag(const size_t n, const double x, const size_t M /* = 0 */, const size_t N /* = 0 */ ){ vector<Tri> tri; tri.reserve(n); for(size_t i = 0; i < n; i++) tri.push_back( Tri(M+i, N+i, x) ); return tri; } std::vector<Tri> triDiag(const VectorXd &D, const size_t M, const size_t N){ int n = D.size(); vector<Tri> tri; tri.reserve(n); for(int i = 0; i < n; i++) tri.push_back( Tri(M+i, N+1, D(i)) ); return tri; } } <file_sep>from py_ks import * from personalFunctions import * case = 10 N, L = 64, 22 eqFile = '../../data/ks22Reqx64.h5' poFile = '../../data/ks22h001t120x64EV.h5' if case == 10: """ plot the FV of ppo1 """ ks = pyKS(N, L) ksp = KSplot(ks) fv = ksp.readFV(poFile, 'ppo', 1) fvt0 = fv[0].reshape(30, N-2) name = 'ksppo1fvt0' ksp.oneConfig(fvt0[0], labs=[r'$x$', r'$v$'], axisLabelSize=25, tickSize=18, save=True, name=name+'v1r') ksp.oneConfig(fvt0[1], labs=[r'$x$', r'$v$'], axisLabelSize=25, tickSize=18, save=True, name=name+'v1i') ksp.oneConfig(fvt0[4], labs=[r'$x$', r'$v$'], axisLabelSize=25, tickSize=18, save=True, name=name+'v5') ksp.oneConfig(fvt0[9], labs=[r'$x$', r'$v$'], axisLabelSize=25, tickSize=18, save=True, name=name+'v10') ksp.oneConfig(fvt0[-1], labs=[r'$x$', r'$v$'], axisLabelSize=25, tickSize=18, save=True, name=name+'v30') <file_sep>from py_CQCGL1d import * from cglHelp import * from scipy.integrate import odeint case = 41 if case == 1: """ view the rpo I found view its color map, error, Fourier modes and symmetry reduced Fourier modes """ N = 1024 d = 30 di = 0.36 x, T, nstp, th, phi, err = cqcglReadRPOdi('../../data/cgl/rpoT2X1.h5', di, 1) h = T / nstp nstp = np.int(nstp) cgl = pyCQCGL1d(N, d, 4.0, 0.8, 0.01, di, -1) aa = cgl.intg(x, h, nstp, 1) aaHat, thAll, phiAll = cgl.orbit2slice(aa) # print the errors and plot the color map print norm(cgl.Rotate(aa[-1], th, phi) - aa[0]) plotConfigSpaceFromFourier(cgl, aa, [0, d, 0, nstp*h]) # Fourier trajectory in the full state space i1 = 0 i2 = 1 i3 = 2 fig = plt.figure(figsize=[8, 6]) ax = fig.add_subplot(111, projection='3d') ax.plot(aa[:, i1], aa[:, i2], aa[:, i3], c='r', lw=1) ax.scatter(aa[0, i1], aa[0, i2], aa[0, i3], s=50, marker='o', facecolor='b', edgecolors='none') ax.scatter(aa[-1, i1], aa[-1, i2], aa[-1, i3], s=50, marker='o', facecolor='b', edgecolors='none') ax.set_xlabel('x', fontsize=25) ax.set_ylabel('y', fontsize=25) ax.set_zlabel('z', fontsize=25) fig.tight_layout(pad=0) plt.show(block=False) # Fourier trajectory in the continous symmetry reduced space i1 = 0 i2 = 1 i3 = 2 fig = plt.figure(figsize=[8, 6]) ax = fig.add_subplot(111, projection='3d') ax.plot(aaHat[:, i1], aaHat[:, i2], aaHat[:, i3], c='r', lw=1) ax.scatter(aaHat[0, i1], aaHat[0, i2], aaHat[0, i3], s=50, marker='o', facecolor='b', edgecolors='none') ax.scatter(aaHat[-1, i1], aaHat[-1, i2], aaHat[-1, i3], s=50, marker='o', facecolor='b', edgecolors='none') ax.set_xlabel('x', fontsize=25) ax.set_ylabel('y', fontsize=25) ax.set_zlabel('z', fontsize=25) fig.tight_layout(pad=0) plt.show(block=False) # plot 4 periods M = 6 aa2 = cgl.intg(x, h, nstp*M, 1) plotConfigSpaceFromFourier(cgl, aa2, [0, d, 0, nstp*h*M]) if case == 20: """ view the rpo torus """ N = 1024 d = 30 di = 0.39 x, T, nstp, th, phi, err = cqcglReadRPOdi('../../data/cgl/rpoT2X1.h5', di, 1) h = T / nstp cgl = pyCqcgl1d(N, d, h, False, 0, 4.0, 0.8, 0.01, di, 4) aa0 = cgl.intg(x[0], nstp, 1) # Fourier trajectory in the full state space i1 = 4 i2 = 7 i3 = 2 fig = plt.figure(figsize=[8, 6]) ax = fig.add_subplot(111, projection='3d') for i in range(10): ang = i / 10.0 * 2 * np.pi aa = cgl.Rotate(aa0, ang, 0) ax.plot(aa[:, i1], aa[:, i2], aa[:, i3], c='r', lw=1) ax.scatter(aa[0, i1], aa[0, i2], aa[0, i3], s=50, marker='o', facecolor='b', edgecolors='none') ax.scatter(aa[-1, i1], aa[-1, i2], aa[-1, i3], s=50, marker='o', facecolor='k', edgecolors='none') ax.set_xlabel('x', fontsize=25) ax.set_ylabel('y', fontsize=25) ax.set_zlabel('z', fontsize=25) fig.tight_layout(pad=0) plt.show(block=False) if case == 21: """ check whether the velocity is conserved """ N = 1024 d = 30 di = 0.39 x, T, nstp, th, phi, err = cqcglReadRPOdi('../../data/cgl/rpoT2X1.h5', di, 1) h = T / nstp cgl = pyCqcgl1d(N, d, h, True, 1, 4.0, 0.8, 0.01, di, 4) v0 = cgl.velocity(x[0]) av = cgl.intgv(x[0], v0, nstp) v1 = av[1] print norm(v1) if case == 40: """ use L = 50 to obtain the guess initial conditon for rpo """ N = 1024 d = 50 Bi = 0.8 Gi = -3.6 rpo = CQCGLrpo() x, T, nstp, th, phi, err = rpo.readRpodi('../../data/cgl/rpoT2X1.h5', 0.36, 1) x = x * 0.1**0.5 cgl = pyCQCGL1d(N, d, -0.1, 0.125, 0.5, 1, Bi, -0.1, Gi, -1) aa = cgl.intg(x, 1e-3, 40000, 50) aa = cgl.intg(aa[-1], 1e-3, 10000, 10) plotConfigSpaceFromFourier(cgl, aa, [0, d, 0, 10]) if case == 41: """ use L = 50 to view the rpo """ N, d = 1024, 50 Bi, Gi = 2, -5.6 cgl = pyCQCGL1d(N, d, -0.1, 0.125, 0.5, 1, Bi, -0.1, Gi, -1) rpo = CQCGLrpo(cgl) cp = CQCGLplot(cgl) x, T, nstp, th, phi, err, e, v = rpo.read('../../data/cgl/rpoBiGiEV.h5', rpo.toStr(Bi, Gi, 1), flag=2) a0 = x[:cgl.Ndim] print e[:10] a0 += 0.1*norm(a0)*v[0] numT = 4 for i in range(1): aa = cgl.intg(a0, T/nstp, numT * T, 10) a0 = aa[-1] cp.config(aa, [0, d, 0, T*numT]) if case == 411: """ use L = 50 to view the rpo and the difference plot """ N = 1024 d = 50 Bi, Gi = 4.8, -4.5 cgl = pyCQCGL1d(N, d, -0.1, 0.125, 0.5, 1, Bi, -0.1, Gi, -1) rpo = CQCGLrpo(cgl) cp = CQCGLplot(cgl) x, T, nstp, th, phi, err, e, v = rpo.readRpoBiGi('../../data/cgl/rpoBiGiEV.h5', Bi, Gi, 1, flag=2) a0 = x[:cgl.Ndim] print e[:10] aa0 = cgl.intg(a0, T/nstp, nstp, 10)[:-1] a0 += 0.1*norm(a0)*v[0] numT = 7 skipRate = 10 aaBase = aa0 for i in range(1, numT): aaBase = np.vstack((aaBase, cgl.Rotate(aa0, -i*th, -i*phi))) for i in range(1): aa = cgl.intg(a0, T/nstp, numT*nstp, skipRate) a0 = aa[-1] cp.config(aa, [0, d, 0, T*numT]) dif = aa[:-1] - aaBase cellSize = nstp / skipRate cp.config(dif[0*cellSize:6*cellSize], [0, d, 0*T, 6*T]) if case == 42: """ L = 50 check the po is not req """ N = 1024 d = 50 fileName = '../../data/cgl/rpoBiGi2.h5' angs = np.zeros([39, 55]) for i in range(39): Bi = 1.9 + i * 0.1 for j in range(55): Gi = -5.6 + 0.1*j cgl = pyCQCGL1d(N, d, -0.1, 0.125, 0.5, 1, Bi, -0.1, Gi, 0) rpo = CQCGLrpo(cgl) if rpo.checkExist(fileName, rpo.toStr(Bi, Gi, 1)): x, T, nstp, th, phi, err = rpo.readRpoBiGi(fileName, Bi, Gi, 1) a0 = x[:cgl.Ndim] v0 = cgl.velocity(a0) t1 = cgl.transTangent(a0) t2 = cgl.phaseTangent(a0) ang = pAngle(v0, np.vstack((t1, t2)).T) angs[i, j] = ang if ang < 1e-3: print Bi, Gi, ang if case == 43: """ L = 50 plot the stability table of the rpos """ N = 1024 d = 50 fileName = '../../data/cgl/rpoBiGiEV.h5' cs = {0: 'g'}#, 10: 'm', 2: 'c', 4: 'r', 6: 'b', 8: 'y'}#, 56: 'r', 14: 'grey'} ms = {0: 's'}#, 10: '^', 2: '+', 4: 'o', 6: 'D', 8: 'v'}#, 56: '4', 14: 'v'} es = {} e1 = {} unconverge = {} Ts = np.zeros((39, 55)) ns = set() fig, ax = pl2d(size=[8, 6], labs=[r'$G_i$', r'$B_i$'], axisLabelSize=25, tickSize=20, xlim=[-5.7, -3.95], ylim=[1.8, 6]) for i in range(39): Bi = 1.9 + i*0.1 for j in range(55): Gi = -5.6 + 0.1*j rpo = CQCGLrpo() if rpo.checkExist(fileName, rpo.toStr(Bi, Gi, 1) + '/er'): x, T, nstp, th, phi, err, e, v = rpo.readRpoBiGi(fileName, Bi, Gi, 1, flag=2) es[(Bi, Gi)] = e m, ep, accu = numStab(e, nmarg=3, tol=1e-4, flag=1) if accu == False: unconverge[(Bi, Gi)] = 1 print Bi, Gi, e[m:m+3] e1[(Bi, Gi)] = ep[0] Ts[i, j] = T ns.add(m) # print index, Bi, Gi, m ax.scatter(Gi, Bi, s=60, edgecolors='none', marker=ms.get(m, 'o'), c=cs.get(m, 'r')) #ax.xaxis.set_minor_locator(AutoMinorLocator(10)) #ax.yaxis.set_minor_locator(AutoMinorLocator(10)) #ax.grid(which='major', linewidth=2) #ax.grid(which='minor', linewidth=1) ax2d(fig, ax) plotIm(Ts, [-5.6, 0, -4, 6], size=[8, 6], labs=[r'$G_i$', r'$B_i$']) fig, ax = pl2d(size=[8, 6], labs=[r'$G_i$', r'$B_i$'], axisLabelSize=20, tickSize=15, xlim=[-5.7, -3.95], ylim=[1.8, 6]) keys = unconverge.keys() for i in keys: ax.scatter(i[1], i[0], s=60, edgecolors='none', marker='o', c='k') #ax.xaxis.set_minor_locator(AutoMinorLocator(10)) #ax.yaxis.set_minor_locator(AutoMinorLocator(10)) #ax.grid(which='major', linewidth=2) #ax.grid(which='minor', linewidth=1) ax2d(fig, ax) if case == 44: """ L = 50 Plot the rpo existence in the Bi-Gi plane """ N = 1024 d = 50 fileName = '../../data/cgl/rpoBiGi2.h5' fig, ax = pl2d(size=[8, 6], labs=[r'$G_i$', r'$B_i$'], axisLabelSize=25, xlim=[-5.8, -3.5], ylim=[1.8, 6]) for i in range(39): Bi = 1.9 + i*0.1 for j in range(55): Gi = -5.6 + 0.1*j rpo = CQCGLrpo() if rpo.checkExist(fileName, rpo.toStr(Bi, Gi, 1)): ax.scatter(Gi, Bi, s=15, edgecolors='none', marker='o', c='r') ax.xaxis.set_minor_locator(AutoMinorLocator(10)) ax.yaxis.set_minor_locator(AutoMinorLocator(10)) ax.grid(which='major', linewidth=2) ax.grid(which='minor', linewidth=1) ax2d(fig, ax) if case == 45: """ use L = 50 to view the rpo """ N, d = 1024, 50 Bi, Gi = 1.9, -5.6 cgl = pyCQCGL1d(N, d, -0.1, 0.125, 0.5, 1, Bi, -0.1, Gi, -1) rpo = CQCGLrpo() cp = CQCGLplot(cgl) x, T, nstp, th, phi, err = rpo.readRpoBiGi('../../data/cgl/rpoBiGi2.h5', Bi, Gi, 1, flag=0) a0 = x[:cgl.Ndim] for i in range(2): aa = cgl.intg(a0, T/nstp, 15*nstp, 10) a0 = aa[-1] cp.config(aa, [0, d, 0, 2*T]) if case == 46: """ use L = 50 to view the rpo int the symmetry reduced state space """ N = 1024 d = 50 Bi = 4.8 Gi = -4.5 sysFlag = 1 cgl = pyCQCGL1d(N, d, -0.1, 0.125, 0.5, 1, Bi, -0.1, Gi, -1) rpo = CQCGLrpo(cgl) cp = CQCGLplot(cgl) x, T, nstp, th, phi, err, e, v = rpo.readRpoBiGi('../../data/cgl/rpoBiGiEV.h5', Bi, Gi, 1, flag=2) a0 = x[:cgl.Ndim] po = cgl.intg(a0, T/nstp, nstp, 10) poH = cgl.orbit2slice(po, sysFlag)[0] aE = a0 + 0.001 * norm(a0) * v[0]; aa = cgl.intg(aE, T/nstp, 12*nstp, 10) cp.config(aa, [0, d, 0, 12*T]) aaH, ths, phis = cgl.orbit2slice(aa, sysFlag) cp. config(aaH, [0, d, 0, 12*T]) # req = CQCGLreq(cgl) # reqe, reqaH, reqvH = req.getAxes('../../data/cgl/reqBiGiEV.h5', Bi, Gi, 1, sysFlag) # e1, e2, e3 = orthAxes(reqvH[0].real, reqvH[1].real, reqvH[2].real) # bases = np.vstack((e1, e2, e3)) # poHP, aaHP = poH.dot(bases.T), aaH.dot(bases.T) vrH = cgl.ve2slice(v.real.copy(), a0, sysFlag) viH = cgl.ve2slice(v.imag.copy(), a0, sysFlag) e1, e2, e3 = orthAxes(vrH[0], viH[0], vrH[1]) bases = np.vstack((e1, e2, e3)) poHP, aaHP = poH.dot(bases.T), aaH.dot(bases.T) fig, ax = pl3d(size=[8, 6]) ax.plot(poH[:, -1], poH[:, 4], poH[:, 5], c='r', lw=2) ax.plot(aaH[:, -1], aaH[:, 4], aaH[:, 5], c='b', lw=1, alpha=0.7) #ax.plot(poHP[:, 0], poHP[:, 1], poHP[:, 2], c='r', lw=2) #ax.plot(aaHP[:, 0], aaHP[:, 1], aaHP[:, 2], c='b', lw=1) ax3d(fig, ax) if case == 47: """ L = 50 find all moving rpo """ N = 1024 d = 50 fileName = '../../data/cgl/rpoBiGi2.h5' mv = {} nmv = {} for i in range(39): Bi = 1.9 + i * 0.1 for j in range(55): Gi = -5.6 + 0.1*j rpo = CQCGLrpo() if rpo.checkExist(fileName, rpo.toStr(Bi, Gi, 1)): x, T, nstp, th, phi, err = rpo.readRpoBiGi(fileName, Bi, Gi, 1) if abs(th) > 1e-4: mv[(Bi, Gi)] = th else : nmv[(Bi, Gi)] = th fig, ax = pl2d(size=[8, 6], labs=[r'$G_i$', r'$B_i$'], axisLabelSize=20, tickSize=15, xlim=[-5.7, -3.95], ylim=[1.8, 6]) mvkeys = mv.keys() for i in mvkeys: ax.scatter(i[1], i[0], s=60, edgecolors='none', marker='o', c='r') nmvkeys = nmv.keys() for i in nmvkeys: ax.scatter(i[1], i[0], s=60, edgecolors='none', marker='s', c='g') ax2d(fig, ax) if case == 50: """ plot all the rpos I have """ N = 1024 d = 30 dis, rpos = cqcglReadRPOAll('../../data/cgl/rpoT2X1.h5', 1) for i in range(len(rpos)): x, T, nstp, th, phi, err = rpos[i] di = dis[i] h = T / nstp cgl = pyCqcgl1d(N, d, h, False, 0, 4.0, 0.8, 0.01, di, 4) M = 4 aa = cgl.intg(x[0], nstp*M, 1) plotConfigSpaceFromFourier(cgl, aa, [0, d, 0, nstp*h*M], save=True, name='cqcglHopfCycle' + str(di) + '_4T.eps') if case == 60: """ test the correctness of the Floquet exponents/vectors obtained from the Krylov-Schur algorithm """ N = 1024 d = 30 di = 0.36 x, T, nstp, th, phi, err, es, vs = cqcglReadRPOEVdi( '../../data/cgl/rpoT2X1_v2.h5', di, 1) h = T / nstp cgl = pyCqcgl1d(N, d, h, False, 0, 4.0, 0.8, 0.01, di, 4) U = vs[0:3] # angle between velocity and marginal subspace v0 = cgl.velocity(x) ang1 = pAngle(v0, U.T) # angle between group tangent and marginal subspace tx_tau = cgl.transTangent(x) ang2 = pAngle(tx_tau, U.T) tx_rho = cgl.phaseTangent(x) ang3 = pAngle(tx_rho, U.T) print es print ang1, ang2, ang3 if case == 61: """ Test whether the Krylov-Schur algorithm produces the correct number of marginal exponents. This is very import indicator for it to resolve degenercy. """ for di in np.arange(0.36, 0.4211, 0.001).tolist() + np.arange(0.4211, 0.42201, 0.0001).tolist() + [0.4225, 0.4226]: x, T, nstp, th, phi, err, es, vs = cqcglReadRPOEVdi( '../../data/cgl/rpoT2X1EV30.h5', di, 1) print di, es[0][:4] if case == 70: """ move rpo with FE/FV """ inFile = '../../data/cgl/rpoT2X1_v3.h5' outFile = '../../data/cgl/rpoT2X1EV30.h5' # for di in np.arange(0.36, 0.411, 0.001).tolist() + np.arange(0.414, 0.418, 0.001).tolist() + [0.4225, 0.4226]: for di in np.arange(0.361, 0.4191, 0.002).tolist(): disp(di) cqcglMoveRPOEVdi(inFile, outFile, di, 1) if case == 80: """ plot the largest non-marginal Floquet exponent and periods of all RPO founded. """ dis, xx = cqcglReadRPOAll('../../data/cgl/rpoT2X1EV30.h5', 1, True) fe = [] T = [] for i in range(len(dis)): e = xx[i][6][0] ep = removeMarginal(e, 3) fe.append(ep) T.append(xx[i][1]) e1 = [] e2 = [] for i in range(len(dis)): e1.append(fe[i][0]) e2.append(fe[i][1]) # plot scale = 1.3 fig = plt.figure(figsize=[6/scale, 4/scale]) ax = fig.add_subplot(111) ax.plot(dis, e1, c='b', lw=1, ls='-', marker='o', ms=5, mfc='r', mec='none') ax.plot(dis, np.zeros(len(dis)), c='g', ls='--', lw=2) ax.set_xlabel(r'$d_i$', fontsize=20) ax.set_ylabel(r'$\mu_1$', fontsize=20) fig.tight_layout(pad=0) plt.show(block=False) scale = 1.3 fig = plt.figure(figsize=[6/scale, 4/scale]) ax = fig.add_subplot(111) ax.plot(dis, T, c='b', lw=1, ls='-', marker='o', ms=5, mfc='r', mec='none') ax.set_xlabel(r'$d_i$', fontsize=20) ax.set_ylabel(r'$T_p$', fontsize=20) fig.tight_layout(pad=0) plt.show(block=False) if case == 81: """ For the Hopf bifurcation, we can actually estimate the parameters by experimental data. Here, we plot 1/T and the leading stable expoent of rpo and unstable expoent of req """ dic = 0.36 dis, xx = cqcglReadRPOAll('../../data/cgl/rpoT2X1EV30.h5', 1, True) T = [] e1 = [] for i in range(len(dis)): e = xx[i][6][0] ep = removeMarginal(e, 3) e1.append(ep[0]) T.append(xx[i][1]) ix = [i for i in range(len(dis)) if dis[i] <= dic+0.01 and dis[i] >= dic] dis2, xx2 = cqcglReadReqAll('../../data/cgl/reqDi.h5', 1, True) e1p = [] for i in range(len(dis2)): e = xx2[i][4] ep = removeMarginal(e, 2) e1p.append(ep[0]) ix2 = [i for i in range(len(dis2)) if dis2[i] <= dic+0.01 and dis2[i] >= dic] # plot scale = 1.3 fig = plt.figure(figsize=[6/scale, 4/scale]) ax = fig.add_subplot(111) ax.scatter(np.array(dis)[ix] - dic, -np.array(e1)[ix]/2, s=25, marker='o', facecolor='r', edgecolor='none') ax.scatter(np.array(dis2)[ix2] - dic, np.array(e1p)[ix2], s=25, marker='s', facecolor='b', edgecolor='none') # ax.plot(dis, np.zeros(len(dis)), c='g', ls='--', lw=2) ax.set_xlabel(r'$d_i - d_{ic}$', fontsize=20) # ax.set_ylabel(r'$\mu_1$', fontsize=20) ax.set_xlim([-0.001, 0.011]) ax.set_ylim([0, 0.1]) fig.tight_layout(pad=0) plt.show(block=False) scale = 1.3 fig = plt.figure(figsize=[6/scale, 4/scale]) ax = fig.add_subplot(111) ax.scatter(np.array(dis)[ix] - dic, 1 / np.array(T)[ix], s=25, marker='o', facecolor='r', edgecolor='none') ax.set_xlim([-0.001, 0.011]) ax.set_xlabel(r'$d_i - d_{ic}$', fontsize=20) ax.set_ylabel(r'$1/T_p$', fontsize=20) fig.tight_layout(pad=0) plt.show(block=False) if case == 90: """ calculate the distance of rpo to the zero state because we guess the reason that rpo does not exit after a certain di is that it goes close to zero state which is contracting. """ N = 1024 d = 30 dis = np.arange(0.36, 0.421, 0.002).tolist() + np.arange(0.421, 0.42201, 0.0001).tolist() + [0.4225, 0.4226] minNors = [] for di in dis: print di x, T, nstp, th, phi, err = cqcglReadRPOdi( '../../data/cgl/rpoT2X1.h5', di, 1) h = T / nstp nstp = np.int(nstp) cgl = pyCqcgl1d(N, d, h, True, 0, 4.0, 0.8, 0.01, di, 4) aa = cgl.intg(x, nstp, 1) aaHat, th2, phi2 = cgl.orbit2slice(aa) nors = [] for i in range(aaHat.shape[0]): nor = norm(aaHat[i]) nors.append(nor) minNors.append(min(nors)) scale = 1.3 fig = plt.figure(figsize=[6/scale, 4/scale]) ax = fig.add_subplot(111) ax.plot(dis, minNors, c='b', lw=1, ls='-', marker='o', ms=5, mfc='r', mec='none') ax.set_xlabel(r'$d_i$', fontsize=20) ax.set_ylabel(r'$\min|A|$', fontsize=20) fig.tight_layout(pad=0) plt.show(block=False) if case == 100: """ view the unstable manifold for some unstable Hopf cycles """ N = 1024 d = 30 di = 0.4226 a0, wth0, wphi0, err = cqcglReadReqdi('../../data/cgl/reqDi.h5', di, 1) cgl = pyCqcgl1d(N, d, 0.0002, True, 0, 4.0, 0.8, 0.01, di, 4) eigvalues, eigvectors = eigReq(cgl, a0, wth0, wphi0) eigvectors = Tcopy(realve(eigvectors)) a0Hat = cgl.orbit2slice(a0)[0] veHat = cgl.ve2slice(eigvectors, a0) x, T, nstp, th, phi, err, e, v = cqcglReadRPOEVdi( '../../data/cgl/rpoT2X1EV31.h5', di, 1) h = T / nstp nstp = np.int(nstp) cgl = pyCqcgl1d(N, d, h, True, 0, 4.0, 0.8, 0.01, di, 4) aa = cgl.intg(x, nstp, 1) aaHat, th, phi = cgl.orbit2slice(aa) aaHat -= a0Hat h3 = 0.0005 cgl3 = pyCqcgl1d(N, d, h3, False, 0, 4.0, 0.8, 0.01, di, 4) a0Erg = x + v[0] * 1e-3 nstp = 70000 aaErg = cgl3.intg(a0Erg, 10000, 10000) a0Erg = aaErg[-1] aaErg = cgl3.intg(a0Erg, nstp, 2) aaErgHat, th, th = cgl3.orbit2slice(aaErg) aaErgHat -= a0Hat # e1, e2 = orthAxes2(veHat[0], veHat[1]) e1, e2, e3 = orthAxes(veHat[0], veHat[1], veHat[6]) aaHatProj = np.dot(aaHat, np.vstack((e1, e2, e3)).T) aaErgHatProj = np.dot(aaErgHat, np.vstack((e1, e2, e3)).T) OProj = np.dot(-a0Hat, np.vstack((e1, e2, e3)).T) fig = plt.figure(figsize=[6, 4]) ax = fig.add_subplot(111, projection='3d') ax.plot(aaHatProj[:, 0], aaHatProj[:, 1], aaHatProj[:, 2], c='r', lw=2) ax.plot(aaErgHatProj[:, 0], aaErgHatProj[:, 1], aaErgHatProj[:, 2], c='g', lw=1, alpha=0.4) ax.scatter([0], [0], [0], s=80, marker='o', c='b', edgecolors='none') ax.scatter(OProj[0], OProj[1], OProj[2], s=60, marker='o', c='c', edgecolors='none') ax.set_xlabel(r'$e_1$', fontsize=25) ax.set_ylabel(r'$e_2$', fontsize=25) ax.set_zlabel(r'$e_3$', fontsize=25) fig.tight_layout(pad=0) plt.show(block=False) # plotConfigSurfaceFourier(cgl, aa1, [0, d, 0, T1]) if case == 110: """ view the not converged rpo """ N = 1024 d = 30 di = 0.04 x, T, nstp, th, phi, err = cqcglReadRPO('rpo2.h5', '2') M = x.shape[0] h = T / nstp / M cgl = pyCqcgl1d(N, d, h, True, 0, 4.0, 0.8, 0.01, di, 4) a0, wth0, wphi0, err = cqcglReadReqdi('../../data/cgl/reqDi.h5', di, 1) es, ev = eigReq(cgl, a0, wth0, wphi0) ev = Tcopy(realve(ev)) a0H = cgl.orbit2slice(a0)[0] veH = cgl.ve2slice(ev, a0) nsp = 20 aas = np.empty([0, cgl.Ndim]) aaHs = [] for i in range(M): aa = cgl.intg(x[i], nstp, nsp) aaH = cgl.orbit2slice(aa)[0] aas = np.vstack((aas, aa)) aaHs.append(aaH) plotConfigSpaceFromFourier(cgl, aas, [0, d, 0, T]) e1, e2, e3 = orthAxes(veH[0], veH[1], veH[10]) bases = np.vstack((e1, e2, e3)) aaHPs = [] for i in range(M): aaHP = np.dot(aaHs[i]-a0H, bases.T) aaHPs.append(aaHP) fig = plt.figure(figsize=[6, 4]) ax = fig.add_subplot(111, projection='3d') for i in range(M): ax.plot(aaHPs[i][:, 0], aaHPs[i][:, 1], aaHPs[i][:, 2], c='g', lw=1) if i == 0: c = 'r' elif i == M-1: c = 'k' else: c = 'b' # ax.scatter(aaHPs[i][0, 0], aaHPs[i][0, 1], aaHPs[i][0, 2], # s=50, marker='o', c=c, edgecolors='none') ax.set_xlabel(r'$e_1$', fontsize=25) ax.set_ylabel(r'$e_2$', fontsize=25) ax.set_zlabel(r'$e_3$', fontsize=25) fig.tight_layout(pad=0) plt.show(block=False) for i in range(M-1): tmp = ax.scatter(aaHPs[i][-1, 0], aaHPs[i][-1, 1], aaHPs[i][-1, 2], s=50, marker='o', c='k', edgecolors='none') tmp2 = ax.scatter(aaHPs[i+1][0, 0], aaHPs[i+1][0, 1], aaHPs[i+1][0, 2], s=50, marker='o', c='r', edgecolors='none') t = raw_input("input: ") tmp.remove() tmp2.remove() if case == 120: """ view the not converged rpo the full multistep method """ N = 512 d = 30 di = 0.04 x, T, nstp, th, phi, err = cqcglReadRPO('rpo4.h5', '3') M = x.shape[0] Ts = x[:, -3] ths = x[:, -2] phis = x[:, -1] x = x[:, :-3] h = T / nstp / M cgl = pyCqcgl1d(N, d, h, True, 0, 4.0, 0.8, 0.01, di, 4) nsp = 2 aas = np.empty([0, cgl.Ndim]) aas2 = [] aaHs = [] for i in range(M): newh = Ts[i] / nstp cgl.changeh(newh) aa = cgl.intg(x[i], nstp, nsp) aaH = cgl.orbit2slice(aa)[0] aas = np.vstack((aas, aa)) aas2.append(aa) aaHs.append(aaH) ers = np.zeros(M) ers2 = np.zeros(M) for i in range(M): j = (i+1) % M ers[i] = norm(aaHs[i][-1] - aaHs[j][0]) ers2[i] = norm(cgl.Rotate(aas2[i][-1], ths[i], phis[i]) - aas2[j][0]) plotConfigSpaceFromFourier(cgl, aas, [0, d, 0, T]) fig = plt.figure(figsize=[6, 4]) ax = fig.add_subplot(111, projection='3d') for i in range(M): ax.plot(aaHs[i][:, 0], aaHs[i][:, 1], aaHs[i][:, 2], c='g', lw=1) if i == 0: c = 'r' elif i == M-1: c = 'k' else: c = 'b' # ax.scatter(aaHPs[i][0, 0], aaHPs[i][0, 1], aaHPs[i][0, 2], # s=50, marker='o', c=c, edgecolors='none') ax.set_xlabel(r'$e_1$', fontsize=25) ax.set_ylabel(r'$e_2$', fontsize=25) ax.set_zlabel(r'$e_3$', fontsize=25) fig.tight_layout(pad=0) plt.show(block=False) for i in range(M-1): tmp = ax.scatter(aaHPs[i][-1, 0], aaHPs[i][-1, 1], aaHPs[i][-1, 2], s=50, marker='o', c='k', edgecolors='none') tmp2 = ax.scatter(aaHPs[i+1][0, 0], aaHPs[i+1][0, 1], aaHPs[i+1][0, 2], s=50, marker='o', c='r', edgecolors='none') t = raw_input("input: ") tmp.remove() tmp2.remove() if case == 130: """ use odeint to integrate in the slice directly """ N = 512 d = 30 di = 0.04 x, T, nstp, th, phi, err = cqcglReadRPO('rpo4.h5', '3') M = x.shape[0] Ts = x[:, -3] ths = x[:, -2] phis = x[:, -1] x = x[:, :-3] h = T / nstp / M cgl = pyCqcgl1d(N, d, h, True, 0, 4.0, 0.8, 0.01, di, 4) nsp = 2 aas = np.empty([0, cgl.Ndim]) aas2 = [] aaHs = [] for i in range(M): newh = Ts[i] / nstp cgl.changeh(newh) aa = cgl.intg(x[i], nstp, nsp) aaH = cgl.orbit2slice(aa)[0] aas = np.vstack((aas, aa)) aas2.append(aa) aaHs.append(aaH) def vel(x, t): return cgl.velocity(x) pH = np.empty([0, cgl.Ndim]) pHs = [] for k in range(M): x0H = aaHs[k][0] xH, infodict = odeint(vel, x0H, np.linspace(0, Ts[k], nstp), full_output=True) print np.min(infodict['hu']), np.max(infodict['hu']) pH = np.vstack((pH, xH)) pHs.append(xH) if case == 140: cgl.changeh(cgl.h/10) J = cgl.intgj(x[0], 10, 10, 10)[1].T J2 = np.eye(cgl.Ndim) + cgl.stab(x[0]).T * cgl.h * 10 print np.max(J), np.max(J2), np.min(J), np.min(J2) print J[:3, :3] print J2[:3, :3] def velJ(xj, t): x = xj[:cgl.Ndim] J = xj[cgl.Ndim:].reshape(cgl.Ndim, cgl.Ndim) v = cgl.velocity(x) A = cgl.stab(x).T AJ = A.dot(J) return np.concatenate((v, AJ.ravel())) def calJ(x, n): j = np.eye(cgl.Ndim) xj = np.concatenate((x, j.ravel())) y = odeint(velJ, xj, np.linspace(0, cgl.h*n, n+1)) return y[:, :cgl.Ndim].copy(), y[-1, cgl.Ndim:].copy().reshape((cgl.Ndim, cgl.Ndim)) def calJ2(x, n): y = odeint(velJ, x, np.linspace(0, cgl.h*n, n+1)) return y[-1] def calJ3(x, n): j = np.eye(cgl.Ndim) xj = np.concatenate((x, j.ravel())) y = odeint(velJ, xj, np.linspace(0, cgl.h*n, n+1)) return y[-1] aa, J = cgl.intgj(x[0], 10, 10, 10) aa2, J2 = calJ(x[0], 10) cgl.changeh(cgl.h / 10) aa3, J3 = cgl.intgj(x[0], 100, 100, 100) aa4, J4 = calJ(x[0], 100) print norm(aa3[-1] - aa[-1]), norm(aa4[-1] - aa2[-1]) print np.max(np.max(np.abs(J3-J))), np.max(np.max(np.abs(J4-J2))) y = calJ3(x[0], 10) for i in range(2): print i y = calJ2(y, 100) <file_sep>/* compile command: * mex CXXFLAGS='-std=c++0x -fPIC -O3' KSvelocity.cc ../ksint.cc -I../../../include -I$XDAPPS/eigen/include/eigen3 -lfftw3 * * usage : * >> v = ksVelocity(aa(:,i) ); * */ #include "ksint.hpp" #include "mex.h" #include <cmath> #include <cstring> #include <cassert> #include <Eigen/Dense> using namespace Eigen; static MatrixXd KSvelocity(double *x, const int N){ KS ks(N+2); Map<VectorXd> x2(x, N); return ks.velocity(x2); } void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[]){ // get the pointer and the size of input double *x = mxGetPr(prhs[0]); mwSize N = mxGetM(prhs[0]); mwSize M = mxGetN(prhs[0]); assert(M2 = 1); plhs[0] = mxCreateDoubleMatrix(N, 1, mxREAL); MatrixXd v = KSvelocity(x, N); memcpy(mxGetPr(plhs[0]), &v(0), N*M*sizeof(double)); } <file_sep>/* to compile: * g++ test_ksint.cc -std=c++11 -lksint -ldenseRoutines -lfftw3 -I ../../include/ -L ../../lib/ -I$EIGEN -O3 -DEIGEN_FFTW_DEFAULT && ./a.out */ #include "ksint.hpp" #include "denseRoutines.hpp" #include "myH5.hpp" #include <Eigen/Dense> #include <iostream> using namespace std; using namespace Eigen; using namespace MyH5; using namespace denseRoutines; #define N10 int main(){ #ifdef N10 //====================================================================== // int N = 64; double L = 22; ArrayXd a0 = ArrayXd::Random(N-2) * 0.1; KS ks(N, L); ArrayXXd aa = ks.intgC(a0, 0.01, 20, 10); #endif #if 0 case 10 :{ /* find eq and req for N = 64 from N = 32 */ std::string file = "../../data/ksReqx32.h5"; std::string outFile = "tmp.h5"; const int N = 64; KS ks(N, 0.01, 22); for (int i = 0; i < 2; i++){ int Id = i+1; auto tmp = KSreadReq(file, Id); VectorXd x0(VectorXd::Zero(N-1)); x0.head(30) = tmp.first; x0(N-2) = tmp.second * 2*M_PI/22; auto result = ks.findReq(x0, 1e-13, 100, 20); VectorXd &a0 = std::get<0>(result); double omega = std::get<1>(result); double err = std::get<2>(result); KSwriteReq(outFile, Id, a0, omega, err); } for (int i = 0; i < 3; i++){ int Id = i + 1; auto a0 = KSreadEq(file, Id); VectorXd x0(VectorXd::Zero(N-2)); x0.head(30) = a0; auto result = ks.findEq(x0, 1e-13, 100, 20); VectorXd &a = std::get<0>(result); double err = std::get<1>(result); KSwriteEq(outFile, Id, a, err); } break; } case 11 : { /* calculate the stability exponents of eq */ std::string file = "../../data/ks22Reqx64.h5"; auto eq = KSreadEq(file, 1); VectorXd a0 = eq.first; double err = eq.second; const int N = 64; KS ks(N, 0.01, 22); auto ev = ks.stabEig(a0); cout << ev.first << endl; break; } case 12 : { /* calculate the stability exponents of req */ std::string file = "../../data/ks22Reqx64.h5"; auto req = KSreadReq(file, 1); VectorXd &a0 = std::get<0>(req); double w = std::get<1>(req); double err = std::get<2>(req); const int N = 64; KS ks(N, 0.01, 22); auto ev = ks.stabReqEig(a0, w); cout << ev. first << endl; break; } case 13: { /* write stability exponents */ std::string file = "../../data/ks22Reqx64.h5"; std::string outFile = "ks22Reqx64.h5"; const int N = 64; KS ks(N, 0.01, 22); for(int i = 0; i < 3 ; i++){ int Id = i + 1; auto eq = KSreadEq(file, Id); VectorXd &a0 = eq.first; auto ev = ks.stabEig(a0); KSwriteEqE(outFile, Id, ev.first); } for(int i = 0; i < 2; i++){ int Id = i + 1; auto req = KSreadReq(file, Id); VectorXd &a0 = std::get<0>(req); double w = std::get<1>(req); auto ev = ks.stabReqEig(a0, w); KSwriteReqE(outFile, Id, ev.first); } break; } case 14: { std::string file = "../../data/ks22h001t120x64.h5"; std::string poType = "rpo"; MatrixXd a0; double T, r, s; int nstp; std::tie(a0, T, nstp, r, s) = KSreadRPO(file, poType, 1); KS ks(64, 22); auto tmp = ks.aintgj(a0, 0.01, T, 1); savetxt("a.dat", ks.hs); break; } default : { cout << "please indicate the correct index." << endl; } } #endif return 0; } <file_sep>/* to comiple: * (Note : libksdim.a is static library, so the following order is important) * * h5c++ test_ksFEFV.cc -std=c++11 -O3 -march=corei7 -msse4 -msse2 -I$XDAPPS/eigen/include/eigen3 -I$RESH/include -L$RESH/lib -lksFEFV -lksint -lmyfft -lfftw3 -literMethod -ldenseRoutines -lmyH5 -lped * */ #include <iostream> #include <Eigen/Dense> #include <string> #include <fstream> #include <algorithm> #include "ksFEFV.hpp" #include "myH5.hpp" #include "denseRoutines.hpp" using namespace std; using namespace Eigen; using namespace MyH5; using namespace denseRoutines; int main(){ cout.precision(16); switch (5) { case 1: { /* calculate FE, FV for a single orbit */ const double L = 22; const int nqr = 5; // spacing const int MaxN = 2000; // maximal iteration number for PED const double tol = 1e-12; // torlearance for PED const int trunc = 30; // number of vectors const size_t ppId = 33; const string inputfileName = "../../data/ks22h001t120x64EV.h5"; const string outputfileName = "ex.h5"; const string ppType = "rpo"; // KScalWriteFEFVInit(inputfileName, outputfileName, ppType, ppId, L, MaxN, tol, nqr, trunc); auto tmp = KScalFEFV(inputfileName, ppType, ppId, L, MaxN, tol, nqr, trunc); cout << tmp.first << endl; break; } case 5: { const double L = 22; const int nqr = 5; // spacing const int MaxN = 2000; // maximal iteration number for PED const double tol = 1e-12; // torlearance for PED const int trunc = 30; // number of vectors const size_t ppId = 147; const string inputfileName = "../../data/ks22h001t120x64EV.h5"; const string outputfileName = "ex.h5"; const string ppType = "ppo"; MatrixXd R = KSgetR(inputfileName, ppType, ppId, L, MaxN, tol, nqr); int rs = R.rows(), cs = R.cols() / rs; cout << rs << ' ' << cs << endl; VectorXd maxElements(cs/10); for(int k = 0; k < cs/10; k++){ MatrixXd r(MatrixXd::Identity(10, 10)); for(int i = 0; i < cs; i++){ int index = (2 * cs - 1 - i - k*10) % cs; r = R.middleCols(index*rs, rs).topLeftCorner(10, 10) * r; } r -= r.diagonal().asDiagonal(); // get rid of diagonal maxElements(k) = r.array().abs().maxCoeff(); // cout << maxElements(k) << endl; } savetxt("maxElement.dat", maxElements); break; } case 20: { /* calculate FE, FV for a set of orbits */ const double L = 22; const int nqr = 5; // spacing const int MaxN = 500; // maximal iteration number for PED const double tol = 1e-12; // torlearance for PED const int trunc = 30; // number of vectors const string inName = "../../data/ks22h001t120x64EV.h5"; const string outName = "ex.h5"; int ppIds[] = {33, 36, 59, 60, 79, 81, 109, 114}; const string ppType = "rpo"; for(size_t i = 0; i < sizeof(ppIds)/sizeof(int); i++){ printf("ppId = %d\n ", ppIds[i]); // auto tmp = KSreadRPO(inName, ppType, ppIds[i]); // printf("T=%f, nstp=%d, r=%g, s=%f\n", std::get<1>(tmp), (int)std::get<2>(tmp), // std::get<3>(tmp), std::get<4>(tmp)); KScalWriteFEFVInit(inName, outName, ppType, ppIds[i], L, MaxN, tol, nqr, trunc); } break; } case 30: { /* move KS data base all ppo from one file rpo from 2 files */ const string inFile1 = "../../data/ks22h001t120x64EV.h5"; const string inFile2 = "../../data/ex.h5"; const string outFile1 = "../../data/ks22h001t120x64_t.h5"; const string outFile2 = "../../data/ks22h001t120x64_t2.h5"; std::vector<int> ppIds1; for(int i = 0; i < 200; i++) ppIds1.push_back(i+1); std::vector<int> ppIds2 = {33, 36, 59, 60, 79, 81, 109, 114}; for(int i = 0; i < ppIds1.size(); i++) { printf("f1 ppo, i = %d, ppId = %d \n", i, ppIds1[i]); KSmoveFE(inFile1, outFile1, "ppo", ppIds1[i]); KSmoveFEFV(inFile1, outFile2, "ppo", ppIds1[i]); } for(int i = 0; i < ppIds1.size(); i++) { if(std::find(ppIds2.begin(), ppIds2.end(), ppIds1[i]) == ppIds2.end()){ printf("f1 rpo, i = %d, ppId = %d \n", i, ppIds1[i]); KSmoveFE(inFile1, outFile1, "rpo", ppIds1[i]); KSmoveFEFV(inFile1, outFile2, "rpo", ppIds1[i]); } else { printf("f2 rpo, i = %d, ppId = %d \n", i, ppIds1[i]); KSmoveFE(inFile2, outFile1, "rpo", ppIds1[i]); KSmoveFEFV(inFile2, outFile2, "rpo", ppIds1[i]); } } break; } case 40: { /* move KS initial condtions The purpose is to reduce the space Also it changes double nstp to int nstp */ const string inFile = "../../data/ks22h001t120x64.h5"; const string outFile = "../../data/ks22h001t120x64_2.h5"; for(int i = 0; i < 840; i++){ int ppId = i+1; printf("ppo, i = %d, ppId = %d \n", i, ppId); KSmoveRPO(inFile, outFile, "ppo", ppId); } for(int i = 0; i < 834; i++){ int ppId = i+1; printf("rpo, i = %d, ppId = %d \n", i, ppId); KSmoveRPO(inFile, outFile, "rpo", ppId); } break; } case 50: { /* calculate left FE, FV for a single orbit */ const double L = 22; const int nqr = 5; // spacing const int MaxN = 2000; // maximal iteration number for PED const double tol = 1e-13; // torlearance for PED const int trunc = 30; // number of vectors const size_t ppId = 1; const string inputfileName = "../../data/ks22h001t120x64EV.h5"; const string outputfileName = "left.h5"; const string ppType = "ppo"; KScalWriteLeftFEFV(inputfileName, outputfileName, ppType, ppId, L, MaxN, tol, nqr, trunc); // auto tmp = KScalLeftFEFV(inputfileName, ppType, ppId, L, MaxN, tol, nqr, trunc); // cout << tmp.first << endl; break; } default: { cout << "Please indicate the right #" << endl; } } return 0; } <file_sep>#include "CQCGL2d.hpp" #include <cmath> #include <iostream> #include <algorithm> // std::max #define cee(x) (cout << (x) << endl << endl) using namespace denseRoutines; using namespace MyH5; using namespace Eigen; using namespace std; using namespace MyFFT; ////////////////////////////////////////////////////////////////////// // Class CQCGLgeneral // ////////////////////////////////////////////////////////////////////// /* ------------------------------------------------------ */ /* ---- constructor/destructor ------- */ /* ------------------------------------------------------ */ /** * Constructor of cubic quintic complex Ginzburg-Landau equation * A_t = Mu A + (Dr + Di*i) (A_{xx} + A_{yy}) + (Br + Bi*i) |A|^2 A + (Gr + Gi*i) |A|^4 A * * @param[in] N the number of Fourier modes * @param[in] d the spacial period, size * @param[in] doEnableTan false : forbid tangent space integration * @param[in] threadNum number of threads for integration */ CQCGL2d::CQCGL2d(int N, int M, double dx, double dy, double Mu, double Dr, double Di, double Br, double Bi, double Gr, double Gi, int threadNum) : N(N), M(M), dx(dx), dy(dy), Mu(Mu), Dr(Dr), Di(Di), Br(Br), Bi(Bi), Gr(Gr), Gi(Gi), F{ FFT2d(M, N, threadNum), FFT2d(M, N, threadNum), FFT2d(M, N, threadNum), FFT2d(M, N, threadNum), FFT2d(M, N, threadNum) }, JF{ FFT2d(M, N, threadNum), FFT2d(M, N, threadNum), FFT2d(M, N, threadNum), FFT2d(M, N, threadNum), FFT2d(M, N, threadNum) } { CGLInit(); // calculate coefficients. } /// M = N, dx = dy CQCGL2d::CQCGL2d(int N, double dx, double Mu, double Dr, double Di, double Br, double Bi, double Gr, double Gi, int threadNum) : CQCGL2d(N, N, dx, dx, Mu, Dr, Di, Br, Bi, Gr, Gi, threadNum) {} /** * Constructor of cubic quintic complex Ginzburg-Landau equation * A_t = -A + (1 + b*i) (A_{xx} + A_{yy}) + (1 + c*i) |A|^2 A - (dr + di*i) |A|^4 A */ CQCGL2d::CQCGL2d(int N, int M, double dx, double dy, double b, double c, double dr, double di, int threadNum) : CQCGL2d(N, M, dx, dy, -1, 1, b, 1, c, -dr, -di, threadNum) {} CQCGL2d::CQCGL2d(int N, double dx, double b, double c, double dr, double di, int threadNum) : CQCGL2d(N, N, dx, dx, -1, 1, b, 1, c, -dr, -di, threadNum) {} CQCGL2d::~CQCGL2d(){} CQCGL2d & CQCGL2d::operator=(const CQCGL2d &x){ return *this; } /* ------------------------------------------------------ */ /* ---- Initialization functions ------- */ /* ------------------------------------------------------ */ /** * @brief calculate the number of effective modes: Ne * @note N must be initialized first */ inline int CQCGL2d::calNe(const double N){ return (N/3) * 2 - 1; /* make it an odd number */ } /** * @brief set the corret dimension of the system * * Dealiasing is the method to calculate correct convolution term. For centralized * FFT, it works as set Fourier modes a_k = 0 for wave number |k| > 2/3 * N. * More specifically, in this code, the middle part of modes * is set to zero. * * |<---------------------------------------------------------->| * FFT length: N * * |<--------------->|<--------------------->|<---------------->| * (Ne + 1) / 2 N - Ne (Ne - 1) /2 * = Nplus = Nalias = Nminus * * @Note each term has real and imaginary part, so the indices are * 0, 1, 2,... Nplus*2, Nplus*2+1,... 2*Ne-1 */ void CQCGL2d::CGLInit(){ Ne = calNe(N); Nplus = (Ne + 1) / 2; Nminus = (Ne - 1) / 2; Nalias = N - Ne; Me = calNe(M); Mplus = (Me + 1) / 2; Mminus = (Me - 1) / 2; Malias = M - Me; // calculate the Linear part Kx.resize(N,1); Kx << ArrayXd::LinSpaced(N/2, 0, N/2-1), 0, ArrayXd::LinSpaced(N/2-1, -N/2+1, -1); Kx2.resize(Ne, 1); Kx2 << ArrayXd::LinSpaced(Nplus, 0, Nplus-1), ArrayXd::LinSpaced(Nminus, -Nminus, -1); Ky.resize(M,1); Ky << ArrayXd::LinSpaced(M/2, 0, M/2-1), 0, ArrayXd::LinSpaced(M/2-1, -M/2+1, -1); Ky2.resize(Me, 1); Ky2 << ArrayXd::LinSpaced(Mplus, 0, Mplus-1), ArrayXd::LinSpaced(Mminus, -Mminus, -1); QKx = 2*M_PI/dx * Kx; QKy = 2*M_PI/dy * Ky; L = dcp(Mu, -Omega) - dcp(Dr, Di) * (QKx.square().replicate(1, M).transpose() + QKy.square().replicate(1, N)); L.middleRows(Mplus, Malias) = ArrayXXcd::Zero(Malias, N); L.middleCols(Nplus, Nalias) = ArrayXXcd::Zero(M, Nalias); } void CQCGL2d::changeOmega(double w){ Omega = w; L = dcp(Mu, -Omega) - dcp(Dr, Di) * (QKx.square().replicate(1, M).transpose() + QKy.square().replicate(1, N)); L.middleRows(Mplus, Malias) = ArrayXXcd::Zero(Malias, N); L.middleCols(Nplus, Nalias) = ArrayXXcd::Zero(M, Nalias); } /** * @brief calculate the coefficients of ETDRK4 or Krogstad * * Note, we give up using * Map<ArrayXcd> hLv(hL.data(), hL.size()); * ArrayXXcd LR = ZR(hLv); * to save memory */ void CQCGL2d::calCoe(const double h){ ArrayXXcd hL = h*L; E = hL.exp(); E2 = (hL/2).exp(); a21.resize(M, N); b1.resize(M, N); b2.resize(M, N); b4.resize(M, N); if (Method == 2){ a31.resize(M, N); a32.resize(M, N); a41.resize(M, N); a43.resize(M, N); } for (int i = 0; i < N; i++){ ArrayXXcd LR = ZR(hL.col(i)); ArrayXXcd LR2 = LR.square(); ArrayXXcd LR3 = LR.cube(); ArrayXXcd LRe = LR.exp(); ArrayXXcd LReh = (LR/2).exp(); a21.col(i) = h * ( (LReh - 1)/LR ).rowwise().mean(); b1.col(i) = h * ( (-4.0 - LR + LRe*(4.0 - 3.0 * LR + LR2)) / LR3 ).rowwise().mean(); b2.col(i) = h * 2 * ( (2.0 + LR + LRe*(-2.0 + LR)) / LR3 ).rowwise().mean(); b4.col(i) = h * ( (-4.0 - 3.0*LR -LR2 + LRe*(4.0 - LR) ) / LR3 ).rowwise().mean(); if (Method == 2) { a31.col(i) = h * ( (LReh*(LR - 4) + LR + 4) / LR2 ).rowwise().mean(); a32.col(i) = h * 2 * ( (2*LReh - LR - 2) / LR2 ).rowwise().mean(); a41.col(i) = h * ( (LRe*(LR-2) + LR + 2) / LR2 ).rowwise().mean(); a43.col(i) = h * 2 * ( (LRe - LR - 1) / LR2 ).rowwise().mean(); } } } void CQCGL2d::oneStep(double &du, const bool onlyOrbit){ if (1 == Method) { NL(0, onlyOrbit); F[1].v1 = E2 * F[0].v1 + a21 * F[0].v3; if(!onlyOrbit) JF[1].v1 = E2 * JF[0].v1 + a21 * JF[0].v3; NL(1, onlyOrbit); F[2].v1 = E2 * F[0].v1 + a21 * F[1].v3; if(!onlyOrbit) JF[2].v1 = E2 * JF[0].v1 + a21 * JF[1].v3; NL(2, onlyOrbit); F[3].v1 = E2 * F[1].v1 + a21 * (2*F[2].v3 - F[0].v3); if(!onlyOrbit) JF[3].v1 = E2 * JF[1].v1 + a21 * (2*JF[2].v3 - JF[0].v3); NL(3, onlyOrbit); F[4].v1 = E * F[0].v1 + b1 * F[0].v3 + b2 * (F[1].v3+F[2].v3) + b4 * F[3].v3; if(!onlyOrbit) JF[4].v1 = E * JF[0].v1 + b1 * JF[0].v3 + b2 * (JF[1].v3+JF[2].v3) + b4 * JF[3].v3; NL(4, onlyOrbit); } else { NL(0, onlyOrbit); F[1].v1 = E2 * F[0].v1 + a21 * F[0].v3; if(!onlyOrbit) JF[1].v1 = E2 * JF[0].v1 + a21 * JF[0].v3; NL(1, onlyOrbit); F[2].v1 = E2 * F[0].v1 + a31 * F[0].v3 + a32 * F[1].v3; if(!onlyOrbit) JF[2].v1 = E2 * JF[0].v1 + a31 * JF[0].v3 + a32 * JF[1].v3; NL(2, onlyOrbit); F[3].v1 = E * F[0].v1 + a41 * F[0].v3 + a43 * F[2].v3; if(!onlyOrbit) JF[3].v1 = E * JF[0].v1 + a41 * JF[0].v3 + a43 * JF[2].v3; NL(3, onlyOrbit); F[4].v1 = E * F[0].v1 + b1 * F[0].v3 + b2 * (F[1].v3+F[2].v3) + b4 * F[3].v3; if(!onlyOrbit) JF[4].v1 = E * JF[0].v1 + b1 * JF[0].v3 + b2 * (JF[1].v3+JF[2].v3) + b4 * JF[3].v3; NL(4, onlyOrbit); } // infinity norm du = (b4 * (F[4].v3-F[3].v3)).abs().maxCoeff() / F[4].v1.abs().maxCoeff(); if(!onlyOrbit){ double x = (b4 * (JF[4].v3-JF[3].v3)).abs().maxCoeff() / JF[4].v1.abs().maxCoeff(); du = std::max(du, x); } } /** * @brief calcuate the matrix to do averge of phi(z). */ ArrayXXcd CQCGL2d::ZR(const Ref<const ArrayXcd> &z){ int M1 = z.size(); ArrayXd K = ArrayXd::LinSpaced(MC, 1, MC); // 1,2,3,...,M ArrayXXcd r = R * (K/MC*dcp(0,2*M_PI)).exp().transpose(); // row array. return z.replicate(1, MC) + r.replicate(M1, 1); } /** * @brief calculat the damping factor of time step * * @param[out] doChange true if time step needs change * @param[out] doAccept true if accept current time step * @param[in] s estimate damping factor * @return mu final dampling factor */ double CQCGL2d::adaptTs(bool &doChange, bool &doAccept, const double s){ double mu = 1; doChange = true; doAccept = true; if ( s > mumax) mu = mumax; else if (s > mue) mu = s; else if (s >= 1) { mu = 1; doChange = false; } else { doAccept = false; if (s > muc) mu = muc; else if (s > mumin) mu = s; else mu = mumin; } return mu; } void CQCGL2d::saveState(H5File &file, int id, const ArrayXXcd &a, const ArrayXXcd &v, const int flag){ char groupName[10]; sprintf (groupName, "%.6d", id); std::string s = "/"+std::string(groupName); Group group(file.createGroup(s)); std:: string DS = s + "/"; if (1 == flag || 0 == flag){ writeMatrixXd(file, DS + "ar", a.real()); writeMatrixXd(file, DS + "ai", a.imag()); } if (2 == flag || 0 == flag) { writeMatrixXd(file, DS + "vr", v.real()); writeMatrixXd(file, DS + "vi", v.imag()); } } /** * @brief Constant time step integrator */ ArrayXXcd CQCGL2d::constETD(const ArrayXXcd &a0, const ArrayXXcd &v0, const double h, const int Nt, const int skip_rate, const bool onlyOrbit, const bool doSaveDisk, const string fileName){ int s = 1; if(!onlyOrbit) s = 2; const int m = (Nt+skip_rate-1)/skip_rate + 1; lte.resize(m-1); ArrayXXcd aa; H5File file; if (doSaveDisk){ file = H5File(fileName, H5F_ACC_TRUNC); /* openFile fails */ saveState(file, 0, a0, v0, onlyOrbit ? 1 : 0); } else{ aa.resize(Me, Ne*m*s); aa.leftCols(Ne) = a0; if(!onlyOrbit) aa.middleCols(Ne, Ne) = v0; } F[0].v1 = pad(a0); if(!onlyOrbit) JF[0].v1 = pad(v0); NCallF = 0; calCoe(h); double du; int num = 0; for(int i = 0; i < Nt; i++){ if( constETDPrint > 0 && i % constETDPrint == 0) fprintf(stderr, "%d/%d\n", i, Nt); oneStep(du, onlyOrbit); F[0].v1 = F[4].v1; // update state if(!onlyOrbit) JF[0].v1 = JF[4].v1; NCallF += 5; if ( (i+1)%skip_rate == 0 || i == Nt-1) { lte(num) = du; if(doSaveDisk){ saveState(file, num+1, unpad(F[4].v1), unpad(JF[4].v1), onlyOrbit ? 1 : 0); } else{ aa.middleCols((num+1)*Ne, Ne) = unpad(F[4].v1); if(!onlyOrbit) aa.middleCols((M+num+1)*Ne, Ne) = unpad(JF[4].v1); } num++; } } return aa; } /** * @brief time step adaptive integrator */ ArrayXXcd CQCGL2d::adaptETD(const ArrayXXcd &a0, const ArrayXXcd &v0, const double h0, const double tend, const int skip_rate, const bool onlyOrbit, const bool doSaveDisk, const string fileName){ int s = 1; if(!onlyOrbit) s = 2; double h = h0; calCoe(h); const int Nt = (int)round(tend/h); const int m = (Nt+skip_rate-1) /skip_rate + 1; F[0].v1 = pad(a0); if(!onlyOrbit) JF[0].v1 = pad(v0); ArrayXXcd aa; H5File file; if (doSaveDisk) { file = H5File(fileName, H5F_ACC_TRUNC); saveState(file, 0, a0, v0, onlyOrbit ? 1:0); } else { aa.resize(Me, Ne*m*s); aa.leftCols(Ne) = a0; if(!onlyOrbit) aa.middleCols(Ne, Ne) = v0; } Ts.resize(m); Ts(0) = 0; NCalCoe = 0; NReject = 0; NCallF = 0; NSteps = 0; hs.resize(m-1); lte.resize(m-1); double t = 0; double du = 0; int num = 1; bool doChange, doAccept; bool TimeEnds = false; while(!TimeEnds){ if ( t + h > tend){ h = tend - t; calCoe(h); NCalCoe++; TimeEnds = true; } oneStep(du, onlyOrbit); NCallF += 5; double s = nu * std::pow(rtol/du, 1.0/4); double mu = adaptTs(doChange, doAccept, s); if (doAccept){ t += h; NSteps++; F[0].v1 = F[4].v1; if(!onlyOrbit) JF[0].v1 = JF[4].v1; if ( NSteps % skip_rate == 0 || TimeEnds) { if (num >= Ts.size()) { int m = Ts.size(); Ts.conservativeResize(m+cellSize); if(!doSaveDisk) aa.conservativeResize(Eigen::NoChange, (m+cellSize)*Ne*s); hs.conservativeResize(m-1+cellSize); lte.conservativeResize(m-1+cellSize); } hs(num-1) = h; lte(num-1) = du; if(doSaveDisk) saveState(file, num, unpad(F[4].v1), unpad(JF[4].v1), onlyOrbit ? 1:0); else { aa.middleCols(num*Ne*s, Ne) = unpad(F[4].v1); if (!onlyOrbit) aa.middleCols(num*Ne*s+1, Ne) = unpad(JF[4].v1); } Ts(num) = t; num++; } } else { NReject++; TimeEnds = false; } if (doChange) { h *= mu; calCoe(h); NCalCoe++; } } // lte = lte.head(num) has aliasing problem hs.conservativeResize(num-1); lte.conservativeResize(num-1); Ts.conservativeResize(num); if (doSaveDisk) return aa; else return aa.leftCols(num*Ne*s); } /** @brief Integrator of 2d cqCGL equation. * */ ArrayXXcd CQCGL2d::intg(const ArrayXXcd &a0, const double h, const int Nt, const int skip_rate, const bool doSaveDisk, const string fileName){ assert(a0.rows() == Me && a0.cols() == Ne); ArrayXXcd v0(1, 1); return constETD(a0, v0, h, Nt, skip_rate, true, doSaveDisk, fileName); } ArrayXXcd CQCGL2d::aintg(const ArrayXXcd &a0, const double h, const double tend, const int skip_rate, const bool doSaveDisk, const string fileName){ assert(a0.rows() == Me && a0.cols() == Ne); ArrayXXcd v0(1, 1); return adaptETD(a0, v0, h, tend, skip_rate, true, doSaveDisk, fileName); } /** * @brief integrate the state and a subspace in tangent space */ ArrayXXcd CQCGL2d::intgv(const ArrayXXcd &a0, const ArrayXXcd &v0, const double h, const int Nt, const int skip_rate, const bool doSaveDisk, const string fileName){ assert(a0.rows() == Me && a0.cols() == Ne && v0.rows() == Me && v0.cols() == Ne); ArrayXXcd aa = constETD(a0, v0, h, Nt, skip_rate, false, doSaveDisk, fileName); return aa; } ArrayXXcd CQCGL2d::aintgv(const ArrayXXcd &a0, const ArrayXXcd &v0, const double h, const double tend, const int skip_rate, const bool doSaveDisk, const string fileName){ assert(a0.rows() == Me && a0.cols() == Ne && v0.rows() == Me && v0.cols() == Ne); ArrayXXcd aa = adaptETD(a0, v0, h, tend, skip_rate, false, doSaveDisk, fileName); return aa; } /** * @brief get rid of the high modes */ void CQCGL2d::dealias(const int k, const bool onlyOrbit){ F[k].v3.middleRows(Mplus, Malias) = ArrayXXcd::Zero(Malias, N); F[k].v3.middleCols(Nplus, Nalias) = ArrayXXcd::Zero(M, Nalias); if (!onlyOrbit) { JF[k].v3.middleRows(Mplus, Malias) = ArrayXXcd::Zero(Malias, N); JF[k].v3.middleCols(Nplus, Nalias) = ArrayXXcd::Zero(M, Nalias); } } /* 3 different stage os ETDRK4: * v --> ifft(v) --> fft(g(ifft(v))) * */ void CQCGL2d::NL(const int k, const bool onlyOrbit){ dcp B(Br, Bi); dcp G(Gr, Gi); if(onlyOrbit){ F[k].ifft(); ArrayXXcd A2 = (F[k].v2.real().square() + F[k].v2.imag().square()).cast<dcp>(); F[k].v2 = B * F[k].v2 * A2 + G * F[k].v2 * A2.square(); F[k].fft(); dealias(k, onlyOrbit); } else { F[k].ifft(); JF[k].ifft(); ArrayXXcd aA2 = (F[k].v2.real().square() + F[k].v2.imag().square()).cast<dcp>(); ArrayXXcd A2 = F[k].v2.square(); F[k].v2 = B * F[k].v2 * aA2 + G * F[k].v2 * aA2.square(); JF[k].v2 = JF[k].v2.conjugate() * ((B+G*2.0*aA2) * A2) + JF[k].v2 * ((2.0*B+3.0*G*aA2)*aA2); F[k].fft(); JF[k].fft(); dealias(k, onlyOrbit); } } ArrayXXcd CQCGL2d::unpad(const ArrayXXcd &v){ int m = v.rows(); int n = v.cols(); assert(m == M && n % N == 0); int s = n / N; ArrayXXcd vt(Me, Ne*s); for (int i = 0; i < s; i++){ vt.middleCols(i*Ne, Ne) << v.block(0, i*N, Mplus, Nplus), v.block(0, i*N+Nplus+Nalias, Mplus, Nminus), v.block(Mplus+Malias, i*N, Mminus, Nplus), v.block(Mplus+Malias, i*N+Nplus+Nalias, Mminus, Nminus) ; } return vt; } ArrayXXcd CQCGL2d::pad(const ArrayXXcd &v){ int m = v.rows(); int n = v.cols(); assert( n % Ne == 0 && m == Me); int s = n / Ne; ArrayXXcd vp(M, N*s); for (int i = 0; i < s; i++){ vp.middleCols(i*N, N) << v.block(0, i*Ne, Mplus, Nplus), ArrayXXcd::Zero(Mplus, Nalias), v.block(0, i*Ne+Nplus, Mplus, Nminus), ArrayXXcd::Zero(Malias, N), v.block(Mplus, i*Ne, Mminus, Nplus), ArrayXXcd::Zero(Mminus, Nalias), v.block(Mplus, i*Ne+Nplus, Mminus, Nminus) ; } return vp; } ArrayXd CQCGL2d::c2r(const ArrayXXcd &v){ assert(v.rows() == Me && v.cols() == Ne); return Map<ArrayXd>((double*)&v(0,0), 2 * v.rows() * v.cols()); } ArrayXXcd CQCGL2d::r2c(const ArrayXd &v){ assert( v.size() == 2*Me*Ne); return Map<ArrayXXcd>((dcp*)&v(0,0), Me, Ne); } /* -------------------------------------------------- */ /* ------- Fourier/Configure transformation -------- */ /* -------------------------------------------------- */ /** * @brief back Fourier transform of the states. */ ArrayXXcd CQCGL2d::Fourier2Config(const Ref<const ArrayXXcd> &aa){ ArrayXXcd ap = pad(aa); int s = ap.cols() / N; ArrayXXcd AA(M, N*s); for (size_t i = 0; i < s; i++){ F[0].v1 = ap.middleCols(i*N, N); F[0].ifft(); AA.middleCols(i*N, N) = F[0].v2; } return AA; } /** * @brief Fourier transform of the states. Input and output are both real. */ ArrayXXcd CQCGL2d::Config2Fourier(const Ref<const ArrayXXcd> &AA){ int s = AA.cols() / N; ArrayXXcd aa(M, N*s); for(size_t i = 0; i < s; i++){ F[0].v2 = AA.middleCols(i*N, N); F[0].fft(); aa.middleCols(i*N, N) = F[0].v3; } return unpad(aa); } /* -------------------------------------------------- */ /* -------- velocity field ----------- */ /* -------------------------------------------------- */ /** * @brief velocity field */ ArrayXXcd CQCGL2d::velocity(const ArrayXXcd &a0){ assert(a0.rows() == Me && a0.cols() == Ne); F[0].v1 = pad(a0); NL(0, true); ArrayXXcd vel = L*F[0].v1 + F[0].v3; return unpad(vel); } /** * @brief the generalized velociyt for relative equilibrium * * v(x) + \omega_\tau * t_\tau(x) + \omega_\rho * t_\rho(x) */ ArrayXXcd CQCGL2d::velocityReq(const ArrayXXcd &a0, const double wthx, const double wthy, const double wphi){ return velocity(a0) + wthx*tangent(a0, 1) + wthy*tangent(a0, 2) + wphi*tangent(a0, 3); } /* -------------------------------------------------- */ /* -------- stability matrix ----------- */ /* -------------------------------------------------- */ /** * @brief calculate the product of stability matrix with a vector */ ArrayXXcd CQCGL2d::stab(const ArrayXXcd &a0, const ArrayXXcd &v0){ assert(a0.rows() == Me && a0.cols() == Ne && v0.rows() == Me && v0.cols() == Ne); F[0].v1 = pad(a0); JF[0].v1 = pad(v0); NL(0, false); ArrayXXcd Ax = L*JF[0].v1 + JF[0].v3; return unpad(Ax); } /** * @brief stability for relative equilbrium */ ArrayXXcd CQCGL2d::stabReq(const ArrayXXcd &a0, const ArrayXXcd &v0, const double wthx, const double wthy, const double wphi){ ArrayXXcd z = stab(a0, v0); return z + wthx*tangent(v0, 1) + wthy*tangent(v0, 2) + wphi*tangent(v0, 3); } /* -------------------------------------------------- */ /* ------ symmetry related ------ */ /* -------------------------------------------------- */ ArrayXXcd CQCGL2d::rotate(const Ref<const ArrayXXcd> &a0, const int mode, const double th1, const double th2, const double th3){ switch(mode) { case 1 : { /* translation rotation in x direction */ double thx = th1; ArrayXXd th = (thx*Kx2).replicate(1, Me).transpose(); return a0 * (dcp(0, 1) * th).exp(); } case 2: { /* translation rotation in y direction */ double thy = th1; ArrayXXd th = (thy*Ky2).replicate(1, Ne); return a0 * (dcp(0, 1) * th).exp(); } case 3 : { /* phase rotation */ double phi = th1; return a0 * exp(dcp(0, 1)*phi); // a0*e^{i\phi} } case 4 : { /* translation rotation in both x and y direction */ double thx = th1; double thy = th2; ArrayXXd th = (thx*Kx2).replicate(1, Me).transpose() + (thy*Ky2).replicate(1, Ne); return a0 * (dcp(0, 1) * th).exp(); } case 5 : { /* both rotate */ double thx = th1; double thy = th2; double phi = th3; ArrayXXd th = (thx*Kx2).replicate(1, Me).transpose() + (thy*Ky2).replicate(1, Ne) + phi; return a0 * (dcp(0, 1) * th).exp(); } default :{ fprintf(stderr, "indicate a valid rotate mode !\n"); } } } ArrayXXcd CQCGL2d::tangent(const Ref<const ArrayXXcd> &a0, const int mode){ switch (mode) { case 1 : { /* translation tangent in x direction */ ArrayXXcd R = dcp(0, 1) * Kx2; return a0 * R.replicate(1, Me).transpose(); } case 2 : { /* translation tangent in y direction */ ArrayXXcd R = dcp(0, 1) * Ky2; return a0 * R.replicate(1, Ne); } case 3 : { /* phase rotation tangent */ return a0 * dcp(0, 1); } default :{ fprintf(stderr, "indicate a valid tangent mode !\n"); } } } //==================================================================================================== // H5 related // std::tuple<ArrayXXcd, double, double, double, double> CQCGL2d::readReq(const string fileName, const string groupName){ H5File file(fileName, H5F_ACC_RDONLY); string DS = "/" + groupName + "/"; ArrayXXcd a(Me, Ne); a.real() = readMatrixXd(file, DS + "ar"); a.imag() = readMatrixXd(file, DS + "ai"); return make_tuple(a, readScalar<double>(file, DS + "wthx"), readScalar<double>(file, DS + "wthy"), readScalar<double>(file, DS + "wphi"), readScalar<double>(file, DS + "err") ); } #if 0 /** * @brief rotate the state points in the full state space to the slice * * @param[in] aa states in the full state space * @return aaHat, theta, phi * * @note g(theta, phi)(x+y) is different from gx+gy. There is no physical * meaning to transform the sum/subtraction of two state points. */ std::tuple<ArrayXXd, ArrayXd, ArrayXd> CQCGLgeneral::orbit2sliceWrap(const Ref<const ArrayXXd> &aa){ int n = aa.rows(); int m = aa.cols(); assert(Ndim == n); ArrayXXd raa(n, m); ArrayXd th(m); ArrayXd phi(m); for(size_t i = 0; i < m; i++){ double am1 = atan2(aa(n-1, i), aa(n-2, i)); double a1 = atan2(aa(3, i), aa(2, i)); phi(i) = 0.5 * (a1 + am1); th(i) = 0.5 * (a1 - am1); raa.col(i) = Rotate(aa.col(i), -th(i), -phi(i)); } return std::make_tuple(raa, th, phi); } /** * @brief reduce the continous symmetries without wrapping the phase * so there is no continuity * @see orbit2sliceWrap() */ std::tuple<ArrayXXd, ArrayXd, ArrayXd> CQCGLgeneral::orbit2slice(const Ref<const ArrayXXd> &aa){ int n = aa.rows(); int m = aa.cols(); assert(Ndim == n); ArrayXXd raa(n, m); ArrayXd th(m); ArrayXd phi(m); for(size_t i = 0; i < m; i++){ double am1 = atan2(aa(n-1, i), aa(n-2, i)); double a1 = atan2(aa(3, i), aa(2, i)); phi(i) = 0.5 * (a1 + am1); th(i) = 0.5 * (a1 - am1); } const double M_2PI = 2 * M_PI; for(size_t i = 1; i < m; i++){ double t0 = th(i) - th(i-1); double t1 = t0 - M_PI; double t2 = t0 + M_PI; double t0WrapAbs = fabs(remainder(t0, M_2PI)); if(fabs(t1) < t0WrapAbs) { // theta jump pi up th(i) = remainder(th(i) - M_PI, M_2PI); phi(i) = remainder(phi(i) - M_PI, M_2PI); continue; } if(fabs(t2) < t0WrapAbs) { // theta jump pi down th(i) = remainder(th(i) + M_PI, M_2PI); phi(i) = remainder(phi(i) + M_PI, M_2PI); } } for(size_t i = 0; i < m; i++){ raa.col(i) = Rotate(aa.col(i), -th(i), -phi(i)); } return std::make_tuple(raa, th, phi); } /** * @ simple version of orbit2slice(). Discard translation and phase information. */ ArrayXXd CQCGLgeneral::orbit2sliceSimple(const Ref<const ArrayXXd> &aa){ auto tmp = orbit2slice(aa); return std::get<0>(tmp); } /** @brief project covariant vectors to 1st mode slice * * projection matrix is h = (I - |tx><tp|/<tx|tp>) * g(-th), so eigenvector |ve> is * projected to |ve> - |tx>*(<tp|ve>|/<tx|tp>), before which, g(-th) is * performed. * * In 1th and -1st mode slice, template point is * |xp_\rho>=(0, ...,1, 0) ==> |tp_\rho>=(0,0,0,...,0,1) * |xp_\tau>=(0,0,1,...,0) ==> |tp_\tau>=(0,0,0,1,...,0) * <tp_\rho|ve> = ve.bottomRows(1) // last row * <tp_\tau|ve> = ve.row(3) // 4th row * * @note vectors are not normalized */ MatrixXd CQCGLgeneral::ve2slice(const ArrayXXd &ve, const Ref<const ArrayXd> &x){ int n = x.size(); std::tuple<ArrayXXd, ArrayXd, ArrayXd> tmp = orbit2slice(x); ArrayXXd &xhat = std::get<0>(tmp); // dimension [2*N, 1] double th = std::get<1>(tmp)[0]; double phi = std::get<2>(tmp)[0]; VectorXd tx_rho = phaseTangent(xhat); VectorXd tx_tau = transTangent(xhat); MatrixXd vep = Rotate(ve, -th, -phi); vep = vep - 0.5 * ((tx_rho - tx_tau) * vep.row(n-1) / xhat(n-2) + (tx_rho + tx_tau) * vep.row(3) / xhat(2)); return vep; } #endif <file_sep>#include <boost/python.hpp> #include <boost/numpy.hpp> #include <Eigen/Dense> #include <cstdio> #include "KSETD.hpp" #include "ETDRK4.hpp" using namespace std; using namespace Eigen; namespace bp = boost::python; namespace bn = boost::numpy; ////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////// class pyKSETD : public KSETD { public : pyKSETD(int N, double d) : KSETD(N, d) {} bp::tuple PYetd(bn::ndarray a0, double tend, double h, int skip_rate, int method, bool adapt){ int m, n; getDims(a0, m, n); Map<VectorXd> tmpa0((double*)a0.get_data(), n * m); auto tmp = etd(tmpa0, tend, h, skip_rate, method, adapt); return bp::make_tuple(copy2bn(tmp.first), copy2bn(tmp.second) ); } bn::ndarray PYhs() { return copy2bn(etdrk4->hs); } bn::ndarray PYduu() { return copy2bn(etdrk4->duu); } bp::tuple PYetdParam(){ return bp::make_tuple(etdrk4->NCalCoe, etdrk4->NReject, etdrk4->NCallF, etdrk4->rtol ); } void PYsetRtol(double x){ etdrk4->rtol = x; } }; BOOST_PYTHON_MODULE(py_ks) { bn::initialize(); bp::class_<KSETD>("KSETD", bp::init<int, double>()) ; bp::class_<pyKSETD, bp::bases<KSETD> >("pyKSETD", bp::init<int, double>()) .def_readonly("N", &pyKSETD::N) .def_readonly("d", &pyKSETD::d) .def("etdParam", &pyKSETD::PYetdParam) .def("setRtol", &pyKSETD::PYsetRtol) .def("etd", &pyKSETD::PYetd) .def("hs", &pyKSETD::PYhs) .def("duu", &pyKSETD::PYduu) ; } <file_sep> logisticMap.py ============== This file is copied from dasbuch/SOOC/Course2w12/hw12/logistMap_answer.py <file_sep>#include <iostream> #include <fstream> #include <Eigen/Dense> #include <complex> #include <ctime> #include <H5Cpp.h> #include "myH5.hpp" #include "denseRoutines.hpp" #include "ksdim.hpp" #include "ksint.hpp" using namespace std; using namespace Eigen; /** @brief calculate angle between two subspaces along an upo * * @param[in] fileName file that stores the ppo/rpo information * @param[in] ppType ppo or rpo * @param[in] ppId id of the periodic orbit * @param[in] subspDim 4xM2 matrix storing the bounds of subspaces * @return first matrix : each row stores the angles at one point * second matrix: matrix indicating whether bounds are the * same as specified * @see subspBound */ std::pair<MatrixXd, MatrixXi> anglePO(const string fileName, const string ppType, const int ppId, const MatrixXi subspDim){ assert(subspDim.rows() == 4); MatrixXd eigVals = MyH5::KSreadFE(fileName, ppType, ppId); // Floquet exponents MatrixXd eigVecs = MyH5::KSreadFV(fileName, ppType, ppId); // Floquet vectors // left and right bounds MatrixXi ixSp = denseRoutines::indexSubspace(eigVals.col(2), eigVals.col(0)); const int N = eigVals.rows(); // be careful about N when FVs are not complete assert ( eigVecs.rows() % N == 0); const int NFV = eigVecs.rows() / N; const int M = eigVecs.cols(); const int M2 = subspDim.cols(); MatrixXd ang_po(M, M2); // calculate the exact bound of this indices. std::pair<MatrixXi, MatrixXi> tmp = denseRoutines::subspBound(subspDim, ixSp); MatrixXi &bound = tmp.first; MatrixXi &boundStrict = tmp.second; for(size_t i = 0; i < M; i++){ MatrixXd ve = eigVecs.col(i); ve.resize(N, NFV); for(size_t j = 0; j < M2; j++){ double ang = denseRoutines::angleSubspace(ve.middleCols(bound(0, j), bound(1,j)-bound(0,j)+1), ve.middleCols(bound(2, j), bound(3,j)-bound(2,j)+1) ); ang_po(i, j) = ang; } } return std::make_pair(ang_po, boundStrict); } /** * Test the tangency of tangent bundle. * * @param[in] N number of FVs at each point * @param[in] NN number of periodic orbits * @param[in] spType "vector" or "space" * @param[in] M number of angles * @param[in] saveFolder folder name to save angles * @see anglePOs() */ void anglePOs(const string fileName, const string ppType, const int N, const int NN, const string saveFolder, const string spType, const int M) { std::vector<int> ppIds(NN); for(int i = 0; i < NN; i++) ppIds[i] = i+1; anglePOs(fileName, ppType, N, ppIds, saveFolder, spType, M); } void anglePOs(const string fileName, const string ppType, const int N, const std::vector<int> ppIds, const string saveFolder, const string spType, const int M) { //////////////////////////////////////////////////////////// // judge subspace or vector MatrixXi subspDim(4, M); if(spType.compare("vector") == 0) for (size_t i = 0; i < M; i++) subspDim.col(i) << i, i, i+1, i+1; else if(spType.compare("space") == 0) for (size_t i = 0; i < M; i++) subspDim.col(i) << 0, i, i+1, N-1; else { printf("invalid spType.\n"); } //////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////// // create subfolders for each ppId for(size_t i = 0; i < ppIds.size(); i++){ std::string tmp = saveFolder + '/' + to_string(ppIds[i]); int s = mkdir( tmp.c_str(), S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH); if(s != 0){ fprintf(stderr, "\n creating ppId folder fails. \n"); exit(-1); } } //////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////// // get the index of POs which converge. MatrixXi status = MyH5::checkExistEV(fileName, ppType, ppIds); for(size_t i = 0; i < ppIds.size(); i++){ if( 1 == status(i,0) ){ int ppId = ppIds[i]; printf("========= i = %zd, ppId = %d ========\n", i, ppId); // create files ofstream file[M]; string angName("ang"); for(size_t j = 0; j < M; j++){ std::string tmp = saveFolder + '/' + to_string(ppId) + '/' + angName + to_string(j) + ".dat"; file[j].open(tmp, ios::trunc); file[j].precision(16); } // calculation std::pair<MatrixXd, MatrixXi> tmp = anglePO(fileName, ppType, ppId, subspDim); MatrixXd &ang = tmp.first; MatrixXi &boundStrict = tmp.second; cout << boundStrict << endl; // check whether there are degeneracy MatrixXi pro = boundStrict.row(0).array() * boundStrict.row(1).array() * boundStrict.row(2).array() * boundStrict.row(3).array(); for(size_t i = 0; i < M; i++){ // only keep the orbits whose 4 bounds are not degenerate if(pro(0, i) == 1) file[i] << ang.col(i) << endl; } // close files for(size_t i = 0; i < M; i++) file[i].close(); } } } /** * Calucate local expansion rate of FVs along a periodic orbit * * @param[in] fileName h5 file that stores the ppo/rpo * @param[in] ppType 'rpo' or 'ppo' * @param[in] ppId index of po * @return expansion rate. each column is the expansion rate * at a specific point along the orbit */ MatrixXd partialHyperb(const string fileName, const string ppType, const int ppId) { auto tmp = MyH5::KSreadRPO(fileName, ppType, ppId); MatrixXd &a = std::get<0>(tmp); double T = std::get<1>(tmp); int nstp = (int) std::get<2>(tmp); double r = std::get<3>(tmp); double s = std::get<4>(tmp); MatrixXd eigVals = MyH5::KSreadFE(fileName, ppType, ppId); // Floquet exponents MatrixXd eigVecs = MyH5::KSreadFV(fileName, ppType, ppId); // Floquet vectors const int N = eigVals.rows(); // be careful about N when FVs are not complete assert ( eigVecs.rows() % N == 0); const int NFV = eigVecs.rows() / N; const int M = eigVecs.cols(); const int Nks = a.rows() + 2; const double L = 22; assert(nstp % M == 0); const int space = nstp / M; KS ks(Nks, T/nstp, L); auto tmp2 = ks.intgj(a.col(0), nstp, nstp, space); ArrayXXd &daa = tmp2.second; MatrixXd Jv(N, NFV*M); for(size_t i = 0; i < M; i++){ MatrixXd ve = eigVecs.col(i); ve.resize(N, NFV); MatrixXd J = daa.col(i); J.resize(N, N); Jv.middleCols(i*NFV, NFV) = J * ve; } MatrixXd expand(NFV, M); for(size_t i = 0; i < NFV; i++){ if (eigVals(i, 2) == 0) { // real case for(int j = 0; j < M; j++){ expand(i, j) = Jv.col(j*NFV+i).norm(); } } else { // complex case for(int j = 0; j < M; j++){ double e1 = Jv.col(j*NFV+i).squaredNorm(); double e2 = Jv.col(j*NFV+i+1).squaredNorm(); expand(i, j) = sqrt(e1+e2); expand(i+1, j) = expand(i, j); } i++; } } return expand; } void partialHyperbOneType(const string fileName, const string ppType, const int NN, const string saveFolder){ ofstream file; for(size_t i = 0; i < NN; i++){ int ppId = i + 1; file.open(saveFolder + "FVexpand" + to_string(ppId) + ".dat", ios::trunc); file.precision(16); printf("========= i = %zd ========\n", i); MatrixXd expand = partialHyperb( fileName, ppType, ppId); file << expand << endl; file.close(); } } void partialHyperbAll(const string fileName, const int NNppo, const int NNrpo, const string saveFolder){ partialHyperbOneType(fileName, "ppo", NNppo, saveFolder + "ppo/"); partialHyperbOneType(fileName, "rpo", NNrpo, saveFolder + "rpo/"); } /** @brief calculate the local Floquet exponents by stability matrix * */ MatrixXd localFE(const std::string fileName, const std::string ppType, const int ppId){ auto tmp = MyH5::KSreadRPO(fileName, ppType, ppId); MatrixXd &a = std::get<0>(tmp); double T = std::get<1>(tmp); int nstp = (int) std::get<2>(tmp); double r = std::get<3>(tmp); double s = std::get<4>(tmp); MatrixXd eigVals = MyH5::KSreadFE(fileName, ppType, ppId); // Floquet exponents MatrixXd eigVecs = MyH5::KSreadFV(fileName, ppType, ppId); // Floquet vectors const int N = eigVals.rows(); assert ( eigVecs.rows() % N == 0); const int NFV = eigVecs.rows() / N; const int M = eigVecs.cols(); const int Nks = a.rows() + 2; const double L = 22; assert(nstp % M == 0); const int space = nstp / M; KS ks(Nks, T/nstp, L); ArrayXXd aa = ks.intg(a.col(0), nstp, space); MatrixXd expand(NFV, M); for(size_t i = 0; i < M; i++){ MatrixXd ve = eigVecs.col(i); ve.resize(N, NFV); MatrixXd A = ks.stab(aa.col(i)); for(int j = 0; j < NFV; j++){ expand(j, i) = ve.col(j).transpose() * A * ve.col(j); } } for(int i = 0; i < NFV; i++){ if(eigVals(i, 2) == 1) { // complex case VectorXd tmp = expand.row(i) + expand.row(i+1); expand.row(i) = tmp; expand.row(i+1) = tmp; i++; } } return expand; } void localFEOneType(const string fileName, const string ppType, const int NN, const string saveFolder){ ofstream file; for(size_t i = 0; i < NN; i++){ int ppId = i + 1; file.open(saveFolder + "FVexpand" + to_string(ppId) + ".dat", ios::trunc); file.precision(16); printf("========= i = %zd ========\n", i); MatrixXd expand = localFE( fileName, ppType, ppId); file << expand << endl; file.close(); } } void localFEAll(const string fileName, const int NNppo, const int NNrpo, const string saveFolder){ localFEOneType(fileName, "ppo", NNppo, saveFolder + "ppo/"); localFEOneType(fileName, "rpo", NNrpo, saveFolder + "rpo/"); } /* void expandDifvAngle(const string fileName, const string ppType, const int ppId, const int gTpos, const MatrixXd difv, const VectorXi indexPO){ int num = difv.cols(); int N = difv.rows(); assert(num == indexPO.size()); auto tmp = MyH5::KSreadRPO(fileName, ppType, ppId); MatrixXd &a = std::get<0>(tmp); double T = std::get<1>(tmp); int nstp = (int) std::get<2>(tmp); double r = std::get<3>(tmp); double s = std::get<4>(tmp); MatrixXd eigVecs = MyH5::KSreadFV(fileName, ppType, ppId); // Floquet vectors assert ( eigVecs.rows() % N == 0); const int NFV = eigVecs.rows() / N; const int M = eigVecs.cols(); const int Nks = a.rows() + 2; const double L = 22; assert(nstp % M == 0); const int space = nstp / M; KS ks(Nks, T/nstp, L); ArrayXXd aa = ks.intg(a.col(0), nstp, space); if(ppType.compare("ppo") == 0) { aaWhole = ks.half2whole(aa.leftCols(aa.cols()-1)); eigVecsWhole = ks.half2whole(eigVecs); // this is correct. Think carefully. } else { aaWhole = aa.leftCols(aa.cols()-1); // one less eigVecsWhole = eigVecs; } MatrixXd veSlice = ks.veToSliceAll(eigVecsWhole, aaWhole, NFV); MatrixXd ve_trunc = veTrunc(veSlice, gTpos, Trunc); } */ <file_sep>/** \mainpage trail the fftw routines for my purpose * * \section sec_intro Introduction * * \section sec_use usage * Example: * \code * g++ yourfile.cc -I/path/to/fft.hpp -I/path/to/eigen -std=c++0x * \endcode * * \note Also use shared_ptr of FFT, not define it directly. */ #ifndef FFT_H #define FFT_H #include <fftw3.h> #include <complex> #include <Eigen/Dense> namespace MyFFT { extern long NumOfInstance; ////////////////////////////////////////////////////////////////////////////////////////// // FFT // ////////////////////////////////////////////////////////////////////////////////////////// /** @brief Structure for convenience of fft. */ class FFT { protected: fftw_plan p, rp; // plan for fft/ifft. fftw_complex *c1, *c2, *c3; // c1 = v, c2 = ifft(v), c3 = fft(c2) public: typedef std::complex<double> dcp; int N; int M; bool hasInit = false; Eigen::Map<Eigen::ArrayXXcd> v1, v2, v3; // mapping for c1, c2, c3 respectively ////////////////////////////////////////////////////////////////////// // member functions FFT(const int N, const int M); FFT(); ~FFT(); void init(const int N, const int M); void fft(); void ifft(); }; ////////////////////////////////////////////////////////////////////////////////////////// // RFFT // ////////////////////////////////////////////////////////////////////////////////////////// class RFFT { public: typedef std::complex<double> dcp; const int N; const int M; const int threadNum; Eigen::Map<Eigen::ArrayXXd> vr2; Eigen::Map<Eigen::ArrayXXcd> vc1, vc3; fftw_plan p, rp; fftw_complex *c1, *c3; double *r2; //////////////////////////////////////////////////////////// RFFT(const int N, const int M, const int threadNum = 4); ~RFFT(); void fft(); void ifft(); }; ////////////////////////////////////////////////////////////////////////////////////////// // FFT2d // ////////////////////////////////////////////////////////////////////////////////////////// class FFT2d { public: typedef std::complex<double> dcp; const int N; const int M; const int threadNum; fftw_plan p, rp; // plan for fft/ifft. fftw_complex *c1, *c2, *c3; // c1 = v, c2 = ifft(v), c3 = fft(c2) Eigen::Map<Eigen::ArrayXXcd> v1, v2, v3; // mapping for c1, c2, c3 respectively ////////////////////////////////////////////////////////////////////// // member functions FFT2d(const int N, const int M, const int threadNum = 4); ~FFT2d(); void fft(); void ifft(); }; } #endif /* FFT_H */ <file_sep>#include <boost/python.hpp> #include <boost/numpy.hpp> #include <Eigen/Dense> #include <cstdio> #include "CQCGL1dSub.hpp" #include "myBoostPython.hpp" using namespace std; using namespace Eigen; namespace bp = boost::python; namespace bn = boost::numpy; ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// class pyCQCGL1dSub : public CQCGL1dSub { public: pyCQCGL1dSub(int N, double d, double Mu, double Dr, double Di, double Br, double Bi, double Gr, double Gi, int dimTan): CQCGL1dSub(N, d, Mu, Dr, Di, Br, Bi, Gr, Gi, dimTan) {} pyCQCGL1dSub(int N, double d, double b, double c, double dr, double di, int dimTan) : CQCGL1dSub(N, d, b, c, dr, di, dimTan) {} pyCQCGL1dSub(int N, double d, double delta, double beta, double D, double epsilon, double mu, double nu, int dimTan): CQCGL1dSub(N, d, delta, beta, D, epsilon, mu, nu, dimTan) {} bn::ndarray PYTs(){ return copy2bn(Ts); } bn::ndarray PYlte(){ return copy2bn(lte); } bn::ndarray PYhs(){ return copy2bn(hs); } /* K */ bn::ndarray PYK(){ return copy2bn(K); } /* L */ bn::ndarray PYL(){ return copy2bnc(L); } /* wrap the integrator */ bn::ndarray PYintgC(bn::ndarray a0, double h, double tend, int skip_rate){ int m, n; getDims(a0, m, n); Map<ArrayXd> tmpa((double*)a0.get_data(), m*n); return copy2bn(intgC(tmpa, h, tend, skip_rate)); } /* wrap the integrator with Jacobian */ bp::tuple PYintgjC(bn::ndarray a0, double h, double tend, size_t skip_rate){ int m, n; getDims(a0, m, n); Map<ArrayXd> tmpa((double*)a0.get_data(), m*n); auto result = intgjC(tmpa, h, tend, skip_rate); return bp::make_tuple(copy2bn(result.first), copy2bn(result.second)); } bn::ndarray PYintgvC(bn::ndarray a0, bn::ndarray v, double h, double tend){ int m, n; getDims(a0, m, n); Map<ArrayXd> tmpa((double*)a0.get_data(), m*n); getDims(v, m, n); Map<ArrayXXd> tmpv((double*)v.get_data(), n, m); return copy2bn(intgvC(tmpa, tmpv, h, tend)); } bn::ndarray PYintg(bn::ndarray a0, double h, double tend, int skip_rate){ int m, n; getDims(a0, m, n); Map<ArrayXd> tmpa((double*)a0.get_data(), m*n); return copy2bn(intg(tmpa, h, tend, skip_rate)); } bp::tuple PYintgj(bn::ndarray a0, double h, double tend, int skip_rate){ int m, n; getDims(a0, m, n); Map<ArrayXd> tmpa((double*)a0.get_data(), m*n); auto result = intgj(tmpa, h, tend, skip_rate); return bp::make_tuple(copy2bn(result.first), copy2bn(result.second)); } bn::ndarray PYintgv(bn::ndarray a0, bn::ndarray v, double h, double tend){ int m, n; getDims(a0, m, n); Map<ArrayXd> tmpa((double*)a0.get_data(), m*n); getDims(v, m, n); Map<ArrayXXd> tmpv((double*)v.get_data(), n, m); return copy2bn(intgv(tmpa, tmpv, h, tend)); } /* wrap Fourier2Config */ bn::ndarray PYFourier2Config(bn::ndarray aa){ int m, n; getDims(aa, m, n); Map<ArrayXXd> tmpaa((double*)aa.get_data(), n, m); return copy2bnc( Fourier2Config(tmpaa) ); } /* wrap Config2Fourier */ bn::ndarray PYConfig2Fourier(bn::ndarray AA){ int m, n; getDims(AA, m, n); Map<ArrayXXcd> tmpAA((dcp*)AA.get_data(), n, m); return copy2bn( Config2Fourier(tmpAA) ); } bn::ndarray PYcalQ(const bn::ndarray &aa){ int m, n; getDims(aa, m, n); Map<ArrayXXd> tmpaa((double*)aa.get_data(), n, m); return copy2bn(calQ(tmpaa)); } bn::ndarray PYcalMoment(const bn::ndarray &aa, const int p){ int m, n; getDims(aa, m, n); Map<ArrayXXd> tmpaa((double*)aa.get_data(), n, m); return copy2bn(calMoment(tmpaa, p)); } /* wrap the velocity */ bn::ndarray PYvelocity(bn::ndarray a0){ int m, n; getDims(a0, m, n); Map<ArrayXd> tmpa((double*)a0.get_data(), m*n); return copy2bn(velocity(tmpa)); } /* wrap velocityReq */ bn::ndarray PYvelocityReq(bn::ndarray a0, double phi){ int m, n; getDims(a0, m, n); Map<ArrayXd> tmpa((double*)a0.get_data(), m*n); ArrayXd tmpv = velocityReq(tmpa, phi); return copy2bn(tmpv); } /* stability matrix */ bn::ndarray PYstab(bn::ndarray a0){ int m, n; getDims(a0, m, n); Map<ArrayXd> tmpa((double*)a0.get_data(), n*m); return copy2bn(stab(tmpa)); } /* stability matrix for relative equibrium */ bn::ndarray PYstabReq(bn::ndarray a0, double phi){ int m, n; getDims(a0, m, n); Map<ArrayXd> tmpa((double*)a0.get_data(), n*m); return copy2bn(stabReq(tmpa, phi)); } /* phaseRotate */ bn::ndarray PYphaseRotate(bn::ndarray aa, double phi){ int m, n; getDims(aa, m, n); Map<ArrayXXd> tmpaa((double*)aa.get_data(), n, m); return copy2bn( phaseRotate(tmpaa, phi) ); } /* phaseTangent */ bn::ndarray PYphaseTangent(bn::ndarray aa){ int m, n; getDims(aa, m, n); Map<ArrayXXd> tmpaa((double*)aa.get_data(), n, m); return copy2bn( phaseTangent(tmpaa) ); } }; //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// BOOST_PYTHON_MODULE(py_CQCGL1dSub) { bn::initialize(); // must provide the constructor bp::class_<CQCGL1dSub>("CQCGL1dSub", bp::init< int, double, double, double, double, double, int>()) ; // the EIDc class bp::class_<EIDc>("EIDc", bp::init<>()) .def_readonly("NCalCoe", &EIDc::NCalCoe) .def_readonly("NReject", &EIDc::NReject) .def_readonly("NCallF", &EIDc::NCallF) .def_readonly("NSteps", &EIDc::NSteps) .def_readonly("TotalTime", &EIDc::TotalTime) .def_readonly("CoefficientTime", &EIDc::CoefficientTime) .def_readwrite("rtol", &EIDc::rtol) ; bp::class_<pyCQCGL1dSub, bp::bases<CQCGL1dSub> >("pyCQCGL1dSub", bp::init< int, double, double, double, double, double, int >()) .def(bp::init<int, double, double, double, double, double, double, double, double, int>()) .def(bp::init<int, double, double, double, double, double, double, double, int>()) .def_readonly("N", &pyCQCGL1dSub::N) .def_readonly("d", &pyCQCGL1dSub::d) .def_readwrite("IsQintic", &pyCQCGL1dSub::IsQintic) .def_readonly("Mu", &pyCQCGL1dSub::Mu) .def_readwrite("Br", &pyCQCGL1dSub::Br) .def_readwrite("Bi", &pyCQCGL1dSub::Bi) .def_readonly("Dr", &pyCQCGL1dSub::Dr) .def_readonly("Di", &pyCQCGL1dSub::Di) .def_readwrite("Gr", &pyCQCGL1dSub::Gr) .def_readwrite("Gi", &pyCQCGL1dSub::Gi) .def_readonly("Ndim", &pyCQCGL1dSub::Ndim) .def_readonly("Ne", &pyCQCGL1dSub::Ne) .def_readonly("Omega", &pyCQCGL1dSub::Omega) .def_readwrite("eidc", &pyCQCGL1dSub::eidc) .def_readwrite("eidc2", &pyCQCGL1dSub::eidc2) .def("Ts", &pyCQCGL1dSub::PYTs) .def("hs", &pyCQCGL1dSub::PYhs) .def("lte", &pyCQCGL1dSub::PYlte) .def("K", &pyCQCGL1dSub::PYK) .def("L", &pyCQCGL1dSub::PYL) .def("changeOmega", &pyCQCGL1dSub::changeOmega) .def("intgC", &pyCQCGL1dSub::PYintgC) .def("intgjC", &pyCQCGL1dSub::PYintgjC) .def("intgvC", &pyCQCGL1dSub::PYintgv) .def("intg", &pyCQCGL1dSub::PYintg) .def("intgj", &pyCQCGL1dSub::PYintgj) .def("intgv", &pyCQCGL1dSub::PYintgv) .def("Fourier2Config", &pyCQCGL1dSub::PYFourier2Config) .def("Config2Fourier", &pyCQCGL1dSub::PYConfig2Fourier) .def("calQ", &pyCQCGL1dSub::PYcalQ) .def("calMoment", &pyCQCGL1dSub::PYcalMoment) .def("velocity", &pyCQCGL1dSub::PYvelocity) .def("velocityReq", &pyCQCGL1dSub::PYvelocityReq) .def("stab", &pyCQCGL1dSub::PYstab) .def("stabReq", &pyCQCGL1dSub::PYstabReq) .def("phaseRotate", &pyCQCGL1dSub::PYphaseRotate) .def("phaseTangent", &pyCQCGL1dSub::PYphaseTangent) ; } <file_sep>/* to comiple: * first use * mpicxx --showme -O3 test_CQCGL1dReq_mpi.cc -L../../lib -I../../include -I$EIGEN -std=c++11 -lCQCGL1dReq -lCQCGL1d -lsparseRoutines -ldenseRoutines -literMethod -lmyH5 -lmyfft -lfftw3 -lm * to get the actual linkages. Then change g++ to h5c++ * * h5c++ -O3 test_CQCGL1dReq_mpi.cc -L../../lib -I../../include -I/usr/local/home/xiong/apps/eigen/include/eigen3 -std=c++11 -lCQCGL1dReq -lCQCGL1d -lsparseRoutines -ldenseRoutines -literMethod -lmyH5 -lmyfft -lfftw3 -lm -I/usr/lib/openmpi/include -I/usr/lib/openmpi/include/openmpi -pthread -L/usr//lib -L/usr/lib/openmpi/lib -lmpi_cxx -lmpi -ldl -lhwloc * * execute : mpiexec -np 4 ./a.out */ #include "CQCGL1dReq.hpp" #include <iostream> #include <fstream> #include <Eigen/Dense> #include <complex> #include <H5Cpp.h> #include <mpi.h> using namespace std; using namespace Eigen; using namespace denseRoutines; typedef std::complex<double> dcp; #define N30 int main(int argc, char **argv){ #ifdef N10 //====================================================================== // extend the soliton solution in the Bi-Gi plane iterMethod::LM_OUT_PRINT = false; iterMethod::LM_IN_PRINT = false; iterMethod::CG_PRINT = false; const int N = 1024; const int L = 50; double Bi = 3.4; double Gi = -5.6; CQCGL1dReq cgl(N, L, -0.1, 0.125, 0.5, 1, Bi, -0.1, Gi, 0); string fileName = "../../data/cgl/reqBiGi"; double stepB = 0.1; int NsB = 24; //////////////////////////////////////////////////////////// // mpi part MPI_Init(&argc, &argv); int rank, num; MPI_Comm_rank(MPI_COMM_WORLD, &rank); MPI_Comm_size(MPI_COMM_WORLD, &num); int inc = NsB / num; int rem = NsB - inc * num; int p_size = inc + (rank < rem ? 1 : 0); int p_start = inc*rank + (rank < rem ? rank : rem); int p_end = p_start + p_size; fprintf(stderr, "MPI : %d / %d; range : %d - %d \n", rank, num, p_start, p_end); //////////////////////////////////////////////////////////// H5File file(fileName + "_" + to_string(rank) + ".h5", H5F_ACC_RDWR); int ids[] = {1, 2}; for (int i = 0; i < 2; i++){ int id = ids[i]; // cgl.findReqParaSeq(file, id, stepB, NsB, true); for (int i = p_start; i < p_end; i++){ cgl.Bi = Bi+i*stepB; cgl.findReqParaSeq(file, id, 0.1, 53, false); } } //////////////////////////////////////////////////////////// MPI_Finalize(); //////////////////////////////////////////////////////////// #endif #ifdef N20 //====================================================================== // try to calculate the eigenvalue and eigenvector const int N = 1024; const int L = 50; double Bi = 5.7; double Gi = -5.6; CQCGL1dReq cgl(N, L, -0.1, 0.125, 0.5, 1, Bi, -0.1, Gi, 0); // string file = "/usr/local/home/xiong/00git/research/data/cgl/reqBiGiEV.h5"; string fileName = "../../data/cgl/reqBiGiEV_add_"; ArrayXd a0; double wth0, wphi0, err0; VectorXcd e; MatrixXcd v; std::vector<double> Bis, Gis; for(int i = 0; i < 55; i++) Gis.push_back(Gi+0.1*i); int NsB = 23; //////////////////////////////////////////////////////////// // mpi part MPI_Init(&argc, &argv); int rank, num; MPI_Comm_rank(MPI_COMM_WORLD, &rank); MPI_Comm_size(MPI_COMM_WORLD, &num); int inc = NsB / num; int rem = NsB - inc * num; int p_size = inc + (rank < rem ? 1 : 0); int p_start = inc*rank + (rank < rem ? rank : rem); int p_end = p_start + p_size; for (int i = p_start; i < p_end; i++) Bis.push_back(Bi-0.1*i); fprintf(stderr, "MPI : %d / %d; range : %d - %d \n", rank, num, p_start, p_end); //////////////////////////////////////////////////////////// H5File file(fileName + to_string(rank) + ".h5", H5F_ACC_RDWR); cgl.calEVParaSeq(file, std::vector<int>{1, 2}, Bis, Gis, true); //////////////////////////////////////////////////////////// MPI_Finalize(); //////////////////////////////////////////////////////////// #endif #ifdef N30 //====================================================================== // try to calculate the eigenvalue and eigenvector. Parallel for Gi. const int N = 1024; const int L = 50; double Bi = 3.6; double Gi = -5.6; CQCGL1dReq cgl(N, L, -0.1, 0.125, 0.5, 1, Bi, -0.1, Gi, 0); // string file = "/usr/local/home/xiong/00git/research/data/cgl/reqBiGiEV.h5"; string fileName = "../../data/cgl/reqBiGiEV_add_"; ArrayXd a0; double wth0, wphi0, err0; VectorXcd e; MatrixXcd v; std::vector<double> Bis, Gis; Bis.push_back(Bi); int NsG = 55; //////////////////////////////////////////////////////////// // mpi part MPI_Init(&argc, &argv); int rank, num; MPI_Comm_rank(MPI_COMM_WORLD, &rank); MPI_Comm_size(MPI_COMM_WORLD, &num); int inc = NsG / num; int rem = NsG - inc * num; int p_size = inc + (rank < rem ? 1 : 0); int p_start = inc*rank + (rank < rem ? rank : rem); int p_end = p_start + p_size; for (int i = p_start; i < p_end; i++) Gis.push_back(Gi+0.1*i); fprintf(stderr, "MPI : %d / %d; range : %d - %d \n", rank, num, p_start, p_end); //////////////////////////////////////////////////////////// H5File file(fileName + to_string(rank) + ".h5", H5F_ACC_RDWR); cgl.calEVParaSeq(file, std::vector<int>{1, 2}, Bis, Gis, true); //////////////////////////////////////////////////////////// MPI_Finalize(); //////////////////////////////////////////////////////////// #endif return 0; } <file_sep>/* compile command: * mex CXXFLAGS='-std=c++0x -fPIC -O3' veToSlice.cc ../ksint.cc -I../../../include -I$XDAPPS/eigen/include/eigen3 -lfftw3 * * usage : * >> vep = veToSlice(ve, aa(:,i) ); * */ #include "ksint.hpp" #include "mex.h" #include <cmath> #include <cstring> #include <cassert> #include <Eigen/Dense> using namespace Eigen; /* transform trajectory into 1st mode slice */ static MatrixXd veToSlice(double *ve, double *x, const int N, const int M){ KS ks(N+2); Map<MatrixXd> aa2(ve, N, M); Map<VectorXd> x2(x, N); return ks.veToSlice(aa2, x2); } void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[]){ // get the pointer and the size of input double *aa = mxGetPr(prhs[0]); double *x = mxGetPr(prhs[1]); mwSize N = mxGetM(prhs[0]); mwSize M = mxGetN(prhs[0]); mwSize N2 = mxGetM(prhs[1]); mwSize M2 = mxGetN(prhs[1]); assert(N == N2 && M2 = 1); plhs[0] = mxCreateDoubleMatrix(N, M, mxREAL); MatrixXd vep = veToSlice(aa, x, N, M); memcpy(mxGetPr(plhs[0]), &vep(0,0), N*M*sizeof(double)); } <file_sep>/** \mainpage some frequently used dense matrix related routines * * \section sec_intro Introduction * \section sec_use usage * Example: * \code * g++ yourfile.cc /path/to/denseRoutines.cc -I/path/to/sparseRoutines.hpp -I/path/to/eigen -std=c++0x * \endcode */ #ifndef DENSEROUTINES_H #define DENSEROUTINES_H #include <Eigen/Dense> #include <vector> #include <iostream> #include <fstream> namespace denseRoutines { using namespace std; using namespace Eigen; double angleSubspace(const Ref<const MatrixXd> &A, const Ref<const MatrixXd> &B); double angleSpaceVector(const Ref<const MatrixXd> &Q, const Ref<const VectorXd> &V); std::vector< std::pair<double, int> > findMarginal(const Ref<const VectorXd> &Exponent, const int k = 2 ); MatrixXi indexSubspace(const Ref<const VectorXd> &RCP, const Ref<const VectorXd> &Exponent); std::pair<MatrixXi, MatrixXi> subspBound(const MatrixXi subspDim, const MatrixXi ixSp); void normc(MatrixXd &A); std::vector<int> csort(const VectorXcd &e, int flag); MatrixXcd vr2vc(const VectorXcd &e, const Ref<const MatrixXd> &v); MatrixXd vc2vr(const Ref<const MatrixXcd> &v); VectorXcd eEig(const MatrixXd &A, int flag); MatrixXcd vEig(const MatrixXd &A, int flag); std::pair<VectorXcd, MatrixXcd> evEig(const MatrixXd &A, int flag); VectorXd centerRand(const int N, const double frac); MatrixXd realv(const MatrixXcd &v); MatrixXd orthAxes(const Ref<const MatrixXd> &v); MatrixXd orthAxes(const Ref<const VectorXd> &e1, const Ref<const VectorXd> &e2); MatrixXd orthAxes(const Ref<const VectorXd> &e1, const Ref<const VectorXd> &e2, const Ref<const VectorXd> &e3); VectorXd spacing(const Ref<const MatrixXd> &v); int minDisIndex(const Ref<const VectorXd> &a, const Ref<const MatrixXd> &v, double &minD); int minDisIndex(const Ref<const VectorXd> &a, const Ref<const MatrixXd> &v); std::pair<MatrixXd, MatrixXd> GS(const Ref<const MatrixXd> &A); MatrixXd GSsimple(const Ref<const MatrixXd> &A); std::pair<MatrixXd, MatrixXd> QR(const Ref<const MatrixXd> &A); MatrixXd randM(int M, int N); MatrixXcd loadComplex(const std::string f1, const std::string f2); ArrayXXd calPhase(const Ref<const ArrayXXcd> &AA); /////////////////////////// template or inline function implementation //////////////////////////////////////////////////////////////////////////////////// /** @brief save a matrix into a text file */ inline void savetxt(const std::string f, const Ref<const MatrixXd> &A){ ofstream file(f, ios::trunc); file.precision(16); file << A << endl; file.close(); } /** @brief read data from text file */ template<class T = double> Matrix<T, Dynamic, Dynamic> loadtxt(const std::string f){ int cols = 0; int rows = 0; std::vector<T> buff; buff.reserve(1000); ifstream infile(f); assert(!infile.fail()); while (! infile.eof()) { string line; std::getline(infile, line); int temp_cols = 0; stringstream stream(line); while(!stream.eof()){ T x; stream >> x; buff.push_back(x); temp_cols++; } if (rows == 0) cols = temp_cols; else if (temp_cols != cols) break; rows++; } infile.close(); Matrix<T, Dynamic, Dynamic> result(rows, cols); for (int i = 0; i < rows; i++) for (int j = 0; j < cols; j++) result(i, j) = buff[ cols*i+j]; return result; } /* @brief create 2d centerized random variables */ inline MatrixXcd center2d(const int M, const int N, const double f1, const double f2){ MatrixXcd a(M, N); a.real() = MatrixXd::Random(M, N)*0.5+0.5*MatrixXd::Ones(M, N); a.imag() = MatrixXd::Random(M, N)*0.5+0.5*MatrixXd::Ones(M, N); int M2 = (int) (0.5 * M * (1-f1)); int N2 = (int) (0.5 * N * (1-f2)); a.topRows(M2) = MatrixXcd::Zero(M2, N); a.bottomRows(M2) = MatrixXcd::Zero(M2, N); a.leftCols(N2) = MatrixXcd::Zero(M, N2); a.rightCols(N2) = MatrixXcd::Zero(M, N2); return a; } /** @brief Gaussian profile * * $f(x) = a exp(\frac{-(x-b)^2}{2 c^2})$ */ inline VectorXcd Gaussian(const int N, const int b, const double c, const double a = 1){ ArrayXd dx = ArrayXd::LinSpaced(N, 0, N-1) - b; VectorXd f = (- dx.square() / (2*c*c)).exp() * a; return f.cast<std::complex<double>>(); } /** @brief 2d Gaussian profile * * $f(x, y) = a exp(\frac{-(x-b_1)^2}{2 c_1^2} + \frac{-(y-b_2)^2}{2 c_2^2})$ * The rectangle size is [M x N] corresponding to y and x direction. */ inline MatrixXcd Gaussian2d(const int M, const int N, const int b1, const int b2, const double c1, const double c2, const double a = 1){ MatrixXd dx = (VectorXd::LinSpaced(N, 0, N-1)).replicate(1, M).transpose() - MatrixXd::Constant(M, N, b1); MatrixXd dy = (VectorXd::LinSpaced(M, 0, M-1)).replicate(1, N) - MatrixXd::Constant(M, N, b2); MatrixXd d = dx.array().square() / (2*c1*c1) + dy.array().square() / (2*c2*c2); MatrixXd f = (-d).array().exp() * a; return f.cast<std::complex<double>>(); } inline MatrixXcd soliton(const int M, const int N, const int x, const int y, const double a, const double b){ MatrixXd dx = (VectorXd::LinSpaced(M, 0, M-1)).replicate(1, N) - MatrixXd::Constant(M, N, x); MatrixXd dy = (VectorXd::LinSpaced(N, 0, N-1)).replicate(1, M).transpose() - MatrixXd::Constant(M, N, y); MatrixXd d = (dx.array() / M / a).square() + (dy.array() / N / b).square(); return (-d).array().exp().cast<std::complex<double>>(); } inline MatrixXcd solitons(const int M, const int N, const VectorXd xs, const VectorXd ys, const VectorXd as, const VectorXd bs){ int n = xs.size(); MatrixXcd A(MatrixXcd::Zero(M, N)); for (int i = 0; i < n; i++){ A += soliton(M, N, xs(i), ys(i), as(i), bs(i)); } return A; } inline MatrixXcd solitonMesh(const int M, const int N, const int nx, const int ny, const double a){ MatrixXd px = (VectorXd::LinSpaced(nx, M/nx/2, M-1-M/nx/2)).replicate(1, ny); MatrixXd py = (VectorXd::LinSpaced(ny, N/ny/2, N-1-N/ny/2)).replicate(1, nx).transpose(); px.resize(nx*ny, 1); py.resize(nx*ny, 1); VectorXd as = VectorXd::Constant(nx*ny, a); return solitons(M, N, px, py, as, as); } /** create a matrix with designed eigenvalues. * A V = V E */ inline MatrixXd matE(const VectorXd &e){ int n = e.size(); MatrixXd V(MatrixXd::Random(n, n)); return V * e.asDiagonal() * V.inverse(); } } #endif // DENSEROUTINES_H <file_sep>from cglHelp import * from matplotlib import rc rc('font',**{'family':'serif','serif':['Times']}) # I love Times rc('text', usetex=True) import matplotlib.gridspec as gridspec case = 240 if case == 15: """ same as case 10, bu plot contourf plot Note: the problem of contourf() is that whenever there is a jump in the levels, say from lv1 to lv2 but lv2 = lv1 + 2, then it will interpolate these two levels, thus a line for lv1 + 1 is plotted between these two regions. I need to draw each region indivisually. """ saveData = np.loadtxt("BiGiReqStab.dat") BiRange = [-3.2, 3.5] GiRange = [-5.6, -0.5] inc = 0.1 nx = np.int(np.rint( (BiRange[1] - BiRange[0])/inc ) + 1) ny = np.int(np.rint( (GiRange[1] - GiRange[0])/inc ) + 1) x = np.linspace(BiRange[0], BiRange[1], nx) y = np.linspace(GiRange[0], GiRange[1], ny) X, Y = np.meshgrid(x, y) Z = np.zeros([ny, nx]) - 1 # initialized with -1 for item in saveData: Gi, Bi, m = item idx = np.int(np.rint((Bi - BiRange[0]) / inc)) idy = np.int(np.rint((Gi - GiRange[0]) / inc)) if idx >= 0 and idx < nx and idy >= 0 and idy < ny: Z[idy, idx] = m if m < 8 else 8 levels = [-1, 0, 2, 4, 6, 8] cs = ['w', 'm', 'c', 'grey', 'r', 'y'] fig, ax = pl2d(size=[8, 6], labs=[r'$\beta_i$', r'$\gamma_i$'], axisLabelSize=30, tickSize=25) for i in range(len(levels)): vfunc = np.vectorize(lambda t : 0 if t == levels[i] else 1) Z2 = vfunc(Z) ax.contourf(X, Y, Z2, levels=[-0.1, 0.9], colors=cs[i]) # add zoom rectangle BiZoom = [1.9, 3.5] GiZoom = [-5.6, -4] ax.plot([BiZoom[0], BiZoom[0]], [GiZoom[0], GiZoom[1]], ls='--', lw=3, c='k') ax.plot([BiZoom[1], BiZoom[1]], [GiZoom[0], GiZoom[1]], ls='--', lw=3, c='k') ax.plot([BiZoom[0], BiZoom[1]], [GiZoom[0], GiZoom[0]], ls='--', lw=3, c='k') ax.plot([BiZoom[0], BiZoom[1]], [GiZoom[1], GiZoom[1]], ls='--', lw=3, c='k') ax.text(0, -2, r'$S$', fontsize=30) ax.text(0, -4.5, r'$U_1$', fontsize=30) ax.text(1.8, -2.5, r'$U_2$', fontsize=30) ax.text(2., -4.8, r'$U_3$', fontsize=30) ax.text(2.7, -3, r'$U_{\geq 4}$', fontsize=30) #ax.scatter(2.0,-5, c='k', s=100, edgecolor='none') #ax.scatter(2.7,-5, c='k', s=100, edgecolor='none') ax.scatter(0.8, -0.6, c='k', s=100, edgecolor='none') ax.scatter(1.4,-3.9, c='k', marker='*', s=200, edgecolor='none') ax.set_xlim(BiRange) ax.set_ylim(GiRange) ax.set_xticks(range(-3, 4)) ax2d(fig, ax) if case == 60: """ plot the stability table of the rpos """ N, d = 1024, 50 fileName = '../../data/cgl/rpoBiGiEV.h5' cs = {0: 'g'}#, 10: 'm', 2: 'c', 4: 'r', 6: 'b', 8: 'y'}#, 56: 'r', 14: 'grey'} ms = {0: 's'}#, 10: '^', 2: '+', 4: 'o', 6: 'D', 8: 'v'}#, 56: '4', 14: 'v'} fig, ax = pl2d(size=[8, 6], labs=[r'$\beta_i$', r'$\gamma_i$'], axisLabelSize=30, tickSize=25, ylim=[-5.65, -3.95], xlim=[1.8, 5.8]) for i in range(39): Bi = 1.9 + i*0.1 for j in range(55): Gi = -5.6 + 0.1*j rpo = CQCGLrpo() if rpo.checkExist(fileName, rpo.toStr(Bi, Gi, 1) + '/er'): x, T, nstp, th, phi, err, e, v = rpo.read(fileName, rpo.toStr(Bi, Gi, 1), flag=2) m, ep, accu = numStab(e, nmarg=3, tol=1e-4, flag=1) ax.scatter(Bi, Gi, s=60, edgecolors='none', marker=ms.get(m, 'o'), c=cs.get(m, 'r')) # add zoom rectangle BiZoom = [1.9, 3.5] GiZoom = [-5.6, -4] ax.plot([BiZoom[1], BiZoom[1]], [GiZoom[0], GiZoom[1]], ls='--', lw=3, c='k') ax.plot([BiZoom[0], BiZoom[0]], [GiZoom[0], GiZoom[1]], ls='--', lw=3, c='k') ax.plot([BiZoom[0], BiZoom[1]], [GiZoom[0], GiZoom[0]], ls='--', lw=3, c='k') ax.plot([BiZoom[0], BiZoom[1]], [GiZoom[1], GiZoom[1]], ls='--', lw=3, c='k') # ax.plot([BiZoom[0], BiZoom[1]], [GiZoom[1], GiZoom[1]], ls='--', lw=3, c='k') #ax.xaxis.set_minor_locator(AutoMinorLocator(10)) #ax.yaxis.set_minor_locator(AutoMinorLocator(10)) #ax.grid(which='major', linewidth=2) #ax.grid(which='minor', linewidth=1) ax.scatter(4.6, -5.0, c='k', s=200, edgecolor='none') ax.scatter(4.8, -4.5, c='k', marker='*', s=400, edgecolor='none') ax.set_yticks([-4, -4.5, -5, -5.5]) ax.set_xticks(np.arange(2, 6, 0.5)) ax2d(fig, ax) if case == 90: """ plot the two coexisting soltions for the same paramter in the same figure load saved data """ N, d = 1024, 50 fig, ax = pl2d(size=[8, 6], labs=[r'$x$', r'$|A|$'], axisLabelSize=30, tickSize=25) Bi, Gi = 0.8, -0.6 profiles = np.load('solitonProfileFor08n06.npz') absA1, absA2 = profiles['absA1'], profiles['absA2'] ax.plot(np.linspace(0, d, absA1.shape[0]), absA1, lw=2, ls='-', c='r') ax.plot(np.linspace(0, d, absA2.shape[0]), absA2, lw=2, ls='--', c='b') ax2d(fig, ax) if case == 76: """ plot one Hopf bifurcation using save data subplot (a) : heat map of the limit cycle subplot (b) : symmetry-reduced state space figure """ N, d = 1024, 50 data = np.load('hopfCycleAndWuOfReq.npz') hopfCycleProfiles4Periods, T, aaP, aapP = data['hopfCycleProfiles4Periods'], data['T'], data['aaP'], data['aapP'] # plot figure fig = plt.figure(figsize=[8, 4]) nx, ny = 8, 4 gs = gridspec.GridSpec(nx, ny) ax = fig.add_subplot(gs[:nx-1, 0]) ax.text(0.1, 0.9, '(a)', horizontalalignment='center', transform=ax.transAxes, fontsize=18, color='white') ax.set_xlabel(r'$x$', fontsize=25) ax.set_ylabel(r'$t$', fontsize=25) ax.set_xticks(range(0, 60, 10)) ax.set_yticks(range(0, 16, 3)) ax.tick_params(axis='both', which='major', labelsize=15) im = ax.imshow(hopfCycleProfiles4Periods, cmap=plt.get_cmap('jet'), extent=[0, d, 0, 4*T], aspect='auto', origin='lower') # ax.grid('on') dr = make_axes_locatable(ax) cax =dr.append_axes('right', size='5%', pad=0.05) cb = plt.colorbar(im, cax=cax, ticks=np.arange(0, 2, 0.4)) cb.ax.tick_params(labelsize=15) ax = fig.add_subplot(gs[:, 1:], projection='3d') ax.text2D(0.1, 0.9, '(b)', horizontalalignment='center', transform=ax.transAxes, fontsize=18) ax.set_xlabel(r'$v_1$', fontsize=25) ax.set_ylabel(r'$v_2$', fontsize=25) ax.set_zlabel(r'$v_3$', fontsize=25) # ax.set_xlim([-20, 20]) # ax.set_ylim([0, 250]) # ax.set_zlim([-30, 30]) ax.tick_params(axis='both', which='major', labelsize=15) ax.locator_params(nbins=4) # ax.scatter(a0H[], a0H[4], a0H[5], c='r', s=40) # ax.plot(aaH[:, -1], aaH[:, 4], aaH[:, 5], c='b', lw=1, alpha=0.7) # ax.plot(aapH[:, -1], aapH[:, 4], aapH[:, 5], c='r', lw=2) ax.scatter(0, 0, 0, c='r', s=40) ax.plot(aaP[:, 0], aaP[:, 1], aaP[:, 2], c='b', lw=1, alpha=0.7) ax.plot(aapP[:, 0], aapP[:, 1], aapP[:, 2], c='r', lw=2) fig.tight_layout(pad=0) plt.show(block=False) if case == 150: """ plot the example explosions using loaded data """ N, d = 1024, 50 data = np.load('explosionExample08n06.npz') Aamp1 = data['AampSymmetric'] T1 = data['Tsymmetric'] Aamp2 = data['AampAsymmetric'] T2 = data['Tasymmetric'] # plot the figure fig = plt.figure(figsize=[8, 5]) ax = fig.add_subplot(121) ax.text(0.1, 0.9, '(a)', horizontalalignment='center', transform=ax.transAxes, fontsize=30, color='white') ax.set_xlabel(r'$x$', fontsize=30) ax.set_ylabel(r'$t$', fontsize=30) ax.set_xticks(range(0, 60, 10)) ax.set_yticks(range(0, 12, 2)) ax.tick_params(axis='both', which='major', labelsize=20) im = ax.imshow(Aamp1, cmap=plt.get_cmap('jet'), extent=[0, d, 0, T1], aspect='auto', origin='lower') # ax.grid('on') dr = make_axes_locatable(ax) cax =dr.append_axes('right', size='5%', pad=0.05) cb = plt.colorbar(im, cax=cax, ticks=np.arange(0, 4, 1)) cb.ax.tick_params(labelsize=20) ax = fig.add_subplot(122) ax.text(0.1, 0.9, '(b)', horizontalalignment='center', transform=ax.transAxes, fontsize=30, color='white') ax.set_xlabel(r'$x$', fontsize=30) ax.set_ylabel(r'$t$', fontsize=30) ax.set_xticks(range(0, 60, 10)) ax.set_yticks(range(0, 12, 2)) ax.tick_params(axis='both', which='major', labelsize=20) im = ax.imshow(Aamp2, cmap=plt.get_cmap('jet'), extent=[0, d, 0, T2], aspect='auto', origin='lower') # ax.grid('on') dr = make_axes_locatable(ax) cax =dr.append_axes('right', size='5%', pad=0.05) cb = plt.colorbar(im, cax=cax, ticks=np.arange(0, 4, 1)) cb.ax.tick_params(labelsize=20) fig.tight_layout(pad=0) plt.show(block=False) if case == 200: """ print out the eigen exponents of Hopt RPO """ Bi, Gi = 1.4, -3.9 rpo = CQCGLrpo() x, T, nstp, th, phi, err, e, v = rpo.read('../../data/cgl/rpoHopfBiGi.h5', rpo.toStr(Bi, Gi, 1), flag=2) mu = np.log(np.abs(e)) / T theta = np.arctan2(e.imag, e.real) if case == 220: """ print out the eigen exponents of rpos """ rpo = CQCGLrpo() Bi, Gi = (4.6, -5.0) if False else (4.8, -4.5) x, T, nstp, th, phi, err, e, v = rpo.read('../../data/cgl/rpoBiGiEV.h5', rpo.toStr(Bi, Gi, 1), flag=2) mu = np.log(np.abs(e)) / T theta = np.arctan2(e.imag, e.real) if case == 240: """ plot the stability exponent diagram """ req = CQCGLreq() Bi, Gi = 0.8, -0.6 a0, wth0, wphi0, err0, e, v = req.read('../../data/cgl/reqBiGiEV.h5', req.toStr(Bi, Gi, 1), flag=2) def Lam(k): return -0.1 - (0.125 + 0.5j) * (2*np.pi/50 * k)**2 # Lam = lambda k : -0.1 - (0.125 + 0.5j) * (2*np.pi/50 * k)**2 M = (e.shape[0] - 2 ) / 4 x = [0, 0] for i in range(1, M+1): x = x + [i]*4 x = np.array(x) e_thresh = 180 eip = -np.abs(e.imag) eip[:e_thresh] *= -1 fig = plt.figure(figsize=[8, 6]) ax = fig.add_subplot(111) ax.tick_params(axis='x', which='major', labelsize=22) ax.set_xlabel(r'$k$', fontsize=30) ax.tick_params(axis='y', which='major', colors='r', labelsize=22) ax.set_ylabel(r'$\mu^{(j)}$', color='r', fontsize=30) ax.scatter(x, e.real, s=10, facecolors='none', edgecolors='r') ax.plot(x, Lam(x).real, c='y', ls='--', lw=2) ax.set_ylim([-250, 50]) ax2 = ax.twinx() ax2.tick_params(axis='y', which='major', colors='b', labelsize=22) ax2.set_ylabel(r'$\omega^{(j)}$', color='b', fontsize=30) ax2.scatter(x, eip, s=10, facecolors='none', edgecolors='b') ax2.plot(x, Lam(x).imag, c='k', ls='--', lw=2) ax2.set_ylim([-1200, 50]) # Plot insert x = x[:200] e = e[:200] eip = eip[:200] axInsert = plt.axes([.23, .25, .32, .32]) axInsert.tick_params(axis='x', which='major', labelsize=18) axInsert.set_xlabel(r'$k$', fontsize=25) axInsert.tick_params(axis='y', which='major', colors='r', labelsize=18) axInsert.scatter(x, e.real, s=10, facecolors='none', edgecolors='r') axInsert.plot(x, Lam(x).real, c='y', ls='--', lw=3) axInsert2 = axInsert.twinx() axInsert2.tick_params(axis='y', which='major', colors='b', labelsize=18) axInsert2.scatter(x, eip, s=10, facecolors='none', edgecolors='b') axInsert2.plot(x, Lam(x).imag, c='k', ls='--', lw=3) axInsert2.set_ylim([-30, 20]) # END ax2d(fig, ax) # fig, ax = pl2d(size=[8, 6], labs=[r'$j$', r'$\omega^{(j)}$'], axisLabelSize=30, tickSize=25) # ax.scatter(x, np.abs(e.imag), c='r', s=10) # #ax.plot(x, np.abs(e.imag)) # ax.plot(x, np.abs(Lam(x).imag), c='b', ls='--', lw=2) # ax2d(fig, ax) if case == 250: """ test of case 240 """ req = CQCGLreq() Bi, Gi = 0.8, -0.6 a0, wth0, wphi0, err0, e, v = req.read('../../data/cgl/reqBiGiEV.h5', req.toStr(Bi, Gi, 1), flag=2) def Lam(k): return -0.1 - (0.125 + 0.5j) * (2*np.pi/50 * k)**2 M = (e.shape[0] - 2 ) / 4 x = [0, 0] for i in range(1, M+1): x = x + [i]*4 x = np.array(x) e_thresh = 180 eip = -np.abs(e.imag) eip[:e_thresh] *= -1 x = x[200:300] e = e[200:300] eip = eip[200:300] fig = plt.figure(figsize=[8, 6]) ax = fig.add_subplot(111) ax.tick_params(axis='x', which='major', labelsize=25) ax.set_xlabel(r'$k$', fontsize=30) ax.tick_params(axis='y', which='major', colors='r', labelsize=25) ax.set_ylabel(r'$\mu^{(j)}$', color='r', fontsize=30) ax.scatter(x, e.real, s=10, facecolors='none', edgecolors='r') ax.plot(x, Lam(x).real, c='k', ls='--', lw=2) # ax2 = ax.twinx() # ax2.tick_params(axis='y', which='major', colors='b', labelsize=25) # ax2.set_ylabel(r'$\omega^{(j)}$', color='b', fontsize=30) # ax2.scatter(x, eip, s=10, facecolors='none', edgecolors='b') # ax2.plot(x, Lam(x).imag, c='k', ls='--', lw=2) # ax2.set_ylim([-1200, 50]) # END ax2d(fig, ax) <file_sep>#!/bin/bash # usage: # ./createAll DEST=/usr/local/home/xiong/00git/research/lib/boostPython/ rm -rf bin pylib b2 && mv pylib/py_CQCGL1dEIDc.so $DEST && rm -rf bin pylib <file_sep>import matplotlib.pyplot as plt import numpy as np import scipy.io as sio from mpl_toolkits.mplot3d import Axes3D from scipy.interpolate import interp1d; fig=plt.figure(figsize=(8,5)) ax=fig.add_subplot(111) pp = sio.loadmat('./ppo4/angAver.mat'); dis = pp['x'][:,0]; ang = pp['angleAverage']; logDis = np.linspace(np.log10(dis[0]), np.log10(dis[-1]), 100) Ncol = 9 # ang.shape[1]; cix = [0, 1, 2, 3, 4, 6, 8, 9, 10] spix = [3, 4, 5, 6, 7, 9, 13, 15, 21] colors = ['b','g', 'm','c', 'r', 'DarkGreen', 'Brown', 'Purple', 'Navy'] ############################################## for i in range(Ncol): f = interp1d(np.log10(dis), np.log10(ang[:,cix[i]])) ax.plot(10**logDis, 10**(f(logDis)), c = colors[i], ls = '--' ); ax.scatter(dis, ang[:,cix[i]], s=30, c = colors[i], edgecolor='none', label='1-'+str(spix[i])) if i < 6: ax.text(dis[0]-0.0005, ang[0, cix[i]], str(spix[i])) else : ax.text(dis[7], ang[7, cix[i]], str(spix[i])) ax.set_yscale('log') ax.set_xscale('log') #ax.legend(loc='upper left') #ax.set_title('(a)') ax.set_ylabel(r'$< \sin(\theta) >$',size='large') ax.set_xlabel(r'$||\Delta x||_2$',size='large') fig.tight_layout(pad=0) plt.show() <file_sep># My research C++ code This repository contains all my code for research at [Center for Nonliear Science](http://www.cns.gatech.edu/) at School of Physics in Georgia Institute of Technology. It is mainly C++ code and a few Python/Matlab bindings. Large datasets are not committed. ## folder structure * **source** C++ files and their Matlab/Python binding files * **include** header files * **lib** The shared/static library, compiled Matlab/Python binding library * **PythonWrapper** The Boost.Python bindings for C++ classes * **MatlabWrapper** The Matlab bindings for C++ functions ## Requirement * G++ 4.7 above (supporting C++11) * Eigen 3.1 or above * FFTW3 library * HDF5 If you need build python binding, you also need * [Boost.Python](http://www.boost.org/doc/libs/1_58_0/libs/python/doc/) * [Boost.NumPy](https://github.com/ndarray/Boost.NumPy) For Arpack++ support, you need * [arpackpp](https://github.com/m-reuter/arpackpp) <file_sep>from personalFunctions import * from py_ks import * from scipy.interpolate import interp1d from personalPlotly import * from ksInv22 import * ############################################################################### if __name__ == '__main__': reqFile = '../../data/ks22Reqx64.h5' poFile = '../../data/ks22h001t120x64EV.h5' case = 40 if case == 10: """ view the unstable manifold of eq/req """ inv = Inv(reqFile, poFile, 2, True, 3) nn = 30 aas, dom, jumps = inv.Es[2].getMu(vId=0, nn=nn, T=120) ii = [3, 7, 11] E2, E3 = inv.Es[1].go, inv.Es[2].go fig, ax = pl3d(labs=[r'$v_1$', r'$v_2$', r'$v_3$']) inv.plotRE(ax, ii) for i in range(nn): inv.plotFundOrbit(ax, aas[i], jumps[i], ii) # ax.plot(E2[:, ii[0]], E2[:, ii[1]], E2[:, ii[2]]) ax.plot(E3[:, ii[0]], E3[:, ii[1]], E3[:, ii[2]]) ax3d(fig, ax) if case == 20: """ view the unstable manifold of a single eq/req and one po/rpo This is done in Fourier projection space """ inv = Inv(reqFile, poFile, 2, True, 3, [], [1, 4]) nn = 30 aas, dom, jumps = inv.Es[1].getMu(vId=0, nn=nn, T=100) ii = [3, 7, 11] E2, E3 = inv.Es[1].go, inv.Es[2].go fig, ax = pl3d(labs=[r'$v_1$', r'$v_2$', r'$v_3$']) inv.plotRE(ax, ii) for i in range(nn): inv.plotFundOrbit(ax, aas[i], jumps[i], ii) cs = ['r', 'b'] for i in range(len(inv.rpos)): inv.plotFundOrbit(ax, inv.rpos[i].fdo, inv.rpos[i].jumps, ii, c='k' if i > 0 else cs[i], alpha=1, lw=1.5) #ax.plot(E2[:, ii[0]], E2[:, ii[1]], E2[:, ii[2]], c='c') ax.plot(E3[:, ii[0]], E3[:, ii[1]], E3[:, ii[2]], c='b') ax3d(fig, ax, angle=[50, 80]) if case == 30: """ same with 20 but to save figures """ inv = Inv(reqFile, poFile, 2, True, 3, [], []) nn = 30 aas, dom, jumps = inv.Es[1].getMu(vId=0, nn=nn, T=100) ii = [3, 7, 11] E2, E3 = inv.Es[1].go, inv.Es[2].go for k in range(2, 51): inv.rpoIds = [1, k] inv.loadPO() fig, ax = pl3d(labs=[r'$v_1$', r'$v_2$', r'$v_3$']) inv.plotRE(ax, ii) for i in range(nn): inv.plotFundOrbit(ax, aas[i], jumps[i], ii) for i in range(len(inv.rpos)): inv.plotFundOrbit(ax, inv.rpos[i].fdo, inv.rpos[i].jumps, ii, c='k' if i > 0 else 'r', alpha=1, lw=1.5, label='rpo'+str(inv.rpoIds[i])) ax.plot(E3[:, ii[0]], E3[:, ii[1]], E3[:, ii[2]], c='b') ax3d(fig, ax, angle=[50, 80], save=True, name='rpo'+str(k)+'.png') if case == 40: """ just try to have a look at the 3rd slice """ inv = Inv(reqFile, poFile, 3, True, 2, [], [1, 3]) nn = 30 aas, dom, jumps = inv.Es[2].getMu(vId=0, nn=nn, T=120) ii = [1, 3, 5] E2, E3 = inv.Es[1].go, inv.Es[2].go fig, ax = pl3d(labs=[r'$v_1$', r'$v_2$', r'$v_3$']) inv.plotRE(ax, ii) for i in range(nn): inv.plotFundOrbit(ax, aas[i], jumps[i], ii) cs = ['r', 'b'] for i in range(len(inv.rpos)): inv.plotFundOrbit(ax, inv.rpos[i].fdo, inv.rpos[i].jumps, ii, c='k' if i > 0 else cs[i], alpha=1, lw=1.5, label='rpo'+str(inv.rpoIds[i])) ax.plot(E2[:, ii[0]], E2[:, ii[1]], E2[:, ii[2]], c='c') #ax.plot(E3[:, ii[0]], E3[:, ii[1]], E3[:, ii[2]], c='b') ax3d(fig, ax, angle=[30, 120]) if case == 50: """ same with 40 but to save figures """ inv = Inv(reqFile, poFile, 3, True, 2, [], []) nn = 30 aas, dom, jumps = inv.Es[2].getMu(vId=0, nn=nn, T=120) ii = [1, 3, 5] E2, E3 = inv.Es[1].go, inv.Es[2].go for k in range(2, 51): inv.rpoIds = [1, k] inv.loadPO() fig, ax = pl3d(labs=[r'$v_1$', r'$v_2$', r'$v_3$']) inv.plotRE(ax, ii) for i in range(nn): inv.plotFundOrbit(ax, aas[i], jumps[i], ii) for i in range(len(inv.rpos)): inv.plotFundOrbit(ax, inv.rpos[i].fdo, inv.rpos[i].jumps, ii, c='k' if i > 0 else 'r', alpha=1, lw=1.5, label='rpo'+str(inv.rpoIds[i])) ax.plot(E2[:, ii[0]], E2[:, ii[1]], E2[:, ii[2]], c='c') ax3d(fig, ax, angle=[30, 120], save=True, name='rpo'+str(k)+'.eps', picForm='eps') if case == 14: """ save the symbolic dynamcis """ data = np.load('PoPoincare.npz') ppo = data['ppo'] rpo = data['rpo'] po = rpo poName = 'rpo' for i in range(len(po)): x, y, z = po[i][:, 0], po[i][:, 1], po[i][:, 2] fig, ax = pl3d(labs=[r'$v_1$', r'$v_2$', r'$v_3$']) ax.scatter(0, 0, 0, c='m', edgecolors='none', s=100, marker='^') for j in range(len(ppo)): p = ppo[j] ax.scatter(p[:, 0], p[:, 1], p[:, 2], c=[0, 0, 0, 0.2], marker='o', s=10, edgecolors='none') for j in range(len(rpo)): p = rpo[j] ax.scatter(p[:, 0], p[:, 1], p[:, 2], c=[0, 0, 0, 0.2], marker='o', s=10, edgecolors='none') ax.scatter(x[::2], y[::2], z[::2], c='r', marker='o', s=40, edgecolors='none') ax.scatter(x[1::2], y[1::2], z[1::2], c='b', marker='o', s=40, edgecolors='none') for j in range(po[i].shape[0]): ax.text(x[j], y[j], z[j], str(j+1), fontsize=20, color='g') s = poName + str(i+1) # ax3d(fig, ax, angle=[20, -120], save=True, name=s+'.png', title=s) ax3d(fig, ax, angle=[30, 180], save=True, name=s+'.png', title=s) if case == 15: """ visulaize the symmbolic dynamcis """ data = np.load('PoPoincare.npz') borderPtsP = data['borderPtsP'] pcN = data['pcN'] ncN = data['ncN'] M = len(borderPtsP) ii = [0, 1, 2] fig, ax = pl3d(size=[12, 10], labs=[r'$v_1$', r'$v_2$', r'$v_3$']) ax.scatter(0, 0, 0, c='k', s=70, edgecolors='none') for i in range(M): x, y, z = [borderPtsP[i][:, ii[0]], borderPtsP[i][:, ii[1]], borderPtsP[i][:, ii[2]]] ax.scatter(x, y, z, c=[0, 0, 0, 0.2], marker='o', s=10, edgecolors='none') ax3d(fig, ax) for i in range(100, 110): x, y, z = [borderPtsP[i][:, ii[0]], borderPtsP[i][:, ii[1]], borderPtsP[i][:, ii[2]]] add3d(fig, ax, x, y, z, maxShow=20) if case == 16: """ plot 3 cases together """ trace = [] trace.append(ptlyTrace3d([0], [0], [0], plotType=1, ms=7, mc='black')) ii = [0, 1, 2] fig, ax = pl3d(labs=[r'$v_1$', r'$v_2$', r'$v_3$']) ax.scatter(0, 0, 0, c='k', s=70, edgecolors='none') if True: borderPtsP = np.load('ErgodicPoincare.npy') ax.scatter(borderPtsP[:, ii[0]], borderPtsP[:, ii[1]], borderPtsP[:, ii[2]], c='r', s=20, edgecolors='none') trace.append(ptlyTrace3d(borderPtsP[:, ii[0]], borderPtsP[:, ii[1]], borderPtsP[:, ii[2]], plotType=1, ms=2, mc='red')) if True: borderPtsP = np.load('E2Poincare.npy') M = borderPtsP.shape[0] for i in range(M): ax.scatter(borderPtsP[i][:, ii[0]], borderPtsP[i][:, ii[1]], borderPtsP[i][:, ii[2]], c='b', marker='s', s=20, edgecolors='none') for i in range(M): trace.append(ptlyTrace3d(borderPtsP[i][:, ii[0]], borderPtsP[i][:, ii[1]], borderPtsP[i][:, ii[2]], plotType=1, ms=2, mc='blue')) if True: borderPtsP = np.load('PoPoincare.npy') M = borderPtsP.shape[0] for i in range(M): ax.scatter(borderPtsP[i][:, ii[0]], borderPtsP[i][:, ii[1]], borderPtsP[i][:, ii[2]], c='g', marker='o', s=20, edgecolors='none') for i in range(M): trace.append(ptlyTrace3d(borderPtsP[i][:, ii[0]], borderPtsP[i][:, ii[1]], borderPtsP[i][:, ii[2]], plotType=1, ms=2, mc='green')) ax3d(fig, ax) if True: ptly3d(trace, 'mixPoincare', off=True, labs=['$v_1$', '$v_2$', '$v_3$']) if case == 17: """ use the poincare section b2=0 and b2 from negative to positive for unstable manifold of E2. Note, the unstable manifold lives in the invariant subspace, which is also the poincare section border. """ nn = 50 pos, poDom, poJumps = inv.getMuEq('e', eId=1, vId=0, p=1, nn=nn, T=100) M = len(pos) borderPts = [] for i in range(M): borderPts.append(pos[i][::100, :]) data = np.load('bases.npz') Ori = data['Ori'] bases = data['bases'] borderPtsP = [] for i in range(M): p = (borderPts[i]-Ori).dot(bases.T) borderPtsP.append(p) ii = [0, 1, 2] fig, ax = pl3d(labs=[r'$v_1$', r'$v_2$', r'$v_3$']) ax.scatter(0, 0, 0, c='k', s=70, edgecolors='none') for i in range(M): ax.scatter(borderPtsP[i][:, ii[0]], borderPtsP[i][:, ii[1]], borderPtsP[i][:, ii[2]], c='b' if i < 50 else 'r', marker='o' if i < 50 else 's', s=20, edgecolors='none') ax3d(fig, ax) if False: trace = [] trace.append(ptlyTrace3d(0, 0, 0, plotType=1, ms=7, mc='black')) for i in range(M): trace.append(ptlyTrace3d(borderPtsP[i][:, ii[0]], borderPtsP[i][:, ii[1]], borderPtsP[i][:, ii[2]], plotType=1, ms=2, mc='red')) ptly3d(trace, 'E2Poincare', labs=['$v_1$', '$v_2$', '$v_3$']) spt = pos ii = [1, 5, 3] fig, ax = pl3d(labs=[r'$v_1$', r'$v_2$', r'$v_3$']) inv.plotRE(ax, ii) for i in range(nn): inv.plotFundOrbit(ax, spt[i], poJumps[i], ii) ax3d(fig, ax) # np.save('E2Poincare', borderPtsP) if case == 18: """ use the poincare section b2=0 and b2 from negative to positive for ergodic trajectories """ a0 = rand(N-2) aa = inv.ks.aintg(a0, 0.01, 100, 1) aa = inv.ks.aintg(aa[-1], 0.01, 6000, 1) raa, dids, ths = inv.ks.redO2f(aa, 1) jumps = getJumpPts(dids) borderIds, borderPts, pcN, ncN = inv.getPoinc(raa, dids, jumps) data = np.load('bases.npz') Ori = data['Ori'] bases = data['bases'] borderPtsP = (borderPts - Ori).dot(bases.T) ii = [0, 1, 2] x, y, z = [borderPtsP[:, ii[0]], borderPtsP[:, ii[1]], borderPtsP[:, ii[2]]] fig, ax = pl3d(labs=[r'$v_1$', r'$v_2$', r'$v_3$']) ax.scatter(0, 0, 0, c='k', s=70, edgecolors='none') ax.scatter(x, y, z, c='y', s=20, edgecolors='none') ax3d(fig, ax) add3d(fig, ax, x, y, z, maxShow=20) if False: trace = [] trace.append(ptlyTrace3d(0, 0, 0, plotType=1, ms=7, mc='black')) trace.append(ptlyTrace3d(borderPtsP[:, ii[0]], borderPtsP[:, ii[1]], borderPtsP[:, ii[2]], plotType=1, ms=2, mc='red')) ptly3d(trace, 'ErgodicPoincare', labs=['$v_1$', '$v_2$', '$v_3$']) # np.save('ErgodicPoincare', borderPtsP) if case == 19: """ use the poincare section b2=0 and b2 from negative to positive """ inv.loadPO(1, ppoIds=range(1, 101), rpoIds=range(1, 101)) # ptsId = inv.rpos[0].jumps[0] # Ori = inv.rpos[0].pp[0] # fe, fv, rfv, bases = inv.poFvPoinc('rpo', 1, ptsId, 1, [0, 3, 4], # reflect=True) ptsId = inv.rpos[1].jumps[1] Ori = inv.rpos[1].pp[1] fe, fv, rfv, bases = inv.poFvPoinc('rpo', 2, ptsId, 1, [0, 1, 4], reflect=False) inv.poPoincProject(bases, Ori) fig, ax = pl3d(labs=[r'$v_1$', r'$v_2$', r'$v_3$']) ax.scatter(0, 0, 0, c='k', s=70, edgecolors='none') for i in range(len(inv.ppos)): p = inv.ppos[i].ppp ax.scatter(p[:, 0], p[:, 1], p[:, 2], c='y', marker='o', s=20, edgecolors='none') for i in range(len(inv.rpos)): p = inv.rpos[i].ppp ax.scatter(p[:, 0], p[:, 1], p[:, 2], c='y', marker='o', s=20, edgecolors='none') ax3d(fig, ax) if True: trace = [] trace.append(ptlyTrace3d([0], [0], [0], plotType=1, ms=7, mc='black')) for i in range(len(inv.ppos)): p = inv.ppos[i].ppp trace.append(ptlyTrace3d(p[:, 0], p[:, 1], p[:, 2], plotType=1, ms=2, mc='red', mt='circle')) for i in range(len(inv.rpos)): p = inv.rpos[i].ppp trace.append(ptlyTrace3d(p[:, 0], p[:, 1], p[:, 2], plotType=1, ms=2, mc='red', mt='circle')) ptly3d(trace, 'PoPoincare', labs=['$v_1$', '$v_2$', '$v_3$']) if False: ii = [2, 6, 4] # ii = [1, 5, 3] fig, ax = pl3d(labs=[r'$v_1$', r'$v_2$', r'$v_3$']) for i in range(len(pos)): inv.plotFundOrbit(ax, pos[i], poJumps[i], ii, alpha=0.5) ax.scatter(borderPts[i][:, ii[0]], borderPts[i][:, ii[1]], borderPts[i][:, ii[2]], c='k') ax3d(fig, ax) np.savez_compressed('bases', Ori=Ori, bases=bases) inv.savePoPoincProject() if case == 25: """ view 2 shadowing orbits """ poIds = [[1, 26], range(4, 4)] pos, poDom, poJumps = inv.loadPO('../../data/ks22h001t120x64EV.h5', poIds, 1) ii = [1, 3, 2] fig, ax = pl3d(labs=[r'$v_1$', r'$v_2$', r'$v_3$']) for i in range(len(pos)): inv.plotFundOrbit(ax, pos[i], poJumps[i], ii, c='k' if i > 0 else 'r', alpha=1, lw=1.5) ax3d(fig, ax) if case == 200: """ visualize the unstable manifold of eq and req together """ nn = 10 MuE, MuTw = inv.getMuAll(1, nn=nn) ii = [1, 3, 5] cs = ['r', 'b', 'c', 'k', 'y'] fig, ax = pl3d(labs=[r'$v_1$', r'$v_2$', r'$v_3$']) inv.plotRE(ax, ii) for k in range(1, len(MuE)-3): for i in range(nn): inv.plotFundOrbit(ax, MuE[0][0][i], MuE[0][2][i], ii, c=cs[k]) E2, E3 = inv.Eg['E2'], inv.Eg['E3'] ax.plot(E2[:, ii[0]], E2[:, ii[1]], E2[:, ii[2]]) ax.plot(E3[:, ii[0]], E3[:, ii[1]], E3[:, ii[2]]) ax3d(fig, ax) if case == 400: """ watch an ergodic trajectory after reducing O2 symmetry """ N = 64 d = 22 ks = pyKS(N, d) req, ws, reqr, eq, eqr = loadRE('../../data/ks22Reqx64.h5', N) a0 = rand(N-2) * 0.1 aa = ks.aintg(a0, 0.001, 300, 1) raa, dids, ths = ks.redO2f(aa, 1) ii = [1, 2, 3] doProj = False if doProj: pev, bases = getBases(ks, 'eq', eq[1], [6, 7, 10]) paas = raa.dot(bases.T) reqr = reqr.dot(bases.T) eqr = eqr.dot(bases.T) paas -= eqr[1] reqr -= eqr[1] eqr -= eqr[1] ii = [0, 1, 2] fig, ax = pl3d(labs=[r'$v_1$', r'$v_2$', r'$v_3$']) plotRE(ax, reqr, eqr, ii) if doProj: ax.plot(paas[:, ii[0]], paas[:, ii[1]], paas[:, ii[2]], alpha=0.5) else: ax.plot(raa[:, ii[0]], raa[:, ii[1]], raa[:, ii[2]], alpha=0.5) ax3d(fig, ax) doMovie = False if doMovie: fig, ax = pl3d(labs=[r'$v_1$', r'$v_2$', r'$v_3$'], xlim=[-1, 0.4], ylim=[-0.6, 0.6], zlim=[-0.15, 0.15], isBlack=False) frame, = ax.plot([], [], [], c='gray', ls='-', lw=1, alpha=0.5) frame2, = ax.plot([], [], [], c='r', ls='-', lw=1.5, alpha=1) pts, = ax.plot([], [], [], 'co', lw=3) def anim(i): k = max(0, i-500) j = min(i, paas.shape[0]) frame.set_data(paas[:k, ii[0]], paas[:k, ii[1]]) frame.set_3d_properties(paas[:k, ii[2]]) frame2.set_data(paas[k:j, ii[0]], paas[k:j, ii[1]]) frame2.set_3d_properties(paas[k:j, ii[2]]) pts.set_data(paas[j, ii[0]], paas[j, ii[1]]) pts.set_3d_properties(paas[j, ii[2]]) ax.view_init(30, 0.5 * i) return frame, frame2, pts ani = animation.FuncAnimation(fig, anim, frames=paas.shape[0], interval=0, blit=False, repeat=False) # ax3d(fig, ax) ax.legend() fig.tight_layout(pad=0) # ani.save('ani.mp4', dpi=200, fps=30, extra_args=['-vcodec', 'libx264']) plt.show() if case == 500: """ view a collection of rpo and ppo """ N = 64 L = 22 ks = pyKS(N, L) req, ws, reqr, eq, eqr = loadRE('../../data/ks22Reqx64.h5', N) poIds = [[1]+range(1, 10), range(1, 10)] aas = loadPO('../../data/ks22h001t120x64EV.h5', poIds) ii = [1, 2, 3] # ii = [7, 8, 11] doProj = False if doProj: pev, bases = getBases(ks, 'eq', eq[1], [6, 7, 10]) reqr = reqr.dot(bases.T) eqr = eqr.dot(bases.T) paas = [] for i in range(len(aas)): paas.append(aas[i].dot(bases.T) - eqr[1]) reqr -= eqr[1] eqr -= eqr[1] ii = [0, 1, 2] fig, ax = pl3d(labs=[r'$v_1$', r'$v_2$', r'$v_3$']) plotRE(ax, reqr, eqr, ii) if doProj: for i in range(len(aas)): ax.plot(paas[i][:, ii[0]], paas[i][:, ii[1]], paas[i][:, ii[2]], alpha=0.2) ax.plot(paas[0][:, ii[0]], paas[0][:, ii[1]], paas[0][:, ii[2]], c='k', label=r'$rpo_{16.31}$') else: for i in range(len(aas)): ax.plot(aas[i][:, ii[0]], aas[i][:, ii[1]], aas[i][:, ii[2]], alpha=0.2) ax3d(fig, ax) if case == 60: """ view rpo/ppo pair one at a time """ N = 64 L = 22 h = 0.001 ks = pyKS(N, h, L) for i in range(1, 20): req, ws, reqr, eq, eqr = loadRE('../../data/ks22Reqx64.h5', N) poIds = [[1] + range(i, i+1), range(i, i+1)] aas = loadPO('../../data/ks22h001t120x64EV.h5', poIds) ii = [0, 3, 4] doProj = True if doProj: pev, bases = getBases(ks, 'eq', eq[1], [6, 7, 10]) # pev, bases = getBases(ks, 'eq', eq[0], [2, 3, 5]) # pev, bases = getBases(ks, 'req', req[0], [0, 1, 3], ws[0]) reqr = reqr.dot(bases.T) eqr = eqr.dot(bases.T) paas = [] for i in range(len(aas)): paas.append(aas[i].dot(bases.T) - eqr[1]) reqr -= eqr[1] eqr -= eqr[1] ii = [0, 1, 2] fig, ax = pl3d(labs=[r'$v_1$', r'$v_2$', r'$v_3$']) plotRE(ax, reqr, eqr, ii) if doProj: for i in range(1, len(aas)): ax.plot(paas[i][:, ii[0]], paas[i][:, ii[1]], paas[i][:, ii[2]], alpha=0.8) ax.plot(paas[0][:, ii[0]], paas[0][:, ii[1]], paas[0][:, ii[2]], c='k', ls='--', label=r'$rpo_{16.31}$') else: for i in range(len(aas)): ax.plot(aas[i][:, ii[0]], aas[i][:, ii[1]], aas[i][:, ii[2]], alpha=0.7) ax3d(fig, ax, doBlock=True) if case == 70: """ construct poincare section in ergodic trajectory """ N = 64 d = 22 h = 0.001 ks = pyKS(N, h, d) req, ws, reqr, eq, eqr = loadRE('../../data/ks22Reqx64.h5', N) pev, bases = getBases(ks, 'eq', eq[1], [6, 7, 10]) reqr = reqr.dot(bases.T) eqr = eqr.dot(bases.T) reqr -= eqr[1] x0 = eqr[1] paas, poinc, poincf = ergoPoinc(ks, bases, x0, 2*np.pi/6, 'n') eqr -= eqr[1] ii = [0, 1, 2] fig, ax = pl3d(labs=[r'$v_1$', r'$v_2$', r'$v_3$']) plotRE(ax, reqr, eqr, ii) ax.plot(paas[:, ii[0]], paas[:, ii[1]], paas[:, ii[2]], alpha=0.5) ax.scatter(poincf[:, 0], poincf[:, 1], poincf[:, 2]) ax3d(fig, ax) scatter2dfig(poinc[:, 1], poinc[:, 2], ratio='equal') if case == 80: """ construct poincare section with po """ N = 64 d = 22 h = 0.001 ks = pyKS(N, h, d) req, ws, reqr, eq, eqr = loadRE('../../data/ks22Reqx64.h5', N) pev, bases = getBases(ks, 'eq', eq[1], [6, 7, 10]) reqr = reqr.dot(bases.T) eqr = eqr.dot(bases.T) reqr -= eqr[1] x0 = eqr[1] i = 40 poIds = [range(1, i+1), range(1, i+1)] # poIds = [[], [2, 4, 8]] aas, poinc, nums = poPoinc('../../data/ks22h001t120x64EV.h5', poIds, bases, x0, 0.5 * np.pi/6, 'p') eqr -= eqr[1] ii = [0, 1, 2] fig, ax = pl3d(labs=[r'$v_1$', r'$v_2$', r'$v_3$']) plotRE(ax, reqr, eqr, ii) for i in range(1, len(aas)): ax.plot(aas[i][:, ii[0]], aas[i][:, ii[1]], aas[i][:, ii[2]], alpha=0.2) ax.plot(aas[0][:, ii[0]], aas[0][:, ii[1]], aas[0][:, ii[2]], c='k', ls='--', label=r'$rpo_{16.31}$') ax.scatter(poinc[:, 0], poinc[:, 1], poinc[:, 2]) ax3d(fig, ax) fig, ax = pl2d(labs=[r'$v_1$', r'$v_2$']) for i in range(1, len(aas)): ax.plot(aas[i][:, ii[0]], aas[i][:, ii[1]], alpha=0.2) ax.plot(aas[0][:, ii[0]], aas[0][:, ii[1]], c='k', ls='--', label=r'$rpo_{16.31}$') ax.scatter(poinc[:, 0], poinc[:, 1]) ax3d(fig, ax) scatter2dfig(poinc[:, 1], poinc[:, 2], ratio='equal') plot1dfig(nums) if case == 90: """ construct poincare section in ergodic trajectory and try to find the map """ N = 64 d = 22 ks = pyKS(N, d) req, ws, reqr, eq, eqr = loadRE('../../data/ks22Reqx64.h5', N) pev, bases = getBases(ks, 'eq', eq[1], [6, 7, 10]) reqr = reqr.dot(bases.T) eqr = eqr.dot(bases.T) reqr -= eqr[1] x0 = eqr[1].copy() eqr -= eqr[1] paas, poinc, poincf, poincRaw = ergoPoinc2(ks, bases, x0, 2*np.pi/6, 2.0/3*np.pi/6) ii = [0, 1, 2] fig, ax = pl2d(labs=[r'$v_1$', r'$v_2$']) plotRE2d(ax, reqr, eqr, ii) ax.plot(paas[:, ii[0]], paas[:, ii[1]], c='b', alpha=0.5) ax.scatter(poincf[:, 0], poincf[:, 1], c='r', edgecolors='none') ax2d(fig, ax) fig, ax = pl2d(size=[8, 3], labs=[None, 'z'], axisLabelSize=20, ratio='equal') ax.scatter(poinc[:, 1], poinc[:, 2], c='r', edgecolors='none') ax2d(fig, ax) plt.hold('on') for i in range(40): print i ax.scatter(poinc[i, 1], poinc[i, 2], c='g', s=20) plt.savefig(str(i)) if case == 100: """ New version to get Poincare points from pos """ N = 64 d = 22 ks = pyKS(N, d) req, ws, reqr, eq, eqr = loadRE('../../data/ks22Reqx64.h5', N) pev, bases = getBases(ks, 'eq', eq[1], [6, 7, 10]) reqr = reqr.dot(bases.T) eqr = eqr.dot(bases.T) reqr -= eqr[1] x0 = eqr[1].copy() eqr -= eqr[1] i = 100 poIds = [range(1, i+1), range(1, i+1)] aas, poinc, poincf, poincRaw, nums = poPoinc( '../../data/ks22h001t120x64EV.h5', poIds, bases, x0, 2*np.pi/6, 2.0/3*np.pi/6) ii = [0, 1, 2] fig, ax = pl2d(labs=[r'$v_1$', r'$v_2$']) plotRE2d(ax, reqr, eqr, ii) for i in range(len(aas)): ax.plot(aas[i][:, ii[0]], aas[i][:, ii[1]], c='gray', alpha=0.2) ax.scatter(poincf[:, 0], poincf[:, 1], c='r', edgecolors='none') ax2d(fig, ax) fig, ax = pl2d(size=[8, 3], labs=[None, 'z'], axisLabelSize=20, ratio='equal') ax.scatter(poinc[:, 1], poinc[:, 2], c='r', edgecolors='none') ax2d(fig, ax) plot1dfig(nums) if case == 110: """ Get the return map from the Poincare section points """ N = 64 d = 22 h = 0.001 ks = pyKS(N, d) req, ws, reqr, eq, eqr = loadRE('../../data/ks22Reqx64.h5', N) pev, bases = getBases(ks, 'eq', eq[1], [6, 7, 10]) reqr = reqr.dot(bases.T) eqr = eqr.dot(bases.T) reqr -= eqr[1] x0 = eqr[1].copy() eqr -= eqr[1] i = 100 poIds = [range(1, i+1), range(1, i+1)] aas, poinc, poincf, poincRaw, nums = poPoinc( '../../data/ks22h001t120x64EV.h5', poIds, bases, x0, 2*np.pi/6, 2.0/3*np.pi/6) ii = [0, 1, 2] fig, ax = pl2d(labs=[r'$v_1$', r'$v_2$']) plotRE2d(ax, reqr, eqr, ii) for i in range(len(aas)): ax.plot(aas[i][:, ii[0]], aas[i][:, ii[1]], c='gray', alpha=0.2) ax.scatter(poincf[:, 0], poincf[:, 1], c='r', edgecolors='none') ax2d(fig, ax) fig, ax = pl2d(size=[8, 3], labs=[None, 'z'], axisLabelSize=20, ratio='equal') ax.scatter(poinc[:, 1], poinc[:, 2], c='r', edgecolors='none') ax2d(fig, ax) plot1dfig(nums) xf = poinc[:, 1:] sel = xf[:, 0] > 0 # xf = xf[sel] # poincRaw = poincRaw[sel] scale = 10 nps = 5000 svr = GridSearchCV(SVR(kernel='rbf', gamma=0.1), cv=5, param_grid={"C": [1e0, 1e1, 1e2, 1e3], "gamma": np.logspace(-2, 2, 5), "degree": [3]}) svr.fit(xf[:, 0:1], xf[:, 1]*scale) xp = linspace(0.43, -0.3, nps) # start form right side xpp = xp.reshape(nps, 1) yp = svr.predict(xpp)/scale fig, ax = pl2d(size=[8, 3], labs=[None, 'z'], axisLabelSize=20, ratio='equal') ax.scatter(poinc[:, 1], poinc[:, 2], c='r', s=10, edgecolors='none') ax.plot(xp, yp, c='g', ls='-', lw=2) ax2d(fig, ax) curve = np.zeros((nps, 2)) curve[:, 0] = xp curve[:, 1] = yp minIds, minDs = getCurveIndex(xf, curve) sortId = np.argsort(minIds) dis, coor = getCurveCoordinate(sortId, poincRaw) fig, ax = pl2d(size=[6, 4], labs=[r'$S_n$', r'$S_{n+1}$'], axisLabelSize=15) ax.scatter(coor[:-1], coor[1:], c='r', s=10, edgecolors='none') ax2d(fig, ax) <file_sep>#include <iostream> #include <functional> #include "CQCGL1dReq.hpp" #include "iterMethod.hpp" #define cee(x) (cout << (x) << endl << endl) namespace ph = std::placeholders; using namespace std; using namespace Eigen; using namespace iterMethod; using namespace denseRoutines; using namespace MyH5; ////////////////////////////////////////////////////////////////////// // constructor // ////////////////////////////////////////////////////////////////////// // A_t = Mu A + (Dr + Di*i) A_{xx} + (Br + Bi*i) |A|^2 A + (Gr + Gi*i) |A|^4 A CQCGL1dReq::CQCGL1dReq(int N, double d, double Mu, double Dr, double Di, double Br, double Bi, double Gr, double Gi, int dimTan): CQCGL1d(N, d, Mu, Dr, Di, Br, Bi, Gr, Gi, dimTan) {} // A_t = -A + (1 + b*i) A_{xx} + (1 + c*i) |A|^2 A - (dr + di*i) |A|^4 A CQCGL1dReq::CQCGL1dReq(int N, double d, double b, double c, double dr, double di, int dimTan): CQCGL1d(N, d, b, c, dr, di, dimTan){} // iA_z + D A_{tt} + |A|^2 A + \nu |A|^4 A = i \delta A + i \beta A_{tt} + i |A|^2 A + i \mu |A|^4 A CQCGL1dReq::CQCGL1dReq(int N, double d, double delta, double beta, double D, double epsilon, double mu, double nu, int dimTan) : CQCGL1d(N, d, delta, beta, D, epsilon, mu, nu, dimTan) {} CQCGL1dReq::~CQCGL1dReq(){} CQCGL1dReq & CQCGL1dReq::operator=(const CQCGL1dReq &x){ return *this; } ////////////////////////////////////////////////////////////////////// // member functions // ////////////////////////////////////////////////////////////////////// std::string CQCGL1dReq::toStr(double Bi, double Gi, int id){ // avoid possibilty that 000000.000000 or -00000.000000 if (fabs(Bi) < 1e-6) Bi = 0; if (fabs(Gi) < 1e-6) Gi = 0; char g1[20], g2[20]; sprintf(g1, "%013.6f", Bi); sprintf(g2, "%013.6f", Gi); string s1(g1); string s2(g2); string s = s1 + '/' + s2 + '/' + to_string(id); return s; } /** * @brief read req (relative equibrium) info from hdf5 file * */ std::tuple<VectorXd, double, double ,double> CQCGL1dReq::read(H5File &file, const std::string groupName){ // H5File file(fileName, H5F_ACC_RDONLY); string DS = "/" + groupName + "/"; return make_tuple(readMatrixXd(file, DS + "a").col(0), readScalar<double>(file, DS + "wth"), readScalar<double>(file, DS + "wphi"), readScalar<double>(file, DS + "err") ); } /** * @brief write [a, wth, wphi, err] of Req of cqcgl into a group * * @note group should be a new group */ void CQCGL1dReq::write(H5File &file, const std::string groupName, const ArrayXd &a, const double wth, const double wphi, const double err){ // H5File file(fileName, H5F_ACC_RDWR); checkGroup(file, groupName, true); string DS = "/" + groupName + "/"; writeMatrixXd(file, DS + "a", a); writeScalar<double>(file, DS + "wth", wth); writeScalar<double>(file, DS + "wphi", wphi); writeScalar<double>(file, DS + "err", err); } VectorXcd CQCGL1dReq::readE(H5File &file, const std::string groupName){ string DS = "/" + groupName + "/"; VectorXd er = readMatrixXd(file, DS + "er"); VectorXd ei = readMatrixXd(file, DS + "ei"); VectorXcd e(er.size()); e.real() = er; e.imag() = ei; return e; } MatrixXcd CQCGL1dReq::readV(H5File &file, const std::string groupName){ string DS = "/" + groupName + "/"; MatrixXd vr = readMatrixXd(file, DS + "vr"); MatrixXd vi = readMatrixXd(file, DS + "vi"); MatrixXcd v(vr.rows(), vr.cols()); v.real() = vr; v.imag() = vi; return v; } void CQCGL1dReq::writeE(H5File &file, const std::string groupName, const VectorXcd e){ // H5File file(fileName, H5F_ACC_RDWR); checkGroup(file, groupName, true); string DS = "/" + groupName + "/"; writeMatrixXd(file, DS + "er", e.real()); writeMatrixXd(file, DS + "ei", e.imag()); } void CQCGL1dReq::writeV(H5File &file, const std::string groupName, const MatrixXcd v){ // H5File file(fileName, H5F_ACC_RDWR); checkGroup(file, groupName, true); string DS = "/" + groupName + "/"; writeMatrixXd(file, DS + "vr", v.real()); writeMatrixXd(file, DS + "vi", v.imag()); } void CQCGL1dReq::move(H5File &fin, std::string gin, H5File &fout, std::string gout, int flag){ VectorXd a; VectorXcd e; MatrixXcd v; double wth, wphi, err; std::tie(a, wth, wphi, err) = read(fin, gin); if (flag == 1 || flag == 2) e = readE(fin, gin); if (flag == 2) v = readV(fin, gin); write(fout, gout, a, wth, wphi, err); if (flag == 1 || flag == 2) writeE(fout, gout, e); if (flag == 2) writeV(fout, gout, v); } //==================================================================================================== VectorXd CQCGL1dReq::Fx(const VectorXd &x){ assert(x.size() == 2*Ne + 2); Vector2d th = x.tail<2>(); // wth, wphi VectorXd a = x.head(2*Ne); // use matrix type for resizing ArrayXd v = velocityReq(a, th(0), th(1)); VectorXd F(2*Ne+2); F << v, 0, 0; return F; } std::tuple<MatrixXd, MatrixXd, VectorXd> CQCGL1dReq::calJJF(const VectorXd &x){ ArrayXd a0 = x.head(2*Ne); double wth = x(2*Ne); double wphi = x(2*Ne+1); int n = a0.rows(); assert(Ndim == n); MatrixXd DF(n, n+2); ArrayXd tx_trans = transTangent(a0); ArrayXd tx_phase = phaseTangent(a0); DF.topLeftCorner(2*Ne, 2*Ne) = stabReq(a0, wth, wphi); DF.col(2*Ne).head(2*Ne)= tx_trans; DF.col(2*Ne+1).head(2*Ne) = tx_phase; VectorXd F(n); F.head(n) = velocity(a0) + wth*tx_trans + wphi*tx_phase; MatrixXd JJ = DF.transpose() * DF; MatrixXd D = JJ.diagonal().asDiagonal(); VectorXd df = DF.transpose() * F; return std::make_tuple(JJ, D, df); } std::tuple<VectorXd, double, double, double, int> CQCGL1dReq::findReq_LM(const ArrayXd &a0, const double wth0, const double wphi0, const double tol, const int maxit, const int innerMaxit){ VectorXd x(2*Ne+2); x << a0, wth0, wphi0; auto fx = std::bind(&CQCGL1dReq::Fx, this, ph::_1); CQCGL1dReqJJF<MatrixXd> jj(this); PartialPivLU<MatrixXd> solver; VectorXd xe; std::vector<double> res; int flag; std::tie(xe, res, flag) = LM0(fx, jj, solver, x, tol, maxit, innerMaxit); if(flag != 0) fprintf(stderr, "Req not converged ! \n"); VectorXd a = xe.head(2*Ne); double wth = xe(2*Ne); double wphi = xe(2*Ne+1); return std::make_tuple( a, wth, wphi, res.back(), flag ); } /** @brief find the optimal guess of wth and wphi for a candidate req * * When we find a the inital state of a candidate of req, we also need * to know the appropriate th and phi to start the Newton search. * According to the definition of velocityReq(), this is a residual * minimization problem. * * @return [wth, wphi, err] such that velocityReq(a0, wth, wphi) minimal */ std::vector<double> CQCGL1dReq::optThPhi(const ArrayXd &a0){ VectorXd t1 = transTangent(a0); VectorXd t2 = phaseTangent(a0); double c = t2.dot(t1) / t1.dot(t1); VectorXd t3 = t2 - c * t1; VectorXd v = velocity(a0); double a1 = t1.dot(v) / t1.dot(t1); double a2 = t3.dot(v) / t3.dot(t3); double err = (v - a1 * t1 - a2 * t3).norm(); std::vector<double> x = {-(a1-a2*c), -a2, err}; return x; } /** * @brief find req with a sequence of Bi or Gi */ void CQCGL1dReq::findReqParaSeq(H5File &file, int id, double step, int Ns, bool isBi){ double Bi0 = Bi; double Gi0 = Gi; ArrayXd a0; double wth0, wphi0, err0; std::tie(a0, wth0, wphi0, err0) = read(file, toStr(Bi, Gi, id)); ArrayXd a; double wth, wphi, err; int flag; int Nfail = 0; for (int i = 0; i < Ns; i++){ if (isBi) Bi += step; else Gi += step; // if exist, use it as seed, otherwise find req if ( checkGroup(file, toStr(Bi, Gi, id), false) ){ std::tie(a0, wth0, wphi0, err0) = read(file, toStr(Bi, Gi, id)); } else { fprintf(stderr, "%d %g %g \n", id, Bi, Gi); std::tie(a, wth, wphi, err, flag) = findReq_LM(a0, wth0, wphi0, 1e-10, 100, 1000); if (flag == 0){ write(file, toStr(Bi, Gi, id), a, wth, wphi, err); a0 = a; wth0 = wth; wphi0 = wphi; } else { if(++Nfail == 3) break; } } } Bi = Bi0; // restore Bi, Gi Gi = Gi0; } /// @brief calculate the eigenvalues and eigenvectors of req in certain range void CQCGL1dReq::calEVParaSeq(H5File &file, std::vector<int> ids, std::vector<double> Bis, std::vector<double> Gis, bool saveV){ double Bi0 = Bi; double Gi0 = Gi; int id; ArrayXd a0; double wth0, wphi0, err0; VectorXcd e; MatrixXcd v; for (int i = 0; i < ids.size(); i++){ id = ids[i]; for (int j = 0; j < Bis.size(); j++){ Bi = Bis[j]; for(int k = 0; k < Gis.size(); k++){ Gi = Gis[k]; if ( checkGroup(file, toStr(Bi, Gi, id), false) ){ if( !checkGroup(file, toStr(Bi, Gi, id) + "/er", false)){ fprintf(stderr, "%d %g %g \n", id, Bi, Gi); std::tie(a0, wth0, wphi0, err0) = read(file, toStr(Bi, Gi, id)); std::tie(e, v) = evReq(a0, wth0, wphi0); writeE(file, toStr(Bi, Gi, id), e); if (saveV) writeV(file, toStr(Bi, Gi, id), v.leftCols(10)); } } } } } Bi = Bi0; // restore Bi, Gi Gi = Gi0; } #if 0 //==================================================================================================== VectorXd CQCGL1dReq::DFx(const VectorXd &x, const VectorXd &dx){ assert(x.size() == 2*Ne*Me + 3 && dx.size() == 2*Ne*Me + 3); Vector3d th = x.tail<3>(); // wthx, wthy, wphi Vector3d dth = dx.tail<3>(); VectorXd ra = x.head(2*Me*Ne); VectorXd rda = dx.head(2*Me*Ne); ArrayXXcd a = r2c(ra); ArrayXXcd da = r2c(rda); ArrayXXcd t1 = tangent(a, 1); ArrayXXcd t2 = tangent(a, 2); ArrayXXcd t3 = tangent(a, 3); ArrayXXcd Ax = stabReq(a, da, th(0), th(1), th(2)) + dth(0) * t1 + dth(1) * t2 + dth(2) * t3; double t1x = (t1 * da.conjugate()).sum().real(); double t2x = (t2 * da.conjugate()).sum().real(); double t3x = (t3 * da.conjugate()).sum().real(); VectorXd DF(2*Ne*Me+3); DF << c2r(Ax), t1x, t2x, t3x; return DF; } std::tuple<ArrayXXcd, double, double, double, double> CQCGL1dReq::findReq_hook(const ArrayXXcd &x0, const double wthx0, const double wthy0, const double wphi0){ HOOK_PRINT_FREQUENCE = hookPrint; assert(x0.rows() == Me && x0.cols() == Ne); auto fx = std::bind(&CQCGL1dReq::Fx, this, ph::_1); auto dfx = std::bind(&CQCGL1dReq::DFx, this, ph::_1, ph::_2); VectorXd x(2*Me*Ne+3); x << c2r(x0), wthx0, wthy0, wphi0; VectorXd xnew; std::vector<double> errs; int flag; auto Pre = [this](const VectorXd &x, const VectorXd &dx){ Vector3d th = x.tail<3>(); Vector3d dth = dx.tail<3>(); VectorXd dra = dx.head(2*Me*Ne); ArrayXXcd da = r2c(dra); ArrayXXcd px = 1/(Lu + Tx*th(0) + Ty*th(1) + Tp*th(2)) * da; VectorXd p(2*Ne*Me+3); p << c2r(px), dth; return p; }; std::tie(xnew, errs, flag) = Gmres0HookPre(fx, dfx, Pre, x, tol, minRD, maxit, maxInnIt, GmresRtol, GmresRestart, GmresMaxit, false, 1); if(flag != 0) fprintf(stderr, "Req not converged ! \n"); Vector3d th = xnew.tail<3>(); VectorXd y = xnew.head(2*Me*Ne); return std::make_tuple(r2c(y), th(0), th(1), th(2), errs.back()); } #endif <file_sep>#include "myH5.hpp" #include <iostream> #include <sstream> namespace MyH5 { /** * @brief read a double matrix */ MatrixXd readMatrixXd(H5File &file, string DSitem){ DataSet item = file.openDataSet(DSitem); DataSpace dsp = item.getSpace(); const int D = dsp.getSimpleExtentNdims(); if (D == 2) { hsize_t dims[2]; int ndims = dsp.getSimpleExtentDims(dims, NULL); MatrixXd x(dims[1], dims[0]); /* HDF5 uses row major by default */ item.read(x.data(), PredType::NATIVE_DOUBLE); return x; } else if (D == 1) { hsize_t dims[1]; int ndims = dsp.getSimpleExtentDims(dims, NULL); MatrixXd x(dims[0], 1); item.read(x.data(), PredType::NATIVE_DOUBLE); return x; } else { fprintf(stderr, "readMatrixXd() dimension wrong !\n"); exit(-1); } } /** * @brief read a double vector */ VectorXd readVectorXd(H5File &file, string DSitem){ DataSet item = file.openDataSet(DSitem); DataSpace dsp = item.getSpace(); const int D = dsp.getSimpleExtentNdims(); assert ( D == 1); hsize_t dims[1]; int ndims = dsp.getSimpleExtentDims(dims, NULL); VectorXd x(dims[0]); item.read(x.data(), PredType::NATIVE_DOUBLE); return x; } /** * @brief write a double matrix */ void writeMatrixXd(H5File &file, string DSitem, const MatrixXd &mat){ const int N = mat.rows(); const int M = mat.cols(); if ( 1 == M){ hsize_t dim[] = {N}; DataSpace dsp(1, dim); DataSet item = file.createDataSet(DSitem, PredType::NATIVE_DOUBLE, dsp); item.write(mat.data(), PredType::NATIVE_DOUBLE); } else { hsize_t dim[] = {M, N}; /* HDF5 uses row major by default */ DataSpace dsp(2, dim); DataSet item = file.createDataSet(DSitem, PredType::NATIVE_DOUBLE, dsp); item.write(mat.data(), PredType::NATIVE_DOUBLE); } } /** * @brief write a double vector */ void writeVectorXd(H5File &file, string DSitem, const VectorXd &vec){ const int N = vec.size(); hsize_t dim[] = {N}; DataSpace dsp(1, dim); DataSet item = file.createDataSet(DSitem, PredType::NATIVE_DOUBLE, dsp); item.write(vec.data(), PredType::NATIVE_DOUBLE); } /** * @brief check the existence of groups recursively. * * If doCreate = false, it will immediately return if not exist * If doCreate = true. It will finish the loop * * @param[in] groupName some string like "a/b/c". Note, no '/' at the head or tail. * @param[in] doCreate if not exist, whether create the group */ bool checkGroup(H5File &file, const std::string groupName, const bool doCreate){ stringstream ss(groupName); string item, g; hid_t id = file.getId(); bool exist = true; while (getline(ss, item, '/')) { g += '/' + item; if(H5Lexists(id, g.c_str(), H5P_DEFAULT) == false){ exist = false; if (doCreate) file.createGroup(g.c_str()); else return exist; } } return exist; } bool checkGroup(std::string fileName, const std::string groupName, const bool doCreate){ H5File file(fileName, H5F_ACC_RDWR); return checkGroup(file, groupName, doCreate); } // obtain all unique groupnames in a file // if file has datasets /a/b/c/d1, /a/b/c/d2, /a/b/d3 // the it outputs a/b/c, a/b // from https://support.hdfgroup.org/ftp/HDF5/examples/misc-examples/h5_info.c vector<vector<string>> scanGroup(std::string fileName){ H5File file(fileName, H5F_ACC_RDONLY); unordered_set<string> record; vector<vector<string>> result; vector<string> curt; scanGroupHelp(file.getId(), result, record, curt); return result; } // I do not know why H5Gopen does not work but H5Gopen1 works void scanGroupHelp(hid_t gid, vector<vector<string>> &result, unordered_set<string> &record, vector<string> &curt) { int MAX_NAME = 100; char memb_name[MAX_NAME]; hsize_t nobj; herr_t err = H5Gget_num_objs(gid, &nobj); for (int i = 0; i < nobj; i++) { int len = H5Gget_objname_by_idx(gid, (hsize_t)i, memb_name, (size_t)MAX_NAME ); int otype = H5Gget_objtype_by_idx(gid, (size_t)i ); switch(otype) { case H5G_GROUP: { hid_t grpid = H5Gopen1(gid, memb_name); curt.push_back(string(memb_name)); scanGroupHelp(grpid, result, record, curt); curt.pop_back(); H5Gclose(grpid); break; } case H5G_DATASET: { string groupName; for(auto s : curt) groupName += s + "/"; groupName.pop_back(); if (record.find(groupName) == record.end()){ record.insert(groupName); result.push_back(curt); } break; } default: fprintf(stderr, "scanGroup unknown? \n"); } } } //////////////////////////////////////////////////////////////////////////////// // KS related //////////////////////////////////////////////////////////////////////////////// std::pair<VectorXd, double> KSreadEq(const std::string fileName, const int Id){ H5File file(fileName, H5F_ACC_RDONLY); string DS = "/E/" + to_string(Id) + "/"; return std::make_pair(readMatrixXd(file, DS + "a"), readScalar<double>(file, DS + "err") ); } std::tuple<VectorXd, double, double> KSreadReq(const std::string fileName, const int Id){ H5File file(fileName, H5F_ACC_RDONLY); string DS = "/tw/" + to_string(Id) + "/"; return std::make_tuple(readMatrixXd(file, DS + "a"), readScalar<double>(file, DS + "w"), readScalar<double>(file, DS + "err") ); } } <file_sep>#include <boost/python.hpp> #include <boost/numpy.hpp> #include <Eigen/Dense> #include <cstdio> #include "CQCGL1d.hpp" #include "myBoostPython.hpp" using namespace std; using namespace Eigen; namespace bp = boost::python; namespace bn = boost::numpy; ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// class pyCQCGL1d : public CQCGL1d { public: pyCQCGL1d(int N, double d, double Mu, double Dr, double Di, double Br, double Bi, double Gr, double Gi, int dimTan): CQCGL1d(N, d, Mu, Dr, Di, Br, Bi, Gr, Gi, dimTan) {} pyCQCGL1d(int N, double d, double b, double c, double dr, double di, int dimTan) : CQCGL1d(N, d, b, c, dr, di, dimTan) {} pyCQCGL1d(int N, double d, double delta, double beta, double D, double epsilon, double mu, double nu, int dimTan): CQCGL1d(N, d, delta, beta, D, epsilon, mu, nu, dimTan) {} bn::ndarray PYTs(){ return copy2bn(Ts); } bn::ndarray PYlte(){ return copy2bn(lte); } bn::ndarray PYhs(){ return copy2bn(hs); } /* K */ bn::ndarray PYK(){ return copy2bn(K); } /* L */ bn::ndarray PYL(){ return copy2bnc(L); } /* wrap the integrator */ bn::ndarray PYintgC(bn::ndarray a0, double h, double tend, int skip_rate){ int m, n; getDims(a0, m, n); Map<ArrayXd> tmpa((double*)a0.get_data(), m*n); return copy2bn(intgC(tmpa, h, tend, skip_rate)); } /* wrap the integrator with Jacobian */ bp::tuple PYintgjC(bn::ndarray a0, double h, double tend, size_t skip_rate){ int m, n; getDims(a0, m, n); Map<ArrayXd> tmpa((double*)a0.get_data(), m*n); auto result = intgjC(tmpa, h, tend, skip_rate); return bp::make_tuple(copy2bn(result.first), copy2bn(result.second)); } bn::ndarray PYintgvC(bn::ndarray a0, bn::ndarray v, double h, double tend){ int m, n; getDims(a0, m, n); Map<ArrayXd> tmpa((double*)a0.get_data(), m*n); getDims(v, m, n); Map<ArrayXXd> tmpv((double*)v.get_data(), n, m); return copy2bn(intgvC(tmpa, tmpv, h, tend)); } bn::ndarray PYintg(bn::ndarray a0, double h, double tend, int skip_rate){ int m, n; getDims(a0, m, n); Map<ArrayXd> tmpa((double*)a0.get_data(), m*n); return copy2bn(intg(tmpa, h, tend, skip_rate)); } bp::tuple PYintgj(bn::ndarray a0, double h, double tend, int skip_rate){ int m, n; getDims(a0, m, n); Map<ArrayXd> tmpa((double*)a0.get_data(), m*n); auto result = intgj(tmpa, h, tend, skip_rate); return bp::make_tuple(copy2bn(result.first), copy2bn(result.second)); } bn::ndarray PYintgv(bn::ndarray a0, bn::ndarray v, double h, double tend){ int m, n; getDims(a0, m, n); Map<ArrayXd> tmpa((double*)a0.get_data(), m*n); getDims(v, m, n); Map<ArrayXXd> tmpv((double*)v.get_data(), n, m); return copy2bn(intgv(tmpa, tmpv, h, tend)); } /* wrap the velocity */ bn::ndarray PYvelocity(bn::ndarray a0){ int m, n; getDims(a0, m, n); Map<ArrayXd> tmpa((double*)a0.get_data(), m*n); return copy2bn(velocity(tmpa)); } /* wrap the velSlice */ bn::ndarray PYvelSlice(bn::ndarray aH){ int m, n; getDims(aH, m, n); Map<VectorXd> tmpa((double*)aH.get_data(), m*n); return copy2bn(velSlice(tmpa)); } /* wrap the velPhase */ bn::ndarray PYvelPhase(bn::ndarray aH){ int m, n; getDims(aH, m, n); Map<VectorXd> tmpa((double*)aH.get_data(), m*n); VectorXd tmpv = velPhase(tmpa); return copy2bn(tmpv); } /* wrap velocityReq */ bn::ndarray PYvelocityReq(bn::ndarray a0, double th, double phi){ int m, n; getDims(a0, m, n); Map<ArrayXd> tmpa((double*)a0.get_data(), m*n); ArrayXd tmpv = velocityReq(tmpa, th, phi); return copy2bn(tmpv); } /* wrap Fourier2Config */ bn::ndarray PYFourier2Config(bn::ndarray aa){ int m, n; getDims(aa, m, n); Map<ArrayXXd> tmpaa((double*)aa.get_data(), n, m); return copy2bnc( Fourier2Config(tmpaa) ); } /* wrap Config2Fourier */ bn::ndarray PYConfig2Fourier(bn::ndarray AA){ int m, n; getDims(AA, m, n); Map<ArrayXXcd> tmpAA((dcp*)AA.get_data(), n, m); return copy2bn( Config2Fourier(tmpAA) ); } /* wrap Fourier2ConfigMag */ bn::ndarray PYFourier2ConfigMag(bn::ndarray aa){ int m, n; getDims(aa, m, n); Map<ArrayXXd> tmpaa((double*)aa.get_data(), n, m); return copy2bn( Fourier2ConfigMag(tmpaa) ); } /* wrap Fourier2Phase */ bn::ndarray PYFourier2Phase(bn::ndarray aa){ int m, n; getDims(aa, m, n); Map<ArrayXXd> tmpaa((double*)aa.get_data(), n, m); return copy2bn( Fourier2Phase(tmpaa) ); } bn::ndarray PYcalQ(const bn::ndarray &aa){ int m, n; getDims(aa, m, n); Map<ArrayXXd> tmpaa((double*)aa.get_data(), n, m); return copy2bn(calQ(tmpaa)); } bn::ndarray PYcalMoment(const bn::ndarray &aa, const int p){ int m, n; getDims(aa, m, n); Map<ArrayXXd> tmpaa((double*)aa.get_data(), n, m); return copy2bn(calMoment(tmpaa, p)); } bn::ndarray PYcalMoment2(const bn::ndarray &aa){ return PYcalMoment(aa, 1); } /* orbit2slice */ bp::tuple PYorbit2slice(const bn::ndarray &aa, int method){ int m, n; getDims(aa, m, n); Map<ArrayXXd> tmpaa((double*)aa.get_data(), n, m); std::tuple<ArrayXXd, ArrayXd, ArrayXd> tmp = orbit2slice(tmpaa, method); return bp::make_tuple(copy2bn(std::get<0>(tmp)), copy2bn(std::get<1>(tmp)), copy2bn(std::get<2>(tmp))); } bn::ndarray PYve2slice(const bn::ndarray &ve, const bn::ndarray &x, int flag){ int m, n; getDims(ve, m, n); Map<ArrayXXd> tmpve((double*)ve.get_data(), n, m); getDims(x, m, n); Map<ArrayXd> tmpx((double*)x.get_data(), n*m); return copy2bn(ve2slice(tmpve, tmpx, flag)); } /* stability matrix */ bn::ndarray PYstab(bn::ndarray a0){ int m, n; getDims(a0, m, n); Map<ArrayXd> tmpa((double*)a0.get_data(), n*m); return copy2bn(stab(tmpa)); } /* stability matrix for relative equibrium */ bn::ndarray PYstabReq(bn::ndarray a0, double th, double phi){ int m, n; getDims(a0, m, n); Map<ArrayXd> tmpa((double*)a0.get_data(), n*m); return copy2bn(stabReq(tmpa, th, phi)); } /* reflection */ bn::ndarray PYreflect(const bn::ndarray &aa){ int m, n; getDims(aa, m, n); Map<ArrayXXd> tmpaa((double*)aa.get_data(), n, m); return copy2bn( reflect(tmpaa) ); } /* reduceReflection */ bn::ndarray PYreduceReflection(const bn::ndarray &aa){ int m, n; getDims(aa, m, n); Map<ArrayXXd> tmpaa((double*)aa.get_data(), n, m); return copy2bn( reduceReflection(tmpaa) ); } /* refGradMat */ bn::ndarray PYrefGradMat(bn::ndarray aa){ int m, n; getDims(aa, m, n); Map<ArrayXd> tmpaa((double*)aa.get_data(), n * m); return copy2bn( refGradMat(tmpaa) ); } /* reflectVe */ bn::ndarray PYreflectVe(const bn::ndarray &veHat, const bn::ndarray &xHat){ int m, n; getDims(veHat, m, n); Map<MatrixXd> tmpveHat((double*)veHat.get_data(), n, m); int m2, n2; getDims(xHat, m2, n2); Map<ArrayXd> tmpxHat((double*)xHat.get_data(), n2*m2); return copy2bn( reflectVe(tmpveHat, tmpxHat) ); } /* transRotate */ bn::ndarray PYtransRotate(bn::ndarray aa, double th){ int m, n; getDims(aa, m, n); Map<ArrayXXd> tmpaa((double*)aa.get_data(), n, m); return copy2bn( transRotate(tmpaa, th) ); } /* transTangent */ bn::ndarray PYtransTangent(bn::ndarray aa){ int m, n; getDims(aa, m, n); Map<ArrayXXd> tmpaa((double*)aa.get_data(), n, m); return copy2bn( transTangent(tmpaa) ); } /* phaseRotate */ bn::ndarray PYphaseRotate(bn::ndarray aa, double phi){ int m, n; getDims(aa, m, n); Map<ArrayXXd> tmpaa((double*)aa.get_data(), n, m); return copy2bn( phaseRotate(tmpaa, phi) ); } /* phaseTangent */ bn::ndarray PYphaseTangent(bn::ndarray aa){ int m, n; getDims(aa, m, n); Map<ArrayXXd> tmpaa((double*)aa.get_data(), n, m); return copy2bn( phaseTangent(tmpaa) ); } /* Rotate */ bn::ndarray PYRotate(bn::ndarray aa, double th, double phi){ int m, n; getDims(aa, m, n); Map<ArrayXXd> tmpaa((double*)aa.get_data(), n, m); return copy2bn( Rotate(tmpaa, th, phi) ); } /* rotateOrbit */ bn::ndarray PYrotateOrbit(bn::ndarray aa, bn::ndarray th, bn::ndarray phi){ int m, n; getDims(aa, m, n); int m2, n2; getDims(th, m2, n2); int m4, n4; getDims(phi, m4, n4); Map<ArrayXXd> tmpaa((double*)aa.get_data(), n, m); Map<ArrayXd> tmpth((double*)th.get_data(), n2 * m2); Map<ArrayXd> tmpphi((double*)phi.get_data(), n4 * m4); return copy2bn( rotateOrbit(tmpaa, tmpth, tmpphi) ); } bn::ndarray PYC2R(bn::ndarray v){ int m, n; getDims(v, m, n); Map<ArrayXXcd> tmpv((dcp*)v.get_data(), n, m); return copy2bn( C2R(tmpv) ); } }; //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// BOOST_PYTHON_MODULE(py_CQCGL1d) { bn::initialize(); // must provide the constructor bp::class_<CQCGL1d>("CQCGL1d", bp::init< int, double, double, double, double, double, int>()) ; // the EIDc class bp::class_<EIDc>("EIDc", bp::init<>()) .def_readonly("NCalCoe", &EIDc::NCalCoe) .def_readonly("NReject", &EIDc::NReject) .def_readonly("NCallF", &EIDc::NCallF) .def_readonly("NSteps", &EIDc::NSteps) .def_readonly("TotalTime", &EIDc::TotalTime) .def_readonly("CoefficientTime", &EIDc::CoefficientTime) .def_readwrite("rtol", &EIDc::rtol) ; bp::class_<pyCQCGL1d, bp::bases<CQCGL1d> >("pyCQCGL1d", bp::init< int, double, double, double, double, double, int >()) .def(bp::init<int, double, double, double, double, double, double, double, double, int>()) .def(bp::init<int, double, double, double, double, double, double, double, int>()) .def_readonly("N", &pyCQCGL1d::N) .def_readonly("d", &pyCQCGL1d::d) .def_readwrite("IsQintic", &pyCQCGL1d::IsQintic) .def_readonly("Mu", &pyCQCGL1d::Mu) .def_readwrite("Br", &pyCQCGL1d::Br) .def_readwrite("Bi", &pyCQCGL1d::Bi) .def_readonly("Dr", &pyCQCGL1d::Dr) .def_readonly("Di", &pyCQCGL1d::Di) .def_readwrite("Gr", &pyCQCGL1d::Gr) .def_readwrite("Gi", &pyCQCGL1d::Gi) .def_readonly("Ndim", &pyCQCGL1d::Ndim) .def_readonly("Ne", &pyCQCGL1d::Ne) .def_readonly("Omega", &pyCQCGL1d::Omega) .def_readwrite("eidc", &pyCQCGL1d::eidc) .def_readwrite("eidc2", &pyCQCGL1d::eidc2) .def("Ts", &pyCQCGL1d::PYTs) .def("hs", &pyCQCGL1d::PYhs) .def("lte", &pyCQCGL1d::PYlte) .def("K", &pyCQCGL1d::PYK) .def("L", &pyCQCGL1d::PYL) .def("changeOmega", &pyCQCGL1d::changeOmega) .def("intgC", &pyCQCGL1d::PYintgC) .def("intgjC", &pyCQCGL1d::PYintgjC) .def("intgvC", &pyCQCGL1d::PYintgv) .def("intg", &pyCQCGL1d::PYintg) .def("intgj", &pyCQCGL1d::PYintgj) .def("intgv", &pyCQCGL1d::PYintgv) .def("velocity", &pyCQCGL1d::PYvelocity) .def("velSlice", &pyCQCGL1d::PYvelSlice) .def("velPhase", &pyCQCGL1d::PYvelPhase) .def("velocityReq", &pyCQCGL1d::PYvelocityReq) .def("Fourier2Config", &pyCQCGL1d::PYFourier2Config) .def("Config2Fourier", &pyCQCGL1d::PYConfig2Fourier) .def("Fourier2ConfigMag", &pyCQCGL1d::PYFourier2ConfigMag) .def("Fourier2Phase", &pyCQCGL1d::PYFourier2Phase) .def("calQ", &pyCQCGL1d::PYcalQ) .def("calMoment", &pyCQCGL1d::PYcalMoment) .def("calMoment", &pyCQCGL1d::PYcalMoment2) .def("orbit2slice", &pyCQCGL1d::PYorbit2slice) .def("ve2slice", &pyCQCGL1d::PYve2slice) .def("stab", &pyCQCGL1d::PYstab) .def("stabReq", &pyCQCGL1d::PYstabReq) .def("reflect", &pyCQCGL1d::PYreflect) .def("reduceReflection", &pyCQCGL1d::PYreduceReflection) .def("refGradMat", &pyCQCGL1d::PYrefGradMat) .def("reflectVe", &pyCQCGL1d::PYreflectVe) .def("transRotate", &pyCQCGL1d::PYtransRotate) .def("transTangent", &pyCQCGL1d::PYtransTangent) .def("phaseRotate", &pyCQCGL1d::PYphaseRotate) .def("phaseTangent", &pyCQCGL1d::PYphaseTangent) .def("Rotate", &pyCQCGL1d::PYRotate) .def("rotateOrbit", &pyCQCGL1d::PYrotateOrbit) .def("C2R", &pyCQCGL1d::PYC2R) ; } <file_sep>/* try to form the Jacobian for finding the relative equilibirum * * | A+wT , tx| * J = | tx , 0| * * @param[in] x [a0, omega] * return J^T*J, diag(J^T*J), J^T * F */ std::tuple<MatrixXd, MatrixXd, VectorXd> KS::calReqJJF(const Ref<const VectorXd> &x){ assert(x.size() == N-1); double omega = x(N-2); MatrixXd A = stabReq(x.head(N-2), omega); VectorXd tx = gTangent(x.head(N-2)); MatrixXd J(N-1, N-1); J << A, tx, tx.transpose(), 0; VectorXd F(N-1); F << velg(x.head(N-2), omega), 0 ; MatrixXd JJ = J.transpose() * J; MatrixXd DJJ = JJ.diagonal().asDiagonal(); VectorXd JF = J.transpose() * F; return std::make_tuple(JJ, DJJ, JF); } /** * @see calReqJJF */ std::tuple<MatrixXd, MatrixXd, VectorXd> KS::calEqJJF(const Ref<const VectorXd> &x){ assert(x.size() == N-2); MatrixXd J = stab(x); VectorXd F = velocity(x); MatrixXd JJ = J.transpose() * J; MatrixXd DJJ = JJ.diagonal().asDiagonal(); VectorXd JF = J.transpose() * F; return std::make_tuple(JJ, DJJ, JF); } /* find reqs in KS */ std::tuple<VectorXd, double, double> KS::findReq(const Ref<const VectorXd> &x, const double tol, const int maxit, const int innerMaxit){ auto fx = [&](const VectorXd &x){ VectorXd F(N-1); F << velg(x.head(N-2), x(N-2)), 0; return F; }; KSReqJJF<MatrixXd> jj(*this); ColPivHouseholderQR<MatrixXd> solver; auto result = LM0(fx, jj, solver, x, tol, maxit, innerMaxit); if(std::get<2>(result) != 0) fprintf(stderr, "Req not converged ! \n"); VectorXd at = std::get<0>(result); return std::make_tuple(at.head(N-2), at(N-2) , std::get<1>(result).back() ); } /* find eq in KS */ std::pair<VectorXd, double> KS::findEq(const Ref<const VectorXd> &x, const double tol, const int maxit, const int innerMaxit){ auto fx = [&](const VectorXd &x){ return velocity(x); }; KSEqJJF<MatrixXd> jj(*this); ColPivHouseholderQR<MatrixXd> solver; auto result = LM0(fx, jj, solver, x, tol, maxit, innerMaxit); if(std::get<2>(result) != 0) fprintf(stderr, "Req not converged ! \n"); return std::make_pair(std::get<0>(result), std::get<1>(result).back() ); } <file_sep>import h5py from pylab import * import numpy as np from numpy.linalg import norm, eig from time import time from py_cqcgl1d_threads import pyCqcgl1d, pyCqcglRPO from personalFunctions import * case = 1 if case == 1: """ use different N and h to view the explosion process. Try to find the optimal values. """ N = 512 d = 50 h = 0.0001 cgl = pyCqcgl1d(N, d, h, True, 0, -0.1, 1.0, 0.8, 0.125, 0.5, -0.1, -0.6, 4) Ndim = cgl.Ndim nstp3 = 200000 a0Erg3 = cgl.Config2Fourier(centerRand(2*N, 0.25)) aaErg3 = cgl.intg(a0Erg3, 20000, 20000) a0Erg3 = aaErg3[-1] aaErg3 = cgl.intg(a0Erg3, nstp3, 1) aaErgHat3, th3, phi3 = cgl.orbit2slice(aaErg3) aaErgTilde3 = cgl.reduceReflection(aaErgHat3) # plot3dfig(aaErgTildeProj3[:, 0], aaErgTildeProj3[:, 1], aaErgTildeProj3[:, 2]) # plot the variance => indicator of the integration error. plot1dfig(aaErg3[:, 0]) plot1dfig(aaErg3[:-1, 0]-aaErg3[1:, 0]) plot1dfig(abs(aaErg3[:, Ndim/2]), yscale='log') # plotConfigSpace(cgl.Fourier2Config(aaErg3), [0, d, 0, nstp3*h]) <file_sep>/* compile command: * mex CXXFLAGS='-std=c++0x -fPIC -O3 -march=corei7 -msse4.2' MEXcqcgl1d.cpp cqcgl1d.cc -I../../include -I/usr/include/eigen3 -lm -lfftw3 * */ #include "cqcgl1d.hpp" #include "mex.h" #include <cmath> #include <cstring> #include <Eigen/Dense> using namespace Eigen; static int getNdim(int N){ double d = 1; double h = 1; bool enableJacv = false; int Njacv = 0; double b = 1; double c = 1; double dr = 1; double di = 1; int threadNum = 4; Cqcgl1d cgl(N, d, h, enableJacv, Njacv, b, c, dr, di, threadNum); return cgl.Ndim; } void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[]){ int N = mxGetScalar(prhs[0]); double Ndim = (double) getNdim(N); // to simply the process, transform it to double plhs[0] = mxCreateDoubleMatrix(1, 1, mxREAL); memcpy(mxGetPr(plhs[0]), &Ndim, 1*sizeof(double)); } <file_sep>/* g++ test_dense.cc -O3 -std=c++11 -I$EIGEN -I${RESH}/include -L${RESH}/lib -ldenseRoutines */ #include <iostream> #include <Eigen/Dense> #include "denseRoutines.hpp" #define CE(x) (cout << x << endl << endl) using namespace std; using namespace Eigen; using namespace denseRoutines; int main(){ switch (1) { case 1 : { /* test savetxt */ MatrixXcd A(2, 3); A.real() << 1, 2, 3, 4, 5, 6; A.imag() = A.real()/2; CE(A); savetxt("f1.dat", A.real()); savetxt("f2.dat", A.imag()); break; } default :{ fprintf(stderr, "indicate a case \n"); } } return 0; } <file_sep># One- and two-dimensional cubic-quintic complex Ginzburg-Landau equation ## Inheritance diagram ![CQCGL1d](../../include/classCQCGL1d__inherit__graph.png) ![CQCGL2d](../../include/classCQCGL2d__inherit__graph.png) <file_sep>/* to comiple: * (Note : libksdim.a is static library, so the following order is important) * * h5c++ test_ksdim.cc -std=c++11 -O3 -march=corei7 -msse4 -msse2 -I$XDAPPS/eigen/include/eigen3 -I$RESH/include -L$RESH/lib -lksdim -lksint -lfftw3 -ldenseRoutines -lmyH5 * */ #include <iostream> #include <Eigen/Dense> #include <string> #include <fstream> #include "ksdim.hpp" #include <sys/types.h> #include <sys/stat.h> /* for create folder */ #include <unistd.h> using namespace std; using namespace Eigen; int main(){ cout.precision(16); switch (50) { case 1: { MatrixXi subspDim(4,3); subspDim << 0, 0, 0, 0, 7, 27, 1, 8, 28, 1, 29, 29; // (0-6,7-29), (0-7,8-29), (0-8,9-29) cout << subspDim << endl; string fileName("../../data/ks22h001t120x64EV.h5"); string ppType("rpo"); int ppId = 33; auto ang = anglePO(fileName, ppType, ppId, subspDim); cout << ang.second << endl; ofstream file; file.precision(16); file.open("good.dat", ios::trunc); file << ang.first << endl; file.close(); break; } case 2: { /* test the angle tangency */ string fileName("../../data/ks22h001t120x64EV.h5"); string ppType("rpo"); anglePOs(fileName, ppType, 30, 200, "./anglePOs64/rpo/vector", "vector", 29); break; } case 3: { /* test the angle tangency but with diefferent style */ // string fileName("../../data/ks22h001t120x64EV.h5"); string fileName("../../data/ex.h5"); // std::vector<int> ppIds(10); // for(int i = 0; i < 10; i++) ppIds[i] = i+191; int pid[] = {33, 36, 59, 60, 79, 81, 109, 114}; std::vector<int> ppIds(pid, pid+8); char buf[1000]; char* buffer = getcwd(buf, 1000); string pwd = buf; pwd = pwd + "/anglePOs64/"; // create folders bool doCreate = true; std::string fs[6]{"ppo", "ppo/space", "ppo/vector", "rpo", "rpo/space", "rpo/vector"}; int ss = 0; if(doCreate){ for(int i = 0; i < 6; i++){ int s = mkdir( (pwd + fs[i]).c_str(), S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH ); ss += s; } } if ( ss == 0 ){ anglePOs(fileName, "rpo", 30, ppIds, "./anglePOs64/rpo/space", "space", 29); // anglePOs(fileName, "ppo", 30, ppIds, "./anglePOs64/ppo/space", "space", 29); } break; } case 30: { /* test partialHyperb */ string fileName("../../data/ks22h001t120x64EV.h5"); string ppType("rpo"); MatrixXd expand = partialHyperb(fileName, ppType, 3); // cout << expand << endl; break; } case 40: { /* calculate the local expansion rate of FVs */ string fileName("../../data/ks22h001t120x64EV.h5"); partialHyperbOneType(fileName, "rpo", 200, "./FVexpand/rpo/"); // partialHyperbAll(fileName, 200, 200, "./FVexpand/"); break; } case 50: { /* calculate the local Floquet exponents */ string fileName("../../data/ks22h001t120x64EV.h5"); localFEAll(fileName, 200, 200, "./localFE/"); break; } default: { fprintf(stderr, "indicate a case\n"); } } } <file_sep>#ifndef CQCGL1dRpo_H #define CQCGL1dRpo_H #include <complex> #include <utility> #include <Eigen/Dense> #include <Eigen/Sparse> #include <vector> #include "CQCGL1d.hpp" #include "iterMethod.hpp" #include "sparseRoutines.hpp" #include "denseRoutines.hpp" using Eigen::Vector3d; class CQCGL1dRpo : public CQCGL1d { public: typedef std::complex<double> dcp; typedef Eigen::SparseMatrix<double> SpMat; typedef Eigen::Triplet<double> Tri; //////////////////////////////////////////////////////////// // A_t = Mu A + (Dr + Di*i) A_{xx} + (Br + Bi*i) |A|^2 A + (Gr + Gi*i) |A|^4 A CQCGL1dRpo(int N, double d, double Mu, double Dr, double Di, double Br, double Bi, double Gr, double Gi, int dimTan); // A_t = -A + (1 + b*i) A_{xx} + (1 + c*i) |A|^2 A - (dr + di*i) |A|^4 A CQCGL1dRpo(int N, double d, double b, double c, double dr, double di, int dimTan); // iA_z + D A_{tt} + |A|^2 A + \nu |A|^4 A = i \delta A + i \beta A_{tt} + i |A|^2 A + i \mu |A|^4 A CQCGL1dRpo(int N, double d, double delta, double beta, double D, double epsilon, double mu, double nu, int dimTan); ~CQCGL1dRpo(); CQCGL1dRpo & operator=(const CQCGL1dRpo &x); //////////////////////////////////////////////////////////// static std::string toStr(double x); static std::string toStr(double x, double y, int id); static void write(const std::string fileName, const std::string groupName, const MatrixXd &x, const double T, const int nstp, const double th, const double phi, double err); static void write2(const std::string fileName, const std::string groupName, const MatrixXd &x, const int nstp, double err); static std::tuple<MatrixXd, double, int, double, double, double> read(const std::string fileName, const std::string groupName); static void move(std::string infile, std::string ingroup, std::string outfile, std::string outgroup, int flag); static VectorXcd readE(std::string fileName, const std::string groupName); static MatrixXd readV(std::string fileName, const std::string groupName); static void writeE(std::string fileName, const std::string groupName, const VectorXcd &e); static void writeV(std::string fileName, const std::string groupName, const MatrixXd &v); //////////////////////////////////////////////////////////// std::tuple<VectorXd, double, double, double, double> findRPO(const VectorXd &x0, const double T, const double th0, const double phi0, const double tol = 1e-12, const int btMaxIt = 20, const int maxit = 100, const double eta0 = 1e-4, const double t = 1e-4, const double theta_min = 0.1, const double theta_max = 0.5, const int GmresRestart = 30, const int GmresMaxit = 100); std::tuple<MatrixXd, double, double, double, double> findRPOM(const MatrixXd &x0, const double T, const double th0, const double phi0, const double tol = 1e-12, const int btMaxIt = 20, const int maxit = 100, const double eta0 = 1e-4, const double t = 1e-4, const double theta_min = 0.1, const double theta_max = 0.5, const int GmresRestart = 30, const int GmresMaxit = 100); std::tuple<VectorXd, double, double, double, double> findRPO_hook(const VectorXd &x0, const double T, const double th0, const double phi0, const double tol, const double minRD, const int maxit, const int maxInnIt, const double GmresRtol, const int GmresRestart, const int GmresMaxit); std::tuple<MatrixXd, double, double, double, double> findRPOM_hook(const MatrixXd &x0, const double T, const double th0, const double phi0, const double tol = 1e-12, const double minRD = 1e-3, const int maxit = 100, const int maxInnIt = 20, const double GmresRtol = 1e-6, const int GmresRestart = 100, const int GmresMaxit = 100); VectorXd calPre(const VectorXd &x, const VectorXd &dx); std::tuple<MatrixXd, double, int> findRPOM_hook2(const MatrixXd &x0, const int nstp, const double tol, const double minRD, const int maxit, const int maxInnIt, const double GmresRtol, const int GmresRestart, const int GmresMaxit); void findRpoParaSeq(const std::string file, int id, double step, int Ns, bool isBi, int nstpFlag, int paraNstp); std::tuple<SpMat, SpMat, VectorXd> calJJF(const VectorXd &x); std::tuple<MatrixXd, double> findRPOM_LM(const MatrixXd &x0, const double tol, const int maxit, const int innerMaxit); //////////////////////////////////////////////////////////// VectorXd MFx(const VectorXd &x, int nstp); VectorXd MDFx(const VectorXd &x, const VectorXd &dx, int nstp); VectorXd MFx2(const VectorXd &x, int nstp); VectorXd MDFx2(const VectorXd &x, const VectorXd &dx, int nstp); }; template<class Mat> struct cqcglJJF { typedef Eigen::SparseMatrix<double> SpMat; CQCGL1dRpo &rpo; cqcglJJF(CQCGL1dRpo &rpo_) : rpo(rpo_){} std::tuple<SpMat, SpMat, VectorXd> operator()(const VectorXd &x) { return rpo.calJJF(x); } }; #endif /* CQCGL1dRpo */ <file_sep>// how to compile // h5c++ -O3 test_myH5.cc -L../../lib -I../../include -I$EIGEN -std=c++11 -lmyH5 -lm #include "myH5.hpp" using namespace H5; using namespace std; using namespace Eigen; using namespace MyH5; #define N10 int main(){ #ifdef N10 //====================================================================== string s = "/usr/local/home/xiong/00git/research/data/cgl/reqsubBiGi.h5"; vector<vector<string>> x = scanGroup(s); for(auto v : x){ for(auto s : v) cout << s; cout << endl; } #endif return 0; } <file_sep>#include <boost/python.hpp> #include <cstdio> using namespace std; namespace bp = boost::python; ////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////// class Base { public : int x; Base(int x) : x(x) {} Base(){} }; class Test { public: int N; Base b; Test(int N) : N(N) { b.x = 1; } }; ////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////// BOOST_PYTHON_MODULE(py_test) { bp::class_<Base>("Base", bp::init<int>()) .def_readwrite("x", &Base::x) ; bp::class_<Test>("Test", bp::init<int>()) .def_readwrite("N", &Test::N) .def_readwrite("b", &Test::b) //.def("redV2", &pyKS::PYredV2) ; } <file_sep>from personalFunctions import * case = 10 if case == 10: """ check the angle along one orbit maxElement.dat stores the data for ppo147 the largest absolute off diagonal elements """ f = './anglePOs64/ppo/space/147/ang1.dat' ang = np.arccos(np.loadtxt(f)) fig, ax = pl2d(yscale='log', labs=[r'$t$', r'$\theta$'], tickSize=18) ax.plot(ang[::10]) ax2d(fig, ax) off = np.loadtxt('maxElement.dat') fig, ax = pl2d(yscale='log', labs=[r'$t$', r'$\max|R_{ij}|$'], tickSize=18) ax.plot(off) ax2d(fig, ax) <file_sep>CC = g++ AR = ar OPTIM = -O3 -msse2 -msse4 -march=corei7 INCLUDE = ../../include EIGEN = /usr/local/home/xiong/apps/eigen/include/eigen3 CFLAGS = -std=c++11 LIB = ../../lib # for pace cluster ifdef pace OPTIM = -O3 EIGEN = /nv/hp16/xding35/data/apps/eigen/include/eigen3 endif #### CLEANUP = no ifeq ($(CLEANUP), yes) CFLAGS += -DCLEAN endif SOURCE = myfft.cc SHARED = $(addprefix lib, $(addsuffix .so, $(basename $(word 1, $(SOURCE))))) STATIC = $(addprefix lib, $(addsuffix .a, $(basename $(word 1, $(SOURCE))))) all : $(SHARED) $(STATIC) $(SHARED): $(SOURCE) $(CC) -shared -fpic $(CFLAGS) $(OPTIM) -I$(INCLUDE) -I$(EIGEN) $^ -o $@ $(SOURCE:.cc=.o) : $(SOURCE) $(CC) -c $(CFLAGS) $(OPTIM) -I$(INCLUDE) -I$(EIGEN) $^ $(STATIC): $(SOURCE:.cc=.o) $(AR) crs $@ $^ clean: rm -f *.so *.o *.a move: mv *.so *.a $(LIB) <file_sep>/* How to compile: * h5c++ test_KSPO.cc -L../../lib -I../../include -I$EIGEN -std=c++11 -lKSPO -lksint -lmyH5 -literMethod -ldenseRoutines -lsparseRoutines -lped -lfftw3 -lm * * mpicxx has flag -cxx, which can be used to specify cc compiler. eg. -cxx=h5c++ * */ #include "KSPO.hpp" #include "ksint.hpp" #include "myH5.hpp" #include <iostream> #include <cmath> //#include <mpi.h> using namespace std; using namespace Eigen; using namespace MyH5; #define CASE_60 int main(int argc, char **argv) { #ifdef CASE_10 //================================================================================ // move data string fin = "../../data/ks22h001t120x64EV.h5"; H5File fin2(fin, H5F_ACC_RDONLY); string fout = "tmp.h5"; H5File fout2(fout, H5F_ACC_TRUNC); VectorXd a; double T, r, s; int nstp; MatrixXd es, vs; vector<vector<string>> gs = scanGroup(fin); for(auto v : gs){ bool isRPO = v[0] == "rpo"; std::tie(a, T, nstp, s, r) = KSPO::read(fin2, v[0] + "/" + v[1], isRPO); KSPO::write(fout2, KSPO::toStr(v[0], stoi(v[1])), isRPO, a, T, nstp, -s/22*2*M_PI, r); if(checkGroup(fin2, v[0] + "/" + v[1] + "/e", false)){ es = KSPO::readE(fin2, v[0] + "/" + v[1]); vs = KSPO::readV(fin2, v[0] + "/" + v[1]); KSPO::writeE(fout2, KSPO::toStr(v[0], stoi(v[1])), es); KSPO::writeV(fout2, KSPO::toStr(v[0], stoi(v[1])), vs); } } #endif #ifdef CASE_20 //================================================================================ // test multiF(). For rpo, the shift should be reversed. int N = 64; double L = 22; KSPO ks(N, L); string fileName = "../../data/ks22h001t120x64EV.h5"; H5File file(fileName, H5F_ACC_RDONLY); string ppType = "rpo"; bool isRPO = ppType == "rpo"; int ppId = 1; ArrayXd a; double T, theta, err; int nstp; std::tie(a, T, nstp, theta, err) = ks.read(file, ks.toStr(ppType, ppId), isRPO); VectorXd x(ks.N); x << a, T, theta; VectorXd F = ks.MFx(x, nstp, isRPO); cout << F.norm() << endl; #endif #ifdef CASE_30 //================================================================================ // findPO from one L = 22 orbit int N = 64; double L = 21.95; KSPO ks(N, L); string fileName = "../../data/ks22h001t120x64EV.h5"; H5File file(fileName, H5F_ACC_RDONLY); string ppType = "rpo"; bool isRPO = ppType == "rpo"; int ppId = 1; int M = 10; ArrayXd a; double T, theta, err; int nstp; std::tie(a, T, nstp, theta, err) = ks.read(file, ks.toStr(ppType, ppId), isRPO); nstp /= 10; ArrayXXd aa = ks.intgC(a, T/nstp, T, nstp/M); ArrayXXd x; if(isRPO){ x.resize(ks.N, M); x << aa, ArrayXXd::Ones(1, M) * T/M, ArrayXXd::Zero(1, M); x(N-1, M-1) = theta; } else { x.resize(ks.N - 1, M); x << aa, ArrayXXd::Ones(1, M) * T/M; } ArrayXXd ap; double errp; int flag; std::tie(ap, errp, flag) = ks.findPO_LM(x, isRPO, nstp/M, 1e-12, 100, 30); double Tp = ap.row(N-2).sum(); double thetap = isRPO ? ap.row(N-1).sum() : 0; H5File fout("tmp.h5", H5F_ACC_RDWR); if (flag == 0) ks.write(fout, ks.toStr(L, ppType, ppId), isRPO, ap.col(0).head(N-2), Tp, nstp, thetap, errp); #endif #ifdef CASE_40 //================================================================================ // findPO sequentially change parameters int N = 64; string fileName = "../../data/ksh01x64.h5"; H5File file(fileName, H5F_ACC_RDWR); string ppType = "rpo"; bool isRPO = ppType == "rpo"; int ppId = 2; int M = 10; ArrayXd a; double T, theta, err, errp; int nstp, flag; ArrayXXd ap; double dL = 0.05, L0 = 21.4; for(int i = 0; i < 5; i++){ double L = L0 - i*dL; KSPO ks(N, L); std::tie(a, T, nstp, theta, err) = ks.read(file, ks.toStr(L + dL, ppType, ppId), isRPO); ArrayXXd aa = ks.intgC(a, T/nstp, T, nstp/M); ArrayXXd x; if(isRPO){ x.resize(ks.N, M); x << aa, ArrayXXd::Ones(1, M) * T/M, ArrayXXd::Zero(1, M); x(N-1, M-1) = theta; } else { x.resize(ks.N - 1, M); x << aa, ArrayXXd::Ones(1, M) * T/M; } std::tie(ap, errp, flag) = ks.findPO_LM(x, isRPO, nstp/M, 1e-12, 100, 30); double Tp = ap.row(N-2).sum(); double thetap = isRPO ? ap.row(N-1).sum() : 0; if (flag == 0) ks.write(file, ks.toStr(L, ppType, ppId), isRPO, ap.col(0).head(N-2), Tp, nstp, thetap, errp); else exit(1); } #endif #ifdef CASE_50 //================================================================================ // calculate E/V int N = 64; double L = 21.95; KSPO ks(N, L); string fileName = "../../data/ksh01x64.h5"; H5File file(fileName, H5F_ACC_RDONLY); string ppType = "ppo"; bool isRPO = ppType == "rpo"; int ppId = 1; ArrayXd a; double T, theta, err; int nstp; std::tie(a, T, nstp, theta, err) = ks.read(file, ks.toStr(L, ppType, ppId), isRPO); auto ev = ks.calEV(isRPO, a, T, nstp, theta, 1e-12, 1000, 10); MatrixXd &e = ev.first, &v = ev.second; cout << e << endl; #endif #ifdef CASE_60 //================================================================================ // calculate E/V for all rpo/ppo int N = 64; string fileName = "../../data/ksh01x64EV.h5"; H5File file(fileName, H5F_ACC_RDWR); auto gs = scanGroup(fileName); ArrayXd a; double T, theta, err; int nstp; for(auto ss : gs){ double L = stod(ss[0]); string ppType = ss[1]; bool isRPO = ppType == "rpo"; int ppId = stoi(ss[2]); string groupName = KSPO::toStr(L, ppType, ppId); if (!checkGroup(file, groupName + "/e", false)){ KSPO ks(N, L); std::tie(a, T, nstp, theta, err) = ks.read(file, groupName, isRPO); auto ev = ks.calEV(isRPO, a, T, nstp, theta, 1e-12, 1500, 10); MatrixXd &e = ev.first, &v = ev.second; ks.writeE(file, groupName, e.topRows(10)); ks.writeV(file, groupName, v); } } #endif return 0; } <file_sep>#include "iterMethod.hpp" namespace iterMethod { //////////////////////////////////////////////////////////////////////////////////////////////////// // global variables bool CG_PRINT = true; int CG_PRINT_FREQUENCE = 100; bool GMRES_OUT_PRINT = true; int GMRES_OUT_PRINT_FREQUENCE = 1; bool GMRES_IN_PRINT = true; int GMRES_IN_PRINT_FREQUENCE = 1; bool HOOK_PRINT = true; int HOOK_PRINT_FREQUENCE = 1; bool INB_OUT_PRINT = true; int INB_OUT_PRINT_FREQUENCE = 1; bool INB_IN_PRINT = true; int INB_IN_PRINT_FREQUENCE = 1; bool LM_OUT_PRINT = true; int LM_OUT_PRINT_FREQUENCE = 1; bool LM_IN_PRINT = true; int LM_IN_PRINT_FREQUENCE = 1; double LM_LAMBDA_INCREASE_FACTOR = 10; double LM_LAMBDA_DECREASE_FACTOR = 10; double LM_MAX_LAMBDA = 1e10; //////////////////////////////////////////////////////////////////////////////////////////////////// /** * @brief obtain the cos and sin from coordinate (x, y) */ void rotmat(const double &x, const double &y, double *c, double *s){ if(y == 0){ *c = 1; *s = 0; } else if ( fabs(y) > fabs(x) ){ double tmp = x / y; *s = 1.0 / sqrt(1.0 + tmp*tmp); *c = tmp * (*s); } else { double tmp = y / x; *c = 1.0 / sqrt(1.0 + tmp*tmp); *s = tmp * (*c); } } /** * @brief choose the scaling parameter theta in the Inexact Newton Backtracking algorithm * * When choosing theta, we take a quadratic model * g(theta) = ||F(x + theta * s)|| = (g(1) - g(0) - g'(0))*theta^2 + g'(0)*theta + g(0) * with * g'(0) = 2 * F^{T}(x) * F'(x) * s * The derivatives are: * g'(theta) = 2 * (g(1) - g(0) - g'(0))*theta + g'(0) * g''(theta) = 2 * (g(1) - g(0) - g'(0)) * * If g''(0) < 0, take theta = theta_max * If g''(0) > 0, take theta = - g'(0) / 2 * (g(1) - g(0) - g'(0)) */ double chooseTheta(const double g0, const double g1, const double gp0, const double theta_min, const double theta_max){ double theta; double gpp0 = 2 * (g1 - g0 - gp0); if (gpp0 < 0) theta = theta_max; else theta = -gp0 / gpp0; // restrict theta in [theta_min, theta_max] return theta > theta_max ? theta_max : (theta < theta_min ? theta_min : theta); } ////////////////////////////////////////////////////////////////////// /////////////////// trust region GMRES related ///////////////////// ////////////////////////////////////////////////////////////////////// /** * @brief calculate z = d_i * p_i / (d_i^2 + mu) */ ArrayXd calz(const ArrayXd &D, const ArrayXd &p, const double mu){ return D * p / (D.square() + mu); } /** * @brief use newton method to find the parameter mu which minize * ||D*z - p|| w.r.t. ||z||< delta */ std::tuple<double, std::vector<double>, int> findTrustRegion(const ArrayXd &D, const ArrayXd &p, double delta, const double tol, const int maxit, const double mu0){ double mu = mu0; std::vector<double> errVec; // first check whether mu = 0 is enough if( (p / D).matrix().norm() <= delta ) return std::make_tuple(0, errVec, 0); // use Newton iteration to find mu for(size_t i = 0; i < maxit; i++){ ArrayXd denorm = D.square() + mu; /* di^2 + mu */ ArrayXd z = D * p / denorm; /* z */ double z2 = z.matrix().squaredNorm(); /* ||z||^2 */ double phi = z2 - delta * delta; /* phi(mu) */ errVec.push_back(phi); if(fabs(phi) < tol) return std::make_tuple(mu, errVec, 0); double dphi = (-2*(D * p).square() / denorm * denorm * denorm).sum(); mu -= (sqrt(z2) / delta) * ( phi / dphi ); // mu -= phi / dphi ; } // run out of loop => not converged return std::make_tuple(mu, errVec, 1); } ////////////////////////////////////////////////////////////////////// // Levenberg-Marquardt related // ////////////////////////////////////////////////////////////////////// /* std::tuple<MatrixXd, MatrixXd, VectorXd> JJF(const MatrixXd &J, const VectorXd &x){ MatrixXd JJ = J.transpose() * J; MatrixXd d = JJ.diagonal().asDiagonal(); return std::make_tuple(JJ, d, J*x); } */ std::tuple<VectorXd, std::vector<double>, int> LM( const MatrixXd &A, const VectorXd &b, const VectorXd &x0, const double tol, const int maxit, const int innerMaxit){ ColPivHouseholderQR<MatrixXd> solver; auto fx = [&A, &b](const VectorXd &x) { return A*x - b; }; JJF<MatrixXd> jj(A, b); return LM0( fx, jj, solver, x0, tol, maxit, innerMaxit ); } } <file_sep>from py_CQCGL1d import * from cglHelp import * case = 16 if case == 8: """ calculate the stability exponents of req of different di. At the same time, compare it with the linear part of the velocity """ N = 1024 d = 30 di = 0.06 a0, wth0, wphi0, err = cqcglReadReqdi('../../data/cgl/reqDi.h5', di, 1) cgl = pyCQCGL(N, d, 4.0, 0.8, 0.01, di, 0, 4) eigvalues, eigvectors = eigReq(cgl, a0, wth0, wphi0) print eigvalues[:10] e = eigvalues L0 = cgl.L() L1 = cgl.C2R(L0) L2 = L1[::2] + 1j*L1[1::2] L2 = 1 / L2 L3 = np.zeros(cgl.Ndim) L3[::2] = L2.real L3[1::2] = L2.imag L = cgl.L()[:cgl.Ne/2] scatter2dfig(L.real, L.imag) scatter2dfig(e.real, e.imag) def dp(A, L): n = len(L) for i in range(n): A[:, i] = A[:, i] * L[i] return A A = cgl.stabReq(a0, wth0, wphi0).T Ap = dp(A, L3) e2, v2 = eig(Ap) e2, v2 = sortByReal(e2, v2) if case == 10: """ use the new data to calculate tyhe stability exponents of req """ N = 1024 d = 50 Bi = 0.8 Gi = -0.6 index = 1 cgl = pyCQCGL1d(N, d, -0.1, 0.125, 0.5, 1, Bi, -0.1, Gi, 0) req = CQCGLreq(cgl) a0, wth0, wphi0, err0 = req.readReqBiGi('../../data/cgl/reqBiGi.h5', Bi, Gi, index) e, v = req.eigReq(a0, wth0, wphi0) print e[:10] if case == 11: """ calculate the stability exponents and 10 leading vectors save them into the database """ N = 1024 d = 30 h = 0.0002 for i in range(len(dis)): a0, wth0, wphi0, err = cqcglReadReq(files[i], '1') cgl = pyCqcgl1d(N, d, h, True, 0, 4.0, 0.8, 0.01, dis[i], 4) e, v = eigReq(cgl, a0, wth0, wphi0) print e[:8] cqcglAddEV2Req(files[i], '1', e.real, e.imag, v[:, :10].real, v[:, :10].imag) if case == 12: """ simply view the heat map of relative equilibria """ N = 1024 d = 30 h = 1e-4 di = 0.96 a0, wth0, wphi0, err0 = cqcglReadReqdi('../../data/cgl/reqDi.h5', di, 2) cgl = pyCQCGL1d(N, d, 4.0, 0.8, 0.01, di, -1) nstp = 10000 for i in range(3): aa = cgl.intg(a0, h, nstp, 10) a0 = aa[-1] plotConfigSpaceFromFourier(cgl, aa, [0, d, 0, nstp*h]) if case == 13: """ new size L = 50 """ N = 1024 d = 50 h = 1e-4 di = 0.96 a0, wth0, wphi0, err0 = cqcglReadReqdi('../../data/cgl/reqDi.h5', di, 1) a1, wth1, wphi1, err1 = cqcglReadReqdi('../../data/cgl/reqDi.h5', di, 2) cgl = pyCQCGL1d(N, d, 4.0, 0.8, 0.01, di, -1) plotOneConfigFromFourier(cgl, a0) plotOneConfigFromFourier(cgl, a1) if case == 14: N = 1024 d = 30 h = 1e-4 Q0 = [] Q1 = [] dis = np.arange(0.08, 0.57, 0.01) for i in range(len(dis)): di = dis[i] cgl = pyCQCGL1d(N, d, 4.0, 0.8, 0.01, di, -1) a0, wth0, wphi0, err0 = cqcglReadReqdi('../../data/cgl/reqDi.h5', di, 1) a1, wth1, wphi1, err1 = cqcglReadReqdi('../../data/cgl/reqDi.h5', di, 2) Q0.append(cgl.calQ(a0)[0]) Q1.append(cgl.calQ(a1)[0]) fig, ax = pl2d(labs=[r'$d_i$', r'$Q$'], axisLabelSize=25, tickSize=15) ax.plot(dis, Q0, lw=2, c='r', ls='-') ax.plot(dis, Q1, lw=2, c='b', ls='--') ax2d(fig, ax) if case == 16: """ to see different profiles with L = 50 More : to see the transition from req to rpo in the stable region """ N, d = 1024, 50 h = 2e-3 Bi, Gi = 0.8, -0.6 index = 1 cgl = pyCQCGL1d(N, d, -0.1, 0.125, 0.5, 1, Bi, -0.1, Gi, -1) req = CQCGLreq(cgl) cp = CQCGLplot(cgl) a0, wth0, wphi0, err0, e, v = req.readBiGi('../../data/cgl/reqBiGiEV.h5', Bi, Gi, index, flag=2) print e[:20] T = 60 a0 += 0.1*norm(a0)*v[0].real for i in range(1): aa = cgl.intgC(a0, h, T, 10) a0 = aa[-1] cp.config(aa, [0, d, 0, T]) if case == 17: """ view the req with new L """ N = 1024 d = 50 h = 2e-3 Bi = 2.7 Gi = -5.6 index = 1 cgl = pyCQCGL1d(N, d, -0.1, 0.125, 0.5, 1, Bi, -0.1, Gi, 0) req = CQCGLreq(cgl) fig, ax = pl2d(size=[8, 6], labs=[r'$x$', r'$|A|$'], axisLabelSize=25, tickSize=16) a0, wth0, wphi0, err0 = req.readReqBiGi('../../data/cgl/reqBiGiEV.h5', Bi, Gi, 1, flag=0) Aamp = np.abs(cgl.Fourier2Config(a0)) ax.plot(np.linspace(0, d, Aamp.shape[0]), Aamp, lw=2, c='r') a0, wth0, wphi0, err0 = req.readReqBiGi('../../data/cgl/reqBiGiEV.h5', Bi, Gi, 2, flag=0) Aamp = np.abs(cgl.Fourier2Config(a0)) ax.plot(np.linspace(0, d, Aamp.shape[0]), Aamp, lw=2, c='b') ax2d(fig, ax) if case == 18: """ Plot the solitons in the Bi-Gi plane to see the transition. """ N = 1024 d = 50 h = 2e-3 fileName = '../../data/cgl/reqBiGi.h5' for i in range(90): Bi = -3.2 + i * 0.1 fig, ax = pl2d(size=[8, 6], labs=[r'$x$', r'$|A|$'], ylim=[-0.5, 3], axisLabelSize=25) name = format(Bi, '013.6f') + '.png' for j in range(55): Gi = -0.2 - 0.1*j cgl = pyCQCGL1d(N, d, -0.1, 0.125, 0.5, 1, Bi, -0.1, Gi, 0) req = CQCGLreq(cgl) if req.checkExist(fileName, req.toStr(Bi, Gi, 1)): a0, wth0, wphi0, err0 = req.readReqBiGi(fileName, Bi, Gi, 1) Aamp = np.abs(cgl.Fourier2Config(a0)) ax.plot(np.linspace(0, d, Aamp.shape[0]), Aamp) if req.checkExist(fileName, req.toStr(Bi, Gi, 2)): a0, wth0, wphi0, err0 = req.readReqBiGi(fileName, Bi, Gi, 2) Aamp = np.abs(cgl.Fourier2Config(a0)) ax.plot(np.linspace(0, d, Aamp.shape[0]), Aamp) ax2d(fig, ax, save=True, name='ex/'+name) if case == 19: """ plot the stability of req in the Bi-Gi plane and save the data """ N = 1024 d = 50 h = 2e-3 fileName = '../../data/cgl/reqBiGiEV.h5' index = 1 cs = {0: 'g', 1: 'm', 2: 'c', 4: 'r', 6: 'b'}#, 8: 'y', 56: 'r', 14: 'grey'} ms = {0: 's', 1: '^', 2: '+', 4: 'o', 6: 'D'}#, 8: '8', 56: '4', 14: 'v'} es = np.zeros([90, 55, 1362], dtype=np.complex) e1 = np.zeros((90, 55), dtype=np.complex) ns = set() saveData = np.zeros([0, 3]) fig, ax = pl2d(size=[8, 6], labs=[r'$G_i$', r'$B_i$'], axisLabelSize=25, xlim=[-6, 0], ylim=[-4, 6]) for i in range(90): Bi = 5.7 - i*0.1 for j in range(55): Gi = -0.2 - 0.1*j req = CQCGLreq() if req.checkExist(fileName, req.toStr(Bi, Gi, index) + '/vr'): a0, wth0, wphi0, err0, e, v = req.readReqBiGi(fileName, Bi, Gi, index, flag=2) es[i, j, :] = e m, ep, accu = numStab(e) e1[i, j] = ep[0] ns.add(m) # print index, Bi, Gi, m ax.scatter(Gi, Bi, s=15, edgecolors='none', marker=ms.get(m, '*'), c=cs.get(m, 'k')) saveData = np.vstack((saveData, np.array([Gi, Bi, m]))); ax.grid(which='both') ax2d(fig, ax) np.savetxt("BiGiReqStab.dat", saveData) if case == 20: """ check req really converges """ fileName = '../../data/cgl/reqBiGiEV.h5' index = 2 for i in range(90): Bi = 3.4 - i*0.1 for j in range(55): Gi = -0.2 - 0.1*j req = CQCGLreq() if req.checkExist(fileName, req.toStr(Bi, Gi, index)): a0, wth0, wphi0, err0= req.readReqBiGi(fileName, Bi, Gi, index) if err0 > 1e-6: print err0, Bi, Gi if case == 30: """ Try to locate the Hopf bifurcation limit cycle. There is singularity for reducing the discrete symmetry """ N = 1024 d = 30 h = 0.0005 di = 0.37 a0, wth0, wphi0, err = cqcglReadReqdi('../../data/cgl/reqDi.h5', di, 1) cgl = pyCqcgl1d(N, d, h, True, 0, 4.0, 0.8, 0.01, di, 4) eigvalues, eigvectors = eigReq(cgl, a0, wth0, wphi0) eigvectors = Tcopy(realve(eigvectors)) a0Hat = cgl.orbit2slice(a0)[0] a0Tilde = cgl.reduceReflection(a0Hat) veHat = cgl.ve2slice(eigvectors, a0) # veTilde = cgl.reflectVe(veHat, a0Hat) nstp = 10000 # a0Erg = a0 + eigvectors[0]*1e2 A0 = 2*centerRand(2*N, 0.2) a0Erg = cgl.Config2Fourier(A0) for i in range(2): aaErg = cgl.intg(a0Erg, nstp, 1) a0Erg = aaErg[-1] aaErgHat, th, phi = cgl.orbit2slice(aaErg) # aaErgTilde = cgl.reduceReflection(aaErgHat) # aaErgTilde -= a0Tilde aaErgHat -= a0Hat # e1, e2, e3 = orthAxes(veTilde[0], veTilde[1], veTilde[6]) e1, e2 = orthAxes2(veHat[0], veHat[1]) # aaErgTildeProj = np.dot(aaErgTilde, np.vstack((e1, e2, e3)).T) aaErgHatProj = np.dot(aaErgHat, np.vstack((e1, e2)).T) fig = plt.figure(figsize=[6, 4]) ax = fig.add_subplot(111) # ax.plot(aaErgTildeProj[:, 0], aaErgTildeProj[:, 1], # aaErgTildeProj[:, 2], c='r', lw=1) ax.plot(aaErgHatProj[:, 0], aaErgHatProj[:, 1], c='r', lw=1) ax.scatter(aaErgHatProj[0, 0], aaErgHatProj[0, 1], s=30, facecolor='g') ax.scatter(aaErgHatProj[-1, 0], aaErgHatProj[-1, 1], s=30, facecolor='k') ax.scatter([0], [0], s=160) ax.set_xlabel(r'$e_1$', fontsize=25) ax.set_ylabel(r'$e_2$', fontsize=25) fig.tight_layout(pad=0) plt.show(block=False) if case == 31: """ Try to find the guess of the limit cycle for di large enough such that the soliton is unstable. """ N = 1024 d = 30 h = 0.0004 di = 0.43 cgl = pyCqcgl1d(N, d, h, True, 0, 4.0, 0.8, 0.01, di, 4) A0 = 2*centerRand(2*N, 0.2) a0 = cgl.Config2Fourier(A0) nstp = 10000 x = [] for i in range(3): aa = cgl.intg(a0, nstp, 1) a0 = aa[-1] plotConfigSpaceFromFourier(cgl, aa, [0, d, 0, nstp*h]) # plotPhase(cgl, aa, [0, d, 0, nstp*h]) # plotOneConfigFromFourier(cgl, aa[-1], d) # plotOnePhase(cgl, aa[-1], d) # plot1dfig(aa[:, 0]) x.append(aa) aaHat, th, phi = cgl.orbit2slice(aa) i1 = 3000 i2 = 6800 plot3dfig(aaHat[i1:i2, 0], aaHat[i1:i2, 1], aaHat[i1:i2, 2]) plotConfigSpaceFromFourier(cgl, aa[i1:i2], [0, d, 0, nstp*h]) nstp = i2 - i1 T = nstp * h th0 = th[i1] - th[i2] phi0 = phi[i1] - phi[i2] err = norm(aaHat[i1] - aaHat[i2]) print nstp, T, th0, phi0, err # cqcglSaveRPOdi('rpot.h5', di, 1, aa[i1], T, nstp, th0, phi0, err) if case == 40: """ compare the Hopf bifurcation limit cycle with slightly different di """ N = 1024 d = 30 h = 0.0002 dis = [-0.07985, -0.0799, -0.08] files = ['req07985.h5', 'req0799.h5', 'req08.h5'] orbits = [] for i in range(len(dis)): a0, wth0, wphi0, err = cqcglReadReq(files[i], '1') cgl = pyCqcgl1d(N, d, h, True, 0, 4.0, 0.8, -0.01, dis[i], 4) eigvalues, eigvectors = eigReq(cgl, a0, wth0, wphi0) print eigvalues[:8] eigvectors = Tcopy(realve(eigvectors)) a0Hat = cgl.orbit2slice(a0)[0] veHat = cgl.ve2slice(eigvectors, a0) nstp = 20000 a0Erg = a0 + eigvectors[0]*1e-3 for i in range(10): aaErg = cgl.intg(a0Erg, nstp, 1) a0Erg = aaErg[-1] aaErgHat, th, phi = cgl.orbit2slice(aaErg) aaErgHat -= a0Hat e1, e2 = orthAxes2(veHat[0], veHat[1]) aaErgHatProj = np.dot(aaErgHat, np.vstack((e1, e2)).T) orbits.append(aaErgHatProj) fig = plt.figure(figsize=[6, 4]) ax = fig.add_subplot(111) for i in range(len(orbits)): ax.plot(orbits[i][:, 0], orbits[i][:, 1], lw=1, label=str(dis[i])) ax.scatter([0], [0], s=160) ax.set_xlabel(r'$e_1$', fontsize=25) ax.set_ylabel(r'$e_2$', fontsize=25) fig.tight_layout(pad=0) plt.legend(loc='upper right', frameon=False) plt.show(block=False) if case == 50: """ visualize a few explosion examples in the covariant coordinate. Only care about the part after explosion. """ N = 1024 d = 30 h = 0.0002 di = -0.0799 a0, wth0, wphi0, err = cqcglReadReq('req0799.h5', '1') cgl = pyCqcgl1d(N, d, h, True, 0, 4.0, 0.8, -0.01, di, 4) eigvalues, eigvectors = eigReq(cgl, a0, wth0, wphi0) eigvectors = Tcopy(realve(eigvectors)) a0Hat = cgl.orbit2slice(a0)[0] veHat = cgl.ve2slice(eigvectors, a0) e1, e2, e3 = orthAxes(veHat[0], veHat[1], veHat[4]) aa1 = load('0799_v6.npz')['x'] aa1Hat, th1, phi1 = cgl.orbit2slice(aa1) aa1Hat -= a0Hat aa1HatProj = np.dot(aa1Hat, np.vstack((e1, e2, e3)).T) plotConfigSpaceFromFourier(cgl, aa1, [0, d, 0, aa1.shape[0]*h]) id1 = 4000 id2 = aa1.shape[0] - 12000 fig = plt.figure(figsize=[6, 4]) ax = fig.add_subplot(111) ax.plot(aa1HatProj[id1:id2, 0], aa1HatProj[id1:id2, 1], c='r', lw=1) ax.scatter(aa1HatProj[id1, 0], aa1HatProj[id1, 1], s=30) ax.scatter([0], [0], s=160) ax.set_xlabel(r'$e_1$', fontsize=25) ax.set_ylabel(r'$e_2$', fontsize=25) fig.tight_layout(pad=0) plt.show(block=False) fig = plt.figure(figsize=[6, 4]) ax = fig.add_subplot(111, projection='3d') ax.plot(aa1HatProj[id1:id2, 0], aa1HatProj[id1:id2, 1], aa1HatProj[id1:id2, 2], c='r', lw=1) ax.scatter(aa1HatProj[id1, 0], aa1HatProj[id1, 1], aa1HatProj[id1, 2], s=30) ax.scatter([0], [0], [0], s=160) ax.set_xlabel(r'$e_1$', fontsize=25) ax.set_ylabel(r'$e_2$', fontsize=25) ax.set_zlabel(r'$e_3$', fontsize=25) fig.tight_layout(pad=0) plt.show(block=False) if case == 60: """ In the case that we visualize Hopf limit cycle and the explosion in the same frame, we find that after explosion, the system almost lands in a closed cycle. This is a good candidate for search periodic orbits. So, we record it. """ N = 1024 d = 30 h = 0.0002 di = -0.0799 cgl = pyCqcgl1d(N, d, h, True, 0, 4.0, 0.8, -0.01, di, 4) aa1 = load('0799_v4.npz')['x'] aa1Hat, th1, phi1 = cgl.orbit2slice(aa1) i1 = 0 i2 = 1 i3 = 2 id1 = 19810 id2 = 20000 plot3dfig(aa1Hat[id1:id2+1, i1], aa1Hat[id1:id2+1, i2], aa1Hat[id1:id2+1, i3]) x = aa1[id1] nstp = id2 - id1 T = nstp * h th = th1[id1] - th1[id2] phi = phi1[id1] - phi1[id2] err = 1000.0 print T, th, phi, err cqcglSaveRPO('rpo3.h5', '1', x, T, nstp, th, phi, err) if case == 70: """ construct the plane wave solutions and get their stability """ N = 1024 L = 30 h = 0.0002 b = 4.0 c = 0.8 dr = 0.01 di = 0.07985 cgl = pyCqcgl1d(N, L, h, True, 0, b, c, dr, di, 4) m = 14 k = 2*np.pi / L * m a2 = 1/(2*dr) * (1 + np.sqrt(1-4*dr*(k**2+1))) w = b*k**2 - c*a2 + di*a2**2 a0 = np.zeros(cgl.Ndim) a0[2*m] = sqrt(a2) * N nstp = 5000 aa = cgl.intg(a0, nstp, 1) plotConfigSpaceFromFourier(cgl, aa, [0, L, 0, nstp*h]) eigvalues, eigvectors = eigReq(cgl, a0, 0, w) eigvectors = Tcopy(realve(eigvectors)) print eigvalues[:20] if case == 80: """ plot the figure show the stability of solition solutions for different di """ N = 1024 d = 30 dis, reqs = cqcglReadReqEVAll('../../data/cgl/reqDi.h5', 1) ers = [] for i in range(len(reqs)): a, wth, wphi, err, er, ei, vr, vi = reqs[i] k = 0 while abs(er[k]) < 1e-8: k += 1 ers.append(er[k]) fig = plt.figure(figsize=[6, 4]) ax = fig.add_subplot(111) ax.plot([min(dis), max(dis)], [0, 0], c='r', ls='--', lw=1.5) ax.scatter(dis, ers, s=10, marker='o', facecolor='b', edgecolors='none') ax.set_xlabel(r'$d_i$', fontsize=20) ax.set_ylabel(r'$\mu$', fontsize=20) # ax.set_yscale('log') ax.set_xlim(0, 1) # ax.set_ylim(-2, 18) fig.tight_layout(pad=0) plt.show(block=False) if case == 90: """ view the unstable manifold of the req in the symmetry reduced projected coordinates """ N = 1024 d = 30 di = 0.06 a0, wth0, wphi0, err = cqcglReadReqdi('../../data/cgl/reqDi.h5', di, 1) cgl = pyCQCGL(N, d, 4.0, 0.8, 0.01, di, 0, 4) cgl.changeOmega(-wphi0) cgl.rtol = 1e-10 eigvalues, eigvectors = eigReq(cgl, a0, wth0, 0) eigvectors = Tcopy(realve(eigvectors)) a0Hat = cgl.orbit2slice(a0)[0] veHat = cgl.ve2slice(eigvectors, a0) T = 20 a0Erg = a0 + eigvectors[0]*1e-3 aaErg = cgl.aintg(a0Erg, 0.001, T, 1) aaErgHat, th, th = cgl.orbit2slice(aaErg) aaErgHat -= a0Hat a0E2 = a0 + eigvectors[2]*1e-3 aaE2 = cgl.aintg(a0E2, 0.001, T, 1) aaE2H, th2, phi2 = cgl.orbit2slice(aaE2) aaE2H -= a0Hat # e1, e2 = orthAxes2(veHat[0], veHat[1]) e1, e2, e3 = orthAxes(veHat[3], veHat[2], veHat[6]) bases = np.vstack((e1, e2, e3)).T aaErgHatProj = np.dot(aaErgHat, bases) OProj = np.dot(-a0Hat, bases) aaE2HP = np.dot(aaE2H, bases) i1 = 32000 i2 = 38000 fig, ax = pl3d(labs=[r'$e_1$', r'$e_2$', r'$e_3$'], axisLabelSize=25) #ax.plot(aaErgHatProj[i1:i2, 0], aaErgHatProj[i1:i2, 1], # aaErgHatProj[i1:i2, 2], c='g', lw=1, alpha=0.4) ax.plot(aaE2HP[i1:i2, 0], aaE2HP[i1:i2, 1], aaE2HP[i1:i2, 2], c='r', lw=1, alpha=0.4) ax.plot(aaE2HP[:9000, 0], aaE2HP[:9000, 1], aaE2HP[:9000, 2], c='g', lw=1, alpha=0.4) ax.plot(aaErgHatProj[:11000, 0], aaErgHatProj[:11000, 1], aaErgHatProj[:11000, 2], c='y', lw=1, alpha=1) ax.scatter([0], [0], [0], s=80, marker='o', c='b', edgecolors='none') ax.scatter(OProj[0], OProj[1], OProj[2], s=60, marker='o', c='c', edgecolors='none') ax3d(fig, ax) plotConfigSpaceFromFourier(cgl, aaErg[::10].copy(), [0, d, 0, T]) plotConfigSpaceFromFourier(cgl, aaE2[::10].copy(), [0, d, 0, T]) # vel = [] # for i in range(-10000, -000): # vel.append(norm(cgl.velocity(aaErg[i]))) if case == 100: """ view the 2 soliton solution together, and see how the unstable manifold of the first hits the second solition. """ N = 1024 d = 30 h = 0.0002 di = 0.4227 cgl = pyCqcgl1d(N, d, h, True, 0, 4.0, 0.8, 0.01, di, 4) a0, wth0, wphi0, err = cqcglReadReqdi('../../data/cgl/reqDi.h5', di, 1) a1, wth1, wphi1, err1 = cqcglReadReqdi('../../data/cgl/reqDi.h5', di, 2) eigvalues, eigvectors = eigReq(cgl, a0, wth0, wphi0) eigvectors = Tcopy(realve(eigvectors)) a0Hat = cgl.orbit2slice(a0)[0] veHat = cgl.ve2slice(eigvectors, a0) a1Hat = cgl.orbit2slice(a1)[0] a1Hat -= a0Hat h3 = 0.0005 cgl3 = pyCqcgl1d(N, d, h3, False, 0, 4.0, 0.8, 0.01, di, 4) nstp = 70000 a0Erg = a0 + eigvectors[0]*1e-3 aaErg = cgl3.intg(a0Erg, 50000, 50000) a0Erg = aaErg[-1] aaErg = cgl3.intg(a0Erg, nstp, 2) aaErgHat, th3, th3 = cgl3.orbit2slice(aaErg) aaErgHat -= a0Hat # e1, e2 = orthAxes2(veHat[0], veHat[1]) e1, e2, e3 = orthAxes(veHat[0], veHat[1], veHat[6]) aaErgHatProj = np.dot(aaErgHat, np.vstack((e1, e2, e3)).T) OProj = np.dot(-a0Hat, np.vstack((e1, e2, e3)).T) a1HatProj = np.dot(a1Hat, np.vstack((e1, e2, e3)).T) fig = plt.figure(figsize=[6, 4]) ax = fig.add_subplot(111, projection='3d') ax.plot(aaErgHatProj[:, 0], aaErgHatProj[:, 1], aaErgHatProj[:, 2], c='g', lw=1, alpha=0.4) # i1 = -1000 # ax.plot(aaErgHatProj[i1:, 0], aaErgHatProj[i1:, 1], # aaErgHatProj[i1:, 2], c='k', lw=2) ax.scatter([0], [0], [0], s=80, marker='o', c='b', edgecolors='none') ax.scatter(OProj[0], OProj[1], OProj[2], s=60, marker='o', c='c', edgecolors='none') ax.scatter(a1HatProj[0], a1HatProj[1], a1HatProj[2], s=60, marker='o', c='m', edgecolors='none') ax.set_xlabel(r'$e_1$', fontsize=25) ax.set_ylabel(r'$e_2$', fontsize=25) ax.set_zlabel(r'$e_3$', fontsize=25) fig.tight_layout(pad=0) plt.show(block=False) # plotConfigSurfaceFourier(cgl, aa1, [0, d, 0, T1]) # vel = [] # for i in range(-10000, -000): # vel.append(norm(cgl.velocity(aaErg[i]))) <file_sep>from py_CQCGL2d import * from py_CQCGL2dReq import * from personalFunctions import * case = 40 if case == 10: """ test find req """ N = 1024 d = 30 di = 0.05 cgl = pyCQCGL2dReq(N, d, 4.0, 0.8, 0.01, di, 4) c2dp = CQCGL2dPlot(d, d) a0 = c2dp.load('ex.h5', 721) # c2dp.plotOneState(cgl, 'ex.h5', 400) cgl.GmresRestart = 300 cgl.GmresRtol = 1e-6 th = -cgl.optReqTh(a0) print th x, wthx, wthy, wphi, err = cgl.findReq_hook(a0, th[0], th[1], th[2]) if case == 20: """ find the best candidate for req """ N = 1024 d = 30 di = 0.05 cgl = pyCQCGL2dReq(N, d, 4.0, 0.8, 0.01, di, 4) c2dp = CQCGL2dPlot(d, d) es = [] for i in range(750): a0 = c2dp.load('ex.h5', i) th = -cgl.optReqTh(a0) e = norm(cgl.velocityReq(a0, th[0], th[1], th[2])) es.append(e) es = np.array(es) if case == 30: """ find possible different localized invariant structures. """ N = 1024 d = 30 di = 0.05 cgl = pyCQCGL2dReq(N, d, 4.0, 0.8, 0.01, di, 4) c2dp = CQCGL2dPlot(d, d) A0 = 4*centerRand2d(N, N, 0.2, 0.2, True) a0 = cgl.Config2Fourier(A0) cgl.GmresRestart = 300 cgl.GmresRtol = 1e-6 th = -cgl.optReqTh(a0) print th x, wthx, wthy, wphi, err = cgl.findReq_hook(a0, th[0], th[1], th[2]) print "norm", norm(x) if case == 40: """ check the accuracy of the req """ N, d = 1024, 50 Bi, Gi = 0.8, -0.6 reqFile = "../../data/cgl/req2dBiGi.h5" cgl = pyCQCGL2dReq(N, d, -0.1, 0.125, 0.5, 1, Bi, -0.1, Gi, 4) c2dp = CQCGL2dPlot(d, d) a0, wthx0, wthy0, wphi0, err = c2dp.loadReq(reqFile, c2dp.toStr(Bi, Gi, 1)) v = cgl.velocityReq(a0, wthx0, wthy0, wphi0) print norm(v) if case == 60: """ find possible different localized invariant structures. for L = 50 """ N, d = 1024, 50 Bi, Gi = 0.8, -0.6 cgl = pyCQCGL2dReq(N, d, -0.1, 0.125, 0.5, 1, Bi, -0.1, Gi, 4) c2dp = CQCGL2dPlot(d, d) a0 = c2dp.load('ex.h5', 350) # A0 = 1*centerRand2d(N, N, 0.2, 0.2, True) # a0 = cgl.Config2Fourier(A0) cgl.GmresRestart = 300 cgl.GmresRtol = 1e-6 th = -cgl.optReqTh(a0) print th x, wthx, wthy, wphi, err = cgl.findReq_hook(a0, th[0], th[1], th[2]) print "norm", norm(x) <file_sep>/* compile command: * mex CXXFLAGS='-std=c++0x -fPIC -O3' intgM1.cpp ../ksint.cc ../ksintM1.cc -I../../../include -I$XDAPPS/eigen/include/eigen3 -lfftw3 * */ #include "ksintM1.hpp" #include "mex.h" #include "matrix.h" #include <cmath> #include <cstring> #include <cassert> #include <Eigen/Dense> using namespace Eigen; /* ks 1st mode slice integrator without Jacobian */ static std::pair<ArrayXXd, ArrayXd> intgM1(double *a0, int N, double h, int nstp, int np, double d){ KSM1 ks(N+2, h, d); Map<ArrayXd> v0(a0, N); return ks.intg(v0, nstp, np); } void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[]){ int np = 1; double d = 22; switch (nrhs) { case 5 : d = mxGetScalar(prhs[4]); case 4 : np = mxGetScalar(prhs[3]); case 3 : { // get the pointer and the size of input double *a0 = mxGetPr(prhs[0]); mwSize N = mxGetM(prhs[0]); mwSize M = mxGetN(prhs[0]); assert( N % 2 == 0 && M = 1 ); double h = mxGetScalar(prhs[1]); int nstp = mxGetScalar(prhs[2]); plhs[0] = mxCreateDoubleMatrix(N, nstp/np + 1, mxREAL); plhs[1] = mxCreateDoubleMatrix(nstp/np + 1, 1, mxREAL); std::pair<ArrayXXd, ArrayXd> tmp = intgM1(a0, N, h, nstp, np, d); memcpy(mxGetPr(plhs[0]), &tmp.first(0,0), (nstp/np+1)*N*sizeof(double)); memcpy(mxGetPr(plhs[1]), &tmp.second(0), (nstp/np+1)*sizeof(double)); break; // very import } default: mexErrMsgIdAndTxt( "KS_integrator:inputMismatch", " 3 =< #input <=5. Example: intg(a0, h, nstp, np, d) \n"); } } <file_sep>import h5py import matplotlib.pyplot as plt import numpy as np from mpl_toolkits.axes_grid1.inset_locator import mark_inset from mpl_toolkits.axes_grid1.inset_locator import zoomed_inset_axes from mpl_toolkits.axes_grid1.inset_locator import inset_axes import matplotlib.gridspec as gridspec from mpl_toolkits.axes_grid1 import make_axes_locatable from matplotlib.ticker import ScalarFormatter f = h5py.File('../../data/ks22h001t120x64EV.h5') pp = '/ppo/1/' e = np.array(f[pp + 'e'])[0] Nh = 16 x1 = np.kron(np.arange(1, Nh), np.array([1, 1])) x2 = np.kron(np.arange(1, 2*Nh), np.array([1, 1])) x3 = np.arange(1, 2*Nh, 0.01) d = 22 k = 2*np.pi/d*x3 k = k**2-k**4 # create figure fig = plt.figure(figsize=(5, 4)) ax = fig.add_subplot(111) ax.plot(x3, k, 'g--', linewidth=1.8, label=r'$q_k^2 - q_k^4$') ax.scatter(np.arange(1, 32), e[::2], c=(1, 0, 0), marker='o', s=22, edgecolors='none', label=r'$\mu_{2k-1}$') ax.scatter(np.arange(1, 32), e[1::2], marker='s', s=30, facecolors='none', edgecolors='k', label=r'$\mu_{2k}$') yfmt = ScalarFormatter() yfmt.set_powerlimits((0, 1)) ax.yaxis.set_major_formatter(yfmt) ax.set_xlabel('k') ax.set_yticks((-7e3, -3e3, 0, 1e3)) ax.set_xlim((0, 35)) ax.set_ylim((-7e3, 1e3)) ax.grid('on') axin = inset_axes(ax, width="45%", height="50%", loc=3) axin.scatter(np.arange(1, 32), e[::2], c=(1, 0, 0), marker='o', s=22, edgecolors='none') axin.scatter(np.arange(1, 32), e[1::2], c=(1, 0, 0), marker='s', s=30, facecolors='none', edgecolors='k') axin.set_xlim(0.5, 4.5) axin.set_ylim(-0.4, 0.1) axin.yaxis.set_ticks_position('right') axin.xaxis.set_ticks_position('top') axin.set_xticks((1, 2, 3, 4)) # axin.set_yticks((-0.3,-0.2,-0.1,0,0.1)) axin.grid('on') mark_inset(ax, axin, loc1=1, loc2=2, fc="none") ax.legend() fig.tight_layout(pad=0) plt.show() <file_sep>from py_CQCGL1d import * from personalFunctions import * case = 10 if case == 10: """ use L = 50 to view the rpo, its FV and the explosion """ N, d = 1024, 50 Bi, Gi = 2.0, -5.6 cgl = pyCQCGL1d(N, d, -0.1, 0.125, 0.5, 1, Bi, -0.1, Gi, -1) rpo = CQCGLrpo(cgl) cp = CQCGLplot(cgl) x, T, nstp, th, phi, err, e, v = rpo.readRpoBiGi('../../data/cgl/rpoBiGiEV.h5', Bi, Gi, 1, flag=2) a0 = x[:cgl.Ndim] print e[:10] # plot the leading Fv isvReal = True cp.oneConfig(v[0], d=50, labs=[r'$x$', r'$|\mathbf{e}_0|$' if isvReal else r'$|Re(\mathbf{e}_0)|$']) # plot 4 period of the orbit aa = cgl.intg(a0, T/nstp, 4*nstp, 10) cp.config(aa, [0, d, 0, 4*T], axisLabelSize=25, tickSize=15, barTicks=[0.5, 1, 1.5]) # plot the explosion a0 += 0.1*norm(a0)*v[0] skipRate = 50 aa = cgl.intg(a0, T/nstp, 20*nstp, skipRate) cellSize = nstp/skipRate cp.config(aa[12*cellSize:19*cellSize], [0, d, T*12, T*19]) if case == 20: """ plot a long integration to see whether there are only symmetric/asymmetric explosions or both of them """ N, d = 1024, 50 Bi, Gi = 4.6, -5.0 cgl = pyCQCGL1d(N, d, -0.1, 0.125, 0.5, 1, Bi, -0.1, Gi, -1) rpo = CQCGLrpo(cgl) cp = CQCGLplot(cgl) x, T, nstp, th, phi, err, e, v = rpo.readRpoBiGi('../../data/cgl/rpoBiGiEV.h5', Bi, Gi, 1, flag=2) a0 = x[:cgl.Ndim] a0 += 0.1 * norm(a0) * v[0] for i in range(10): aa = cgl.intg(a0, T/nstp, 10*nstp, 50) a0 = aa[-1] cp.config(aa, [0, d, 0, 10*T]) <file_sep>#include "denseRoutines.hpp" #include <vector> #include <algorithm> #include <time.h> /* time */ using namespace std; using namespace Eigen; /* ----------- functions -------------- */ ////////////////////////////////////////////////////////////////////// // subspace angle // ////////////////////////////////////////////////////////////////////// /** @brief calculate the cos() of the largest angle * between the two subspaces spanned by the * columns of matrices A and B. */ double denseRoutines::angleSubspace(const Ref<const MatrixXd> &A, const Ref<const MatrixXd> &B){ assert(A.rows() == B.rows()); const int N = A.rows(); const int M1 = A.cols(); const int M2 = B.cols(); MatrixXd thinQa(MatrixXd::Identity(N,M1)); MatrixXd thinQb(MatrixXd::Identity(N,M2)); ColPivHouseholderQR<MatrixXd> qra(A); thinQa = qra.householderQ() * thinQa; ColPivHouseholderQR<MatrixXd> qrb(B); thinQb = qrb.householderQ() * thinQb; JacobiSVD<MatrixXd> svd(thinQa.transpose() * thinQb); VectorXd sv = svd.singularValues(); return sv.maxCoeff(); } double denseRoutines::angleSpaceVector(const Ref<const MatrixXd> &Q, const Ref<const VectorXd> &V){ assert( Q.rows() == V.rows()); VectorXd P = Q.transpose() * V; double cos2 = P.squaredNorm() / V.squaredNorm(); return sqrt(1-cos2); } ////////////////////////////////////////////////////////////////////// // eigenspace related // ////////////////////////////////////////////////////////////////////// /** @brief find the marginal exponents and their position. * * This function tries to find the n (default 2) * smallest absolute * value of the exponents, and assume they are marginal. * * @input Exponent Floquet exponent (the frist column of e) * @return a n-element vector. Each element is a pair of * the marginal exponent and its corresponding postion */ std::vector< std::pair<double, int> > denseRoutines::findMarginal(const Ref<const VectorXd> &Exponent, const int k /* = 2 */){ const int N = Exponent.size(); std::vector<std::pair<double, int> > var; for (size_t i = 0; i < N; i++) { var.push_back( std::make_pair(Exponent(i), i) ); } // sort the exponent from large to small by absolute value std::sort(var.begin(), var.end(), [](std::pair<double, int> i , std::pair<double, int> j) {return fabs(i.first) < fabs(j.first);} ); return std::vector<std::pair<double, int> >(var.begin(), var.begin() + k); } /** @brief Get the supspace index. * * For each index, it has a Left value (L) and a Right value (R), which * denote when this index is used as the left bound or right bound * for a subspace. For real eigenvalues, L = index = R. For complex * eigenvalues, L1, L2 = index1, R1, R2 = index1+1; * * @param[in] RCP real/complex position, usually it is the third * column of the Floquet exponents matrix. * @param[in] Exponent Floquet exponents used to get the marginal position * @return N x 2 matrix */ MatrixXi denseRoutines::indexSubspace(const Ref<const VectorXd> &RCP, const Ref<const VectorXd> &Exponent){ assert(RCP.size() == Exponent.size()); const int N = RCP.size(); std::vector< std::pair<double, int> > marginal = findMarginal(Exponent); // create a new real/complex position vector whose marginal // will be considered to complex. VectorXd RCP2(RCP); RCP2(marginal[0].second) = 1.0; RCP2(marginal[1].second) = 1.0; MatrixXi index_sub(N, 2); for(size_t i = 0; i < N; i++){ if(RCP2(i) == 0){ // real case index_sub(i, 0) = i; index_sub(i, 1) = i; } else{ // complex case index_sub(i, 0) = i; index_sub(i, 1) = i+1; index_sub(i+1, 0) = i; index_sub(i+1,1) = i+1; i++; } } return index_sub; } /** @brief calculate the actual subspace bound and the indicator whether the actual * bound is the same as specified. * * @param[in] subspDim subspace bounds. Each column is a 4-vector storing dimension of * two subspaces. * @param[in] ixSp subspace index, i.e the left and right bounds * @see indexSubspace * @return a pair of integer matrix. The first one is actual subspace bound. * The second one indicate whether the bounds are the same as specified. */ std::pair<MatrixXi, MatrixXi> denseRoutines::subspBound(const MatrixXi subspDim, const MatrixXi ixSp){ assert(subspDim.rows() == 4); // two subspaces have 4 indices. const int M = subspDim.cols(); MatrixXi boundStrict(MatrixXi::Zero(4,M)); MatrixXi bound(4, M); for(size_t i = 0; i < M; i++){ int L1 = ixSp(subspDim(0,i), 0); bound(0,i) = L1; int R1 = ixSp(subspDim(1,i), 1); bound(1,i) = R1; int L2 = ixSp(subspDim(2,i), 0); bound(2,i) = L2; int R2 = ixSp(subspDim(3,i), 1); bound(3,i) = R2; if(L1 == subspDim(0,i)) boundStrict(0,i) = 1; if(R1 == subspDim(1,i)) boundStrict(1,i) = 1; if(L2 == subspDim(2,i)) boundStrict(2,i) = 1; if(R2 == subspDim(3,i)) boundStrict(3,i) = 1; } return std::make_pair(bound, boundStrict); } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// /** @brief normalize each column of a matrix */ void denseRoutines::normc(MatrixXd &A){ int m = A.cols(); for(size_t i = 0; i < m; i++) A.col(i).array() = A.col(i).array() / A.col(i).norm(); } /** * @brief get the sorted indices of a complex vector in descending order * by their real part */ std::vector<int> denseRoutines::csort(const VectorXcd &e, int flag){ int n = e.size(); std::vector<int> id(n); for(int i = 0; i < n; i++) id[i] = i; switch (flag){ case 1 : // real part std::sort(id.begin(), id.end(), [&e](int i, int j){return e(i).real() > e(j).real();} ); break; case 2 : // magnitude std::sort(id.begin(), id.end(), [&e](int i, int j){return std::abs(e(i)) > std::abs(e(j)); } ); break; default: fprintf(stderr, "errer of csort in denseRoutines\n"); } return id; } /// @brief transform real-format eigenvector matrix to complex format /// @note assume complex paris are complete MatrixXcd denseRoutines::vr2vc(const VectorXcd &e, const Ref<const MatrixXd> &v){ assert(e.size() == v.cols()); int m = v.rows(); int n = v.cols(); MatrixXcd vc(m, n); int i = 0; while(i < n-1){ double r1 = fabs( e(i).imag() ); double r2 = fabs( e(i).imag() + e(i+1).imag() ); if(r1 > 1e-6 && r2 < 1e-10){ vc.col(i).real() = v.col(i); vc.col(i).imag() = v.col(i+1); vc.col(i+1).real() = v.col(i); vc.col(i+1).imag() = -v.col(i+1); i += 2; } else { vc.col(i).real() = v.col(i); vc.col(i).imag().setZero(); i++; } } if (i == n-1) { vc.col(i).real() = v.col(i); vc.col(i).imag().setZero(); } return vc; } MatrixXd denseRoutines::vc2vr(const Ref<const MatrixXcd> &v){ int m = v.rows(); int n = v.cols(); MatrixXd vr(m, n); int i = 0; while (i < n-1) { double r1 = v.col(i).imag().array().abs().maxCoeff(); double r2 = (v.col(i) + v.col(i+1)).imag().array().abs().maxCoeff(); if (r1 > 1e-6 && r2 < 1e-10){ vr.col(i) = v.col(i).real(); vr.col(i+1) = v.col(i).imag(); i += 2; } else { vr.col(i) = v.col(i).real(); i++; } } if (i == n-1) vr.col(i) = v.col(i).real(); return vr; } /** * @brief calculate the eigenvalues of a real matrix. * * The eigenvalues are sorted by their real part. It returns a complex vector. */ VectorXcd denseRoutines::eEig(const MatrixXd &A, int flag){ EigenSolver<MatrixXd> es(A); std::vector<int> id = csort(es.eigenvalues(), flag); int n = id.size(); VectorXcd re(n); for(size_t i = 0; i < n; i++) re(i) = es.eigenvalues()(id[i]); return re; } /** * @brief calculate the eigenvectors of a real matrix. It returns a complex matrix. * * The eigenvalues are sorted by their real part. It returns a complex matrix. */ MatrixXcd denseRoutines::vEig(const MatrixXd &A, int flag){ EigenSolver<MatrixXd> es(A); std::vector<int> id = csort(es.eigenvalues(), flag); int n = id.size(); MatrixXcd rv(n, n); for(size_t i = 0; i < n; i++) rv.col(i) = es.eigenvectors().col(id[i]); return rv; } /** * @brief calculate the eigenvalues and eigenvectors of a real matrix. * * The eigenvalues are sorted by their real part. */ std::pair<VectorXcd, MatrixXcd> denseRoutines::evEig(const MatrixXd &A, int flag){ EigenSolver<MatrixXd> es(A); std::vector<int> id = csort(es.eigenvalues(), flag); int n = id.size(); VectorXcd re(n); MatrixXcd rv(n, n); for(size_t i = 0; i < n; i++){ re(i) = es.eigenvalues()(id[i]); rv.col(i) = es.eigenvectors().col(id[i]); } return make_pair(re, rv); } /** * @brief Reform complex eigenvector matrix to real format */ MatrixXd denseRoutines::realv(const MatrixXcd &v){ int n = v.rows(); int m = v.cols(); MatrixXd vp(n, m); VectorXd tmp = v.imag().array().abs().colwise().sum(); for(size_t i = 0; i < m; i++){ if(tmp(i) < 1e-6) vp.col(i) = v.col(i).real(); else { vp.col(i) = v.col(i).real(); vp.col(i+1) = v.col(i).imag(); i++; } } return vp; } /** * @brief construct orthonormal bases from the coloumn vectors of a matrix * * Note: we do not use ColPivHouseHolderQR because we want to preserve the order. */ MatrixXd denseRoutines::orthAxes(const Ref<const MatrixXd> &v){ int n = v.rows(); int m = v.cols(); HouseholderQR<MatrixXd> qr(v); return qr.householderQ() * MatrixXd::Identity(n, m); } /** * @brief construct orthonormal vectors from a 2 vectors */ MatrixXd denseRoutines::orthAxes(const Ref<const VectorXd> &e1, const Ref<const VectorXd> &e2){ int n = e1.size(); MatrixXd tmp(n, 2); tmp << e1, e2; return orthAxes(tmp); } /** * @brief construct orthonormal vectors from a 3 vectors */ MatrixXd denseRoutines::orthAxes(const Ref<const VectorXd> &e1, const Ref<const VectorXd> &e2, const Ref<const VectorXd> &e3){ int n = e1.size(); MatrixXd tmp(n, 3); tmp << e1, e2, e3; return orthAxes(tmp); } /** * @brief my wrapper to HouseHolderQR */ std::pair<MatrixXd, MatrixXd> denseRoutines::QR(const Ref<const MatrixXd> &A){ int n = A.rows(); int m = A.cols(); assert(n >= m); // this is the only correct way to extract Q and R // which makes sure the returned matrices have continous memory layout HouseholderQR<MatrixXd> qr(A); MatrixXd Q = qr.householderQ() * MatrixXd::Identity(n, m); MatrixXd R = MatrixXd::Identity(m, n) * qr.matrixQR().triangularView<Upper>(); return std::make_pair(Q, R); } /** * @brief My personal implimentation of Gram-Schmidt orthonormalization method * * We suggest using HouseholderQR instead of our method. */ std::pair<MatrixXd, MatrixXd> denseRoutines::GS(const Ref<const MatrixXd> &A){ const int N = A.rows(); const int M = A.cols(); MatrixXd Q(N, M); MatrixXd R(MatrixXd::Zero(N, M)); // make sure the lower part is zero R(0, 0) = A.col(0).norm(); Q.col(0) = A.col(0) / R(0, 0); for(int j = 1; j < M; j++){ VectorXd v = A.col(j); VectorXd coe = Q.leftCols(j-1).transpose() * v; R.col(j).head(j-1) = coe; v -= Q.leftCols(j-1) * coe; R(j, j) = v.norm(); Q.col(j) = v / R(j, j); } return std::make_pair(Q, R); } /** * @see GS() */ MatrixXd denseRoutines::GSsimple(const Ref<const MatrixXd> &A){ return GS(A).first; } /** * @brief return the spacing between adjacent vectors * * @param[in] v mxn matrix * @return n-1 vector */ VectorXd denseRoutines::spacing(const Ref<const MatrixXd> &v){ int m = v.rows(); int n = v.cols(); VectorXd sp(n-1); for(size_t i = 0; i < n-1; i++) sp(i) = (v.col(i) - v.col(i+1)).norm(); return sp; } /** * @brief return the index of vector which is closest to the sample point * * @param[in] a sample pointx * @param[in] v a trajectory * @param[out] minD minimal distance * @return index of v closest to a */ int denseRoutines::minDisIndex(const Ref<const VectorXd> &a, const Ref<const MatrixXd> &v, double &minD){ int m = v.rows(); int n = v.cols(); int id = 0; minD = (a - v.col(0)).norm(); for(size_t i = 0; i < n; i++){ double d = (a - v.col(i)).norm(); if(d < minD) { id = i; minD = d; } } return id; } int denseRoutines::minDisIndex(const Ref<const VectorXd> &a, const Ref<const MatrixXd> &v){ double minD; return minDisIndex(a, v, minD); } MatrixXcd denseRoutines::loadComplex(const std::string f1, const std::string f2){ MatrixXd re = loadtxt<double>(f1); MatrixXd im = loadtxt<double>(f2); int n1 = re.rows(); int m1 = re.cols(); int n2 = im.rows(); int m2 = im.cols(); assert(n1 == n2 && m1 == m2); MatrixXcd A(n1, m1); A.real() = re; A.imag() = im; return A; } ArrayXXd denseRoutines::calPhase(const Ref<const ArrayXXcd> &AA){ int m = AA.cols(); int n = AA.rows(); ArrayXXd phase(n, m); for(size_t i = 0; i < m; i++) for(size_t j =0; j < n; j++) phase(j, i) = atan2(AA(j, i).imag(), AA(j, i).real()); return phase; } //////////////////////////////////////////////////////////////////////////////////////////////////// // special matrix generator /** * Generate center localized random initial condition */ VectorXd denseRoutines::centerRand(const int N, const double frac){ VectorXd a(VectorXd::Random(N)); /* -1 to 1 */ int N2 = (int) (0.5 * N * (1-frac)); a.head(N2) = VectorXd::Zero(N2); a.tail(N2) = VectorXd::Zero(N2); return a; } MatrixXd denseRoutines::randM(int M, int N){ srand(time(NULL)); MatrixXd A(M, N); for (int i = 0; i < M; i++) for (int j = 0; j < N; j++) A(i,j) = (double)rand() / RAND_MAX - 0.5; return A; } <file_sep>#include "ksint.hpp" #include "denseRoutines.hpp" #include <cmath> #include <iostream> using namespace denseRoutines; ////////////////////////////////////////////////////////////////////// KS::NL::NL(){} KS::NL::NL(KS *ks, int cols) : ks(ks), N(ks->N) { u.resize(ks->N, cols); } KS::NL::~NL(){} void KS::NL::operator()(ArrayXXcd &x, ArrayXXcd &dxdt, double t){ int cs = x.cols(); assert(cs == dxdt.cols() && N/2+1 == x.rows() && N/2+1 == dxdt.rows()); for(int i = 0; i < cs; i++) ks->fft.inv(u.data() + i*N, x.data() + i*(N/2+1), N); ArrayXd orbit = u.col(0); u = u.colwise() * orbit; for(int i = 0; i < cs; i++) ks->fft.fwd(dxdt.data() + i*(N/2+1), u.data() + i*N, N); dxdt.col(0) *= ks->G; if(cs > 1) dxdt.rightCols(cs-1).colwise() *= 2.0 * ks->G; } ////////////////////////////////////////////////////////////////////// /*-------------------- constructor, destructor -------------------- */ // dimension of physical state : N // dimension of state space : N - 2 (zeroth and highest mode are excluded) // dimension of Fourier space : N/2 + 1 KS::KS(int N, double d) : N(N), d(d), nl(this, 1), nl2(this, N-1) { K = ArrayXd::LinSpaced(N/2+1, 0, N/2) * 2 * M_PI / d; //2*PI/d*[0, 1, 2,...,N/2] K(N/2) = 0; L = K*K - K*K*K*K; G = 0.5 * dcp(0,1) * K * N; fft.SetFlag(fft.HalfSpectrum); // very important int nYN0 = eidr.names.at(eidr.scheme).nYN; // do not call setScheme here. Different. for(int i = 0; i < nYN0; i++){ Yv[i].resize(N/2+1, 1); Nv[i].resize(N/2+1, 1); Yv2[i].resize(N/2+1, N-1); Nv2[i].resize(N/2+1, N-1); } eidr.init(&L, Yv, Nv); eidr2.init(&L, Yv2, Nv2); } KS & KS::operator=(const KS &x){ return *this; } KS::~KS(){} /*------------------- member methods ------------------ */ void KS::setScheme(std::string x){ int nYN0 = eidr.names.at(eidr.scheme).nYN; eidr.scheme = x; int nYN1 = eidr.names.at(eidr.scheme).nYN; for (int i = nYN0; i < nYN1; i++) { Yv[i].resize(N/2+1, 1); Nv[i].resize(N/2+1, 1); Yv2[i].resize(N/2+1, N-1); Nv2[i].resize(N/2+1, N-1); } } ArrayXXd KS::intgC(const ArrayXd &a0, const double h, const double tend, const int skip_rate){ assert(a0.size() == N-2); ArrayXXcd u0 = R2C(a0); const int Nt = (int)round(tend/h); const int M = (Nt + skip_rate - 1) / skip_rate; ArrayXXcd aa(N/2+1, M); lte.resize(M); int count = 0; auto ss = [this, &count, &aa](ArrayXXcd &x, double t, double h, double err){ aa.col(count) = x; lte(count++) = err; }; eidr.intgC(nl, ss, 0, u0, tend, h, skip_rate); return C2R(aa); } std::pair<ArrayXXd, ArrayXXd> KS::intgjC(const ArrayXd &a0, const double h, const double tend, const int skip_rate){ assert(a0.size() == N-2); ArrayXXd v0(N-2, N-1); v0 << a0, MatrixXd::Identity(N-2, N-2); ArrayXXcd u0 = R2C(v0); const int Nt = (int)round(tend/h); const int M = (Nt + skip_rate - 1) / skip_rate; ArrayXXcd aa(N/2+1, M), daa(N/2+1, (N-2)*M); lte.resize(M); int count = 0; auto ss = [this, &count, &aa, &daa](ArrayXXcd &x, double t, double h, double err){ aa.col(count) = x.col(0); daa.middleCols(count*(N-2), N-2) = x.rightCols(N-2); lte(count++) = err; x.rightCols(N-2) = R2C(MatrixXd::Identity(N-2, N-2)); }; eidr2.intgC(nl2, ss, 0, u0, tend, h, skip_rate); return std::make_pair(C2R(aa), C2R(daa)); } ArrayXXd KS::intg(const ArrayXd &a0, const double h, const double tend, const int skip_rate){ assert(a0.size() == N-2); ArrayXXcd u0 = R2C(a0); const int Nt = (int)round(tend/h); const int M = (Nt+skip_rate-1)/skip_rate; ArrayXXcd aa(N/2+1, M); Ts.resize(M); hs.resize(M); lte.resize(M); int count = 0; auto ss = [this, &count, &aa](ArrayXXcd &x, double t, double h, double err){ int m = Ts.size(); if (count >= m ) { Ts.conservativeResize(m+cellSize); aa.conservativeResize(Eigen::NoChange, m+cellSize); hs.conservativeResize(m+cellSize); lte.conservativeResize(m+cellSize); } hs(count) = h; lte(count) = err; aa.col(count) = x; Ts(count++) = t; }; eidr.intg(nl, ss, 0, u0, tend, h, skip_rate); hs.conservativeResize(count); lte.conservativeResize(count); Ts.conservativeResize(count); aa.conservativeResize(Eigen::NoChange, count); return C2R(aa); } std::pair<ArrayXXd, ArrayXXd> KS::intgj(const ArrayXd &a0, const double h, const double tend, const int skip_rate){ assert(a0.size() == N-2); ArrayXXd v0(N-2, N-1); v0 << a0, MatrixXd::Identity(N-2, N-2); ArrayXXcd u0 = R2C(v0); const int Nt = (int)round(tend/h); const int M = (Nt + skip_rate - 1) / skip_rate; ArrayXXcd aa(N/2+1, M), daa(N/2+1, (N-2)*M); Ts.resize(M); hs.resize(M); lte.resize(M); int count = 0; auto ss = [this, &count, &aa, &daa](ArrayXXcd &x, double t, double h, double err){ int m = Ts.size(); if (count >= m ) { Ts.conservativeResize(m+cellSize); hs.conservativeResize(m+cellSize); lte.conservativeResize(m+cellSize); aa.conservativeResize(Eigen::NoChange, m+cellSize); // rows not change, just extend cols daa.conservativeResize(Eigen::NoChange, (m+cellSize)*(N-2)); } hs(count) = h; lte(count) = err; Ts(count) = t; aa.col(count) = x.col(0); daa.middleCols(count*(N-2), N-2) = x.rightCols(N-2); x.rightCols(N-2) = R2C(MatrixXd::Identity(N-2, N-2)); count++; }; eidr2.intg(nl2, ss, 0, u0, tend, h, skip_rate); return std::make_pair(C2R(aa), C2R(daa)); } /* @brief complex matrix to the corresponding real matrix. * [N/2+1, M] --> [N-2, M] * Since the Map is not address continous, the performance is * not good enough. */ ArrayXXd KS::C2R(const ArrayXXcd &v){ int rs = v.rows(), cs = v.cols(); assert(N/2+1 == rs); ArrayXXcd vt = v.middleRows(1, rs-2); ArrayXXd vp = Map<ArrayXXd>((double*)(vt.data()), N-2, cs); return vp; } ArrayXXcd KS::R2C(const ArrayXXd &v){ int rs = v.rows(), cs = v.cols(); assert( N - 2 == rs); ArrayXXcd vp(N/2+1, cs); vp << ArrayXXcd::Zero(1, cs), Map<ArrayXXcd>((dcp*)(v.data()), N/2-1, cs), ArrayXXcd::Zero(1, cs); return vp; } /*************************************************** * stability ralated * ***************************************************/ /** @brief calculate the velocity * * @param[in] a0 state vector * @return velocity field at a0 */ ArrayXd KS::velocity(const Ref<const ArrayXd> &a0){ assert( N - 2 == a0.rows() ); ArrayXXcd u = R2C(a0); ArrayXXcd v(N/2+1, 1); nl(u, v, 0); return C2R(L*u + v); } /* return v(x) + theta *t(x) */ ArrayXd KS::velReq(const Ref<const VectorXd> &a0, const double theta){ return velocity(a0) + theta * gTangent(a0); } /** @brief calculate the stability matrix * A = (qk^2 - qk^4) * v - i*qk* F( F^{-1}(a0) * F^{-1}(v)) */ MatrixXd KS::stab(const Ref<const ArrayXd> &a0){ assert(a0.size() == N-2); ArrayXXd v0(N-2, N-1); v0 << a0, MatrixXd::Identity(N-2, N-2); ArrayXXcd u0 = R2C(v0); ArrayXXcd v(N/2+1, N-1); nl2(u0, v, 0); ArrayXXcd j0 = R2C(MatrixXd::Identity(N-2, N-2)); MatrixXcd Z = L.matrix().asDiagonal() * j0.matrix() + v.rightCols(N-2).matrix(); return C2R(Z); } /* the stability matrix of a relative equilibrium */ MatrixXd KS::stabReq(const Ref<const VectorXd> &a0, const double theta){ return stab(a0) + theta * gGenerator(); } /* Eigenvalues/Eigenvectors of equilibrium */ std::pair<VectorXcd, MatrixXcd> KS::evEq(const Ref<const VectorXd> &a0){ return evEig(stab(a0), 1); } /* Eigenvalues/Eigenvectors of equilibrium */ std::pair<VectorXcd, MatrixXcd> KS::evReq(const Ref<const VectorXd> &a0, const double theta){ return evEig(stabReq(a0, theta), 1); } /*************************************************** * energe ralated * ***************************************************/ double KS::pump(const ArrayXcd &vc){ VectorXcd tmp = vc * K; return tmp.squaredNorm(); } double KS::disspation(const ArrayXcd &vc){ VectorXcd tmp = vc * K * K; return tmp.squaredNorm(); } /*************************************************** * Symmetry related * ***************************************************/ /** @brief apply reflection on each column of input */ ArrayXXd KS::reflect(const Ref<const ArrayXXd> &aa){ int n = aa.rows(); int m = aa.cols(); assert( 0 == n%2 ); ArrayXd R(n); for(size_t i = 0; i < n/2; i++) { R(2*i) = -1; R(2*i+1) = 1; } ArrayXXd Raa = aa.colwise() * R; return Raa; } ArrayXXd KS::half2whole(const Ref<const ArrayXXd> &aa){ int n = aa.rows(); int m = aa.cols(); ArrayXXd raa = reflect(aa); ArrayXXd aaWhole(n, 2*m); aaWhole << aa, raa; return aaWhole; } /** @brief apply rotation to each column of input with the * same angle specified * a_k => a_k * e^{ik*th} */ ArrayXXd KS::rotate(const Ref<const ArrayXXd> &aa, const double th){ assert(aa.rows() == N - 2); ArrayXd indices = ArrayXd::LinSpaced(N/2+1, 0, N/2); // different from K return C2R( R2C(aa).colwise() * (dcp(0, th) * indices).exp() ); } /** @brief group tangent of SO(2) * * x=(b1, c1, b2, c2, ...) ==> tx=(-c1, b1, -2c2, 2b2, ...) * That is a_k => a_k * {ik} */ ArrayXXd KS::gTangent(const Ref<const ArrayXXd> &x){ assert(x.rows() == N - 2); ArrayXd indices = ArrayXd::LinSpaced(N/2+1, 0, N/2); // different from K return C2R(R2C(x).colwise() * (dcp(0, 1) * indices) ); } /* group generator matrix T */ MatrixXd KS::gGenerator(){ MatrixXd T(MatrixXd::Zero(N-2, N-2)); for (int i = 0; i < N/2-1; i++ ){ T(2*i, 2*i+1) = -(i+1); T(2*i+1, 2*i) = i+1; } return T; } /** * @brief transform the SO2 symmetry to C_p. * * Use p-th mode to reduce SO2 symmetry. If p > 1, then the symmetry is not reduced * but tranformed to cyclic symmetry. * * For example, if p = 2, then SO2 is reduced to C2, so together with reflection, * we have D2 symmetry. If we rotate to the imaginary axis, then we have rules * R : ( - + - + - + ...) * C2: ( - - + + - - ...) * * * @param[in] p index of Fourier mode * @param[in] toY True => tranform to positive imaginary axis. */ std::pair<MatrixXd, VectorXd> KS::redSO2(const Ref<const MatrixXd> &aa, const int p, const bool toY){ int n = aa.rows(); int m = aa.cols(); assert( 0 == n%2 && p > 0); MatrixXd raa(n, m); VectorXd ang(m); double s = toY ? M_PI/2 : 0; /* pi/2 or 0 */ for(int i = 0; i < m; i++){ double th = (atan2(aa(2*p-1, i), aa(2*p-2, i)) - s )/ p; ang(i) = th; raa.col(i) = rotate(aa.col(i), -th); } return std::make_pair(raa, ang); } /** * If we use the 2nd mode to reduce SO2, then we use 1st mode or 3rd mode * to define fundamental domain. b_1 > 0 && c_1 > 0 * * If we use the 1st mode to reduce SO2, then we use 2nd mode * to define fundamental domain. b_2 > 0 * * In all these cases, we assume SO2 is reduced to positive y-axis. * * @param[in] pSlice index of Fourier mode used to define slice * @param[in] pFund index of Fourier mode used to define fundamental domain * */ std::pair<MatrixXd, VectorXi> KS::fundDomain(const Ref<const MatrixXd> &aa, const int pSlice, const int pFund){ int n = aa.rows(); int m = aa.cols(); assert( 0 == n%2 && pSlice > 0 && pFund > 0 && pSlice != pFund); MatrixXd faa(n, m); VectorXi DomainIds(m); ArrayXd R(n); // reflection matrix for(int i = 0; i < n/2; i++){ R(2*i) = -1; R(2*i+1) = 1; } if (pSlice == 1){ // 1st mode slice int id = 2 * (pFund - 1); for (int i = 0; i < m; i++) { if(aa(id, i) > 0 ) { faa.col(i) = aa.col(i); DomainIds(i) = 1; } else { faa.col(i) = aa.col(i).array() * R; DomainIds(i) = 2; } } } else if (pSlice == 2){ // 2nd mode slice ArrayXd C(n); // rotation by pi int s = -1; for(int i = 0; i < n/2; i++){ C(2*i) = s; C(2*i+1) = s; s *= -1; } ArrayXd RC = R * C; int id = 2 * (pFund - 1); for(int i = 0; i < m; i++){ bool x = aa(id, i) > 0; bool y = aa(id+1, i) > 0; if(x && y) { faa.col(i) = aa.col(i); DomainIds(i) = 1; } else if (!x && y) { faa.col(i) = aa.col(i).array() * R; DomainIds(i) = 2; } else if (!x && !y) { faa.col(i) = aa.col(i).array() * C; DomainIds(i) = 3; } else { // if (x && !y) { faa.col(i) = aa.col(i).array() * RC; DomainIds(i) = 4; } } } else if (pSlice == 3){ ArrayXcd C1(n/2+2), C2(n/2+2); for (int i = 0; i < n/2; i++){ double th = (i+1) * 2 * M_PI / 3; C1[i+1] = dcp(cos(th), sin(th)); C2[i+1] = dcp(cos(2*th), sin(2*th)); } int id = 2 * (pFund - 1); for(int i = 0; i < m; i++){ int x = aa(id, i), y = aa(id+1, i); if ( y <= x/2 && y >= -x/2){ // domain 1 faa.col(i) = aa.col(i); DomainIds(i) = 1; } else if (y >= x/2 && y <= -x/2){ // domain 4 faa.col(i) = aa.col(i).array() * R; DomainIds(i) = 4; } else if (y >= x/2 && x >= 0) { // domain 2 faa.col(i) = C2R(C1 * R2C(aa.col(i)).array()) * R; DomainIds(i) = 2; } else if(y <= x/2 && x <= 0) { // domain 5 faa.col(i) = C2R(C1 * R2C(aa.col(i)).array()); DomainIds(i) = 5; } else if (y >= -x/2 && x <= 0){ // domain 3 faa.col(i) = C2R(C2 * R2C(aa.col(i)).array()); DomainIds(i) = 3; } else { // domain 6 faa.col(i) = C2R(C2 * R2C(aa.col(i)).array()) * R; DomainIds(i) = 6; } } } else { fprintf(stderr, "wrong index of Fourier mode !\n"); } return std::make_pair(faa, DomainIds); } /** @brief reduce O2 symmetry to fundamental domain * * * @param[in] aa states in the full state space * @param[in] pSlice index of Fourier mode used to define slice * @param[in] pFund index of Fourier mode used to define fundamental domain * @return state in fundamental domain, domain indices, angles **/ std::tuple<MatrixXd, VectorXi, VectorXd> KS::redO2f(const Ref<const MatrixXd> &aa, const int pSlice, const int pFund){ auto tmp = redSO2(aa, pSlice, true); auto tmp2 = fundDomain(tmp.first, pSlice, pFund); return std::make_tuple(tmp2.first, tmp2.second, tmp.second); } // projection matrix is h= (I - |tx><tp|/<tx|tp>) * g(-th) MatrixXd KS::redV(const Ref<const MatrixXd> &v, const Ref<const VectorXd> &a, const int p, const bool toY){ auto tmp = redSO2(a, p, toY); MatrixXd &aH = tmp.first; double th = tmp.second(0); VectorXd tx = gTangent(aH); VectorXd x0(VectorXd::Zero(N-2)); if (toY) x0(2*p-1) = 1; else x0(2*p-2) = 1; VectorXd t0 = gTangent(x0); MatrixXd vep = rotate(v, -th); MatrixXd dot = (t0.transpose() * vep) / (t0.transpose() * tx); vep = vep - tx * dot; return vep; } #if 0 /** @beief project the sequence of Floquet vectors to 1st mode slice * * Usaully, aa has one more column the the Floquet vectors, so you can * call this function like: * \code * veToSliceAll(eigVecs, aa.leftCols(aa.cols()-1)) * \endcode * * @param[in] eigVecs Floquet vectors along the orbit. Dimension: [N*Trunc, M] * @param[in] aa the orbit * @return projected vectors on the slice with dimension [N, M*Trunc] * * @note vectors are not normalized */ MatrixXd KS::veToSliceAll(const MatrixXd &eigVecs, const MatrixXd &aa, const int trunc /* = 0*/){ int Trunc = trunc; if(trunc == 0) Trunc = sqrt(eigVecs.rows()); assert(eigVecs.rows() % Trunc == 0); const int n = eigVecs.rows() / Trunc ; const int m = eigVecs.cols(); const int n2 = aa.rows(); const int m2 = aa.cols(); assert(m == m2 && n == n2); MatrixXd newVe(n, Trunc*m); for(size_t i = 0; i < m; i++){ MatrixXd ve = eigVecs.col(i); ve.resize(n, Trunc); newVe.middleCols(i*Trunc, Trunc) = veToSlice(ve, aa.col(i)); } return newVe; } /** * @brief get the full orbit and full set of Fvs * * Given the inital point and the set of Fvs, the whole set is * twice bigger for ppo, but for rpo, it is the single piece. * * @param[in] a0 the inital condition of the ppo/rpo * @param[in] ve the set of Fvs. Dimension [(N-2)*NFV, M] * @param[in] nstp number of integration steps * @param[in] ppTpe ppo/rpo * @return the full orbit and full set of Fvs. */ std::pair<ArrayXXd, ArrayXXd> KS::orbitAndFvWhole(const ArrayXd &a0, const ArrayXXd &ve, const double h, const size_t nstp, const std::string ppType ){ assert(N-2 == a0.rows()); const int M = ve.cols(); assert(nstp % M == 0); const int space = nstp / M; ArrayXXd aa = intg(a0, h, nstp, space); if(ppType.compare("ppo") == 0) return std::make_pair( half2whole(aa.leftCols(aa.cols()-1)), half2whole(ve) // this is correct. Think carefully. ); else return std::make_pair( aa.leftCols(aa.cols()-1), // one less ve ); } /** * @brief get rid of the marginal direction of the Fvs * * @param[in] ve dimension [N, M*trunc] * @param[in] pos the location of the group tangent margianl Floquet vector. * pos starts from 0. * @param[in] return the clean set of Fvs */ MatrixXd KS::veTrunc(const MatrixXd ve, const int pos, const int trunc /* = 0 */){ int Trunc = trunc; if(trunc == 0) Trunc = ve.rows(); const int N = ve.rows(); const int M = ve.cols() / Trunc; assert(ve.cols()%M == 0); MatrixXd newVe(N, (Trunc-1)*M); for(size_t i = 0; i < M; i++){ newVe.middleCols(i*(Trunc-1), pos) = ve.middleCols(i*Trunc, pos); newVe.middleCols(i*(Trunc-1)+pos, Trunc-1-pos) = ve.middleCols(i*Trunc+pos+1, Trunc-1-pos); } return newVe; } /** * @brief get the full orbit and full set of Fvs on the slice * * @return the full orbit and full set of Fvs on slice * @see orbitAndFvWhole(), veTrunc() */ std::pair<ArrayXXd, ArrayXXd> KS::orbitAndFvWholeSlice(const ArrayXd &a0, const ArrayXXd &ve, const double h, const size_t nstp, const std::string ppType, const int pos ){ assert(ve.rows() % (N-2) == 0); const int NFV = ve.rows() / (N-2); auto tmp = orbitAndFvWhole(a0, ve, h, nstp, ppType); auto tmp2 = orbitToSlice(tmp.first); MatrixXd veSlice = veToSliceAll(tmp.second, tmp.first, NFV); MatrixXd ve_trunc = veTrunc(veSlice, pos, NFV); return std::make_pair(tmp2.first, ve_trunc); } #endif /*************************************************** * Others * ***************************************************/ /* calculate mode modulus */ MatrixXd KS::calMag(const Ref<const MatrixXd> &aa){ assert(aa.rows() == N - 2); ArrayXXcd u = R2C(aa).middleRows(1, N/2-1); return (u * u.conjugate()).real(); } std::pair<MatrixXd, MatrixXd> KS::toPole(const Ref<const MatrixXd> &aa){ assert(aa.rows() == N - 2); ArrayXXcd u = R2C(aa).middleRows(1, N/2-1); MatrixXd mag = (u * u.conjugate()).real(); MatrixXd th(u.rows(), u.cols()); for(int i = 0; i < u.rows(); i++){ for(int j = 0; j < u.cols(); j++){ th(i, j) = arg(u(i, j)); } } return std::make_pair(mag, th); } <file_sep>/* to comiple: * h5c++ -O3 test_CQCGL1dReq.cc -L../../lib -I../../include -I$EIGEN -std=c++11 -lCQCGL1dReq -lCQCGL1d -lsparseRoutines -ldenseRoutines -literMethod -lmyH5 -lfftw3 -lm */ #include "CQCGL1dReq.hpp" #include <iostream> #include <fstream> #include <Eigen/Dense> #include <complex> #include <H5Cpp.h> using namespace std; using namespace Eigen; using namespace denseRoutines; using namespace MyH5; typedef std::complex<double> dcp; #define N10 int main(int argc, char **argv){ #ifdef N10 //====================================================================== // test the accuracy of req. const int N = 1024, L = 50; double Bi = 0.8, Gi = -0.6; CQCGL1dReq cgl(N, L, -0.1, 0.125, 0.5, 1, Bi, -0.1, Gi, 0); string fileName = "/usr/local/home/xiong/00git/research/data/cgl/reqBiGi.h5"; H5File file(fileName, H5F_ACC_RDWR); ArrayXd a0; double wth0, wphi0, err0; std::tie(a0, wth0, wphi0, err0) = cgl.read(file, cgl.toStr(Bi, Gi, 1)); a0 += ArrayXd::Random(a0.size()) * 0.1; ArrayXd a; double wth, wphi, err; int flag; std::tie(a, wth, wphi, err, flag) = cgl.findReq_LM(a0, wth0, wphi0, 1e-10, 100, 1000); fprintf(stderr, "%g %g %g\n", wth, wphi, err); #endif #ifdef N20 //====================================================================== // use a Gaussian shape guess to find the 2nd soliton. const int N = 1024; const double L = 50; double Bi = 0.8; double Gi = -0.6; CQCGL1dReq cgl(N, L, -0.1, 0.125, 0.5, 1, Bi, -0.1, Gi, 0); VectorXcd A0 = Gaussian(N, N/2, N/20, 1); ArrayXd a0 = cgl.Config2Fourier(A0); std::vector<double> th = cgl.optThPhi(a0); double wth0 = th[0], wphi0 = th[1]; cout << wth0 << ' ' << wphi0 << endl; ArrayXd a; double wth, wphi, err; int flag; std::tie(a, wth, wphi, err, flag) = cgl.findReq_LM(a0, wth0, wphi0, 1e-10, 100, 1000); fprintf(stderr, "%g %g %g\n", wth, wphi, err); string file = "/usr/local/home/xiong/00git/research/data/cgl/reqBiGi.h5"; if (flag == 0) cgl.write(file, Bi, Gi, 2, a, wth, wphi, err); #endif #ifdef N30 //====================================================================== // use a Gaussian shape guess and evove it for a while and then to find // the 1st soliton const int N = 1024; const double L = 50; double Bi = 0.8; double Gi = -0.6; CQCGL1dReq cgl(N, L, -0.1, 0.125, 0.5, 1, Bi, -0.1, Gi, 0); VectorXcd A0 = Gaussian(N, N/2, N/20, 3); ArrayXd a0 = cgl.Config2Fourier(A0); ArrayXXd aa = cgl.intg(a0, 1e-3, 10000, 10000); a0 = aa.rightCols(1); std::vector<double> th = cgl.optThPhi(a0); double wth0 = th[0], wphi0 = th[1]; cout << wth0 << ' ' << wphi0 << endl; ArrayXd a; double wth, wphi, err; int flag; std::tie(a, wth, wphi, err, flag) = cgl.findReq_LM(a0, wth0, wphi0, 1e-10, 100, 1000); fprintf(stderr, "%g %g %g\n", wth, wphi, err); string file = "/usr/local/home/xiong/00git/research/data/cgl/reqBiGi.h5"; if (flag == 0) cgl.write(file, Bi, Gi, 1, a, wth, wphi, err); #endif #ifdef N40 //====================================================================== // try to calculate the eigenvalue and eigenvector of one req const int N = 1024; const double L = 50; double Bi = 1.8; double Gi = -0.6; CQCGL1dReq cgl(N, L, -0.1, 0.125, 0.5, 1, Bi, -0.1, Gi, 0); string file = "/usr/local/home/xiong/00git/research/data/cgl/reqBiGi.h5"; int id = 1; ArrayXd a0; double wth0, wphi0, err0; std::tie(a0, wth0, wphi0, err0) = cgl.read(file, cgl.toStr(Bi, Gi, id)); VectorXcd e; MatrixXcd v; std::tie(e, v) = cgl.evReq(a0, wth0, wphi0); cout << e.head(10) << endl; cout << endl; cout << v.cols() << ' ' << v.rows() << endl; #endif #ifdef N50 //====================================================================== // combine the calculated E/V data string s = "/usr/local/home/xiong/00git/research/data/cgl/reqBiGiEV"; H5File fout(s + ".h5", H5F_ACC_RDWR); int ids[] = {1, 2}; for ( int i = 0; i < 8; i++){ H5File fin(s + "_add_" + to_string(i) + ".h5", H5F_ACC_RDONLY); for (int j = 0; j < 2; j++){ int id = ids[j]; for( int k = 0; k < 24; k++){ double Bi = 3.5 + 0.1*k; for(int p = 0; p < 55; p++){ double Gi = -5.6 + 0.1*p; string g = CQCGL1dReq::toStr(Bi, Gi, id); if (checkGroup(fin, g+"/vr", false)){ fprintf(stderr, "%d %g %g\n", id, Bi, Gi); CQCGL1dReq::move(fin, g, fout, g, 2); } } } } } #endif #ifdef N60 //====================================================================== // extend the soliton in one direction of parameter space iterMethod::LM_OUT_PRINT = false; iterMethod::LM_IN_PRINT = false; iterMethod::CG_PRINT = false; const int N = 1024; const double L = 50; double Bi = 4.5; double Gi = -5.6; CQCGL1dReq cgl(N, L, -0.1, 0.125, 0.5, 1, Bi, -0.1, Gi, 0); string fileName = "/usr/local/home/xiong/00git/research/data/cgl/reqBiGi.h5"; H5File file(fileName, H5F_ACC_RDWR); double stepB = 0.1; int NsB = 55; cgl.findReqParaSeq(file, 1, stepB, NsB, false); cgl.findReqParaSeq(file, 2, stepB, NsB, false); // cgl.findReqParaSeq(file, 2, 0.1, 53, false); #endif return 0; } <file_sep>import numpy as np import matplotlib.pyplot as plt import h5py N = 256; f = h5py.File('/usr/local/home/xiong/svn/DOGS/blog/code/data/req.h5', 'r') ver = f['/req1/vecr']; n1, n2 = ver.shape vei = f['/req1/veci'] vr = np.zeros((n1,n2), np.double); vi = np.zeros((n1,n2), np.double); ver.read_direct(vr); vei.read_direct(vi); ve = vr+1j*vi taa = ve.T ia = np.fft.ifft(taa, axis=0) fig = plt.figure(figsize=(5,5)); ax = fig.add_subplot(111) ax.plot(np.linspace(0, 50, 2*N), ia[:,0].real, 'r-', lw = 2.0, label='real') ax.plot(np.linspace(0, 50, 2*N), ia[:,0].imag, 'b--', lw = 2.0, label='imag') ax.locator_params(nbins=5) ax.set_ylim((-0.008, 0.008)) plt.tight_layout(pad=0) plt.legend() plt.show() f.close() <file_sep>#ifndef EID_H #define EID_H #include <cmath> #include <ctime> #include <chrono> #include <iostream> #include <unordered_map> #include <Eigen/Dense> // #include "denseRoutines.hpp" using namespace std; using namespace Eigen; ////////////////////////////////////////////////////////////////////////////////// // Exponetial Integrator with Diagonal Linear Part ////////////////////////////////////////////////////////////////////////////////// /** * @brief Exponential Integrator * * DT : data type (double/complex) */ template<typename DT> class EID { public: typedef std::complex<double> dcp; typedef Array<DT, Dynamic, 1> Ary; ////////////////////////////////////////////////////////////////////// Ary *L; ArrayXXcd *N, *Y; // single or multiple states struct Scheme { // string name; // scheme name int nstage; /* number of stages, which is used to indicate which Y[?] store the update */ int nYN; // number of Y[], N[] needed in the internal stage int nnl; // number of nonlinear evaluations per step int nab; // number of calculation of a, b whenever change step int order; // orders of scheme Scheme(int nstage, int nYN, int nnl, int nab, int order) : nstage(nstage), nYN(nYN), nnl(nnl), nab(nab), order(order) {} }; const std::unordered_map<std::string, Scheme> names = { // name nstage nYN nnl nab order {"Cox_Matthews", Scheme(4, 5, 5, 4, 4)}, {"Krogstad", Scheme(4, 5, 5, 8, 4)}, {"Hochbruck_Ostermann", Scheme(5, 5, 5, 11, 4)}, {"Luan_Ostermann", Scheme(8, 9, 9, 23, 5)}, {"IFRK43", Scheme(4, 5, 5, 0, 4)}, {"IFRK54", Scheme(6, 7, 7, 0, 5)}, {"SSPP43", Scheme(3, 4, 24, 0, 4)} }; std::string scheme = "Cox_Matthews"; /* default scheme */ Ary a[9][9], b[9], c[9]; int M = 64; /* number of sample points */ int R = 1; /* radius for evaluating phi(z) */ int CN = 0; /* counter number. When L has large dimension, we should split L into pieces and then do counter average. The purpose is to save memory. Name, L -> L[0:CN], L[CN+1, 2*CN], ... If CN <= 0, then not split. */ double a1, a2, a3; // for split step method //////////////////////////////////////////////////////////// // time adaptive method related parameters double rtol = 1e-8; double nu = 0.9; /* safe factor */ double mumax = 4; /* maximal time step increase factor */ double mumin = 0.4; /* minimal time step decrease factor */ double mue = 1.25; /* upper lazy threshold */ double muc = 0.85; /* lower lazy threshold */ //double mue = 1.35; //double muc = 0.8; int NCalCoe = 0; /* times to evaluate coefficient */ int NReject = 0; /* times that new state is rejected */ int NCallF = 0; /* times to call velocity function f */ int NSteps = 0; /* total number of integrations steps */ double TotalTime = 0; double CoefficientTime = 0; double err = 0; /* LTE : local truncation error estimation */ //////////////////////////////////////////////////////////// // constructor and desctructor EID(){} EID(Ary *L, ArrayXXcd *Y, ArrayXXcd *N) : L(L), Y(Y), N(N){} ~EID(){} void init(Ary *L, ArrayXXcd *Y, ArrayXXcd *N){ this->L = L; this->Y = Y; this->N = N; } //////////////////////////////////////////////////////////// // NL : the nonlinear function // SS : save state function template<class NL, class SS> void intg(NL nl, SS saveState, const double t0, const ArrayXXcd &u0, const double tend, const double h0, const int skip_rate){ auto t_start = std::chrono::high_resolution_clock::now(); int ns = names.at(scheme).nstage; int od = names.at(scheme).order; int nnl = names.at(scheme).nnl; int nab = names.at(scheme).nab; NCalCoe = 0; NReject = 0; NCallF = 0; NSteps = 0; TotalTime = 0; CoefficientTime = 0; double h = h0; CoefficientTime += calCoe(h); NCalCoe += nab; double t = t0; Y[0] = u0; bool doChange, doAccept; bool TimeEnds = false; while(!TimeEnds){ if ( t + h > tend){ h = tend - t; CoefficientTime += calCoe(h); NCalCoe += nab; TimeEnds = true; } oneStep(t, h, nl); NCallF += nnl; double s = nu * std::pow(rtol/err, 1.0/od); double mu = adaptTs(doChange, doAccept, s); if (doAccept){ t += h; NSteps++; Y[0] = Y[ns]; if ( NSteps % skip_rate == 0 || TimeEnds) saveState(Y[0], t, h, err); } else { NReject++; TimeEnds = false; } if (doChange) { h *= mu; CoefficientTime += calCoe(h); NCalCoe += nab; } } auto t_end = std::chrono::high_resolution_clock::now(); std::chrono::duration<double> t_elapse = t_end - t_start; TotalTime = t_elapse.count(); } /// @brief constant time-stepping integrator. /// @note the initial condition will not be recorded. template<class NL, class SS> void intgC(NL nl, SS saveState, const double t0, const ArrayXXcd &u0, const double tend, const double h, const int skip_rate){ int ns = names.at(scheme).nstage; int nnl = names.at(scheme).nnl; int nab = names.at(scheme).nab; NCallF = 0; NSteps = 0; NCalCoe = 0; calCoe(h); NCalCoe += nab; const int Nt = static_cast<int>( round((tend-t0)/h) ); double t = t0; Y[0] = u0; for(int i = 0; i < Nt; i++){ oneStep(t, h, nl); NCallF += nnl; NSteps++; t += h; Y[0] = Y[ns]; if((i+1)%skip_rate == 0 || i == Nt-1) saveState(Y[0], t, h, err); } } /** * @brief calculat the damping factor of time step * * @param[out] doChange true if time step needs change * @param[out] doAccept true if accept current time step * @param[in] s estimate damping factor * @return mu final dampling factor */ inline double adaptTs(bool &doChange, bool &doAccept, const double s){ double mu = 1; doChange = true; doAccept = true; if ( s > mumax) mu = mumax; else if (s > mue) mu = s; else if (s >= 1) { mu = 1; doChange = false; } else { doAccept = false; if (s > muc) mu = muc; else if (s > mumin) mu = s; else mu = mumin; // cout << mu << '\t' << rtol << '\t' << err << '\t' << NSteps << endl; } return mu; } /** * nonlinear class NL provides container for intermediate steps * * @note the multiplication operator blow is overloaded. */ template<class NL> void oneStep(double t, double h, NL nl){ if(scheme == "Cox_Matthews") { nl(Y[0], N[0], t); Y[1] = MUL(c[1], Y[0]) + MUL(a[1][0], N[0]); nl(Y[1], N[1], t+h/2); Y[2] = MUL(c[1], Y[0]) + MUL(a[1][0], N[1]); nl(Y[2], N[2], t+h/2); Y[3] = MUL(c[1], Y[1]) + MUL(a[1][0], 2*N[2]-N[0]); nl(Y[3], N[3], t+h); Y[4] = MUL(c[3], Y[0]) + MUL(b[0], N[0]) + MUL(b[1], N[1]+N[2]) + MUL(b[3], N[3]); nl(Y[4], N[4], t+h); err = MUL(b[3], N[4]-N[3]).abs().maxCoeff() / Y[4].abs().maxCoeff(); } else if (scheme == "Krogstad") { nl(Y[0], N[0], t); Y[1] = MUL(c[1], Y[0]) + MUL(a[1][0], N[0]); nl(Y[1], N[1], t+h/2); Y[2] = MUL(c[1], Y[0]) + MUL(a[2][0], N[0]) + MUL(a[2][1], N[1]); nl(Y[2], N[2], t+h/2); Y[3] = MUL(c[3], Y[0]) + MUL(a[3][0], N[0]) + MUL(a[3][2], N[2]); nl(Y[3], N[3], t+h); Y[4] = MUL(c[3], Y[0]) + MUL(b[0], N[0]) + MUL(b[1], N[1]+N[2]) + MUL(b[3], N[3]); nl(Y[4], N[4], t+h); err = MUL(b[3], N[4]-N[3]).abs().maxCoeff() / Y[4].abs().maxCoeff(); } else if (scheme == "Hochbruck_Ostermann") { nl(Y[0], N[0], t); Y[1] = MUL(c[1], Y[0]) + MUL(a[1][0], N[0]); nl(Y[1], N[1], t+h/2); Y[2] = MUL(c[1], Y[0]) + MUL(a[2][0], N[0]) + MUL(a[2][1], N[1]); nl(Y[2], N[2], t+h/2); Y[3] = MUL(c[3], Y[0]) + MUL(a[3][0], N[0]) + MUL(a[3][1], N[1]+N[2]); nl(Y[3], N[3], t+h); Y[4] = MUL(c[1], Y[0]) + MUL(a[4][0], N[0]) + MUL(a[4][1], N[1]+N[2]) + MUL(a[4][3], N[3]); nl(Y[4], N[4], t+h/2); Y[5] = MUL(c[3], Y[0]) + MUL(b[0], N[0]) + MUL(b[3], N[3]) + MUL(b[4], N[4]); err = MUL(b[4], N[4]-0.5*N[2]-0.5*N[1]).abs().maxCoeff() / Y[5].abs().maxCoeff(); } else if (scheme == "Luan_Ostermann"){ nl(Y[0], N[0], t); Y[1] = MUL(c[1], Y[0]) + MUL(a[1][0], N[0]); nl(Y[1], N[1], t+h/2); Y[2] = MUL(c[1], Y[0]) + MUL(a[2][0], N[0]) + MUL(a[2][1], N[1]); nl(Y[2], N[2], t+h/2); Y[3] = MUL(c[3], Y[0]) + MUL(a[3][0], N[0]) + MUL(a[3][2], N[2]); nl(Y[3], N[3], t+h/4); Y[4] = MUL(c[1], Y[0]) + MUL(a[4][0], N[0]) + MUL(a[4][2], N[2]) + MUL(a[4][3], N[3]); nl(Y[4], N[4], t+h/2); Y[5] = MUL(c[5], Y[0]) + MUL(a[5][0], N[0]) + MUL(a[5][3], N[3]) + MUL(a[5][4], N[4]); nl(Y[5], N[5], t+h/5); Y[6] = MUL(c[6], Y[0]) + MUL(a[6][0], N[0]) + MUL(a[6][3], N[3]) + MUL(a[6][4], N[4]) + MUL(a[6][5], N[5]); nl(Y[6], N[6], t+2*h/3); Y[7] = MUL(c[7], Y[0]) + MUL(a[7][0], N[0]) + MUL(a[7][4], N[4]) + MUL(a[7][5], N[5]) + MUL(a[7][6], N[6]); nl(Y[7], N[7], t+h); Y[8] = MUL(c[7], Y[0]) + MUL(b[0], N[0]) + MUL(b[5], N[5]) + MUL(b[6], N[6]) + MUL(b[7], N[7]); nl(Y[8], N[8], t+h); err = MUL(b[7], N[8]-N[7]).abs().maxCoeff() / Y[8].abs().maxCoeff(); } else if (scheme == "IFRK43") { nl(Y[0], N[0], t); Y[1] = MUL(c[1], Y[0]) + MUL(a[1][0], N[0]); nl(Y[1], N[1], t+h/2); Y[2] = MUL(c[1], Y[0]) + (h*0.5)*N[1]; nl(Y[2], N[2], t+h/2); Y[3] = MUL(c[3], Y[0]) + MUL(a[3][2], N[2]); nl(Y[3], N[3], t+h); Y[4] = MUL(c[3], Y[0]) + MUL(b[0], N[0]) + MUL(b[1], N[1]+N[2]) + (h/6)*N[3]; nl(Y[4], N[4], t+h); err = h*(1.0/10)*(N[4] - N[3]).abs().maxCoeff() / Y[4].abs().maxCoeff(); } else if (scheme == "IFRK54"){ nl(Y[0], N[0], t); Y[1] = MUL(c[1], Y[0]) + MUL(a[1][0], N[0]); nl(Y[1], N[1], t+h/5); Y[2] = MUL(c[2], Y[0]) + MUL(a[2][0], N[0]) + MUL(a[2][1], N[1]); nl(Y[2], N[2], t+3*h/10); Y[3] = MUL(c[3], Y[0]) + MUL(a[3][0], N[0]) + MUL(a[3][1], N[1]) + MUL(a[3][2], N[2]); nl(Y[3], N[3], t+4*h/5); Y[4] = MUL(c[4], Y[0]) + MUL(a[4][0], N[0]) + MUL(a[4][1], N[1]) + MUL(a[4][2], N[2]) + MUL(a[4][3], N[3]); nl(Y[4], N[4], t+8*h/9); Y[5] = MUL(c[5], Y[0]) + MUL(a[5][0], N[0]) + MUL(a[5][1], N[1]) + MUL(a[5][2], N[2]) + MUL(a[5][3], N[3]) + MUL(a[5][4], N[4]); nl(Y[5], N[5], t+h); Y[6] = MUL(c[5], Y[0]) + MUL(b[0], N[0]) + MUL(b[2], N[2]) + MUL(b[3], N[3]) + MUL(b[4], N[4]) + (h*11./84)*N[5]; nl(Y[6], N[6], t+h); err = h*(-71./57600*N[0] + 71./16695*N[2] - 71./1920*N[3] + 17253./339200*N[4] -22./525*N[5] + 1./40*N[6]).abs().maxCoeff() / Y[4].abs().maxCoeff(); } else if (scheme == "SSPP43") { ArrayXcd y0 = Y[0]; Y[0] = MUL(c[0], Y[0]); Y[0] = rk4(t+a1*h, a3*h, nl); Y[0] = MUL(c[1], Y[0]); Y[0] = rk4(t+(a1+a2+a3)*h, a2*h, nl); Y[0] = MUL(c[2], Y[0]); ArrayXcd t1 = rk4(t+(a1+2*a3+2*a2)*h, a1*h, nl); Y[0] = y0; Y[0] = rk4(t, a1*h, nl); Y[0] = MUL(c[2], Y[0]); Y[0] = rk4(t+(a1+a3)*h, a2*h, nl); Y[0] = MUL(c[1], Y[0]); Y[0] = rk4(t+(a1+a3+2*a2)*h, a3*h, nl); ArrayXcd t2 = MUL(c[0], Y[0]); Y[3] = 0.5*(t1 + t2); err = 0.5*(t1 - t2).abs().maxCoeff() / Y[3].abs().maxCoeff(); Y[0] = y0; // reset previous state } else { fprintf(stderr, "Please indicate the scheme !\n"); exit(1); } } template<class NL> ArrayXcd rk4(double t, double h, NL nl){ nl(Y[0], N[0], t); Y[1] = Y[0] + h/2 * N[0]; nl(Y[1], N[1], t+h/2); Y[2] = Y[0] + h/2 * N[1]; nl(Y[2], N[2], t+h/2); Y[3] = Y[0] + h * N[2]; nl(Y[3], N[3], t+h); return Y[0] + h/6* (N[0] + 2*(N[1]+N[2]) + N[3]); } /// @brief calculate the coefficients of Butcher table. /// The size of coefficient is determined by L. /// /// @return time used in seconds double calCoe(double h){ auto t_start = std::chrono::high_resolution_clock::now(); int sL = (*L).size(); // size of L int p = 1; int n = sL; if (CN > 0){ p = sL / CN; n = CN; } Ary hL = h * (*L); if(scheme == "Cox_Matthews") { c[1] = (hL/2).exp(); c[3] = hL.exp(); a[1][0].resize(sL); b[0].resize(sL); b[1].resize(sL); b[3].resize(sL); for (int i = 0; i < p; i++){ int s = i != p-1 ? n : sL-(p-1)*n; Ary hLs = h * (*L).segment(i*n, s); ArrayXXcd z = ZR(hLs); ArrayXXcd z2 = z.square(); ArrayXXcd z3 = z.cube(); ArrayXXcd ze = z.exp(); ArrayXXcd zeh = (z/2).exp(); a[1][0].segment(i*n, s) = h * mean( (zeh - 1)/z ); b[0].segment(i*n, s) = h * mean( (-4.0 - z + ze*(4.0 - 3.0 * z + z2)) / z3 ); b[1].segment(i*n, s) = h*2*mean( (2.0 + z + ze*(-2.0 + z)) / z3 ); b[3].segment(i*n, s) = h * mean( (-4.0 - 3.0*z -z2 + ze*(4.0 - z) ) / z3 ); } } else if (scheme == "Krogstad") { c[1] = (hL/2).exp(); c[3] = hL.exp(); a[1][0].resize(sL); a[2][0].resize(sL); a[2][1].resize(sL); a[3][0].resize(sL); a[3][2].resize(sL); b[0].resize(sL); b[1].resize(sL); b[3].resize(sL); for(int i = 0; i < p; i++){ int s = i != p-1 ? n : sL-(p-1)*n; Ary hLs = h * (*L).segment(i*n, s); ArrayXXcd z = ZR(hLs); ArrayXXcd z2 = z.square(); ArrayXXcd z3 = z.cube(); ArrayXXcd ze = z.exp(); ArrayXXcd zeh = (z/2).exp(); ArrayXXcd t1 = z + 2; ArrayXXcd t2 = z - 2; ArrayXXcd t3 = z - 4; ArrayXXcd t4 = z + 4; a[1][0].segment(i*n, s) = h * mean( (zeh - 1)/z ); a[2][0].segment(i*n, s) = h * mean( (zeh*t3 + t4) / z2 ); a[2][1].segment(i*n, s) = h*2*mean( (2*zeh - t1) / z2 ); a[3][0].segment(i*n, s) = h * mean( (ze*t2 + t1) / z2 ); a[3][2].segment(i*n, s) = h*2*mean( (ze - z - 1) / z2 ); b[0].segment(i*n, s) = h * mean( (-t4 + ze*(4.0 - 3.0 * z + z2)) / z3 ); b[1].segment(i*n, s) = h*2*mean( (t1 + ze*t2) / z3 ); b[3].segment(i*n, s) = h * mean( (-4.0 - 3.0*z -z2 - ze*t3 ) / z3 ); } } else if (scheme == "Hochbruck_Ostermann") { c[1] = (hL/2).exp(); c[3] = hL.exp(); a[1][0].resize(sL); a[2][0].resize(sL); a[2][1].resize(sL); a[3][0].resize(sL); a[3][1].resize(sL); a[4][0].resize(sL); a[4][1].resize(sL); a[4][3].resize(sL); b[0].resize(sL); b[3].resize(sL); b[4].resize(sL); for (int i = 0; i < p; i++){ int s = i != p-1 ? n : sL-(p-1)*n; Ary hLs = h * (*L).segment(i*n, s); ArrayXXcd z = ZR(hLs); ArrayXXcd z2 = z.square(); ArrayXXcd z3 = z.cube(); ArrayXXcd ze = z.exp(); ArrayXXcd zeh = (z/2).exp(); ArrayXXcd t1 = -4 + z; ArrayXXcd t2 = 4*z3; ArrayXXcd t3 = 20 + ze*t1; ArrayXXcd t4 = 4 + z; ArrayXXcd t5 = -2 + z; ArrayXXcd t6 = 2 + z; a[1][0].segment(i*n, s) = h * mean( (zeh - 1)/z ); a[2][0].segment(i*n, s) = h * mean( (zeh*t1 + t4) / z2 ); a[2][1].segment(i*n, s) = h*2*mean( (2*zeh - t6) / z2 ); a[3][0].segment(i*n, s) = h * mean( (ze*t5 + t6) / z2 ); a[3][1].segment(i*n, s) = h * mean( (ze - z - 1) / z2 ); a[4][0].segment(i*n, s) =-h * mean( (t3 - z + z2 - 4*zeh*(4-3*z+z2)) / t2 ); a[4][1].segment(i*n, s) = h * mean( (t3 + 3*z - z2 + 8*zeh*t5) / t2 ); a[4][3].segment(i*n, s) =-h * mean( (t3 + 7*z + z2 + 4*zeh*t1) / t2 ); b[0].segment(i*n, s) = h * mean( (-t4 + ze*(4 - 3*z + z2)) / z3 ); b[3].segment(i*n, s) =-h * mean( (4 + 3*z + z2 + ze*t1) / z3 ); b[4].segment(i*n, s) = h*4*mean( (t6 + ze*t5 ) / z3 ); } } else if (scheme == "Luan_Ostermann"){ c[1] = (hL/2).exp(); c[3] = (hL/4).exp(); c[5] = (hL/5).exp(); c[6] = (2*hL/3).exp(); c[7] = hL.exp(); a[1][0].resize(sL); a[2][0].resize(sL); a[2][1].resize(sL); a[3][0].resize(sL); a[3][2].resize(sL); a[4][0].resize(sL); a[4][2].resize(sL); a[4][3].resize(sL); a[5][0].resize(sL); a[5][3].resize(sL); a[5][4].resize(sL); a[6][0].resize(sL); a[6][3].resize(sL); a[6][4].resize(sL); a[6][5].resize(sL); a[7][0].resize(sL); a[7][4].resize(sL); a[7][5].resize(sL); a[7][6].resize(sL); b[0].resize(sL); b[5].resize(sL); b[6].resize(sL); b[7].resize(sL); for (int i = 0; i < p; i++){ int s = i != p-1 ? n : sL-(p-1)*n; Ary hLs = h * (*L).segment(i*n, s); ArrayXXcd z = ZR(hLs); ArrayXXcd z2 = z.square(); ArrayXXcd z3 = z.cube(); ArrayXXcd z4 = z2.square(); ArrayXXcd ze = z.exp(); ArrayXXcd zeh = (z/2).exp(); ArrayXXcd ze4 = (z/4).exp(); ArrayXXcd ze5 = (z/5).exp(); ArrayXXcd ze3 = (2*z/3).exp(); ArrayXXcd t1 = -4 + z; ArrayXXcd t2 = 2*z2; ArrayXXcd t3 = 25*z3; ArrayXXcd t4 = 4 + z; ArrayXXcd t5 = 60-14*z+z2; ArrayXXcd t6 = -375*ze5*t5 - 486*ze3*t5; ArrayXXcd t7 = 16-6*z+z2; ArrayXXcd t8 = 100-5*z-3*z2; a[1][0].segment(i*n, s) = h * mean( (zeh - 1)/z ); a[2][0].segment(i*n, s) = h * mean( (zeh*(-2+z) + 2) / z2 ); a[2][1].segment(i*n, s) = h * mean( (2*zeh - z - 2) / z2 ); a[3][0].segment(i*n, s) = h * mean( (2*ze4*(-2+z)- t1) / t2 ); a[3][2].segment(i*n, s) = h * mean( (4*ze4 - t4) / t2 ); a[4][0].segment(i*n, s) = h * mean( (zeh*t7 - 2*(8+z)) / z3 ); a[4][2].segment(i*n, s) =-h * mean( (2*zeh*(-8+z) + 16 + 6*z + z2) / z3 ); a[4][3].segment(i*n, s) = h*8*mean( (zeh*t1 + t4) / z3 ); a[5][0].segment(i*n, s) = h * mean( (-400 + 70*z - 3*z2 + 25*ze5*t7) / t3 ); a[5][3].segment(i*n, s) = h*8*mean( (t8 + 25*ze5*t1) / t3 ); a[5][4].segment(i*n, s) = h*2*mean( (-200 - 25*ze5*(-8+z) - 15*z + z2) / t3 ); a[6][0].segment(i*n, s) =-h * mean( (3740 + 125*ze5*t1 + 1001*z + 111*z2 - 162*ze3*(20-7*z+z2)) / (162*z3) ); a[6][3].segment(i*n, s) =h*20*mean( (-t8 - 25*ze5*t1) / (81*z3) ); a[6][4].segment(i*n, s) =-h * mean( (2740 + 324*ze3*(-10+z) - 125*ze5*t1 + 1861*z + 519*z2) / (243*z3) ); a[6][5].segment(i*n, s) =h*25*mean( (125*ze5*t1 + 162*ze3*t1 + 7*(164+35*z+3*z2)) / (486*z3) ); a[7][0].segment(i*n, s) = h * mean( (t6 + 35*ze*(-180+82*z-17*z2+2*z3) + 28*(2070+547*z+110*z2+14*z3)) / (70*z4) ); a[7][4].segment(i*n, s) = h*4*mean( (t6 - 140*ze*(45-13*z+z2) + 7*(8280+2338*z+525*z2+76*z3)) / (105*z4) ); a[7][5].segment(i*n, s) = h*5*mean( (-t6 + 350*ze*(18-7*z+z2) - 7*(8280+2248*z+465*z2+61*z3)) / (147*z4) ); a[7][6].segment(i*n, s) =h*27*mean( (125*ze5*t5 + 162*ze3*t5 + 35*ze*t5 - 14*(1380+398*z+95*z2+16*z3)) / (490*z4) ); b[0].segment(i*n, s) = h * mean( (90 + 34*z + 4*z2 + ze*(-90 + 56*z -15*z2 + 2*z3)) / (2*z4) ); b[5].segment(i*n, s)=h*125*mean( (-18 - 8*z - z2 + 2*ze*(9 - 5*z + z2)) / (28*z4) ); b[6].segment(i*n, s)=-h*27*mean( (ze*(30 - 12*z + z2) - 2*(15 + 9*z + 2*z2)) / (14*z4) ); b[7].segment(i*n, s) =-h * mean( (90 + 64*z + 21*z2 + 4*z3 - 2*ze*(45 - 13*z + z2)) / (4*z4) ); } } else if (scheme == "IFRK43") { c[1] = (hL/2).exp(); c[3] = hL.exp(); a[1][0] = h/2 * c[1]; a[3][2] = h * c[1]; b[0] = h * (1.0/6) * c[3]; b[1] = h * (1.0/3) * c[1]; } else if (scheme == "IFRK54"){ c[1] = (hL/5).exp(); c[2] = (3*hL/10).exp(); c[3] = (4*hL/5).exp(); c[4] = (8*hL/9).exp(); c[5] = hL.exp(); a[1][0] = (h/5) * c[1]; a[2][0] = (h*3/40) * c[2]; a[2][1] = (h*9/40) * (hL/10).exp(); a[3][0] = (h*44/45) * c[3]; a[3][1] = (-h*56.0/15) * (3*hL/5).exp(); a[3][2] = (h*32.0/9) * (hL/2).exp(); a[4][0] = (h*19372.0/6561) * c[4]; a[4][1] = (-h*25360.0/2187) * (31*hL/45).exp(); a[4][2] = (h*64448.0/6561) * (53*hL/90).exp(); a[4][3] = (-h*212.0/729) * (4*hL/45).exp(); a[5][0] = (h*9017.0/3168) * c[5]; a[5][1] = (-h*355.0/33) * (4*hL/5).exp(); a[5][2] = (h*46732.0/5247) * (7*hL/10).exp(); a[5][3] = (h*49.0/176) * c[1]; a[5][4] = (-h*5103.0/18656) * (hL/9).exp(); b[0] = (h*35.0/384) * c[5]; b[2] = (h*500./1113) * (7*hL/10).exp(); b[3] = (h*125./192) * c[1]; b[4] = (-h*2187./6784) * (hL/9).exp(); } else if (scheme == "SSPP43") { a1 = 0.268330095781759925; a2 = -0.187991618799159782; a3 = 0.919661523017399857; c[0] = (a1*hL).exp(); c[1] = (a2*hL).exp(); c[2] = (a3*hL).exp(); } else { fprintf(stderr, "Please indicate the scheme !\n"); exit(1); } auto t_end = std::chrono::high_resolution_clock::now(); std::chrono::duration<double> t_elapse = t_end - t_start; return t_elapse.count(); } /// @brief multiplication /// @note in order to pass expressions as arguments, the arguments /// must be declared as const inline virtual ArrayXXcd MUL(const Ary &C, const ArrayXXcd &Y){ // for ArrayXcd * (ArrayXcd/ArrayXXcd): Y.colwise() * C // for ArrayXd * (ArrayXcd/ArrayXXcd): C.matrix().asDiagonal() * Y.matrix() } inline virtual ArrayXXcd ZR(Ary &z){} inline virtual Ary mean(const Ref<const ArrayXXcd> &x){} }; #endif /* EID_H */ <file_sep>from py_CQCGL1d import * from cglHelp import * case = 20 if case == 5: """ View the req and rpo for the same di. 2d version """ N = 1024 d = 30 h = 0.0002 di = 0.422 a0, wth0, wphi0, err = cqcglReadReqdi('../../data/cgl/reqDi.h5', di, 1) cgl = pyCqcgl1d(N, d, h, True, 0, 4.0, 0.8, 0.01, di, 4) eigvalues, eigvectors = eigReq(cgl, a0, wth0, wphi0) eigvectors = Tcopy(realve(eigvectors)) a0Hat = cgl.orbit2slice(a0)[0] veHat = cgl.ve2slice(eigvectors, a0) e1, e2 = orthAxes2(veHat[0], veHat[1]) x1, T1, nstp1, th1, phi1, err1 = cqcglReadRPOdi( '../../data/cgl/rpoT2X1.h5', di, 1) h1 = T1 / nstp1 nstp1 = np.int(nstp1) cgl2 = pyCqcgl1d(N, d, h1, False, 0, 4.0, 0.8, 0.01, di, 4) aa1 = cgl2.intg(x1, nstp1, 1) aa1Hat, th2, phi2 = cgl2.orbit2slice(aa1) aa1Hat -= a0Hat aa1HatProj = np.dot(aa1Hat, np.vstack((e1, e2)).T) fig = plt.figure(figsize=[6, 4]) ax = fig.add_subplot(111) ax.plot(aa1HatProj[:, 0], aa1HatProj[:, 1], c='r', lw=1) ax.scatter([0], [0], s=160) ax.set_xlabel(r'$e_1$', fontsize=25) ax.set_ylabel(r'$e_2$', fontsize=25) fig.tight_layout(pad=0) plt.show(block=False) # plotConfigSurfaceFourier(cgl, aa1, [0, d, 0, T1]) if case == 6: """ View origin, req and rpo for the same di. 3d version """ N = 1024 d = 30 h = 0.0002 di = 0.41 a0, wth0, wphi0, err = cqcglReadReqdi('../../data/cgl/reqDi.h5', di, 1) cgl = pyCqcgl1d(N, d, h, True, 0, 4.0, 0.8, 0.01, di, 4) eigvalues, eigvectors = eigReq(cgl, a0, wth0, wphi0) eigvectors = Tcopy(realve(eigvectors)) a0Hat = cgl.orbit2slice(a0)[0] veHat = cgl.ve2slice(eigvectors, a0) x1, T1, nstp1, th1, phi1, err1 = cqcglReadRPOdi( '../../data/cgl/rpoT2X1.h5', di, 1) h1 = T1 / nstp1 nstp1 = np.int(nstp1) cgl2 = pyCqcgl1d(N, d, h1, False, 0, 4.0, 0.8, 0.01, di, 4) aa1 = cgl2.intg(x1, nstp1, 1) aa1Hat, th2, phi2 = cgl2.orbit2slice(aa1) aa1Hat -= a0Hat # e1, e2 = orthAxes2(veHat[0], veHat[1]) e1, e2, e3 = orthAxes(veHat[0], veHat[1], veHat[6]) aa1HatProj = np.dot(aa1Hat, np.vstack((e1, e2, e3)).T) OProj = np.dot(-a0Hat, np.vstack((e1, e2, e3)).T) fig = plt.figure(figsize=[6, 4]) ax = fig.add_subplot(111, projection='3d') ax.plot(aa1HatProj[:, 0], aa1HatProj[:, 1], aa1HatProj[:, 2], c='r', lw=2) ax.scatter([0], [0], [0], s=80, marker='o', c='b', edgecolors='none') ax.scatter(OProj[0], OProj[1], OProj[2], s=60, marker='o', c='c', edgecolors='none') ax.set_xlabel(r'$e_1$', fontsize=25) ax.set_ylabel(r'$e_2$', fontsize=25) ax.set_zlabel(r'$e_3$', fontsize=25) fig.tight_layout(pad=0) plt.show(block=False) if case == 10: """ view rep and rpo together in the symmetry reduced prejection frame. Also view the unstable manifold of the req """ N = 1024 d = 30 h = 0.0002 di = 0.4226 a0, wth0, wphi0, err = cqcglReadReqdi('../../data/cgl/reqDi.h5', di, 1) cgl = pyCqcgl1d(N, d, h, True, 0, 4.0, 0.8, 0.01, di, 4) eigvalues, eigvectors = eigReq(cgl, a0, wth0, wphi0) eigvectors = Tcopy(realve(eigvectors)) a0Hat = cgl.orbit2slice(a0)[0] veHat = cgl.ve2slice(eigvectors, a0) x1, T1, nstp1, th1, phi1, err1 = cqcglReadRPOdi( '../../data/cgl/rpoT2X1.h5', di, 1) h1 = T1 / nstp1 nstp1 = np.int(nstp1) cgl2 = pyCqcgl1d(N, d, h1, False, 0, 4.0, 0.8, 0.01, di, 4) aa1 = cgl2.intg(x1, nstp1, 1) aa1Hat, th2, phi2 = cgl2.orbit2slice(aa1) aa1Hat -= a0Hat h3 = 0.0005 cgl3 = pyCqcgl1d(N, d, h3, False, 0, 4.0, 0.8, 0.01, di, 4) nstp = 70000 a0Erg = a0 + eigvectors[0]*1e-3 aaErg = cgl3.intg(a0Erg, 50000, 50000) a0Erg = aaErg[-1] aaErg = cgl3.intg(a0Erg, nstp, 2) aaErgHat, th3, th3 = cgl3.orbit2slice(aaErg) aaErgHat -= a0Hat # e1, e2 = orthAxes2(veHat[0], veHat[1]) e1, e2, e3 = orthAxes(veHat[0], veHat[1], veHat[6]) aa1HatProj = np.dot(aa1Hat, np.vstack((e1, e2, e3)).T) aaErgHatProj = np.dot(aaErgHat, np.vstack((e1, e2, e3)).T) OProj = np.dot(-a0Hat, np.vstack((e1, e2, e3)).T) fig = plt.figure(figsize=[6, 4]) ax = fig.add_subplot(111, projection='3d') ax.plot(aa1HatProj[:, 0], aa1HatProj[:, 1], aa1HatProj[:, 2], c='r', lw=2) ax.plot(aaErgHatProj[:, 0], aaErgHatProj[:, 1], aaErgHatProj[:, 2], c='g', lw=1, alpha=0.4) i1 = 27500 ax.plot(aaErgHatProj[i1:, 0], aaErgHatProj[i1:, 1], aaErgHatProj[i1:, 2], c='k', lw=1) ax.scatter([0], [0], [0], s=80, marker='o', c='b', edgecolors='none') ax.scatter(OProj[0], OProj[1], OProj[2], s=60, marker='o', c='c', edgecolors='none') ax.set_xlabel(r'$e_1$', fontsize=25) ax.set_ylabel(r'$e_2$', fontsize=25) ax.set_zlabel(r'$e_3$', fontsize=25) fig.tight_layout(pad=0) plt.show(block=False) # plotConfigSurfaceFourier(cgl, aa1, [0, d, 0, T1]) if case == 20: """ plot req and rpo for same Bi, Gi in the full and symmetry-reduced state space """ N, d = 1024, 50 sysFlag = 1 Bi, Gi = 2, -5 cgl = pyCQCGL1d(N, d, -0.1, 0.125, 0.5, 1, Bi, -0.1, Gi, -1) req, cp = CQCGLreq(cgl), CQCGLplot(cgl) a0, wth, wphi, err = req.read('../../data/cgl/reqBiGiEV.h5', req.toStr(Bi, Gi, 1)) OrbitEq = cgl.intg(a0, 0.001, 2, 2) OrbitEqH = cgl.orbit2slice(OrbitEq, sysFlag)[0] Bi, Gi = 4.8, -4.5 cgl = pyCQCGL1d(N, d, -0.1, 0.125, 0.5, 1, Bi, -0.1, Gi, -1) rpo, cp = CQCGLrpo(cgl), CQCGLplot(cgl) x, T, nstp, th, phi, err = rpo.read('../../data/cgl/rpoBiGi.h5', rpo.toStr(Bi, Gi, 1)) po = cgl.intgC(x[:cgl.Ndim], T/nstp, T, 2) poH = cgl.orbit2slice(po, sysFlag)[0] fig, ax = pl2d(size=[6.5, 6], labs=[r'$b_2$', r'$c_2$'], axisLabelSize=30, tickSize=20) ax.plot(OrbitEq[:, 4], OrbitEq[:, 5], ls='-', lw=2, c='r') ax.plot(po[:, 4], po[:, 5], ls='-', lw=2, c='b') ax.set_xticks(ax.get_xticks()[::2]) ax.set_yticks(ax.get_yticks()[::2]) ax2d(fig, ax) fig, ax = pl2d(size=[6.5, 6], labs=[r'$\hat{b}_2$', r'$\hat{c}_2$'], axisLabelSize=30, tickSize=20) ax.scatter(OrbitEqH[0, 4], OrbitEqH[0, 5], s=100, edgecolors='none', marker='o', c='r') ax.plot(poH[:, 4], poH[:, 5], ls='-', lw=2, c='b') ax.set_xlim(25, 55) ax.set_xticks(ax.get_xticks()[::2]) ax.set_yticks(ax.get_yticks()[::2]) ax2d(fig, ax) """ fig, ax = pl3d(size=[8, 6]) ax.plot(poH[:, -1], poH[:, 4], poH[:, 5], c='r', lw=2) ax.plot(aaH[:, -1], aaH[:, 4], aaH[:, 5], c='b', lw=1, alpha=0.7) #ax.plot(poHP[:, 0], poHP[:, 1], poHP[:, 2], c='r', lw=2) #ax.plot(aaHP[:, 0], aaHP[:, 1], aaHP[:, 2], c='b', lw=1) ax3d(fig, ax) """ <file_sep>from py_CQCGL1d import * from py_CQCGL1dEIDc import * from cglHelp import * import matplotlib.gridspec as gridspec case = 150 if case == 10: """ plot the Bi - Gi req stability plot using the saved date from running viewReq.py data format : {Gi, Bi, #unstable} #unstalbe is 0, 2, 4, 6 ... """ saveData = np.loadtxt("BiGiReqStab.dat") cs = {0: 'c', 1: 'm', 2: 'g', 4: 'r', 6: 'b'}#, 8: 'y', 56: 'r', 14: 'grey'} ms = {0: '^', 1: '^', 2: 'x', 4: 'o', 6: 'D'}#, 8: '8', 56: '4', 14: 'v'} fig, ax = pl2d(size=[8, 6], labs=[r'$\gamma_i$', r'$\beta_i$'], axisLabelSize=30, tickSize=20, xlim=[-6, 0], ylim=[-4, 6]) for item in saveData: Gi, Bi, m = item ax.scatter(Gi, Bi, s=18 if m > 0 else 18, edgecolors='none', marker=ms.get(m, 'v'), c=cs.get(m, 'k')) # ax.grid(which='both') ax2d(fig, ax) if case == 15: """ same as case 10, bu plot contourf plot Note: the problem of contourf() is that whenever there is a jump in the levels, say from lv1 to lv2 but lv2 = lv1 + 2, then it will interpolate these two levels, thus a line for lv1 + 1 is plotted between these two regions. I need to draw each region indivisually. """ saveData = np.loadtxt("BiGiReqStab.dat") BiRange = [-3.2, 4] GiRange = [-5.6, -0.9] inc = 0.1 nx = np.int(np.rint( (BiRange[1] - BiRange[0])/inc ) + 1) ny = np.int(np.rint( (GiRange[1] - GiRange[0])/inc ) + 1) x = np.linspace(BiRange[0], BiRange[1], nx) y = np.linspace(GiRange[0], GiRange[1], ny) X, Y = np.meshgrid(x, y) Z = np.zeros([ny, nx]) - 1 # initialized with -1 for item in saveData: Gi, Bi, m = item idx = np.int(np.rint((Bi - BiRange[0]) / inc)) idy = np.int(np.rint((Gi - GiRange[0]) / inc)) if idx >= 0 and idx < nx and idy >= 0 and idy < ny: Z[idy, idx] = m if m < 8 else 8 levels = [-1, 0, 2, 4, 6, 8] cs = ['w', 'm', 'c', 'grey', 'r', 'y'] fig, ax = pl2d(size=[8, 6], labs=[r'$\beta_i$', r'$\gamma_i$'], axisLabelSize=30, tickSize=20) for i in range(len(levels)): vfunc = np.vectorize(lambda t : 0 if t == levels[i] else 1) Z2 = vfunc(Z) ax.contourf(X, Y, Z2, levels=[-0.1, 0.9], colors=cs[i]) ax.text(0, -2, r'$S$', fontsize=30) ax.text(0, -4.5, r'$U_1$', fontsize=30) ax.text(1.8, -2.5, r'$U_2$', fontsize=30) ax.text(2., -4.8, r'$U_3$', fontsize=30) ax.text(3., -3, r'$U_{\geq 4}$', fontsize=30) ax.scatter(2.0,-5, c='k', s=100, edgecolor='none') ax.scatter(2.7,-5, c='k', s=100, edgecolor='none') ax.scatter(1.4,-3.9, c='k', marker='*', s=200, edgecolor='none') ax.set_xlim(BiRange) ax.set_ylim(GiRange) ax2d(fig, ax) if case == 20: """ use L = 50 to view the rpo, its unstable manifold and the difference plot """ N, d = 1024, 50 params = [[4.6, -5.0], [4.8, -4.5]] intgOfT = [19, 7] baseT = [[0, 4], [0, 4]] WuT = [[12, 19], [2, 7]] difT = [[7, 16], [0, 6]] skipRate = 10 fig = plt.figure(figsize=[8, 7]) for i in range(2): Bi, Gi = params[i] cgl = pyCQCGL1d(N, d, -0.1, 0.125, 0.5, 1, Bi, -0.1, Gi, -1) rpo, cp = CQCGLrpo(cgl), CQCGLplot(cgl) x, T, nstp, th, phi, err, e, v = rpo.read('../../data/cgl/rpoBiGiEV.h5', rpo.toStr(Bi, Gi, 1), flag=2) a0 = x[:cgl.Ndim] print e[:10] aa0 = cgl.intg(a0, T/nstp, nstp, 10)[:-1] a0 += 0.1*norm(a0)*v[0] aaBase = aa0 for k in range(1, intgOfT[i]): aaBase = np.vstack((aaBase, cgl.Rotate(aa0, -k*th, -k*phi))) aa = cgl.intg(a0, T/nstp, intgOfT[i]*nstp, skipRate) dif = aa[:-1] - aaBase cellSize = nstp / skipRate # cp.config(dif, [0, d, 0*T, 6*T]) aaBase = aaBase[baseT[i][0]*cellSize : baseT[i][1]*cellSize] aa = aa[WuT[i][0]*cellSize : WuT[i][1]*cellSize] dif = dif[difT[i][0]*cellSize : difT[i][1]*cellSize] states = [aaBase, aa, dif] for j in range(3): ax = fig.add_subplot('23' + str(3*i+j+1)) ax.text(0.1, 0.9, '('+ chr(ord('a')+3*i+j) + ')', horizontalalignment='center', transform=ax.transAxes, fontsize=20, color='white') if i == 1: ax.set_xlabel(r'$x$', fontsize=25) if j == 0: ax.set_ylabel(r'$t$', fontsize=25) if i == 0: ax.set_xticklabels([]) ax.tick_params(axis='both', which='major', labelsize=12) if j == 0: extent = [0, d, baseT[i][0]*T, baseT[i][1]*T] elif j == 1: extent = [0, d, WuT[i][0]*T, WuT[i][1]*T] else: extent = [0, d, difT[i][0]*T, difT[i][1]*T] im = ax.imshow(np.abs(cgl.Fourier2Config(states[j])), cmap=plt.get_cmap('jet'), extent=extent, aspect='auto', origin='lower') ax.grid('on') dr = make_axes_locatable(ax) cax =dr.append_axes('right', size='5%', pad=0.05) plt.colorbar(im, cax=cax, ticks=[0, 1, 2, 3]) fig.tight_layout(pad=0) plt.show(block=False) if case == 30: """ view the leading FV of two rpo. The leading FV of these two rpo are real, so there is no need to special transformation """ N, d = 1024 , 50 params = [[4.6, -5.0], [4.8, -4.5]] fig = plt.figure(figsize=[8, 4]) for i in range(2): Bi, Gi = params[i] cgl = pyCQCGL1d(N, d, -0.1, 0.125, 0.5, 1, Bi, -0.1, Gi, -1) rpo, cp = CQCGLrpo(cgl), CQCGLplot(cgl) x, T, nstp, th, phi, err, e, v = rpo.read('../../data/cgl/rpoBiGiEV.h5', rpo.toStr(Bi, Gi, 1), flag=2) ax = fig.add_subplot('12' + str(i+1)) ax.text(0.1, 0.9, '('+ chr(ord('a')+i) + ')', horizontalalignment='center', transform=ax.transAxes, fontsize=20) ax.set_xlabel(r'$x$', fontsize=30) # ax.set_ylabel(r'$|v_1|$', fontsize=20) ax.tick_params(axis='both', which='major', labelsize=13) Aamp = np.abs(cgl.Fourier2Config(v[0])) ax.plot(np.linspace(0, d, Aamp.shape[0]), Aamp.shape[0]*Aamp, lw=1.5) fig.tight_layout(pad=0) plt.show(block=False) if case == 35: """ Similar to case = 30, but for rpo(4.6, -5.0), we plot all its unstable Floquet vectors. """ N, d = 1024 , 50 vs = [] Bi, Gi = 4.6, -5.0 cgl = pyCQCGL1d(N, d, -0.1, 0.125, 0.5, 1, Bi, -0.1, Gi, -1) rpo, cp = CQCGLrpo(cgl), CQCGLplot(cgl) x, T, nstp, th, phi, err, e, v = rpo.read('../../data/cgl/rpoBiGiEV.h5', rpo.toStr(Bi, Gi, 1), flag=2) for i in range(3): vs.append(v[i]) # do not need to define another instance of cgl Bi, Gi = 4.8, -4.5 x, T, nstp, th, phi, err, e, v = rpo.read('../../data/cgl/rpoBiGiEV.h5', rpo.toStr(Bi, Gi, 1), flag=2) vs.insert(1, v[0]) fig = plt.figure(figsize=[8, 7]) for i in range(4): ax = fig.add_subplot('22' + str(i+1)) ax.text(0.1, 0.9, '('+ chr(ord('a')+i) + ')', horizontalalignment='center', transform=ax.transAxes, fontsize=20) if i > 1: ax.set_xlabel(r'$x$', fontsize=30) # ax.set_ylabel(r'$|v_1|$', fontsize=20) ax.tick_params(axis='both', which='major', labelsize=13) Aamp = np.abs(cgl.Fourier2Config(vs[i])) ax.plot(np.linspace(0, d, Aamp.shape[0]), Aamp.shape[0]*Aamp, lw=1.5) fig.tight_layout(pad=0) plt.show(block=False) if case == 40: """ use L = 50 to view the one req and one rpo int the symmetry reduced state space """ N, d = 1024 , 50 h = 2e-3 sysFlag = 1 fig = plt.figure(figsize=[8, 8]) nx, ny = 16, 4 gs = gridspec.GridSpec(nx, ny) # req Bi, Gi = 2, -2 cgl = pyCQCGL1d(N, d, -0.1, 0.125, 0.5, 1, Bi, -0.1, Gi, -1) EI = pyCQCGL1dEIDc(N, d, -0.1, 0.125, 0.5, 1, Bi, -0.1, Gi) req, cp = CQCGLreq(cgl), CQCGLplot(cgl) a0, wth0, wphi0, err0, e, v = req.read('../../data/cgl/reqBiGiEV.h5', req.toStr(Bi, Gi, 1), flag=2) a0H = cgl.orbit2slice(a0, sysFlag)[0] aE = a0 + 0.001 * norm(a0) * v[0].real T = 50 aa = EI.intg(aE, h, T, 10) aaH = cgl.orbit2slice(aa, sysFlag)[0] ax = fig.add_subplot(gs[:nx/2-1, 0]) ax.text(0.9, 0.9, '(a)', horizontalalignment='center', transform=ax.transAxes, fontsize=20, color='white') ax.set_xlabel(r'$x$', fontsize=20) ax.set_ylabel(r'$t$', fontsize=20) ax.tick_params(axis='both', which='major', labelsize=12) aaTime = aa[cp.sliceTime(EI.Ts()), :] im = ax.imshow(np.abs(cgl.Fourier2Config(aaTime)), cmap=plt.get_cmap('jet'), extent=[0, d, 0, T], aspect='auto', origin='lower') ax.grid('on') dr = make_axes_locatable(ax) cax =dr.append_axes('right', size='5%', pad=0.05) plt.colorbar(im, cax=cax, ticks=[0, 1, 2, 3]) ax = fig.add_subplot(gs[:nx/2, 1:], projection='3d') ax.text2D(0.1, 0.9, '(b)', horizontalalignment='center', transform=ax.transAxes, fontsize=20) ax.set_xlabel(r'$Re(a_0)$', fontsize=18) ax.set_ylabel(r'$Re(a_2)$', fontsize=18) ax.set_zlabel(r'$Im(a_2)$', fontsize=18) # ax.set_xlim([-20, 20]) # ax.set_ylim([0, 250]) # ax.set_zlim([-30, 30]) ax.locator_params(nbins=4) ax.scatter(a0H[0], a0H[4], a0H[5], c='r', s=100, edgecolor='none') ax.plot(aaH[:, 0], aaH[:, 4], aaH[:, 5], c='b', lw=1, alpha=0.5) # rpo Bi, Gi = 4.8, -4.5 cgl = pyCQCGL1d(N, d, -0.1, 0.125, 0.5, 1, Bi, -0.1, Gi, -1) EI = pyCQCGL1dEIDc(N, d, -0.1, 0.125, 0.5, 1, Bi, -0.1, Gi) rpo, cp = CQCGLrpo(cgl), CQCGLplot(cgl) x, T, nstp, th, phi, err, e, v = rpo.read('../../data/cgl/rpoBiGiEV.h5', rpo.toStr(Bi, Gi, 1), flag=2) a0 = x[:cgl.Ndim] po = EI.intg(a0, T/nstp, T, 1) poH = cgl.orbit2slice(po, sysFlag)[0] aE = a0 + 0.001 * norm(a0) * v[0]; aa = EI.intg(aE, T/nstp, 16*T, 1) aaH, ths, phis = cgl.orbit2slice(aa, sysFlag) ax = fig.add_subplot(gs[nx/2:nx-1, 0]) ax.text(0.9, 0.9, '(c)', horizontalalignment='center', transform=ax.transAxes, fontsize=20, color='white') ax.set_xlabel(r'$x$', fontsize=20) ax.set_ylabel(r'$t$', fontsize=20) ax.tick_params(axis='both', which='major', labelsize=12) aaTime = aa[cp.sliceTime(EI.Ts()), :] im = ax.imshow(np.abs(cgl.Fourier2Config(aaTime)), cmap=plt.get_cmap('jet'), extent=[0, d, 0, 16*T], aspect='auto', origin='lower') ax.grid('on') dr = make_axes_locatable(ax) cax =dr.append_axes('right', size='5%', pad=0.05) plt.colorbar(im, cax=cax, ticks=[0, 1, 2, 3]) ax = fig.add_subplot(gs[nx/2:, 1:], projection='3d') ax.text2D(0.1, 0.9, '(d)', horizontalalignment='center', transform=ax.transAxes, fontsize=20) ax.set_xlabel(r'$Re(a_{0})$', fontsize=18) ax.set_ylabel(r'$Re(a_{2})$', fontsize=18) ax.set_zlabel(r'$Im(a_{2})$', fontsize=18) # ax.set_ylim([-50, 200]) ax.locator_params(nbins=4) ax.plot(poH[:, 0], poH[:, 4], poH[:, 5], c='r', lw=2) ax.plot(aaH[:, 0], aaH[:, 4], aaH[:, 5], c='b', lw=1, alpha=0.5) fig.tight_layout(pad=0) plt.show(block=False) if case == 50: """ plot one req explosion and its symmetry reduced plots use it to test case = 40 """ N, d = 1024, 50 h = 2e-3 sysFlag = 1 Bi, Gi = 2, -2 cgl = pyCQCGL1d(N, d, -0.1, 0.125, 0.5, 1, Bi, -0.1, Gi, 0) EI = pyCQCGL1dEIDc(N, d, -0.1, 0.125, 0.5, 1, Bi, -0.1, Gi) req, cp = CQCGLreq(cgl), CQCGLplot(cgl) a0, wth0, wphi0, err0, e, v = req.read('../../data/cgl/reqBiGiEV.h5', req.toStr(Bi, Gi, 1), flag=2) # get the bases vt = np.vstack([v[0].real, v[0].imag, v[6].real]) vRed = cgl.ve2slice(vt, a0, sysFlag) Q = orthAxes(vRed[0], vRed[1], vRed[2]) a0H = cgl.orbit2slice(a0, sysFlag)[0] a0P = a0H.dot(Q) aE = a0 + 0.001 * norm(a0) * v[0].real T = 50 aa = EI.intg(aE, h, T, 2) aaH = cgl.orbit2slice(aa, sysFlag)[0] aaP = aaH.dot(Q) - a0P fig, ax = pl3d(size=[8, 6], labs=[r'$v_1$', r'$v_2$', r'$v_3$'], axisLabelSize=20, tickSize=20) ax.scatter(0, 0, 0, c='k', s=100, edgecolors='none') id1 = bisect_left(EI.Ts(), 24) ax.plot(aaP[id1/2:id1, 0], aaP[id1/2:id1, 1], aaP[id1/2:id1, 2], c='m', lw=1, alpha=0.5) id2 = bisect_left(EI.Ts(), 33) ax.plot(aaP[id2:, 0], aaP[id2:, 1], aaP[id2:, 2], c='b', lw=1, alpha=0.6) ax3d(fig, ax) if case == 55: """ plot one rpo explosion and its symmetry reduced plots use it to test case = 40 """ N, d = 1024, 50 h = 2e-3 sysFlag = 1 Bi, Gi = 4.8, -4.5 cgl = pyCQCGL1d(N, d, -0.1, 0.125, 0.5, 1, Bi, -0.1, Gi, 0) EI = pyCQCGL1dEIDc(N, d, -0.1, 0.125, 0.5, 1, Bi, -0.1, Gi) rpo, cp = CQCGLrpo(cgl), CQCGLplot(cgl) x, T, nstp, th, phi, err, e, v = rpo.read('../../data/cgl/rpoBiGiEV.h5', rpo.toStr(Bi, Gi, 1), flag=2) a0 = x[:cgl.Ndim] # get the bases vt = np.vstack([v[0], v[1], v[3]]) vRed = cgl.ve2slice(vt, a0, sysFlag) Q = orthAxes(vRed[0], vRed[1], vRed[2]) a0H = cgl.orbit2slice(a0, sysFlag)[0] a0P = a0H.dot(Q) po = EI.intg(a0, T/nstp, T, 1) poH = cgl.orbit2slice(po, sysFlag)[0] poP = poH.dot(Q) - a0P aE = a0 + 0.001 * norm(a0) * v[0]; aa = EI.intg(aE, T/nstp, 16*T, 2) aaH = cgl.orbit2slice(aa, sysFlag)[0] aaP = aaH.dot(Q) - a0P fig, ax = pl3d(size=[8, 6], labs=[r'$v_1$', r'$v_2$', r'$v_3$'], axisLabelSize=20, tickSize=20) ax.scatter(0, 0, 0, c='k', s=100, edgecolors='none') ax.plot(poP[:, 0], poP[:, 1], poP[:, 2], c='r', lw=2) id1 = bisect_left(EI.Ts(), 23) ax.plot(aaP[id1/2:id1, 0], aaP[id1/2:id1, 1], aaP[id1/2:id1, 2], c='m', lw=1, alpha=0.5) id2 = bisect_left(EI.Ts(), 35) ax.plot(aaP[id2:, 0], aaP[id2:, 1], aaP[id2:, 2], c='b', lw=1, alpha=0.6) ax3d(fig, ax) if case == 60: """ plot the stability table of the rpos """ N, d = 1024, 50 fileName = '../../data/cgl/rpoBiGiEV.h5' cs = {0: 'g'}#, 10: 'm', 2: 'c', 4: 'r', 6: 'b', 8: 'y'}#, 56: 'r', 14: 'grey'} ms = {0: 's'}#, 10: '^', 2: '+', 4: 'o', 6: 'D', 8: 'v'}#, 56: '4', 14: 'v'} fig, ax = pl2d(size=[8, 6], labs=[r'$\beta_i$', r'$\gamma_i$'], axisLabelSize=30, tickSize=20, ylim=[-5.65, -3.95], xlim=[1.8, 5.8]) for i in range(39): Bi = 1.9 + i*0.1 for j in range(55): Gi = -5.6 + 0.1*j rpo = CQCGLrpo() if rpo.checkExist(fileName, rpo.toStr(Bi, Gi, 1) + '/er'): x, T, nstp, th, phi, err, e, v = rpo.read(fileName, rpo.toStr(Bi, Gi, 1), flag=2) m, ep, accu = numStab(e, nmarg=3, tol=1e-4, flag=1) ax.scatter(Bi, Gi, s=60, edgecolors='none', marker=ms.get(m, 'o'), c=cs.get(m, 'r')) #ax.xaxis.set_minor_locator(AutoMinorLocator(10)) #ax.yaxis.set_minor_locator(AutoMinorLocator(10)) #ax.grid(which='major', linewidth=2) #ax.grid(which='minor', linewidth=1) ax2d(fig, ax) if case == 70: """ plot one Hopf bifurcation subplot (a) : heat map of the limit cycle subplot (b) : symmetry-reduced state space figure """ N, d = 1024, 50 h = 2e-3 sysFlag = 1 Bi, Gi = 1.4, -3.9 index = 1 cgl = pyCQCGL1d(N, d, -0.1, 0.125, 0.5, 1, Bi, -0.1, Gi, 0) req = CQCGLreq(cgl) rpo = CQCGLrpo(cgl) cp = CQCGLplot(cgl) # obtain unstable manifold of req a0, wth0, wphi0, err0, e, v = req.read('../../data/cgl/reqBiGiEV.h5', req.toStr(Bi, Gi, index), flag=2) # get the bases vt = np.vstack([v[0].real, v[0].imag, v[4].real]) vRed = cgl.ve2slice(vt, a0, sysFlag) Q = orthAxes(vRed[0], vRed[1], vRed[2]) a0H = cgl.orbit2slice(a0, sysFlag)[0] a0P = a0H.dot(Q) aE = a0 + 0.1*norm(a0)*v[0].real T = 800 aa = cgl.intg(aE, h, np.int(100/h), 100000) aE = aa[-1] aa = cgl.intg(aE, h, np.int(T/h), 50) aaH = cgl.orbit2slice(aa, sysFlag)[0] aaP = aaH.dot(Q) - a0P # obtain limit cycle x, T, nstp, th, phi, err = rpo.read('../../data/cgl/rpoHopfBiGi.h5', rpo.toStr(Bi, Gi, 1)) ap0 = x[:-3] hp = T / nstp aap = cgl.intg(ap0, hp, nstp, 10) aapH = cgl.orbit2slice(aap, sysFlag)[0] aapP = aapH.dot(Q) - a0P aap4 = aap for k in range(1, 4): aap4 = np.vstack((aap4, cgl.Rotate(aap, -k*th, -k*phi))) # plot figure fig = plt.figure(figsize=[8, 4]) nx, ny = 8, 4 gs = gridspec.GridSpec(nx, ny) ax = fig.add_subplot(gs[:nx-1, 0]) ax.text(0.1, 0.9, '(a)', horizontalalignment='center', transform=ax.transAxes, fontsize=18, color='white') ax.set_xlabel(r'$x$', fontsize=25) ax.set_ylabel(r'$t$', fontsize=25) ax.tick_params(axis='both', which='major', labelsize=12) im = ax.imshow(np.abs(cgl.Fourier2Config(aap4)), cmap=plt.get_cmap('jet'), extent=[0, d, 0, 4*T], aspect='auto', origin='lower') ax.grid('on') dr = make_axes_locatable(ax) cax =dr.append_axes('right', size='5%', pad=0.05) plt.colorbar(im, cax=cax, ticks=[0, 1, 2, 3]) ax = fig.add_subplot(gs[:, 1:], projection='3d') ax.text2D(0.1, 0.9, '(b)', horizontalalignment='center', transform=ax.transAxes, fontsize=18) ax.set_xlabel(r'$v_1$', fontsize=25) ax.set_ylabel(r'$v_2$', fontsize=25) ax.set_zlabel(r'$v_3$', fontsize=25) # ax.set_xlim([-20, 20]) # ax.set_ylim([0, 250]) # ax.set_zlim([-30, 30]) ax.locator_params(nbins=4) # ax.scatter(a0H[], a0H[4], a0H[5], c='r', s=40) # ax.plot(aaH[:, -1], aaH[:, 4], aaH[:, 5], c='b', lw=1, alpha=0.7) # ax.plot(aapH[:, -1], aapH[:, 4], aapH[:, 5], c='r', lw=2) ax.scatter(0, 0, 0, c='r', s=40) ax.plot(aaP[:, 0], aaP[:, 1], aaP[:, 2], c='b', lw=1, alpha=0.7) ax.plot(aapP[:, 0], aapP[:, 1], aapP[:, 2], c='r', lw=2) fig.tight_layout(pad=0) plt.show(block=False) if case == 75: """ same as case 70 but only save the data """ N, d = 1024, 50 h = 2e-3 sysFlag = 1 Bi, Gi = 1.4, -3.9 index = 1 cgl = pyCQCGL1d(N, d, -0.1, 0.125, 0.5, 1, Bi, -0.1, Gi, 0) req = CQCGLreq(cgl) rpo = CQCGLrpo(cgl) cp = CQCGLplot(cgl) # obtain unstable manifold of req a0, wth0, wphi0, err0, e, v = req.read('../../data/cgl/reqBiGiEV.h5', req.toStr(Bi, Gi, index), flag=2) # get the bases vt = np.vstack([v[0].real, v[0].imag, v[4].real]) vRed = cgl.ve2slice(vt, a0, sysFlag) Q = orthAxes(vRed[0], vRed[1], vRed[2]) a0H = cgl.orbit2slice(a0, sysFlag)[0] a0P = a0H.dot(Q) aE = a0 + 0.1*norm(a0)*v[0].real T = 800 aa = cgl.intgC(aE, h, 100, 100000) aE = aa[-1] if aa.ndim == 2 else aa aa = cgl.intgC(aE, h, T, 50) aaH = cgl.orbit2slice(aa, sysFlag)[0] aaP = aaH.dot(Q) - a0P # obtain limit cycle x, T, nstp, th, phi, err = rpo.read('../../data/cgl/rpoHopfBiGi.h5', rpo.toStr(Bi, Gi, 1)) ap0 = x[:-3] hp = T / nstp aap = cgl.intgC(ap0, hp, T, 10) aapH = cgl.orbit2slice(aap, sysFlag)[0] aapP = aapH.dot(Q) - a0P aap4 = aap for k in range(1, 4): aap4 = np.vstack((aap4, cgl.Rotate(aap, -k*th, -k*phi))) # save the data hopfCycleProfiles4Periods = np.abs(cgl.Fourier2Config(aap4)) np.savez_compressed('hopfCycleAndWuOfReq', hopfCycleProfiles4Periods=hopfCycleProfiles4Periods, T=T, aaP=aaP, aapP=aapP) if case == 80: """ new size L = 50 plot the plane soliton and composite soliton in the same figure. """ N, d = 1024, 50 fig, ax = pl2d(size=[8, 6], labs=[r'$x$', r'$|A|$'], axisLabelSize=30, tickSize=20) Bi, Gi = 2.0, -5 cgl = pyCQCGL1d(N, d, -0.1, 0.125, 0.5, 1, Bi, -0.1, Gi, 0) req = CQCGLreq(cgl) a0, wth0, wphi0, err0 = req.read('../../data/cgl/reqBiGiEV.h5', req.toStr(Bi, Gi, 1), flag=0) Aamp = np.abs(cgl.Fourier2Config(a0)) ax.plot(np.linspace(0, d, Aamp.shape[0]), Aamp, lw=2, ls='-', c='k') Bi, Gi = 2.7, -5 cgl = pyCQCGL1d(N, d, -0.1, 0.125, 0.5, 1, Bi, -0.1, Gi, 0) req = CQCGLreq(cgl) a0, wth0, wphi0, err0 = req.read('../../data/cgl/reqBiGiEV.h5', req.toStr(Bi, Gi, 1), flag=0) Aamp = np.abs(cgl.Fourier2Config(a0)) ax.plot(np.linspace(0, d, Aamp.shape[0]), Aamp, lw=2, ls='--', c='k') ax2d(fig, ax) if case == 90: """ save the data for the two coexsting solitons for the same parameter """ N, d = 1024, 50 Bi, Gi = 0.8, -0.6 cgl = pyCQCGL1d(N, d, -0.1, 0.125, 0.5, 1, Bi, -0.1, Gi, 0) req = CQCGLreq(cgl) a1, wth0, wphi0, err0 = req.read('../../data/cgl/reqBiGiEV.h5', req.toStr(Bi, Gi, 1), flag=0) a2, wth0, wphi0, err0 = req.read('../../data/cgl/reqBiGiEV.h5', req.toStr(Bi, Gi, 2), flag=0) absA1 = np.abs(cgl.Fourier2Config(a1)) absA2 = np.abs(cgl.Fourier2Config(a2)) np.savez_compressed('solitonProfileFor08n06', absA1=absA1, absA2=absA2) if case == 100: """ same as case = 40. but in two different plots """ N, d = 1024 , 50 h = 2e-3 sysFlag = 1 fig = plt.figure(figsize=[8, 4]) nx, ny = 8, 4 gs = gridspec.GridSpec(nx, ny) # req Bi, Gi = 2, -2 cgl = pyCQCGL1d(N, d, -0.1, 0.125, 0.5, 1, Bi, -0.1, Gi, 0) req, cp = CQCGLreq(cgl), CQCGLplot(cgl) a0, wth0, wphi0, err0, e, v = req.readReqBiGi('../../data/cgl/reqBiGiEV.h5', Bi, Gi, 1, flag=2) a0H = cgl.orbit2slice(a0, sysFlag)[0] aE = a0 + 0.001 * norm(a0) * v[0].real T = 50 aa = cgl.intg(aE, h, np.int(T/h), 1) # cp.config(aa, [0, d, 0, T]) aaH, ths, phis = cgl.orbit2slice(aa, sysFlag) ax = fig.add_subplot(gs[:nx-1, 0]) ax.text(0.1, 0.9, '(a)', horizontalalignment='center', transform=ax.transAxes, fontsize=18, color='white') ax.set_xlabel(r'$x$', fontsize=16) ax.set_ylabel(r'$t$', fontsize=16) ax.tick_params(axis='both', which='major', labelsize=12) im = ax.imshow(np.abs(cgl.Fourier2Config(aa)), cmap=plt.get_cmap('jet'), extent=[0, d, 0, T], aspect='auto', origin='lower') ax.grid('on') dr = make_axes_locatable(ax) cax =dr.append_axes('right', size='5%', pad=0.05) plt.colorbar(im, cax=cax, ticks=[0, 1, 2, 3]) ax = fig.add_subplot(gs[:, 1:], projection='3d') ax.text2D(0.1, 0.9, '(b)', horizontalalignment='center', transform=ax.transAxes, fontsize=18) ax.set_xlabel(r'$Re(a_{-1})$', fontsize=16) ax.set_ylabel(r'$Re(a_{2})$', fontsize=16) ax.set_zlabel(r'$Im(a_{2})$', fontsize=16) ax.set_xlim([-20, 20]) ax.set_ylim([0, 250]) ax.set_zlim([-30, 30]) ax.locator_params(nbins=4) ax.scatter(a0H[-1], a0H[4], a0H[5], c='r', s=40) ax.plot(aaH[:, -1], aaH[:, 4], aaH[:, 5], c='b', lw=1, alpha=0.7) fig.tight_layout(pad=0) plt.show(block=False) fig = plt.figure(figsize=[8, 4]) nx, ny = 8, 4 gs = gridspec.GridSpec(nx, ny) # rpo Bi, Gi = 4.8, -4.5 cgl = pyCQCGL1d(N, d, -0.1, 0.125, 0.5, 1, Bi, -0.1, Gi, -1) rpo, cp = CQCGLrpo(cgl), CQCGLplot(cgl) x, T, nstp, th, phi, err, e, v = rpo.readRpoBiGi('../../data/cgl/rpoBiGiEV.h5', Bi, Gi, 1, flag=2) a0 = x[:cgl.Ndim] po = cgl.intg(a0, T/nstp, nstp, 10) poH = cgl.orbit2slice(po, sysFlag)[0] aE = a0 + 0.001 * norm(a0) * v[0]; aa = cgl.intg(aE, T/nstp, 20*nstp, 1) # cp.config(aa, [0, d, 0, 20*T]) aaH, ths, phis = cgl.orbit2slice(aa, sysFlag) ax = fig.add_subplot(gs[:nx-1, 0]) ax.text(0.1, 0.9, '(a)', horizontalalignment='center', transform=ax.transAxes, fontsize=18, color='white') ax.set_xlabel(r'$x$', fontsize=16) ax.set_ylabel(r'$t$', fontsize=16) ax.tick_params(axis='both', which='major', labelsize=12) im = ax.imshow(np.abs(cgl.Fourier2Config(aa)), cmap=plt.get_cmap('jet'), extent=[0, d, 0, 20*T], aspect='auto', origin='lower') ax.grid('on') dr = make_axes_locatable(ax) cax =dr.append_axes('right', size='5%', pad=0.05) plt.colorbar(im, cax=cax, ticks=[0, 1, 2, 3]) ax = fig.add_subplot(gs[:, 1:], projection='3d') ax.text2D(0.1, 0.9, '(b)', horizontalalignment='center', transform=ax.transAxes, fontsize=18) ax.set_xlabel(r'$Re(a_{-1})$', fontsize=16) ax.set_ylabel(r'$Re(a_{2})$', fontsize=16) ax.set_zlabel(r'$Im(a_{2})$', fontsize=16) # ax.set_ylim([-50, 200]) ax.locator_params(nbins=4) ax.plot(poH[:, -1], poH[:, 4], poH[:, 5], c='r', lw=2) ax.plot(aaH[:, -1], aaH[:, 4], aaH[:, 5], c='b', lw=1, alpha=0.7) # fig, ax = pl3d(size=[8, 6], labs=[r'$Re(a_{-1})$', r'$Re(a_{2})$', r'$Im(a_{2})$'], # axisLabelSize=20, tickSize=20) # ax.plot(poH[:, -1], poH[:, 4], poH[:, 5], c='r', lw=2) # ax.plot(aaH[:, -1], aaH[:, 4], aaH[:, 5], c='b', lw=1, alpha=0.7) # ax3d(fig, ax) fig.tight_layout(pad=0) plt.show(block=False) if case == 150: """ find one representative symmetric and asymmetric explosions save the data """ N, d = 1024 , 50 h = 2e-3 Bi, Gi = 0.8, -0.6 cgl = pyCQCGL1d(N, d, -0.1, 0.125, 0.5, 1, Bi, -0.1, Gi, 0) req, cp = CQCGLreq(cgl), CQCGLplot(cgl) a0, wth0, wphi0, err0, e, v = req.read('../../data/cgl/reqBiGiEV.h5', req.toStr(Bi, Gi, 1), flag=2) aE = a0 + 0.001 * norm(a0) * v[0].real # get rid of transicent aa = cgl.intgC(aE, h, 69, 100000) aE = aa[-1] if aa.ndim == 2 else aa # save symmetric explosion Tsymmetric = 10 aa = cgl.intgC(aE, h, Tsymmetric, 10) AampSymmetric = np.abs(cgl.Fourier2Config(aa)) aE = aa[-1] if aa.ndim == 2 else aa # save asymmetric explosion aa = cgl.intgC(aE, h, 189, 100000) aE = aa[-1] if aa.ndim == 2 else aa Tasymmetric = 10 aa = cgl.intgC(aE, h, Tasymmetric, 10) AampAsymmetric = np.abs(cgl.Fourier2Config(aa)) a0RealAsymmetric = aa[:, 0].real aE = aa[-1] if aa.ndim == 2 else aa np.savez_compressed('explosionExample08n06', AampSymmetric=AampSymmetric, AampAsymmetric=AampAsymmetric, Tsymmetric=Tsymmetric, Tasymmetric=Tasymmetric, a0RealAsymmetric=a0RealAsymmetric) <file_sep>#ifndef CQCGL1dRpo_arpack_H #define CQCGL1dRpo_arpack_H #include "CQCGL1dRpo.hpp" class CQCGL1dRpo_arpack : public CQCGL1dRpo { public: typedef std::complex<double> dcp; //////////////////////////////////////////////////////////// // A_t = Mu A + (Dr + Di*i) A_{xx} + (Br + Bi*i) |A|^2 A + (Gr + Gi*i) |A|^4 A CQCGL1dRpo_arpack(int N, double d, double Mu, double Dr, double Di, double Br, double Bi, double Gr, double Gi, int dimTan); // A_t = -A + (1 + b*i) A_{xx} + (1 + c*i) |A|^2 A - (dr + di*i) |A|^4 A CQCGL1dRpo_arpack(int N, double d, double b, double c, double dr, double di, int dimTan); // iA_z + D A_{tt} + |A|^2 A + \nu |A|^4 A = i \delta A + i \beta A_{tt} + i |A|^2 A + i \mu |A|^4 A CQCGL1dRpo_arpack(int N, double d, double delta, double beta, double D, double epsilon, double mu, double nu, int dimTan); ~CQCGL1dRpo_arpack(); CQCGL1dRpo_arpack & operator=(const CQCGL1dRpo_arpack &x); //////////////////////////////////////////////////////////// std::pair<VectorXcd, MatrixXd> evRpo(const ArrayXd &a0, double h, int nstp, double th, double phi, int ne); void calEVParaSeq(std::string file, std::vector<double> Bis, std::vector<double> Gis, int ne, bool saveV); static std::pair< std::vector<double>, std::vector<double> > getMissIds(std::string file, double Bi0, double Gi0, double incB, double incG, int nB, int nG); }; struct Jdotx { CQCGL1dRpo_arpack *rpo; ArrayXd a0; double h, th, phi; int Nt; Jdotx(CQCGL1dRpo_arpack *rpo, const ArrayXd &a0, double h, int Nt, double th, double phi) : rpo(rpo), a0(a0), h(h), Nt(Nt), th(th), phi(phi){} void mul(double *v, double *w){ int Ndim = rpo->Ndim; Map<const ArrayXd> mv(v, Ndim); Map<ArrayXd> mw(w, Ndim); ArrayXXd tmp = rpo->intgv(a0, mv, h, Nt); mw = rpo->Rotate(tmp.rightCols(1), th, phi); } }; #endif /* CQCGL1dRpo_arpack */ <file_sep>#include <iostream> #include <cstdio> #include <Eigen/Dense> #include <H5Cpp.h> #include "ksFEFV.hpp" #include "myH5.hpp" #include "ksint.hpp" #include "ped.hpp" using namespace std; using namespace Eigen; /** @brief calculate Floquet exponents and Floquet vectors of KS system. * * @param[in] ppType periodic type: ppo/rpo * @param[in] ppId id of the orbit * @param[in] MaxN maximal number of PED iteration * @param[in] tol tolerance of PED * @param[in] nqr spacing * @return FE and FV */ pair<MatrixXd, MatrixXd> KScalFEFV(const string fileName, const string ppType, const int ppId, const int L /* = 22 */, const int MaxN /* = 80000 */, const double tol /* = 1e-15 */, const int nqr /* = 1 */, const int trunc /* = 0 */){ // get the initla condition of the orbit auto tmp = MyH5::KSreadRPO(fileName, ppType, ppId); MatrixXd &a = std::get<0>(tmp); double T = std::get<1>(tmp); int nstp = (int) std::get<2>(tmp); double r = std::get<3>(tmp); double s = std::get<4>(tmp); const int N = a.rows(); const int Nks = N + 2; // solve the Jacobian of this po. KS ks(Nks, L); std::pair<ArrayXXd, ArrayXXd> tmp2 = ks.intgj(a.col(0), T/nstp, nstp, nqr); MatrixXd daa = tmp2.second; daa = daa.rightCols(daa.cols() - daa.rows()).eval(); // calculate the Flqouet exponents and vectors. PED ped; ped.reverseOrder(daa); // reverse order. if(ppType.compare("ppo") == 0) daa.leftCols(N) = ks.reflect(daa.leftCols(N)); // R*J for ppo else // R*J for rpo daa.leftCols(N) = ks.rotate(daa.leftCols(N), -s*2*M_PI/L); pair<MatrixXd, MatrixXd> eigv = ped.EigVecs(daa, MaxN, tol, false, trunc); MatrixXd &eigvals = eigv.first; eigvals.col(0) = eigvals.col(0).array()/T; MatrixXd &eigvecs = eigv.second; return make_pair(eigvals, eigvecs); } /** @brief calculate Floquet exponents of KS system. * * @param[in] ppType periodic type: ppo/rpo * @param[in] ppId id of the orbit * @param[in] MaxN maximal number of PED iteration * @param[in] tol tolerance of PED * @param[in] nqr spacing * @return FE and FV */ MatrixXd KScalFE(const string fileName, const string ppType, const int ppId, const int L /* = 22 */, const int MaxN /* = 80000 */, const double tol /* = 1e-15 */, const int nqr /* = 1 */){ // get the initla condition of the orbit auto tmp = MyH5::KSreadRPO(fileName, ppType, ppId); MatrixXd &a = std::get<0>(tmp); double T = std::get<1>(tmp); int nstp = (int) std::get<2>(tmp); double r = std::get<3>(tmp); double s = std::get<4>(tmp); const int N = a.rows(); const int Nks = N + 2; // solve the Jacobian of this po. KS ks(Nks, L); pair<ArrayXXd, ArrayXXd> tmp2 = ks.intgj(a.col(0), T/nstp, nstp, nqr); MatrixXd daa = tmp2.second; daa = daa.rightCols(daa.cols() - daa.rows()).eval(); // calculate the Flqouet exponents and vectors. PED ped; ped.reverseOrder(daa); // reverse order. if(ppType.compare("ppo") == 0) daa.leftCols(N) = ks.reflect(daa.leftCols(N)); // R*J for ppo else // R*J for rpo daa.leftCols(N) = ks.rotate(daa.leftCols(N), -s*2*M_PI/L); MatrixXd eigvals = ped.EigVals(daa, MaxN, tol, false); eigvals.col(0) = eigvals.col(0).array()/T; return eigvals; } MatrixXd KSgetR(const string fileName, const string ppType, const int ppId, const int L /* = 22 */, const int MaxN /* = 80000 */, const double tol /* = 1e-15 */, const int nqr /* = 1 */){ auto tmp = MyH5::KSreadRPO(fileName, ppType, ppId); MatrixXd &a = std::get<0>(tmp); double T = std::get<1>(tmp); int nstp = (int) std::get<2>(tmp); double r = std::get<3>(tmp); double s = std::get<4>(tmp); const int N = a.rows(); const int Nks = N + 2; // solve the Jacobian of this po. KS ks(Nks, L); pair<ArrayXXd, ArrayXXd> tmp2 = ks.intgj(a.col(0), T/nstp, nstp, nqr); MatrixXd daa = tmp2.second; daa = daa.rightCols(daa.cols() - daa.rows()).eval(); // calculate the Flqouet exponents and vectors. PED ped; ped.reverseOrder(daa); // reverse order. if(ppType.compare("ppo") == 0) daa.leftCols(N) = ks.reflect(daa.leftCols(N)); // R*J for ppo else // R*J for rpo daa.leftCols(N) = ks.rotate(daa.leftCols(N), -s*2*M_PI/L); MatrixXd eigvals = ped.EigVals(daa, MaxN, tol, false); eigvals.col(0) = eigvals.col(0).array()/T; return daa; } void KScalWriteFE(const string inputfileName, const string outputfileName, const string ppType, const int ppId, const int L /* = 22 */, const int MaxN /* = 80000 */, const double tol /* = 1e-15 */, const int nqr /* = 1 */){ MatrixXd eigvals = KScalFE(inputfileName, ppType, ppId, L, MaxN, tol, nqr); MyH5::KSwriteFE(outputfileName, ppType, ppId, eigvals); } void KScalWriteFEInit(const string inputfileName, const string outputfileName, const string ppType, const int ppId, const int L /* = 22 */, const int MaxN /* = 80000 */, const double tol /* = 1e-15 */, const int nqr /* = 1 */){ MatrixXd eigvals = KScalFE(inputfileName, ppType, ppId, L, MaxN, tol, nqr); MyH5::KSwriteFE(outputfileName, ppType, ppId, eigvals); auto tmp = MyH5::KSreadRPO(inputfileName, ppType, ppId); MatrixXd &a = std::get<0>(tmp); double T = std::get<1>(tmp); int nstp = (int) std::get<2>(tmp); double r = std::get<3>(tmp); double s = std::get<4>(tmp); MyH5::KSwriteRPO(outputfileName, ppType, ppId, a, T, nstp, r, s); } void KScalWriteFEFV(const string inputfileName, const string outputfileName, const string ppType, const int ppId, const int L /* = 22 */, const int MaxN /* = 80000 */, const double tol /* = 1e-15 */, const int nqr /* = 1 */, const int trunc /* = 0 */){ pair<MatrixXd, MatrixXd> eigv = KScalFEFV(inputfileName, ppType, ppId, L, MaxN, tol, nqr, trunc); MatrixXd &eigvals = eigv.first; MatrixXd &eigvecs = eigv.second; MyH5::KSwriteFEFV(outputfileName, ppType, ppId, eigvals, eigvecs); } /** * @brief calculate FE and FV and save inital conditions and FE, FV to outputfile */ void KScalWriteFEFVInit(const string inputfileName, const string outputfileName, const string ppType, const int ppId, const int L /* = 22 */, const int MaxN /* = 80000 */, const double tol /* = 1e-15 */, const int nqr /* = 1 */, const int trunc /* = 0 */){ pair<MatrixXd, MatrixXd> eigv = KScalFEFV(inputfileName, ppType, ppId, L, MaxN, tol, nqr, trunc); MatrixXd &eigvals = eigv.first; MatrixXd &eigvecs = eigv.second; MyH5::KSwriteFEFV(outputfileName, ppType, ppId, eigvals, eigvecs); auto tmp = MyH5::KSreadRPO(inputfileName, ppType, ppId); MatrixXd &a = std::get<0>(tmp); double T = std::get<1>(tmp); int nstp = (int) std::get<2>(tmp); double r = std::get<3>(tmp); double s = std::get<4>(tmp); MyH5::KSwriteRPO(outputfileName, ppType, ppId, a, T, nstp, r, s); } //////////////////////////////////////////////////////////////////////////////////////////////////// // Left eigenvector related std::pair<MatrixXd, MatrixXd> KScalLeftFEFV(const std::string fileName, const std::string ppType, const int ppId, const int L, const int MaxN, const double tol, const int nqr, const int trunc){ auto tmp = MyH5::KSreadRPO(fileName, ppType, ppId); MatrixXd &a = std::get<0>(tmp); double T = std::get<1>(tmp); int nstp = (int) std::get<2>(tmp); double r = std::get<3>(tmp); double s = std::get<4>(tmp); const int N = a.rows(); const int Nks = N + 2; // solve the Jacobian of this po. KS ks(Nks, L); std::pair<ArrayXXd, ArrayXXd> tmp2 = ks.intgj(a.col(0), T/nstp, nstp, nqr); MatrixXd daa = tmp2.second; // get the order of J_1^T, J_2^T, ..., (R*J_M)^T int M = daa.cols(); daa.resize(N, N*M); if(ppType.compare("ppo") == 0) daa.rightCols(N) = ks.reflect(daa.rightCols(N)); // R*J for ppo else // R*J for rpo daa.rightCols(N) = ks.rotate(daa.rightCols(N), -s*2*M_PI/L); for(int i = 0; i < M; i++) { MatrixXd tmp = daa.middleCols(i*N, N).transpose(); daa.middleCols(i*N, N) = tmp; } // calculate the Flqouet exponents and vectors. PED ped; pair<MatrixXd, MatrixXd> eigv = ped.EigVecs(daa, MaxN, tol, false, trunc); MatrixXd &eigvals = eigv.first; eigvals.col(0) = eigvals.col(0).array()/T; MatrixXd &eigvecs = eigv.second; return make_pair(eigvals, eigvecs); } void KScalWriteLeftFEFV(const string inputfileName, const string outputfileName, const string ppType, const int ppId, const int L, const int MaxN , const double tol , const int nqr , const int trunc ){ std::pair<MatrixXd, MatrixXd> eigv = KScalLeftFEFV(inputfileName, ppType, ppId, L, MaxN, tol, nqr, trunc); MatrixXd &eigvals = eigv.first; MatrixXd &eigvecs = eigv.second; MyH5::KSwriteFEFV(outputfileName, ppType, ppId, eigvals, eigvecs); } <file_sep>/* compile command: * mex CXXFLAGS='-std=c++0x -fPIC -O3 -march=corei7 -msse4.2' MEXcqcgl1d.cpp cqcgl1d.cc -I../../include -I/usr/include/eigen3 -lm -lfftw3 * */ #include "cqcgl1d.hpp" #include "mex.h" #include <cmath> #include <cstring> #include <Eigen/Dense> using namespace Eigen; static ArrayXXd gintgv(int N, double d, double h, int Njacv, double b, double c, double dr, double di, int threadNum, double *a0, double *v, double th, double phi, int nstp){ bool enableJacv = true; Cqcgl1d cgl(N, d, h, enableJacv, Njacv, b, c, dr, di, threadNum); Map<ArrayXd> tmpa(a0, cgl.Ndim); Map<ArrayXXd> tmpv(v, cgl.Ndim, cgl.trueNjacv); ArrayXXd av = cgl.gintgv(tmpa, tmpv, th, phi, nstp); return av; } void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[]){ int N = mxGetScalar(prhs[0]); double d = mxGetScalar(prhs[1]); double h = mxGetScalar(prhs[2]); int Njacv = mxGetScalar(prhs[3]); double b = mxGetScalar(prhs[4]); double c = mxGetScalar(prhs[5]); double dr = mxGetScalar(prhs[6]); double di = mxGetScalar(prhs[7]); int threadNum = mxGetScalar(prhs[8]); double *a0 = mxGetPr(prhs[9]); double *v = mxGetPr(prhs[10]); double th = mxGetScalar(prhs[11]); double phi = mxGetScalar(prhs[12]); int nstp = mxGetScalar(prhs[13]); // mwSize isJ = mxGetScalar(prhs[14]); ArrayXXd av = gintgv(N, d, h, Njacv, b, c, dr, di, threadNum, a0, v, th, phi, nstp); plhs[0] = mxCreateDoubleMatrix(av.rows(), av.cols(), mxREAL); memcpy(mxGetPr(plhs[0]), av.data(), av.cols()*av.rows()*sizeof(double)); } <file_sep>#include "ksrefine.hpp" #include "iterMethod.hpp" #include <iostream> #include <fstream> using namespace std; using namespace Eigen; typedef Eigen::SparseMatrix<double> SpMat; typedef Eigen::Triplet<double> Tri; //////////////////////////////////////////////////////////// // class KSrefine // //////////////////////////////////////////////////////////// /*------------ constructor ---------------*/ KSrefine::KSrefine(int N /* = 32 */, double L /* = 22 */) : N(N), L(L) {} KSrefine::KSrefine(const KSrefine &x) : N(x.N), L(x.L) {} KSrefine & KSrefine::operator=(const KSrefine &x){ return *this;} KSrefine::~KSrefine(){} /* ----------- member functions -------------- */ struct KeepDiag { inline bool operator() (const int& row, const int& col, const double&) const { return row == col; } }; /* @brief transform a dense matrix into Triplet form, which should be used to * initialize a spase matrix subblock. * * @param[in] M row position of the subblock * @param[in] N col position of the sbublock * @return the triplet representation of the dense matrix * */ vector<Tri> KSrefine::triMat(const MatrixXd &A, const size_t M /* = 0 */, const size_t N /* = 0 */){ vector<Tri> tri; size_t m = A.rows(); size_t n = A.cols(); tri.reserve(m*n); // for efficience, loop in the row wise. for(size_t j = 0; j < n; j++) for(size_t i = 0; i < m; i++) tri.push_back( Tri(M+i, N+j, A(i,j) )); return tri; } /* @brief transform a diagoal matrix (diagonal elements are the same) into Triplet * form * * @param[in] n size of the diagonal matrix * @param[in] x the diagonal elements * @param[in] M row position of the subblock * @param[in] N col position of the sbublock * @see triMat() */ vector<Tri> KSrefine::triDiag(const size_t n, const double x, const size_t M /* = 0 */, const size_t N /* = 0 */ ){ vector<Tri> tri; tri.reserve(n); for(size_t i = 0; i < n; i++) tri.push_back( Tri(M+i, N+i, x) ); return tri; } /* @brief form the multishooting difference vector * [ f(x_0) - x_1, * f(x_1) - x_2, * ... * R*f(x_{m-1}) - x_0] * Here R is rotation for rpo, reflection for ppo. * * @param[in] ks KS object used to integrate the system * @param[in] x [x_0, x_1, ..., x_{n-1}] state vectors * @param[in] nstp integratin steps * @param[in] ppType "ppo" or "rpo" * @param[in] th rotation angle for rpo. It is not used for ppo. */ VectorXd KSrefine::multiF(KS &ks, const ArrayXXd &x, const int nstp, const string ppType, const double th /* = 0.0 */){ int n = x.rows(); int m = x.cols(); VectorXd F(m*n); // form the first m - 1 difference vectors for(size_t i = 0; i < m - 1; i++){ ArrayXXd aa = ks.intg(x.col(i), nstp, nstp); F.segment(i*n, n) = aa.col(1) - x.col(i+1); } // the last difference vector ArrayXXd aa = ks.intg(x.col(m-1), nstp, nstp); if(ppType.compare("ppo") == 0) F.segment((m-1)*n, n) = ks.reflect(aa.col(1)) - x.col(0); else if(ppType.compare("rpo") == 0) F.segment((m-1)*n, n) = ks.rotate(aa.col(1), th) - x.col(0); else fprintf(stderr, "please indicate the right PO type !\n"); return F; } /** @brief calculate the column size of the multishooting matrix * */ int KSrefine::calColSizeDF(const int &rows, const int &cols, const string ppType){ int colsizeDF(0); if(ppType.compare("ppo") == 0) colsizeDF = rows*cols+1; else if(ppType.compare("rpo") == 0) colsizeDF = rows*cols+2; else fprintf(stderr, "please indicate the right PO type !\n"); return colsizeDF; } /* @brief not only form the difference vector but also the multishooting matrix * * @return multishooting matrix and difference vector * @see multiF() */ pair<SpMat, VectorXd> KSrefine::multishoot(KS &ks, const ArrayXXd &x, const int nstp, const string ppType, const double th /* = 0.0 */, const bool Print /* = false */){ int n = x.rows(); int m = x.cols(); int colsizeDF = calColSizeDF(n, m, ppType); SpMat DF(m*n, colsizeDF); VectorXd F(m*n); vector<Tri> nz; nz.reserve(2*m*n*n+m*n); if(Print) printf("Forming multishooting matrix:"); for(size_t i = 0 ; i < m; i++){ if(Print) printf("%zd ", i); pair<ArrayXXd, ArrayXXd> tmp = ks.intgj(x.col(i), nstp, nstp, nstp); ArrayXXd &aa = tmp.first; ArrayXXd &J = tmp.second; // assert(J.rows() == n*n && J.cols() == 1); J.resize(n, n); if(i < m-1) { // J vector<Tri> triJ = triMat(J, i*n, i*n); nz.insert(nz.end(), triJ.begin(), triJ.end()); // velocity vector<Tri> triv = triMat(ks.velocity(aa.col(1)), i*n, m*n); nz.insert(nz.end(), triv.begin(), triv.end()); // f(x_i) - x_{i+1} F.segment(i*n, n) = aa.col(1) - x.col(i+1); } else { if(ppType.compare("ppo") == 0){ // R*J vector<Tri> triJ = triMat(ks.reflect(J), i*n, i*n); nz.insert(nz.end(), triJ.begin(), triJ.end()); // R*velocity vector<Tri> triv = triMat(ks.reflect(ks.velocity(aa.col(1))), i*n, m*n); nz.insert(nz.end(), triv.begin(), triv.end()); // R*f(x_{m-1}) - x_0 F.segment(i*n, n) = ks.reflect(aa.col(1)) - x.col(0); } else if (ppType.compare("rpo") == 0){ // g*J vector<Tri> triJ = triMat(ks.rotate(J, th), i*n, i*n); nz.insert(nz.end(), triJ.begin(), triJ.end()); // R*velocity vector<Tri> triv = triMat(ks.rotate(ks.velocity(aa.col(1)), th), i*n, m*n); nz.insert(nz.end(), triv.begin(), triv.end()); // T*g*f(x_{m-1}) VectorXd tx = ks.gTangent( ks.rotate(aa.col(1), th) ); vector<Tri> tritx = triMat(tx, i*n, m*n+1); nz.insert(nz.end(), tritx.begin(), tritx.end()); // g*f(x_{m-1}) - x_0 F.segment(i*n, n) = ks.rotate(aa.col(1), th) - x.col(0); } else { fprintf(stderr, "please indicate the right PO type !\n"); } } // -I on subdiagonal vector<Tri> triI = triDiag(n, -1, i*n, ((i+1)%m)*n); nz.insert(nz.end(), triI.begin(), triI.end()); } if(Print) printf("\n"); DF.setFromTriplets(nz.begin(), nz.end()); return make_pair(DF, F); } /** @brief find ppo/rpo in KS system * * @param[in] a0 guess of initial condition * @param[in] T guess of period * @param[in] h0 guess of time step * @param[in] Norbit number of pieces of the orbit, so each segment has Norbit/M. * @param[in] M number of pieces for multishooting method * @param[in] ppType ppo/rpo * @param[in] th0 guess of initial group angle. For ppo, it is zero. * @param[in] hinit: the initial time step to get a good starting guess. * @param[in] MaxN maximal number of iteration * @param[in] tol tolerance of convergence * @return initial conditions along the orbit, time step, shift, error * */ tuple<MatrixXd, double, double, double> KSrefine::findPOmulti(const ArrayXd &a0, const double T, const int Norbit, const int M, const string ppType, const double hinit /* = 0.1*/, const double th0 /* = 0 */, const int MaxN /* = 100 */, const double tol /* = 1e-14*/, const bool Print /* = false */, const bool isSingle /* = false */){ bool Terminate = false; assert(a0.rows() == N - 2 && Norbit % M == 0); const int nstp = Norbit/M; double h = T/Norbit; double th = th0; double lam = 1; SparseLU<SpMat> solver; // used in the pre-CG method // prepare the initial state sequence KS ks0(N, hinit, L); ArrayXXd tmpx = ks0.intg(a0, (int)ceil(T/hinit), (int)floor(T/hinit/M)); ArrayXXd x = tmpx.leftCols(M); double err = 0; // error for(size_t i = 0; i < MaxN; i++){ if(Print && i%10 == 0) printf("****** i = %zd/%d ****** \n", i, MaxN); KS ks(N, h, L); VectorXd F; if(!isSingle) F = multiF(ks, x, nstp, ppType, th); else F = multiF(ks, x.col(0), Norbit, ppType, th); err = F.norm(); if(err < tol){ fprintf(stderr, "stop at norm(F)=%g for iteration %zd\n", err, i); break; } pair<SpMat, VectorXd> p = multishoot(ks, x, nstp, ppType, th, false); SpMat JJ = p.first.transpose() * p.first; VectorXd JF = p.first.transpose() * p.second; SpMat Dia = JJ; Dia.prune(KeepDiag()); for(size_t j = 0; j < 20; j++){ //////////////////////////////////////// // solve the update SpMat H = JJ + lam * Dia; pair<VectorXd, vector<double> > cg = iterMethod::ConjGradSSOR<SpMat> (H, -JF, solver, VectorXd::Zero(H.rows()), H.rows(), 1e-6); VectorXd &dF = cg.first; //////////////////////////////////////// // print the CG infomation if(Print) printf("CG error %g after %lu iterations.\n", cg.second.back(), cg.second.size()); //////////////////////////////////////// // update the state ArrayXXd xnew = x + Map<ArrayXXd>(&dF(0), N-2, M); double hnew = h + dF((N-2)*M)/nstp; // be careful here. double thnew = th; if(ppType.compare("rpo") == 0) thnew += dF((N-2)*M+1); // check the new time step positve if( hnew <= 0 ){ fprintf(stderr, "new time step is negative\n"); Terminate = true; break; } KS ks1(N, hnew, L); VectorXd newF; if(!isSingle) newF = multiF(ks1, xnew, nstp, ppType, thnew); else newF = multiF(ks1, xnew.col(0), Norbit, ppType, thnew); if(Print) printf("err = %g \n", newF.norm()); if (newF.norm() < err){ x = xnew; h = hnew; th = thnew; lam = lam/10; break; } else{ lam *= 10; if(Print) printf("lam = %g \n", lam); if( lam > 1e10) { fprintf(stderr, "lam = %g too large.\n", lam); Terminate = true; break; } } } if( Terminate ) break; } return make_tuple(x, h, th, err); } std::tuple<VectorXd, double, double> KSrefine::findPO(const Eigen::ArrayXd &a0, const double T, const int Norbit, const int M, const std::string ppType, const double hinit /* = 0.1 */, const double th0 /* = 0 */, const int MaxN /* = 100 */, const double tol /* = 1e-14 */, const bool Print /* = false */, const bool isSingle /* = false */){ tuple<MatrixXd, double, double, double> tmp = findPOmulti(a0, T, Norbit, M, ppType, hinit, th0, MaxN, tol, Print, isSingle); return make_tuple(std::get<0>(tmp).col(0), std::get<1>(tmp), std::get<2>(tmp)); } /* pair<MatrixXd, VectorXd> newtonReq(Cqcgl1d &cgl, const ArrayXd &a0, const double w1, const double w2){ MatrixXd DF(2*N+2, 2*N+2); ArrayXd t1 = cgl.TS1(a0); ArrayXd t2 = cgl.TS2(a0); DF.topLeftCorner(2*N, 2*N) = cgl.stab(a0) + w1*cgl.GS1() + w2*cgl.GS2(); DF.col(2*N).head(2*N) = t1; DF.col(2*N+1).head(2*N) = t2; //DF.row(2*N).head(2*N) = t1.transpose(); //DF.row(2*N+1).head(2*N) = t2.transpose(); DF.row(2*N).head(2*N) = VectorXd::Zero(2*N); DF.row(2*N+1).head(2*N) = VectorXd::Zero(2*N); DF.bottomRightCorner(2,2) = MatrixXd::Zero(2,2); VectorXd F(2*N+2); F.head(2*N) = cgl.vel(a0) + w1*t1 + w2*t2; F(2*N) = 0; F(2*N+1) = 0; return make_pair(DF, F); } */ /* ArrayXd findReq(const ArrayXd &a0, const double w10, const double w20, const int MaxN, const double tol){ ArrayXd a = a0; double w1 = w10; double w2 = w20; double lam = 1; ConjugateGradient<MatrixXd> CG; Cqcgl1d cgl(N, L); for(size_t i = 0; i < MaxN; i++){ if (lam > 1e10) break; printf("******** i = %zd/%d ******** \n", i, MaxN); VectorXd F = cgl.vel(a) + w1*cgl.TS1(a) + w2*cgl.TS2(a); double err = F.norm(); if(err < tol){ printf("stop at norm(F)=%g\n", err); break; } pair<MatrixXd, VectorXd> p = newtonReq(cgl, a, w1, w2); MatrixXd JJ = p.first.transpose() * p.first; VectorXd JF = p.first.transpose() * p.second; for(size_t j = 0; j < 20; j++){ printf("inner iteration j = %zd\n", j); //MatrixXd H = JJ + lam * JJ.diagonal().asDiagonal(); MatrixXd H = JJ; H.diagonal() *= (1+lam); CG.compute(H); VectorXd dF = CG.solve(-JF); printf("CG error %f, iteration number %d\n", CG.error(), CG.iterations()); ArrayXd anew = a + dF.head(2*N).array(); double w1new = w1 + dF(2*N); double w2new = w2 + dF(2*N+1); printf("w1new = %f, w2new = %f\n", w1new, w2new); VectorXd Fnew = cgl.vel(anew) + w1new*cgl.TS1(anew) + w2new*cgl.TS2(anew); cout << "err = " << Fnew.norm() << endl; if (Fnew.norm() < err){ a = anew; w1 = w1new; w2 = w2new; lam = lam/10; cout << "lam = "<< lam << endl; break; } else{ lam *= 10; cout << "lam = "<< lam << endl; if( lam > 1e10) { printf("lam = %f too large.\n", lam); break; } } } } ArrayXd req(2*N+3); VectorXd err = cgl.vel(a) + w1*cgl.TS1(a) + w2*cgl.TS2(a); req << a, w1, w2, err.norm(); return req; } */ <file_sep>#include <boost/python.hpp> #include <boost/numpy.hpp> #include <Eigen/Dense> #include <cstdio> #include "CQCGL1dEIDc.hpp" #include "myBoostPython.hpp" using namespace std; using namespace Eigen; namespace bp = boost::python; namespace bn = boost::numpy; ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// class pyCQCGL1dEIDc : public CQCGL1dEIDc { public: pyCQCGL1dEIDc(int N, double d, double Mu, double Dr, double Di, double Br, double Bi, double Gr, double Gi): CQCGL1dEIDc(N, d, Mu, Dr, Di, Br, Bi, Gr, Gi) {} pyCQCGL1dEIDc(int N, double d, double b, double c, double dr, double di) : CQCGL1dEIDc(N, d, b, c, dr, di) {} bn::ndarray PYTs(){ return copy2bn(Ts); } bn::ndarray PYlte(){ return copy2bn(lte); } bn::ndarray PYhs(){ return copy2bn(hs); } /* wrap the integrator */ bn::ndarray PYintgC(bn::ndarray a0, double h, double tend, int skip_rate){ int m, n; getDims(a0, m, n); Map<ArrayXd> tmpa((double*)a0.get_data(), m*n); return copy2bn(intgC(tmpa, h, tend, skip_rate)); } bn::ndarray PYintg(bn::ndarray a0, double h, double tend, int skip_rate){ int m, n; getDims(a0, m, n); Map<ArrayXd> tmpa((double*)a0.get_data(), m*n); return copy2bn(intg(tmpa, h, tend, skip_rate)); } }; //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// BOOST_PYTHON_MODULE(py_CQCGL1dEIDc) { bn::initialize(); // must provide the constructor bp::class_<CQCGL1dEIDc>("CQCGL1dEIDc", bp::init< int, double, double, double, double, double, double, double, double>()) ; // the EIDc class bp::class_<EIDc>("EIDc", bp::init<>()) .def_readonly("NCalCoe", &EIDc::NCalCoe) .def_readonly("NReject", &EIDc::NReject) .def_readonly("NCallF", &EIDc::NCallF) .def_readonly("NSteps", &EIDc::NSteps) .def_readonly("TotalTime", &EIDc::TotalTime) .def_readonly("CoefficientTime", &EIDc::CoefficientTime) .def_readwrite("rtol", &EIDc::rtol) ; // bp::class_<pyCQCGL1dEIDc, bp::bases<CQCGL1dEIDc> >("pyCQCGL1dEIDc", bp::init< int, double, double, double, double, double, double, double, double>()) .def(bp::init<int, double, double, double ,double, double>()) .def_readonly("N", &pyCQCGL1dEIDc::N) .def_readonly("d", &pyCQCGL1dEIDc::d) .def_readonly("Mu", &pyCQCGL1dEIDc::Mu) .def_readwrite("Br", &pyCQCGL1dEIDc::Br) .def_readwrite("Bi", &pyCQCGL1dEIDc::Bi) .def_readonly("Dr", &pyCQCGL1dEIDc::Dr) .def_readonly("Di", &pyCQCGL1dEIDc::Di) .def_readwrite("Gr", &pyCQCGL1dEIDc::Gr) .def_readwrite("Gi", &pyCQCGL1dEIDc::Gi) .def_readonly("Ndim", &pyCQCGL1dEIDc::Ndim) .def_readonly("Ne", &pyCQCGL1dEIDc::Ne) .def_readonly("Omega", &pyCQCGL1dEIDc::Omega) .def_readwrite("eidc", &pyCQCGL1dEIDc::eidc) .def("Ts", &pyCQCGL1dEIDc::PYTs) .def("hs", &pyCQCGL1dEIDc::PYhs) .def("lte", &pyCQCGL1dEIDc::PYlte) .def("changeOmega", &pyCQCGL1dEIDc::changeOmega) .def("setScheme", &pyCQCGL1dEIDc::setScheme) .def("intgC", &pyCQCGL1dEIDc::PYintgC) .def("intg", &pyCQCGL1dEIDc::PYintg) ; } <file_sep>/* to compile : * g++ test_iterMethod.cc -O3 -march=corei7 -msse2 -msse4 -I $XDAPPS/eigen/include/eigen3 -std=c++11 -I ../../include -L ../../lib -literMethod -ldenseRoutines */ #include "iterMethod.hpp" #include <cmath> #include <complex> #include <iostream> #include <time.h> /* time */ #define cee(x) (cout << (x) << endl << endl) using namespace std; using namespace Eigen; using namespace denseRoutines; using namespace iterMethod; typedef Eigen::Triplet<double> Tri; typedef Eigen::SparseMatrix<double> SpMat; int main() { cout.precision(16); switch (9) { case 1: // test ConjGrad() with dense matrix { const int N = 10; MatrixXd A(N, N); VectorXd b(N); for (int i = 0; i < N; i++) { for (int j = 0; j < N; j++) { A(i,j) = (i+j)%11; } b(i) = sin(i*i); } pair<VectorXd, vector<double> > tmp = iterMethod::ConjGrad<MatrixXd>(A, b, VectorXd::Zero(N), 100, 1e-6); cout << tmp.first << endl << endl; for (int i = 0; i < tmp.second.size(); i++) { cout << tmp.second[i] << endl; } cout << tmp.second.size() << endl; break; } case 2: //test ConjGrad() with sparse matrix { const int N = 10; vector<Tri> tri; for (int i = 0; i < N; i++) { tri.push_back(Tri(i, i, 2)); if(i < N-1) { tri.push_back(Tri(i, i+1, -1)); tri.push_back(Tri(i+1, i, -1)); } } SpMat A(N, N); A.setFromTriplets(tri.begin(), tri.end()); VectorXd b(N); for (int i = 0; i < N; i++) b(i) = sin(i*i); // perform CG method pair<VectorXd, vector<double> > tmp = iterMethod::ConjGrad<SpMat>(A, b, VectorXd::Zero(N), 100, 1e-6); cout << tmp.first << endl << endl; for (int i = 0; i < tmp.second.size(); i++) { cout << tmp.second[i] << endl; } cout << tmp.second.size() << endl; } case 3 : // test ConjGradPre() with dense matrix { // initialization const int N = 10; MatrixXd A(N, N); for (int i = 0; i < N; i++) { A(i, i) = 2; if(i < N-1) { A(i+1, i) = -1; A(i, i+1) = -1; } } VectorXd b(N); for (int i = 0; i < N; i++) b(i) = sin(i*i); // compute MatrixXd M(MatrixXd::Identity(N, N)); cout << A << endl; PartialPivLU<MatrixXd> solver; pair<VectorXd, vector<double> > tmp = iterMethod::ConjGradPre<MatrixXd, PartialPivLU<MatrixXd> > (A, b, M, solver, VectorXd::Zero(N), 100, 1e-16); cout << tmp.first << endl << endl; for (int i = 0; i < tmp.second.size(); i++) { cout << tmp.second[i] << endl; } cout << tmp.second.size() << endl; break; } case 4: // test ConjGradPre() with sparse matrix { const int N = 10; vector<Tri> tri; for (int i = 0; i < N; i++) { tri.push_back(Tri(i, i, 2)); if(i < N-1) { tri.push_back(Tri(i, i+1, -1)); tri.push_back(Tri(i+1, i, -1)); } } SpMat A(N, N); A.setFromTriplets(tri.begin(), tri.end()); VectorXd b(N); for (int i = 0; i < N; i++) b(i) = sin(i*i); // compute SpMat M(N, N); vector<Tri> triM; for (int i = 0; i < N; i++) triM.push_back(Tri(i, i, 1)); M.setFromTriplets(triM.begin(), triM.end()); cout << M << endl; SparseLU<SpMat> solver; pair<VectorXd, vector<double> > tmp = iterMethod::ConjGradPre<SpMat, SparseLU<SpMat> > (A, b, M, solver, VectorXd::Zero(N), 100, 1e-16); cout << tmp.first << endl << endl; for (int i = 0; i < tmp.second.size(); i++) { cout << tmp.second[i] << endl; } cout << tmp.second.size() << endl; break; } case 5 : // test SSOR preconditioning { const int N = 10; vector<Tri> tri; for (int i = 0; i < N; i++) { tri.push_back(Tri(i, i, 2)); if(i < N-1) { tri.push_back(Tri(i, i+1, -1)); tri.push_back(Tri(i+1, i, -1)); } } SpMat A(N, N); A.setFromTriplets(tri.begin(), tri.end()); SpMat ssor = iterMethod::preSSOR<SpMat>(A); cout << ssor << endl; break; } case 6: // test ConjGradSSOR() with sparse matrix { const int N = 10; vector<Tri> tri; for (int i = 0; i < N; i++) { tri.push_back(Tri(i, i, 2)); if(i < N-1) { tri.push_back(Tri(i, i+1, -1)); tri.push_back(Tri(i+1, i, -1)); } } SpMat A(N, N); A.setFromTriplets(tri.begin(), tri.end()); VectorXd b(N); for (int i = 0; i < N; i++) b(i) = sin(i*i); // compute SparseLU<SpMat> solver; pair<VectorXd, vector<double> > tmp = iterMethod::ConjGradSSOR<SpMat, SparseLU<SpMat> > (A, b, solver, VectorXd::Zero(N), 100, 1e-16); cout << tmp.first << endl << endl; for (int i = 0; i < tmp.second.size(); i++) { cout << tmp.second[i] << endl; } cout << tmp.second.size() << endl; break; } case 7: // test Gmres() with dense matrix { srand (time(NULL)); const int N = 10; MatrixXd A(N, N); VectorXd x(N); for (int i = 0; i < N; i++) { for (int j = 0; j < N; j++) { A(i,j) = (double)rand() / RAND_MAX - 0.5; } x(i) = (double)rand() / RAND_MAX - 0.5; } VectorXd b = A * x; //cout << A << endl << endl; cout << x << endl << endl; cout << b << endl << endl; // compute std::tuple<VectorXd, vector<double>, int> tmp = iterMethod::Gmres<MatrixXd> (A, b, VectorXd::Zero(N), 20, 20, 1e-8); cout << std::get<0>(tmp) << endl << endl; for (int i = 0; i < std::get<1>(tmp).size(); i++) { cout << std::get<1>(tmp)[i] << endl; } cout << std::get<2>(tmp) << endl << endl;; cout << std::get<1>(tmp).size() << endl << endl; cout << (A * std::get<0>(tmp) - b).norm() << endl; break; } case 8: // test findTrustRegion { srand (time(NULL)); const int N = 5; ArrayXd D(N), p(N); for(int i = 0; i < N; i++){ /* D(i) = i+1; */ /* p(i) = i+1; */ /* D(i) = (double)rand() / RAND_MAX - 0.5; */ /* p(i) = (double)rand() / RAND_MAX - 0.5; */ D(i) = rand() % 100; p(i) = rand() % 100; } cout << D <<endl << endl; cout << p << endl << endl; cout << p / D << endl << endl; cout << p.matrix().norm() << endl << endl; auto tmp = iterMethod::findTrustRegion(D, p, 0.1, 1e-4, 20, 0); cout << std::get<0>(tmp) << endl; cout << std::get<1>(tmp).size() << endl; cout << std::get<2>(tmp) << endl; auto x = std::get<1>(tmp); for_each (x.begin(), x.end(), [](double i){cout << i << endl;}); ArrayXd z = iterMethod::calz(D, p, std::get<0>(tmp)); cout << "z norm " << z.matrix().norm() << endl; cout << "Dz-p " << endl << (D*z - p).matrix().norm() << endl; break; } case 9: // test GmresHook()/GmresHookPre() with dense matrix { const int N = 50; //MatrixXd A = MatrixXd::Random(N, N); //A.diagonal() *= 200; VectorXd t = VectorXd::Random(N) * 0.5 + 5*VectorXd::Ones(N); t(N-1) = 1e6; MatrixXd A = matE(t); VectorXd x(VectorXd::Random(N)); VectorXd b = A * x; VectorXcd e = eEig(A); // cee(e); VectorXd bp; std::vector<double> errs; int flag; std::tie(bp, errs, flag) = iterMethod::GmresHook<MatrixXd> (A, b, VectorXd::Zero(N), 1e-12, 1e-3, 20, 20, 1e-8, 100, 20, false, 1); for (int i = 0; i < errs.size(); i++) cout << errs[i] << endl; cee( (A * bp - b).norm() ); break; } case 10: /* test LM() function */ { srand(time(NULL)); const int N = 100; MatrixXd A(randM(N, N)); A.col(10) *= 1e7; VectorXd x(randM(N, 1)); VectorXd b = A * x; cout << x << endl << endl; cout << b << endl << endl; auto tmp = LM(A, b, VectorXd::Zero(N), 1e-13, 100, 20); cout << std::get<0>(tmp) << endl << endl; auto res = std::get<1>(tmp); for(int i = 0; i < res.size(); i++) cout << res[i] << endl; cout << std::get<2>(tmp) << endl << endl; break; } } return 0; } <file_sep>/* g++ -std=c++11 -I$EIGEN test_EigenFFT.cc */ #include <Eigen/Dense> #include <unsupported/Eigen/FFT> #include <iostream> #define EIGEN_FFTW_DEFAULT #define CE(x) cout << (x) << endl << endl using namespace Eigen; using namespace std; int main(){ VectorXcd A(4); A.real() << 2, 8, 3, 6; A.imag() << 3, 5, 7, 19; VectorXcd B(4); VectorXcd C(4); FFT<double> fft; fft.fwd(B, A); fft.inv(C, B); CE(A); CE(B); CE(C); return 0; } <file_sep>from personalFunctions import * case = 20 if case == 10: """ allocate all soliton solutions """ ix = np.arange(0.09, 0.57, 0.01).tolist() ixf = [format(i, ".6f") for i in ix] fs = ['req09.h5', 'req1.h5', 'req11.h5', 'req12.h5', 'req13.h5', 'req14.h5', 'req15.h5', 'req16.h5', 'req17.h5', 'req18.h5', 'req19.h5', 'req2.h5', 'req21.h5', 'req22.h5', 'req23.h5', 'req24.h5', 'req25.h5', 'req26.h5', 'req27.h5', 'req28.h5', 'req29.h5', 'req3.h5', 'req31.h5', 'req32.h5', 'req33.h5', 'req34.h5', 'req35.h5', 'req36.h5', 'req37.h5', 'req38.h5', 'req39.h5', 'req4.h5', 'req41.h5', 'req42.h5', 'req43.h5', 'req44.h5', 'req45.h5', 'req46.h5', 'req47.h5', 'req48.h5', 'req49.h5', 'req5.h5', 'req51.h5', 'req52.h5', 'req53.h5', 'req54.h5', 'req55.h5', 'req56.h5'] inps = ['./req_different_di/' + i for i in fs] for i in range(len(ix)): cqcglMoveReqEV(inps[i], '1', 'reqDi.h5', ixf[i]+'/1') if case == 20: """ allocate all soliton solutions """ ix = [0.57, 0.59, 0.61, 0.63, 0.65, 0.67, 0.69, 0.71, 0.74, 0.77, 0.8, 0.83, 0.86, 0.9, 0.94, 0.96] ixf = [format(i, ".6f") for i in ix] fs = ['req57.h5', 'req59.h5', 'req61.h5', 'req63.h5', 'req65.h5', 'req67.h5', 'req69.h5', 'req71.h5', 'req74.h5', 'req77.h5', 'req8.h5', 'req83.h5', 'req86.h5', 'req9.h5', 'req94.h5', 'req96.h5'] inps = ['./req_different_di/' + i for i in fs] for i in range(len(ix)): cqcglMoveReqEV(inps[i], '1', 'reqDi.h5', ixf[i]+'/1') <file_sep>/* to comiple: * h5c++ -O3 test_cqcgl1d.cc -L../../lib -I../../include -I $XDAPPS/eigen/include/eigen3 -std=c++0x -lCQCGL1d -lsparseRoutines -ldenseRoutines -lmyH5 -lped -lmyfft -lfftw3 -lm */ #include "CQCGL1d.hpp" #include "myH5.hpp" #include <iostream> #include <fstream> #include <eigen3/Eigen/Dense> #include <complex> #include <H5Cpp.h> using namespace std; using namespace Eigen; using namespace MyH5; using namespace denseRoutines; typedef std::complex<double> dcp; #define N10 int main(){ #ifdef N10 //====================================================================== /* test the new constructor */ const int N = 1024; const int L = 50; // CQCGL1d cgl(N, L, 4.0, 0.8, 0.01, 0.06, -1); CQCGL1d cgl(N, L, -1, 1, 4.0, 1, 0.8, -0.01, -0.06, -1); int nstp = 1; VectorXcd A0 = Gaussian(N, N/2, N/10, 3) + Gaussian(N, N/4, N/10, 0.5); VectorXd a0 = cgl.Config2Fourier(A0); ArrayXXd aa = cgl.intg(a0, 0.0001, nstp, 1); cout << aa.rows() << 'x' << aa.cols() << endl; cout << aa << endl; #endif return 0; } <file_sep>#ifndef KSFEFV_H #define KSFEFV_H #include <Eigen/Dense> std::pair<Eigen::MatrixXd, Eigen::MatrixXd> KScalFEFV(const std::string fileName, const std::string ppType, const int ppId, const int L = 22 , const int MaxN = 80000, const double tol = 1e-15, const int nqr = 1, const int trunc = 0); Eigen::MatrixXd KScalFE(const std::string fileName, const std::string ppType, const int ppId, const int L = 22, const int MaxN = 80000, const double tol = 1e-15, const int nqr = 1); Eigen::MatrixXd KSgetR(const std::string fileName, const std::string ppType, const int ppId, const int L /* = 22 */, const int MaxN /* = 80000 */, const double tol /* = 1e-15 */, const int nqr /* = 1 */); void KScalWriteFE(const std::string inputfileName, const std::string outputfileName, const std::string ppType, const int ppId, const int L = 22, const int MaxN = 80000, const double tol = 1e-15, const int nqr = 1); void KScalWriteFEInit(const std::string inputfileName, const std::string outputfileName, const std::string ppType, const int ppId, const int L = 22, const int MaxN = 80000, const double tol = 1e-15, const int nqr = 1); void KScalWriteFEFV(const std::string inputfileName, const std::string outputfileName, const std::string ppType, const int ppId, const int L = 22, const int MaxN = 80000, const double tol = 1e-15, const int nqr = 1, const int trunc = 0); void KScalWriteFEFVInit(const std::string inputfileName, const std::string outputfileName, const std::string ppType, const int ppId, const int L = 22, const int MaxN = 80000, const double tol = 1e-15, const int nqr = 1, const int trunc = 0); //////////////////////////////////////////////////////////////////////////////// std::pair<Eigen::MatrixXd, Eigen::MatrixXd> KScalLeftFEFV(const std::string fileName, const std::string ppType, const int ppId, const int L, const int MaxN, const double tol, const int nqr, const int trunc); void KScalWriteLeftFEFV(const std::string inputfileName, const std::string outputfileName, const std::string ppType, const int ppId, const int L, const int MaxN , const double tol , const int nqr , const int trunc ); #endif /* KSFEFV_H */ <file_sep>/* h5c++ test_CQCGL1dEIDc.cc -std=c++11 -lCQCGL1d -lmyfft -lmyH5 -ldenseRoutines -literMethod -lfftw3 -I $RESH/include/ -L $RESH/lib/ -I $XDAPPS/eigen/include/eigen3 -DEIGEN_FFTW_DEFAULT -O3 -o cgl1d.out && time ./cgl1d.out */ #include <iostream> #include <ctime> #include "CQCGL1dEIDc.hpp" #include "myH5.hpp" // #include "CQCGL1d.hpp" #include "denseRoutines.hpp" #define cee(x) cout << (x) << endl << endl; #define N5 using namespace MyH5; using namespace std; using namespace Eigen; using namespace denseRoutines; int main(){ std::vector<std::string> scheme = {"IFRK43", "IFRK54", "Cox_Matthews", "Krogstad", "Hochbruck_Ostermann", "Luan_Ostermann", "SSPP43"}; #ifdef N5 //==================================================================================================== // test the integrator const int N = 1024; const double d = 50; double Bi = 0.8, Gi = -0.6; CQCGL1dEIDc cgl(N, d, -0.1, 0.125, 0.5, 1, Bi, -0.1, Gi); #endif #ifdef N10 //==================================================================================================== // test the performance of the EID compared with previous implementation. // The initial condition is the travelling wave, or a suppoposition of // two Gaussian waves. This asymmetric initial condition will result // asymmetric explosions. const int N = 1024; const double d = 30; const double di = 0.06; CQCGL1dEIDc cgl(N, d, 4, 0.8, 0.01, di); CQCGL1d cgl2(N, d, 4, 0.8, 0.01, di, -1, 4); std::string file = "/usr/local/home/xiong/00git/research/data/cgl/reqDi.h5"; std::string groupName = to_string(di) + "/1"; VectorXd a0; double wth, wphi, err; std::tie(a0, wth, wphi, err) = CqcglReadReq(file, groupName); if (true) { VectorXcd A0 = Gaussian(N, N/2, N/10, 3) + Gaussian(N, N/4, N/10, 0.5); a0 = cgl2.Config2Fourier(A0); } double T = 4; time_t t = clock(); ArrayXXd aa = cgl.intgC(a0, 0.001, T, 10); t = clock()-t; cout << static_cast<double>(t) / CLOCKS_PER_SEC << endl; t = clock(); ArrayXXd aa2 = cgl2.intg(a0, 0.001, static_cast<int>(T/0.001), 10); t = clock()-t; cout << static_cast<double>(t) / CLOCKS_PER_SEC << endl; cout << aa.cols() << ' ' << aa2.cols() << ' ' << (aa-aa2.rightCols(aa.cols())).abs().maxCoeff() << ' ' << aa.abs().maxCoeff() << ' ' << cgl.lte.maxCoeff() << endl; savetxt("aa.dat", aa.transpose()); savetxt("aa2.dat", aa2.transpose()); // Output: // 0.871511 // 0.738813 // 4000 4001 3197.97 3297.8 0.000316152 // the performance are almost the same. #endif #ifdef N15 //==================================================================================================== // test a single method to see whether there is a bug // Also, save the state for orbits const int N = 1024; const double d = 50; double Bi = 0.8, Gi = -0.6; CQCGL1dEIDc cgl(N, d, -0.1, 0.125, 0.5, 1, Bi, -0.1, Gi); CQCGL1d cgl2(N, d, -0.1, 0.125, 0.5, 1, Bi, -0.1, Gi, -1); VectorXcd A0 = Gaussian(N, N/2, N/30, 2.5) + Gaussian(N, 2*N/5, N/30, 0.2); VectorXd a0 = cgl2.Config2Fourier(A0); double T = 20; cgl.setScheme("Cox_Matthews"); ArrayXXd aa = cgl.intgC(a0, 0.002, T, 50); savetxt("aa.dat", aa.transpose()); aa = cgl.intgC(a0, 0.002, T, 5); savetxt("a0NoAdapt.dat", aa.row(0).transpose()); // save for time adaption integrated orbit if(true){ cgl.eidc.rtol = 1e-10; cgl.setScheme("Cox_Matthews"); ArrayXXd aaAdapt = cgl.intg(a0, T/(1<<15), T, 400); savetxt("aaAdapt_Cox_Matthews.dat", aaAdapt.transpose()); savetxt("TsAdapt_Cox_Matthews.dat", cgl.Ts); cgl.setScheme("SSPP43"); aaAdapt = cgl.intg(a0, T/(1<<15), T, 400); savetxt("aaAdapt_SSPP43.dat", aaAdapt.transpose()); savetxt("TsAdapt_SSPP43.dat", cgl.Ts); } // save for time adaption orbit in comoving frame if(true){ cgl.eidc.rtol = 1e-10; cgl.setScheme("Cox_Matthews"); cgl.changeOmega(-17.667504892760448); ArrayXXd aaCom = cgl.intg(a0, T/(1<<15), T, 200); savetxt("aaCom.dat", aaCom.transpose()); savetxt("TsCom.dat", cgl.Ts); aaCom = cgl.intgC(a0, 0.002, T, 5); savetxt("a0ComNoAdapt.dat", aaCom.row(0).transpose()); } #endif #ifdef N20 //==================================================================================================== // Test the accuracy of constant stepping shemes. // Choose Luan-Ostermann method with a small time step as the base const int N = 1024; const double d = 50; double Bi = 0.8, Gi = -0.6; CQCGL1dEIDc cgl(N, d, -0.1, 0.125, 0.5, 1, Bi, -0.1, Gi); CQCGL1d cgl2(N, d, -0.1, 0.125, 0.5, 1, Bi, -0.1, Gi, -1); VectorXcd A0 = Gaussian(N, N/2, N/30, 2.5) + Gaussian(N, 2*N/5, N/30, 0.2); VectorXd a0 = cgl2.Config2Fourier(A0); double T = 20; double h0 = T / (1<<18); // T / 2^18 cgl.setScheme("Luan_Ostermann"); ArrayXd x0 = cgl.intgC(a0, h0, T, 1000000).rightCols(1); int n = 8; MatrixXd erros(n, scheme.size()+1); for(int i = 0; i < scheme.size(); i++) { cgl.setScheme(scheme[i]); for(int j = 0, k=2; j < n; j++, k*=2){ double h = k*h0; if(i == 0) { erros(j, 0) = h; } ArrayXXd aa = cgl.intgC(a0, h, T, 1000000); double err = (aa.rightCols(1) - x0).abs().maxCoeff() / x0.abs().maxCoeff(); erros(j, i+1) = err; cout << err << ' '; } cout << endl; } savetxt("cqcgl1d_N20_err.dat", erros); #endif #ifdef N30 //==================================================================================================== // fix the time step. try to look at the estimated local error of all shemes const int N = 1024; const double d = 50; double Bi = 0.8, Gi = -0.6; CQCGL1dEIDc cgl(N, d, -0.1, 0.125, 0.5, 1, Bi, -0.1, Gi); CQCGL1d cgl2(N, d, -0.1, 0.125, 0.5, 1, Bi, -0.1, Gi, -1); VectorXcd A0 = Gaussian(N, N/2, N/30, 2.5) + Gaussian(N, 2*N/5, N/30, 0.2); VectorXd a0 = cgl2.Config2Fourier(A0); double T = 20; int n0 = 15, n1 = 6; double h0 = T / (1<<n0); double w[] = {0, -17.667504892760448}; MatrixXd ltes(1<<(n0-n1), 2*scheme.size()); for(int k = 0; k < 2; k++){ cgl.changeOmega(w[k]); for(int i = 0; i < scheme.size(); i++) { cgl.setScheme(scheme[i]); ArrayXXd aa = cgl.intgC(a0, h0, T, 1<<n1); ltes.col(k*scheme.size() + i) = cgl.lte; } } savetxt("cqcgl1d_N30_lte.dat", ltes); #endif #ifdef N40 //==================================================================================================== // compare static frame integration and comoving frame integration for a single method // by using different rtol so make the global error close const int N = 1024; const double d = 50; double Bi = 0.8, Gi = -0.6; CQCGL1dEIDc cgl(N, d, -0.1, 0.125, 0.5, 1, Bi, -0.1, Gi); CQCGL1d cgl2(N, d, -0.1, 0.125, 0.5, 1, Bi, -0.1, Gi, -1); cgl.setScheme("Cox_Matthews"); MatrixXd hs; VectorXcd A0 = Gaussian(N, N/2, N/30, 2.5) + Gaussian(N, 2*N/5, N/30, 0.2); VectorXd a0 = cgl2.Config2Fourier(A0); double T = 20; double w[] = {0, -17.667504892760448}; for(int i = 0; i < 2; i++){ cgl.changeOmega(w[i]); cgl.eidc.rtol = i == 0 ? 1e-10 : 1e-11; ArrayXXd aa = cgl.intg(a0, T/(1<<12), T, 100); MatrixXd tmp(cgl.hs.size(), 2); tmp << cgl.Ts, cgl.hs; savetxt("cqcgl1d_N40_" + to_string(i) + ".dat", tmp); savetxt("aa_" + to_string(i) + ".dat", aa.transpose()); } #endif #ifdef N50 //==================================================================================================== // static frame integration // set the rtol = 1e-10 and output time steps const int N = 1024; const double d = 50; double Bi = 0.8, Gi = -0.6; CQCGL1dEIDc cgl(N, d, -0.1, 0.125, 0.5, 1, Bi, -0.1, Gi); CQCGL1d cgl2(N, d, -0.1, 0.125, 0.5, 1, Bi, -0.1, Gi, -1); cgl.eidc.rtol = 1e-10; VectorXcd A0 = Gaussian(N, N/2, N/30, 2.5) + Gaussian(N, 2*N/5, N/30, 0.2); VectorXd a0 = cgl2.Config2Fourier(A0); double T = 20; double h0 = T / (1<<12); // T / 2^12 for(int i = 0; i < scheme.size(); i++) { cgl.setScheme(scheme[i]); ArrayXXd aa = cgl.intg(a0, h0, T, 1<<5); savetxt("cqcgl1d_N50_hs_"+to_string(i)+".dat", cgl.hs); } #endif #ifdef N60 //==================================================================================================== // Comoving frame integration // set the rtol = 1e-10 and output time steps const int N = 1024; const double d = 50; double Bi = 0.8, Gi = -0.6; CQCGL1dEIDc cgl(N, d, -0.1, 0.125, 0.5, 1, Bi, -0.1, Gi); CQCGL1d cgl2(N, d, -0.1, 0.125, 0.5, 1, Bi, -0.1, Gi, -1); cgl.eidc.rtol = 1e-10; cgl.changeOmega(-17.667504892760448); VectorXcd A0 = Gaussian(N, N/2, N/30, 2.5) + Gaussian(N, 2*N/5, N/30, 0.2); VectorXd a0 = cgl2.Config2Fourier(A0); double T = 20; double h0 = T / (1<<12); // T / 2^12 for(int i = 0; i < scheme.size(); i++) { cgl.setScheme(scheme[i]); ArrayXXd aa = cgl.intg(a0, h0, T, 1<<5); savetxt("cqcgl1d_N60_comoving_hs_"+to_string(i)+".dat", cgl.hs); } #endif #ifdef N65 //==================================================================================================== // comoving frame integration // rtol vs global relative error for a single method // const int N = 1024; const double d = 50; double Bi = 0.8, Gi = -0.6; CQCGL1dEIDc cgl(N, d, -0.1, 0.125, 0.5, 1, Bi, -0.1, Gi); cgl.changeOmega(-17.667504892760448); CQCGL1d cgl2(N, d, -0.1, 0.125, 0.5, 1, Bi, -0.1, Gi, -1); VectorXcd A0 = Gaussian(N, N/2, N/20, 2.5) + Gaussian(N, N/3, N/20, 0.5); VectorXd a0 = cgl2.Config2Fourier(A0); double T = 40; double h0 = T / (1 << 20); cgl.setScheme("Luan_Ostermann"); ArrayXd x0 = cgl.intgC(a0, h0, T, 1000000).rightCols(1); int n = 10; time_t t; cgl.setScheme("Luan_Ostermann"); VectorXd errors(n); for(int i = 0, k = 1; i < n; i++, k*=5){ printf("i == %d\n", i); double rtol = k * 1e-15; cgl.eidc.rtol = rtol; ArrayXd lastState = cgl.intg(a0, T/(1<<12), T, 1000000).rightCols(1); double err = (lastState - x0).abs().maxCoeff() / x0.abs().maxCoeff(); errors[i] = err; } cout << errors << endl; #endif #ifdef N70 //==================================================================================================== // static & comoving frame integration with time step adaption turned on. // choose different rtol to obtain // rtol vs global relative error // rtol vs integration steps, N(x) evaluation times // const int N = 1024; const double d = 50; double Bi = 0.8, Gi = -0.6; CQCGL1dEIDc cgl(N, d, -0.1, 0.125, 0.5, 1, Bi, -0.1, Gi); CQCGL1d cgl2(N, d, -0.1, 0.125, 0.5, 1, Bi, -0.1, Gi, -1); VectorXcd A0 = Gaussian(N, N/2, N/30, 2.5) + Gaussian(N, 2*N/5, N/30, 0.2); VectorXd a0 = cgl2.Config2Fourier(A0); double T = 20; double h0 = T / (1<<18); // T / 2^20 double w[] = {0, -17.667504892760448}; int n = 10; time_t t; for(int p = 0; p < 2; p++){ cgl.changeOmega(w[p]); cgl.setScheme("IFRK54"); ArrayXd x0 = cgl.intgC(a0, h0, T, 1000000).rightCols(1); MatrixXd erros(n, 6*scheme.size()+1); for(int i = 0; i < scheme.size(); i++) { cgl.setScheme(scheme[i]); for(int j = 0, k=1; j < n; j++, k*=5){ double rtol = k*1e-13; cgl.eidc.rtol = rtol; if(i == 0) { erros(j, 0) = rtol; } ArrayXd xf = cgl.intg(a0, T/(1<<12), T, 1000000).rightCols(1); double err = (xf - x0).abs().maxCoeff() / x0.abs().maxCoeff(); erros.row(j).segment(6*i+1, 6) << err, cgl.eidc.NCalCoe, cgl.eidc.NCallF, cgl.eidc.NReject, cgl.eidc.TotalTime, cgl.eidc.CoefficientTime; cout << err << ' '; } cout << endl; } savetxt("cqcgl1d_N70_stat" + to_string(p) + ".dat", erros); } #endif #ifdef N75 //==================================================================================================== // figure out why the Luan_Ostermann method produces large Nab const int N = 1024; const double d = 50; double Bi = 0.8, Gi = -0.6; CQCGL1dEIDc cgl(N, d, -0.1, 0.125, 0.5, 1, Bi, -0.1, Gi); cgl.changeOmega(-17.667504892760448); CQCGL1d cgl2(N, d, -0.1, 0.125, 0.5, 1, Bi, -0.1, Gi, -1); VectorXcd A0 = Gaussian(N, N/2, N/30, 2.5) + Gaussian(N, 2*N/5, N/30, 0.2); VectorXd a0 = cgl2.Config2Fourier(A0); double T = 20; double h0 = T / (1<<18); // T / 2^20 int n = 10; time_t t; cgl.setScheme("Luan_Ostermann"); ArrayXd x0 = cgl.intgC(a0, h0, T, 1000000).rightCols(1); //cgl.setScheme("Hochbruck_Ostermann"); //cgl.setScheme("IFRK54"); for(int j = 0, k=1; j < n; j++, k*=5){ double rtol = k*1e-13; cgl.eidc.rtol = rtol; t = clock(); ArrayXd xf = cgl.intg(a0, T/(1<<12), T, 1000000).rightCols(1); t = clock() - t; double err = (xf - x0).abs().maxCoeff() / x0.abs().maxCoeff(); cout << err << '\t' << static_cast<double>(t) / CLOCKS_PER_SEC << '\t' << cgl.eidc.NCallF << '\t' << cgl.eidc.NCalCoe << '\t' << cgl.eidc.NSteps << '\t' << cgl.eidc.NReject << endl; } #endif #ifdef N80 //==================================================================================================== // test the accuracy of calculating coefficient // there is no problem with coefficients const int N = 1024; const double d = 30; const double di = 0.06; CQCGL1dEIDc cgl(N, d, 4, 0.8, 0.01, di); cgl.changeOmega(-176.67504941219335); int n = 3; ArrayXXcd c(N, n); for (int i = 0; i < n; i++){ cgl.eidc.M = 64 * (1<<i); cout << cgl.eidc.M << endl; cgl.eidc.calCoe(1e-3); c.col(i) = cgl.eidc.b[3]; } MatrixXd err(n, n); for( int i = 0; i < n; i++) { for (int j = 0; j < n; j++){ err(i, j) = (c.col(i) - c.col(j)).abs().maxCoeff(); } } cout << err << endl; #endif #ifdef N90 //==================================================================================================== // test the norm of b for estimating the local error const int N = 1024; const double d = 50; double Bi = 0.8, Gi = -0.6; CQCGL1dEIDc cgl(N, d, -0.1, 0.125, 0.5, 1, Bi, -0.1, Gi); int bindex[] = {3, 3, 4, 7}; ArrayXXcd bs1(N, 4); for (int i = 0; i < 4; i++){ cgl.setScheme(scheme[i]); cgl.eidc.calCoe(1e-3); bs1.col(i) = cgl.eidc.b[bindex[i]]; } savetxt("l1r.dat", cgl.L.real()); savetxt("l1c.dat", cgl.L.imag()); cgl.changeOmega(-17.667504892760448); ArrayXXcd bs2(N, 4); for (int i = 0; i < 4; i++){ cgl.setScheme(scheme[i]); cgl.eidc.calCoe(1e-3); bs2.col(i) = cgl.eidc.b[bindex[i]]; } savetxt("l2r.dat", cgl.L.real()); savetxt("l2c.dat", cgl.L.imag()); for(int i = 0; i < 4; i++) cout << bs1.col(i).matrix().norm() << '\t'; cout << endl; for(int i = 0; i < 4; i++) cout << bs2.col(i).matrix().norm() << '\t'; cout << endl; savetxt("bs1r.dat", bs1.real()); savetxt("bs1c.dat", bs1.imag()); savetxt("bs2r.dat", bs2.real()); savetxt("bs2c.dat", bs2.imag()); #endif return 0; } <file_sep>#ifndef CQCGL2DEIDC_H #define CQCGL2DEIDC_H #include "EIDc.hpp" #include <Eigen/Dense> #include <unsupported/Eigen/FFT> #include "myH5.hpp" using namespace MyH5; /// integrator for 2d CQCGL /// /// The domain layout is /// /// dx /// ************* /// * * /// dy * * M /// * * /// * * /// ************* /// N /// /// /// class CQCGL2dEIDc { public : typedef std::complex<double> dcp; const int N, M; /* dimension of FFT */ const double dx, dy; /* system domain size */ int Ne, Me; int Nplus, Nminus, Nalias; int Mplus, Mminus, Malias; double Br, Bi, Gr, Gi, Dr, Di, Mu; double Omega = 0; ArrayXd Kx, QKx, Ky, QKy; ArrayXXcd L; ArrayXcd Lv; FFT<double> fft; VectorXd hs; /* time step sequnce */ VectorXd lte; /* local relative error estimation */ VectorXd Ts; /* time sequnence for adaptive method */ int cellSize = 50; int IntPrint = 0; // print frequency during integration. struct NL { CQCGL2dEIDc *cgl; dcp B, G; MatrixXcd A; NL(CQCGL2dEIDc *cgl) : cgl(cgl), B(cgl->Br, cgl->Bi), G(cgl->Gr, cgl->Gi) { A.resize(cgl->M, cgl->N); } ~NL(){} void operator()(ArrayXcd &x, ArrayXcd &dxdt, double t){ Map<MatrixXcd> xv(x.data(), cgl->M, cgl->N); Map<MatrixXcd> dxdtv(dxdt.data(), cgl->M, cgl->N); cgl->fft.inv2(A.data(), x.data(), cgl->N, cgl->M); ArrayXXcd A2 = A.array() * A.array().conjugate(); A = B * A.array() * A2 + G * A.array() * A2.square(); cgl->fft.fwd2(dxdt.data(), A.data(), cgl->N, cgl->M); dxdtv.middleRows(cgl->Mplus, cgl->Malias).setZero(); /* dealias */ dxdtv.middleCols(cgl->Nplus, cgl->Nalias).setZero(); /* dealias */ } }; NL nl; ArrayXcd Yv[10], Nv[10]; EIDc eidc; //////////////////////////////////////////////////////////////////////////////////////////////////// CQCGL2dEIDc(int N, int M, double dx, double dy, double Mu, double Dr, double Di, double Br, double Bi, double Gr, double Gi) : N(N), M(M), dx(dx), dy(dy), Mu(Mu), Dr(Dr), Di(Di), Br(Br), Bi(Bi), Gr(Gr), Gi(Gi), nl(this) { Ne = (N/3) * 2 - 1; Nplus = (Ne + 1) / 2; Nminus = (Ne - 1) / 2; Nalias = N - Ne; Me = (M/3) * 2 - 1; Mplus = (Me + 1) / 2; Mminus = (Me - 1) / 2; Malias = M - Me; // calculate the Linear part Kx.resize(N,1); Kx << ArrayXd::LinSpaced(N/2, 0, N/2-1), N/2, ArrayXd::LinSpaced(N/2-1, -N/2+1, -1); Ky.resize(M,1); Ky << ArrayXd::LinSpaced(M/2, 0, M/2-1), 0, ArrayXd::LinSpaced(M/2-1, -M/2+1, -1); QKx = 2*M_PI/dx * Kx; QKy = 2*M_PI/dy * Ky; L = dcp(Mu, -Omega) - dcp(Dr, Di) * (QKx.square().replicate(1, M).transpose() + QKy.square().replicate(1, N)); L.middleRows(Mplus, Malias).setZero(); L.middleCols(Nplus, Nalias).setZero(); Lv = Map<VectorXcd>(L.data(), M*N); int nYN0 = eidc.names.at(eidc.scheme).nYN; for(int i = 0; i < nYN0; i++){ Yv[i].resize(M*N); Nv[i].resize(M*N); } eidc.init(&Lv, Yv, Nv); eidc.CN = 8*M; } CQCGL2dEIDc(int N, double dx, double Mu, double Dr, double Di, double Br, double Bi, double Gr, double Gi) : CQCGL2dEIDc(N, N, dx, dx, Mu, Dr, Di, Br, Bi, Gr, Gi) { } CQCGL2dEIDc(int N, int M, double dx, double dy, double b, double c, double dr, double di) : CQCGL2dEIDc(N, M, dx, dy, -1, 1, b, 1, c, -dr, -di) { } CQCGL2dEIDc(int N, double d, double b, double c, double dr, double di) : CQCGL2dEIDc(N, N, d, d, b, c, dr, di) { } ~CQCGL2dEIDc(){} //////////////////////////////////////////////////////////////////////////////////////////////////// inline void setScheme(std::string x){ int nYN0 = eidc.names.at(eidc.scheme).nYN; eidc.scheme = x; int nYN1 = eidc.names.at(eidc.scheme).nYN; for (int i = nYN0; i < nYN1; i++) { Yv[i].resize(M*N); Nv[i].resize(M*N); } } inline void changeOmega(double w){ Omega = w; L = dcp(Mu, -Omega) - dcp(Dr, Di) * (QKx.square().replicate(1, M).transpose() + QKy.square().replicate(1, N)); L.middleRows(Mplus, Malias) = ArrayXXcd::Zero(Malias, N); L.middleCols(Nplus, Nalias) = ArrayXXcd::Zero(M, Nalias); Lv = Map<VectorXcd>(L.data(), M*N); } inline ArrayXXcd intgC(const ArrayXXcd &a0, const double h, const double tend, const int skip_rate, const int saveFlag, const string fileName){ const int Nt = (int)round(tend/h); const int m = (Nt + skip_rate - 1) / skip_rate; lte.resize(m); ArrayXXcd aa; H5File file; if (0 == saveFlag) file = H5File(fileName, H5F_ACC_TRUNC); /* openFile fails */ else if (1 == saveFlag) aa.resize(Me, Ne*m); ArrayXXcd tu0 = pad(a0); ArrayXcd u0 = Map<ArrayXcd>(tu0.data(), M*N); int ks = 0; auto ss = [this, &ks, &aa, &file, &saveFlag, &tend](ArrayXcd &x, double t, double h, double err){ if( IntPrint > 0 && ks % IntPrint == 0) fprintf(stderr, "%f/%f\n", t, tend); Map<ArrayXXcd> xv(x.data(), M, N); ArrayXXcd uxv = unpad(xv); lte(ks) = err; if(0 == saveFlag){ char groupName[10]; sprintf (groupName, "%.6d", ks); std::string s = "/" + std::string(groupName); Group group(file.createGroup(s)); std:: string DS = s + "/"; writeMatrixXd(file, DS + "ar", uxv.real()); writeMatrixXd(file, DS + "ai", uxv.imag()); } else if (1 == saveFlag){ aa.middleCols((ks)*Ne, Ne) = uxv; } else { // only try to get integeration information } ks++; }; eidc.intgC(nl, ss, 0, u0, tend, h, skip_rate); return aa; } inline ArrayXXcd intg(const ArrayXXcd &a0, const double h, const double tend, const int skip_rate, const int saveFlag, const string fileName){ const int Nt = (int)round(tend/h); const int m = (Nt+skip_rate-1)/skip_rate; Ts.resize(m); hs.resize(m); lte.resize(m); ArrayXXcd aa; H5File file; if (0 == saveFlag) file = H5File(fileName, H5F_ACC_TRUNC); /* openFile fails */ else if (1 == saveFlag) aa.resize(Me, Ne*m); ArrayXXcd tu0 = pad(a0); ArrayXcd u0 = Map<ArrayXcd>(tu0.data(), M*N); int ks = 0; auto ss = [this, &ks, &aa, &file, &saveFlag, &tend](ArrayXcd &x, double t, double h, double err){ if( IntPrint > 0 && ks % IntPrint == 0 ) fprintf(stderr, "%f/%f\n", t, tend); Map<ArrayXXcd> xv(x.data(), M, N); ArrayXXcd uxv = unpad(xv); int m = Ts.size(); if(ks >= m){ Ts.conservativeResize(m+cellSize); hs.conservativeResize(m+cellSize); lte.conservativeResize(m+cellSize); } hs(ks) = h; lte(ks) = err; Ts(ks) = t; if(0 == saveFlag){ char groupName[10]; sprintf (groupName, "%.6d", ks); std::string s = "/" + std::string(groupName); Group group(file.createGroup(s)); std:: string DS = s + "/"; writeMatrixXd(file, DS + "ar", uxv.real()); writeMatrixXd(file, DS + "ai", uxv.imag()); } else if (1 == saveFlag){ if(ks >= m) aa.conservativeResize(Eigen::NoChange, m+cellSize*Ne); aa.middleCols(ks*Ne, Ne) = uxv; } else { // only try to get integeration information } ks++; }; eidc.intg(nl, ss, 0, u0, tend, h, skip_rate); hs.conservativeResize(ks); lte.conservativeResize(ks); Ts.conservativeResize(ks); if(1 == saveFlag) aa.conservativeResize(Eigen::NoChange, ks); return aa; } ArrayXXcd unpad(const ArrayXXcd &v){ int m = v.rows(); int n = v.cols(); assert(m == M && n % N == 0); int s = n / N; ArrayXXcd vt(Me, Ne*s); for (int i = 0; i < s; i++){ vt.middleCols(i*Ne, Ne) << v.block(0, i*N, Mplus, Nplus), v.block(0, i*N+Nplus+Nalias, Mplus, Nminus), v.block(Mplus+Malias, i*N, Mminus, Nplus), v.block(Mplus+Malias, i*N+Nplus+Nalias, Mminus, Nminus) ; } return vt; } ArrayXXcd pad(const ArrayXXcd &v){ int m = v.rows(); int n = v.cols(); assert( n % Ne == 0 && m == Me); int s = n / Ne; ArrayXXcd vp(M, N*s); for (int i = 0; i < s; i++){ vp.middleCols(i*N, N) << v.block(0, i*Ne, Mplus, Nplus), ArrayXXcd::Zero(Mplus, Nalias), v.block(0, i*Ne+Nplus, Mplus, Nminus), ArrayXXcd::Zero(Malias, N), v.block(Mplus, i*Ne, Mminus, Nplus), ArrayXXcd::Zero(Mminus, Nalias), v.block(Mplus, i*Ne+Nplus, Mminus, Nminus) ; } return vp; } }; #endif /* CQCGL2DEIDC_H */ <file_sep>import numpy as np from numpy.linalg import norm import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D from matplotlib.patches import FancyArrowPatch from mpl_toolkits.mplot3d import proj3d class Arrow3D(FancyArrowPatch): """ The 3d arrow class """ def __init__(self, xs, ys, zs, *args, **kwargs): FancyArrowPatch.__init__(self, (0, 0), (0, 0), *args, **kwargs) self._verts3d = xs, ys, zs def draw(self, renderer): xs3d, ys3d, zs3d = self._verts3d xs, ys, zs = proj3d.proj_transform(xs3d, ys3d, zs3d, renderer.M) self.set_positions((xs[0], ys[0]), (xs[1], ys[1])) FancyArrowPatch.draw(self, renderer) def setvalue(self, x, y, z): self._verts3d = x, y, z ################################################## data = np.load('data.npz') aaTilde1 = data['aaTilde1'] veTilde1 = data['veTilde1'] aaTilde2 = data['aaTilde2'] veTilde2 = data['veTilde2'] ee = data['ee'] i1 = 0 i2 = 1 i3 = 2 fig = plt.figure(figsize=(8, 6)) ax = fig.add_subplot(111, projection='3d') ax.plot(aaTilde1[:, i1], aaTilde1[:, i2], aaTilde1[:, i3], 'r') ax.plot(aaTilde2[:, i1], aaTilde2[:, i2], aaTilde2[:, i3], 'g') spa = 60 ratio1 = 5 ah1 = aaTilde1 veIndex1 = 0 nor1 = norm(veTilde1[veIndex1::30], axis=1) nor1.resize((nor1.size, 1)) ae1r = ah1 + veTilde1[veIndex1::30] / nor1 / ratio1 veIndex1 = 1 nor1 = norm(veTilde1[veIndex1::30], axis=1) nor1.resize((nor1.size, 1)) ae1i = ah1 + veTilde1[veIndex1::30] / nor1 / ratio1 ratio2 = 5 ah2 = aaTilde2 veIndex2 = 0 nor2 = norm(veTilde2[veIndex2::30], axis=1) nor2.resize((nor2.size, 1)) ae2r = ah2 + veTilde2[veIndex2::30] / nor2 / ratio2 veIndex2 = 1 nor2 = norm(veTilde2[veIndex2::30], axis=1) nor2.resize((nor2.size, 1)) ae2i = ah2 + veTilde2[veIndex2::30] / nor2 / ratio2 for i in np.arange(0, aaTilde1.shape[0], spa): a1 = Arrow3D([ah1[i, i1], ae1r[i, i1]], [ah1[i, i2], ae1r[i, i2]], [ah1[i, i3], ae1r[i, i3]], mutation_scale=20, lw=1.0, arrowstyle="-|>", color="m") ax.add_artist(a1) a1 = Arrow3D([ah1[i, i1], ae1i[i, i1]], [ah1[i, i2], ae1i[i, i2]], [ah1[i, i3], ae1i[i, i3]], mutation_scale=20, lw=1.0, arrowstyle="-|>", color="b") ax.add_artist(a1) for i in np.arange(0, aaTilde2.shape[0], spa): a2 = Arrow3D([ah2[i, i1], ae2r[i, i1]], [ah2[i, i2], ae2r[i, i2]], [ah2[i, i3], ae2r[i, i3]], mutation_scale=20, lw=1.0, arrowstyle="-|>", color="k") ax.add_artist(a2) a2 = Arrow3D([ah2[i, i1], ae2i[i, i1]], [ah2[i, i2], ae2i[i, i2]], [ah2[i, i3], ae2i[i, i3]], mutation_scale=20, lw=1.0, arrowstyle="-|>", color="c") ax.add_artist(a2) ax.set_xlabel(r'$e_1$', fontsize=25) ax.set_ylabel(r'$e_2$', fontsize=25) ax.set_zlabel(r'$e_3$', fontsize=25) plt.tight_layout(pad=0) plt.show(block=False) <file_sep>/* to comiple: * g++ -O3 test_lorenz.cc -L../../lib -I../../include -I $XDAPPS/eigen/include/eigen3 -std=c++11 -llorenz -ldenseRoutines -lm && ./a.out */ #include "lorenz.hpp" #include <iostream> #include <fstream> using namespace std; using namespace Eigen; using namespace denseRoutines; typedef std::complex<double> dcp; int main(){ switch(1){ case 1: { /* test integrator */ Vector3d x0(VectorXd::Random(3)); Lorenz loz = Lorenz(); // auto tmp = loz.intgj(x0, 0.01, 1000, 1, 1); // savetxt("xx.dat", tmp.first); loz.Rho = 487.115277; loz.B = 0.25; MatrixXd xx = loz.equilibriaIntg(1, 0, 1e-3, 0.001, 8000, 1); savetxt("xx.dat", xx); cout << loz.equilibria() << endl; break; } default: { fprintf(stderr, "please indicate a valid case number \n"); } } return 0; } <file_sep>from py_CQCGL2d import * from personalFunctions import * case = 10 if case == 10: """ test the plot function """ N, d = 1024, 50 Bi, Gi = 0.8, -0.6 cgl = pyCQCGL2d(N, d, -0.1, 0.125, 0.5, 1, Bi, -0.1, Gi, 4) Ns = 10000 skip = 20 cgl.constETDPrint = 200 fileName = 'ex.h5' A0 = 3*centerRand2d(N, N, 0.2, 0.2, True) a0 = cgl.Config2Fourier(A0) aa = cgl.intg(a0, 0.005, Ns, skip, True, fileName) c2dp = CQCGL2dPlot(d, d) # c2dp.oneState(cgl, fileName, 100) c2dp.savePlots(cgl, fileName, range(Ns/skip+1), 'fig3', plotType=2, size=[12, 6]) <file_sep>################################################### # This file contains all the related functions to # investigate the escape rate in Logistic map using # cycle expansion. # please complete the experimental part ################################################### import numpy as np import matplotlib.pyplot as plt from scipy.optimize import fsolve import sympy as sp from personalFunctions import * class Logistic: def __init__(self, A): self.A = A def oneIter(self, x): return self.A * (1.0 - x) * x def multiIters(self, x, n): y = np.zeros(n+1) y[0] = x tmpx = x for i in range(n): tmpx = self.oneIter(tmpx) y[i+1]=tmpx return y def df(self, x): return self.A*(1-2*x) def dfn(self, x): n = np.size(x) multiplier = 1.0 for i in range(n): multiplier *= self.df(x[i]) return multiplier def plotIni(self): fig = plt.figure(figsize=[8, 8]) ax = fig.add_subplot(111) ax.set_xlabel(r'$x_n$', fontsize=30) ax.set_ylabel(r'$x_{n+1}$', fontsize=30) ax.set_xlim([0, 1]) ax.set_ylim([0, 1]) plt.gca().set_aspect('equal', adjustable='box') ax.tick_params(axis='both', which='major', labelsize=20) x = np.linspace(0, 1, 200) y = self.oneIter(x) ax.plot(x, y, lw=2, c='b') ax.plot(x, x, lw=2, c='k', ls='--') return fig, ax def plotEnd(self, fig, ax): ax2d(fig, ax) def plotIter(self, ax, x0, n): x, y = x0, self.oneIter(x0) for i in range(n): print i newy = self.oneIter(y) ax.scatter(x, y, c='g', edgecolors='none', s=100) ax.plot([x, y], [y, y], lw=1.5, c='r') ax.plot([y, y], [y, newy], lw=1.5, c='r') x, y = y, newy if __name__ == '__main__': """ experiment """ case = 10 if case == 10: A = 5.0 order = 4 lm = Logistic(A) f = lambda x : lm.multiIters(x, order)[-1] - x x = fsolve(f, 0.2) xn = lm.multiIters(x, order-1) mp = lm.dfn(xn) np.set_printoptions(precision=16) print lm.multiIters(x, order), mp if case == 20: # Floquet multipliers for the periodic orbits up to length 4 # { {0, 1}, {01}, {001, 011}, {0001, 0011, 0111} } mp = [[-4., 6.0], [-20.0], [-114.954535015, 82.9545350148], [ -684.424135353, 485.09371391, -328.669578465] ] lm = Logistic(6.0) z = sp.Symbol('z') zeta = 1 order = 4 # cycle expansion order for i in range(order): for j in range(np.size(mp[i])): zeta = zeta * (1 - z**(i+1)/np.abs(mp[i][j])) zeta = ( zeta.expand() + sp.O(z**(order+1)) ).removeO() # remove higher orders print "zeta function at order: ", order print zeta # for efficicy, we choose to use np.roots() instead sp.solve() to find the zero points coe = sp.Poly(zeta, z).coeffs() # get the coefficients => a_n, a_{n-1}, ..., a_0 zps = np.roots(coe) # find the zeros points of zeta function leig = np.max(1.0 / zps), # get the leading eigenvalues print leig, np.log(leig) if case == 30: # Floquet multipliers for the periodic orbits up to length 4 # { 0, 1, 01, 001, 011, 0001, 0011, 0111 } # multipliers for A = 6.0 mp = [[-4., 6.0], [-20.0], [-114.954535015, 82.9545350148], [ -684.424135353, 485.09371391, -328.669578465] ] lm = Logistic(6.0) z = sp.Symbol('z') trace = 0 order = 4 for i in range(order): for j in range(np.size(mp[i])): for r in range(order/(i+1)): trace += (i+1) * z**((r+1)*(i+1))/(np.abs(mp[i][j]**(r+1)-1)) C = sp.Poly(trace, z).coeffs() # obtain coefficients of trace: C_n, C_{n-1}, C_1 C = C[::-1] # reverse the order => C_1, C_2,... C_n Q = np.zeros(np.size(C)) Q[0] = C[0] for i in range(order): Q[i] = C[i] for j in range(i): Q[i] -= (C[j]*Q[i-1-j]) Q[i] = Q[i] / np.double(i+1) det = np.append(1.0, -Q) # obtain the coefficients of spectral determinant print det zps = np.roots(det[::-1]) # find the zeros points of zeta function leig = np.max(1.0 / zps), # get the leading eigenvalues print leig, np.log(leig) if case == 35: """ periodic orbits for A = 5.0 """ if case == 40: # Floquet multipliers for the periodic orbits up to length 5 # { {0, 1}, {01}, {001, 011}, {0001, 0011, 0111}, # {00001, 00011, 00101, 00111, 01011, 01111} } # multipliers for A = 5.0 mp = [[-3.0, 5.0], [-11.0], [-49.4264068712, 35.4264068712], [ -240.961389769, 167.507590647, -103.546200878], [-1198.49148617, 827.861204429, 547.72002265, -481.824783312 ,-386.519433432, 313.254476004] ] lm = Logistic(5.0) z = sp.Symbol('z') trace = 0 order = 3 for i in range(order): for j in range(np.size(mp[i])): for r in range(order/(i+1)): trace += (i+1) * z**((r+1)*(i+1))/(np.abs(mp[i][j]**(r+1)-1)) C = sp.Poly(trace, z).coeffs() # obtain coefficients of trace: C_n, C_{n-1}, C_1 C = C[::-1] # reverse the order => C_1, C_2,... C_n Q = np.zeros(np.size(C)) Q[0] = C[0] for i in range(order): Q[i] = C[i] for j in range(i): Q[i] -= (C[j]*Q[i-1-j]) Q[i] = Q[i] / np.double(i+1) det = np.append(1.0, -Q) # obtain the coefficients of spectral determinant print det zps = np.roots(det[::-1]) # find the zeros points of zeta function leig = np.max(1.0 / zps), # get the leading eigenvalues print leig, np.log(leig) <file_sep>#ifndef KSSYM_H #define KSSYM_H #include <eigen3/Eigen/Dense> using Eigen::MatrixXd; using Eigen::Matrix2d; class Kssym { public: const int px; /** @brief SO2 reduction of a sequence of column vectors stored in aa. * * @param[in] aa matrix storing the vectors * @param[out] ang pointer to the theta array. If you do not need * angle information, then just pass NULL to angle * @return the group transformed vectors * */ MatrixXd redSO2(const MatrixXd &aa, double *ang); /** @brief calculate g(th) * aa * * @param[in] aa [n,m] matrix * @param[in] th SO2 group angle * @return rotated matrix */ MatrixXd rotate(const MatrixXd &aa, const double th); /* ------------ constructor/ destructor ----------------- */ Kssym(int p = 1): px(p) {} Kssym(const Kssym &k): px(k.px) {} Kssym & operator=(const Kssym &x ){ return *this; } ~Kssym(){} }; #endif /* KSSYM_H */ <file_sep>import numpy as np import matplotlib.pyplot as plt import h5py from mpl_toolkits.axes_grid1.inset_locator import mark_inset from mpl_toolkits.axes_grid1.inset_locator import zoomed_inset_axes from mpl_toolkits.axes_grid1.inset_locator import inset_axes N = 256; f = h5py.File('/usr/local/home/xiong/svn/DOGS/blog/code/data/req.h5', 'r') valr = f['/req1/valr']; n1= valr.shape[0] vali = f['/req1/vali'] vr = np.zeros((n1,), np.double); vi = np.zeros((n1,), np.double); valr.read_direct(vr); vali.read_direct(vi); ve = vr+1j*vi ia = ve fig = plt.figure(figsize=(8,5)); ax = fig.add_subplot(111) #ax.plot(range(1,2*N+1), ia.real, 'r.') ax.scatter(range(1,2*N+1), ia.real, s=4, c = 'r', marker='o', edgecolor='none') ax.locator_params(nbins=5) ax.set_xlim((0,520)) ax.set_ylim((-35,1)) ax.grid('on') ax2in=inset_axes(ax,width="45%",height="50%",loc=3) ax2in.scatter(np.arange(1,11), ia[:10].real, c=(1,0,0), marker='o', s=22,edgecolors='none') ax2in.set_xlim(0.5,10.5) ax2in.set_ylim(-0.2,0.4) ax2in.yaxis.set_ticks_position('right') ax2in.xaxis.set_ticks_position('top') ax2in.set_xticks((1,3,6,9)) #ax2in.set_yticks((-0.3,-0.2,-0.1,0,0.1)) ax2in.grid('on') mark_inset(ax,ax2in,loc1=1,loc2=2,fc="none") plt.tight_layout(pad=0) plt.show() f.close() <file_sep>#ifndef CQCGL2dREQ_H #define CQCGL2dREQ_H #include "CQCGL2d.hpp" class CQCGL2dReq : public CQCGL2d { public : double tol = 5e-8; double minRD = 0; int maxit = 10; int maxInnIt = 20; double GmresRtol = 1e-6; int GmresRestart = 100; int GmresMaxit = 4; int hookPrint = 1; ArrayXXcd Lu; ArrayXXcd Tx; ArrayXXcd Ty; ArrayXXcd Tp; //////////////////////////////////////////////////////////// CQCGL2dReq(int N, int M, double dx, double dy, double Mu, double Dr, double Di, double Br, double Bi, double Gr, double Gi, int threadNum); CQCGL2dReq(int N, double dx, double Mu, double Dr, double Di, double Br, double Bi, double Gr, double Gi, int threadNum); CQCGL2dReq(int N, int M, double dx, double dy, double b, double c, double dr, double di, int threadNum); CQCGL2dReq(int N, double dx, double b, double c, double dr, double di, int threadNum); ~CQCGL2dReq(); CQCGL2dReq & operator=(const CQCGL2dReq &x); //////////////////////////////////////////////////////////// void calPre(); VectorXd Fx(const VectorXd &x); VectorXd DFx(const VectorXd &x, const VectorXd &dx); std::tuple<ArrayXXcd, double, double, double, double> findReq_hook(const ArrayXXcd &x0, const double wthx0, const double wthy0, const double wphi0); Eigen::Vector3d optReqTh(const ArrayXXcd &a0); }; #endif /* CQCGL2dREQ_H */ <file_sep># usage: make t=*** # or on pace cluster : make t=** pace=** CC = g++ AR = ar OPTIM = -O3 -msse2 -msse4 -march=corei7 INCLUDE = ../../include EIGEN = /usr/local/home/xiong/apps/eigen/include/eigen3 CFLAGS = -std=c++11 -DEIGEN_FFTW_DEFAULT LIB = ../../lib # for pace cluster ifdef pace OPTIM = -O3 EIGEN = /nv/hp16/xding35/data/apps/eigen/include/eigen3 endif #### ifndef t t = int endif ifeq ($(t), int) # for 1d integration SOURCE = CQCGL1d.cc else ifeq ($(t), sub1d) # sub1d integration SOURCE = CQCGL1dSub.cc else ifeq ($(t), req1d) # for REQ code SOURCE = CQCGL1dReq.cc else ifeq ($(t), sub1dreq) # sub1d req SOURCE = CQCGL1dSubReq.cc else ifeq ($(t), rpo1d) # for RPO code SOURCE = CQCGL1dRpo.cc else ifeq ($(t), rpo1dar) # for 1d Rpo with arpack support SOURCE = CQCGL1dRpo_arpack.cc CFLAGS += -I$(XDAPPS)/arpackpp/include # -llapack -larpack -lsuperlu -lopenblas else ifeq ($(t), int2d) # for 2d CQCGL class SOURCE = CQCGL2d.cc else ifeq ($(t), req2d) SOURCE = CQCGL2dReq.cc else ifeq ($(t), ani) SOURCE = CQCGL2dDislin.cc else SOURCE = CQCGL1d.cc endif SHARED = $(addprefix lib, $(addsuffix .so, $(basename $(word 1, $(SOURCE))))) STATIC = $(addprefix lib, $(addsuffix .a, $(basename $(word 1, $(SOURCE))))) all : $(SHARED) # $(STATIC) $(SHARED): $(SOURCE) $(CC) -shared -fpic $(CFLAGS) $(OPTIM) -I$(INCLUDE) -I$(EIGEN) $^ -o $@ $(SOURCE:.cc=.o) : $(SOURCE) $(CC) -c $(CFLAGS) $(OPTIM) -I$(INCLUDE) -I$(EIGEN) $^ $(STATIC): $(SOURCE:.cc=.o) $(AR) crs $@ $^ clean: rm -f *.so *.o *.a move: mv *.so *.a $(LIB) <file_sep>#ifndef CQCGL1DEIDC_H #define CQCGL1DEIDC_H #include "EIDc.hpp" #include <Eigen/Dense> #include <unsupported/Eigen/FFT> class CQCGL1dEIDc { public : typedef std::complex<double> dcp; const int N; /* dimension of FFT */ const double d; /* system domain size */ int Ne, Ndim, Nplus, Nminus, Nalias; double Br, Bi, Gr, Gi, Dr, Di, Mu; double Omega = 0; ArrayXd K, QK; ArrayXcd L; FFT<double> fft; // support MatrixBase but not ArrayBase VectorXd hs; /* time step sequnce */ VectorXd lte; /* local relative error estimation */ VectorXd Ts; /* time sequnence for adaptive method */ int cellSize = 500; struct NL { CQCGL1dEIDc *cgl; dcp B, G; VectorXcd A; NL(CQCGL1dEIDc *cgl) : cgl(cgl), B(cgl->Br, cgl->Bi), G(cgl->Gr, cgl->Gi) { A.resize(cgl->N); } ~NL(){} void operator()(ArrayXXcd &x, ArrayXXcd &dxdt, double t){ Map<VectorXcd> xv(x.data(), x.size()); Map<VectorXcd> dxdtv(dxdt.data(), dxdt.size()); cgl->fft.inv(A, xv); ArrayXcd A2 = A.array() * A.array().conjugate(); A = B * A.array() * A2 + G * A.array() * A2.square(); cgl->fft.fwd(dxdtv, A); dxdtv.segment(cgl->Nplus, cgl->Nalias).setZero(); /* dealias */ } }; NL nl; ArrayXXcd Yv[10], Nv[10]; EIDc eidc; //////////////////////////////////////////////////////////////////////////////////////////////////// CQCGL1dEIDc(int N, double d, double Mu, double Dr, double Di, double Br, double Bi, double Gr, double Gi): N(N), d(d), Mu(Mu), Dr(Dr), Di(Di), Br(Br), Bi(Bi), Gr(Gr), Gi(Gi), nl(this) { Ne = (N/3) * 2 - 1; Ndim = 2 * Ne; Nplus = (Ne + 1) / 2; Nminus = (Ne - 1) / 2; Nalias = N - Ne; // calculate the Linear part K.resize(N,1); K << ArrayXd::LinSpaced(N/2, 0, N/2-1), N/2, ArrayXd::LinSpaced(N/2-1, -N/2+1, -1); QK = 2*M_PI/d * K; L = dcp(Mu, -Omega) - dcp(Dr, Di) * QK.square(); L.segment(Nplus, Nalias).setZero(); int nYN0 = eidc.names.at(eidc.scheme).nYN; // do not call setScheme here. Different. for(int i = 0; i < nYN0; i++){ Yv[i].resize(N, 1); Nv[i].resize(N, 1); } eidc.init(&L, Yv, Nv); } CQCGL1dEIDc(int N, double d, double b, double c, double dr, double di) : CQCGL1dEIDc(N, d, -1, 1, b, 1, c, -dr, -di) { } ~CQCGL1dEIDc(){} //////////////////////////////////////////////////////////////////////////////////////////////////// inline void setScheme(std::string x){ int nYN0 = eidc.names.at(eidc.scheme).nYN; eidc.scheme = x; int nYN1 = eidc.names.at(eidc.scheme).nYN; for (int i = nYN0; i < nYN1; i++) { Yv[i].resize(N, 1); Nv[i].resize(N, 1); } } inline void changeOmega(double w){ Omega = w; L = dcp(Mu, -Omega) - dcp(Dr, Di) * QK.square(); L.segment(Nplus, Nalias).setZero(); } inline ArrayXXd intgC(const ArrayXd &a0, const double h, const double tend, const int skip_rate){ assert( Ndim == a0.size()); ArrayXXcd u0 = R2C(a0); const int Nt = (int)round(tend/h); const int M = (Nt + skip_rate - 1) / skip_rate; ArrayXXcd aa(N, M); lte.resize(M); int ks = 0; auto ss = [this, &ks, &aa](ArrayXXcd &x, double t, double h, double err){ aa.col(ks) = x; lte(ks++) = err; }; eidc.intgC(nl, ss, 0, u0, tend, h, skip_rate); return C2R(aa); } inline ArrayXXd intg(const ArrayXd &a0, const double h, const double tend, const int skip_rate){ assert( Ndim == a0.size()); ArrayXXcd u0 = R2C(a0); const int Nt = (int)round(tend/h); const int M = (Nt+skip_rate-1)/skip_rate; ArrayXXcd aa(N, M); Ts.resize(M); hs.resize(M); lte.resize(M); int ks = 0; auto ss = [this, &ks, &aa](ArrayXXcd &x, double t, double h, double err){ int m = Ts.size(); if (ks >= m ) { Ts.conservativeResize(m+cellSize); aa.conservativeResize(Eigen::NoChange, m+cellSize); // rows not change, just extend cols hs.conservativeResize(m+cellSize); lte.conservativeResize(m+cellSize); } hs(ks) = h; lte(ks) = err; aa.col(ks) = x; Ts(ks++) = t; }; eidc.intg(nl, ss, 0, u0, tend, h, skip_rate); hs.conservativeResize(ks); lte.conservativeResize(ks); Ts.conservativeResize(ks); aa.conservativeResize(Eigen::NoChange, ks); return C2R(aa); } /** @brief transform conjugate matrix to its real form */ ArrayXXd C2R(const ArrayXXcd &v){ int n = v.rows(); int m = v.cols(); assert(N == n); ArrayXXcd vt(Ne, m); vt << v.topRows(Nplus), v.bottomRows(Nminus); return Map<ArrayXXd>((double*)(vt.data()), 2*vt.rows(), vt.cols()); } ArrayXXcd R2C(const ArrayXXd &v){ int n = v.rows(); int m = v.cols(); assert( n == Ndim); Map<ArrayXXcd> vp((dcp*)&v(0,0), Ne, m); ArrayXXcd vpp(N, m); vpp << vp.topRows(Nplus), ArrayXXcd::Zero(Nalias, m), vp.bottomRows(Nminus); return vpp; } }; #endif /* CQCGL1DEIDC_H */ <file_sep>#ifndef EIDR_H #define EIDR_H #include "EID.hpp" class EIDr : public EID<double> { public : //////////////////////////////////////////////////////////////////////////////////////////////////// // constructor and destructor EIDr(){} EIDr(ArrayXd *L, ArrayXXcd *Y, ArrayXXcd *N) : EID<double>(L, Y, N){} EIDr & operator=(const EIDr &x){ return *this; } ~EIDr(){} //////////////////////////////////////////////////////////////////////////////////////////////////// inline ArrayXXcd MUL(const ArrayXd &C, const ArrayXXcd &Y){ return C.matrix().asDiagonal() * Y.matrix(); } inline ArrayXd mean(const Ref<const ArrayXXcd> &x){ return x.rowwise().mean().real(); } /** * @brief calcuate the matrix to do averge of phi(z). */ inline ArrayXXcd ZR(ArrayXd &z){ int M1 = z.size(); ArrayXd K = ArrayXd::LinSpaced(M, 1, M); // 1,2,3,...,M ArrayXXcd r = R * ((K-0.5)/M * dcp(0, M_PI)).exp().transpose(); return z.template cast<std::complex<double>>().replicate(1, M) + r.replicate(M1, 1); } }; #endif /* EIDR_H */ <file_sep>import matplotlib.pyplot as plt import numpy as np import scipy.io as sio from mpl_toolkits.mplot3d import Axes3D from personalFunctions import * from py_ks import * def statisAverage(dis, ang, cell): dis = np.floor(np.log10(dis)/cell) N = len(dis) minD = np.min(dis) maxD = np.max(dis) sumAng = np.zeros((maxD-minD+1, ang.shape[1])) sumNum = np.zeros(maxD - minD + 1) for i in range(N): ix = dis[i] - minD sumNum[ix] += 1 sumAng[ix, :] += ang[i, :] # calcuate the mean value average = np.zeros([maxD-minD+1, ang.shape[1]]) for i in range(len(sumNum)): if sumNum[i] != 0: average[i, :] = sumAng[i, :] / sumNum[i] # form x coordinate x = np.arange(minD, maxD+1) + 0.5 return 10**(x*cell), average def calSpacing(fileName, ppType, ppId, nqr): """ calculate the spacing of points in a rpo/ppo """ a, T, nstp, r, s = KSreadPO(fileName, ppType, ppId) h = T / nstp ks = pyKS(64, h, 22) aa = ks.intg(a, np.int(nstp), nqr) aa = aa[:-1, :] if ppType == 'ppo': aaWhole = ks.half2whole(aa) else: aaWhole = aa aaHat = ks.orbitToSlice(aaWhole)[0] M = aaHat.shape[0] dis = np.zeros(M) for i in range(M): dis[i] = np.linalg.norm(aaHat[(i+1) % M] - aaHat[i]) return dis def setAxis(ax, xl, xr, yl, yr, px, py): ax.set_yscale('log') ax.set_xscale('log') ax.set_ylim([yl, yr]) ax.set_xlim([xl, xr]) # ax.legend(loc='upper left') # ax.set_title('(a)') ax.text(px, py, r'$\sin(\theta)$', fontsize=18) # ax.set_ylabel(r'$\sin(\theta)$', size='large') # ax.set_xlabel(r'$||\Delta \hat{u}||_2$', fontsize=15, labelpad=0) def setAxis2(ax): ax.set_yscale('log') ax.set_xscale('log') # ax.text(px, py, r'$\langle \sin(\theta) \rangle$', fontsize=15) # ax.set_ylabel(r'$< \sin(\theta) >$', size='large') # ax.set_xlabel(r'$||\Delta \hat{u}||_2$', size='large') if __name__ == "__main__": case = 6 if case == 1: """ compare the truncated and untruncated """ fig = plt.figure(figsize=(6, 5)) ax = fig.add_subplot(111) folder = 'cases32modes/case4rpo8x10sT40/' ang = np.sin(np.arccos(np.loadtxt(folder + 'angle'))) dis = np.loadtxt(folder + 'dis') idx = np.loadtxt(folder + 'indexPo') sps = np.loadtxt('cases32modes/spacing/spacing_rpo8.txt') ax.scatter(dis, ang[:, 4], s=7, c='b', marker='o', edgecolor='none') ii = [i for i in range(np.size(dis)) if dis[i] > 4*sps[idx[i]]] ax.scatter(dis[ii], ang[ii, 4], s=7, c='r', marker='s', edgecolor='none') ax.set_yscale('log') ax.set_xscale('log') ax.set_ylim([1e-4, 1e-1]) ax.set_xlim([1e-3, 1e-1]) ax.set_ylabel(r'$\sin(\theta)$', size='large') ax.set_xlabel(r'$||\Delta x||_2$', size='large') fig.tight_layout(pad=0) plt.show() if case == 2: """ plot one good truncated statistic figure """ folder = 'cases32modes/case4rpo4x10sT30/' sps = np.loadtxt('cases32modes/spacing/spacing_rpo4.txt') ang = np.sin(np.arccos(np.loadtxt(folder + 'angle'))) dis = np.loadtxt(folder + 'dis') idx = np.loadtxt(folder + 'indexPo') ii = [i for i in range(np.size(dis)) if dis[i] > 4*sps[idx[i]]] cix = [3, 4, 5] # column index spix = [6, 7, 8, 15] # subspace index colors = ['r', 'b', 'c', 'm'] markers = ['o', 's', 'v', '*'] Num = np.size(cix) fig = plt.figure(figsize=(3, 2)) ax = fig.add_subplot(111) for i in range(Num): ax.scatter(dis[ii], ang[ii, cix[i]], s=7, c=colors[i], marker=markers[i], edgecolor='none', label='1-'+str(spix[i])) ax.set_yscale('log') ax.set_xscale('log') ax.set_ylim([1e-4, 1e-0]) ax.set_xlim([1e-3, 1e-1]) # ax.legend(loc='upper left') # ax.set_title('(a)') ax.text(1.2e-3, 2e-1, r'$\sin(\theta)$', fontsize=18) # ax.set_ylabel(r'$\sin(\theta)$', size='large') # ax.set_xlabel(r'$||\Delta x||_2$', size='large') fig.tight_layout(pad=0) plt.show() if case == 3: """ plot only one shadowing incidence """ folder = 'cases32modes/case4ppo3x10sT30/' sps = np.loadtxt('cases32modes/spacing/spacing_ppo3.txt') ang = np.sin(np.arccos(np.loadtxt(folder + 'angle'))) dis = np.loadtxt(folder + 'dis') idx = np.loadtxt(folder + 'indexPo') No = np.loadtxt(folder + 'No') midx = np.argmax(No) i1 = np.int(np.sum(No[:midx])) i2 = np.int(np.sum(No[:midx+1])) ii = [i for i in range(i1, i2) if dis[i] > 4*sps[idx[i]]] cix = [3, 4, 5] # column index spix = [6, 7, 8, 15] # subspace index colors = ['r', 'b', 'c', 'm'] markers = ['o', 's', 'v', '*'] Num = np.size(cix) fig = plt.figure(figsize=(3, 2)) ax = fig.add_subplot(111) for i in range(Num): ax.scatter(dis[ii], ang[ii, cix[i]], s=10, c=colors[i], marker=markers[i], edgecolor='none', label='1-'+str(spix[i])) ax.set_yscale('log') ax.set_xscale('log') ax.set_ylim([5e-4, 2e-1]) ax.set_xlim([5e-3, 1e-1]) # ax.legend(loc='upper left') # ax.set_title('(a)') ax.text(6e-3, 9e-2, r'$\sin(\theta)$', fontsize=18) # ax.set_ylabel(r'$\sin(\theta)$', size='large') # ax.set_xlabel(r'$||\Delta \hat{u}||_2$', fontsize=15, labelpad=0) fig.tight_layout(pad=0) plt.show() if case == 4: """ plot spacing along periodic orbit """ sps = np.loadtxt('spacing/spacing_rpo6.txt') fig = plt.figure(figsize=(8, 6)) ax = fig.add_subplot(111) ax.semilogy(sps) ax.set_xlabel('index of points along the orbit') ax.set_ylabel('spacing') ax.set_title('rpo6') # ax.set_xlim([0, 2100]) ax.set_ylim([4e-4, 1e-1]) plt.tight_layout(pad=0) plt.show() if case == 5: """ plot the distance structure """ fig = plt.figure(figsize=(6, 4)) ax = fig.add_subplot(111) dis = np.loadtxt('./cases32modes/case4rpo6x10sT30/dis') No = np.loadtxt('./cases32modes/case4rpo6x10sT30/No', dtype=int) ix = 13 # shadowing incidence. h = 0.1 start = No[:ix].sum() # number of point before what we want x = h*np.arange(No[ix]) y = dis[start:start+No[ix]] ax.plot(x, y, c='b', lw=1) # ax.quiver(22, 2e-3, 0, 0.1) # ax.quiver(18, 2e-3, 0, 0.1) ax.text(8.5, 6e-3, 'B') ax.text(16.5, 1.6e-2, 'C') ax.set_ylim([4e-3, 1e-1]) ax.set_yscale('log') ax.set_xlabel('t') ax.set_ylabel(r'$||\Delta x||_2$') fig.tight_layout(pad=0) plt.show() ############################################################ # The new set of data : x5 # ############################################################ if case == 6: """ plot one good truncated statistic figure """ ppType = 'ppo' ppId = 4 sps = calSpacing('../ks22h001t120x64EV.h5', ppType, ppId, 5) folder = 'cases32modes_x5/case4ppo4x5sT30/' ang = np.sin(np.arccos(np.loadtxt(folder + 'angle2'))) dis = np.loadtxt(folder + 'dis') idx = np.loadtxt(folder + 'indexPo') ii = [i for i in range(np.size(dis)) if dis[i] > 4*sps[idx[i]]] """ cix = [3, 4, 5] # column index spix = [6, 7, 8, 15] # subspace index colors = ['r', 'b', 'c', 'm'] markers = ['o', 's', 'v', '*'] Num = np.size(cix) fig = plt.figure(figsize=(3, 2)) ax = fig.add_subplot(111) for i in range(Num): ax.scatter(dis[ii], ang[ii, cix[i]], s=7, c=colors[i], marker=markers[i], edgecolor='none', label='1-'+str(spix[i])) ax.set_yscale('log') ax.set_xscale('log') ax.set_ylim([1e-4, 1e-0]) ax.set_xlim([1e-3, 1e-1]) # ax.legend(loc='upper left') # ax.set_title('(a)') ax.text(1.2e-3, 2e-1, r'$\sin(\theta)$', fontsize=18) # ax.set_ylabel(r'$\sin(\theta)$', size='large') # ax.set_xlabel(r'$||\Delta x||_2$', size='large') fig.tight_layout(pad=0) plt.show() # savez_compressed('rpo4Scatter.npz', dis=dis[ii], ang=ang[ii][:, cix]) """ if case == 7: """ plot only one shadowing incidence """ ppType = 'rpo' ppId = 4 sps = calSpacing('../ks22h001t120x64EV.h5', ppType, ppId, 5) folder = 'cases32modes_x5/case4rpo4x5sT30/' ang = np.sin(np.arccos(np.loadtxt(folder + 'angle'))) dis = np.loadtxt(folder + 'dis') idx = np.loadtxt(folder + 'indexPo') No = np.loadtxt(folder + 'No') # midx = 1 for rpo4; midx = 6 for ppo4; # midx = np.argmax(No) midx = 1 i1 = np.int(np.sum(No[:midx])) i2 = np.int(np.sum(No[:midx+1])) ii = [i for i in range(i1, i2) if dis[i] > 4*sps[idx[i]]] cix = [3, 4, 5] # column index spix = [6, 7, 8, 15] # subspace index colors = ['r', 'b', 'c', 'm'] markers = ['o', 's', 'v', '*'] Num = np.size(cix) fig = plt.figure(figsize=(3, 2)) ax = fig.add_subplot(111) for i in range(Num): ax.scatter(dis[ii], ang[ii, cix[i]], s=10, c=colors[i], marker=markers[i], edgecolor='none', label='1-'+str(spix[i])) setAxis(ax, 7e-3, 1e-1, 1e-3, 5e-1, 8e-3, 2e-1) # for rpo4 # setAxis(ax, 7e-3, 1e-1, 5e-4, 8e-2, 8e-3, 4e-2) # for ppo4 fig.tight_layout(pad=0) plt.show() # savez_compressed('rpo4OneShadow.npz', dis=dis[ii], ang=ang[ii][:, cix]) if case == 8: """ plot the statistic avaerage """ ppType = 'rpo' ppId = 4 sps = calSpacing('../ks22h001t120x64EV.h5', ppType, ppId, 5) folder = 'cases32modes_x5/case4rpo4x5sT30/' ang = np.sin(np.arccos(np.loadtxt(folder + 'angle'))) dis = np.loadtxt(folder + 'dis') idx = np.loadtxt(folder + 'indexPo') ii = [i for i in range(np.size(dis)) if dis[i] > 4*sps[idx[i]]] cell = 0.2 x, aver = statisAverage(dis[ii], ang[ii], 0.2) fig = plt.figure(figsize=(3, 2)) ax = fig.add_subplot(111) for i in range(aver.shape[1]): ax.plot(x, aver[:, i], '-o') setAxis2(ax) fig.tight_layout(pad=0) plt.show() if case == 9: """ calcuate and save the full angle points. modify : ppType, folder, gTpos """ ppType = 'ppo' ppId = 4 gTpos = 3 # work both for ppo4 and rpo4 sps = calSpacing('../ks22h001t120x64EV.h5', ppType, ppId, 5) a, T, nstp, r, s = KSreadPO('../ks22h001t120x64EV.h5', ppType, ppId) h = T / nstp veAll = KSreadFV('../ks22h001t120x64EV.h5', ppType, ppId) ks = pyKS(64, h, 22) aaHat, veHat = ks.orbitAndFvWholeSlice(a, veAll, nstp, ppType, gTpos) folder = 'cases32modes_x5/case4ppo4x5sT30/' ang = np.sin(np.arccos(np.loadtxt(folder + 'angle'))) dis = np.loadtxt(folder + 'dis') idx = np.loadtxt(folder + 'indexPo') difv = np.loadtxt(folder + 'difv') M = len(idx) NFV = 29 ang2 = np.zeros((M, NFV)) for i in range(M): if i % 100 == 0: print "i = ", i d = idx[i] fvs = veHat[d*NFV:(d+1)*NFV, :] for j in range(NFV): ang2[i, j] = pAngle(difv[i], fvs[:j+1].T) ang3 = np.cos(ang2) np.savetxt('ang2.dat', ang3) if case == 10: """ plot the statistic avarage also use more subspaces change: ppType, folder """ ppType = 'ppo' ppId = 4 sps = calSpacing('../ks22h001t120x64EV.h5', ppType, ppId, 5) folder = 'cases32modes_x5/case4ppo4x5sT30/' ang = np.sin(np.arccos(np.loadtxt(folder + 'angle2'))) dis = np.loadtxt(folder + 'dis') idx = np.loadtxt(folder + 'indexPo') ii = [i for i in range(np.size(dis)) if dis[i] > 4*sps[idx[i]]] cell = 0.2 x, aver = statisAverage(dis[ii], ang[ii], 0.2) """ fig = plt.figure(figsize=(3, 2)) ax = fig.add_subplot(111) for i in range(3, 6) + range(6, 11, 2)+range(16, 25, 4): ax.plot(x, aver[:, i], '-o') setAxis2(ax) ax.set_yticks([1e-6, 1e-4, 1e-2, 1e0]) fig.tight_layout(pad=0) plt.show() """ # savez_compressed('rpo4Average.npz', x=x, aver=aver) if case == 11: """ plot the shadowing configuration for one shadowing incidence change : ppType, folder, midx """ ppType = 'ppo' ppId = 4 sps = calSpacing('../ks22h001t120x64EV.h5', ppType, ppId, 5) folder = 'cases32modes_x5/case4ppo4x5sT30/' ang = np.sin(np.arccos(np.loadtxt(folder + 'angle'))) dis = np.loadtxt(folder + 'dis') idx = np.loadtxt(folder + 'indexPo') No = np.loadtxt(folder + 'No') difv = np.loadtxt(folder + 'difv') # midx = 1 for rpo4; midx = 6 for ppo4; # midx = np.argmax(No) midx = 6 i1 = np.int(np.sum(No[:midx])) i2 = np.int(np.sum(No[:midx+1])) # ii = [i for i in range(i1, i2) if dis[i] > 4*sps[idx[i]]] ii = range(i1, i2) cix = [3, 4, 5] # column index spix = [6, 7, 8, 15] # subspace index colors = ['r', 'b', 'c', 'm'] markers = ['o', 's', 'v', '*'] Num = np.size(cix) a, T, nstp, r, s = KSreadPO('../ks22h001t120x64EV.h5', ppType, ppId) h = T / nstp ks = pyKS(64, h, 22) aa = ks.intg(a, nstp, 5) aa = aa[:-1, :] if ppType == 'ppo': aaWhole = ks.half2whole(aa) else: aaWhole = aa aaHat = ks.orbitToSlice(aaWhole)[0] aaErgHat = np.zeros((len(ii), difv.shape[1])) for i in range(len(ii)): aaErgHat[i] = difv[ii[i]] + aaHat[idx[ii[i]]] """ fig = plt.figure(figsize=(3, 2)) ax = fig.add_subplot(111, projection='3d') f1 = 0 f2 = 2 f3 = 3 ax.plot(aaHat[:, f1], aaHat[:, f2], aaHat[:, f3]) ax.plot(aaErgHat[:, f1], aaHat[:, f2], aaHat[:, f3]) for i in range(Num): ax.scatter(dis[ii], ang[ii, cix[i]], s=10, c=colors[i], marker=markers[i], edgecolor='none', label='1-'+str(spix[i])) setAxis(ax, 7e-3, 1e-1, 1e-3, 5e-1, 8e-3, 2e-1) # for rpo4 # setAxis(ax, 7e-3, 1e-1, 5e-4, 8e-2, 8e-3, 4e-2) # for ppo4 fig.tight_layout(pad=0) plt.show() """ <file_sep>import numpy as np from matplotlib import pyplot as plt from matplotlib import animation N = 1024; M = 10000; AA = np.fromfile('aa.bin', np.double, 2*N*M).reshape(M,2*N).T; Ar = AA[0::2,:]; Ai = AA[1::2, :]; Ama = abs(Ar+1j*Ai); fig = plt.figure(figsize=(8,6)); ax = fig.add_subplot(111) ax.set_ylim((-0.5, 3.5)) ax.set_xlabel('L'); ax.set_ylabel('|A|'); ax.grid('on', color ='w', lw = 1); fig.tight_layout(pad = 0) ax.patch.set_facecolor('black') x = np.linspace(0, 50, N, endpoint=False) line, = ax.plot(x, Ama[:,0], c=(0,1,0) ,lw=1.5, label = '0'); Maxf = 7000 ; def animate(i): y = Ama[:,i]; line.set_ydata(y); # only use the integer part to get rid of flashes of legend. line.set_label('time : ' + str( int((i*0.005+500)*10)/10.0 ) ); ax.legend(fancybox=True) return line, ax; # ax also needs be updated in order to update legend. anim = animation.FuncAnimation(fig, animate, frames=Maxf, interval=0 , blit=False, repeat=False); anim.save('cqcgl1d.mp4', dpi=100, fps=30, extra_args=['-vcodec', 'libx264']) #plt.show() <file_sep>/* compile command: * mex CXXFLAGS='-std=c++0x -fPIC -O3' intg2M1.cpp ../ksint.cc ../ksintM1.cc -I../../../include -I$XDAPPS/eigen/include/eigen3 -lfftw3 * */ #include "ksintM1.hpp" #include "mex.h" #include "matrix.h" #include <cmath> #include <cstring> #include <cassert> #include <Eigen/Dense> using namespace Eigen; /* ks 1st mode slice integrator without Jacobian */ static std::pair<ArrayXXd, ArrayXd> intg2M1(double *a0, int N, double h, double T, int np, double d){ KSM1 ks(N+2, h, d); Map<ArrayXd> v0(a0, N); return ks.intg2(v0, T, np); } void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[]){ int np = 1; double d = 22; switch (nrhs) { case 5 : d = mxGetScalar(prhs[4]); case 4 : np = mxGetScalar(prhs[3]); case 3 : { // get the pointer and the size of input double *a0 = mxGetPr(prhs[0]); mwSize N = mxGetM(prhs[0]); mwSize M = mxGetN(prhs[0]); assert( N % 2 == 0 && M = 1 ); double h = mxGetScalar(prhs[1]); double T = mxGetScalar(prhs[2]); std::pair<ArrayXXd, ArrayXd> tmp = intg2M1(a0, N, h, T, np, d); int m = tmp.first.cols(); plhs[0] = mxCreateDoubleMatrix(N, m, mxREAL); plhs[1] = mxCreateDoubleMatrix(m, 1, mxREAL); memcpy(mxGetPr(plhs[0]), &tmp.first(0,0), m*N*sizeof(double)); memcpy(mxGetPr(plhs[1]), &tmp.second(0), m*sizeof(double)); break; // very import } default: mexErrMsgIdAndTxt( "KS_integrator:inputMismatch", " 3 =< #input <=5. Example: intg(a0, h, nstp, np, d) \n"); } } <file_sep>from personalFunctions import * def setAxis(ax, xr, xlabel=r'$t$', ylabel=r'$\lambda_k(t)$'): # ax.get_yaxis().set_tick_params(which='both', direction='in', pad = -20) # ax.get_xaxis().set_tick_params(which='both', direction='in', pad = -20) # ax.set_xlabel(xlabel, fontsize=20) # ax.set_ylabel(ylabel, fontsize=20) ax.set_xlim([0, xr]) ax.set_xticks([0, xr-1]) ax.set_xticklabels([0, r'$T_p$'], fontsize=13) if __name__ == '__main__': case = 10 if case == 1: """ plot the local Flouqet exponents of ppo1 """ # load data ksp = KSplot() a, T, nstp, r, s = ksp.readPO('../ks22h001t120x64EV.h5', 'ppo', 1) expand = np.log(np.loadtxt('./ppo/FVexpand1.dat')) / (5 * T / nstp) fig = plt.figure(figsize=[3, 2]) ax = fig.add_subplot(111) ax.plot(expand[0], lw=1.5, ls='-') ax.plot(expand[2], lw=1.5, ls='-') ax.plot(expand[3], lw=1.5, ls='-') ax.plot(expand[4], lw=1.5, ls='-') ax.plot(expand[5], lw=1.5, ls='-') ax.plot(expand[7], lw=1.5, ls='-') ax.plot(expand[8], lw=1.5, ls='-') ax.plot(expand[9], lw=1.5, ls='-') ax.text(expand.shape[1]/50, 0.4, r'$\lambda_k(t)$', fontsize=18) ax.text(expand.shape[1]/3, -0.8, r'$k=1, 3, 4, 5, 6, 8$', fontsize=18) ax.text(expand.shape[1]/2, -1.8, r'$k=9, 10$', fontsize=18) setAxis(ax, expand.shape[1]) ax.set_ylim([-2.5, 1]) ax.set_yticks([-2, -1, 0, 1]) fig.tight_layout(pad=0) plt.show() if case == 10: """ plot the local Flouqet exponents of rpo1 """ ksp = KSplot() a, T, nstp, r, s = ksp.readPO('../ks22h001t120x64EV.h5', 'rpo', 1) expand = np.log(np.loadtxt('./rpo/FVexpand1.dat')) / (5 * T / nstp) fig, ax = pl2d(labs=[r'$t$', r'$\lambda_j(u(t))$'], axisLabelSize=25, tickSize=20) ax.plot(expand[0], lw=1.5, ls='-', label=r'$j=1$') ax.plot(expand[1], lw=1.5, ls='-', label=r'$j=2$') ax.plot(expand[2], lw=1.5, ls='-', label=r'$j=3$') ax.plot(expand[3], lw=1.5, ls='-', label=r'$j=4$') ax.plot(expand[4], lw=1.5, ls='-') ax.plot(expand[5], lw=1.5, ls='-', label=r'$j=5, 6$') ax.plot(expand[6], lw=1.5, ls='-', label=r'$j=7$') ax.plot(expand[7], lw=1.5, ls='-', label=r'$j=8$') ax.plot(expand[8], lw=1.5, ls='-') ax.plot(expand[9], lw=1.5, ls='-', label=r'$j=9, 10$') xr = expand.shape[1] ax.set_xlim([0, xr]) ax.set_xticks([0, xr-1]) ax.set_xticklabels([0, r'$T_p$'], fontsize=20) # ax.set_ylim([-2.5, 1]) ax.set_yticks([-2.5, -1, 0, 0.5]) ax.legend(loc='best', ncol=3, fontsize=20) fig.tight_layout(pad=0) plt.show(block=False) if case == 2: """ plot $\lambda_i(t) -\lambda$ for a small subset """ a, T, nstp, r, s = KSreadPO('../ks22h001t120x64EV.h5', 'ppo', 1) expand = np.log(np.loadtxt('./ppo/FVexpand1.dat')) / (5 * T / nstp) fe = KSreadFE('../ks22h001t120x64EV.h5', 'ppo', 1)[0] fig = plt.figure(figsize=[3, 2]) ax = fig.add_subplot(111) ix = [8, 9, 10, 11] for i in ix: ax.plot(expand[i]-fe[i], lw=1.5, ls='-', label='k='+str(i+1)) setAxis(ax, expand.shape[1], ylabel=r'$\lambda_k(t) - \lambda_k$') ax.set_yticks([-0.03, 0, 0.03, 0.06]) ax.legend(loc='best', fontsize=13, frameon=False) fig.tight_layout(pad=0) plt.show() # savez_compressed('ppo1', T=T, nstp=nstp, fe=fe) if case == 3: """ plot $\lambda_i(t) -\lambda$ for the remaining set """ a, T, nstp, r, s = KSreadPO('../ks22h001t120x64EV.h5', 'ppo', 1) expand = np.log(np.loadtxt('./ppo/FVexpand1.dat')) / (5 * T / nstp) fe = KSreadFE('../ks22h001t120x64EV.h5', 'ppo', 1)[0] fig = plt.figure(figsize=[3, 2]) ax = fig.add_subplot(111) ix = [12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26] for i in ix: ax.plot(expand[i]-fe[i], lw=1.5, ls='-') ax.arrow(expand.shape[1]/20, 0.009, 0, -0.003, width=20, head_length=0.001, head_width=80, fc='k') setAxis(ax, expand.shape[1], ylabel=r'$\lambda_k(t) - \lambda_k$') ax.set_yticks([-0.008, -0.002, 0.004, 0.01]) fig.tight_layout(pad=0) plt.show() if case == 4: """ The partial hyperbolicity degree """ pn = np.zeros(29) for i in range(1, 201): print i expand = np.loadtxt('./ppo/FVexpand' + str(i) + '.dat') for j in range(1, 30): x = np.amin(expand[:j], axis=0) - np.amax(expand[j:], axis=0) if np.amin(x) > 0: pn[j-1] += 1 rn = np.zeros(29) for i in range(1, 201): print i expand = np.loadtxt('./rpo/FVexpand' + str(i) + '.dat') for j in range(1, 30): x = np.amin(expand[:j], axis=0) - np.amax(expand[j:], axis=0) if np.amin(x) > 0: rn[j-1] += 1 ph = pn + rn # np.savetxt('ph.dat', ph) fig = plt.figure(figsize=[3, 3]) ax = fig.add_subplot(111) ax.scatter(range(1, 30), ph, s=30, facecolor='b', edgecolors='none') ax.set_xticks(range(0, 31, 4)) ax.set_xlim([0, 30]) ax.set_ylim([-50, 450]) # ax.set_xlabel('k', fontsize=20) ax.grid('on') fig.tight_layout(pad=0) plt.show() <file_sep>#include "ksintM1.hpp" #include <cmath> using Eigen::NoChange; /* ================================================== * Class : KS 1st mode integrator * ==================================================*/ /* -------------------- constructors -------------------- */ KSM1::KSM1(int N, double h, double d) : KS(N, h, d) {} KSM1::KSM1(const KSM1 &x) : KS(x) {} KSM1 & KSM1::operator=(const KSM1 &x) { return *this; } /* -------------------- member functions -------------------- */ /** @brief calculate the nonlinear term * (a_1 - 1)*(q_k^2 - q_k^4)a_k - iq_k/2 fft(ifft^2(a)) + iq_k/2*a*real(fft(ifft(a))_1) **/ void KSM1::NL(KSfft &f){ double a1hat = f.vc1(1).real(); ifft(f); f.vr2 = f.vr2 * f.vr2; fft(f); f.vc3 = (a1hat - 1)*L*f.vc1 + a1hat*G*f.vc3 - f.vc3(1).real()*G*f.vc1; } #if 0 void KSM1::jNL(KSfft &f){ double a1 = f.vc1(1,0).real(); ArrayXd y1 = f.vc1.block(1,1,1,N-2).real(); ifft(f); ArrayXd tmp = f.vr2.col(0); f.vr2 = tmp.matrix().asDiagonal()*f.vr2.matrix(); fft(f); double fv1 = f.vc3.row(1).real(); /* (q_k^2-q_k^4)*a - iq_k/2*\sum a_m a_{k-m} */ f.vc3.col(0) = L*f.vc1.col(0) + G*f.vc3.col(0); /* (q_k^2-q_k^4)*y - iq_k/2*\sum a_m y_{k-m} */ f.vc3.rightCols(N-2) = L*f.vc1.rightCols(N-2) + 2.0*G*f.vr3.rightCols(N-2); f.vc3.rightCols(N-2) = (a1-1)*f.vc3.rightCols(N-2) - G * f.vc1.rightCols(N-2)*fv1(0) +y1*f.vr3.col(0) - 2.0*G*fv1.tail(N-2); f.vc3.col(0) = a1*f.vc3.col(0) - L*f.vc1.col(0) -fv1(0)*G*f.vc1; } #endif /** @brief Integrator on the 1st mode slice. * * @return the trajectory (first element of the return pair) and the time * in the full state space (second element of the return pair) */ std::pair<ArrayXXd, ArrayXd> KSM1::intg(const ArrayXd &a0, size_t nstp, size_t np){ if( N-2 != a0.rows() ) {printf("dimension error of a0\n"); exit(1);} Fv.vc1 = R2C(a0); Fv.vc1(1) = dcp(Fv.vc1(1).real(), 0.0); //force the imag of 1st mode to be zero ArrayXXd aa(N-2, nstp/np+1); aa.col(0) = a0; ArrayXd tt(nstp/np+1); tt(0) = 0.0; double t = 0; for(size_t i = 1; i < nstp +1; i++){ NL(Fv); Fa.vc1 = E2*Fv.vc1 + Q*Fv.vc3; NL(Fa); Fb.vc1 = E2*Fv.vc1 + Q*Fa.vc3; NL(Fb); Fc.vc1 = E2*Fa.vc1 + Q*(2.0*Fb.vc3 - Fv.vc3); NL(Fc); Fv.vc1 = E*Fv.vc1 + Fv.vc3*f1 + 2.0*(Fa.vc3+Fb.vc3)*f2 + Fc.vc3*f3; t += Fv.vc1(1).real() * h; if( 0 == i%np ) { aa.col(i/np) = C2R(Fv.vc1); tt(i/np) = t; } } return std::make_pair(aa, tt); } /** @brief Integrator on the 1st mode slice. It will integrate KS on slice * until the corresponding time lapse in full state is approximate T. * Therefore, the result's dimension depends. * * @param[in] T time to be integrated in the full state space. * */ std::pair<ArrayXXd, ArrayXd> KSM1::intg2(const ArrayXd &a0, double T, size_t np){ const size_t cell = 1000; if( N-2 != a0.rows() ) {printf("dimension error of a0\n"); exit(1);} Fv.vc1 = R2C(a0); Fv.vc1(1) = dcp(Fv.vc1(1).real(), 0.0); //force the imag of 1st mode to be zero ArrayXXd aa(N-2, cell); aa.col(0) = a0; ArrayXd tt(cell); tt(0) = 0.0; double t = 0; size_t i = 1; // record the integration steps. size_t ix = 1; // record the #columns of aa. double lastT = 0; // record the last time recorded in tt. while(lastT < T){ NL(Fv); Fa.vc1 = E2*Fv.vc1 + Q*Fv.vc3; NL(Fa); Fb.vc1 = E2*Fv.vc1 + Q*Fa.vc3; NL(Fb); Fc.vc1 = E2*Fa.vc1 + Q*(2.0*Fb.vc3 - Fv.vc3); NL(Fc); Fv.vc1 = E*Fv.vc1 + Fv.vc3*f1 + 2.0*(Fa.vc3+Fb.vc3)*f2 + Fc.vc3*f3; t += Fv.vc1(1).real() * h; if( 0 == i%np ) { int m = aa.cols(); if(i/np > m - 1) { aa.conservativeResize(NoChange, m+cell); // rows not change, just extend cols tt.conservativeResize(m+cell); } aa.col(i/np) = C2R(Fv.vc1); tt(i/np) = t; lastT = t; ix++; } i++; } return std::make_pair(aa.leftCols(ix), tt.head(ix)); } #if 0 KSM1::intgj(const ArrayXd a0, size_t nstp, size_t np, size_t nqr){ if( N-2 != a0.rows() ) {printf("dimension error of a0\n"); exit(1);} ArrayXXd v0(N-2, N-1); v0 << a0, MatrixXd::Identity(N-2, N-2); jFv.vc1 = R2C(v0); ArrayXXd aa(N-2, nstp/np+1); aa.col(0) = a0; ArrayXXd daa((N-3)*(N-3), nstp/nqr); for(size_t i = 1; i < nstp + 1; i++){ } } #endif <file_sep>from py_CQCGL1dSub import * from py_CQCGL1d import * from cglHelp import * ################################################################################ # compare req in subspace and in full space ################################################################################ case = 10 if case == 10: """ compare eigenvalues for symmetric subspace and full space """ N, d = 1024, 50 Bi, Gi = 2, -5 index = 1 cgl = pyCQCGL1dSub(N, d, -0.1, 0.125, 0.5, 1, Bi, -0.1, Gi, 0) req = CQCGLreq(cgl) a0, wth0, wphi0, err0, e0, v0 = req.read('../../data/cgl/reqBiGiEV.h5', req.toStr(Bi, Gi, index), flag=2) e1 = e0 a0, wth0, wphi0, err0, e0, v0 = req.read('../../data/cgl/reqsubBiGiEV.h5', req.toStr(Bi, Gi, index), flag=2, sub=True) e2 = e0 print e1[:10] print e2[:10] if case == 20: """ compare eigenvectors """ N, d = 1024, 50 Bi, Gi = 2, -2 index = 1 cgl = pyCQCGL1d(N, d, -0.1, 0.125, 0.5, 1, Bi, -0.1, Gi, 0) cglsub = pyCQCGL1dSub(N, d, -0.1, 0.125, 0.5, 1, Bi, -0.1, Gi, 0) req, reqsub = CQCGLreq(cgl), CQCGLreq(cglsub), cp, cpsub = CQCGLplot(cgl), CQCGLplot(cglsub) a0, wth0, wphi0, err0, e0, v0 = req.read('../../data/cgl/reqBiGiEV.h5', req.toStr(Bi, Gi, index), flag=2) cp.oneConfig(v0[0].real * cgl.N) cp.oneConfig(v0[0].imag * cgl.N) cp.oneConfig(v0[1].real * cgl.N) cp.oneConfig(v0[1].imag * cgl.N) a1, wth1, wphi1, err1, e1, v1 = reqsub.read('../../data/cgl/reqsubBiGiEV.h5', req.toStr(Bi, Gi, index), sub=True,flag=2) cpsub.oneConfig(v1[0].real * cgl.N) cpsub.oneConfig(v1[0].imag * cgl.N) if case == 30: """ same as case 20, but sperate real/imag part """ N, d = 1024, 50 Bi, Gi = 2, -2 index = 1 cgl = pyCQCGL1d(N, d, -0.1, 0.125, 0.5, 1, Bi, -0.1, Gi, 0) cglsub = pyCQCGL1dSub(N, d, -0.1, 0.125, 0.5, 1, Bi, -0.1, Gi, 0) req, reqsub = CQCGLreq(cgl), CQCGLreq(cglsub), cp, cpsub = CQCGLplot(cgl), CQCGLplot(cglsub) a0, wth0, wphi0, err0, e0, v0 = req.read('../../data/cgl/reqBiGiEV.h5', req.toStr(Bi, Gi, index), flag=2) plot1dfig(cgl.Fourier2Config(v0[0].real * cgl.N).real) plot1dfig(cgl.Fourier2Config(v0[0].real * cgl.N).imag) plot1dfig(cgl.Fourier2Config(v0[0].imag * cgl.N).real) plot1dfig(cgl.Fourier2Config(v0[0].imag * cgl.N).imag) plot1dfig(cgl.Fourier2Config(v0[2].real * cgl.N).real) plot1dfig(cgl.Fourier2Config(v0[2].real * cgl.N).imag) plot1dfig(cgl.Fourier2Config(v0[2].imag * cgl.N).real) plot1dfig(cgl.Fourier2Config(v0[2].imag * cgl.N).imag) a1, wth1, wphi1, err1, e1, v1 = reqsub.read('../../data/cgl/reqsubBiGiEV.h5', req.toStr(Bi, Gi, index), sub=True,flag=2) plot1dfig(cglsub.Fourier2Config(v1[0].real * cglsub.N).real) plot1dfig(cglsub.Fourier2Config(v1[0].real * cglsub.N).imag) plot1dfig(cglsub.Fourier2Config(v1[0].imag * cglsub.N).real) plot1dfig(cglsub.Fourier2Config(v1[0].imag * cglsub.N).imag) <file_sep>from py_ks import * from personalFunctions import * def magvalue(x): return np.abs(x[0::2] + 1j * x[1::2]) case = 4 if case == 1: f = h5py.File('../../data/myN32/ks22h02t100EV.h5') ve = np.array(f['/ppo/1/ve']).T N, M = ve.shape N = np.int(np.sqrt(N)) ve = ve[:, 0] ve.resize(N, N) fig = plt.figure(figsize=(8, 4)) ax = fig.add_subplot(111) ax.plot(range(1, N/2+1), magvalue(ve[:, 0]), '-o', c='r', label=r'$V_{1r}$') ax.plot(range(1, N/2+1), magvalue(ve[:, 1]), '-s', c='b', label=r'$V_{1i}$') ax.plot(range(1, N/2+1), magvalue(ve[:, 7]), '-^', c='g', label=r'$V_{8}$') ax.plot([4.5, 4.5], [0, 0.7], '--', c='k', lw=3) ax.grid('on') ax.set_xlabel('Fourier mode index') ax.set_ylabel('amplitute') ax.legend() plt.tight_layout(pad=0) plt.show() # The black dashed line separate the physical (first 8) and transient modes ( 9 to 30). # since # $$ # u(x_{n},t)=\!\!\sum_{k=-N/2+1}^{N/2}\!\!a_{k}(t)e^{iq_{k}x_{n}} # $$ # Denote $a_k = b_k + ic_k$, so we has state space $[b_1, c_1, b_2, c_2, \cdots]$. X-axis is the exponent index of this state space ### Plot the unphysical Floquet vectors # In[63]: fig = plt.figure(figsize=(8,4)) ax = fig.add_subplot(111) ax.plot(range(1, N/2+1), magvalue(ve[:, 8]), '-o', c='r', label=r'$V_{9}$') ax.plot(range(1, N/2+1), magvalue(ve[:, 17]), '-s', c='b', label=r'$V_{18}$') ax.plot(range(1, N/2+1), magvalue(ve[:, 24]), '-v', c='c', label=r'$V_{25}$') ax.plot(range(1, N/2+1), magvalue(ve[:, 29]), '-^', c='g', label=r'$V_{30}$') ax.plot([4.5, 4.5], [0,1], '--', c='k', lw=3) ax.grid('on') ax.set_xlabel('Fourier mode index') ax.set_ylabel('amplitute') ax.legend(loc='best') plt.tight_layout(pad=0) plt.show() if case == 2: """ plot Fvs for N = 64 """ f = h5py.File('../../data/myN32/ks22h02t100EV.h5') ve = np.array(f['/ppo/1/ve']).T N, M = ve.shape N = np.int(np.sqrt(N)) ve = ve[:, 0] ve.resize(N, N) fig = plt.figure(figsize=(8, 4)) ax = fig.add_subplot(111) ax.plot(range(1, N/2+1), magvalue(ve[:, 0]), '-o', c='r', label=r'$V_{1r}$') ax.plot(range(1, N/2+1), magvalue(ve[:, 1]), '-s', c='b', label=r'$V_{1i}$') ax.plot(range(1, N/2+1), magvalue(ve[:, 7]), '-^', c='g', label=r'$V_{8}$') ax.plot([4.5, 4.5], [0, 0.7], '--', c='k', lw=3) ax.grid('on') ax.set_xlabel('Fourier mode index') ax.set_ylabel('amplitute') ax.legend() plt.tight_layout(pad=0) plt.show() # The black dashed line separate the physical (first 8) and transient modes ( 9 to 30). # since # $$ # u(x_{n},t)=\!\!\sum_{k=-N/2+1}^{N/2}\!\!a_{k}(t)e^{iq_{k}x_{n}} # $$ # Denote $a_k = b_k + ic_k$, so we has state space $[b_1, c_1, b_2, c_2, \cdots]$. X-axis is the exponent index of this state space ### Plot the unphysical Floquet vectors # In[63]: fig = plt.figure(figsize=(8,4)) ax = fig.add_subplot(111) ax.plot(range(1, N/2+1), magvalue(ve[:, 8]), '-o', c='r', label=r'$V_{9}$') ax.plot(range(1, N/2+1), magvalue(ve[:, 17]), '-s', c='b', label=r'$V_{18}$') ax.plot(range(1, N/2+1), magvalue(ve[:, 24]), '-v', c='c', label=r'$V_{25}$') ax.plot(range(1, N/2+1), magvalue(ve[:, 29]), '-^', c='g', label=r'$V_{30}$') ax.plot([4.5, 4.5], [0,1], '--', c='k', lw=3) ax.grid('on') ax.set_xlabel('Fourier mode index') ax.set_ylabel('amplitute') ax.legend(loc='best') plt.tight_layout(pad=0) plt.show() if case == 3: """ plot the orbit ppo1 for N = 64 """ N = 64 f = h5py.File('../../data/ks22h001t120x64EV.h5') pp = '/ppo/1/' T = np.array(f[pp + 'T'])[0] nstp = np.int(np.array(f[pp + 'nstp'])[0]) a0 = np.array(f[pp + 'a']) h = T / nstp ks = pyKS(N, h, 22) aa = ks.intg(a0, nstp*4, 10) KSplotColorMapOrbit(aa, [0, 22, 0, 10.25*4]) if case == 4: """ plot the orbit rpo1 for N = 64 """ N, L = 64, 22 ks = pyKS(N, L) ksp = KSplot(ks) poFile = '../../data/ks22h001t120x64EV.h5' a0, T, nstp, r, s = ksp.readPO(poFile, 'rpo', 1) h = T / nstp aa = ks.intg(a0, h, nstp*2, 10) ksp.config(aa, [0, 22, 0, 16.31*2]) if case == 5: """ plot the Fv of ppo1 for N = 64 """ N = 64 Ndim = N - 2 f = h5py.File('../../data/ks22h001t120x64EV.h5') pp = '/ppo/1/' T = np.array(f[pp + 'T'])[0] nstp = np.int(np.array(f[pp + 'nstp'])[0]) a0 = np.array(f[pp + 'a']) h = T / nstp veAll = np.array(f[pp + 've']) Nve = 30 veid = 30 ve = veAll[:, (veid-1)*Ndim:veid*Ndim] KSplotColorMapOrbit(ve, [0, 22, 0, 10.25], size=[2.5, 6], save=True, name='ppo1Fv30_64', axisOn=False, barOn=False) if case == 6: """ plot the Fv of rpo1 for N = 64 """ N = 64 Ndim = N - 2 f = h5py.File('../../data/ks22h001t120x64EV.h5') pp = '/rpo/1/' T = np.array(f[pp + 'T'])[0] nstp = np.int(np.array(f[pp + 'nstp'])[0]) a0 = np.array(f[pp + 'a']) h = T / nstp veAll = np.array(f[pp + 've']) Nve = 30 veid = 30 ve = veAll[:, (veid-1)*Ndim:veid*Ndim] KSplotColorMapOrbit(ve, [0, 22, 0, 16.31], size=[2.5, 6], save=True, name='rpo1Fv30_64', axisOn=False, barOn=False) if case == 7: """ plot the Fv power graph of ppo1/rpo1 for N = 64 """ N = 64 Ndim = N - 2 f = h5py.File('../../data/ks22h001t120x64EV.h5') pp = '/ppo/1/' T = np.array(f[pp + 'T'])[0] nstp = np.int(np.array(f[pp + 'nstp'])[0]) a0 = np.array(f[pp + 'a']) h = T / nstp veAll = np.array(f[pp + 've']) Nve = 30 ve = veAll[0] fig = plt.figure(figsize=(5, 4)) ax = fig.add_subplot(111) ax.set_xlabel('k') ax.set_ylabel('power') for i in range(Nve): x = range(1, Nve/2+1) y = ve[Ndim*i:Ndim*(i+1)] y = y[::2]**2 + y[1::2]**2 y = y[:Nve/2] if i < 8: ax.plot(x, y, 'r-o', lw=1) if i >= 8: ax.plot(x, y, 'b-o', lw=1) # ax.set_yscale('log') fig.tight_layout(pad=0) plt.show() if case == 20: """ Have a look at the Floquet vectors obtained from PED for N = 64 KS. Some of them do not converge, so maybe I can visulize the error """ N = 64 Ndim = N - 2 ppId = 33 poType = 'rpo' # fe, fv = KSreadFEFV('../../data/ks22h001t120x64EV.h5', 'rpo', ppId) fe, fv = KSreadFEFV('../../data/ex.h5', 'rpo', ppId) vs = fv[0].reshape(30, Ndim) plot1dfig(vs[29]) if case == 30: """ Have a look at some left eigenvector of periodic orbits of KS. """ N = 64 Ndim = N - 2 ppId = 1 poType = 'ppo' f1 = '../../data/ks22h001t120x64EV.h5' fe1, fv1 = KSreadFEFV(f1, poType, ppId) fe, fv = KSreadFEFV('../../data/left.h5', poType, ppId) vs1 = fv1[0].reshape(30, Ndim) vs = fv[0].reshape(30, Ndim) plot1dfig(vs1[9]) plot1dfig(vs[9]) a0, T, nstp, r, s = KSreadPO(f1, poType, ppId) h = T / nstp ks = pyKS(N, h, 22) aa = ks.intg(a0, nstp, 5) KSplotColorMapOrbit(aa, [0, 22, 0, T]) ix = 3 v1 = fv1[:, 62*ix:62*(ix+1)] v = fv[:, 62*ix:62*(ix+1)] KSplotColorMapOrbit(v, [0, 22, 0, T]) KSplotColorMapOrbit(v1, [0, 22, 0, T]) <file_sep>#ifndef KSPO_H #define KSPO_H #include <vector> #include <tuple> #include <Eigen/Dense> #include <Eigen/Sparse> #include "ksint.hpp" #include "myH5.hpp" #include "ped.hpp" using namespace H5; class KSPO : public KS{ public: ////////////////////////////////////////////////// typedef Eigen::SparseMatrix<double> SpMat; typedef Eigen::Triplet<double> Tri; ////////////////////////////////////////////////// KSPO(int N, double d); KSPO & operator=(const KSPO &x); ~KSPO(); ////////////////////////////////////////////////// static std::string toStr(string ppType, int id); static std::string toStr(double domainSize, string ppType, int id); static std::tuple<VectorXd, double, int, double, double> read(H5File &file, const std::string groupName, const bool isRPO); static void write(H5File &file, const std::string groupName, const bool isRPO, const ArrayXd &a, const double T, const int nstp, const double theta, const double err); static MatrixXd readE(H5File &file, const std::string groupName); static MatrixXd readV(H5File &file, const std::string groupName); static void writeE(H5File &file, const std::string groupName, const MatrixXd &e); static void writeV(H5File &file, const std::string groupName, const MatrixXd &v); static void move(H5File &fin, std::string gin, H5File &fout, std::string gout, int flag = 0); ////////////////////////////////////////////////// VectorXd MFx(const VectorXd &x, const int nstp, const bool isRPO); std::tuple<SpMat, SpMat, VectorXd> multiCalJJF(const VectorXd &x, int nstp, const bool isRPO); std::tuple<MatrixXd, MatrixXd, VectorXd> calJJF(const VectorXd &x, int nstp, const bool isRPO); std::tuple<ArrayXXd, double, int> findPO_LM(const ArrayXXd &a0, const bool isRPO, const int nstp, const double tol, const int maxit, const int innerMaxit); std::pair<MatrixXd, MatrixXd> calEV(const bool isRPO, const ArrayXd &a0, const double T, const int nstp, const double theta, const double tol, const int MaxN, const int trunc); }; template<class Mat> class KSPO_JJF { public : KSPO *ks; bool isRPO; int nstp; KSPO_JJF(KSPO *ks, int nstp, bool isRPO) : ks(ks), nstp(nstp), isRPO(isRPO){} std::tuple<MatrixXd, MatrixXd, VectorXd> operator()(const VectorXd &x) { return ks->calJJF(x, nstp, isRPO); } }; template<class Mat> class KSPO_MULTIJJF { public: KSPO *ks; bool isRPO; int nstp; KSPO_MULTIJJF(KSPO *ks, int nstp, bool isRPO) : ks(ks), nstp(nstp), isRPO(isRPO) {} std::tuple<KSPO::SpMat, KSPO::SpMat, VectorXd> operator()(const VectorXd &x) { return ks->multiCalJJF(x, nstp, isRPO); } }; #endif /* KSPO_H */ <file_sep>import matplotlib.pyplot as plt import matplotlib.cm as cm from numpy import * import scipy.io as sio from mpl_toolkits.mplot3d import Axes3D ################################################## # function to add embedded plot # rect = [ x of left corner, y of left corner, width, height ] in # percentage def add_subplot_axes(ax,rect,axisbg='w'): fig = plt.gcf() box = ax.get_position() width = box.width height = box.height inax_position = ax.transAxes.transform(rect[0:2]) transFigure = fig.transFigure.inverted() infig_position = transFigure.transform(inax_position) x = infig_position[0] y = infig_position[1] width *= rect[2] height *= rect[3] # <= Typo was here subax = fig.add_axes([x,y,width,height],axisbg=axisbg) x_labelsize = subax.get_xticklabels()[0].get_size() y_labelsize = subax.get_yticklabels()[0].get_size() x_labelsize *= rect[2]**0.5 y_labelsize *= rect[3]**0.5 subax.xaxis.set_tick_params(labelsize=x_labelsize) subax.yaxis.set_tick_params(labelsize=y_labelsize) return subax ################################################## # load data ixRange = range(22,29); #ixRange.insert(0, 0); N = len(ixRange) fileName = ['ang'+ str(i) + '.txt' for i in ixRange] a = []; b = []; angNum = []; angSpan = []; ns = 1000; for i in range(N): print i ang = arccos(loadtxt(fileName[i])) angNum.append(ang.shape[0]) angSpan.append(max(ang)-min(ang)) at, bt = histogram(ang, ns); a.append(at); b.append(bt); ################################################## # plot fig = plt.figure(figsize = (7,5)) ax = fig.add_subplot(111) ReverseAngle = False; colors = cm.rainbow(linspace(0, 1, N)) labs = ['(1-' + str(i+1) + ',' + str(i+2) + '-30)' for i in ixRange] labx =[pi/16, pi/8*1.1, pi/8*0.9, pi/8*3*0.9, pi/2*0.8] laby =[0.9, 0.02, 0.1, 0.05, 0.005] if(ReverseAngle): for i in range(N): b[i] = 1/b[i] ax2 = add_subplot_axes(ax, [0.6, 0.1, 0.4, 0.5]) ax2.set_xlim(0,200) ax.set_xlabel(r'$1/\theta$',size='large') else: ax.set_xlabel(r'$\theta$',size='large') ax.set_xticks([0., .125*pi, 0.25*pi, 0.375*pi]) ax.set_xticklabels(["$0$", r"$\frac{1}{8}\pi$", r"$\frac{2}{8}\pi$", r"$\frac{3}{8}\pi$"]) for i in range(N): ax.scatter(b[i][:-1], a[i]*ns/(angSpan[i]*angNum[i]), s = 7, c = colors[i], edgecolor='none', label=labs[i]) #if(not ReverseAngle): #ax.text(labx[i], laby[i], labs[i]) ax.legend(fontsize='small', loc='upper center', ncol = 2, bbox_to_anchor=(1.11, 1), fancybox=True) ax.set_yscale('log') ax.set_ylim([0.001, 1000]) #ax.set_title('(a)') ax.set_ylabel(r'$\rho(\theta)$',size='large') if(ReverseAngle): ax2.scatter(b[0][:-1], a[0]*ns/max(ang[0])/ang[0].shape[0], s = 7, c = colors[0], edgecolor='none') #ax2.scatter(b[2][:-1], a[2]*ns/max(ang[2])/ang[2].shape[0], s = 7, # c = colors[2], edgecolor='none') ax2.set_yscale('log') plt.tight_layout(pad=0) plt.show() <file_sep>from cglHelp import * from py_CQCGL1d import * case = 44 labels = ["IF4(3)", "IF5(4)", "ERK4(3)2(2)", "ERK4(3)3(3)", "ERK4(3)4(3)", "ERK5(4)5(4)", "SS4(3)"] mks = ['o', 's', '+', '^', 'x', 'v', 'p'] Nscheme = len(labels) lss = ['--', '-.', ':', '-', '-', '-', '-'] if case == 10: lte = np.loadtxt('data/N10_lte.dat') T = 10.25 n = lte.shape[0] fig, ax = pl2d(labs=[r'$t$', r'$LTE$'], yscale='log', xlim=[0, 2*T]) for i in range(6): ax.plot(np.linspace(0, 2*T, n), lte[:, i], lw=2, label=labels[i]) ax2d(fig, ax) if case == 20: ltes = [] for i in range(3): k = 10**i lte = np.loadtxt('data/KS_N20_lte' + str(k) + '.dat') ltes.append(lte) T = 10.25 fig, ax = pl2d(labs=[r'$t$', r'$LTE$'], yscale='log', xlim=[0, T]) k = 5 for i in range(3): n = len(ltes[i][:, k]) ax.plot(np.linspace(0, T, n), ltes[i][:, k], lw=2) ax2d(fig, ax) fig, ax = pl2d(labs=[r'$t$', r'$LTE$'], yscale='log', xlim=[0, 2*T]) k = 1 for i in range(Nscheme): n = len(ltes[k][:, i]) ax.plot(np.linspace(0, 2*T, n), ltes[k][:, i], lw=2, label=labels[i]) ax2d(fig, ax) if case == 30: err = np.loadtxt('data/KS_N30_err.dat') h = err[:, 0] fig, ax = pl2d(size=[6, 5], labs=[r'$h$', 'relative error'], axisLabelSize=20, tickSize=15, xlim=[5e-5, 4e-1], xscale='log', yscale='log') for i in range(Nscheme): ax.plot(h, err[:, i+1], lw=1.5, marker=mks[i], mfc='none', ms=8, label=labels[i]) ax.plot([1e-2, 1e-1], [1e-10, 1e-6], lw=2, c='k', ls='--') ax.plot([4e-2, 4e-1], [1e-11, 1e-6], lw=2, c='k', ls='--') # ax.grid(True, which='both') ax.locator_params(axis='y', numticks=4) ax2d(fig, ax) ############################################################################### # 1d cqcgl if case == 40: """ plot 1d cqcgl of heat map / configuration figure for the const time step, time step adaption and comoving frame methods """ N, d = 1024, 50 Bi, Gi = 0.8, -0.6 cgl = pyCQCGL1d(N, d, -0.1, 0.125, 0.5, 1, Bi, -0.1, Gi, -1) cp = CQCGLplot(cgl) ################### # the case with constant time step ################### aa = np.loadtxt('data/aa.dat') # plot the heat map AA = cgl.Fourier2Config(aa) Aamp = np.abs(AA) fig, ax = pl2d(size=[4, 5], labs=[r'$x$', r'$t$'], axisLabelSize=25, tickSize=18) im = ax.imshow(Aamp, cmap=plt.get_cmap('jet'), extent=[0, d, 0, 20], aspect='auto', origin='lower') ax.grid('on') dr = make_axes_locatable(ax) cax = dr.append_axes('right', size='5%', pad=0.05) plt.colorbar(im, cax=cax, ticks=[0, 1, 2, 3]) ax2d(fig, ax) # plot a single state numOfState = aa.shape[0] fig, ax = pl2d(size=[6, 5], labs=[r'$x$', r'$|A|$'], ylim=[0, 3.5], axisLabelSize=25, tickSize=18) A = cgl.Fourier2Config(aa[int(10./20 * numOfState)]) Aamp = np.abs(A) ax.plot(np.linspace(0, d, Aamp.shape[0]), Aamp, lw=3, ls='--', c='r') A = cgl.Fourier2Config(aa[int(7.0/20 * numOfState)]) Aamp = np.abs(A) ax.plot(np.linspace(0, d, Aamp.shape[0]), Aamp, lw=2, ls='-', c='b') ax.locator_params(axis='y', nbins=4) ax2d(fig, ax) ################### # the case with static frame time step adaption ################### aa = np.loadtxt('data/aaAdapt_Cox_Matthews.dat') Ts = np.loadtxt('data/TsAdapt_Cox_Matthews.dat') AA = cgl.Fourier2Config(aa) Aamp = np.abs(AA) fig, ax = pl2d(size=[4, 5], labs=[r'$x$', r'$t$'], axisLabelSize=25, tickSize=18) im = ax.imshow(Aamp, cmap=plt.get_cmap('jet'), extent=[0, d, 0, 20], aspect='auto', origin='lower') yls = [0, 5, 10, 15, 20] ids = [bisect_left(Ts, yl) for yl in yls] yts = [x / float(Ts.size) * 20 for x in ids] ax.set_yticks(yts) ax.set_yticklabels(yls) ax.grid('on') dr = make_axes_locatable(ax) cax = dr.append_axes('right', size='5%', pad=0.05) plt.colorbar(im, cax=cax, ticks=[0, 1, 2, 3]) ax2d(fig, ax) aa = np.loadtxt('data/aaAdapt_SSPP43.dat') Ts = np.loadtxt('data/TsAdapt_SSPP43.dat') AA = cgl.Fourier2Config(aa) Aamp = np.abs(AA) fig, ax = pl2d(size=[4, 5], labs=[r'$x$', r'$t$'], axisLabelSize=25, tickSize=18) im = ax.imshow(Aamp, cmap=plt.get_cmap('jet'), extent=[0, d, 0, 20], aspect='auto', origin='lower') yls = [0, 5, 10, 15, 20] ids = [bisect_left(Ts, yl) for yl in yls] yts = [x / float(Ts.size) * 20 for x in ids] ax.set_yticks(yts) ax.set_yticklabels(yls) ax.grid('on') dr = make_axes_locatable(ax) cax = dr.append_axes('right', size='5%', pad=0.05) plt.colorbar(im, cax=cax, ticks=[0, 1, 2, 3]) ax2d(fig, ax) ################### # the case with comoving frame time step adaption ################### aa = np.loadtxt('data/aaCom.dat') Ts = np.loadtxt('data/TsCom.dat') AA = cgl.Fourier2Config(aa) Aamp = np.abs(AA) fig, ax = pl2d(size=[4, 5], labs=[r'$x$', r'$t$'], axisLabelSize=25, tickSize=18) im = ax.imshow(Aamp, cmap=plt.get_cmap('jet'), extent=[0, d, 0, 20], aspect='auto', origin='lower') yls = [0, 5, 10, 15, 20] ids = [bisect_left(Ts, yl) for yl in yls] yts = [x / float(Ts.size) * 20 for x in ids] ax.set_yticks(yts) ax.set_yticklabels(yls) ax.grid('on') dr = make_axes_locatable(ax) cax = dr.append_axes('right', size='5%', pad=0.05) plt.colorbar(im, cax=cax, ticks=[0, 1, 2, 3]) ax2d(fig, ax) #################### # plot the high frequency phase rotation #################### aa = np.loadtxt('data/a0NoAdapt.dat') fig = plt.figure(figsize=[6, 5]) ax = fig.add_subplot('111') ax.set_xlabel(r'$t$', fontsize=25) ax.set_ylabel(r'$Re(a_0)$', fontsize=20) ax.tick_params(axis='both', which='major', labelsize=15) ax.plot(np.linspace(0, 20, aa.size), aa, lw=1, c='r') plt.tight_layout(pad=0) plt.show(block=False) #################### # plot the phase rotation and the profile of req #################### aa = np.loadtxt('data/a0ComNoAdapt.dat') req = CQCGLreq(cgl) a0, wth0, wphi0, err0 = req.readReqBiGi('../../data/cgl/reqBiGi.h5', Bi, Gi, 1) AA = cgl.Fourier2Config(a0) Aamp = np.abs(AA) fig = plt.figure(figsize=[12, 5]) ax = fig.add_subplot('121') ax.text(0.1, 0.9, '(a)', horizontalalignment='center', transform=ax.transAxes, fontsize=18, color='black') ax.set_xlabel(r'$x$', fontsize=25) ax.set_ylabel(r'$|A|$', fontsize=20) ax.tick_params(axis='both', which='major', labelsize=15) ax.plot(np.linspace(0, d, Aamp.shape[0]), Aamp, lw=2) ax = fig.add_subplot('122') ax.text(0.1, 0.9, '(b)', horizontalalignment='center', transform=ax.transAxes, fontsize=18, color='black') ax.set_xlabel(r'$t$', fontsize=25) ax.set_ylabel(r'$Re(\tilde{a}_0)$', fontsize=20) ax.tick_params(axis='both', which='major', labelsize=15) ax.plot(np.linspace(0, 20, aa.size), aa, lw=1, c='r') plt.tight_layout(pad=0) plt.show(block=False) if case == 44: """ transform data in case 40 """ N, d = 1024, 50 # 1st cgl = pyCQCGL1d(N, d, -0.1, 0.08, 0.5, 0.782, 1, -0.1, -0.08, -1) pulsate = np.load('data/pulsatingSoliton.npz') aa, aa2, Ts, T = pulsate['states'], pulsate['statesAdapt'], pulsate['Ts'], pulsate['T'] AA = cgl.Fourier2Config(aa) Aamp = np.abs(AA) AA2 = cgl.Fourier2Config(aa2) Aamp2 = np.abs(AA2) np.savez_compressed('data/pulsatingSolitonAmp.npz', states=Aamp, statesAdapt=Aamp2, Ts=Ts, T=T) # 2nd Bi, Gi = 3.5, -5.0 cgl = pyCQCGL1d(N, d, -0.1, 0.125, 0.5, 1, Bi, -0.1, Gi, -1) pulsate = np.load('data/extremeSoliton.npz') aa, aa2, Ts, T = pulsate['states'], pulsate['statesAdapt'], pulsate['Ts'], pulsate['T'] AA = cgl.Fourier2Config(aa) Aamp = np.abs(AA) AA2 = cgl.Fourier2Config(aa2) Aamp2 = np.abs(AA2) np.savez_compressed('data/extremeSolitonAmp.npz', states=Aamp, statesAdapt=Aamp2, Ts=Ts, T=T) # 3rd Bi, Gi = 0.8, -0.6 cgl = pyCQCGL1d(N, d, -0.1, 0.125, 0.5, 1, Bi, -0.1, Gi, -1) aa = np.loadtxt('data/aa.dat') aa2 = np.loadtxt('data/aaAdapt_Cox_Matthews.dat') Ts = np.loadtxt('data/TsAdapt_Cox_Matthews.dat') T = 20 AA = cgl.Fourier2Config(aa) Aamp = np.abs(AA) AA2 = cgl.Fourier2Config(aa2) Aamp2 = np.abs(AA2) np.savez_compressed('data/explodingSolitonAmp.npz', states=Aamp, statesAdapt=Aamp2, Ts=Ts, T=T) if case == 45: """ plot fence instead of heat """ N, d = 1024, 50 fig = plt.figure(figsize=[15, 4]) # 1st ax = ax3dinit(fig, num=131, labs=[r'$x$', r'$t$', r'$|A|$'], axisLabelSize=20, tickSize=12) ax.text2D(0.3, 0.9, '(a)', horizontalalignment='center', transform=ax.transAxes, fontsize=18) cgl = pyCQCGL1d(N, d, -0.1, 0.08, 0.5, 0.782, 1, -0.1, -0.08, -1) skipRate = 1 pulsate = np.load('data/pulsatingSoliton.npz') aa, aa2, Ts, T = pulsate['states'], pulsate['statesAdapt'], pulsate['Ts'], pulsate['T'] AA = cgl.Fourier2Config(aa) Aamp = np.abs(AA) Aamp = Aamp[::skipRate, :] rows, cols = Aamp.shape X = np.linspace(0, d, cols) Y = np.linspace(0, T, rows) for i in range(Aamp.shape[0]): ax.plot(X, np.ones(cols) * Y[i], Aamp[i], c='k', alpha=1) ax.set_yticks([0, 30, 60]) ax.set_zticks([0, 3]) ax.view_init(75, -50) # 2nd ax = ax3dinit(fig, num=132, labs=[r'$x$', r'$t$', r'$|A|$'], axisLabelSize=20, tickSize=12) ax.text2D(0.3, 0.9, '(b)', horizontalalignment='center', transform=ax.transAxes, fontsize=18) Bi, Gi = 3.5, -5.0 cgl = pyCQCGL1d(N, d, -0.1, 0.125, 0.5, 1, Bi, -0.1, Gi, -1) skipRate = 1 pulsate = np.load('data/extremeSoliton.npz') aa, aa2, Ts, T = pulsate['states'], pulsate['statesAdapt'], pulsate['Ts'], pulsate['T'] AA = cgl.Fourier2Config(aa) Aamp = np.abs(AA) Aamp = Aamp[::skipRate, :] rows, cols = Aamp.shape X = np.linspace(0, d, cols) Y = np.linspace(0, T, rows) for i in range(Aamp.shape[0]): ax.plot(X, np.ones(cols) * Y[i], Aamp[i], c='k', alpha=1) ax.set_ylim([0, 13]) ax.set_yticks([0, 5, 10]) ax.set_zticks([0, 1]) ax.view_init(60, -40) # 3rd ax = ax3dinit(fig, num=133, labs=[r'$x$', r'$t$', r'$|A|$'], axisLabelSize=20, tickSize=12) ax.text2D(0.3, 0.9, '(c)', horizontalalignment='center', transform=ax.transAxes, fontsize=18) Bi, Gi = 0.8, -0.6 cgl = pyCQCGL1d(N, d, -0.1, 0.125, 0.5, 1, Bi, -0.1, Gi, -1) skipRate = 5 aa = np.loadtxt('data/aa.dat') T = 20 AA = cgl.Fourier2Config(aa) Aamp = np.abs(AA) Aamp = Aamp[::skipRate, :] rows, cols = Aamp.shape X = np.linspace(0, d, cols) Y = np.linspace(0, T, rows) for i in range(Aamp.shape[0]): ax.plot(X, np.ones(cols) * Y[i], Aamp[i], c='k', alpha=1) ax.set_ylim([0, 13]) ax.set_yticks([0, 5, 10]) ax.set_zticks([0, 3]) ax.view_init(75, -80) ############ ax3d(fig, ax) if case == 50: """ plot the relative errors of 1d cgcgl by constant schemes """ err = np.loadtxt('data/cqcgl1d_N20_err.dat') h = err[:, 0] fig, ax = pl2d(size=[6, 5], labs=[r'$h$', None], axisLabelSize=20, tickSize=15, xlim=[3e-5, 3e-2], ylim=[1e-11, 1e1], xscale='log', yscale='log') for i in range(Nscheme): ax.plot(h, err[:, i+1], lw=1.5, marker=mks[i], mfc='none', label=labels[i]) ax.plot([1e-4, 1e-2], [1e-8, 1e0], lw=2, c='k', ls='--') ax.plot([2e-3, 2e-2], [1e-9, 1e-4], lw=2, c='k', ls='--') # ax.grid(True, which='both') ax.locator_params(axis='y', numticks=5) ax2d(fig, ax, loc='upper left') if case == 60: """ plot the estimated local error of 1d cgcgl by constant schemes """ err = np.loadtxt('data/cqcgl1d_N30_lte.dat') lss = ['--', '-.', ':', '-', '-', '-', '-'] n = err.shape[0] T = 20.0 x = np.arange(1, n+1) * T/n fig, ax = pl2d(size=[6, 5], labs=[r'$t$', r'estimated local error'], axisLabelSize=20, tickSize=15, # xlim=[1e-8, 5e-3], ylim=[1e-17, 1e-7], yscale='log') for i in range(Nscheme): ax.plot(x, err[:, i], lw=1.5, ls=lss[i], label=labels[i]) ax.locator_params(axis='y', numticks=5) ax.locator_params(axis='x', nbins=5) fig.tight_layout(pad=0) ax.legend(loc='lower right', ncol=2) plt.show(block=False) # ax2d(fig, ax, loc='lower right') fig, ax = pl2d(size=[6, 5], labs=[r'$t$', r'estimated local error'], axisLabelSize=20, tickSize=15, # xlim=[1e-8, 5e-3], ylim=[1e-30, 1e-8], yscale='log') for i in range(Nscheme): ax.plot(x, err[:, Nscheme+i], lw=2, ls=lss[i], label=labels[i]) ax.locator_params(axis='y', numticks=4) ax.locator_params(axis='x', nbins=5) ax2d(fig, ax, loc='lower right') if case == 70: """ plot the time steps used in the process """ hs = [] for i in range(Nscheme): x = np.loadtxt('data/cqcgl1d_N50_hs_' + str(i) + '.dat') hs.append(x) T = 20.0 lss = ['--', '-.', ':', '-', '-', '-', '-'] fig, ax = pl2d(size=[6, 5], labs=[r'$t$', r'$h$'], axisLabelSize=20, tickSize=15, # xlim=[1e-8, 5e-3], ylim=[2e-5, 2e-3], yscale='log') for i in range(Nscheme): n = len(hs[i]) x = np.arange(1, n+1) * T/n ax.plot(x, hs[i], lw=2, ls=lss[i], label=labels[i]) # ax.locator_params(axis='y', numticks=5) ax.locator_params(axis='x', nbins=5) fig.tight_layout(pad=0) ax.legend(loc='lower right', ncol=2) plt.show(block=False) # ax2d(fig, ax, loc='upper left') if case == 80: """ same as case 70 but in comoving frame plot the time steps used in the process """ hs = [] for i in range(Nscheme): x = np.loadtxt('data/cqcgl1d_N60_comoving_hs_' + str(i) + '.dat') hs.append(x) T = 20.0 lss = ['--', '-.', ':', '-', '-', '-', '-'] fig, ax = pl2d(size=[6, 5], labs=[r'$t$', r'$h$'], axisLabelSize=20, tickSize=15, # xlim=[1e-8, 5e-3], ylim=[8e-6, 2e-2], yscale='log') for i in range(Nscheme): n = len(hs[i]) x = np.arange(1, n+1) * T/n ax.plot(x, hs[i], lw=1.5, ls=lss[i], label=labels[i]) ax.locator_params(axis='y', numticks=5) ax.locator_params(axis='x', nbins=5) fig.tight_layout(pad=0) ax.legend(loc='lower right', ncol=2) plt.show(block=False) # ax2d(fig, ax, loc='upper left') if case == 90: """ static & comoving frame plot the relative error, Nab, Nn vs rtol """ loadFlag = 0 err = np.loadtxt('data/cqcgl1d_N70_stat' + ('0' if loadFlag == 0 else '1') + '.dat') rtol = err[:, 0] fig = plt.figure(figsize=[12, 15]) # plot relative error ax = fig.add_subplot('321') ax.text(0.5, 0.9, '(a)', horizontalalignment='center', transform=ax.transAxes, fontsize=18, color='black') ax.set_xscale('log') ax.set_yscale('log') ax.set_xlabel(r'$rtol$', fontsize=20) ax.set_ylabel('relative error', fontsize=15) ax.tick_params(axis='both', which='major', labelsize=15) for i in range(Nscheme): ax.plot(rtol, err[:, 6*i+1], lw=1.5, marker=mks[i], mfc='none', ms=8, label=labels[i]) ax.locator_params(axis='y', numticks=5) ax.locator_params(axis='x', numticks=5) ax.legend(loc='bottem right', fontsize=12) # plot Nab ax = fig.add_subplot('322') ax.text(0.5, 0.9, '(b)', horizontalalignment='center', transform=ax.transAxes, fontsize=18, color='black') ax.set_xscale('log') ax.set_xlabel(r'$rtol$', fontsize=20) ax.set_ylabel(r'$Nab$', fontsize=20) ax.tick_params(axis='both', which='major', labelsize=15) for i in range(2, 6): ax.plot(rtol, err[:, 6*i+2], lw=1.5, marker=mks[i], mfc='none', ms=8, label=labels[i]) ax.locator_params(axis='y', nbins=5) ax.locator_params(axis='x', numticks=5) ax.legend(loc='right', fontsize=12) # plot Nn ax = fig.add_subplot('323') ax.text(0.1, 0.9, '(c)', horizontalalignment='center', transform=ax.transAxes, fontsize=18, color='black') ax.set_xscale('log') ax.set_yscale('log') ax.set_xlabel(r'$rtol$', fontsize=20) ax.set_ylabel(r'$Nn$', fontsize=20) ax.tick_params(axis='both', which='major', labelsize=15) for i in range(Nscheme): ax.plot(rtol, err[:, 6*i+3], lw=1.5, marker=mks[i], mfc='none', ms=8, label=labels[i]) ax.locator_params(axis='y', numticks=5) ax.locator_params(axis='x', numticks=5) ax.legend(loc='upper right', fontsize=12) # plot NReject ax = fig.add_subplot('324') ax.text(0.9, 0.9, '(d)', horizontalalignment='center', transform=ax.transAxes, fontsize=18, color='black') ax.set_xscale('log') # ax.set_yscale('log') ax.set_xlabel(r'$rtol$', fontsize=20) ax.set_ylabel(r'number of rejections', fontsize=15) ax.set_ylim([0, 80] if loadFlag == 0 else [0, 250]) ax.tick_params(axis='both', which='major', labelsize=15) for i in range(Nscheme): ax.plot(rtol, err[:, 6*i+4], lw=1.5, marker=mks[i], mfc='none', ms=8, label=labels[i]) ax.locator_params(axis='y', numticks=5) ax.locator_params(axis='x', numticks=5) ax.legend(loc='upper left', ncol=2, fontsize=12) # plot Wt ax = fig.add_subplot('325') ax.text(0.1, 0.9, '(e)', horizontalalignment='center', transform=ax.transAxes, fontsize=18, color='black') ax.set_xscale('log') ax.set_yscale('log') ax.set_xlabel(r'$rtol$', fontsize=20) ax.set_ylabel(r'$Wt$', fontsize=20) ax.tick_params(axis='both', which='major', labelsize=15) for i in range(Nscheme): ax.plot(rtol, err[:, 6*i+5], lw=1.5, marker=mks[i], mfc='none', ms=8, label=labels[i]) ax.locator_params(axis='y', numticks=5) ax.locator_params(axis='x', numticks=5) ax.legend(loc='upper right', fontsize=12) # plot time of calculating coefficients / Wt ax = fig.add_subplot('326') ax.text(0.07, 0.9, '(f)', horizontalalignment='center', transform=ax.transAxes, fontsize=18, color='black') ax.set_xscale('log') ax.set_yscale('log') ax.set_xlabel(r'$rtol$', fontsize=20) ax.set_ylabel(r'time ratio', fontsize=15) ax.set_ylim([1e-6, 2e0]) ax.tick_params(axis='both', which='major', labelsize=15) for i in range(Nscheme): ax.plot(rtol, err[:, 6*i+6]/err[:, 6*i+5], lw=1.5, marker=mks[i], mfc='none', ms=8, label=labels[i]) ax.locator_params(axis='y', numticks=5) ax.locator_params(axis='x', numticks=5) ax.legend(loc='lower right', fontsize=12) ## fig.tight_layout(pad=1) plt.show(block=False) if case == 68: """ comoving frame plot the relative error, Nab, Nn vs rtol """ err = np.loadtxt('data/cqcgl1d_N70_comoving.dat') rtol = err[:, 0] # plot relative error fig, ax = pl2d(size=[6, 5], labs=[r'$rtol$', 'relative error'], axisLabelSize=20, tickSize=15, # xlim=[1e-8, 5e-3], ylim=[1e-9, 4e-0], xscale='log', yscale='log') for i in range(Nscheme): ax.plot(rtol, err[:, 4*i+1], lw=1.5, marker=mks[i], mfc='none', ms=8, label=labels[i]) ax.locator_params(axis='y', numticks=5) ax.locator_params(axis='x', numticks=5) ax2d(fig, ax, loc='lower right') # plot Nab fig, ax = pl2d(size=[6, 5], labs=[r'$rtol$', r'$Nab$'], axisLabelSize=20, tickSize=15, ylim=[500, 4000], # yscale='log', xscale='log') for i in range(4): ax.plot(rtol, err[:, 4*i+2], lw=1.5, marker=mks[i], mfc='none', ms=8, label=labels[i]) ax.locator_params(axis='y', nbins=5) ax.locator_params(axis='x', numticks=5) ax2d(fig, ax, loc='upper left') # plot Nn fig, ax = pl2d(size=[6, 5], labs=[r'$rtol$', r'$Nn$'], axisLabelSize=20, tickSize=15, ylim=[4e4, 1e9], xscale='log', yscale='log') for i in range(Nscheme): ax.plot(rtol, err[:, 4*i+3], lw=1.5, marker=mks[i], mfc='none', ms=8, label=labels[i]) ax.locator_params(axis='y', numticks=5) ax.locator_params(axis='x', numticks=5) ax2d(fig, ax, loc='upper right') # plot Wt fig, ax = pl2d(size=[6, 5], labs=[r'$rtol$', r'$Wt$'], axisLabelSize=20, tickSize=15, ylim=[2e0, 1e4], xscale='log', yscale='log') for i in range(Nscheme): ax.plot(rtol, err[:, 4*i+4], lw=1.5, marker=mks[i], mfc='none', ms=8, label=labels[i]) ax.locator_params(axis='y', numticks=5) ax.locator_params(axis='x', numticks=5) ax2d(fig, ax, loc='upper right') if case == 120: """ Compare the accuracy of static and comoving frames """ err = np.loadtxt('data/cqcgl1d_N70_stat0.dat') err2 = np.loadtxt('data/cqcgl1d_N70_stat1.dat') rtol = err[:, 0] for i in range(2, 6): fig, ax = pl2d(size=[6, 5], labs=[r'$rtol$', 'relative error'], axisLabelSize=20, tickSize=15, # xlim=[1e-8, 5e-3], ylim=[1e-9, 4e-0], xscale='log', yscale='log') ax.plot(rtol, err[:, 4*i+1], lw=1.5, marker=mks[0], mfc='none', ms=8, label='static') ax.plot(rtol, err2[:, 4*i+1], lw=1.5, marker=mks[1], mfc='none', ms=8, label='comoving') ax.locator_params(axis='y', numticks=5) ax.locator_params(axis='x', numticks=5) ax.text(0.3, 0.9, labels[i], fontsize=15, horizontalalignment='center', verticalalignment='center', bbox=dict(ec='black', fc='none'), transform=ax.transAxes) ax2d(fig, ax, loc='upper right') <file_sep>#include <boost/python.hpp> #include <boost/numpy.hpp> #include <Eigen/Dense> #include <cstdio> #include "ksint.hpp" #include "myBoostPython.hpp" using namespace std; using namespace Eigen; namespace bp = boost::python; namespace bn = boost::numpy; ////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////// class pyKS : public KS { public: pyKS(int N, double d) : KS(N, d) {} bn::ndarray PYTs(){ return copy2bn(Ts); } bn::ndarray PYlte(){ return copy2bn(lte); } bn::ndarray PYhs(){ return copy2bn(hs); } /* wrap the integrator */ bn::ndarray PYintgC(bn::ndarray a0, double h, double tend, int skip_rate){ int m, n; getDims(a0, m, n); Map<ArrayXd> tmpa((double*)a0.get_data(), n*m); return copy2bn(intgC(tmpa, h, tend, skip_rate)); } /* wrap the integrator with Jacobian */ bp::tuple PYintgjC(bn::ndarray a0, double h, double tend, int skip_rate){ int m, n; getDims(a0, m, n); Map<ArrayXd> tmpa((double*)a0.get_data(), n*m); auto tmpav = intgjC(tmpa, h, tend, skip_rate); return bp::make_tuple(copy2bn(tmpav.first), copy2bn(tmpav.second)); } bn::ndarray PYintg(bn::ndarray a0, double h, double tend, int skip_rate){ int m, n; getDims(a0, m, n); Map<ArrayXd> tmpa((double*)a0.get_data(), n*m); return copy2bn(intg(tmpa, h, tend, skip_rate)); } bp::tuple PYintgj(bn::ndarray a0, double h, double tend, int skip_rate){ int m, n; getDims(a0, m, n); Map<ArrayXd> tmpa((double*)a0.get_data(), n*m); auto result = intgj(tmpa, h, tend, skip_rate); return bp::make_tuple(copy2bn(result.first), copy2bn(result.second)); } /* wrap the velocity */ bn::ndarray PYvelocity(bn::ndarray a0){ int m, n; getDims(a0, m, n); Map<ArrayXd> tmpa((double*)a0.get_data(), n*m); return copy2bn(velocity(tmpa)); } bn::ndarray PYvelReq(bn::ndarray a0, double theta){ int m, n; getDims(a0, m, n); Map<VectorXd> tmpa((double*)a0.get_data(), n*m); return copy2bn(velReq(tmpa, theta)); } /* stab */ bn::ndarray PYstab(bn::ndarray a0){ int m, n; getDims(a0, m, n); Map<ArrayXd> tmpa((double*)a0.get_data(), n*m); return copy2bn(stab(tmpa)); } bn::ndarray PYstabReq(bn::ndarray a0, double theta){ int m, n; getDims(a0, m, n); Map<VectorXd> tmpa((double*)a0.get_data(), n*m); return copy2bn(stabReq(tmpa, theta)); } /* reflection */ bn::ndarray PYreflect(bn::ndarray aa){ int m, n; getDims(aa, m, n); Map<ArrayXXd> tmpaa((double*)aa.get_data(), n, m); return copy2bn(reflect(tmpaa)); } /* half2whole */ bn::ndarray PYhalf2whole(bn::ndarray aa){ int m, n; getDims(aa, m, n); Map<ArrayXXd> tmpaa((double*)aa.get_data(), n, m); return copy2bn(half2whole(tmpaa)); } /* Rotation */ bn::ndarray PYrotate(bn::ndarray aa, const double th){ int m, n; getDims(aa, m, n); Map<ArrayXXd> tmpaa((double*)aa.get_data(), n, m); return copy2bn(rotate(tmpaa, th)); } bp::tuple PYredSO2(bn::ndarray aa, int p, bool toY){ int m, n; getDims(aa, m, n); Map<MatrixXd> tmpaa((double*)aa.get_data(), n, m); auto tmp = redSO2(tmpaa, p, toY); return bp::make_tuple(copy2bn(tmp.first), copy2bn(tmp.second)); } bp::tuple PYfundDomain(bn::ndarray aa, int pSlice, int pFund){ int m, n; getDims(aa, m, n); Map<MatrixXd> tmpaa((double*)aa.get_data(), n, m); auto tmp = fundDomain(tmpaa, pSlice, pFund); return bp::make_tuple( copy2bn(tmp.first), copy2bn<ArrayXXi, int>(tmp.second)); } bp::tuple PYredO2f(bn::ndarray aa, int pSlice, int pFund){ int m, n; getDims(aa, m, n); Map<MatrixXd> tmpaa((double*)aa.get_data(), n, m); auto tmp = redO2f(tmpaa, pSlice, pFund); return bp::make_tuple( copy2bn(std::get<0>(tmp)), copy2bn<ArrayXXi, int>(std::get<1>(tmp)), copy2bn(std::get<2>(tmp)) ); } bn::ndarray PYredV(bn::ndarray v, bn::ndarray a, int p, bool toY){ int m, n; getDims(v, m, n); Map<MatrixXd> tmpv((double*)v.get_data(), n, m); getDims(a, m, n); Map<VectorXd> tmpa((double*)a.get_data(), n * m); return copy2bn( redV(tmpv, tmpa, p, toY) ); } bn::ndarray PYcalMag(bn::ndarray aa){ int m, n; getDims(aa, m, n); Map<MatrixXd> tmpaa((double*)aa.get_data(), n, m); return copy2bn(calMag(tmpaa)); } bp::tuple PYtoPole(bn::ndarray aa){ int m, n; getDims(aa, m, n); Map<MatrixXd> tmpaa((double*)aa.get_data(), n, m); auto tmp = toPole(tmpaa); return bp::make_tuple(copy2bn(tmp.first), copy2bn(tmp.second) ); } }; ////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////// BOOST_PYTHON_MODULE(py_ks) { bn::initialize(); bp::class_<KS>("KS", bp::init<int, double>()) ; // the EIDr class bp::class_<EIDr>("EIDr", bp::init<>()) .def_readonly("NCalCoe", &EIDr::NCalCoe) .def_readonly("NReject", &EIDr::NReject) .def_readonly("NCallF", &EIDr::NCallF) .def_readonly("NSteps", &EIDr::NSteps) .def_readonly("TotalTime", &EIDr::TotalTime) .def_readonly("CoefficientTime", &EIDr::CoefficientTime) .def_readwrite("rtol", &EIDr::rtol) ; bp::class_<pyKS, bp::bases<KS> >("pyKS", bp::init<int, double>()) .def_readonly("N", &pyKS::N) .def_readonly("d", &pyKS::d) .def_readwrite("eidr", &pyKS::eidr) .def_readwrite("eidr2", &pyKS::eidr2) .def("Ts", &pyKS::PYTs) .def("hs", &pyKS::PYhs) .def("lte", &pyKS::PYlte) .def("intgC", &pyKS::PYintgC) .def("intgjC", &pyKS::PYintgjC) .def("intg", &pyKS::PYintg) .def("intgj", &pyKS::PYintgj) .def("velocity", &pyKS::PYvelocity) .def("velReq", &pyKS::PYvelReq) .def("stab", &pyKS::PYstab) .def("stabReq", &pyKS::PYstabReq) .def("reflect", &pyKS::PYreflect) .def("half2whole", &pyKS::PYhalf2whole) .def("rotate", &pyKS::PYrotate) .def("redSO2", &pyKS::PYredSO2) .def("fundDomain", &pyKS::PYfundDomain) .def("redO2f", &pyKS::PYredO2f) .def("redV", &pyKS::PYredV) .def("calMag", &pyKS::PYcalMag) .def("toPole", &pyKS::PYtoPole) ; } <file_sep># usage: make t=*** CC = g++ AR = ar OPTIM = -O3 -msse2 -msse4 -march=corei7 INCLUDE = ../../include EIGEN = /usr/local/home/xiong/apps/eigen/include/eigen3 CFLAGS = -std=c++11 -DEIGEN_FFTW_DEFAULT # -Wfatal-errors ifndef t t = int endif ifeq ($(t), int) SOURCE = ksint.cc else ifeq ($(t), po) SOURCE = KSPO.cc else ifeq ($(t), dim) SOURCE = ksdim.cc else ifeq ($(t), fefv) SOURCE = ksFEFV.cc else ifeq ($(t), refine) SOURCE = ksrefine.cc endif SHARED = $(addprefix lib, $(addsuffix .so, $(basename $(word 1, $(SOURCE))))) STATIC = $(addprefix lib, $(addsuffix .a, $(basename $(word 1, $(SOURCE))))) all : $(SHARED) # $(STATIC) $(SHARED): $(SOURCE) $(CC) -shared -fpic $(CFLAGS) $(OPTIM) -I$(INCLUDE) -I$(EIGEN) $^ -o $@ $(SOURCE:.cc=.o) : $(SOURCE) $(CC) -c $(CFLAGS) $(OPTIM) -I$(INCLUDE) -I$(EIGEN) $^ $(STATIC): $(SOURCE:.cc=.o) $(AR) crs $@ $^ clean: rm -f *.so *.o *.a move: mv *.so *.a /usr/local/home/xiong/00git/research/lib <file_sep>from personalFunctions import * from personalPlotly import * case = 2 if case == 1: x, y, z = np.random.rand(3, 10) trace1 = go.Scatter3d( x=x, y=y, z=z, mode='lines+markers', marker=dict( size=12, line=dict( color='rgba(217, 217, 217, 0.14)', width=0.5 ), opacity=0.8 ), name='$\\theta$' ) layout = go.Layout( scene=go.Scene( xaxis=dict( title='$\\theta$', showbackground=True, backgroundcolor='rgb(230, 230,230)' ), yaxis=dict( title='$Y$', showbackground=True, backgroundcolor='rgb(230, 230,230)' ), zaxis=go.ZAxis(title='z axis title') ), margin=dict( b=0, l=0, r=0, t=0 ), showlegend=True, ) fig = go.Figure(data=[trace1], layout=layout) py.plot(fig, filename='ex1', fileopt='overwrite') # plot_url = py.plot_mpl(fig, filename='ex1', fileopt='overwrite') if case == 2: x, y, z = rand(3, 10) ptly3d(0, 1, 2, 'ex2', plotType=2, ls='dot') # ptly3d(x, y, z, 'ex2', plotType=2, ls='dot') <file_sep># This makefile tries to compile the shared library for matlab # You should note the difference with the ordinary C/C++ complilation procedure. # # 1) As with Boost.Python, mex cannot deal with shared linkages, so except the bottom # library, all other source files must be compiled. # CC = mex CXX = '/usr/bin/g++-4.7' CXXFLAGS = '-std=c++11 -fPIC -O3' CXXFLAGS_THREADS = '-std=c++11 -fPIC -O3 -DTFFT' INCLUDE = -I../../../include -I/usr/local/home/xiong/apps/eigen/include/eigen3 LIB = -L../../../lib -L/usr/lib/x86_64-linux-gnu LINK = -lm -lfftw3_threads -lfftw3 -lped -lsparseRoutines -ldenseRoutines -literMethod SOURCE = ../cqcgl1d.cc ../../myfft/myfft.cc all : cqcglIntgv cqcglNdim cqcglGintgv cqcglIntgv : cqcglIntgv.cpp $(SOURCE) $(CC) CXX=$(CXX) CXXFLAGS=$(CXXFLAGS_THREADS) $(INCLUDE) $(LIB) $(LINK) $^ mv [email protected] $@_threads.mexa64 $(CC) CXX=$(CXX) CXXFLAGS=$(CXXFLAGS) $(INCLUDE) $(LIB) $(LINK) $^ cqcglNdim : cqcglNdim.cpp $(SOURCE) $(CC) CXX=$(CXX) CXXFLAGS=$(CXXFLAGS) $(INCLUDE) $(LIB) $(LINK) $^ cqcglGintgv : cqcglGintgv.cpp $(SOURCE) $(CC) CXX=$(CXX) CXXFLAGS=$(CXXFLAGS_THREADS) $(INCLUDE) $(LIB) $(LINK) $^ mv [email protected] $@_threads.mexa64 $(CC) CXX=$(CXX) CXXFLAGS=$(CXXFLAGS) $(INCLUDE) $(LIB) $(LINK) $^ clean: rm -f *.mexa64 move: mv *.mexa64 /usr/local/home/xiong/00git/research/lib/mex <file_sep>import sympy as sp sp.init_printing() ap, am = sp.symbols('a_+, a_-') print sp.Integral(1/ap, ap) <file_sep>#include <iostream> #include <functional> #include "CQCGL2dReq.hpp" #include "iterMethod.hpp" #define cee(x) (cout << (x) << endl << endl) namespace ph = std::placeholders; using namespace std; using namespace Eigen; using namespace iterMethod; using namespace denseRoutines; using namespace MyH5; ////////////////////////////////////////////////////////////////////// // constructor // ////////////////////////////////////////////////////////////////////// CQCGL2dReq::CQCGL2dReq(int N, int M, double dx, double dy, double Mu, double Dr, double Di, double Br, double Bi, double Gr, double Gi, int threadNum) :CQCGL2d(N, M, dx, dy, Mu, Dr, Di, Br, Bi, Gr, Gi, threadNum) { calPre(); } CQCGL2dReq::CQCGL2dReq(int N, double dx, double Mu, double Dr, double Di, double Br, double Bi, double Gr, double Gi, int threadNum) : CQCGL2d(N, dx, Mu, Dr, Di, Br, Bi, Gr, Gi, threadNum) { calPre(); } CQCGL2dReq::CQCGL2dReq(int N, int M, double dx, double dy, double b, double c, double dr, double di, int threadNum) : CQCGL2d(N, M, dx, dy, b, c, dr, di, threadNum) { calPre(); } CQCGL2dReq::CQCGL2dReq(int N, double dx, double b, double c, double dr, double di, int threadNum) : CQCGL2d(N, dx, b, c, dr, di, threadNum) { calPre(); } CQCGL2dReq & CQCGL2dReq::operator=(const CQCGL2dReq &x){ return *this; } CQCGL2dReq::~CQCGL2dReq(){} ////////////////////////////////////////////////////////////////////// // member functions // ////////////////////////////////////////////////////////////////////// void CQCGL2dReq::calPre(){ Lu = unpad(L); Tx = (dcp(0, 1) * Kx2).replicate(1, Me).transpose(); Ty = (dcp(0, 1) * Ky2).replicate(1, Ne); Tp = dcp(0, 1) * ArrayXXd::Ones(Me, Ne); } VectorXd CQCGL2dReq::Fx(const VectorXd &x){ assert(x.size() == 2*Ne*Me + 3); Vector3d th = x.tail<3>(); // wthx, wthy, wphi VectorXd ra = x.head(2*Me*Ne); // use matrix type for resizing ArrayXXcd a = r2c(ra); ArrayXXcd v = velocityReq(a, th(0), th(1), th(2)); VectorXd F(2*Ne*Me+3); F << c2r(v), 0, 0, 0; return F; } VectorXd CQCGL2dReq::DFx(const VectorXd &x, const VectorXd &dx){ assert(x.size() == 2*Ne*Me + 3 && dx.size() == 2*Ne*Me + 3); Vector3d th = x.tail<3>(); // wthx, wthy, wphi Vector3d dth = dx.tail<3>(); VectorXd ra = x.head(2*Me*Ne); VectorXd rda = dx.head(2*Me*Ne); ArrayXXcd a = r2c(ra); ArrayXXcd da = r2c(rda); ArrayXXcd t1 = tangent(a, 1); ArrayXXcd t2 = tangent(a, 2); ArrayXXcd t3 = tangent(a, 3); ArrayXXcd Ax = stabReq(a, da, th(0), th(1), th(2)) + dth(0) * t1 + dth(1) * t2 + dth(2) * t3; double t1x = (t1 * da.conjugate()).sum().real(); double t2x = (t2 * da.conjugate()).sum().real(); double t3x = (t3 * da.conjugate()).sum().real(); VectorXd DF(2*Ne*Me+3); DF << c2r(Ax), t1x, t2x, t3x; return DF; } std::tuple<ArrayXXcd, double, double, double, double> CQCGL2dReq::findReq_hook(const ArrayXXcd &x0, const double wthx0, const double wthy0, const double wphi0){ HOOK_PRINT_FREQUENCE = hookPrint; assert(x0.rows() == Me && x0.cols() == Ne); auto fx = std::bind(&CQCGL2dReq::Fx, this, ph::_1); auto dfx = std::bind(&CQCGL2dReq::DFx, this, ph::_1, ph::_2); VectorXd x(2*Me*Ne+3); x << c2r(x0), wthx0, wthy0, wphi0; VectorXd xnew; std::vector<double> errs; int flag; auto Pre = [this](const VectorXd &x, const VectorXd &dx){ Vector3d th = x.tail<3>(); Vector3d dth = dx.tail<3>(); VectorXd dra = dx.head(2*Me*Ne); ArrayXXcd da = r2c(dra); ArrayXXcd px = 1/(Lu + Tx*th(0) + Ty*th(1) + Tp*th(2)) * da; VectorXd p(2*Ne*Me+3); p << c2r(px), dth; return p; }; std::tie(xnew, errs, flag) = Gmres0HookPre(fx, dfx, Pre, x, tol, minRD, maxit, maxInnIt, GmresRtol, GmresRestart, GmresMaxit, false, 1); if(flag != 0) fprintf(stderr, "Req not converged ! \n"); Vector3d th = xnew.tail<3>(); VectorXd y = xnew.head(2*Me*Ne); return std::make_tuple(r2c(y), th(0), th(1), th(2), errs.back()); } /** @brief find the optimal guess of wthx, wthy and wphi for a candidate req * * Let $V = [t1, t2, t3]$ the matrix of group tangent, and $V = QR$. * Then expansion coefficient of vector $x$ is $a = Q^T x$. * So The subtraction should be $Q a$, which is $V R^{-1} a$. Therefore, the * optimal expansion coefficients in V basis is $R^{-1}a$. * * @return [wthx, wthy, wphi] such that velocityReq(a0, wthx, wthy, wphi) minimal */ Vector3d CQCGL2dReq::optReqTh(const ArrayXXcd &a0){ ArrayXXcd t1 = tangent(a0, 1); ArrayXXcd t2 = tangent(a0, 2); ArrayXXcd t3 = tangent(a0, 3); ArrayXXcd x = velocity(a0); MatrixXd V(2*Me*Ne, 3); V << c2r(t1), c2r(t2), c2r(t3); MatrixXd Q, R; std::tie(Q, R) = QR(V); Vector3d a = Q.transpose() * c2r(x).matrix(); Vector3d b = R.inverse() * a; return b; } <file_sep>from personalFunctions import * from py_CQCGL1d import * from py_CQCGL2d import * labels = ["IFRK4(3)", "IFRK5(4)", "ERK4(3)2(2)", "ERK4(3)3(3)", "ERK4(3)4(3)", "ERK5(4)5(4)", "SSPP4(3)"] mks = ['o', 's', '+', '^', 'x', 'v', 'p'] Nscheme = len(labels) lss = ['--', '-.', ':', '-', '-', '-', '-'] case = 10 if case == 10: """ plot the integration process """ N, d = 1024, 50 Bi, Gi = 0.8, -0.6 cgl = pyCQCGL2d(N, d, -0.1, 0.125, 0.5, 1, Bi, -0.1, Gi, 4) fileName = 'aaSS.h5' c2dp = CQCGL2dPlot(d, d) c2dp.savePlots(cgl, fileName, 'fig3', plotType=2, size=[12, 6]) c2dp.makeMovie('fig3') <file_sep>from personalFunctions import * from py_ks import * def getEnoughN(x, nb): ma = max(x) mi = min(x) l = ma - mi id = np.floor(nb * (x - mi) / l) s = 0 for i range(len(id)): case = 10 if case == 10: N = 64 d = 22 h = 0.01 ks = pyKS(N, d) fileName = '../../data/ks22h001t120x64EV.h5' poType = 'rpo' poId = 1 a0, T, nstp, r, s = KSreadPO(fileName, poType, poId) a0H = ks.orbitToSlice(a0)[0] FE, FV = KSreadFEFV(fileName, poType, poId) FV = FV[0].reshape((30, N-2)) FVH = ks.veToSlice(FV, a0) fv = FVH[[0, 1] + range(3, 30)] # get rid of group tengent aa = ks.aintg(rand(N-2), h, T, 1000000) vd = np.zeros((0, N-2)) for i in range(100): if i % 10 == 0: print i, vd.shape a0E = aa[-1] aa = ks.aintg(a0E, h, 500, 1) aaH = ks.orbitToSlice(aa)[0] div = aaH-a0H dis = norm(div, axis=1) ix = dis < 0.1 vd = np.vstack((vd, div[ix])) x = fv[0] / norm(fv[0]) x = vd.dot(x) <file_sep>/* How to compile this program: * h5c++ readks.cc ../ped/ped.cc ../ksint/ksint.cc * -std=c++0x -I$XDAPPS/eigen/include/eigen3 -I../../include -lfftw3 * -march=corei7 -msse4 -O3 */ #ifndef READKS_H #define READKS_H #include "ksint.hpp" #include "ped.hpp" #include <Eigen/Dense> #include <tuple> #include <string> class ReadKS { public: ////////////////////////////////////////////////// const std::string fileName; // intial condition H5 file const std::string fileNameE; // exponents H5 file const std::string fileNameEV; // vectors H5 file const int N; // dimension of eigenvectors. default N = 30 const int Nks; // truncation number of KS. default Nks = 32 const double L; // size of KS. default L = 22 ////////////////////////////////////////////////// ////////////////////////////////////////////////// ReadKS(std::string s1, std::string s2, std::string s3, int N = 30, int Nks = 32, double L = 22); explicit ReadKS(const ReadKS &x); ReadKS & operator=(const ReadKS &x); ~ReadKS(); ////////////////////////////////////////////////// ////////////////////////////////////////////////// Eigen::MatrixXi checkExistEV(const std::string &ppType, const int NN); std::tuple<Eigen::ArrayXd, double, double> readKSorigin(const std::string &ppType, const int ppId); std::tuple<Eigen::ArrayXd, double, double, double, double> readKSinit(const std::string &ppType, const int ppId); std::tuple<MatrixXd, double, double, double, double> readKSinitMulti(const std::string fileName, const std::string &ppType, const int ppId); void writeKSinit(const std::string fileName, const std::string ppType, const int ppId, const std::tuple<ArrayXd, double, double, double, double> ksinit ); void writeKSinitMulti(const std::string fileName, const std::string ppType, const int ppId, const std::tuple<MatrixXd, double, double, double, double> ksinit ); Eigen::MatrixXd readKSe(const std::string &ppType, const int ppId); Eigen::MatrixXd readKSve(const std::string &ppType, const int ppId); void writeKSe(const std::string &ppType, const int ppId, const Eigen::MatrixXd &eigvals, const bool rewrite = false); void writeKSev(const std::string &ppType, const int ppId, const Eigen::MatrixXd &eigvals, const Eigen::MatrixXd &eigvecs, const bool rewrite = false); std::pair<MatrixXd, MatrixXd> calKSFloquet(const std::string ppType, const int ppId, const int MaxN = 80000, const double tol = 1e-15, const int nqr = 1, const int trunc = 0); std::pair<MatrixXd, MatrixXd> calKSFloquetMulti(const std::string fileName, const std::string ppType, const int ppId, const int MaxN = 80000, const double tol = 1e-15, const int nqr = 1, const int trunc = 0); MatrixXd calKSFloquetOnlyE(const std::string ppType, const int ppId, const int MaxN = 80000, const double tol = 1e-15, const int nqr = 1); void calKSOneOrbit( const std::string ppType, const int ppId, const int MaxN = 80000, const double tol = 1e-15, const bool rewrite = false, const int nqr = 1, const int trunc = 0); void calKSOneOrbitOnlyE( const std::string ppType, const int ppId, const int MaxN = 80000, const double tol = 1e-15, const bool rewrite = false, const int nqr = 1); std::vector< std::pair<double, int> > findMarginal(const Eigen::Ref<const Eigen::VectorXd> &Exponent); Eigen::MatrixXi indexSubspace(const Eigen::Ref<const Eigen::VectorXd> &RCP, const Eigen::Ref<const Eigen::VectorXd> &Exponent); ////////////////////////////////////////////////// }; #endif /* READKS_H */ <file_sep>/* to comiple: * h5c++ -O3 test_CQCGL2dDislin.cc -L../../lib -I../../include -I $XDAPPS/eigen/include/eigen3 -std=c++11 -lCQCGL2d -lsparseRoutines -ldenseRoutines -lmyH5 -lmyfft -lfftw3 -lm -lCQCGL2dDislin -ldiscpp */ #include "CQCGL2dDislin.hpp" #include "myH5.hpp" #include "denseRoutines.hpp" #include <iostream> #include <fstream> #include <Eigen/Dense> #include <complex> #include <H5Cpp.h> #define cee(x) (cout << (x) << endl << endl) #define CASE10 using namespace std; using namespace Eigen; using namespace MyH5; using namespace denseRoutines; typedef std::complex<double> dcp; int main(){ switch(0){ case 1 : { /* test integrator */ int N = 1024; double L = 100; double di = 0.05; CQCGL2dDislin cgl(N, L, 4.0, 0.8, 0.01, di, 4); VectorXd xs(2); xs << N/4, 3*N/4; VectorXd as(2); as << 0.1, 0.1; ArrayXXcd A0 = dcp(3, 3)*solitons(N, N, xs, xs, as, as); // ArrayXXcd A0 = dcp(3, 3)*soliton(N, N, N/2, N/2, 0.1, 0.1); //ArrayXXcd A0 = dcp(3, 0) * center2d(N, N, 0.2, 0.2); ArrayXXcd a0 = cgl.Config2Fourier(A0); cgl.constAnim(a0, 0.001, 10); break; } case 2 : { int N = 1024; double L = 100; double di = 0.05; CQCGL2dDislin cgl(N, L, 4.0, 0.8, 0.01, di, 4); VectorXd xs(4); xs << N/4, N/4, 3*N/4, 3*N/4; VectorXd ys(4); ys << N/4, 3*N/4, N/4, 3*N/4; VectorXd as(4); as << 0.1, 0.1, 0.1, 0.1; ArrayXXcd A0 = dcp(3, 3)*solitons(N, N, xs, ys, as, as); ArrayXXcd a0 = cgl.Config2Fourier(A0); cgl.constAnim(a0, 0.001, 10); break; } case 3 : { int N = 1024; double L = 100; double di = 0.05; CQCGL2dDislin cgl(N, L, 4.0, 0.8, 0.01, di, 4); ArrayXXcd A0 = dcp(3, 3)*solitonMesh(N, N, 3, 3, 0.05); ArrayXXcd a0 = cgl.Config2Fourier(A0); cgl.constAnim(a0, 0.001, 10); break; } case 4 : { } default: { fprintf(stderr, "please indicate a valid case number \n"); } } #ifdef CASE10 // ==================================================================================================== int N = 1024; double L = 30; double di = 0.05; CQCGL2dDislin cgl(N, L, 4.0, 0.8, 0.01, di, 4); ArrayXXcd A0 = Gaussian2d(N, N, N/2, N/2, N/10, N/10, 3) + Gaussian2d(N, N, N/2, N/4, N/10, N/10, 0.5); ArrayXXcd a0 = cgl.Config2Fourier(A0); cgl.constAnim(a0, 0.001, 10); #endif return 0; } <file_sep>from py_ks import * from personalFunctions import * case = 20 if case == 10: """ use a larger domain size for simulation """ N, L = 128*2, 100 ks = pyKS(N, L) ksp = KSplot(ks) T, h = 100, 0.001 a0 = rand(N-2) aa = ks.intg(a0, h, np.int(100/h), 1000000) a0 = aa[-1] aa = ks.intg(a0, h, np.int(T/h), 5) ksp.config(aa, [0, L, 0, T], size=[3.6, 6], axisLabelSize=25, tickSize=16) ksp.config(aa, [0, L, 0, T], size=[3.4, 6], labs=[None, None], axisLabelSize=25, tickSize=16) if case == 20: """ use a larger domain size for simulation """ N, L = 128*2, 200 ks = pyKS(N, L) ksp = KSplot(ks) T, h = 100, 0.001 a0 = rand(N-2) aa = ks.intg(a0, h, np.int(400/h), 1000000) a0 = aa[-1] aa = ks.intg(a0, h, np.int(T/h), 5) ksp.config(aa, [0, L, 0, T], size=[6, 6], axisLabelSize=25, tickSize=16) ksp.config(aa, [0, L, 0, T], size=[6, 6], labs=[None, None], axisLabelSize=25, tickSize=16) <file_sep>#!/bin/bash make && make move perl -pe 's/CLEANUP = no/CLEANUP = yes/' Makefile > tmp make -f tmp && mv libmyfft.so libmyfft_clean.so \ && mv libmyfft.a libmyfft_clean.a && make move rm tmp <file_sep>import numpy as np import matplotlib.pyplot as plt N = 1024; M = 10000; AA = np.fromfile('aa.bin', np.double, 2*N*M).reshape(M,2*N).T; Ar = AA[0::2,:]; Ai = AA[1::2, :]; Ama = abs(Ar+1j*Ai); Ama=Ama.T; Maxf = 7000 ; mag = 2; h = 0.005; fig = plt.figure(figsize=(6,8)); ax = fig.add_subplot(111) ax.set_xlabel('x') ax.set_ylabel('t') ax.set_yticks([0, h*mag*Maxf]) ax.set_yticklabels(["$0$", "35"]) #ax.set_ylim((-0.5, 3.5)) ax.imshow(Ama[:,0:Maxf], cmap=plt.get_cmap('seismic'), extent=(0,50,0,h*mag*Maxf)); ax.grid('on') fig.tight_layout(pad=0) plt.show() <file_sep>from ksHelp import * from py_ks import * case = 10 if case == 10: N, L = 64, 21.7 ks = pyKS(N, L) ksp = KSplot(ks) a0 = rand(N-2) a0 = ks.intgC(a0, 0.01, 100, 1000000) for i in range(10): aa = ks.intgC(a0, 0.01, 100, 10) a0 = aa[-1] # raa, ths = ks.redSO2(aa, 1, False) ksp.config(aa, [0, L, 0, 100]) if case == 20: """ visulize rpo with different L """ N = 64 L0, dL = 21.95, 0.05 ppType = 'rpo' isRPO = ppType == 'rpo' ppId = 2 fileName = '../../data/ksh01x64.h5' Ts, ths = [], [] for i in range(20): L = L0 - i * dL ks = pyKS(N, L) ksp = KSplot(ks) groupName = ksp.toStr(ppType, ppId, L, flag=1) if ksp.checkExist(fileName, groupName): a, T, nstp, theta, err = ksp.readPO(fileName, groupName, isRPO)[:5] Ts.append(T) ths.append(theta) if i%1 == 0: aa = ks.intgC(a, T/nstp, 4*T, 5) ksp.config(aa, [0, L, 0, 4*T]) print Ts print ths if case == 30: """ visulize the state space for small L """ N, L = 64, 21.95 ks = pyKS(N, L) ksp = KSplot(ks) ppType = 'ppo' isRPO = ppType == 'rpo' ppId = 1 a, T, nstp, theta, err = ksp.readPO('../../data/ksh01x64.h5', ksp.toStr(ppType, ppId, L, flag=1), isRPO)[:5] ap = ks.intgC(a, T/nstp, T, 10) apH = ks.redSO2(ap, 2, True)[0] aE = rand(N-2)*0.1 aE = ks.intgC(aE, 0.01, 100, 100000) aa = ks.intgC(aE, 0.01, 1000, 10) aaH = ks.redSO2(aa, 2, True)[0] fig, ax = pl3d(size=[8, 6]) ax.plot(apH[:, 1], apH[:, 5], apH[:, 3], c='r', lw=3) ax.plot(aaH[:, 1], aaH[:, 5], aaH[:, 3], c='b') ax3d(fig, ax) if case == 40: """ have a look at stability of rpo/ppo for different L """ N = 64 L0, dL = 21.95, 0.05 ppType = 'rpo' isRPO = ppType == 'rpo' ppId = 2 fileName = '../../data/ksh01x64EV.h5' Ls, Es, Ts = [], [], [] for i in range(20): L = L0 - i * dL ksp = KSplot() groupName = ksp.toStr(ppType, ppId, L, flag=1) if ksp.checkExist(fileName, groupName): a, T, nstp, theta, err, e = ksp.readPO(fileName, groupName, isRPO, flag=1)[:6] Ts.append(T) Ls.append(L) Es.append(e) print Ts print Ls print Es <file_sep>#!/bin/bash for f in ./*.eps; do epspdf $f $(basename $f .eps).pdf done <file_sep>from py_CQCGL_threads import * from personalFunctions import * case = 60 if case == 10: """ save the same initial condition """ N = 1024 d = 30 di = 0.06 T = 8 cgl = pyCQCGL(N, d, 4.0, 0.8, 0.01, di, 0, 4) Ndim = cgl.Ndim A0 = 3*centerRand(N, 0.2, True) a0 = cgl.Config2Fourier(A0) aa = cgl.aintg(a0, 0.001, T, 100000) print aa.shape np.savetxt('init.dat', aa[-1]) if case == 20: """ constant time step result """ N = 1024 d = 30 di = 0.06 T = 8 h = 1e-4 nstp = np.int(T/h) cgl = pyCQCGL(N, d, 4.0, 0.8, 0.01, di, 0, 4) cgl.Method = 1 a0 = np.loadtxt('init.dat') aa = cgl.intg(a0, h, nstp, 10) lte1 = cgl.lte() # plot 3d and heat profiles plotConfigSpaceFromFourier(cgl, aa, [0, d, 0, T], tickSize=15, axisLabelSize=25) plotConfigWireFourier(cgl, aa[::40].copy(), [0, d, 0, T]) # plot single soliton profile fig, ax = pl2d(size=[6, 4.5], labs=[r'$x$', r'$|A|$'], axisLabelSize=25, tickSize=15) A1 = cgl.Fourier2Config(aa[0]) A2 = cgl.Fourier2Config(aa[2100]) # t = 2.1 ax.plot(np.linspace(0, d, len(A1)), np.abs(A1), lw=1.5, ls='-', c='b') ax.plot(np.linspace(0, d, len(A2)), np.abs(A2), lw=1.5, ls='-', c='r') ax2d(fig, ax) cgl.Method = 2 aa2 = cgl.intg(a0, h, nstp, 10) lte2 = cgl.lte() # plot lte fig, ax = pl2d(size=[6, 4.5], labs=[r'$t$', r'$LTE$'], axisLabelSize=25, tickSize=15, yscale='log') ax.plot(np.linspace(0, T, len(lte1)), lte1, lw=1.5, ls='-', c='r', label='Cox-Matthews') ax.plot(np.linspace(0, T, len(lte2)), lte2, lw=2, ls='--', c='b', label='Krogstad') ax2d(fig, ax) if case == 30: """ time step adaption in static frame """ N = 1024 d = 30 di = 0.06 T = 8 cgl = pyCQCGL(N, d, 4.0, 0.8, 0.01, di, 0, 4) a0 = np.loadtxt('init.dat') cgl.changeOmega(-176.67504941219335) cgl.Method = 1 aa = cgl.aintg(a0, 1e-3, T, 40) Ts1 = cgl.Ts() lte1 = cgl.lte() hs1 = cgl.hs() print cgl.NSteps, cgl.NReject, cgl.NCallF, cgl.NCalCoe cgl.Method = 2 aa2 = cgl.aintg(a0, 1e-3, T, 40) Ts2 = cgl.Ts() lte2 = cgl.lte() hs2 = cgl.hs() print cgl.NSteps, cgl.NReject, cgl.NCallF, cgl.NCalCoe # plot heat map plotConfigSpaceFromFourier(cgl, aa, [0, d, 0, T], tt=Ts1, yls=range(0, T+1), tickSize=15, axisLabelSize=25) # plot the accumlated time. fig, ax = pl2d(size=[6, 4.5], labs=[r'$\tau$', r'$t$'], axisLabelSize=25, tickSize=15) ax.plot(np.linspace(0, T, len(Ts1)), Ts1, lw=1.5, ls='-', c='r', label='Cox-Matthews') ax.plot(np.linspace(0, T, len(Ts2)), Ts2, lw=2, ls='--', c='b', label='Krogstad') ax2d(fig, ax) # plot lte fig, ax = pl2d(size=[6, 4.5], labs=[r'$\tau$', r'$LTE$'], axisLabelSize=25, tickSize=15, ylim=[1e-11, 1e-10], yscale='log') ax.plot(np.linspace(0, T, len(lte1)), lte1, lw=1.5, ls='-', c='r', label='Cox-Matthews') ax.plot(np.linspace(0, T, len(lte2)), lte2, lw=2, ls='--', c='b', label='Krogstad') ax2d(fig, ax) # plot hs fig, ax = pl2d(size=[6, 4.5], labs=[r'$\tau$', r'$h$'], axisLabelSize=25, tickSize=18, ylim=[8e-6, 1e-4], yscale='log') ax.plot(np.linspace(0, T, len(hs1)), hs1, lw=1.5, ls='-', c='r', label='Cox-Matthews') ax.plot(np.linspace(0, T, len(hs2)), hs2, lw=2, ls='--', c='b', label='Krogstad') ax2d(fig, ax) # plot the real part of the zeros mode fig, ax = pl2d(size=[6, 4.5], labs=[r'$\tau$', r'$Re(a_0)$'], axisLabelSize=25, tickSize=18) n = aa.shape[0] ids = np.arange(3*n/4, n) ax.plot(np.linspace(3*T/4, T, len(ids)), aa[ids, 0], lw=1, ls='-', c='r') ax2d(fig, ax) if case == 40: """ time step adaption in co-moving frame """ N = 1024 d = 30 di = 0.06 T = 8 cgl = pyCQCGL(N, d, 4.0, 0.8, 0.01, di, 0, 4) a0 = np.loadtxt('init.dat') cgl.changeOmega(-176.67504941219335) cgl.Method = 1 aa = cgl.aintg(a0, 1e-3, T, 40) Ts1 = cgl.Ts() lte1 = cgl.lte() hs1 = cgl.hs() print cgl.NSteps, cgl.NReject, cgl.NCallF, cgl.NCalCoe cgl.Method = 2 aa2 = cgl.aintg(a0, 1e-3, T, 40) Ts2 = cgl.Ts() lte2 = cgl.lte() hs2 = cgl.hs() print cgl.NSteps, cgl.NReject, cgl.NCallF, cgl.NCalCoe # plot heat map plotConfigSpaceFromFourier(cgl, aa, [0, d, 0, T], tt=Ts1, yls=range(0, T+1), tickSize=15, axisLabelSize=25) # plot the accumlated time. fig, ax = pl2d(size=[6, 4.5], labs=[r'$\tau$', r'$t$'], axisLabelSize=25, tickSize=15) ax.plot(np.linspace(0, T, len(Ts1)), Ts1, lw=1.5, ls='-', c='r', label='Cox-Matthews') ax.plot(np.linspace(0, T, len(Ts2)), Ts2, lw=2, ls='--', c='b', label='Krogstad') ax2d(fig, ax) # plot lte fig, ax = pl2d(size=[6, 4.5], labs=[r'$\tau$', r'$LTE$'], axisLabelSize=25, tickSize=15, ylim=[1e-11, 1e-10], yscale='log') ax.plot(np.linspace(0, T, len(lte1)), lte1, lw=1.5, ls='-', c='r', label='Cox-Matthews') ax.plot(np.linspace(0, T, len(lte2)), lte2, lw=2, ls='--', c='b', label='Krogstad') ax2d(fig, ax) # plot hs fig, ax = pl2d(size=[6, 4.5], labs=[r'$\tau$', r'$h$'], axisLabelSize=25, tickSize=18, ylim=[8e-6, 1e-3], yscale='log') ax.plot(np.linspace(0, T, len(hs1)), hs1, lw=1.5, ls='-', c='r', label='Cox-Matthews') ax.plot(np.linspace(0, T, len(hs2)), hs2, lw=2, ls='--', c='b', label='Krogstad') ax2d(fig, ax) # plot the real part of the zeros mode fig, ax = pl2d(size=[6, 4.5], labs=[r'$\tau$', r'$Re(a_0)$'], axisLabelSize=25, tickSize=18) n = aa.shape[0] ids = np.arange(3*n/4, n) ax.set_ylim([-1000, 1000]) ax.plot(np.linspace(3*T/4, T, len(ids)), aa[ids, 0], lw=1, ls='-', c='r') ax2d(fig, ax) if case == 50: """ plot the relative equilibrium """ N = 1024 d = 30 di = 0.06 a0, wth0, wphi0, err = cqcglReadReqdi('../../data/cgl/reqDi.h5', di, 1) cgl = pyCQCGL(N, d, 4.0, 0.8, 0.01, di, 0, 4) # plot the solition profile fig, ax = pl2d(size=[6, 4.5], labs=[r'$x$', r'$|A(x)|$'], axisLabelSize=25, tickSize=18) A1 = cgl.Fourier2Config(a0) ax.plot(np.linspace(0, d, len(A1)), np.abs(A1), lw=1.5, ls='-', c='r') ax2d(fig, ax) if case == 60: """ collect the performance of static and co-moving frames """ N = 1024 d = 30 di = 0.06 T = 8 cgl = pyCQCGL(N, d, 4.0, 0.8, 0.01, di, 0, 4) a0 = np.loadtxt('init.dat') rtols = [1e-6, 1e-7, 1e-8, 1e-9, 1e-10, 1e-11] R1 = np.zeros((2, len(rtols))) N1 = np.zeros((2, len(rtols))) for i in range(len(rtols)): cgl.rtol = rtols[i] print i, cgl.rtol cgl.Method = 1 aa = cgl.aintg(a0, 1e-3, T, 1000000) print cgl.NSteps, cgl.NReject, cgl.NCallF, cgl.NCalCoe R1[0, i] = cgl.NReject N1[0, i] = cgl.NSteps cgl.Method = 2 aa2 = cgl.aintg(a0, 1e-3, T, 1000000) print cgl.NSteps, cgl.NReject, cgl.NCallF, cgl.NCalCoe R1[1, i] = cgl.NReject N1[1, i] = cgl.NSteps cgl.changeOmega(-176.67504941219335) R2 = np.zeros((2, len(rtols))) N2 = np.zeros((2, len(rtols))) for i in range(len(rtols)): cgl.rtol = rtols[i] print i, cgl.rtol cgl.Method = 1 aa = cgl.aintg(a0, 1e-3, T, 1000000) print cgl.NSteps, cgl.NReject, cgl.NCallF, cgl.NCalCoe R2[0, i] = cgl.NReject N2[0, i] = cgl.NSteps cgl.Method = 2 aa2 = cgl.aintg(a0, 1e-3, T, 1000000) print cgl.NSteps, cgl.NReject, cgl.NCallF, cgl.NCalCoe R2[1, i] = cgl.NReject N2[1, i] = cgl.NSteps # save result # np.savez_compressed('perf', R1=R1, N1=N1, R2=R2, N2=N2) # plot the number of integration steps fig, ax = pl2d(size=[6, 4.5], labs=[r'$\epsilon$', r'$N_s$'], axisLabelSize=25, tickSize=18, yscale='log') ax.set_xscale('log') ax.plot(rtols, N1[0], lw=1.5, ls='-', marker='o', ms=7, mew=2, mfc='none', mec='r', c='r', label='Static Cox-Matthews') ax.plot(rtols, N1[1], lw=1.5, ls='-', marker='s', ms=10, mew=2, mfc='none', mec='g', c='g', label='Static Krogstad') ax.plot(rtols, N2[0], lw=1.5, ls='--', marker='o', ms=7, mew=2, mfc='none', mec='c', c='c', label='Co-moving Cox-Matthews') ax.plot(rtols, N2[1], lw=1.5, ls='--', marker='s', ms=10, mew=2, mfc='none', mec='k', c='k', label='Co-moving Krogstad') ax.grid(True, which='both') ax2d(fig, ax) # plot the number of rejections fig, ax = pl2d(size=[6, 4.5], labs=[r'$\epsilon$', r'$N_r$'], axisLabelSize=25, tickSize=18) ax.set_xscale('log') ax.plot(rtols, R1[0], lw=1.5, ls='-', marker='o', ms=7, mew=2, mfc='none', mec='r', c='r', label='Static Cox-Matthews') ax.plot(rtols, R1[1], lw=1.5, ls='-', marker='s', ms=10, mew=2, mfc='none', mec='g', c='g', label='Static Krogstad') ax.plot(rtols, R2[0], lw=1.5, ls='--', marker='o', ms=7, mew=2, mfc='none', mec='c', c='c', label='Co-moving Cox-Matthews') ax.plot(rtols, R2[1], lw=1.5, ls='--', marker='s', ms=10, mew=2, mfc='none', mec='k', c='k', label='Co-moving Krogstad') ax.grid(True, which='both') ax2d(fig, ax) <file_sep>#include<iostream> #include <cmath> #include "lorenz.hpp" using namespace std; using namespace Eigen; using namespace denseRoutines; Lorenz::Lorenz(){ } Lorenz::~Lorenz(){ } Lorenz & Lorenz::operator=(const Lorenz &x){ return *this; } /* ====================================================================== */ /* velocity field of Lorenz flow * * | sigma * (y -x) | * v(x) = | rho * y - y - x*z | * | x*y - b*z | */ Vector3d Lorenz::vel(const Ref<const Vector3d> &x){ Vector3d v; v << Sigma * (x(1) - x(0)), Rho * x(0) - x(1) - x(0)*x(2), x(0)*x(1) - B * x(2); return v; } /* stability matrix */ Matrix3d Lorenz::stab(const Ref<const Vector3d> &x){ Matrix3d A; A << -Sigma, Sigma, 0, Rho-x(2), -1, -x(0), x(1), x(0), -B; return A; } MatrixXd Lorenz::velJ(const Ref<const MatrixXd> &x){ MatrixXd vJ(3, 4); vJ << vel(x.col(0)), stab(x.col(0)) * x.rightCols(3); return vJ; } MatrixXd Lorenz::intg(const Ref<const Vector3d> &x0, const double h, const int nstp, const int nq){ int M = nstp/nq + 1; MatrixXd xx(3, M); xx.col(0) = x0; Vector3d x(x0); for (int i = 0; i < nstp; i++){ Vector3d k1 = vel(x); Vector3d k2 = vel(x + h/2*k1); Vector3d k3 = vel(x + h/2*k2); Vector3d k4 = vel(x + h*k3); x += h/6 * (k1 + 2*k2 + 2*k3 + k4); if((i+1)%nq == 0) xx.col((i+1)/nq) = x; } return xx; } std::pair<MatrixXd, MatrixXd> Lorenz::intgj(const Ref<const Vector3d> &x0, const double h, const int nstp, const int xs, const int js){ int M1 = nstp / xs + 1; int M2 = nstp / js; MatrixXd xx(3, M1); MatrixXd JJ(3, 3*M2); xx.col(0) = x0; MatrixXd x(3, 4); x << x0, MatrixXd::Identity(3,3); for (int i = 0; i < nstp; i++){ MatrixXd k1 = velJ(x); MatrixXd k2 = velJ(x + h/2*k1); MatrixXd k3 = velJ(x + h/2*k2); MatrixXd k4 = velJ(x + h*k3); x += h/6 * (k1 + 2*k2 + 2*k3 + k4); if ((i+1)%xs == 0) xx.col((i+1)/xs) = x.col(0); if ((i+1)%js == 0) JJ.middleCols((i+1)/js-1, 3) = x.rightCols(3); } return std::make_pair(xx, JJ); } /* ============================================================ */ /** * If rho > 1 there are 3 equilibria : * Eq0 = [0, 0, 0] * Eq1 = [\sqrt{b(rho-1)}, \sqrt{b(rho-1)}, rho-1] * Eq2 = [-\sqrt{b(rho-1)}, -\sqrt{b(rho-1)}, rho-1] * * @return each column is an equilibrium */ Matrix3d Lorenz::equilibria(){ double z = Rho - 1; double x = sqrt(B*z); Matrix3d E; E << 0, x, -x, 0, x, -x, 0, z, z; return E; } /* obtain the stability matrix of the ith equilibrium */ Matrix3d Lorenz::equilibriaStab(const int i){ Matrix3d E = equilibria(); return stab(E.col(i)); } /* obtain the eigenvalues/eigenvectors of the stability matrix of * the ith equilibrium */ std::pair<VectorXcd, MatrixXcd> Lorenz::equilibriaEV(const int i){ Matrix3d A = equilibriaStab(i); return evEig(A); } MatrixXd Lorenz::equilibriaIntg(const int i, const int j, const double eps, const double h, const int nstp, const int nq){ Vector3d x0 = equilibria().col(i); auto e = equilibriaEV(i); Vector3d v = e.second.col(j).real(); return intg(x0 + eps*v, h, nstp, nq); } <file_sep>/* Requirement: >= g++4.6, >=eigen3.1 * compile command: * g++ -o libks2py.so ksintM1.cc ksint.cc ksint2py.cc * -shared -fpic -lm -lfftw3 -std=c++0x -march=corei7 -O3 -msse2 -msse4 * -I../../include -I/path/to/eigen3 */ #include "ksintM1.hpp" #include <Eigen/Dense> #include <cstring> #include <cstdlib> using Eigen::ArrayXXd; using Eigen::ArrayXd; using Eigen::Map; typedef struct { double *aa; double *tt; } at; const int N = 32; extern "C" void ksf(double *aa, double *a0, double d, double h, int nstp, int np){ KS ks(N, h, d); Map<ArrayXd> v0(a0, N-2); ArrayXXd vv = ks.intg(v0, nstp, np); memcpy(aa, &vv(0,0), (nstp/np+1)*(N-2)*sizeof(double)); } extern "C" void ksfM1(double *aa, double *tt, double *a0, double d, double h, int nstp, int np){ KSM1 ks(N, h, d); Map<ArrayXd> v0(a0, N-2); std::pair<ArrayXXd, ArrayXd> vv = ks.intg(v0, nstp, np); memcpy(aa, &(vv.first(0,0)), (nstp/np+1)*(N-2)*sizeof(double)); memcpy(tt, &(vv.second(0)), (nstp/np+1)*sizeof(double)); } extern "C" int ksf2M1(at *at, double *a0, double d, double h, double T, int np){ KSM1 ks(N, h, d); Map<ArrayXd> v0(a0, N-2); std::pair<ArrayXXd, ArrayXd> vv = ks.intg2(v0, T, np); int m = vv.first.cols(); double *aa = new double[m*(N-2)]; double *tt = new double[m]; memcpy(aa, &(vv.first(0,0)), m*(N-2)*sizeof(double)); memcpy(tt, &(vv.second(0)), m*sizeof(double)); at->aa = aa; at->tt = tt; return m; } extern "C" void freeks(at *at){ delete[] at->aa; delete[] at->tt; } <file_sep>#ifndef KSDIM_H #define KSDIM_H #include <Eigen/Dense> #include <iostream> #include <cstdio> #include <sys/types.h> #include <sys/stat.h> /* for create folder */ std::pair<Eigen::MatrixXd, Eigen::MatrixXi> anglePO(const std::string fileName, const std::string ppType, const int ppId, const Eigen::MatrixXi subspDim); void anglePOs(const std::string fileName, const std::string ppType, const int N, const int NN, const std::string saveFolder, const std::string spType, const int M = 29); void anglePOs(const std::string fileName, const std::string ppType, const int N, const std::vector<int> ppIds, const std::string saveFolder, const std::string spType, const int M); Eigen::MatrixXd partialHyperb(const std::string fileName, const std::string ppType, const int ppId); void partialHyperbOneType(const std::string fileName, const std::string ppType, const int NN, const std::string saveFolder); void partialHyperbAll(const std::string fileName, const int NNppo, const int NNrpo, const std::string saveFolder); Eigen::MatrixXd localFE(const std::string fileName, const std::string ppType, const int ppId); void localFEOneType(const std::string fileName, const std::string ppType, const int NN, const std::string saveFolder); void localFEAll(const std::string fileName, const int NNppo, const int NNrpo, const std::string saveFolder); #endif /* KSDIM_H */ <file_sep>/* compile command: * mex CXXFLAGS='-std=c++0x -fPIC -O3' half2whole.cc ../ksint.cc -I../../../include -I$XDAPPS/eigen/include/eigen3 -lfftw3 * */ #include "ksint.hpp" #include "mex.h" #include <cmath> #include <cstring> #include <Eigen/Dense> using namespace Eigen; /* transform trajectory into 1st mode slice */ static MatrixXd orbitToSlice(double *aa, const int N, const int M){ KS ks(N+2); Map<MatrixXd> aa2(aa, N, M); return ks.half2whole(aa2); } void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[]){ // get the pointer and the size of input double *aa = mxGetPr(prhs[0]); mwSize N = mxGetM(prhs[0]); mwSize M = mxGetN(prhs[0]); MatrixXd tmp = orbitToSlice(aa, N, M); mwSize N2 = tmp.rows(); mwSize M2 = tmp.cols(); plhs[0] = mxCreateDoubleMatrix(N2, M2, mxREAL); memcpy(mxGetPr(plhs[0]), &tmp(0,0), N2*M2*sizeof(double)); } <file_sep>from time import time from py_cqcgl1d import pyCqcgl1d, pyCqcglRPO from personalFunctions import * def cqcglFindReq(fileName, frac=0.3, MaxIter=300, Ntrial=1000): N = 512 d = 50 h = 0.005 cgl = pyCqcgl1d(N, d, h, -0.1, 1.0, 0.8, 0.125, 0.5, -0.1, -0.6) ReqNum = 1 for i in range(Ntrial): A0 = 3*centerRand(2*N, frac) a0 = cgl.Config2Fourier(A0).squeeze() wth0 = rand() wphi0 = rand() a, wth, wphi, err = cgl.findReq(a0, wth0, wphi0, MaxIter, 1e-12, True, False) if err < 1e-12: print "found : " + str(ReqNum) cqcglSaveReq(fileName, str(ReqNum), a, wth, wphi, err) ReqNum += 1 def cqcglConvertReq(N2, inputFile, outputFile, indices, MaxIter=300, tol=1e-12, doesPrint=False): """ convert the relative equilibria found for some truncation number N to a finer resolution N2 = 2*N. parameters: N2 the dimension of the finer system inputFile file storing reqs with N outputFile file is about to create to store reqs with 2*N indices the indices of reqs needed to be converted """ # N = 512 d = 50 h = 0.005 # time step is not used acturally cgl = pyCqcgl1d(N2, d, h, True, 0, -0.1, 1.0, 0.8, 0.125, 0.5, -0.1, -0.6, 4) for i in indices: a0, wth0, wphi0, err0 = cqcglReadReq(inputFile, str(i)) a0unpad = 2 * cgl.generalPadding(a0) a, wth, wphi, err = cgl.findReq(a0unpad, wth0, wphi0, MaxIter, tol, True, doesPrint) print err cqcglSaveReq(outputFile, str(i), a, wth, wphi, err) case = 9 if case == 1: """ find the relative equlibria after changing dimension """ N = 512 d = 50 h = 0.005 cgl = pyCqcgl1d(N, d, h, -0.1, 1.0, 0.8, 0.125, 0.5, -0.1, -0.6) Ndim = cgl.Ndim a0, wth0, wphi0, err0 = cqcglReadReq('../../data/cgl/req.h5', '10') a0unpad = 2*cgl.generalPadding(a0) a, wth, wphi, err = cgl.findReq(a0unpad, 0, wphi0, 100, 1e-12, True, True) # cqcglSaveReq("req.hdf5", '1', a, wth, wphi, err) nstp = 10000 aa = cgl.intg(a, nstp, 1) plotConfigSpace(cgl.Fourier2Config(aa), [0, d, 0, nstp*h]) if case == 2: """ try different guesses to find relative equilibria Just for test purpose """ N = 1024 d = 30 h = 0.0002 cgl = pyCqcgl1d(N, d, h, True, 0, 4.0, 0.8, -0.01, -0.08, 4) A0 = 5*centerRand(2*N, 0.2) # A0 = 5*centerOne(2*N, 0.25) a0 = cgl.Config2Fourier(A0) wth0 = rand() wphi0 = rand() a, wth, wphi, err = cgl.findReq(a0, wth0, wphi0, 100, 1e-12, True, True) nstp = 10000 aa = cgl.intg(a, nstp, 1) plotConfigSpace(cgl.Fourier2Config(aa), [0, d, 0, nstp*h]) plot1dfig(a) plotOneConfigFromFourier(cgl, a) print wth, wphi # cqcglSaveReq("req2.h5", '1', a, wth, wphi, err) if case == 9: """ load the guess from file and then find req """ N = 1024 d = 30 h = 0.0002 di = 0.05 cgl = pyCqcgl1d(N, d, h, True, 0, 4.0, 0.8, 0.01, di, 4) a0, wth0, wphi0, err = cqcglReadReqdi('../../data/cgl/reqTmp.h5', di, 1) a, wth, wphi, err = cgl.findReq(a0, wth0, wphi0, 100, 1e-12, True, True) nstp = 10000 aa = cgl.intg(a, nstp, 1) plotConfigSpace(cgl.Fourier2Config(aa), [0, d, 0, nstp*h]) plotOneConfigFromFourier(cgl, a) print wth, wphi # cqcglSaveReq("req2.h5", '1', a, wth, wphi, err) if case == 10: """ use existing req to find the req with slightly different di """ N = 1024 d = 30 h = 0.0002 diOld = 0.41 di = diOld + 0.001 cgl = pyCqcgl1d(N, d, h, True, 0, 4.0, 0.8, 0.01, di, 4) a0, wth0, wphi0, err = cqcglReadReqdi('../../data/cgl/reqDi.h5', diOld, 1) a, wth, wphi, err = cgl.findReq(a0, wth0, wphi0, 40, 1e-12, True, True) nstp = 10000 aa = cgl.intg(a, nstp, 1) plotConfigSpace(cgl.Fourier2Config(aa), [0, d, 0, nstp*h]) plot1dfig(a) plotOneConfigFromFourier(cgl, a) print wth, wphi # cqcglSaveReq("req98.h5", '1', a, wth, wphi, err) eigvalues, eigvectors = eigReq(cgl, a, wth, wphi) print eigvalues[:10] if case == 11: """ use existing req to find the req with slightly different di and do this for a sequence of di s. """ N = 1024 d = 30 h = 0.0002 diOld = 0.94 diInc = 0.02 for i in range(1): di = diOld + diInc print di cgl = pyCqcgl1d(N, d, h, True, 0, 4.0, 0.8, 0.01, di, 4) fileName = '../../data/cgl/reqDi.h5' a0, wth0, wphi0, err0 = cqcglReadReqdi(fileName, diOld, 2) a, wth, wphi, err = cgl.findReq(a0, wth0, wphi0, 20, 1e-12, True, True) plotOneConfigFromFourier(cgl, a, save=True, name=str(di)+'.png') print wth, wphi, err e, v = eigReq(cgl, a, wth, wphi) print e[:8] cqcglSaveReqEVdi(fileName, di, 2, a, wth, wphi, err, e.real, e.imag, v[:, :10].real, v[:, :10].imag) diOld += diInc if case == 3: """ run a long time to collect relative equilibria """ cqcglFindReq("req3.h5", 0.3, 300, 1000) if case == 4: """ have a look at these relative equilibrium and remove the duplicates. All kinds of manipulations to build the final data base. """ N = 256 d = 50 h = 0.005 cgl = pyCqcgl1d(N, d, h, -0.1, 1.0, 0.8, 0.125, 0.5, -0.1, -0.6) # Num = 851 # wthAll = np.zeros(Num) # wphiAll = np.zeros(Num) # errAll = np.zeros(Num) # aAll = np.zeros((Num, 2*N)) # for i in range(Num): # a, wth, wphi, err = cqcglReadReq("req3.hdf5", str(i+1)) # aAll[i] = a # wthAll[i] = wth # wphiAll[i] = wphi # errAll[i] = err # dup = [] # groups = [] # for i in range(Num): # for j in range(i): # if (np.abs(np.abs(wthAll[i]) - np.abs(wthAll[j])) < 1e-6 and # np.abs(wphiAll[i] - wphiAll[j]) < 1e-6): # dup.append([i, j]) # groups.append(i+1) # break # cqcglRemoveReq("req3.hdf5", "req4.hdf5", Num, groups) # Num2 = 567 # for i in range(Num2): # a, wth, wphi, err = cqcglReadReq("req4.hdf5", str(i+1)) # plotOneConfigFromFourier(cgl, a, save=True, # name=str(i+1)+'.png') # print wth, wphi, err # wait = raw_input("press enter to continue") # groups = [1, 2, 3, 10, 12, 18, 62, 138, 141, 212, 214, 221, 265, # 270, 276, 292, 330, 351, 399, 414, 425] # cqcglExtractReq('req4.hdf5', 'req5.h5', groups, 2) # for i in range(21): # a, wth, wphi, err = cqcglReadReq("req5.h5", str(i+2)) # print wth, wphi, err # plotOneConfigFromFourier(cgl, a, save=True, # name=str(i+2)+'.png') if case == 5: """ change the existing reqs to different dimension """ # cqcglConvertReq('../../data/cgl/req.h5', 'req2.h5', range(1, 23)) # cqcglConvertReq(2048, '../../data/cgl/reqN1024.h5', 'req2.h5', range(1, 23)) cqcglConvertReq(4096, '../../data/cgl/reqN2048.h5', 'req2.h5', range(1, 23), tol=1.5e-11, doesPrint=True) if case == 6: """ plot the interesting relative equilibria that I have found """ N = 1024 d = 50 h = 0.005 cgl = pyCqcgl1d(N, d, h, True, 0, -0.1, 1.0, 0.8, 0.125, 0.5, -0.1, -0.6, 4) Num = 22 nstp = 18000 for i in range(Num): a, wth, wphi, err = cqcglReadReq('../../data/cgl/reqN1024.h5', str(i+1)) aa = cgl.intg(a, nstp, 1) plotConfigSpace(cgl.Fourier2Config(aa), [0, d, 0, nstp*h], save=True, name='cqcglReq'+str(i+1)+'T90'+'.png') plotOneConfigFromFourier(cgl, a, save=True, name='cqcglReq'+str(i+1)+'.png') <file_sep>from personalFunctions import * from py_ks import * case = 10 if case == 10: N, L = 64, 22 ks = pyKS(N, L) t_init = time(); a0 = np.ones(N-2)*0.1 for i in range(100): aa = ks.intgC(a0, 0.01, 30, 10) print time() - t_init t_init = time() for i in range(1): aa, daa = ks.intgjC(a0, 0.01, 30, 100000) print time() - t_init if case == 15: ks = pyKSM1(32, 0.1, 22) t_init = time() for i in range(1000): a0 = np.ones(30)*0.1 a0[1] = 0 aa, tt = ks.intg(a0, 2000, 1) print time() - t_init t_init = time() for i in range(10): a0 = np.ones(30)*0.1 a0[1] = 0 aa, tt = ks.intg2(a0, 20, 1) print time() - t_init if case == 20: ks = pyKS(32, 0.1, 22) aa = ks.intg(np.ones(30)*0.1, 20, 1) aaHat, ang = ks.orbitToSlice(aa) aaTilde = ks.reduceReflection(aaHat) # check p2 print np.sqrt(aaHat[:, 2]**2 + aaHat[:, 5]**2) print aaTilde[:, 2] # check the last transformed term print aaHat[:, 26] * aaHat[:, 29] / np.sqrt(aaHat[:, 26]**2 + aaHat[:, 29]**2) print aaTilde[:, 29] # check the unchanged terms print aaHat[:, 3] print aaTilde[:, 3] x = 0.1*np.arange(30) ve = np.sin(range(30)) veTilde = ks.reflectVe(ve, x) if case == 30: """ test the redSO2 and fundDomain() functions """ N = 64 d = 22 ks = pyKS(N, d) a0 = rand(N-2) aa = ks.aintg(a0, 0.01, 100, 1000000) aa = ks.aintg(aa[-1], 0.01, 200, 1) plot3dfig(aa[:, 0], aa[:, 1], aa[:, 2]) raa1, ang1 = ks.redSO2(aa, 1, True) faa1, dids1 = ks.fundDomain(raa1, 2) print norm(raa1[:, 0]) plot3dfig(raa1[:, 3], raa1[:, 1], raa1[:, 2]) plot3dfig(faa1[:, 3], faa1[:, 1], faa1[:, 2]) plot1dfig(dids1) raa2, ang2 = ks.redSO2(aa, 2, True) faa2, dids2 = ks.fundDomain(raa2, 1) print norm(raa2[:, 2]) plot3dfig(raa2[:, 0], raa1[:, 1], raa1[:, 3]) plot3dfig(faa2[:, 0], faa2[:, 1], faa2[:, 3]) plot1dfig(dids2) if case == 40: """ test the 2nd slice """ N = 64 d = 22 ks = pyKS(N, d) x = rand(N-2)-0.5 y = ks.Reflection(x) th0 = np.pi*2.47 th1 = np.pi*4.22 x1, t1 = ks.redO2(x) x2, t2 = ks.redO2(ks.Rotation(x, th0)) y1, r1 = ks.redO2(y) y2, r2 = ks.redO2(ks.Rotation(y, th1)) print norm(x2-x1), norm(y2-y1), norm(y2-x2) if case == 50: """ test the 2nd slice with fundamental domain """ N = 64 d = 22 ks = pyKS(N, d) x = rand(N-2)-0.5 y = ks.Reflection(x) th0 = np.pi*2.47 th1 = np.pi*4.22 x1, id1, t1 = ks.redO2f(x, 2) x2, id2, t2 = ks.redO2f(ks.Rotation(x, th0), 2) y1, id3, r1 = ks.redO2f(y, 2) y2, id4, r2 = ks.redO2f(ks.Rotation(y, th1), 2) print norm(x2-x1), norm(y2-y1), norm(y2-x2) if case == 60: """ test ks.stab() function """ N = 64 d = 22 ks = pyKS(N, d) fileName = '/usr/local/home/xiong/00git/research/data/ks22Reqx64.h5' a0, err = KSreadEq(fileName, 3) print norm(ks.velocity(a0)) A = ks.stab(a0) e, v = eig(A.T) idx = argsort(e.real)[::-1] e = e[idx] v = v[:, idx] print e if case == 70: """ visualize heat map of ppo/rpo """ N = 64 L = 22 ks = pyKS(N, L) fileName = '/usr/local/home/xiong/00git/research/data/ks22h001t120x64EV.h5' poType = 'ppo' poId = 2 KSplotPoHeat(ks, fileName, poType, poId, NT=2, Ts=100, fixT=True) if case == 80: """ print the period """ fileName = '/usr/local/home/xiong/00git/research/data/ks22h001t120x64EV.h5' Ts = [] for poId in range(1, 31): a0, T, nstp, r, s = KSreadPO(fileName, 'rpo', poId) print '%0.2f\n' % T, Ts.append(T) <file_sep>from cglHelp import * from py_CQCGL2d import * case = 90 labels = ["IF4(3)", "IF5(4)", "ERK4(3)2(2)", "ERK4(3)3(3)", "ERK4(3)4(3)", "ERK5(4)5(4)", "SS4(3)"] mks = ['o', 's', '+', '^', 'x', 'v', 'p'] Nscheme = len(labels) lss = ['--', '-.', ':', '-', '-', '-', '-'] if case == 40: """ plot one instance of explosion in heat map. Also plot the req in heat map """ N, d = 1024, 50 Bi, Gi = 0.8, -0.6 cgl = pyCQCGL2d(N, d, -0.1, 0.125, 0.5, 1, Bi, -0.1, Gi, 4) cglp = CQCGL2dPlot(d, d) fig = plt.figure(figsize=[12, 15]) states = [] # load explosion data ts = [3, 5, 8, 10, 12] for i in range(len(ts)): t = ts[i] index = np.int(t / 20.0 * 256) a = cglp.load('aaCox.h5', index) states.append(a) # load req data a, wthx, wthy, wphi, err = cglp.loadReq('../../data/cgl/req2dBiGi.h5', cglp.toStr(Bi, Gi, 1)) states.append(a) for i in range(6): ax = fig.add_subplot('32' + str(i+1)) ax.set_axis_off() # ax.tick_params(axis='both', which='major', labelsize=18) ax.text(0.1, 0.9, '('+ chr(ord('a') + i) +')', horizontalalignment='center', transform=ax.transAxes, fontsize=18, color='white') A = cgl.Fourier2Config(states[i]) aA = np.abs(A).T im = ax.imshow(aA, cmap=plt.get_cmap('jet'), aspect='equal', origin='lower', extent=[0, d, 0, d]) dr = make_axes_locatable(ax) cax = dr.append_axes('right', size=0.08, pad=0.05) cax.tick_params(labelsize=18) plt.colorbar(im, cax=cax, ticks=[1, 2, 3]) #### fig.tight_layout(pad=1) plt.show(block=False) if case == 60: """ plot the estimated local error of 2d cgcgl by constant schemes """ err = np.loadtxt('data/cqcgl2d_N30_lte.dat') lss = ['--', '-.', ':', '-', '-', '-', '-'] n = err.shape[0] T = 20.0 x = np.arange(1, n+1) * T/n fig, ax = pl2d(size=[6, 5], labs=[r'$t$', r'estimated local error'], axisLabelSize=20, tickSize=15, # xlim=[1e-8, 5e-3], # ylim=[1e-17, 1e-7], yscale='log') for i in range(Nscheme): ax.plot(x, err[:, i], lw=1.5, ls=lss[i], label=labels[i]) ax.locator_params(axis='y', numticks=5) ax.locator_params(axis='x', nbins=5) fig.tight_layout(pad=0) ax.legend(loc='lower right', ncol=2) plt.show(block=False) # ax2d(fig, ax, loc='lower right') fig, ax = pl2d(size=[6, 5], labs=[r'$t$', r'estimated local error'], axisLabelSize=20, tickSize=15, # xlim=[1e-8, 5e-3], # ylim=[1e-30, 1e-8], yscale='log') for i in range(Nscheme): ax.plot(x, err[:, Nscheme+i], lw=2, ls=lss[i], label=labels[i]) ax.locator_params(axis='y', numticks=4) ax.locator_params(axis='x', nbins=5) ax2d(fig, ax, loc='lower right') if case == 70: """ plot the time steps used in the process """ hs = [] for i in range(Nscheme): x = np.loadtxt('data/cqcgl2d_N50_hs_' + str(i) + '.dat') hs.append(x) T = 20.0 lss = ['--', '-.', ':', '-', '-', '-', '-'] fig, ax = pl2d(size=[6, 5], labs=[r'$t$', r'$h$'], axisLabelSize=20, tickSize=15, # xlim=[1e-8, 5e-3], # ylim=[2e-5, 2e-3], yscale='log') for i in range(Nscheme): n = len(hs[i]) x = np.arange(1, n+1) * T/n ax.plot(x, hs[i], lw=2, ls=lss[i], label=labels[i]) # ax.locator_params(axis='y', numticks=5) ax.locator_params(axis='x', nbins=5) fig.tight_layout(pad=0) ax.legend(loc='lower right', ncol=2) plt.show(block=False) # ax2d(fig, ax, loc='upper left') if case == 80: """ same as case 70 but in comoving frame plot the time steps used in the process """ hs = [] for i in range(Nscheme): x = np.loadtxt('data/cqcgl2d_N60_comoving_hs_' + str(i) + '.dat') hs.append(x) T = 20.0 lss = ['--', '-.', ':', '-', '-', '-', '-'] fig, ax = pl2d(size=[6, 5], labs=[r'$t$', r'$h$'], axisLabelSize=20, tickSize=15, # xlim=[1e-8, 5e-3], # ylim=[8e-6, 2e-2], yscale='log') for i in range(Nscheme): n = len(hs[i]) x = np.arange(1, n+1) * T/n ax.plot(x, hs[i], lw=1.5, ls=lss[i], label=labels[i]) ax.locator_params(axis='y', numticks=5) ax.locator_params(axis='x', nbins=5) fig.tight_layout(pad=0) ax.legend(loc='lower right', ncol=2) plt.show(block=False) # ax2d(fig, ax, loc='upper left') if case == 90: """ static & comoving frame plot the relative error, Nab, Nn vs rtol """ loadFlag = 1 err = np.loadtxt('data/new_cqcgl2d_N70_stat' + ('0' if loadFlag == 0 else '1') + '.dat') rtol = err[:, 0] hs = [] for i in range(Nscheme): s = '50' if loadFlag == 0 else '60_comoving' x = np.loadtxt('data/cqcgl2d_N' + s + '_hs_' + str(i) + '.dat') hs.append(x) fig = plt.figure(figsize=[12, 15]) #plot time step T = 20.0 lss = ['--', '-.', ':', '-', '-', '-', '-'] ax = fig.add_subplot('321') ax.text(0.5, 0.9, '(a)', horizontalalignment='center', transform=ax.transAxes, fontsize=18, color='black') ax.set_yscale('log') ax.set_xlabel(r'$t$', fontsize=20) ax.set_ylabel(r'$h$', fontsize=20) ax.set_ylim([3e-5, 2e-2] if loadFlag == 0 else [2e-5, 4e-2]) ax.tick_params(axis='both', which='major', labelsize=15) for i in range(Nscheme): n = len(hs[i]) x = np.arange(1, n+1) * T/n ax.plot(x, hs[i], lw=1.5, ls=lss[i], label=labels[i]) ax.locator_params(axis='y', numticks=5) ax.locator_params(axis='x', nbins=5) ax.legend(loc='lower right', ncol=2, fontsize=12) # plot Nab ax = fig.add_subplot('322') ax.text(0.5, 0.9, '(b)', horizontalalignment='center', transform=ax.transAxes, fontsize=18, color='black') ax.set_xscale('log') ax.set_xlabel(r'$rtol$', fontsize=20) ax.set_ylabel(r'$Nab$', fontsize=20) ax.set_ylim([0, 5000] if loadFlag == 0 else [0, 7000]) ax.tick_params(axis='both', which='major', labelsize=15) for i in range(2, 6): ax.plot(rtol, err[:, 5*i+1], lw=1.5, marker=mks[i], mfc='none', ms=8, label=labels[i]) ax.locator_params(axis='y', nbins=5) ax.locator_params(axis='x', numticks=5) ax.legend(loc='right', fontsize=12) # plot Nn ax = fig.add_subplot('323') ax.text(0.1, 0.9, '(c)', horizontalalignment='center', transform=ax.transAxes, fontsize=18, color='black') ax.set_xscale('log') ax.set_yscale('log') ax.set_xlabel(r'$rtol$', fontsize=20) ax.set_ylabel(r'$Nn$', fontsize=20) ax.set_ylim([8e3, 1e7]) ax.tick_params(axis='both', which='major', labelsize=15) for i in range(Nscheme): ax.plot(rtol, err[:, 5*i+2], lw=1.5, marker=mks[i], mfc='none', ms=8, label=labels[i]) ax.locator_params(axis='y', numticks=5) ax.locator_params(axis='x', numticks=5) ax.legend(loc='upper right', fontsize=12) # plot NReject ax = fig.add_subplot('324') ax.text(0.9, 0.9, '(d)', horizontalalignment='center', transform=ax.transAxes, fontsize=18, color='black') ax.set_xscale('log') # ax.set_yscale('log') ax.set_xlabel(r'$rtol$', fontsize=20) ax.set_ylabel(r'number of rejections', fontsize=15) ax.set_ylim([0, 180] if loadFlag == 0 else [0, 250]) ax.tick_params(axis='both', which='major', labelsize=15) for i in range(Nscheme): ax.plot(rtol, err[:, 5*i+3], lw=1.5, marker=mks[i], mfc='none', ms=8, label=labels[i]) ax.locator_params(axis='y', numticks=5) ax.locator_params(axis='x', numticks=5) ax.legend(loc='upper left', ncol=2, fontsize=12) # plot Wt ax = fig.add_subplot('325') ax.text(0.1, 0.9, '(e)', horizontalalignment='center', transform=ax.transAxes, fontsize=18, color='black') ax.set_xscale('log') ax.set_yscale('log') ax.set_xlabel(r'$rtol$', fontsize=20) ax.set_ylabel(r'$Wt$', fontsize=20) ax.set_ylim([1e3, 1e6]) ax.tick_params(axis='both', which='major', labelsize=15) for i in range(Nscheme): ax.plot(rtol, err[:, 5*i+4], lw=1.5, marker=mks[i], mfc='none', ms=8, label=labels[i]) ax.locator_params(axis='y', numticks=5) ax.locator_params(axis='x', numticks=5) ax.legend(loc='upper right', fontsize=12) # plot time of calculating coefficients / Wt ax = fig.add_subplot('326') ax.text(0.07, 0.9, '(f)', horizontalalignment='center', transform=ax.transAxes, fontsize=18, color='black') ax.set_xscale('log') ax.set_yscale('log') ax.set_xlabel(r'$rtol$', fontsize=20) ax.set_ylabel(r'time ratio', fontsize=15) ax.set_ylim([1e-6, 2e0]) ax.tick_params(axis='both', which='major', labelsize=15) for i in range(Nscheme): ax.plot(rtol, err[:, 5*i+5]/err[:, 5*i+4], lw=1.5, marker=mks[i], mfc='none', ms=8, label=labels[i]) ax.locator_params(axis='y', numticks=4) ax.locator_params(axis='x', numticks=5) ax.legend(loc='lower right', ncol=2, fontsize=12) ## fig.tight_layout(pad=1) plt.show(block=False) <file_sep>/* to compile: * g++ test_ksintM1.cc -std=c++0x -lksint -lfftw3 -I ../../include/ -L ../../lib/ -I $XDAPPS/eigen/include/eigen3 */ #include "ksintM1.hpp" #include <Eigen/Dense> #include <iostream> using namespace std; using namespace Eigen; int main(){ /* ------------------------------------------------------- */ switch (2) { case 1: { ArrayXd a0 = ArrayXd::Ones(30) * 0.1; a0(1) = 0.0; KSM1 ks(32, 0.1, 22); std::pair<ArrayXXd, ArrayXd> at = ks.intg(a0, 2000, 2000); cout << at.first << endl; cout << at.second << endl; break; } case 2: { ArrayXd a0 = ArrayXd::Ones(30) * 0.1; a0(1) = 0.0; KSM1 ks(32, 0.1, 22); std::pair<ArrayXXd, ArrayXd> at = ks.intg2(a0, 2, 1); cout << at.first.cols()<< endl; cout << at.first.rows() << endl; cout << at.second.tail(1) << endl; break; } default : { cout << "please indicate the correct index." << endl; } } return 0; } <file_sep>from ksHelp import * from py_ks import * from personalFunctions import * class Sym(): """ Parameters ========== N : number of Fourier modes in KS L : domain size of KS pSlice : Fourier mode index used to define slice pFund : Fourier mode index used to define fundamental domain toY : whether rotate to the positive Y axis """ N, L = 64, 22 ks = pyKS(N, L) ksp = KSplot(ks) def __init__(self, pSlice, toY, pFund): self.pSlice = pSlice self.pFund = pFund self.toY = toY def getMuFullState(self, x0, v0, v1=None, T=200, r0=1e-5, nn=30, b=1): """ get the unstable mainifold in the full state space case 1: ------- For a complex pair (the case of E1 and E2), we use distribution a0 = x0 + r0 * exp(s) * v0 Here, s = np.arange(0, nn, b). For real case, b = 1. For complex case, b = 2 * pi * |mu / nv| with (mu + i * nv) the stability exponent. case 2: ------- For two degerate real unstable directions (the case of E3), we use distribution a0 = x0 + r0 * (v1*cos + v2*sin) Here, we v1 and v2 are orthornormal. --------- return : aars : orbits in reduced fundamental domain dom : domain indices jumps : jumping indices """ aars = [] dom = [] jumps = [] if v1 is not None: v0 = v0 / LA.norm(v0) v1p = v1 - np.dot(v0, v1) * v0 v1p = v1p / LA.norm(v1p) for i in range(nn): if v1 is None: # case 1 s = np.double(i) / nn * b a0 = x0 + r0 * np.exp(s) * v0 else: # case 2 th = i * 2 * np.pi / nn a0 = x0 + r0 * (np.cos(th) * v0 + np.cos(th) * v1p) aa = self.ks.aintg(a0, 0.01, T, 1) raa, dids, ths = self.ks.redO2f(aa, self.pSlice, self.pFund) aars.append(raa) dom.append(dids) jumps.append(getJumpPts(dids)) return aars, dom, jumps class Eq(Sym): """ equilibrium class """ def __init__(self, a0, r, pSlice, toY, pFund, DoGetSliceState=True, DoCalculateEsEv=True, DoGetGroupOrbit=True): Sym.__init__(self, pSlice, toY, pFund) self.a0 = a0 self.r = r # error self.go = None # group orbit self.so = None # state in the slice self.es = None # stability exponents self.ev = None # stability eigenvectors self.evr = None # stability eigenvectors in real format self.rev = None # in-slice stability eigenvectors # ev is in cloumn format. While evr and rev are in row format if DoGetSliceState: self.so = self.ks.redO2f(self.a0, pSlice, pFund)[0] # E2 and E3 may be in the slice border, so # just obtain their group orbits if DoGetGroupOrbit: n = 100 self.go = np.zeros((n, self.N-2)) for i in range(n): th = 2*i*np.pi / n self.go[i] = self.ks.Rotation(a0, th) # get the eigenvector of eq/req if DoCalculateEsEv: self.es, self.ev = self.getEsEv() self.evr = Tcopy(realve(self.ev)) self.rev = self.ks.redV(self.evr, self.a0, self.pSlice, True) def getEsEv(self): es, ev = self.ksp.stabEig(self.a0) return es, ev def getMu(self, vId, T=200, r0=1e-5, nn=30): """ obtain the unstable manifold of eq Some properties: 1) unstable manifold of E2 is in the antisymmetric subspace. 2) When we check the the correctness of rev of E3. rev[2] does not vanish becuase E3 is in the slice border. """ v0, v1 = self.evr[vId], self.evr[vId+1] # default case 2 b = 1 if np.iscomplex(self.es[vId]): # case 1 v1 = None b = 2 * np.pi * np.abs(self.es[vId].real / self.es[vId].imag) return self.getMuFullState(self.a0, v0, v1, T=T, r0=r0, nn=nn, b=b) class Req(Eq): """ relative equilibrium class """ def __init__(self, a0, w, r, pSlice, toY, pFund, DoGetSliceState=True, DoCalculateEsEv=True, DoGetGroupOrbit=True): self.w = w Eq.__init__(self, a0, r, pSlice, toY, pFund, DoGetSliceState, DoCalculateEsEv, DoGetGroupOrbit) def getEsEv(self): es, ev = self.ksp.stabReqEig(self.a0, self.w) return es, ev class PPO(Sym): """ ppo class """ def __init__(self, a0, T, nstp, r, pSlice, toY, pFund, DoGetFullOrbit=True, DoGetInsliceOrbit=True, DoGetFundOrbit=True): Sym.__init__(self, pSlice, toY, pFund) self.a0 = a0 self.T = T self.nstp = nstp self.r = r # error self.fo = None # full state space orbit self.so = None # slice orbit self.fdo = None # fundamental domain orbit self.po = None # projected orbit self.pp = None # Poincare point self.ppp = None # Projected Poincare point self.dids = None # domain ids self.jumps = None # domain jump index self.ths = None # slice angles ########## if DoGetFullOrbit: h = T / nstp self.fo = self.ks.intg(a0, h, nstp, 5) if DoGetInsliceOrbit: self.so, self.ths = self.ks.redSO2(self.fo, pSlice, toY) if DoGetFundOrbit: self.fdo, self.dids = self.ks.fundDomain(self.so, pSlice, pFund) self.jumps = getJumpPts(self.dids) class RPO(PPO): """ rpo class """ def __init__(self, a0, T, nstp, r, s, pSlice, toY, pFund, DoGetFullOrbit=True, DoGetInsliceOrbit=True, DoGetFundOrbit=True): PPO.__init__(self, a0, T, nstp, r, pSlice, toY, pFund, DoGetFullOrbit, DoGetInsliceOrbit, DoGetFundOrbit) self.s = s # shift class Inv(Sym): """ This class is designed to study the structure of KS system in the symmetry reduced fundamental state space. "Inv" means invariant structures in this system. Slice is chosen to make the pth mode's real part zero. Note, for 1st mode slice, E2 and E3 are on the slice border, it makes no sence to reduce symmetry for them, nor for the projection of vectors. """ def __init__(self, reqFile, poFile, pSlice, toY, pFund, ppoIds=[], rpoIds=[]): """ reqFile : the file storing reqs poFile: the file storing ppo/rpo and Floquet vectors ------- Es : the 3 equilibria TWs : the 2 relative equilibria ppos : a list of ppo rpos : a list of rpo ppoIds : indices of ppo rpoIds : indices of rpo """ Sym.__init__(self, pSlice, toY, pFund) self.reqFile = reqFile self.poFile = poFile self.ppoIds = ppoIds self.rpoIds = rpoIds self.Es, self.TWs, self.ppos, self.rpos = [], [], [], [] self.loadRE() self.loadPO() def loadRE(self): """ load all req and eq and their corresponding symmetry reduced states in the fundamental domain. reqFile : path to the req data file p : the fourier mode used to reduce symmetry """ # load req for i in range(2): a, w, err = self.ksp.readReq(self.reqFile, i+1) self.TWs.append(Req(a, w, err, self.pSlice, self.toY, self.pFund, self.ksp)) # load eq for i in range(3): a, err = self.ksp.readEq(self.reqFile, i+1) self.Es.append(Eq(a, err, self.pSlice, self.toY, self.pFund, self.ksp)) def loadPO(self): """ Load rpo and ppo and reduce the symmetry. If bases and orgin x0 are given, then also return the projection. This functions is called in the constructor, but it can also be called afterwards so as to refresh the rpo/ppo set """ self.ppos, self.rpos = [], [] for i in self.ppoIds: a0, T, nstp, r, s = self.ksp.readPO(self.poFile, 'ppo', i) self.ppos.append(PPO(a0, T, nstp, r, self.pSlice, self.toY, self.pFund)) for i in self.rpoIds: a0, T, nstp, r, s = self.ksp.readPO(self.poFile, 'rpo', i) self.rpos.append(RPO(a0, T, nstp, r, s, self.pSlice, self.toY, self.pFund)) def poPoincProject(self, bases, x0): for i in range(len(self.ppos)): self.ppos[i].ppp = (self.ppos[i].pp - x0).dot(bases.T) for i in range(len(self.rpos)): self.rpos[i].ppp = (self.rpos[i].pp - x0).dot(bases.T) def savePoPoincProject(self): ppo = [] rpo = [] for i in range(len(self.ppos)): ppo.append(self.ppos[i].ppp) for i in range(len(self.rpos)): rpo.append(self.rpos[i].ppp) np.savez_compressed('PoPoincare', ppo=ppo, rpo=rpo) def poFvPoinc(self, poType, poId, ptsId, p, ii, reflect=False): """ get the in-slice Floquet vector """ a0, T, nstp, r, s = KSreadPO(self.poFile, poType, poId) h = T / nstp aa = self.ks.intg(a0, h, nstp, 5) fe = KSreadFE(self.poFile, poType, poId) fv = KSreadFV(self.poFile, poType, poId)[ptsId].reshape(30, self.N-2) x0 = aa[ptsId] if reflect: x0 = self.ks.Reflection(x0) fv = self.ks.Reflection(fv) rfv = self.ks.redV(fv, x0, p, True) v1, v2, v3 = orthAxes(rfv[ii[0]], rfv[ii[1]], rfv[ii[2]]) bases = np.vstack((v1, v2, v3)) return fe, fv, rfv, bases def getMuAll(self, p, T=200, r0=1e-5, nn=30): """ get the unstable manifolds af all eq/req """ MuE = [] for i in range(3): a0 = self.eqr[i] v0 = ksreq.Ev['e'][i][0] aars, dom, jumps = self.getMu(a0, v0, p, T=T, r0=r0, nn=nn) MuE.append([aars, dom, jumps]) if i == 0: v0 = ksreq.Ev['e'][i][2] aars, dom, jumps = self.getMu(a0, v0, p, T=T, r0=r0, nn=nn) MuE.append([aars, dom, jumps]) if i == 2: v0 = ksreq.Ev['e'][i][1] aars, dom, jumps = self.getMu(a0, v0, p, T=T, r0=r0, nn=nn) MuE.append([aars, dom, jumps]) MuTw = [] for i in range(2): a0 = self.reqr[i] v0 = ksreq.Ev['tw'][i][0] aars, dom, jumps = self.getMu(a0, v0, p, T=T, r0=r0, nn=nn) MuTw.append([aars, dom, jumps]) if i == 0: v0 = ksreq.Ev['tw'][i][2] aars, dom, jumps = self.getMu(a0, v0, p, T=T, r0=r0, nn=nn) MuTw.append([aars, dom, jumps]) return MuE, MuTw def plotRE(self, ax, ii, doProject=False, do3d=True): """ construct the plotting block for req/eq """ c1 = ['r', 'b'] for i in range(2): x = self.TWs[i].so if do3d: ax.scatter(x[ii[0]], x[ii[1]], x[ii[2]], c=c1[i], s=70, edgecolors='none', label='TW'+str(i+1)) else: ax.scatter(x[ii[0]], x[ii[1]], c=c1[i], s=70, edgecolors='none', label='TW'+str(i+1)) c2 = ['c', 'k', 'y'] for i in range(3): x = self.Es[i].so if do3d: ax.scatter(x[ii[0]], x[ii[1]], x[ii[2]], c=c2[i], s=70, edgecolors='none', label='E'+str(i+1)) else: ax.scatter(x[ii[0]], x[ii[1]], c=c2[i], s=70, edgecolors='none', label='E'+str(i+1)) def plotFundOrbit(self, ax, faa, jumps, ii, c=None, alpha=0.5, lw=1, label=None): """ plot orbit in the fundamental domain. sudden jumps are avoided. faa : a single orbit in the fundamental domain jumps : indices where orbit jumps from one domain to another ii : the plot index """ if c is None: c = rand(3, 1) x = np.concatenate(([-1], jumps, [len(faa)-1])) for i in range(len(x)-1): r = range(x[i]+1, x[i+1]+1) if i == 0: ax.plot(faa[r, ii[0]], faa[r, ii[1]], faa[r, ii[2]], c=c, alpha=alpha, lw=lw, label=label) else: ax.plot(faa[r, ii[0]], faa[r, ii[1]], faa[r, ii[2]], c=c, alpha=alpha, lw=lw) def getBases(self, etype, eId, ii): """ get projection bases x0 : origin bases : selected bases """ v = self.Evr[etype][eId] v1, v2, v3 = orthAxes(v[ii[0]], v[ii[1]], v[ii[2]]) bases = np.vstack((v1, v2, v3)) x0 = self.Eqr[etype][eId].dot(bases.T) self.EqrP['e'] = self.Eqr['e'].dot(bases.T) - x0 self.EqrP['tw'] = self.Eqr['tw'].dot(bases.T) - x0 E2 = self.Eg['E2'].dot(bases.T) - x0 E3 = self.Eg['E3'].dot(bases.T) - x0 self.EgP = {'E2': E2, 'E3': E3} return x0, bases def getPoinc(self, raa, jumps, first): """ get the poincare intersection points. Poincare section is b_2 = 0 from negative to positive. Note it is very important to record the point after crossing Poincare section. Also both crossings are recorded due to reflection symmetry, but the order should be shuffled. -------- Paramters raa : orbit in the fundamental domain dids : indices of regions jumps : indices when orbit crosses Poincare section Return borderIds : indices of intersection points which are in the 1st region borderPts : the corresponding points start : starting index from negative to positive """ case = 1 if case == 1: """ Poincare section is the reflection border """ n = len(jumps) borderPts = np.zeros((n, raa.shape[1])) # for i in range(n): # j = jumps[i] # if j < 0: # # interp1d works for every row # f = interp1d(raa[j-1:j+2, 2], raa[j-1:j+2].T, kind='quadratic') # else: # f = interp1d(raa[j:j+2, 2], raa[j:j+2].T, kind='linear') # borderPts[i] = f(0) for i in range(n): j = jumps[i] x1, x2 = raa[j], raa[j+1] x1 = self.ks.Reflection(x1) p = np.vstack((x1, x2)) f = interp1d(p[:, 2], p.T, kind='linear') borderPts[i] = f(0) if case == 2: """ c_1 = 0.3 is the Poincare section """ n = raa.shape[0] borderPts = np.zeros((0, raa.shape[1])) for i in range(n-1): if raa[i, 6] < 0 and raa[i+1, 6] > 0: borderPts = np.vstack((borderPts, raa[i])) return borderPts <file_sep>#include <boost/python.hpp> #include <boost/numpy.hpp> #include <Eigen/Dense> #include <cstdio> #include "CQCGL2dReq.hpp" #include "myBoostPython.hpp" using namespace std; using namespace Eigen; namespace bp = boost::python; namespace bn = boost::numpy; ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// class pyCQCGL2dReq : public CQCGL2dReq { public: pyCQCGL2dReq(int N, int M, double dx, double dy, double Mu, double Dr, double Di, double Br, double Bi, double Gr, double Gi, int threadNum) : CQCGL2dReq(N, M, dx, dy, Mu, Dr, Di, Br, Bi, Gr, Gi, threadNum) {} pyCQCGL2dReq(int N, double dx, double Mu, double Dr, double Di, double Br, double Bi, double Gr, double Gi, int threadNum) : CQCGL2dReq(N, dx, Mu, Dr, Di, Br, Bi, Gr, Gi, threadNum) {} pyCQCGL2dReq(int N, int M, double dx, double dy, double b, double c, double dr, double di, int threadNum) : CQCGL2dReq(N, M, dx, dy, b, c, dr, di, threadNum) {} pyCQCGL2dReq(int N, double dx, double b, double c, double dr, double di, int threadNum) : CQCGL2dReq(N, dx, b, c, dr, di, threadNum) {} bn::ndarray PYTs(){ return copy2bn(Ts); } bn::ndarray PYlte(){ return copy2bn(lte); } bn::ndarray PYhs(){ return copy2bn(hs); } /* Kx */ bn::ndarray PYKx(){ return copy2bn(Kx); } /* Ky */ bn::ndarray PYKy(){ return copy2bn(Ky); } /* L */ bn::ndarray PYL(){ return copy2bnc(L); } /* wrap the integrator */ bn::ndarray PYintg(bn::ndarray a0, double h, int Nt, int skip_rate, bool doSaveDisk, string fileName){ int m, n; getDims(a0, m, n); Map<ArrayXXcd> tmpa((dcp*)a0.get_data(), n, m); return copy2bnc(intg(tmpa, h, Nt, skip_rate, doSaveDisk, fileName)); } bn::ndarray PYaintg(bn::ndarray a0, double h, double tend, int skip_rate, bool doSaveDisk, string fileName){ int m, n; getDims(a0, m, n); Map<ArrayXXcd> tmpa((dcp*)a0.get_data(), n, m); return copy2bnc(aintg(tmpa, h, tend, skip_rate, doSaveDisk, fileName)); } bn::ndarray PYintgv(bn::ndarray a0, bn::ndarray v0, double h, int Nt, int skip_rate, bool doSaveDisk, string fileName){ int m, n; getDims(a0, m, n); Map<ArrayXXcd> tmpa((dcp*)a0.get_data(), n, m); getDims(v0, m, n); Map<ArrayXXcd> tmpv((dcp*)v0.get_data(), n, m); return copy2bnc(intgv(tmpa, tmpv, h, Nt, skip_rate, doSaveDisk, fileName)); } bn::ndarray PYaintgv(bn::ndarray a0, bn::ndarray v0, double h, double tend, int skip_rate, bool doSaveDisk, string fileName){ int m, n; getDims(a0, m, n); Map<ArrayXXcd> tmpa((dcp*)a0.get_data(), n, m); getDims(v0, m, n); Map<ArrayXXcd> tmpv((dcp*)v0.get_data(), n, m); return copy2bnc(aintgv(tmpa, tmpv, h, tend, skip_rate, doSaveDisk, fileName)); } bn::ndarray PYFourier2Config(bn::ndarray aa){ int m, n; getDims(aa, m, n); Map<ArrayXXcd> tmpaa((dcp*)aa.get_data(), n, m); return copy2bnc( Fourier2Config(tmpaa) ); } bn::ndarray PYConfig2Fourier(bn::ndarray AA){ int m, n; getDims(AA, m, n); Map<ArrayXXcd> tmpAA((dcp*)AA.get_data(), n, m); return copy2bnc( Config2Fourier(tmpAA) ); } bn::ndarray PYvelocity(bn::ndarray a0){ int m, n; getDims(a0, m, n); Map<ArrayXXcd> tmpa((dcp*)a0.get_data(), n, m); return copy2bnc(velocity(tmpa)); } bn::ndarray PYvelocityReq(bn::ndarray a0, double wthx, double wthy, double wphi){ int m, n; getDims(a0, m, n); Map<ArrayXXcd> tmpa((dcp*)a0.get_data(), n, m); return copy2bnc(velocityReq(tmpa, wthx, wthy, wphi)); } bp::tuple PYfindReq_hook(bn::ndarray x0, double wthx0, double wthy0, double wphi0){ int m, n; getDims(x0, m, n); Map<ArrayXXcd> tmpx0((dcp*)x0.get_data(), n, m); auto result = findReq_hook(tmpx0, wthx0, wthy0, wphi0); return bp::make_tuple(copy2bnc(std::get<0>(result)), std::get<1>(result), std::get<2>(result), std::get<3>(result), std::get<4>(result) ); } bn::ndarray PYoptReqTh(bn::ndarray a0){ int m, n; getDims(a0, m, n); Map<ArrayXXcd> tmpa((dcp*)a0.get_data(), n, m); return copy2bn(optReqTh(tmpa)); } }; //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// BOOST_PYTHON_MODULE(py_CQCGL2dReq) { bn::initialize(); // must provide the constructor bp::class_<CQCGL2dReq>("CQCGL2dReq", bp::init< int, double, double, double, double, double, int>()) ; bp::class_<pyCQCGL2dReq, bp::bases<CQCGL2dReq> >("pyCQCGL2dReq", bp::init< int, double, double, double, double, double, int>()) .def(bp::init<int, int, double, double, double, double, double, double, double, double, double, int>()) .def(bp::init<int, double, double, double, double, double, double, double, double, int>()) .def(bp::init<int, int, double, double, double, double, double, double, int>()) .def_readonly("N", &pyCQCGL2dReq::N) .def_readonly("M", &pyCQCGL2dReq::M) .def_readonly("dx", &pyCQCGL2dReq::dx) .def_readonly("dy", &pyCQCGL2dReq::dy) .def_readonly("Mu", &pyCQCGL2dReq::Mu) .def_readonly("Br", &pyCQCGL2dReq::Br) .def_readonly("Bi", &pyCQCGL2dReq::Bi) .def_readonly("Dr", &pyCQCGL2dReq::Dr) .def_readonly("Di", &pyCQCGL2dReq::Di) .def_readonly("Gr", &pyCQCGL2dReq::Gr) .def_readonly("Gi", &pyCQCGL2dReq::Gi) .def_readonly("Ne", &pyCQCGL2dReq::Ne) .def_readonly("Me", &pyCQCGL2dReq::Me) // .def_readonly("b", &pyCQCGL2dReq::b) // .def_readonly("c", &pyCQCGL2dReq::c) // .def_readonly("dr", &pyCQCGL2dReq::dr) // .def_readonly("di", &pyCQCGL2dReq::di) .def_readonly("Omega", &pyCQCGL2dReq::Omega) .def_readwrite("rtol", &pyCQCGL2dReq::rtol) .def_readwrite("nu", &pyCQCGL2dReq::nu) .def_readwrite("mumax", &pyCQCGL2dReq::mumax) .def_readwrite("mumin", &pyCQCGL2dReq::mumin) .def_readwrite("mue", &pyCQCGL2dReq::mue) .def_readwrite("muc", &pyCQCGL2dReq::muc) .def_readwrite("NCalCoe", &pyCQCGL2dReq::NCalCoe) .def_readwrite("NReject", &pyCQCGL2dReq::NReject) .def_readwrite("NCallF", &pyCQCGL2dReq::NCallF) .def_readwrite("NSteps", &pyCQCGL2dReq::NSteps) .def_readwrite("Method", &pyCQCGL2dReq::Method) .def_readwrite("constETDPrint", &pyCQCGL2dReq::constETDPrint) .def_readwrite("tol", &pyCQCGL2dReq::tol) .def_readwrite("minRD", &pyCQCGL2dReq::minRD) .def_readwrite("maxit", &pyCQCGL2dReq::maxit) .def_readwrite("maxInnIt", &pyCQCGL2dReq::maxInnIt) .def_readwrite("GmresRtol", &pyCQCGL2dReq::GmresRtol) .def_readwrite("GmresRestart", &pyCQCGL2dReq::GmresRestart) .def_readwrite("GmresMaxit", &pyCQCGL2dReq::GmresMaxit) .def("Ts", &pyCQCGL2dReq::PYTs) .def("hs", &pyCQCGL2dReq::PYhs) .def("lte", &pyCQCGL2dReq::PYlte) .def("Kx", &pyCQCGL2dReq::PYKx) .def("Ky", &pyCQCGL2dReq::PYKy) .def("L", &pyCQCGL2dReq::PYL) .def("changeOmega", &pyCQCGL2dReq::changeOmega) .def("intg", &pyCQCGL2dReq::PYintg) .def("aintg", &pyCQCGL2dReq::PYaintg) .def("intgv", &pyCQCGL2dReq::PYintgv) .def("aintgv", &pyCQCGL2dReq::PYaintgv) .def("Fourier2Config", &pyCQCGL2dReq::PYFourier2Config) .def("Config2Fourier", &pyCQCGL2dReq::PYConfig2Fourier) .def("velocity", &pyCQCGL2dReq::PYvelocity) .def("velocityReq", &pyCQCGL2dReq::PYvelocityReq) .def("findReq_hook", &pyCQCGL2dReq::PYfindReq_hook) .def("optReqTh", &pyCQCGL2dReq::PYoptReqTh) ; } <file_sep>################################################## # Functions tool set ################################################## from time import time import h5py import matplotlib #matplotlib.use('Qt4Agg') #matplotlib.use('Qt5Agg') #from pylab import * import numpy as np from numpy.random import rand from scipy.spatial.distance import pdist, cdist, squareform import numpy.linalg as LA import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D from mpl_toolkits.axes_grid1 import make_axes_locatable from matplotlib.patches import FancyArrowPatch from mpl_toolkits.mplot3d import proj3d import matplotlib.animation as animation from mpl_toolkits.mplot3d.art3d import Poly3DCollection import os import subprocess as sps from numpy.linalg import norm from matplotlib.ticker import AutoMinorLocator from bisect import bisect_left ################################################## # Plot related # ################################################## class Arrow3D(FancyArrowPatch): """ The 3d arrow class """ def __init__(self, xs, ys, zs, *args, **kwargs): FancyArrowPatch.__init__(self, (0, 0), (0, 0), *args, **kwargs) self._verts3d = xs, ys, zs def draw(self, renderer): xs3d, ys3d, zs3d = self._verts3d xs, ys, zs = proj3d.proj_transform(xs3d, ys3d, zs3d, renderer.M) self.set_positions((xs[0], ys[0]), (xs[1], ys[1])) FancyArrowPatch.draw(self, renderer) def setvalue(self, x, y, z): self._verts3d = x, y, z def plinit(size=[8, 6]): fig = plt.figure(figsize=size) return fig def ax3dinit(fig, num=111, labs=[r'$x$', r'$y$', r'$z$'], axisLabelSize=25, tickSize=None, xlim=None, ylim=None, zlim=None, isBlack=False): ax = fig.add_subplot(num, projection='3d') if labs[0] is not None: ax.set_xlabel(labs[0], fontsize=axisLabelSize) if labs[1] is not None: ax.set_ylabel(labs[1], fontsize=axisLabelSize) if labs[2] is not None: ax.set_zlabel(labs[2], fontsize=axisLabelSize) if tickSize is not None: ax.tick_params(axis='both', which='major', labelsize=tickSize) if xlim is not None: ax.set_xlim(xlim) if ylim is not None: ax.set_ylim(ylim) if zlim is not None: ax.set_zlim(zlim) if isBlack: fig.patch.set_facecolor('black') ax.patch.set_facecolor('black') return ax def pl3d(size=[8, 6], labs=[r'$x$', r'$y$', r'$z$'], axisLabelSize=25, tickSize=None, xlim=None, ylim=None, zlim=None, isBlack=False): fig = plinit(size=size) ax = ax3dinit(fig, labs=labs, axisLabelSize=axisLabelSize, tickSize=tickSize, xlim=xlim, ylim=ylim, zlim=zlim, isBlack=isBlack) return fig, ax def ax3d(fig, ax, doBlock=False, save=False, name='output.png', angle=None, title=None, loc='best', alpha=0.2, picForm='png'): fig.tight_layout(pad=0) if angle is not None: ax.view_init(angle[0], angle[1]) if title is not None: ax.set_title(title) ax.legend(loc=loc, framealpha=alpha) if save: plt.savefig(name, format=picForm) plt.close() else: plt.show(block=doBlock) def add3d(fig, ax, x, y, z, maxShow=5, c='r', s=70): i = 0 pts = [] while raw_input(i) == '': if i >= len(x): for p in pts: p.remove() break if len(pts) > maxShow: p = pts.pop(0) p.remove() if len(pts) > 0: pts[-1].set_sizes([2*s]) if len(pts) > 1: pts[-2].set_sizes([s]) tmp = ax.scatter(x[i], y[i], z[i], c=c, s=s, edgecolors='none') pts.append(tmp) fig.canvas.draw() # plt.show(block=False) i += 1 def ax2dinit(fig, num=111, labs=[r'$x$', r'$y$'], axisLabelSize=25, xscale=None, yscale=None, xlim=None, ylim=None, tickSize=None, isBlack=False, ratio='auto'): ax = fig.add_subplot(num) if labs[0] is not None: ax.set_xlabel(labs[0], fontsize=axisLabelSize) if labs[1] is not None: ax.set_ylabel(labs[1], fontsize=axisLabelSize) if xscale is not None: ax.set_xscale(xscale) if yscale is not None: ax.set_yscale(yscale) if tickSize is not None: ax.tick_params(axis='both', which='major', labelsize=tickSize) if xlim is not None: ax.set_xlim(xlim) if ylim is not None: ax.set_ylim(ylim) if isBlack: fig.patch.set_facecolor('black') ax.patch.set_facecolor('black') ax.set_aspect(ratio) return ax def pl2d(size=[8, 6], num=111, labs=[r'$x$', r'$y$'], axisLabelSize=25, xscale=None, yscale=None, xlim=None, ylim=None, tickSize=None, isBlack=False, ratio='auto'): fig = plt.figure(figsize=size) ax = ax2dinit(fig, num=111, labs=labs, axisLabelSize=axisLabelSize, xscale=xscale, yscale=yscale, xlim=xlim, ylim=ylim, tickSize=tickSize, isBlack=isBlack, ratio=ratio) return fig, ax def ax2d(fig, ax, doBlock=False, save=False, name='output', title=None, loc='best', alpha=0.2): fig.tight_layout(pad=0) if title is not None: print "aaa" ax.set_title(title) ax.legend(loc=loc, framealpha=alpha) if save: plt.savefig(name + '.png', format='png') # plt.savefig(name + '.eps', format='eps') plt.close() else: plt.show(block=doBlock) def makeMovie(data): fig, ax = pl3d() frame, = ax.plot([], [], [], c='red', ls='-', lw=1, alpha=0.5) pts, = ax.plot([], [], [], 'co', lw=3) def anim(i): j = min(i, data.shape[0]) frame.set_data(data[:j, 0], data[:j, 1]) frame.set_3d_properties(data[:j, 2]) pts.set_data(data[j, 0], data[j, 1]) pts.set_3d_properties(data[j, 2]) ax.view_init(30, 0.5 * i) return frame, pts ani = animation.FuncAnimation(fig, anim, frames=data.shape[0], interval=0, blit=False, repeat=False) # ax3d(fig, ax) ax.legend() fig.tight_layout(pad=0) # ani.save('ani.mp4', dpi=200, fps=30, extra_args=['-vcodec', 'libx264']) plt.show() def plot1dfig(x, c='r', lw=1, ls='-', marker=None, labs=[r'$x$', r'$y$'], size=[8, 6], axisLabelSize=25, yscale=None): """ plot 2d figures in genereal """ fig = plt.figure(figsize=size) ax = fig.add_subplot(111) ax.plot(x, c=c, lw=lw, ls=ls, marker=marker) if labs[0] is not None: ax.set_xlabel(labs[0], fontsize=axisLabelSize) if labs[1] is not None: ax.set_ylabel(labs[1], fontsize=axisLabelSize) if yscale is not None: ax.set_yscale(yscale) fig.tight_layout(pad=0) plt.show(block=False) def plot2dfig(x, y, c='r', lw=1, ls='-', labs=[r'$x$', r'$y$'], size=[8, 6], axisLabelSize=25): """ plot 2d figures in genereal """ fig = plt.figure(figsize=size) ax = fig.add_subplot(111) ax.plot(x, y, c=c, lw=lw, ls=ls) ax.set_xlabel(labs[0], fontsize=axisLabelSize) ax.set_ylabel(labs[1], fontsize=axisLabelSize) fig.tight_layout(pad=0) plt.show(block=False) def scatter2dfig(x, y, s=20, marker='o', fc='r', ec='none', labs=[r'$x$', r'$y$'], size=[8, 6], axisLabelSize=25, ratio='auto'): fig = plt.figure(figsize=size) ax = fig.add_subplot(111) ax.scatter(x, y, s=s, marker=marker, facecolor=fc, edgecolors=ec) ax.set_xlabel(labs[0], fontsize=axisLabelSize) ax.set_ylabel(labs[1], fontsize=axisLabelSize) ax.set_aspect(ratio) fig.tight_layout(pad=0) plt.show(block=False) def plot3dfig(x, y, z, c='r', lw=1, labs=[r'$x$', r'$y$', r'$z$'], size=[8, 6], axisLabelSize=25): """ plot 3d figures in genereal """ fig = plt.figure(figsize=size) ax = fig.add_subplot(111, projection='3d') ax.plot(x, y, z, c=c, lw=lw) ax.set_xlabel(labs[0], fontsize=axisLabelSize) ax.set_ylabel(labs[1], fontsize=axisLabelSize) ax.set_zlabel(labs[2], fontsize=axisLabelSize) fig.tight_layout(pad=0) plt.show(block=False) def plotMat(y, colortype='jet', percent='5%', colorBar=True, save=False, name='out.png'): """ plot a matrix """ fig = plt.figure() ax = fig.add_subplot(111) im = ax.matshow(y, cmap=plt.get_cmap(colortype)) ax.grid('on') if colorBar: dr = make_axes_locatable(ax) cax = dr.append_axes('right', size=percent, pad=0.05) plt.colorbar(im, cax=cax) if save: plt.savefig(name) plt.close() else: plt.show(block=False) def plotIm(y, ext, size=[4, 5], labs=[r'$x$', r'$y$'], colortype='jet', percent='5%', axisLabelSize=25, barTicks=None, tickSize=None, save=False, name='out.png'): """ plot the imag color map of a matrix. It has more control compared with plotMat """ fig, ax = pl2d(size=size, labs=labs, axisLabelSize=axisLabelSize) im = ax.imshow(y, cmap=plt.get_cmap(colortype), extent=ext, aspect='auto', origin='lower') ax.grid('on') dr = make_axes_locatable(ax) cax = dr.append_axes('right', size=percent, pad=0.05) if barTicks is not None: plt.colorbar(im, cax=cax, ticks=barTicks) else: plt.colorbar(im, cax=cax) if tickSize is not None: ax.tick_params(axis='both', which='major', labelsize=tickSize) ax2d(fig, ax, save=save, name=name) def plotContour(z, x=None, y=None, size=[8, 6], labs=[r'$x$', r'$y$'], axisLabelSize=25, save=False, name='output.png', title=None, loc='best'): fig, ax = pl2d(size=size, labs=labs, axisLabelSize=axisLabelSize) if x is None or y is None: m, n = z.shape x = np.arange(n) y = np.arange(m) X, Y = np.meshgrid(x, y) CS = ax.contour(X, Y, z) ax.clabel(CS, inline=1, fontsize=10) ax2d(fig, ax, save=save, name=name, title=title, loc=loc) ############################################################ # Common functions # ############################################################ def sortByReal(eigvalue, eigvector=None): indx = np.argsort(eigvalue.real) indx = indx[::-1] if eigvector is None: return eigvalue[indx] else: return eigvalue[indx], eigvector[:, indx] def pAngleVQ(V, Q): """ compute the angle between a vector V and set of vectors Q Q is an orthonormal matrix """ assert V.ndim == 1 V = V / LA.norm(V) c = LA.norm(np.dot(Q.T, V)) if (c > 1): c = 1 return np.arccos(c) def pAngle(V, U): """ compute the principle angle between a vector V and a subspace U """ q = LA.qr(U)[0] return pAngleVQ(V, q) def vecAngle(v, u): """ compute the angle between two vectors """ return np.arccos(v.dot(u) / norm(v) / norm(u)) def seqAng(seqDifv, U): """ seqDifv is a sequence of row vector """ q = LA.qr(U)[0] M, N = seqDifv.shape ang = np.zeros(M) for i in range(M): ang[i] = pAngle(seqDifv[i, :], q) return ang def findMarginal(e, k): """ find the position of marginal exponents """ ix = argsort(abs(e)) return ix[:k] def removeMarginal(e, k): ix = findMarginal(e, k) ep = [i for i in e if i not in e[ix]] return ep def centerRand(N, frac, isComplex=True): """ generate a localized random vector. frac: the fraction of the nonzero center in the totol size """ if isComplex: a = rand(N) + 1j*rand(N) else: a = rand(N) N2 = np.int((1-frac)*0.5*N) a[:N2] = 0 a[-N2:] = 0 return a def centerRand2d(M, N, f1, f2, isComplex=True): """ generatate a localized random MxN matrix """ if isComplex: a = rand(M, N) + 1j*rand(M, N) + 0.5 else: a = rand(M, N) M2 = np.int((1-f1)*0.5*M) N2 = np.int((1-f2)*0.5*N) a[:M2, :] = 0 a[-M2:, :] = 0 a[:, :N2] = 0 a[:, -N2:] = 0 return a def centerOne(N, frac): """ generate a localized random vector. frac: the fraction of the nonzero center in the totol size """ a = ones(N) N2 = np.int((1-frac)*0.5*N) a[:N2] = 0 a[-N2:] = 0 return a def Tcopy(x): """ transpose and change the memory layout """ m, n = x.shape y = np.zeros((n, m)) for i in range(n): y[i] = x[:, i] return y def realve(ve): """ transform complex vectors to real format """ n, m = ve.shape rve = np.zeros((n, m)) i = 0 while i < m: if np.sum(np.iscomplex(ve[:, i])) > 0: rve[:, i] = ve[:, i].real rve[:, i+1] = ve[:, i].imag i = i+2 else: rve[:, i] = ve[:, i].real i = i+1 return rve def orthAxes2(e1, e2): """ construct an orthogonal two vectors from 2 general vectors. """ n = e1.shape[0] x = np.zeros((n, 2)) x[:, 0] = e1 x[:, 1] = e2 q, r = LA.qr(x) return q[:, 0], q[:, 1] def orthAxes(e1, e2, e3): n = e1.shape[0] x = np.zeros((n, 3)) x[:, 0] = e1 x[:, 1] = e2 x[:, 2] = e3 q, r = LA.qr(x) # q is a [N x 3] matrix # return q[:, 0], q[:, 1], q[:, 2] return q def mag2vec(v1, v2): return np.sqrt(v1**2 + v2**2) def normR(x): """ the norm of each row of a matrix """ return norm(x, axis=1) def int2p(x, y, k=0): """ interpolate two points """ c1 = y[k] / (y[k] - x[k]) c2 = -x[k] / (y[k] - x[k]) return c1 * x + c2 * y, c1 def rotz(x, y, th): """ rotate by z axis """ c = np.cos(th) s = np.sin(th) return c * x - s * y, s * x + c * y def difMap(x, farSize, size=[6, 6], percent='5%', colortype='jet'): m, n = x.shape y = np.zeros((m, farSize)) for i in range(m-farSize): y[i] = norm(x[i]-x[i:i+farSize], axis=1) fig = plt.figure(figsize=size) ax = fig.add_subplot(111) # ax.set_xlabel('x', fontsize=axisLabelSize) # ax.set_ylabel('t', fontsize=axisLabelSize) im = ax.imshow(y, cmap=plt.get_cmap(colortype), aspect='auto', origin='lower') ax.grid('on') dr = make_axes_locatable(ax) cax = dr.append_axes('right', size=percent, pad=0.05) plt.colorbar(im, cax=cax) fig.tight_layout(pad=0) plt.show(block=False) def difMap2(x1, x2, size=[6, 4], percent='5%', colortype='jet'): """ try to locate the possible po """ y = cdist(x1, x2) fig = plt.figure(figsize=size) ax = fig.add_subplot(111) # ax.set_xlabel('x', fontsize=axisLabelSize) # ax.set_ylabel('t', fontsize=axisLabelSize) im = ax.imshow(y, cmap=plt.get_cmap(colortype), aspect='auto', origin='lower') ax.grid('on') dr = make_axes_locatable(ax) cax = dr.append_axes('right', size=percent, pad=0.05) plt.colorbar(im, cax=cax) fig.tight_layout(pad=0) plt.show(block=False) def getJumpPts(x): """ for a sequence of integers x, try to get the locations when it jumps """ n = x.shape[0] d = x[1:] - x[:-1] y = np.arange(n-1) y = y[d != 0] return y def numStab(e, nmarg=2, tol=1e-8, flag=0): """ get the number of unstable exponents. Assume e is sorted by its real part. Parameters ====== nmarg : number of marginal eigenvalues of expolents flag : flag = 0 => exponents; flag = 1 => eigenvalues tol : tolerance to judge marginal exponents Return ====== m : number of unstable exponents or starting index for marginal exponent ep : exponents without marginal ones """ accu = True if flag == 0: x = e.real else: x = np.log(np.abs(e)) n = len(x) m = n-1 for i in range(n): if abs(x[i]) < tol: m = i break if m >= n-1: accu = False else: for i in range(m+1, min(m+nmarg, n)): if abs(x[i]) > tol: accu = False break ep = np.delete(e, range(m, m+nmarg)) return m, ep, accu <file_sep>import h5py import numpy as np from numpy.linalg import norm import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D import scipy.io as sio # from IPython.display import display # from IPython.html.widgets import interact from py_ks import * from personalFunctions import * ################################################## # load data f = h5py.File('../../data/myN32/ks22h02t100EV.h5', 'r') dataName1 = '/ppo/1/' a1 = f[dataName1 + 'a'].value T1 = f[dataName1 + 'T'].value[0] nstp1 = np.int(f[dataName1 + 'nstp'].value[0]) h1 = T1 / nstp1 e1 = f[dataName1 + 'e'].value ve1 = f[dataName1 + 've'].value dataName2 = '/rpo/2/' a2 = f[dataName2 + 'a'].value T2 = f[dataName2 + 'T'].value[0] nstp2 = np.int(f[dataName2 + 'nstp'].value[0]) h2 = T2 / nstp2 e2 = f[dataName2 + 'e'].value ve2 = f[dataName2 + 've'].value ################################################## # different experimental cases case = 3 if case == 1: """ visualize the orbit after reduce reflection symmetry projected into Fourier space """ ks1 = pyKS(32, h1, 22) aa1 = ks1.intg(a1, nstp1, 1) aa1 = aa1[:-1] # aaWhole1 = ks1.half2whole(aa1) aaWhole1 = aa1 aaHat1, ang1 = ks1.orbitToSlice(aaWhole1) aaTilde1 = ks1.reduceReflection(aaHat1) plot3dfig(aaHat1[:, 0], aaHat1[:, 2], aaHat1[:, 3]) plot3dfig(aaTilde1[:, 0], aaTilde1[:, 2], aaTilde1[:, 3]) if case == 2: """ see how ppo2 is shadowed by rpo1 after reducing O2 symmetry. Note: only integrate one period """ ks1 = pyKS(32, h1, 22) aa1 = ks1.intg(a1, nstp1, 1)[:-1] aaWhole1 = aa1 aaHat1, ang1 = ks1.orbitToSlice(aaWhole1) aaTilde1 = ks1.reduceReflection(aaHat1) ks2 = pyKS(32, h2, 22) aa2 = ks2.intg(a2, nstp2, 1) aa2 = aa2[:-1] aaHat2, ang2 = ks2.orbitToSlice(aa2) aaTilde2 = ks2.reduceReflection(aaHat2) plot3dfig2lines(aaTilde1[:, 0], aaTilde1[:, 2], aaTilde1[:, 3], aaTilde2[:, 0], aaTilde2[:, 2], aaTilde2[:, 3]) if case == 3: """ visualize how Floquet vectors are aligned along ppo/rpo """ ks1 = pyKS(32, h1, 22) aa1 = ks1.intg(a1, nstp1, 1) aa1 = aa1[:-1] aaWhole1 = ks1.half2whole(aa1) veWhole1 = ks1.half2whole(ve1) aaHat1, ang1 = ks1.orbitToSlice(aaWhole1) vep1 = ks1.veToSliceAll(veWhole1, aaWhole1, 0) ks2 = pyKS(32, h2, 22) aa2 = ks2.intg(a2, nstp2, 1) aa2 = aa2[:-1] aaHat2, ang2 = ks2.orbitToSlice(aa2) vep2 = ks2.veToSliceAll(ve2, aa2, 0) i1 = 0 i2 = 2 i3 = 3 fig = plt.figure(figsize=(8, 6)) ax = fig.add_subplot(111, projection='3d') ax.plot(aaHat1[:, i1], aaHat1[:, i2], aaHat1[:, i3], 'r') ax.plot(aaHat2[:, i1], aaHat2[:, i2], aaHat2[:, i3], 'g') spa = 70 ratio1 = 5 veIndex1 = 1 ah1 = aaHat1 nor1 = norm(vep1[veIndex1::30], axis=1) nor1.resize((nor1.size, 1)) ae1 = aaHat1 + vep1[veIndex1::30] / nor1 / ratio1 ratio2 = 5 veIndex2 = 1 ah2 = aaHat2 nor2 = norm(vep2[veIndex2::30], axis=1) nor2.resize((nor2.size, 1)) ae2 = aaHat2 + vep2[veIndex2::30] / nor2 / ratio2 shift = 900 ah1 = np.vstack((ah1[shift:], ah1[:shift])) ae1 = np.vstack((ae1[shift:], ae1[:shift])) for i in np.arange(0, aaHat1.shape[0]/2, spa): a1 = Arrow3D([ah1[i, i1], ae1[i, i1]], [ah1[i, i2], ae1[i, i2]], [ah1[i, i3], ae1[i, i3]], mutation_scale=20, lw=1.0, arrowstyle="-|>", color="m") ax.add_artist(a1) for i in np.arange(0, aaHat2.shape[0], spa): a2 = Arrow3D([ah2[i, i1], ae2[i, i1]], [ah2[i, i2], ae2[i, i2]], [ah2[i, i3], ae2[i, i3]], mutation_scale=20, lw=1.0, arrowstyle="-|>", color="k") ax.add_artist(a2) ax.set_xlabel(r'$b_1$') ax.set_ylabel(r'$b_2$') ax.set_zlabel(r'$c_2$') plt.tight_layout(pad=0) plt.show(block=False) if case == 4: """ visualize how Floquet vectors are aligned along ppo/rpo afeter reducing both rotation and reflection """ ks1 = pyKS(32, h1, 22) aa1 = ks1.intg(a1, nstp1, 1)[:-1] aaHat1, ang1 = ks1.orbitToSlice(aa1) vep1 = ks1.veToSliceAll(ve1, aa1, 0) aaTilde1 = ks1.reduceReflection(aaHat1) veTilde1 = ks1.reflectVeAll(vep1, aaHat1, 0) ks2 = pyKS(32, h2, 22) aa2 = ks2.intg(a2, nstp2, 1)[:-1] aaHat2, ang2 = ks2.orbitToSlice(aa2) vep2 = ks2.veToSliceAll(ve2, aa2, 0) aaTilde2 = ks2.reduceReflection(aaHat2) veTilde2 = ks2.reflectVeAll(vep2, aaHat2, 0) # load Burak's axes. # comment out this part if using Fourier modes projection ee = sio.loadmat('ee.mat')['ee'][:3].T aaTilde1 = np.dot(aaTilde1, ee) veTilde1 = np.dot(veTilde1, ee) aaTilde2 = np.dot(aaTilde2, ee) veTilde2 = np.dot(veTilde2, ee) i1 = 0 i2 = 1 i3 = 2 fig = plt.figure(figsize=(8, 6)) ax = fig.add_subplot(111, projection='3d') ax.plot(aaTilde1[:, i1], aaTilde1[:, i2], aaTilde1[:, i3], 'r') ax.plot(aaTilde2[:, i1], aaTilde2[:, i2], aaTilde2[:, i3], 'g') spa = 60 ratio1 = 5 ah1 = aaTilde1 veIndex1 = 0 nor1 = norm(veTilde1[veIndex1::30], axis=1) nor1.resize((nor1.size, 1)) ae1r = ah1 + veTilde1[veIndex1::30] / nor1 / ratio1 veIndex1 = 1 nor1 = norm(veTilde1[veIndex1::30], axis=1) nor1.resize((nor1.size, 1)) ae1i = ah1 + veTilde1[veIndex1::30] / nor1 / ratio1 ratio2 = 5 ah2 = aaTilde2 veIndex2 = 0 nor2 = norm(veTilde2[veIndex2::30], axis=1) nor2.resize((nor2.size, 1)) ae2r = ah2 + veTilde2[veIndex2::30] / nor2 / ratio2 veIndex2 = 1 nor2 = norm(veTilde2[veIndex2::30], axis=1) nor2.resize((nor2.size, 1)) ae2i = ah2 + veTilde2[veIndex2::30] / nor2 / ratio2 for i in np.arange(0, aaTilde1.shape[0], spa): a1 = Arrow3D([ah1[i, i1], ae1r[i, i1]], [ah1[i, i2], ae1r[i, i2]], [ah1[i, i3], ae1r[i, i3]], mutation_scale=20, lw=1.0, arrowstyle="-|>", color="m") ax.add_artist(a1) a1 = Arrow3D([ah1[i, i1], ae1i[i, i1]], [ah1[i, i2], ae1i[i, i2]], [ah1[i, i3], ae1i[i, i3]], mutation_scale=20, lw=1.0, arrowstyle="-|>", color="b") ax.add_artist(a1) for i in np.arange(0, aaTilde2.shape[0], spa): a2 = Arrow3D([ah2[i, i1], ae2r[i, i1]], [ah2[i, i2], ae2r[i, i2]], [ah2[i, i3], ae2r[i, i3]], mutation_scale=20, lw=1.0, arrowstyle="-|>", color="k") ax.add_artist(a2) a2 = Arrow3D([ah2[i, i1], ae2i[i, i1]], [ah2[i, i2], ae2i[i, i2]], [ah2[i, i3], ae2i[i, i3]], mutation_scale=20, lw=1.0, arrowstyle="-|>", color="c") ax.add_artist(a2) ax.set_xlabel(r'$e_1$', fontsize=25) ax.set_ylabel(r'$e_2$', fontsize=25) ax.set_zlabel(r'$e_3$', fontsize=25) plt.tight_layout(pad=0) plt.show(block=False) <file_sep>import plotly.plotly as py import plotly.offline as pyoff import plotly.graph_objs as go def ptlyTrace3d(x, y, z, plotType=0, lw=2, lc='blue', ls='solid', mc='red', ms=5, mt='circle', label=None): if plotType == 0: mode = 'lines' elif plotType == 1: mode = 'markers' else: mode = 'lines' + 'markers' trace = go.Scatter3d( x=x, y=y, z=z, mode=mode, marker=dict( size=ms, color=mc, symbol=mt, # "circle" | "square" | "diamond" | "cross" | "x" ), line=dict( color=lc, width=lw, dash=ls, # solid, dot, dash ), name=label ) return trace def ptlyLayout3d(labs=['$x$', '$y$', '$z$'], showLegend=False): layout = go.Layout( scene=go.Scene( xaxis=dict( title=labs[0], showbackground=True, backgroundcolor='rgb(230, 230,230)' ), yaxis=dict( title=labs[1], showbackground=True, backgroundcolor='rgb(230, 230,230)' ), zaxis=dict( title=labs[2], showbackground=True, backgroundcolor='rgb(230, 230,230)' ) ), margin=dict( b=0, l=0, r=0, t=0 ), showlegend=showLegend, ) return layout def ptly3d(trace, fileName, off=True, labs=['$x$', '$y$', '$z$'], showLegend=False): layout = ptlyLayout3d(labs=labs, showLegend=showLegend) fig = go.Figure(data=trace, layout=layout) if off: pyoff.plot(fig, filename=fileName) else: py.plot(fig, filename=fileName, fileopt='overwrite') def ptlyPlot3d(x, y, z, fileName, off=True, plotType=0, lw=2, lc='blue', ls='solid', mc='red', ms=5, mt='circle', label=None, labs=['$x$', '$y$', '$z$'], showLegend=False): trace = ptlyTrace3d(x, y, z, plotType=plotType, lw=lw, lc=lc, ls=ls, mc=mc, ms=ms, mt=mt, label=label) ptly3d([trace], fileName, off=off, labs=labs, showLegend=showLegend) <file_sep> std::pair<ArrayXXd, ArrayXXd> intgjMulti(const MatrixXd aa0, size_t nstp, size_t np, size_t nqr); std::tuple<MatrixXd, MatrixXd, VectorXd> calReqJJF(const Ref<const VectorXd> &x); std::tuple<VectorXd, double, double> findReq(const Ref<const VectorXd> &x, const double tol, const int maxit, const int innerMaxit); std::tuple<MatrixXd, MatrixXd, VectorXd> calEqJJF(const Ref<const VectorXd> &x); std::pair<VectorXd, double> findEq(const Ref<const VectorXd> &x, const double tol, const int maxit, const int innerMaxit); /*============================================================ * Class : Calculate KS Req LM *============================================================*/ template<class Mat> struct KSReqJJF { KS &ks; KSReqJJF(KS &ks_) : ks(ks_){} std::tuple<MatrixXd, MatrixXd, VectorXd> operator()(const VectorXd &x) { return ks.calReqJJF(x); } }; /*============================================================ * Class : Calculate KS Eq LM *============================================================*/ template<class Mat> struct KSEqJJF { KS &ks; KSEqJJF(KS &ks_) : ks(ks_){} std::tuple<MatrixXd, MatrixXd, VectorXd> operator()(const VectorXd &x) { return ks.calEqJJF(x); } }; <file_sep>/* to comiple: * h5c++ -O3 test_CQCGL2d.cc -L../../lib -I../../include -I $XDAPPS/eigen/include/eigen3 -std=c++11 -lCQCGL2d -lsparseRoutines -ldenseRoutines -lmyH5 -lmyfft -lfftw3 -lm */ #include "CQCGL2d.hpp" #include "myH5.hpp" #include "denseRoutines.hpp" #include <iostream> #include <fstream> #include <Eigen/Dense> #include <complex> #include <H5Cpp.h> #define CE(x) (cout << (x) << endl << endl) using namespace std; using namespace Eigen; using namespace MyH5; using namespace denseRoutines; typedef std::complex<double> dcp; int main(){ switch(2){ case 1: { /* test integrator */ int N = 1024; double L = 30; double di = 0.3; CQCGL2d cgl(N, L, 4.0, 0.8, 0.05, di, 4); ArrayXXcd A0 = 3*center2d<dcp>(N, N, 0.2, 0.2, 2); ArrayXXcd a0 = cgl.Config2Fourier(A0); ArrayXXcd A2 = cgl.Fourier2Config(a0); ArrayXXcd aa = cgl.intg(a0, 0.001, 10, 1, true, "ex.h5"); CE(a0.rows()); CE(a0.cols()); CE(aa.rows()); CE(aa.cols()); break; } case 2:{ /* test r2c and c2r */ int N = 1024; double L = 30; double di = 0.3; CQCGL2d cgl(N, L, 4.0, 0.8, 0.05, di, 4); ArrayXXcd x(ArrayXXcd::Random(3, 4)); ArrayXXd y = cgl.c2r(x); ArrayXXcd z = cgl.r2c(y); CE(x); CE(y); CE(z); break; } #if 0 case 3 :{ /* test Fourier2Config */ const int N = 256; const int L = 50; int nstp = 2; int nqr = 1; double h = 0.01; ArrayXd A0(2*N) ; // prepare Gaussian curve initial condition for(int i = 0; i < N; i++) { double x = (double)i/N*L - L/2.0; A0(2*i) = exp(-x*x/8.0); } Cqcgl1d cgl(N, L, h); ArrayXXd aa = cgl.intg(A0, nstp, nqr); ArrayXXd AA = cgl.Fourier2Config(aa); cout << AA.rows() << 'x' << AA.cols() << endl << "--------------" << endl; //cout << AA.col(2) << endl; //cout << A0 << endl; break; } case 4:{ /* test the new constructor */ const int N = 512; const int L = 50; double h = 0.001; Cqcgl1d cgl(N, L, h, false, 0, 0.1, 0.1, 0.1, 0.1, 4); const int Ndim = cgl.Ndim; int nstp = 1000; ArrayXd A0(2*N) ; // prepare Gaussian curve initial condition for(int i = 0; i < N; i++) { double x = (double)i/N*L - L/2.0; A0(2*i) = exp(-x*x/8.0); } ArrayXd a0 = cgl.Config2Fourier(A0).col(0); ArrayXXd AA = cgl.intg(a0, nstp, 1); cout << AA.rows() << 'x' << AA.cols() << endl << "--------------" << endl; cout << cgl.trueNjacv << endl; break; } case 5:{ /* test the cgl constructor */ const int N = 512; const int L = 50; double h = 0.001; Cgl1d cgl(N, L, h, false, 0, 0.1, 0.2, 4); const int Ndim = cgl.Ndim; cout << cgl.Mu << endl; cout << cgl.Br << endl; cout << cgl.Bi << endl; cout << cgl.Dr << endl; cout << cgl.Di << endl; cout << cgl.Gr << endl; cout << cgl.Gi << endl; cout << cgl.trueNjacv << endl; break; } case 6: { /* test reflectVe() * Find the reason why discrete symmetry reduction will produce NAN elements. * I find the answer is that my transformation is singular at point (0, 0). */ const int N = 1024; const int L = 30; const double h = 0.0002; const double di = 0.0799; std::string file("/usr/local/home/xiong/00git/research/data/cgl/req_different_di/req0799.h5"); VectorXd a0; double wth, wphi, err; CqcglReadReq(file, "1", a0, wth, wphi, err); Cqcgl1d cgl(N, L, h, true, 0, 4.0, 0.8, 0.01, di, 4); auto tmp = cgl.evReq(a0, wth, wphi); VectorXcd &e = tmp.first; MatrixXd v = realv(tmp.second); cout << e.head(10) << endl; ArrayXd a0Hat = cgl.orbit2sliceSimple(a0); ArrayXd a0Tilde = cgl.reduceReflection(a0Hat); MatrixXd vHat = cgl.ve2slice(v, a0); MatrixXd vTilde = cgl.reflectVe(vHat, a0Hat); MatrixXd G = cgl.refGradMat(a0Hat); MatrixXd G1 = cgl.refGrad1(); ArrayXd step1 = cgl.reduceRef1(a0Hat); ArrayXd step2 = cgl.reduceRef2(step1); MatrixXd G2 = cgl.refGrad2(step1); MatrixXd G3 = cgl.refGrad3(step2); cout << G.maxCoeff() << endl; cout << G.minCoeff() << endl << endl; MatrixXd tmp2(step1.size(), 4); tmp2 << a0Hat, step1, step2, a0Tilde; cout << tmp2 << endl << endl; // cout << G3.row(42) << endl << endl; // cout << (G * vHat.col(0)).head(50) << endl; // cout << vTilde.col(0).head(60) << endl; break; } case 7:{ /* see the spacing along a orbit * I find h = 0.0002 seems too large */ const int N = 1024; const int L = 30; const double h = 0.0002; const double di = 0.4; Cqcgl1d cgl(N, L, h, true, 0, 4.0, 0.8, 0.01, di, 4); std::string file("rpot.h5"); int nstp; double T, th, phi, err; MatrixXd x; CqcglReadRPO(file, "1", x, T, nstp, th, phi, err); printf("T %g, nstp %d, th %g, phi %g, err %g\n", T, nstp, th, phi, err); ArrayXXd aa = cgl.intg(x.col(0), nstp*10, 1); VectorXd sp = spacing(aa); cout << sp.maxCoeff() << endl; cout << aa.rightCols(1).matrix().norm() << endl; break; } #endif default: { fprintf(stderr, "please indicate a valid case number \n"); } } return 0; } <file_sep>#include "CQCGL1d.hpp" using namespace denseRoutines; // implementation notes // 1) not use fft.fwd(MatrixBase, MatrixBase) but use // fft.fwd(Complex * dst, const Complex * src, Index nfft) // becuase the former cannot work with Map<VectorXcd> type. // 2) In C++, initialization list will be evaluated in the order they were // declared in the class definition ////////////////////////////////////////////////////////////////////// // Inner Class CQCGL1d // ////////////////////////////////////////////////////////////////////// CQCGL1d::NL::NL(){} CQCGL1d::NL::NL(CQCGL1d *cgl, int cols) : cgl(cgl), N(cgl->N), B(cgl->Br, cgl->Bi), G(cgl->Gr, cgl->Gi) { AA.resize(cgl->N, cols); } CQCGL1d::NL::~NL(){} void CQCGL1d::NL::operator()(ArrayXXcd &x, ArrayXXcd &dxdt, double t){ int cs = x.cols(); assert(cs == dxdt.cols() && N == x.rows() && N == dxdt.rows()); for(int i = 0; i < cs; i++) cgl->fft.inv(AA.data() + i*N, x.data() + i*N, N); ArrayXcd A = AA.col(0); ArrayXcd aA2 = A * A.conjugate(); if (cgl->IsQintic) AA.col(0) = B * A * aA2 + G * A * aA2.square(); else AA.col(0) = B * A * aA2; if(cs > 1){ int M = cs - 1; ArrayXcd A2 = A.square(); if (cgl->IsQintic) AA.rightCols(M) = AA.rightCols(M).conjugate().colwise() * ((B+G*2.0*aA2) * A2) + AA.rightCols(M).colwise() * ((2.0*B+3.0*G*aA2)*aA2); else AA.rightCols(M) = AA.rightCols(M).conjugate().colwise() * (B * A2) + AA.rightCols(M).colwise() * (2.0*B*aA2); } for(int i = 0; i < cs; i++) cgl->fft.fwd(dxdt.data() + i*N, AA.data() + i*N, N); dxdt.middleRows(cgl->Nplus, cgl->Nalias).setZero(); // dealiaze } ////////////////////////////////////////////////////////////////////// // Class CQCGL1d // ////////////////////////////////////////////////////////////////////// /* ------------------------------------------------------ */ /* ---- constructor/destructor ------- */ /* ------------------------------------------------------ */ /** * Constructor of cubic quintic complex Ginzburg-Landau equation * A_t = Mu A + (Dr + Di*i) A_{xx} + (Br + Bi*i) |A|^2 A + (Gr + Gi*i) |A|^4 A * * @param[in] N the number of Fourier modes * @param[in] d the spacial period, size * @param[in] dimTan the dimension of tangent space * dimTan > 0 => dimTan * dimTan = 0 => Ndim * dimTan < 0 => 0 * * Dealiasing is the method to calculate correct convolution term. For centralized * FFT, it works as set Fourier modes a_k = 0 for wave number |k| > 2/3 * N. * More specifically, in this code, the middle part of modes * is set to zero. * * |<---------------------------------------------------------->| * FFT length: N * * |<--------------->|<--------------------->|<---------------->| * (Ne + 1) / 2 N - Ne (Ne - 1) /2 * = Nplus = Nalias = Nminus * * @Note each term has real and imaginary part, so the indices are * 0, 1, 2,... Nplus*2, Nplus*2+1,... 2*Ne-1 */ CQCGL1d::CQCGL1d(int N, double d, double Mu, double Dr, double Di, double Br, double Bi, double Gr, double Gi, int dimTan) : N(N), d(d), Mu(Mu), Dr(Dr), Di(Di), Br(Br), Bi(Bi), Gr(Gr), Gi(Gi), Ne((N/3) * 2 - 1), // make it an odd number Ndim(2 * Ne), Nplus((Ne + 1) / 2), Nminus((Ne - 1) / 2), Nalias(N - Ne), DimTan(dimTan == 0 ? Ndim : (dimTan > 0 ? dimTan : 0)), nl(this, 1), nl2(this, DimTan+1) { // calculate the Linear part K.resize(N,1); K << ArrayXd::LinSpaced(N/2, 0, N/2-1), N/2, ArrayXd::LinSpaced(N/2-1, -N/2+1, -1); K2.resize(Ne, 1); K2 << ArrayXd::LinSpaced(Nplus, 0, Nplus-1), ArrayXd::LinSpaced(Nminus, -Nminus, -1); QK = 2*M_PI/d * K; L = dcp(Mu, -Omega) - dcp(Dr, Di) * QK.square(); L.segment(Nplus, Nalias).setZero(); int nYN0 = eidc.names.at(eidc.scheme).nYN; // do not call setScheme here. Different. for(int i = 0; i < nYN0; i++){ Yv[i].resize(N, 1); Nv[i].resize(N, 1); Yv2[i].resize(N, DimTan+1); Nv2[i].resize(N, DimTan+1); } eidc.init(&L, Yv, Nv); eidc2.init(&L, Yv2, Nv2); } /** * Constructor of cubic quintic complex Ginzburg-Landau equation * A_t = -A + (1 + b*i) A_{xx} + (1 + c*i) |A|^2 A - (dr + di*i) |A|^4 A */ CQCGL1d::CQCGL1d(int N, double d, double b, double c, double dr, double di, int dimTan) : CQCGL1d::CQCGL1d(N, d, -1, 1, b, 1, c, -dr, -di, dimTan) {} CQCGL1d::CQCGL1d(int N, double d, double delta, double beta, double D, double epsilon, double mu, double nu, int dimTan) : CQCGL1d::CQCGL1d(N, d, delta, beta, D/2, epsilon, 1, mu, nu, dimTan) {} CQCGL1d::~CQCGL1d(){} CQCGL1d & CQCGL1d::operator=(const CQCGL1d &x){ return *this; } /* ------------------------------------------------------ */ /* ---- Integrator ------- */ /* ------------------------------------------------------ */ void CQCGL1d::setScheme(std::string x){ int nYN0 = eidc.names.at(eidc.scheme).nYN; eidc.scheme = x; int nYN1 = eidc.names.at(eidc.scheme).nYN; for (int i = nYN0; i < nYN1; i++) { Yv[i].resize(N, 1); Nv[i].resize(N, 1); Yv2[i].resize(N, DimTan+1); Nv2[i].resize(N, DimTan+1); } } void CQCGL1d::changeOmega(double w){ Omega = w; L = dcp(Mu, -Omega) - dcp(Dr, Di) * QK.square(); L.segment(Nplus, Nalias).setZero(); } /** @brief Integrator of 1d cqCGL equation. * * The intial condition a0 should be coefficients of the intial state: * [b0, c0 ,b1, c1,...] where bi, ci the real and imaginary parts of Fourier modes. * * @param[in] a0 initial condition of Fourier coefficents. Size : [2*N,1] * @return state trajectory. Each column is the state followed the previous column. */ ArrayXXd CQCGL1d::intgC(const ArrayXd &a0, const double h, const double tend, const int skip_rate){ assert( Ndim == a0.size()); ArrayXXcd u0 = R2C(a0); const int Nt = (int)round(tend/h); const int M = (Nt + skip_rate - 1) / skip_rate; ArrayXXcd aa(N, M); lte.resize(M); int ks = 0; auto ss = [this, &ks, &aa](ArrayXXcd &x, double t, double h, double err){ aa.col(ks) = x; lte(ks++) = err; }; eidc.intgC(nl, ss, 0, u0, tend, h, skip_rate); return C2R(aa); } std::pair<ArrayXXd, ArrayXXd> CQCGL1d::intgjC(const ArrayXd &a0, const double h, const double tend, const int skip_rate){ assert(a0.size() == Ndim && DimTan == Ndim); ArrayXXd v0(Ndim, Ndim+1); v0 << a0, MatrixXd::Identity(Ndim, Ndim); ArrayXXcd u0 = R2C(v0); const int Nt = (int)round(tend/h); const int M = (Nt + skip_rate - 1) / skip_rate; ArrayXXcd aa(N, M), daa(N, Ndim*M); lte.resize(M); int ks = 0; auto ss = [this, &ks, &aa, &daa](ArrayXXcd &x, double t, double h, double err){ aa.col(ks) = x.col(0); daa.middleCols(ks*Ndim, Ndim) = x.rightCols(Ndim); lte(ks++) = err; x.rightCols(Ndim) = R2C(MatrixXd::Identity(Ndim, Ndim)); }; eidc2.intgC(nl2, ss, 0, u0, tend, h, skip_rate); return std::make_pair(C2R(aa), C2R(daa)); } /** * @brief integrate the state and a subspace in tangent space */ ArrayXXd CQCGL1d::intgvC(const ArrayXd &a0, const ArrayXXd &v, const double h, const double tend){ assert( Ndim == a0.size() && Ndim == v.rows() && DimTan == v.cols()); ArrayXXd v0(Ndim, DimTan+1); v0 << a0, v; ArrayXXcd u0 = R2C(v0); const int Nt = (int)round(tend/h); ArrayXXcd aa(N, DimTan+1); auto ss = [this, &aa](ArrayXXcd &x, double t, double h, double err){ aa = x; }; eidc2.intgC(nl2, ss, 0, u0, tend, h, Nt); return C2R(aa); //both the final orbit and the perturbation } ArrayXXd CQCGL1d::intg(const ArrayXd &a0, const double h, const double tend, const int skip_rate){ assert( Ndim == a0.size()); ArrayXXcd u0 = R2C(a0); const int Nt = (int)round(tend/h); const int M = (Nt+skip_rate-1)/skip_rate; ArrayXXcd aa(N, M); Ts.resize(M); hs.resize(M); lte.resize(M); int ks = 0; auto ss = [this, &ks, &aa](ArrayXXcd &x, double t, double h, double err){ int m = Ts.size(); if (ks >= m ) { Ts.conservativeResize(m+cellSize); aa.conservativeResize(Eigen::NoChange, m+cellSize); // rows not change, just extend cols hs.conservativeResize(m+cellSize); lte.conservativeResize(m+cellSize); } hs(ks) = h; lte(ks) = err; aa.col(ks) = x; Ts(ks++) = t; }; eidc.intg(nl, ss, 0, u0, tend, h, skip_rate); hs.conservativeResize(ks); lte.conservativeResize(ks); Ts.conservativeResize(ks); aa.conservativeResize(Eigen::NoChange, ks); return C2R(aa); } std::pair<ArrayXXd, ArrayXXd> CQCGL1d::intgj(const ArrayXd &a0, const double h, const double tend, const int skip_rate){ assert(a0.size() == Ndim && DimTan == Ndim); ArrayXXd v0(Ndim, Ndim+1); v0 << a0, MatrixXd::Identity(Ndim, Ndim); ArrayXXcd u0 = R2C(a0); const int Nt = (int)round(tend/h); const int M = (Nt + skip_rate - 1) / skip_rate; ArrayXXcd aa(N, M), daa(N, Ndim*M); Ts.resize(M); hs.resize(M); lte.resize(M); int ks = 0; auto ss = [this, &ks, &aa, &daa](ArrayXXcd &x, double t, double h, double err){ int m = Ts.size(); if (ks >= m ) { Ts.conservativeResize(m+cellSize); hs.conservativeResize(m+cellSize); lte.conservativeResize(m+cellSize); aa.conservativeResize(Eigen::NoChange, m+cellSize); // rows not change, just extend cols daa.conservativeResize(Eigen::NoChange, (m+cellSize)*Ndim); } hs(ks) = h; lte(ks) = err; Ts(ks) = t; aa.col(ks) = x.col(0); daa.middleCols(ks*Ndim, Ndim) = x.rightCols(Ndim); x.rightCols(Ndim) = R2C(MatrixXd::Identity(Ndim, Ndim)); ks++; }; eidc2.intg(nl2, ss, 0, u0, tend, h, skip_rate); return std::make_pair(C2R(aa), C2R(daa)); } ArrayXXd CQCGL1d::intgv(const ArrayXXd &a0, const ArrayXXd &v, const double h, const double tend){ assert( Ndim == a0.size() && Ndim == v.rows() && DimTan == v.cols()); ArrayXXd v0(Ndim, DimTan+1); v0 << a0, v; ArrayXXcd u0 = R2C(v0); ArrayXXcd aa(N, DimTan+1); auto ss = [this, &aa](ArrayXXcd &x, double t, double h, double err){ aa = x; }; eidc2.intg(nl2, ss, 0, u0, tend, h, 1000000); return C2R(aa); } /** @brief transform conjugate matrix to its real form */ ArrayXXd CQCGL1d::C2R(const ArrayXXcd &v){ int n = v.rows(); int m = v.cols(); assert(N == n); ArrayXXcd vt(Ne, m); vt << v.topRows(Nplus), v.bottomRows(Nminus); return Map<ArrayXXd>((double*)(vt.data()), 2*vt.rows(), vt.cols()); } ArrayXXcd CQCGL1d::R2C(const ArrayXXd &v){ int n = v.rows(); int m = v.cols(); assert( n == Ndim); Map<ArrayXXcd> vp((dcp*)&v(0,0), Ne, m); ArrayXXcd vpp(N, m); vpp << vp.topRows(Nplus), ArrayXXcd::Zero(Nalias, m), vp.bottomRows(Nminus); return vpp; } ArrayXXd CQCGL1d::c2r(const ArrayXXcd &v){ return Map<ArrayXXd>((double*)&v(0,0), 2*v.rows(), v.cols()); } ArrayXXcd CQCGL1d::r2c(const ArrayXXd &v){ assert( 0 == v.rows() % 2); return Map<ArrayXXcd>((dcp*)&v(0,0), v.rows()/2, v.cols()); } /* -------------------------------------------------- */ /* ------- Fourier/Configure transformation -------- */ /* -------------------------------------------------- */ /** * @brief back Fourier transform of the states. */ ArrayXXcd CQCGL1d::Fourier2Config(const Ref<const ArrayXXd> &aa){ int cs = aa.cols(), rs = aa.rows(); assert(Ndim == rs); ArrayXXcd aac = R2C(aa); ArrayXXcd AA(N, cs); for(size_t i = 0; i < cs; i++) fft.inv(AA.data() + i*N, aac.data() + i*N, N); return AA; } /** * @brief Fourier transform of the states. Input and output are both real. */ ArrayXXd CQCGL1d::Config2Fourier(const Ref<const ArrayXXcd> &AA){ int cs = AA.cols(), rs = AA.rows(); assert(N == rs); ArrayXXcd aac(N, cs); for(size_t i = 0; i < cs; i++) fft.fwd(aac.data() + i*N, AA.data() + i*N, N); return C2R(aac); } ArrayXXd CQCGL1d::Fourier2ConfigMag(const Ref<const ArrayXXd> &aa){ return Fourier2Config(aa).abs(); } ArrayXXd CQCGL1d::calPhase(const Ref<const ArrayXXcd> &AA){ int m = AA.cols(); int n = AA.rows(); assert(N == n); ArrayXXd phase(n, m); for(size_t i = 0; i < m; i++) for(size_t j =0; j < n; j++) phase(j, i) = atan2(AA(j, i).imag(), AA(j, i).real()); return phase; } ArrayXXd CQCGL1d::Fourier2Phase(const Ref<const ArrayXXd> &aa){ return calPhase(Fourier2Config(aa)); } /** * @brief calculate the mean energy density * \frac{\int |A|^2 dx}{\int dx} = 1/N \sum |A_i|^2 = 1/N^2 \sum |a_i|^2 * = 1/N^2 \sum (a_r^2 + a_i^2) */ VectorXd CQCGL1d::calQ(const Ref<const ArrayXXd> &aa){ const int n = aa.cols(); VectorXd Q(n); for (int i = 0; i < n; i++){ Q(i) = aa.col(i).matrix().squaredNorm() / (N*N); } return Q; } VectorXd CQCGL1d::calMoment(const Ref<const ArrayXXd> &aa, const int p){ const int n = aa.cols(); VectorXd mom(n); ArrayXd x = ArrayXd::LinSpaced(N, 0, N-1) * d / N; ArrayXd xp = x; for(int i = 0; i < p-1; i++) xp *= x; ArrayXXcd AA = Fourier2Config(aa); for (int i = 0; i < n; i++){ ArrayXd A2 = (AA.col(i) * AA.col(i).conjugate()).real(); mom(i) = (A2 * xp).sum() / A2.sum(); } return mom; } /* -------------------------------------------------- */ /* -------- velocity field ----------- */ /* -------------------------------------------------- */ /** * @brief velocity field */ ArrayXd CQCGL1d::velocity(const ArrayXd &a0){ assert( Ndim == a0.rows() ); ArrayXXcd A = R2C(a0); ArrayXXcd v(N, 1); nl(A, v, 0); return C2R(L*A + v); } /** * @brief the generalized velociyt for relative equilibrium * * v(x) + \omega_\tau * t_\tau(x) + \omega_\rho * t_\rho(x) */ ArrayXd CQCGL1d::velocityReq(const ArrayXd &a0, const double wth, const double wphi){ return velocity(a0) + wth*transTangent(a0) + wphi*phaseTangent(a0); } /** * velocity in the slice * * @param[in] aH state in the slice */ VectorXd CQCGL1d::velSlice(const Ref<const VectorXd> &aH){ VectorXd v = velocity(aH); Vector2d c; c << v(Ndim-1), v(3); Matrix2d Linv; Linv << 0.5/aH(Ndim-2), 0.5/aH(2), -0.5/aH(Ndim-2), 0.5/aH(2); VectorXd tp = phaseTangent(aH); VectorXd tt = transTangent(aH); MatrixXd vs(Ndim, 2); vs << tp, tt; return v - vs * (Linv * c); } VectorXd CQCGL1d::velPhase(const Ref<const VectorXd> &aH){ VectorXd v = velocity(aH); VectorXd tp = phaseTangent(aH); double c = v(Ndim-1) / aH(Ndim-2); return v - c * tp; } /* -------------------------------------------------- */ /* -------- stability matrix ----------- */ /* -------------------------------------------------- */ MatrixXd CQCGL1d::stab(const ArrayXd &a0){ assert(a0.size() == Ndim && DimTan == Ndim); ArrayXXd v0(Ndim, Ndim+1); v0 << a0, MatrixXd::Identity(Ndim, Ndim); ArrayXXcd u0 = R2C(v0); ArrayXXcd v(N, Ndim+1); nl2(u0, v, 0); ArrayXXcd j0 = R2C(MatrixXd::Identity(Ndim, Ndim)); MatrixXcd Z = j0.colwise() * L + v.rightCols(Ndim); return C2R(Z); } /** * @brief stability for relative equilbrium */ MatrixXd CQCGL1d::stabReq(const ArrayXd &a0, double wth, double wphi){ MatrixXd z = stab(a0); return z + wth*transGenerator() + wphi*phaseGenerator(); } /** * @brief stability exponents of req */ VectorXcd CQCGL1d::eReq(const ArrayXd &a0, double wth, double wphi){ return eEig(stabReq(a0, wth, wphi), 1); } /** * @brief stability vectors of req */ MatrixXcd CQCGL1d::vReq(const ArrayXd &a0, double wth, double wphi){ return vEig(stabReq(a0, wth, wphi), 1); } /** * @brief stability exponents and vectors of req */ std::pair<VectorXcd, MatrixXcd> CQCGL1d::evReq(const ArrayXd &a0, double wth, double wphi){ return evEig(stabReq(a0, wth, wphi), 1); } /* -------------------------------------------------- */ /* ------ symmetry related ------ */ /* -------------------------------------------------- */ /** * @brief reflect the states * * Reflection : a_k -> a_{-k}. so a_0 keeps unchanged */ ArrayXXd CQCGL1d::reflect(const Ref<const ArrayXXd> &aa){ ArrayXXcd raa = R2C(aa); const int n = raa.rows(); // n is an odd number for(size_t i = 1; i < (n+1)/2; i++){ ArrayXcd tmp = raa.row(i); raa.row(i) = raa.row(n-i); raa.row(n-i) = tmp; } return C2R(raa); } /** * @ brief calculate (x^2 - y^2) / \sqrt{x^2 + y^2} */ inline ArrayXd CQCGL1d::rcos2th(const ArrayXd &x, const ArrayXd &y){ ArrayXd x2 = x.square(); ArrayXd y2 = y.square(); return (x2 - y2) / (x2 + y2).sqrt(); } /** * @ brief calculate x * y / \sqrt{x^2 + y^2} */ inline ArrayXd CQCGL1d::rsin2th(const ArrayXd &x, const ArrayXd &y){ return x * y / (x.square() + y.square()).sqrt(); } /** * @brief calculate the gradient of rcos2th() * * partial derivative over x : (x^3 + 3*x*y^2) / (x^2 + y^2)^{3/2} * partial derivative over y : - (y^3 + 3*y*x^2) / (x^2 + y^2)^{3/2} */ inline double CQCGL1d::rcos2thGrad(const double x, const double y){ // only return derivative over x. Derivative over y can be obtained // by exchange x and y and flip sign double denorm = sqrt(x*x + y*y); double denorm3 = denorm * denorm * denorm; return x * (x*x + 3*y*y) / denorm3; } /** * @brief calculate the gradient of rsin2th() * * partial derivative over x : y^3 / (x^2 + y^2)^{3/2} * partial derivative over y : x^3 / (x^2 + y^2)^{3/2} */ inline double CQCGL1d::rsin2thGrad(const double x, const double y){ // only return derivative over x. Derivative over y can be obtained // by exchange x and y double denorm = sqrt(x*x + y*y); double denorm3 = denorm * denorm * denorm; return y*y*y / denorm3; } /** * @brief the first step to reduce the discrete symmetry * * @param[in] aaHat states after reducing continous symmetries */ ArrayXXd CQCGL1d::reduceRef1(const Ref<const ArrayXXd> &aaHat){ const int m = aaHat.cols(); const int n = aaHat.rows(); assert(n == Ndim); ArrayXXd step1(n, m); step1.topRows<2>() = aaHat.topRows<2>(); for(size_t i = 1; i < Nplus; i++){ step1.row(2*i) = 0.5*(aaHat.row(2*i) - aaHat.row(n-2*i)); step1.row(n-2*i) = 0.5*(aaHat.row(2*i) + aaHat.row(n-2*i)); step1.row(2*i+1) = 0.5*(aaHat.row(2*i+1) - aaHat.row(n+1-2*i)); step1.row(n+1-2*i) = 0.5*(aaHat.row(2*i+1) + aaHat.row(n+1-2*i)); } return step1; } ArrayXXd CQCGL1d::reduceRef2(const Ref<const ArrayXXd> &step1){ ArrayXXd step2(step1); ArrayXd p1s = step1.row(2).square(); ArrayXd q1s = step1.row(3).square(); ArrayXd denorm = (p1s + q1s).sqrt(); step2.row(2) = (p1s - q1s) / denorm; step2.row(3) = step1.row(2) * step1.row(3) / denorm.transpose(); for(size_t i = 4; i < 2*Nplus; i++){ ArrayXd denorm = (step1.row(i-1).square() + step1.row(i).square()).sqrt(); step2.row(i) = step1.row(i-1) * step1.row(i) / denorm.transpose() ; } return step2; } /** * @brief get the indices which reflect sign in the 3rd step of reflection * reduction * * 1, 4, 6, ... */ std::vector<int> CQCGL1d::refIndex3(){ std::vector<int> index; // vector storing indices which flip sign index.push_back(1); for(size_t i = 2; i < Nplus; i++) index.push_back(2*i); for(size_t i = Nplus; i < Ne; i++) { if(i%2 != 0){ // the last mode a_{-1} has index Ne-1 even index.push_back(2*i); index.push_back(2*i+1); } } return index; } /** * @brief the 3rd step to reduce the discrete symmetry * */ ArrayXXd CQCGL1d::reduceRef3(const Ref<const ArrayXXd> &aa){ ArrayXXd aaTilde(aa); aaTilde.row(0) = rcos2th(aa.row(0), aa.row(1)); aaTilde.row(1) = rsin2th(aa.row(0), aa.row(1)); std::vector<int> index = refIndex3(); for(size_t i = 1; i < index.size(); i++){ aaTilde.row(index[i]) = rsin2th(aa.row(index[i-1]), aa.row(index[i])); } return aaTilde; } ArrayXXd CQCGL1d::reduceReflection(const Ref<const ArrayXXd> &aaHat){ return reduceRef3(reduceRef2(reduceRef1(aaHat))); } /** * @brief The gradient of the reflection reduction transformation for the * firt step. * * step 1: --------------------------------------- * | 1 | * | 1 | * | 1/2 -1/2 | * | 1/2 -1/2 | * | ... | * | 1/2 -1/2 | * | 1/2 -1/2 | * | 1/2 1/2 | * | 1/2 1/2 | * | ... | * | 1/2 1/2 | * | 1/2 1/2 | * --------------------------------------- */ MatrixXd CQCGL1d::refGrad1(){ MatrixXd Gamma(MatrixXd::Zero(Ndim, Ndim)); Gamma(0, 0) = 1; Gamma(1, 1) = 1; for (size_t i = 1; i < Nplus; i++){ Gamma(2*i, 2*i) = 0.5; Gamma(2*i+1, 2*i+1) = 0.5; Gamma(2*i, Ndim - 2*i) = -0.5; Gamma(2*i+1, Ndim - 2*i + 1) = -0.5; } for(size_t i = Nplus; i < Ne; i++){ Gamma(2*i, 2*i) = 0.5; Gamma(2*i, Ndim - 2*i) = 0.5; Gamma(2*i+1, 2*i+1) = 0.5; Gamma(2*i+1, Ndim - 2*i + 1) = 0.5; } return Gamma; } /** * @brief The gradient of the reflection reduction transformation for the * 2nd step. * * step 2: ------------------------------------ * | 1 | * | 1 | * | * * | * | * * | * | * * | * | * * | * | ... | * | * * | * | 1 | * | 1 | * | ... | * | 1 | * ------------------------------------ * */ MatrixXd CQCGL1d::refGrad2(const ArrayXd &x){ assert (x.size() == Ndim); MatrixXd Gamma(MatrixXd::Zero(Ndim, Ndim)); Gamma(0, 0) = 1; Gamma(1, 1) = 1; Gamma(2, 2) = rcos2thGrad(x(2), x(3)); Gamma(2, 3) = - rcos2thGrad(x(3), x(2)); for (size_t i = 3; i < 2*Nplus; i++){ Gamma(i, i) = rsin2thGrad(x(i), x(i-1)); Gamma(i, i-1) = rsin2thGrad(x(i-1), x(i)); } for (size_t i = 2*Nplus; i < Ndim; i++){ Gamma(i, i) = 1; } return Gamma; } /** * @brief The gradient of the reflection reduction transformation for the * 3rd step. */ MatrixXd CQCGL1d::refGrad3(const ArrayXd &x){ assert(x.size() == Ndim); MatrixXd Gamma(MatrixXd::Identity(Ndim, Ndim)); std::vector<int> index = refIndex3(); Gamma(0, 0) = rcos2thGrad(x(0), x(1)); Gamma(0, 1) = - rcos2thGrad(x(1), x(0)); Gamma(1, 1) = rsin2thGrad(x(1), x(0)); Gamma(1, 0) = rsin2thGrad(x(0), x(1)); for(size_t i = 1; i < index.size(); i++){ Gamma(index[i], index[i]) = rsin2thGrad(x(index[i]), x(index[i-1])); Gamma(index[i], index[i-1]) = rsin2thGrad(x(index[i-1]), x(index[i])); } return Gamma; } /** * @brief calculate the tranformation matrix for reflection reduction */ MatrixXd CQCGL1d::refGradMat(const ArrayXd &x){ ArrayXd step1 = reduceRef1(x); ArrayXd step2 = reduceRef2(step1); return refGrad3(step2) * refGrad2(step1) * refGrad1(); } /** * @brief transform covariant vectors after reducing reflection * * @param[in] veHat covariant vectors after reducing the continuous symmetries. * @param[in] xHat orbit point after reducing continuous symmetries. */ MatrixXd CQCGL1d::reflectVe(const MatrixXd &veHat, const Ref<const ArrayXd> &xHat){ MatrixXd Gamma = refGradMat(xHat); return Gamma * veHat; } /** @beief reduce reflection symmetry of all the Floquet vectors along a po * * Usaully, aaHat has one more column the the Floquet vectors, so you can * call this function like: * \code * reflectVeAll(veHat, aaHat.leftCols(aa.cols()-1)) * \endcode * * @param[in] veHat Floquet vectors along the orbit in the 1st mode slice. * Dimension: [N, M*Trunc] * @param[in] aaHat the orbit in the slice * @param[in] trunc the number of vectors at each orbit point. * trunc = 0 means full set of vectors * @return transformed to the reflection invariant space. * Dimension [N, M*Trunc] * * @note vectors are not normalized */ MatrixXd CQCGL1d::reflectVeAll(const MatrixXd &veHat, const MatrixXd &aaHat, const int trunc /* = 0*/){ int Trunc = trunc; if(trunc == 0) Trunc = veHat.rows(); assert(veHat.cols() % Trunc == 0); const int n = veHat.rows(); const int m = veHat.cols()/Trunc; const int n2 = aaHat.rows(); const int m2 = aaHat.cols(); assert(m == m2 && n == n2); MatrixXd veTilde(n, Trunc*m); for(size_t i = 0; i < m; i++){ veTilde.middleCols(i*Trunc, Trunc) = reflectVe(veHat.middleCols(i*Trunc, Trunc), aaHat.col(i)); } return veTilde; } /** @brief group rotation for spatial translation of set of arrays. * th : rotation angle * */ ArrayXXd CQCGL1d::transRotate(const Ref<const ArrayXXd> &aa, const double th){ ArrayXcd R = ( dcp(0,1) * th * K2 ).exp(); // e^{ik\theta} ArrayXXcd raa = r2c(aa); raa.colwise() *= R; return c2r(raa); } /** @brief group tangent in angle unit. * * x=(b0, c0, b1, c1, b2, c2 ...) ==> tx=(0, 0, -c1, b1, -2c2, 2b2, ...) */ ArrayXXd CQCGL1d::transTangent(const Ref<const ArrayXXd> &aa){ ArrayXcd R = dcp(0,1) * K2; ArrayXXcd raa = r2c(aa); raa.colwise() *= R; return c2r(raa); } /** @brief group generator. */ MatrixXd CQCGL1d::transGenerator(){ MatrixXd T = MatrixXd::Zero(Ndim, Ndim); for(size_t i = 0; i < Ne; i++){ T(2*i, 2*i+1) = -K2(i); T(2*i+1, 2*i) = K2(i); } return T; } /** @brief group transform for complex rotation * phi: rotation angle * */ ArrayXXd CQCGL1d::phaseRotate(const Ref<const ArrayXXd> &aa, const double phi){ return c2r( r2c(aa) * exp(dcp(0,1)*phi) ); // a0*e^{i\phi} } /** @brief group tangent. */ ArrayXXd CQCGL1d::phaseTangent(const Ref<const ArrayXXd> &aa){ return c2r( r2c(aa) * dcp(0,1) ); } /** @brief group generator */ MatrixXd CQCGL1d::phaseGenerator(){ MatrixXd T = MatrixXd::Zero(Ndim, Ndim); for(size_t i = 0; i < Ne; i++){ T(2*i, 2*i+1) = -1; T(2*i+1, 2*i) = 1; } return T; } /** * @brief apply both continous symmetries * * @note for performance purpose, this function is not written as the * superposition of 2 functions */ ArrayXXd CQCGL1d::Rotate(const Ref<const ArrayXXd> &aa, const double th, const double phi){ ArrayXcd R = ( dcp(0,1) * (th * K2 + phi) ).exp(); // e^{ik\theta + \phi} ArrayXXcd raa = r2c(aa); raa.colwise() *= R; return c2r(raa); } /** * @brief rotate the whole orbit with different phase angles at different point */ ArrayXXd CQCGL1d::rotateOrbit(const Ref<const ArrayXXd> &aa, const ArrayXd &th, const ArrayXd &phi){ const int m = aa.cols(); const int n = aa.rows(); const int m2 = th.size(); const int m3 = phi.size(); assert( m == m2 && m2 == m3); ArrayXXd aaHat(n, m); for( size_t i = 0; i < m; i++){ aaHat.col(i) = Rotate(aa.col(i), th(i), phi(i)); } return aaHat; } /** * @brief reduce the continous symmetries * * @param[in] aa states in the full state space * @return aaHat, theta, phi * * @note g(theta, phi)(x+y) is different from gx+gy. There is no physical * meaning to transform the sum/subtraction of two state points. */ std::tuple<ArrayXXd, ArrayXd, ArrayXd> CQCGL1d::orbit2slice(const Ref<const ArrayXXd> &aa, const int method){ int n = aa.rows(); int m = aa.cols(); assert(Ndim == n); ArrayXXd raa(n, m); ArrayXd th(m); ArrayXd phi(m); switch (method){ case 1: { // a0 -> positive real. a1 -> positive real for(int i = 0; i < m; i++){ double x = atan2(aa(1, i), aa(0, i)); double y = atan2(aa(3, i), aa(2, i)); phi(i) = x; th(i) = y - x; } break; } case 2: { // a0 -> positive imag. a1 -> positive real for (int i = 0; i < m; i++){ double x = atan2(aa(1, i), aa(0, i)); double y = atan2(aa(3, i), aa(2, i)); phi(i) = x - M_PI/2; th(i) = y - x + M_PI/2; } break; } case 3: { // a0 -> positive real. a1 -> positive imag for (int i = 0; i < m; i++){ double x = atan2(aa(1, i), aa(0, i)); double y = atan2(aa(3, i), aa(2, i)); phi(i) = x; th(i) = y - x - M_PI/2; } break; } case 4: { // a0 -> positive imag. a1 -> positive imag for (int i = 0; i < m; i++){ double x = atan2(aa(1, i), aa(0, i)); double y = atan2(aa(3, i), aa(2, i)); phi(i) = x - M_PI/2; th(i) = y - x; } break; } case 5: { // a1 -> positive real. a-1 -> positive real // phase is wrapped. for(size_t i = 0; i < m; i++){ double am1 = atan2(aa(n-1, i), aa(n-2, i)); double a1 = atan2(aa(3, i), aa(2, i)); phi(i) = 0.5 * (a1 + am1); th(i) = 0.5 * (a1 - am1); raa.col(i) = Rotate(aa.col(i), -th(i), -phi(i)); } break; } case 6: { // a1 -> positive real. a-1 -> positive real // phase is unwrapped. for(size_t i = 0; i < m; i++){ double am1 = atan2(aa(n-1, i), aa(n-2, i)); double a1 = atan2(aa(3, i), aa(2, i)); phi(i) = 0.5 * (a1 + am1); th(i) = 0.5 * (a1 - am1); } const double M_2PI = 2 * M_PI; for(size_t i = 1; i < m; i++){ double t0 = th(i) - th(i-1); double t1 = t0 - M_PI; double t2 = t0 + M_PI; double t0WrapAbs = fabs(remainder(t0, M_2PI)); if(fabs(t1) < t0WrapAbs) { // theta jump pi up th(i) = remainder(th(i) - M_PI, M_2PI); phi(i) = remainder(phi(i) - M_PI, M_2PI); continue; } if(fabs(t2) < t0WrapAbs) { // theta jump pi down th(i) = remainder(th(i) + M_PI, M_2PI); phi(i) = remainder(phi(i) + M_PI, M_2PI); } } break; } default: fprintf(stderr, "orbit to slice error\n"); } for(size_t i = 0; i < m; i++){ raa.col(i) = Rotate(aa.col(i), -th(i), -phi(i)); } return std::make_tuple(raa, th, phi); } /** @brief project covariant vectors to 1st mode slice * * @note vectors are not normalized */ MatrixXd CQCGL1d::ve2slice(const ArrayXXd &ve, const Ref<const ArrayXd> &x, int flag){ int n = x.size(); ArrayXXd xhat; ArrayXd th, phi; std::tie(xhat, th, phi) = orbit2slice(x, flag); VectorXd tx_rho = phaseTangent(xhat); VectorXd tx_tau = transTangent(xhat); VectorXd x0_rho(n), x0_tau(n); x0_rho.setZero(); x0_tau.setZero(); switch (flag){ case 1 : { x0_rho(0) = 1; x0_tau(2) = 1; break; } case 2 : { x0_rho(1) = 1; x0_tau(2) = 1; break; } case 3 : { x0_rho(0) = 1; x0_tau(3) = 1; break; } case 4 : { x0_rho(1) = 1; x0_tau(3) = 1; break; } case 5 : { x0_rho(n-2) = 1; x0_tau(3) = 1; break; } case 6 : { x0_rho(n-2) = 1; x0_tau(2) = 1; break; } default: fprintf(stderr, "orbit to slice error\n"); } VectorXd tp_rho = phaseTangent(x0_rho); VectorXd tp_tau = transTangent(x0_tau); Matrix2d L; L << tx_rho.dot(tp_rho), tx_tau.dot(tp_rho), tx_rho.dot(tp_tau), tx_tau.dot(tp_tau); MatrixXd tx(n, 2); tx.col(0) = tx_rho; tx.col(1) = tx_tau; MatrixXd t0(n, 2); t0.col(0) = tp_rho; t0.col(1) = tp_tau; MatrixXd vep = Rotate(ve, -th(0), -phi(0)); vep = vep - tx * L.inverse() * t0.transpose() * vep; return vep; } /** * @brief a wrap function => reduce all symmetries of an orbit */ std::tuple<ArrayXXd, ArrayXd, ArrayXd> CQCGL1d::reduceAllSymmetries(const Ref<const ArrayXXd> &aa, int flag){ std::tuple<ArrayXXd, ArrayXd, ArrayXd> tmp = orbit2slice(aa, flag); return std::make_tuple(reduceReflection(std::get<0>(tmp)), std::get<1>(tmp), std::get<2>(tmp)); } /** * @brief a wrap function => reduce all the symmetries of covariant vectors */ MatrixXd CQCGL1d::reduceVe(const ArrayXXd &ve, const Ref<const ArrayXd> &x, int flag){ std::tuple<ArrayXXd, ArrayXd, ArrayXd> tmp = orbit2slice(x, flag); return reflectVe(ve2slice(ve, x, flag), std::get<0>(tmp).col(0)); } //////////////////////////////////////////////////////////////////////////////////////////////////// // Abandoned // //////////////////////////////////////////////////////////////////////////////////////////////////// #if 0 /* -------------------------------------------------- */ /* -------- Lyapunov functional ----------- */ /* -------------------------------------------------- */ /** * @brief calculate the Lyapunov functional * * L = \int dx [ -\mu |A|^2 + D |A_x|^2 - 1/2 \beta |A|^4 - 1/3 \gamma |A|^6 ] * Here FFT[ A_{x} ]_k = iq_k a_k, so * \int dx |A_x|^2 = 1/N \sum (q_k^2 |a_k|^2) * The rest term can be obtained by invere FFT * => * L = \sum_{k=1}^N [ -\mu |A_k|^2 - 1/2 \beta |A_k|^4 - 1/3 \gamma |A_k|^6] * +\sum_{k=1}^N 1/N D [ q_k^2 |a_k|^2 ] * * Note, there are may be pitfalls, but there is indeed asymmetry here: * \sum_n |A_n|^2 = 1/N \sum_k |a_k|^2 */ ArrayXcd CQCGL1d::Lyap(const Ref<const ArrayXXd> &aa){ int M = aa.cols(); VectorXcd lya(M); for (size_t i = 0; i < M; i++){ ArrayXcd a = R2C(aa.col(i)); ArrayXcd a2 = a * a.conjugate(); F[0].v1 = a; F[0].ifft(); ArrayXcd A = F[0].v2; ArrayXcd A2 = A * A.conjugate(); lya(i) = -Mu * A2.sum() - 1.0/2 * dcp(Br, Bi) * (A2*A2).sum() - 1.0/3 * dcp(Gr, Gi) * (A2*A2*A2).sum() + 1.0/N * dcp(Dr, Di) * (QK.square() * a2).sum(); } return lya; } /** * @brief calculate the time derivative of Lyapunov functional * * The time derivative of Lyapunov functional is L_t = -2 \int dx |A_t|^2 * * @see Lyap(), velocity() */ ArrayXd CQCGL1d::LyapVel(const Ref<const ArrayXXd> &aa){ int M = aa.cols(); VectorXd lyavel(M); for (size_t i = 0; i < M; i++){ ArrayXd vel = velocity(aa.col(i)); // Fourier mode of velocity ArrayXcd cvel = R2C(vel); Fv.v1 = cvel; Fv.ifft(); // Fv.v2 is A_t lyavel(i) = -2 * (Fv.v2 * Fv.v2.conjugate()).sum().real(); } return lyavel; } #endif /**************************************************************/ /* plane wave related */ /**************************************************************/ /** * @brief Return plane waves. * * @param[in] k the wave index of the plane wave * @paran[in] isPositive whether the sign in amplitude is positive or not * @return [a0, a, w] Fourier state, amplitude, omega * * @note This function only works for the b, c, dr, di construction */ std::tuple<ArrayXd, double, double> CQCGL1d::planeWave(int k, bool isPositve){ double b = Di, c = Bi, dr = -Gr, di = -Gi; double qk, a2, w; qk = 2 * M_PI * k / d; if(isPositve) a2 = 1/(2*dr) * (1 + sqrt(1-4*dr*(qk*qk+1))); else a2 = 1/(2*dr) * (1 - sqrt(1-4*dr*(qk*qk+1))); w = b*qk*qk - c*a2 + di*a2*a2; ArrayXd a0(ArrayXd::Zero(Ndim)); if(k >= 0) a0(2*k) = sqrt(a2) * N; else a0(Ndim + 2*k) = sqrt(a2) * N; // please check return std::make_tuple(a0, sqrt(a2), w); } /** * @brief Stability exponents of plane wave * * @see planeWave(), eReq() */ VectorXcd CQCGL1d::planeWaveStabE(int k, bool isPositve){ auto tmp = planeWave(k, isPositve); return eReq(std::get<0>(tmp), 0, std::get<2>(tmp)); } std::pair<VectorXcd, MatrixXcd> CQCGL1d::planeWaveStabEV(int k, bool isPositve){ auto tmp = planeWave(k, isPositve); return evReq(std::get<0>(tmp), 0, std::get<2>(tmp)); } <file_sep>from py_CQCGL1d import * from cglHelp import * ################################################################################ # IN the parameter domain (Bi, Gi), we have a transition line which seperates # stable relative equilibria and unstalbe equilibria. Hopf bifurcation happens # close to this transition line. # # This file contains all case studies related to this Hopf bifurcation. ################################################################################ case = 10 if case == 10: """ have a look at how unstable relative equilibrium turns to a limit cycle. """ N, d = 1024, 50 h = 2e-3 Bi, Gi = 0.6, -3.6 index = 1 cgl = pyCQCGL1d(N, d, -0.1, 0.125, 0.5, 1, Bi, -0.1, Gi, -1) req = CQCGLreq(cgl) cp = CQCGLplot(cgl) a0, wth0, wphi0, err0, e, v = req.readBiGi('../../data/cgl/reqBiGiEV.h5', Bi, Gi, index, flag=2) print e[:20] nstp = 30000 a0 += 0.1*norm(a0)*v[0].real for i in range(5): aa = cgl.intg(a0, h, nstp, 10) a0 = aa[-1] cp.config(aa, [0, d, 0, nstp*h]) # save candidate limit cycle if False: rpo = CQCGLrpo(cgl) # be careful that the skip_rate is 10 # rpo.saveBiGi('p.h5', Bi, Gi, 1, aa[200], 3000*h, 3000, 0, 0, 0) if case == 30: """ have a look at the limit cycle """ N, d = 1024, 50 Bi, Gi = 0.8, -3.6 index = 1 cgl = pyCQCGL1d(N, d, -0.1, 0.125, 0.5, 1, Bi, -0.1, Gi, -1) rpo = CQCGLrpo(cgl) cp = CQCGLplot(cgl) x, T, nstp, th, phi, err = rpo.read('../../data/cgl/rpoHopfBiGi.h5', rpo.toStr(Bi, Gi, 1)) a0 = x[:-3] h = T / nstp aa = cgl.intg(a0, h, nstp*4, 10) cp.config(aa, [0, d, 0, nstp*h]) # check it is not a req vel = cgl.velocity(a0) velRed = cgl.ve2slice(vel, a0, 1) print norm(velRed) if case == 40: """ move rpo """ inFile = '../../data/cgl/rpoBiGi2.h5' outFile = '../../data/cgl/rpoHopfBiGi.h5' rpo = CQCGLrpo() gName = rpo.toStr(1.4, -3.9, 1) rpo.move(inFile, gName, outFile, gName, flag=0) <file_sep>import numpy as np import matplotlib.pyplot as plt import scipy.io as sio from mpl_toolkits.axes_grid1 import make_axes_locatable aa = sio.loadmat('../mat/travelingWaveEvolution.mat') h = 0.01 taa = aa['aa']; taa = taa[::2,:]+1j*taa[1::2,:];# change taa to plot differnt types. #################### fig 1 ########## fig = plt.figure(figsize=(4,5)); ax = fig.add_subplot(111) ax.set_xlabel('x') ax.set_ylabel('t') im = ax.imshow(abs(np.fft.ifft(taa, axis=0)).T, cmap=plt.get_cmap('get'), extent=(0,50,0, h*taa.shape[1]), aspect='auto', origin ='lower') ax.grid('on') dr = make_axes_locatable(ax) cax = dr.append_axes('right', size = '5%', pad =0.05) bar = plt.colorbar(im, cax=cax, ticks=[0, 3]) ######################################## fig.tight_layout(pad=0) plt.show() <file_sep>import numpy as np from numpy.fft import rfft, irfft from pdb import set_trace def ksintIm(a0, h, nstp, d = 22, osp = 1, jsp = 1, isJ = False): N = len(a0); a0p = np.zeros(N*2) a0p[1::2] = a0 if isJ == True: tt, aa, daa = ksfjaco(a0p, h, nstp, osp, jsp, d, isJ) aa = aa[1::2, :] daa = daa.T.reshape(-1, 30)[1::2, 1::2] return aa.T, daa else : tt, aa = ksfjaco(a0p, h, nstp, osp, jsp, d, isJ) aa = aa[1::2, :] return aa.T def ksfjaco(a0, h, nstp, osp = 1, jsp = 1, d =22, isJ = True): """ KS integrator. Parameters ---------- a0: one dimensional array or a list initial condition. It shoud be a one dimensional array or a list. h : double time step. nstp: int number of integration steps. osp: int, optional spacing for storing state vectors. If not given, osp = 1. jsp: int, optional spacing for Jacobian matrix. If not given, jsp = 1. d: int, optional length of KS system. If not given, d = 22. isJ: bool, optional Whethe to calculate the Jacobian matrix. If not given, isJ = True. Returns ------- tt: one dimensional array (n,) time samples aa: narray (n,m) each column represent a state vector. daa: narray (only if isJ = True) (n**2, m) each column represent a row-stacked Jacobian. Examples -------- >>> from numpy inport ones >>> tt, aa, daa= ksjaco(ones(30)*0.1, 0.25, 1000) >>> tt, aa = ksjaco(ones(30)*0.1, 0.25, 1000, isJ = False) >>> tt.shape (1000,) >>> aa.shape (30, 1000) >>> daa.shape (900, 1000) """ N = len(a0)+2; Nh = N/2; a0=np.array(a0); if isJ: v = np.zeros((Nh+1, N-1), np.complex128); v[1:Nh, 0] = a0[::2] + 1j*a0[1::2]; iniJ(v[:,1:]); else: v = np.zeros([Nh+1,1], np.complex128); v[1:Nh, 0] = a0[::2] + 1j*a0[1::2]; k, E, E2, Q, f1, f2, f3 = calCoe(h, Nh, d); g = 0.5j * np.r_[k[:-1], 0] * N; g = g[:, np.newaxis]; E = E[:,np.newaxis]; E2 = E2[:,np.newaxis]; Q = Q[:,np.newaxis]; f1 = f1[:,np.newaxis]; f2 = f2[:,np.newaxis]; f3 = f3[:,np.newaxis]; if isJ: g = np.hstack((g, np.tile(2.*g, N-2))); daa = np.empty([(N-2)**2, nstp/jsp]); aa = np.empty([N-2, nstp/osp+1]); tt = np.empty([1, nstp/osp+1]); aa[:,0]=a0; tt[0,0]=0; for n in range(1, nstp+1): t = n*h; rfv = irfft(v, axis=0); Nv = g*rfft(rfv[:,0:1] * rfv, axis = 0); a = E2*v + Q*Nv; rfv = irfft(a, axis=0); Na = g*rfft(rfv[:,0:1] * rfv, axis = 0); b = E2*v + Q*Na; rfv =irfft(b, axis = 0); Nb = g*rfft(rfv[:,0:1] * rfv, axis = 0); c = E2*a + Q*(2*Nb - Nv); rfv =irfft(c, axis = 0); Nc = g*rfft(rfv[:,0:1] * rfv, axis = 0); v = E*v + Nv*f1 + 2*(Na+Nb)*f2 + Nc*f3; if n % osp == 0: y1 = np.c_[v[1:Nh,0].real, v[1:Nh,0].imag]; aa[:, n/osp] = y1.reshape(-1); tt[0,n/osp] =t; #set_trace(); if isJ and n % jsp == 0: da = np.zeros((N-2, N-2)); da[::2,:]= v[1:Nh, 1:].real da[1::2,:] = v[1:Nh, 1:].imag; daa[:,n/jsp-1] = da.reshape(-1); iniJ(v[:,1:]); if isJ: return tt, aa, daa else: return tt, aa def iniJ(J): """ initialize the Jacobian matrix to be [ 0, 0, 0, ... 1, 1j,0, ... 0, 0, 1, 1j, .. ... 0, 0, .... 1, 1j 0, 0, 0, ... ] Parameters ---------- J : array_like Jacobian matrix with size (Nh+1) x (N-2). """ J[:,:]=0; for i in range(1, J.shape[0]-1): J[i, 2*i-2] = 1; J[i, 2*i-1] = 1j; return None def calCoe(h, Nh, d, M = 16): k = 2.*np.pi/d * np.r_[:Nh+1]; # wave number: 0, 1, 2,.. Nh-1, Nh L = k**2 - k**4; E = np.exp(h * L); E2 = np.exp(h * L/ 2.); r = np.exp(1j*np.pi*(np.r_[1:M+1]-0.5)/M); LR = h*np.tile(L,(M,1)).T + np.tile(r,(Nh+1,1)); Q = h*((np.exp(LR/2)-1)/LR).mean(1).real; f1 = h*((-4 - LR + np.exp(LR)*(4-3*LR+LR**2))/LR**3).mean(1).real; f2 = h*((2 + LR + np.exp(LR)*(-2+LR))/LR**3).mean(1).real; f3 = h*((-4 - 3*LR - LR**2 + np.exp(LR)*(4 - LR))/LR**3).mean(1).real; return k, E, E2, Q, f1, f2, f3; def transJ(J): n, m = J.shape; n = n**0.5; #set_trace(); Jp = np.empty([n, m*n]); for i in range(m): Jp[:, i*n:(i+1)*n] = J[:,i].reshape([n,n]); return Jp <file_sep>/* time h5c++ test_CQCGL2dEIDc.cc -std=c++11 -lCQCGL2d -lmyfft -lmyH5 -ldenseRoutines -literMethod -lfftw3 -I $RESH/include/ -L $RESH/lib/ -I $XDAPPS/eigen/include/eigen3 -DEIGEN_FFTW_DEFAULT -O3 -o cgl2d.out && time ./cgl2d.out */ #include <iostream> #include <ctime> #include "CQCGL2dEIDc.hpp" #include "myH5.hpp" #include "CQCGL2d.hpp" #include "denseRoutines.hpp" #define cee(x) cout << (x) << endl << endl; #define N70 using namespace MyH5; using namespace std; using namespace Eigen; using namespace denseRoutines; int main(){ std::vector<std::string> scheme = {"IFRK43", "IFRK54", "Cox_Matthews", "Krogstad", "Hochbruck_Ostermann", "Luan_Ostermann", "SSPP43"}; #ifdef N15 //==================================================================================================== // test a single method to see whether there is a bug // Also, save the state for orbits const int N = 1024; const double d = 50; double Bi = 0.8, Gi = -0.6; CQCGL2dEIDc cgl(N, d, -0.1, 0.125, 0.5, 1, Bi, -0.1, Gi); CQCGL2d cgl2(N, d, -0.1, 0.125, 0.5, 1, Bi, -0.1, Gi, 4); cgl.IntPrint = 1; MatrixXcd A0 = Gaussian2d(N, N, N/2, N/2, N/30, N/30, 2.5) + Gaussian2d(N, N, 2*N/5, 2*N/5, N/30, N/30, 0.2); ArrayXXcd a0 = cgl2.Config2Fourier(A0); double T = 20; cgl.setScheme("Cox_Matthews"); ArrayXXcd aa = cgl.intgC(a0, 0.002, T, 50, 0, "aa.h5"); if(true){ cgl.eidc.rtol = 1e-8; cgl.setScheme("Cox_Matthews"); ArrayXXcd aaAdapt = cgl.intg(a0, T/(1<<10), T, 50, 0, "aaCox.h5"); cgl.setScheme("SSPP43"); aaAdapt = cgl.intg(a0, T/(1<<10), T, 50, 0, "aaSS.h5"); } #endif #ifdef N30 //==================================================================================================== // fix the time step. try to look at the estimated local error of all shemes const int N = 1024; const double d = 50; double Bi = 0.8, Gi = -0.6; CQCGL2dEIDc cgl(N, d, -0.1, 0.125, 0.5, 1, Bi, -0.1, Gi); CQCGL2d cgl2(N, d, -0.1, 0.125, 0.5, 1, Bi, -0.1, Gi, 4); cgl.IntPrint = 10; MatrixXcd A0 = Gaussian2d(N, N, N/2, N/2, N/30, N/30, 2.5) + Gaussian2d(N, N, 2*N/5, 2*N/5, N/30, N/30, 0.2); ArrayXXcd a0 = cgl2.Config2Fourier(A0); double T = 20; int n0 = 14, n1 = 5; double h0 = T / (1<<n0); // T / 2^13 double w[] = {0, -7.3981920609491505}; MatrixXd ltes(1<<(n0 - n1), 2*scheme.size()); for(int k = 0; k < 2; k++){ cgl.changeOmega(w[k]); for(int i = 0; i < scheme.size(); i++) { fprintf(stderr, "k = %d, scheme is %s \n", k, scheme[i].c_str()); cgl.setScheme(scheme[i]); ArrayXXcd aa = cgl.intgC(a0, h0, T, 1<<n1, 2, "aa.h5"); ltes.col(k*scheme.size() + i) = cgl.lte; } } savetxt("cqcgl2d_N30_lte.dat", ltes); #endif #ifdef N50 //==================================================================================================== // static frame integration // set the rtol = 1e-9 and output time steps const int N = 1024; const double d = 50; double Bi = 0.8, Gi = -0.6; CQCGL2dEIDc cgl(N, d, -0.1, 0.125, 0.5, 1, Bi, -0.1, Gi); CQCGL2d cgl2(N, d, -0.1, 0.125, 0.5, 1, Bi, -0.1, Gi, 4); cgl.IntPrint = 10; cgl.eidc.rtol = 1e-9; MatrixXcd A0 = Gaussian2d(N, N, N/2, N/2, N/30, N/30, 2.5) + Gaussian2d(N, N, 2*N/5, 2*N/5, N/30, N/30, 0.2); ArrayXXcd a0 = cgl2.Config2Fourier(A0); double T = 20; double h0 = T / (1<<12); // T / 2^12 for(int i = 0; i < scheme.size(); i++) { fprintf(stderr, "scheme is %s \n", scheme[i].c_str()); cgl.setScheme(scheme[i]); ArrayXXcd aa = cgl.intg(a0, h0, T, 1<<5, 2, "aa.h5"); savetxt("cqcgl2d_N50_hs_"+to_string(i)+".dat", cgl.hs); } #endif #ifdef N60 //==================================================================================================== // Comoving frame integration // set the rtol = 1e-9 and output time steps const int N = 1024; const double d = 50; double Bi = 0.8, Gi = -0.6; CQCGL2dEIDc cgl(N, d, -0.1, 0.125, 0.5, 1, Bi, -0.1, Gi); CQCGL2d cgl2(N, d, -0.1, 0.125, 0.5, 1, Bi, -0.1, Gi, 4); cgl.IntPrint = 10; cgl.eidc.rtol = 1e-9; cgl.changeOmega(-7.3981920609491505); MatrixXcd A0 = Gaussian2d(N, N, N/2, N/2, N/30, N/30, 2.5) + Gaussian2d(N, N, 2*N/5, 2*N/5, N/30, N/30, 0.2); ArrayXXcd a0 = cgl2.Config2Fourier(A0); double T = 20; double h0 = T / (1<<12); // T / 2^12 for(int i = 0; i < scheme.size(); i++) { fprintf(stderr, "scheme is %s \n", scheme[i].c_str()); cgl.setScheme(scheme[i]); ArrayXXcd aa = cgl.intg(a0, h0, T, 1<<5, 2, "aa.h5"); savetxt("cqcgl2d_N60_comoving_hs_"+to_string(i)+".dat", cgl.hs); } #endif #ifdef N70 //==================================================================================================== // static & comoving frame integration with time step adaption turned on. // choose different rtol to obtain // rtol vs global relative error // rtol vs integration steps, N(x) evaluation times // const int N = 1024; const double d = 50; double Bi = 0.8, Gi = -0.6; CQCGL2dEIDc cgl(N, d, -0.1, 0.125, 0.5, 1, Bi, -0.1, Gi); CQCGL2d cgl2(N, d, -0.1, 0.125, 0.5, 1, Bi, -0.1, Gi, 4); cgl.IntPrint = 10; MatrixXcd A0 = Gaussian2d(N, N, N/2, N/2, N/30, N/30, 2.5) + Gaussian2d(N, N, 2*N/5, 2*N/5, N/30, N/30, 0.2); ArrayXXcd a0 = cgl2.Config2Fourier(A0); double T = 20; double w[] = {0, -7.3981920609491505}; int n = 8; time_t t; for(int p = 0; p < 2; p++){ cgl.changeOmega(w[p]); MatrixXd erros(n, 5*scheme.size()+1); for(int i = 0; i < scheme.size(); i++) { cgl.setScheme(scheme[i]); for(int j = 0, k=1; j < n; j++, k*=5){ fprintf(stderr, "w = %f, scheme is %s, j = %d \n\n", w[p], scheme[i].c_str(), j); double rtol = k*1e-11; cgl.eidc.rtol = rtol; if(i == 0) { erros(j, 0) = rtol; } ArrayXXcd xf = cgl.intg(a0, T/(1<<12), T, 1000000, 2, "aa.h5"); erros.row(j).segment(5*i+1, 5) << cgl.eidc.NCalCoe, cgl.eidc.NCallF, cgl.eidc.NReject, cgl.eidc.TotalTime, cgl.eidc.CoefficientTime; } } savetxt("cqcgl2d_N70_stat" + to_string(p) + ".dat", erros); } #endif return 0; } <file_sep>/** * Note : * * 1) the "many" scheme assumes performing FFT in each column of input matrix. Eigen is * column-wise in memory layout, while FFTW is assuming row-wise memory layout, so * caution is exerted there. * * 2) */ #ifndef FFTW_WRAP_H #define FFTW_WRAP_H #include <fftw3.h> #include <complex> #include <Eigen/Dense> namespace FFTW_wrap { using namespace std; using namespace Eigen; ////////////////////////////////////////////////////////////////////////////////////////// // 1d FFT // ////////////////////////////////////////////////////////////////////////////////////////// class fft { public: const int N, M; MatrixXcd time, freq; fftw_plan p, ip; fft(const int N, const int M, bool doInit = true) : N(N), M(M) { if (doInit) init(); } ~fft(){ if(p) fftw_destroy_plan(p); if(ip) fftw_destroy_plan(ip); } inline void init(){ assert (M > 0); time.resize(N, M); freq.resize(N, M); if (1 == M){ p = fftw_plan_dft_1d(N, (fftw_complex*)time.data(), (fftw_complex*)freq.data(), FFTW_FORWARD, FFTW_MEASURE|FFTW_PRESERVE_INPUT); ip = fftw_plan_dft_1d(N, (fftw_complex*)freq.data(), (fftw_complex*)time.data(), FFTW_BACKWARD, FFTW_MEASURE|FFTW_PRESERVE_INPUT); } else{ int n[] = { N }; p = fftw_plan_many_dft(1, n, M, (fftw_complex*)time.data(), n, 1, N, (fftw_complex*)freq.data(), n, 1, N, FFTW_FORWARD, FFTW_MEASURE|FFTW_PRESERVE_INPUT); ip = fftw_plan_many_dft(1, n, M, (fftw_complex*)freq.data(), n, 1, N, (fftw_complex*)time.data(), n, 1, N, FFTW_BACKWARD, FFTW_MEASURE|FFTW_PRESERVE_INPUT); } } inline void fwd(){ fftw_execute(p); } inline void inv(){ fftw_execute(ip); time *= 1.0/N; } }; ////////////////////////////////////////////////////////////////////////////////////////// // 1d real FFT // ////////////////////////////////////////////////////////////////////////////////////////// class rfft { public: const int N, M; MatrixXd time; MatrixXcd freq; fftw_plan p, ip; fft(const int N, const int M, bool doInit = true) : N(N), M(M) { if (doInit) init(); } ~fft(){ if(p) fftw_destroy_plan(p); if(ip) fftw_destroy_plan(ip); } inline void init(){ assert (M > 0); time.resize(N, M); freq.resize(N/2+1, M); if (1 == M){ p = fftw_plan_dft_r2c_1d(N, time.data(), (fftw_complex*)freq.data(), FFTW_MEASURE|FFTW_PRESERVE_INPUT); ip = fftw_plan_dft_c2r_1d(N, (fftw_complex*)freq.data(), time.data(), FFTW_MEASURE|FFTW_PRESERVE_INPUT); } else{ int n[] = { N }; p = fftw_plan_many_dft_r2c(1, n, M, time.data(), n, 1, N, (fftw_complex*)freq.data(), n, 1, N/2+1, FFTW_MEASURE|FFTW_PRESERVE_INPUT); ip = fftw_plan_many_dft_r2c(1, n, M, (fftw_complex*)freq.data(), n, 1, N/2+1, time.data(), n, 1, N, FFTW_MEASURE|FFTW_PRESERVE_INPUT); } } inline void fwd(){ fftw_execute(p); } inline void inv(){ fftw_execute(ip); time *= 1.0/N; } } } #endif /* FFTW_WRAP_H */ <file_sep>/** To compile this class, you need to have g++ >= 4.6, eigen >= 3.1 * g++ -o libksintm1.so ksintM1.cc ksint.cc * -shared -fpic -lm -lfftw3 -std=c++0x * -march=core2 -O3 -msse2 -I/path/to/eigen3 -I../../include * */ #ifndef KSINTM1_H #define KSINTM1_H #include "ksint.hpp" class KSM1 : public KS { public: /* member functions */ std::pair<ArrayXXd, ArrayXd> intg(const ArrayXd &a0, size_t nstp, size_t np); std::pair<ArrayXXd, ArrayXd> intg2(const ArrayXd &a0, double T, size_t np); /* constructors */ KSM1(int N = 32, double h = 0.25, double d = 22); explicit KSM1(const KSM1 &x); KSM1 & operator=(const KSM1 &x); protected: virtual void NL(KSfft &f); // virtual void jNL(KSfft &f); }; #endif /* KSINTM1_H */ <file_sep>#ifndef KSSOLVEM1_H #define KSSOLVEM1_H #include "kssolve.hpp" #include <vector> class KsM1 : public Ks { public: /** structure definition */ typedef std::vector<double> dvec; typedef std::vector<dcomp> dcvec; /** @brief KS solver in the 1st mode slice without Jacobian. * * If np != 1, the time sequence is not accurate. * */ void kssolve(double *a0, int nstp, int np, double *aa, double *tt); void kssolve(double *a0, int nstp, int np, int nqr, double *aa, double *daa, double *tt); /** @brief velocity in the 1st mode slice * * @param[in] a0 vector of size N-3 * @return velocity vector of size N-3 */ dvec velo(dvec &a0); /** @brief integrate point a0 to poincare section defined by x0 * * with its velocity filed. a0 should be below the section which means the * direction of the poincare section is parallel to the velocity field. * * @param[in] x0 template point of the Poincare section * U(x) = v0 * (x - x0) * @param[in] a0 state point that needed to be integrated onto * Poincare section. * @return N-1 vector with last two elements be the time and error */ dvec ks2poinc(dvec &x0, dvec &a0); // constructors, destructor, copy assignment. KsM1(int N = 32, double d = 22, double h = 0.25); explicit KsM1(const KsM1 &x); KsM1 & operator=(const KsM1 &x); /* ------------------- ---------------------------------------- */ protected: /* function onestep() keeps unchanged. */ void initKs(double *a0, dcomp *v, double *aa, FFT &rp, FFT &p) override; void initKs(double *a0, dcomp *v, double *aa, FFT *rp, FFT *p) override; void calNL(dcomp*u, dcomp *Nv, const FFT &p, const FFT &rp) override; void calNL(dcomp *u, dcomp *Nv, const FFT *p, const FFT *rp ) override; void initJ(dcomp *v) override; dvec cv2rv(const dcvec &a0); /* ------------------------------------------------------------ */ private: class Int2p{ public: KsM1 &ks; dvec v0; Int2p(KsM1 &k): ks(k){} void operator() (const dvec &x, dvec &dxdt, const double /* t */); }; Int2p int2p; }; #endif /* KSSOLVEM1_H */ <file_sep>from py_ks import pyKSETD, pyKS from personalFunctions import * case = 1 if case == 1: N = 64 L = 22 ksetd = pyKSETD(N, L) poType = 'rpo' poId = 1 a0, T, nstp, r, s = KSreadPO('../../data/ks22h001t120x64.h5', poType, poId) ksetd.setRtol(1e-8) tt, aa = ksetd.etd(a0, T, 0.01, 1, 2, False) hs = ksetd.hs()[1:] duu = ksetd.duu()[1:] plot1dfig(duu, yscale='log') plot1dfig(hs) print ksetd.etdParam() KSplotColorMapOrbit(aa, [0, L, 0, T]) <file_sep>import numpy as np import scipy.io as sio import matplotlib.pyplot as plt from mpl_toolkits.axes_grid1 import make_axes_locatable aa = sio.loadmat('../mat/cqcglStateTestN.mat') a1 = aa['uu128']; a2 = aa['uu256']; a3 = aa['uu512']; h = 0.01; fig = plt.figure(figsize=(8,4)); ax = fig.add_subplot(131) ax2 = fig.add_subplot(132) ax3 = fig.add_subplot(133) ########## fig 1 ########## ax.set_xlabel('x') ax.set_ylabel('t') ax.imshow(abs(np.fft.ifft(a1, axis = 0)).T, cmap=plt.get_cmap('jet'), extent=(0,128,0, h*a1.shape[1]), aspect='auto', origin ='lower'); ax.grid('on') ########## fig 2 ########## ax2.set_xlabel('x') ax2.set_ylabel('t') ax2.imshow(abs(np.fft.ifft(a2, axis = 0)).T, cmap=plt.get_cmap('jet'), extent=(0,256,0, h*a1.shape[1]), aspect='auto', origin ='lower'); ax2.grid('on') ########## fig 3 ########## ax3.set_xlabel('x') ax3.set_ylabel('t') im = ax3.imshow(abs(np.fft.ifft(a3, axis = 0)).T, cmap=plt.get_cmap('jet'), extent=(0,512,0, h*a1.shape[1]), aspect='auto', origin ='lower'); ax3.grid('on') dr3 = make_axes_locatable(ax3) cax3 = dr3.append_axes('right', size = '10%', pad =0.05) bar = plt.colorbar(im, cax=cax3, ticks=[0, 2.5]) ############################## fig.tight_layout(pad=0) plt.show() <file_sep>#ifndef CQCGL1DSUB_H #define CQCGL1DSUB_H #include <complex> #include <utility> #include <algorithm> #include <vector> #include <unsupported/Eigen/FFT> #include "denseRoutines.hpp" #include "EIDc.hpp" ////////////////////////////////////////////////////////////////////// // class CQCGL1dSub // ////////////////////////////////////////////////////////////////////// class CQCGL1dSub { public: typedef std::complex<double> dcp; const int N; /* dimension of FFT */ const double d; /* system domain size */ const int Ne; // effective number of modes const int Ndim; // dimension of state space const int DimTan; // the dimension of tangent space bool IsQintic = true; // False => cubic equation double Mu, Dr, Di, Br, Bi, Gr, Gi; double Omega = 0; /* used for comoving frame */ ArrayXd K, QK; ArrayXcd L; FFT<double> fft; VectorXd hs; /* time step sequnce */ VectorXd lte; /* local relative error estimation */ VectorXd Ts; /* time sequnence for adaptive method */ int cellSize = 500; /* size of cell when resize output container */ struct NL { CQCGL1dSub *cgl; int N, Ne; dcp B, G; ArrayXXcd modes, field; // Fourier modes and physical field NL(); NL(CQCGL1dSub *cgl, int cols); ~NL(); void operator()(ArrayXXcd &x, ArrayXXcd &dxdt, double t); }; NL nl, nl2; ArrayXXcd Yv[10], Nv[10], Yv2[10], Nv2[10]; EIDc eidc, eidc2; //////////////////////////////////////////////////////////// // constructor, destructor, copy assignment. // //////////////////////////////////////////////////////////// // A_t = Mu A + (Dr + Di*i) A_{xx} + (Br + Bi*i) |A|^2 A + (Gr + Gi*i) |A|^4 A CQCGL1dSub(int N, double d, double Mu, double Dr, double Di, double Br, double Bi, double Gr, double Gi, int dimTan); // A_t = -A + (1 + b*i) A_{xx} + (1 + c*i) |A|^2 A - (dr + di*i) |A|^4 A CQCGL1dSub(int N, double d, double b, double c, double dr, double di, int dimTan); // iA_z + D A_{tt} + |A|^2 A + \nu |A|^4 A = i \delta A + i \beta A_{tt} + i |A|^2 A + i \mu |A|^4 A CQCGL1dSub(int N, double d, double delta, double beta, double D, double epsilon, double mu, double nu, int dimTan); ~CQCGL1dSub(); CQCGL1dSub & operator=(const CQCGL1dSub &x); //////////////////////////////////////////////////////////// // member functions. // //////////////////////////////////////////////////////////// //============================================================ void setScheme(std::string x); void changeOmega(double w); ArrayXXd intgC(const ArrayXd &a0, const double h, const double tend, const int skip_rate); std::pair<ArrayXXd, ArrayXXd> intgjC(const ArrayXd &a0, const double h, const double tend, const int skip_rate); ArrayXXd intgvC(const ArrayXd &a0, const ArrayXXd &v, const double h, const double tend); ArrayXXd intg(const ArrayXd &a0, const double h, const double tend, const int skip_rate); std::pair<ArrayXXd, ArrayXXd> intgj(const ArrayXd &a0, const double h, const double tend, const int skip_rate); ArrayXXd intgv(const ArrayXXd &a0, const ArrayXXd &v, const double h, const double tend); ArrayXXd C2R(const ArrayXXcd &v); ArrayXXcd R2C(const ArrayXXd &v); //============================================================ ArrayXXcd Fourier2Config(const Ref<const ArrayXXd> &aa); ArrayXXd Config2Fourier(const Ref<const ArrayXXcd> &AA); ArrayXXd calPhase(const Ref<const ArrayXXcd> &AA); VectorXd calQ(const Ref<const ArrayXXd> &aa); VectorXd calMoment(const Ref<const ArrayXXd> &aa, const int p = 1); ArrayXd velocity(const ArrayXd &a0); ArrayXd velocityReq(const ArrayXd &a0, const double phi); MatrixXd stab(const ArrayXd &a0); MatrixXd stabReq(const ArrayXd &a0, double phi); VectorXcd eReq(const ArrayXd &a0, double wphi); MatrixXcd vReq(const ArrayXd &a0, double wphi); std::pair<VectorXcd, MatrixXcd> evReq(const ArrayXd &a0, double wphi); ArrayXXd phaseRotate(const Ref<const ArrayXXd> &aa, const double phi); ArrayXXd phaseTangent(const Ref<const ArrayXXd> &aa); MatrixXd phaseGenerator(); }; #endif /* CQCGL1DSUB_H */ <file_sep>from py_CQCGL1dSub import * from cglHelp import * import time case = 10 if case == 10: """ Test the integration result by EID method """ N, d = 1024 , 50 h = 2e-3 sysFlag = 1 Bi, Gi = 2, -2 cgl = pyCQCGL1dSub(N, d, -0.1, 0.125, 0.5, 1, Bi, -0.1, Gi, -1) req, cp = CQCGLreq(cgl), CQCGLplot(cgl) a0, wth0, wphi0, err0 = req.read('../../data/cgl/reqBiGiEV.h5', req.toStr(Bi, Gi, 1)) a0 = a0[:cgl.Ndim] aE = a0 + 0.01 * norm(a0) * rand(cgl.Ndim) T = 200 t = time.time() aa = cgl.intgC(aE, h, T, 50) print time.time() - t cp.config(aa, [0, d, 0, T]) t = time.time() aa2 = cgl.intg(aE, h, T, 50) print time.time() - t cp.config(aa2, [0, d, 0, T]) # t = time.time() # aa3 = EI.intg(aE, h, T, 10) # print time.time() -t # cp.config(aa3, [0, d, 0, T]) if case == 20: """ same test as case = 10, but with rpo intial condition """ N, d = 1024 , 50 h = 2e-3 sysFlag = 1 Bi, Gi = 4.8, -4.5 cgl = pyCQCGL1d(N, d, -0.1, 0.125, 0.5, 1, Bi, -0.1, Gi, -1) EI = pyCQCGL1dEIDc(N, d, -0.1, 0.125, 0.5, 1, Bi, -0.1, Gi) rpo, cp = CQCGLrpo(cgl), CQCGLplot(cgl) x, T, nstp, th, phi, err, e, v = rpo.read('../../data/cgl/rpoBiGiEV.h5', rpo.toStr(Bi, Gi, 1), flag=2) a0 = x[:cgl.Ndim] aE = a0 + 0.001 * norm(a0) * v[0].real t = time.time() aa = cgl.intgC(aE, T/nstp/2, 20*T, 10) print time.time() - t cp.config(aa, [0, d, 0, 20*T]) t = time.time() aa2 = EI.intgC(aE, T/nstp/2, 20*T, 10) print time.time() - t cp.config(aa2, [0, d, 0, 20*T]) if case == 30: """ test the function of calculating stability matrix """ N, d = 1024 , 50 Bi, Gi = 0.8, -0.6 index = 1 cgl = pyCQCGL1d(N, d, -0.1, 0.125, 0.5, 1, Bi, -0.1, Gi, 0) req = CQCGLreq(cgl) a0, wth0, wphi0, err0, e0, v0 = req.read('../../data/cgl/reqBiGiEV.h5', req.toStr(Bi, Gi, index), flag=2) e, v = req.eigReq(a0, wth0, wphi0) print e[:10] <file_sep>#ifndef CQCGL2DDISLIN_H #define CQCGL2DDISLIN_H #include "CQCGL2d.hpp" #include "discpp.h" class CQCGL2dDislin : public CQCGL2d { public: ////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////// CQCGL2dDislin(int N, int M, double dx, double dy, double b, double c, double dr, double di, int threadNum); CQCGL2dDislin(int N, double dx, double b, double c, double dr, double di, int threadNum); ~CQCGL2dDislin(); CQCGL2dDislin & operator=(const CQCGL2dDislin &x); ////////////////////////////////////////////////////////////////////// void initPlot(Dislin &g, const double Lx, const double Ly, const double Lz); void plot(Dislin &g, const double t, const double err); void endPlot(Dislin &g); void constAnim(const ArrayXXcd &a0, const double h, const int skip_rate); void adaptAnim(const ArrayXXcd &a0, const double h0, const int skip_rate); }; #endif /* CQCGL2DDISLIN_H */ <file_sep>#include "myfft.hpp" #include <iostream> using namespace Eigen; using namespace std; namespace MyFFT { long NumOfInstance = 0; ////////////////////////////////////////////////////////////////////////////////////////// // 1d FFT // ////////////////////////////////////////////////////////////////////////////////////////// void FFT::init(const int N, const int M){ this-> N = N; this-> M = M; if(M > 0){ // initialize fft/ifft plan c1 = (fftw_complex*) fftw_malloc(sizeof(fftw_complex) * N * M); c2 = (fftw_complex*) fftw_malloc(sizeof(fftw_complex) * N * M); c3 = (fftw_complex*) fftw_malloc(sizeof(fftw_complex) * N * M); //build the maps. new (&v1) Eigen::Map<Eigen::ArrayXXcd>( (dcp*)&(c1[0][0]), N, M ); new (&v2) Eigen::Map<Eigen::ArrayXXcd>( (dcp*)&(c2[0][0]), N, M ); new (&v3) Eigen::Map<Eigen::ArrayXXcd>( (dcp*)&(c3[0][0]), N, M ); if (1 == M){ p = fftw_plan_dft_1d(N, c2, c3, FFTW_FORWARD, FFTW_MEASURE); rp = fftw_plan_dft_1d(N, c1, c2, FFTW_BACKWARD, FFTW_MEASURE); } else{ int n[] = { N }; p = fftw_plan_many_dft(1, n, M, c2, n, 1, N, c3, n, 1, N, FFTW_FORWARD, FFTW_MEASURE); rp = fftw_plan_many_dft(1, n, M, c1, n, 1, N, c2, n, 1, N, FFTW_BACKWARD, FFTW_MEASURE); } hasInit = true; NumOfInstance++; } } FFT::FFT(const int N, const int M) : N(N), M(M), v1(NULL, 0, 0), v2(NULL, 0, 0), v3(NULL, 0, 0){ init(N, M); } FFT::FFT() : v1(NULL, 0, 0), v2(NULL, 0, 0), v3(NULL, 0, 0){} FFT::~FFT(){ if (hasInit && M > 0){ fftw_destroy_plan(p); fftw_destroy_plan(rp); fftw_free(c1); fftw_free(c2); fftw_free(c3); /* releae the map */ new (&(v1)) Eigen::Map<Eigen::ArrayXXcd>(NULL, 0, 0); new (&(v2)) Eigen::Map<Eigen::ArrayXXcd>(NULL, 0, 0); new (&(v3)) Eigen::Map<Eigen::ArrayXXcd>(NULL, 0, 0); } // only the last instance cleans up if(--NumOfInstance == 0){ #ifdef CLEAN fftw_cleanup(); #endif /* CLEAN */ } } void FFT::fft() { fftw_execute(p); } void FFT::ifft() { fftw_execute(rp); v2 /= N; } ////////////////////////////////////////////////////////////////////////////////////////// // 1d RFFT // ////////////////////////////////////////////////////////////////////////////////////////// RFFT::RFFT(const int N, const int M, const int threadNum) : N(N), M(M), threadNum(threadNum), vc1(NULL, 0, 0), vr2(NULL, 0, 0), vc3(NULL, 0, 0) { if(++NumOfInstance == 1) { #ifdef TFFT // mutlithread fft. if(!fftw_init_threads()){ fprintf(stderr, "error create MultiFFT.\n"); exit(1); } // fftw_plan_with_nthreads(omp_get_max_threads()); fftw_plan_with_nthreads(threadNum); #endif /* TFFT */ } if(M > 0) { r2 = (double*) fftw_malloc(sizeof(double) * N * M); c1 = (fftw_complex*) fftw_malloc(sizeof(fftw_complex) * (N/2+1) * M); c3 = (fftw_complex*) fftw_malloc(sizeof(fftw_complex) * (N/2+1) * M); new (&vr2) Map<ArrayXXd>( &(r2[0]), N, M); new (&vc1) Map<ArrayXXcd>( (dcp*)&(c1[0][0]), N/2+1, M ); new (&vc3) Map<ArrayXXcd>( (dcp*)&(c3[0][0]), N/2+1, M ); if (1 == M){ p = fftw_plan_dft_r2c_1d(N, r2, c3, FFTW_MEASURE); rp = fftw_plan_dft_c2r_1d(N, c1, r2, FFTW_MEASURE|FFTW_PRESERVE_INPUT); } else{ int n[]={N}; p = fftw_plan_many_dft_r2c(1, n, M, r2, n, 1, N, c3, n, 1, N/2+1, FFTW_MEASURE); rp = fftw_plan_many_dft_c2r(1, n, M, c1, n, 1, N/2+1, r2, n, 1, N, FFTW_MEASURE|FFTW_PRESERVE_INPUT); } } } RFFT::~RFFT(){ if(M > 0){ /* free the memory */ fftw_destroy_plan(p); fftw_destroy_plan(rp); fftw_free(c1); fftw_free(r2); fftw_free(c3); /* release the maps */ new (&(vc1)) Map<ArrayXXcd>(NULL, 0, 0); new (&(vr2)) Map<ArrayXXd>(NULL, 0, 0); new (&(vc3)) Map<ArrayXXcd>(NULL, 0, 0); } if(--NumOfInstance == 0 ){ #ifdef CLEAN fftw_cleanup(); #endif /* CLEAN */ #ifdef TFFT fftw_cleanup_threads(); #endif /* TFFT */ } } void RFFT::fft() { fftw_execute(p); } void RFFT::ifft() { //cout << vc1 << endl << endl; fftw_execute(rp); // cout << vr2 << endl; vr2 /= N; } ////////////////////////////////////////////////////////////////////////////////////////// // 2d FFT // ////////////////////////////////////////////////////////////////////////////////////////// /* @brief 2dFFT for a [N x M] matrix. Note N rows M colums */ FFT2d::FFT2d(const int N, const int M, const int threadNum): N(N), M(M), threadNum(threadNum), v1(NULL, 0, 0), v2(NULL, 0, 0), v3(NULL, 0, 0) { // only the first instance do some initialization if(++NumOfInstance == 1){ #ifdef TFFT // mutlithread fft. if(!fftw_init_threads()){ fprintf(stderr, "error create MultiFFT.\n"); exit(1); } // fftw_plan_with_nthreads(omp_get_max_threads()); fftw_plan_with_nthreads(threadNum); #endif /* TFFT */ } c1 = (fftw_complex*) fftw_malloc(sizeof(fftw_complex) * N * M); c2 = (fftw_complex*) fftw_malloc(sizeof(fftw_complex) * N * M); c3 = (fftw_complex*) fftw_malloc(sizeof(fftw_complex) * N * M); //build the maps. new (&v1) Eigen::Map<Eigen::ArrayXXcd>( (dcp*)&(c1[0][0]), N, M ); new (&v2) Eigen::Map<Eigen::ArrayXXcd>( (dcp*)&(c2[0][0]), N, M ); new (&v3) Eigen::Map<Eigen::ArrayXXcd>( (dcp*)&(c3[0][0]), N, M ); /* note, FFTW use row-major format, so M, N exchanged */ p = fftw_plan_dft_2d(M, N, c2, c3, FFTW_FORWARD, FFTW_MEASURE); rp = fftw_plan_dft_2d(M, N, c1, c2, FFTW_BACKWARD, FFTW_MEASURE); } FFT2d::~FFT2d(){ fftw_destroy_plan(p); fftw_destroy_plan(rp); fftw_free(c1); fftw_free(c2); fftw_free(c3); /* releae the map */ new (&(v1)) Eigen::Map<Eigen::ArrayXXcd>(NULL, 0, 0); new (&(v2)) Eigen::Map<Eigen::ArrayXXcd>(NULL, 0, 0); new (&(v3)) Eigen::Map<Eigen::ArrayXXcd>(NULL, 0, 0); // only the last instance cleans up if(--NumOfInstance == 0){ #ifdef CLEAN fftw_cleanup(); #endif /* CLEAN */ #ifdef TFFT fftw_cleanup_threads(); #endif /* TFFT */ } } void FFT2d::fft() { fftw_execute(p); } void FFT2d::ifft() { fftw_execute(rp); v2 /= (N*M); } } <file_sep>/* h5c++ test_KSEIDr.cc -std=c++11 -lksint -lmyfft -lmyH5 -ldenseRoutines -literMethod -lfftw3 -I $RESH/include/ -L $RESH/lib/ -I $XDAPPS/eigen/include/eigen3 -DEIGEN_FFTW_DEFAULT -O3 && ./a.out */ #include <iostream> #include <ctime> #include "KSEIDr.hpp" #include "myH5.hpp" #include "ksint.hpp" #include "denseRoutines.hpp" #define cee(x) cout << (x) << endl << endl; #define N50 using namespace MyH5; using namespace std; using namespace Eigen; using namespace denseRoutines; int main(){ std::vector<std::string> scheme = {"Cox_Matthews", "Krogstad", "Hochbruck_Ostermann", "Luan_Ostermann", "IFRK43", "IFRK54", "SSPP43"}; std::string file = "/usr/local/home/xiong/00git/research/data/ks22h001t120x64.h5"; std::string poType = "ppo"; MatrixXd a0; double T, r, s; int nstp; std::tie(a0, T, nstp, r, s) = KSreadRPO(file, poType, 1); #ifdef N3 //==================================================================================================== // save the state of 2T of ppo1 by one scheme to check whether the orbit is closed or not KSEIDr ks(64, 22); ks.setScheme(scheme[6]); ArrayXXd aa = ks.intgC(a0, T/nstp, 2*T, 1); savetxt("aa.dat", aa.topRows(3)); #endif #ifdef N5 //==================================================================================================== // test the implemenation of Cox-Matthews is consistent with previous implementation by // verifying the accuarycy of ppo1 KSEIDr ks(64, 22); ArrayXXd aa = ks.intgC(a0, T/nstp, T, 1); KS ks2(64, 22); VectorXd a1 = ks2.Reflection(aa.rightCols(1)); ArrayXXd aa2 = ks2.intg(a0, T/nstp, nstp, 1); VectorXd a2 = ks2.Reflection(aa2.rightCols(1)); double err1 = (a1-a0).norm(); double err2 = (a2-a0).norm(); cout << err1 << '\t' << err2 << endl; // Result: // 4.05043e-14 3.92468e-14 #endif #ifdef N10 //==================================================================================================== // test whether the implementations are correct by using ppo1. // Criteria : after one period and reflection, the orbit should be closed KSEIDr ks(64, 22); KS ks2(64, 22); ArrayXXd aa; for(int i = 0; i < scheme.size(); i++) { ks.setScheme(scheme[i]); aa = ks.intgC(a0, T/nstp, T, 1); VectorXd a1 = ks2.Reflection(aa.rightCols(1)); cout << (a1 - a0).norm() << endl; } // Output: // 4.08788e-14 // 2.10358e-13 // 3.26765e-13 // 3.67868e-13 // 7.0766e-11 // 3.80098e-13 // 3.1632e-11 #endif #ifdef N20 //==================================================================================================== // test the order of different schemes by varying time step // By constant stepping, the estimated LTEs are saved KSEIDr ks(64, 22); for(int k = 1; k < 1000; k*=10){ MatrixXd lte(nstp/k, scheme.size()); for(int i = 0; i < scheme.size(); i++) { ks.setScheme(scheme[i]); ArrayXXd aa = ks.intgC(a0, T/nstp*k, T, 1); lte.col(i) = ks.lte; } savetxt("KS_N20_lte" + to_string(k) + ".dat", lte); } #endif #ifdef N30 //==================================================================================================== // Test the accuracy of constant stepping shemes. // Choose Luan-Ostermann method with a small time step as the base, then integrate the // system for one period of ppo1. KSEIDr ks(64, 22); ks.setScheme("Luan_Ostermann"); double h0 = T/131072; // 2^17 ArrayXd x0 = ks.intgC(a0, h0, T, 10000).rightCols(1); int n = 10; MatrixXd erros(n, scheme.size()+1); for(int i = 0; i < scheme.size(); i++) { ks.setScheme(scheme[i]); for(int j = 0, k=8; j < n; j++, k*=2){ double h = k*h0; if(i == 0) erros(j, 0) = h; ArrayXXd aa = ks.intgC(a0, h, T, 1); double err = (aa.rightCols(1) - x0).abs().maxCoeff() / x0.abs().maxCoeff(); erros(j, i+1) = err; cout << err << ' '; } cout << endl; } savetxt("KS_N30_err.dat", erros); #endif #ifdef N40 //==================================================================================================== // time adaptive stepping // test the implemenation of Cox-Matthews is consistent with previous implementation by // verifying the accuarycy of ppo1 KSEIDr ks(64, 22); ArrayXXd aa = ks.intg(a0, T/nstp, T, 1); KS ks2(64, 22); VectorXd a1 = ks2.Reflection(aa.rightCols(1)); ArrayXXd aa2 = ks2.intg(a0, T/nstp, nstp, 1); VectorXd a2 = ks2.Reflection(aa2.rightCols(1)); double err1 = (a1-a0).norm(); double err2 = (a2-a0).norm(); cout << err1 << '\t' << err2 << endl; cout << aa.cols() << '\t' << ks.lte.maxCoeff() << '\t' << ks.hs.maxCoeff() << endl; cout << ks.eidr.NCalCoe << ' ' << ks.eidr.NReject << ' ' << ks.eidr.NCallF << ' ' << ks.eidr.NSteps << endl; // Output: // 1.19741e-08 3.92468e-14 // 699 6.53879e-09 0.0152952 // 8 2 3505 699 #endif #ifdef N50 //==================================================================================================== // same as N40, but test all shemes KSEIDr ks(64, 22); KS ks2(64, 22); for(int i = 0; i < scheme.size(); i++) { ks.setScheme(scheme[i]); ArrayXXd aa = ks.intg(a0, T/nstp, T, 1); VectorXd a1 = ks2.Reflection(aa.rightCols(1)); cout << (a1-a0).norm() << ' ' << ks.lte.maxCoeff() << ' ' << ks.hs.maxCoeff() << ' '; cout << ks.eidr.NCalCoe << ' ' << ks.eidr.NReject << ' ' << ks.eidr.NCallF << ' ' << ks.eidr.NSteps << endl; } // Output: // // 1.19741e-08 6.53879e-09 0.0152952 8 2 3505 699 // 1.45044e-08 6.51859e-09 0.0251392 9 2 2600 518 // 7.36104e-09 6.53008e-09 0.0251002 10 2 2600 518 // 2.12496e-09 2.44513e-09 0.082695 8 0 1215 135 // 2.50557e-08 6.54958e-09 0.00559735 8 2 11695 2337 // 1.90432e-08 5.89591e-09 0.0132776 8 1 6202 885 // 1.94839e-10 6.55866e-09 0.00202678 7 2 154752 6446 #endif return 0; } <file_sep>from personalFunctions import * from py_ks import * case = 50 N, L = 64, 22 eqFile = '../../data/ks22Reqx64.h5' poFile = '../../data/ks22h001t120x64EV.h5' if case == 10: """ plot the configuration profile of eq and req """ ks = pyKS(N, L) ksp = KSplot(ks) for i in range(1, 4): a, err = ksp.readEq(eqFile, i) ksp.oneConfig(a, axisLabelSize=25, tickSize=18) for i in range(1, 3): a, w, err = ksp.readReq(eqFile, i) ksp.oneConfig(a, axisLabelSize=25, tickSize=18) if case == 20: """ plot the 2 req with time and the symmetry reduced figues """ ks = pyKS(N, L) ksp = KSplot(ks) h = 2e-3 T = 100 for i in range(1, 3): a, w, err = ksp.readReq(eqFile, i) aa = ks.intg(a, h, np.int(T/h), 5) raa, ths = ks.redSO2(aa, 1, False) ksp.config(aa, [0, L, 0, T], axisLabelSize=25, tickSize=16) ksp.config(raa, [0, L, 0, T], axisLabelSize=25, tickSize=16) if case == 30: """ Plot rpo and ppo configuration in the full state space and in the reduced space. Also plot without labels. """ ks = pyKS(N, L) ksp = KSplot(ks) Ts = 100 for poType in ['ppo', 'rpo']: for i in range(1, 4): a0, T, nstp, r, s = ksp.readPO(poFile, poType, i) h = T / nstp aa = ks.intg(a0, h, np.int(Ts/h), 5) raa, ths = ks.redSO2(aa, 1, False) name = 'ks' + poType + str(i) + 'T100' ksp.config(aa, [0, L, 0, Ts], axisLabelSize=25, tickSize=16, save=True, name=name) ksp.config(raa, [0, L, 0, Ts], axisLabelSize=25, tickSize=16,save=True, name=name+'Red') ksp.config(aa, [0, L, 0, Ts], axisLabelSize=25, tickSize=16, save=True, name=name+'NoLabel', labs=[None, None]) ksp.config(raa, [0, L, 0, Ts], axisLabelSize=25, tickSize=16,save=True, name=name+'NoLabel'+'Red', labs=[None, None]) if case == 50: """ plot rpo / ppo in the full state space for a few pieces """ ks = pyKS(N, L) ksp = KSplot(ks) Ts = 100 fig, ax = pl3d(size=[8, 6], labs=[r'$b_1$', r'$b_2$', r'$c_2$']) fig2, ax2 = pl3d(size=[8, 6], labs=[r'$b_1$', r'$b_2$', r'$c_2$']) poType = 'rpo' poIds = [5, 22] cs = ['b', 'r'] for i in range(len(poIds)): poId = poIds[i] a0, T, nstp, r, s = ksp.readPO(poFile, poType, poId) h = T / nstp aa = ks.intg(a0, h, np.int(T/h), 5) raa, ths = ks.redSO2(aa, 1, False) name = 'ks' + poType + str(i) + 'T100' for j in range(10): aa2 = ks.Rotation(aa, -s*j / L*2*np.pi) ax.plot(aa2[:, 0], aa2[:, 2], aa2[:, 3], c=cs[i]) ax2.plot(raa[:, 0], raa[:, 2], raa[:, 3], c=cs[i]) plt.locator_params(nbins=4) ax3d(fig, ax) ax3d(fig2, ax2)
15fca27f60ab7fd42fe21511da4f18f2dae51bc7
[ "Markdown", "Makefile", "Python", "C++", "Shell" ]
189
C++
dingxiong/research
b7e82bec1cf7b23cfa840f3cb305a2682164d2f3
1bae45c54a0804c0a3fd4daccd4e8865b9ebebec
refs/heads/master
<file_sep>package com.rimac; import java.util.List; public interface FizzBuzz { List<String> doMagic(int from, int until); } <file_sep>package com.rimac; import java.util.List; public class MyFirstFizzBuzz implements FizzBuzz { /* // This method receives: // Lower bound of closed interval, "from" // Upper bound of closed interval, "until" // // This method outputs (in return value, not on screen): // "Fizz" if the number is divisible by 3 // "Buzz" if the number is divisible by 5 // String representation of the number otherwise */ @Override public List<String> doMagic(int from, int until) { throw new UnsupportedOperationException("Not yet implemented!"); } }
23d0129dfa60e5d7b9f7e0899be5d56b0d6c007c
[ "Java" ]
2
Java
ioreskovic/fizz-buzz
041bc697e2e1d7211b104ebbd9fc4a77700a45a4
0622a3b752099e2208ea9c63e9aea3b08227b400
refs/heads/master
<file_sep>// // RequestGeneric.swift // TheMovieApp // // Created by <NAME> on 17/04/19. // Copyright © 2019 Rafael. All rights reserved. // import Foundation enum Language: String, Codable { case US = "en-US" } class GenericRequest : Codable { var page: Int? var language: Language? } <file_sep>// // HomeWorker.swift // TheMovieApp // // Created by <NAME> on 17/04/19. // Copyright (c) 2019 Rafael. All rights reserved. // // This file was generated by the Clean Swift Xcode Templates so // you can apply clean architecture to your iOS and Mac projects, // see http://clean-swift.com // import Foundation class HomeWorker { private var base = Api.BASE_URL private let api_key = Api.API_KEY func fetchDiscovers(completion: @escaping ((Home.Fetch.ResponseDiscover) -> Void), failure: @escaping ((GenericError) -> Void)) { let service = ServiceClient<Home.Fetch.ResponseDiscover>(baseUrl: self.base) service.fetch(resource: "discover/movie", method: .GET, queryParams: ["api_key": self.api_key], completion: { (response) in completion(response) }) { (code, message) in failure(GenericError(cod: code, message: message)) } } func fetchTrends(completion: @escaping ((Home.Fetch.ResponseTrending) -> Void), failure: @escaping ((GenericError) -> Void)) { let service = ServiceClient<Home.Fetch.ResponseTrending>(baseUrl: self.base) service.fetch(resource: "trending/movie/day", method: .GET, queryParams:["api_key": self.api_key], completion: { (response) in completion(response) }) { (code, message) in failure(GenericError(cod: code, message: message)) } } } <file_sep>// // Response.swift // TheMovieApp // // Created by <NAME> on 17/04/19. // Copyright © 2019 Rafael. All rights reserved. // import Foundation class ResponseGeneric<T: Codable> : Codable { var page: Int? var total_results: Int? var total_pages: Int? var results = [T]() } <file_sep>// // HomePresenter.swift // TheMovieApp // // Created by <NAME> on 17/04/19. // Copyright (c) 2019 Rafael. All rights reserved. // // This file was generated by the Clean Swift Xcode Templates so // you can apply clean architecture to your iOS and Mac projects, // see http://clean-swift.com // import UIKit protocol HomePresentationLogic { func presentSuccessDiscover(response: Home.Fetch.ResponseDiscover) func presentFailedDiscover(error: GenericError) func presentSuccessTrends(response: Home.Fetch.ResponseTrending) func presentFailedTrends(error: GenericError) } class HomePresenter: HomePresentationLogic { weak var viewController: HomeDisplayLogic? // MARK: Do something func presentSuccessDiscover(response: Home.Fetch.ResponseDiscover) { self.viewController?.successDisplayDiscoveredMovies(response: response) } func presentFailedDiscover(error: GenericError) { self.viewController?.failureDisplayDiscoveredMovies(error: error) } func presentSuccessTrends(response: Home.Fetch.ResponseTrending) { self.viewController?.successDisplayTrendsMovies(response: response) } func presentFailedTrends(error: GenericError) { self.viewController?.failureDisplayTrendsMovies(error: error) } } <file_sep>// // HomeInteractor.swift // TheMovieApp // // Created by <NAME> on 17/04/19. // Copyright (c) 2019 Rafael. All rights reserved. // // This file was generated by the Clean Swift Xcode Templates so // you can apply clean architecture to your iOS and Mac projects, // see http://clean-swift.com // import UIKit protocol HomeBusinessLogic { func fetchDiscovered(request: Home.Fetch.Request) func fetchTrends(request: Home.Fetch.Request) } protocol HomeDataStore { //var name: String { get set } } class HomeInteractor: HomeBusinessLogic, HomeDataStore { var presenter: HomePresentationLogic? var trendsPresenter: HomePresentationLogic? var discoverWorker: HomeWorker? var trendsWorker: HomeWorker? //var name: String = "" // MARK: Do something func fetchDiscovered(request: Home.Fetch.Request) { discoverWorker = HomeWorker() discoverWorker?.fetchDiscovers(completion: { (response) in self.presenter?.presentSuccessDiscover(response: response) }, failure: { (error) in self.presenter?.presentFailedDiscover(error: error) }) } func fetchTrends(request: Home.Fetch.Request) { trendsWorker = HomeWorker() trendsWorker?.fetchTrends(completion: { (response) in self.presenter?.presentSuccessTrends(response: response) }, failure: { (error) in self.presenter?.presentFailedTrends(error: error) }) } } <file_sep>// // HomeModels.swift // TheMovieApp // // Created by <NAME> on 17/04/19. // Copyright (c) 2019 Rafael. All rights reserved. // // This file was generated by the Clean Swift Xcode Templates so // you can apply clean architecture to your iOS and Mac projects, // see http://clean-swift.com // import UIKit struct Home { // MARK: Use cases struct Fetch { class Request : GenericRequest {} class ResponseDiscover : ResponseGeneric<DiscoverEntity>{} class DiscoverEntity : GenericMovie{} class ResponseTrending : ResponseGeneric<TrendingEntity>{} class TrendingEntity : GenericMovie{} } } <file_sep>// // API.swift // TheMovieApp // // Created by <NAME> on 17/04/19. // Copyright © 2019 Rafael. All rights reserved. // import Foundation class Api { static let BASE_URL = "https://api.themoviedb.org/3/" static let API_KEY = "<KEY>" } <file_sep>// // GenericError.swift // TheMovieApp // // Created by <NAME> on 17/04/19. // Copyright © 2019 Rafael. All rights reserved. // import Foundation struct GenericError { var cod: Int? var message: String? } <file_sep>// // ServiceClient.swift // TheMovieApp // // Created by <NAME> on 17/04/19. // Copyright © 2019 Rafael. All rights reserved. // import Foundation enum Method : String { case GET = "GET" case POST = "POST" } class ServiceClient<T : Codable> { typealias Completion = ((T) -> Void) typealias Failure = ((_ code: Int, _ message: String) -> Void) private let BASE_URL: String init(baseUrl: String) { self.BASE_URL = baseUrl } private func url(resource: String) -> URL? { let url_string = BASE_URL + resource guard let URL = URL(string: url_string) else { return nil } return URL } func fetch(resource: String, method: Method, queryParams: Dictionary<String, String>, completion: @escaping Completion, failure: @escaping Failure) { var urlQuery = String() for param in queryParams { urlQuery = urlQuery + "\(param.key)=\(param.value)&" } urlQuery = String(urlQuery.dropLast()) guard let url = url(resource: "\(resource)?\(urlQuery)") else { return } var urlRequest = URLRequest(url: url) urlRequest.httpMethod = method.rawValue let session = URLSession.shared.dataTask(with: urlRequest) { (data, response, error) in if let error = error { if let httpResponse = response as? HTTPURLResponse { failure(httpResponse.statusCode, error.localizedDescription) } } if let data = data { do { let json = try JSONDecoder().decode(T.self, from: data) DispatchQueue.main.async { completion(json) } } catch let error { DispatchQueue.main.async { failure(1, error.localizedDescription) } } } } session.resume() } } <file_sep>// // HomeViewController.swift // TheMovieApp // // Created by <NAME> on 17/04/19. // Copyright (c) 2019 Rafael. All rights reserved. // // This file was generated by the Clean Swift Xcode Templates so // you can apply clean architecture to your iOS and Mac projects, // see http://clean-swift.com // import UIKit protocol HomeDisplayLogic: class { func successDisplayDiscoveredMovies(response: Home.Fetch.ResponseDiscover) func failureDisplayDiscoveredMovies(error: GenericError) func successDisplayTrendsMovies(response: Home.Fetch.ResponseTrending) func failureDisplayTrendsMovies(error: GenericError) } class HomeViewController: UIViewController, HomeDisplayLogic { let nibControllerName = "HomeViewController" var interactor: HomeBusinessLogic? var router: (NSObjectProtocol & HomeRoutingLogic & HomeDataPassing)? // MARK: Object lifecycle override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) { super.init(nibName: nibControllerName, bundle: Bundle.main) setup() } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) setup() } // MARK: Setup private func setup() { let viewController = self let interactor = HomeInteractor() let presenter = HomePresenter() let router = HomeRouter() viewController.interactor = interactor viewController.router = router interactor.presenter = presenter presenter.viewController = viewController router.viewController = viewController router.dataStore = interactor } // MARK: Routing override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if let scene = segue.identifier { let selector = NSSelectorFromString("routeTo\(scene)WithSegue:") if let router = router, router.responds(to: selector) { router.perform(selector, with: segue) } } } // MARK: View lifecycle override func viewDidLoad() { super.viewDidLoad() doSomething() } // MARK: Do something //@IBOutlet weak var nameTextField: UITextField! func doSomething() { let request = Home.Fetch.Request() interactor?.fetchDiscovered(request: request) interactor?.fetchTrends(request: request) } func successDisplayDiscoveredMovies(response: Home.Fetch.ResponseDiscover) { for i in response.results { print("DEU BOM NESSA MERDA \(i.title)") } } func failureDisplayDiscoveredMovies(error: GenericError) { print("ERROUUU \(error.cod ?? 0)") } func successDisplayTrendsMovies(response: Home.Fetch.ResponseTrending) { for i in response.results { print("DEU BOM NESSA MERDA DE TRENDS \(i.title)") } } func failureDisplayTrendsMovies(error: GenericError) { print("ERROUUU \(error.cod ?? 0)") } }
b24e051be073295a8b18a6c35ce62aab30b31579
[ "Swift" ]
10
Swift
rafaelcrz/ios-movie-app
ba8ea98c232e7536c08506d06c2ff9057d21afbc
95f48c8b452f5bd3d9779585a5e57c9646788489
refs/heads/master
<file_sep> // // AddViewController.swift // BrawlDatabase // // Created by <NAME> on 19/12/18. // Copyright © 2018 <NAME>. All rights reserved. // import UIKit protocol AddViewControllerDelegate: class { func addViewController(_ vc: AddViewController, didEditTask task: Task) } class AddViewController: UIViewController { @IBOutlet weak var viewBack: UIView! @IBOutlet weak var textField: UITextField! @IBOutlet weak var saveButton : UIButton! internal var task: Task! weak var delegate: AddViewControllerDelegate! convenience init(task: Task?) { self.init() if task == nil{ self.task = Task() self.task.id = UUID().uuidString self.task.name = "" self.task.isDone = false } else{ self.task = task } } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) UIView.animate(withDuration: 0.8) { self.view.backgroundColor = UIColor.white.withAlphaComponent(0.8) } } override func viewDidLoad() { super.viewDidLoad() viewBack.layer.cornerRadius = 8.0 viewBack.layer.masksToBounds = true saveButton.layer.cornerRadius = 8.0 saveButton.layer.masksToBounds = true // Do any additional setup after loading the view. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } @IBAction func closeButtonPressed(){ dismiss(animated: true, completion: nil) } @IBAction func saveButtonPressed(){ self.task.name = textField.text delegate.addViewController(self, didEditTask: task) } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ } <file_sep>// // TaskCell.swift // BrawlDatabase // // Created by <NAME> on 19/12/18. // Copyright © 2018 <NAME>. All rights reserved. // import UIKit class TaskCell: UITableViewCell { @IBOutlet weak var lblTaskCell : UILabel! @IBOutlet weak var imgTaskCell : UIImageView! override func awakeFromNib() { super.awakeFromNib() // Initialization code } override func setSelected(_ selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) // Configure the view for the selected state } } <file_sep>// // Task.swift // BrawlDatabase // // Created by <NAME> on 19/12/18. // Copyright © 2018 <NAME>. All rights reserved. // import UIKit class Task{ var id : String! var name: String! var isDone = false }
b1f3e23cd23218b5218909bf65a3a517258a568a
[ "Swift" ]
3
Swift
nacholagorta/SwiftBrawl
fbc99da25979b5a3647a881179a15da5dd4eb98a
2fe03ea3461c78ecdbe58f20be5e32f9dd282201
refs/heads/master
<file_sep>package edu.jsu.mcis.cs310.tas_sp21; public class Shift { //There should also be " getShift() " methods //UNIX_TIMESTAMP() //To retrieve the hours and minutes from the TIME fields of the //Shift table as separate values, use the HOUR() and MINUTE() functions of MySQL. //"Shift Start” and “Shift Stop" //“Lunch Start” and “Lunch Stop” private String shift; private String id; private String description; private int start; private int stop; private int interval; private int graceperiod; private int dock; private int lunchstart; private int lunchstop; private int lunchduration; private int lunchdeduct; public Shift(String id, String description, int start, int stop, int interval, int graceperiod, int dock, int lunchstart, int lunchstop, int lunchdeduct) { this.shift = shift; this.id = id; this.description = description; this.start = start; this.stop = stop; this.interval = interval; this.graceperiod = graceperiod; this.dock = dock; this.lunchstart = lunchstart; this.lunchstop = lunchstop; this.lunchdeduct = lunchdeduct; } public String getShift() { return shift; } public String getId() { return id; } public String getDescription() { return description; } public int getStart() { return start; } public int getStop() { return stop; } public int getInterval() { return interval; } public int getGraceperiod() { return graceperiod; } public int getDock() { return dock; } public int getLunchstart() { return lunchstart; } public int getLunchstop() { return lunchstop; } public int getLunchdeduct() { return lunchdeduct; } @Override public String toString() { //"#07901755, (Terrell, <NAME>)" StringBuilder s = new StringBuilder(); s.append("#").append(id).append(" "); s.append("(").append(description).append(")"); return ( s.toString() ); } }
8c6844a86b6e62e2a3122aad522d2b611f867a53
[ "Java" ]
1
Java
Jay-Batiste/ProjectTeamE
e81571f10e994ffe68f52bac9aaa3ee533702c62
145440446e8c7e09e4fe9138bd493a8b9be27e04
refs/heads/master
<repo_name>Knalpot45/Movie-ti-PPB<file_sep>/movie/app/src/main/java/com/example/d2a/movie/Model.java package com.example.d2a.movie; public class Model { private String title; private String rating; private String status; public Model(String title, String rating, String status) { this.title = title; this.rating = rating; this.status = status; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getRating() { return rating; } public void setRating(String rating) { this.rating = rating; } public String getStatus() { return status; } public void setStatus(String status) { this.status = status; } } <file_sep>/movie/app/src/main/java/com/example/d2a/movie/ModelAdapter.java package com.example.d2a.movie; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import java.util.ArrayList; public class ModelAdapter extends RecyclerView.Adapter<ModelAdapter.ModelViewHolder> { private ArrayList<Model> dataList; public ModelAdapter(ArrayList<Model> dataList) { this.dataList = dataList; } @Override public ModelViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { LayoutInflater layoutInflater = LayoutInflater.from(parent.getContext()); View view = layoutInflater.inflate(R.layout.list_view, parent, false); return new ModelViewHolder(view); } @Override public void onBindViewHolder(ModelViewHolder holder, int position) { holder.txt_title.setText(dataList.get(position).getTitle()); holder.txt_rating.setText(dataList.get(position).getRating()); holder.txt_status.setText(dataList.get(position).getStatus()); } @Override public int getItemCount() { return (dataList != null) ? dataList.size() : 0; } public class ModelViewHolder extends RecyclerView.ViewHolder{ private TextView txt_title, txt_rating, txt_status; public ModelViewHolder(View itemView) { super(itemView); txt_title = (TextView) itemView.findViewById(R.id.txttitle); txt_rating = (TextView) itemView.findViewById(R.id.txtrating); txt_status = (TextView) itemView.findViewById(R.id.txtstatus); } } }
88cf74cf15ec14e4f9255adcddf3a82aa46c7a4a
[ "Java" ]
2
Java
Knalpot45/Movie-ti-PPB
34182c7a9850c4ef73eacef0e2495d54d90a0c01
2e3e843bcee38e8daf4033ca76589027b7caf02a
refs/heads/master
<repo_name>hyoungjong1856/algorithmForOperation<file_sep>/integration/integration/integrationDlg.cpp  // integrationDlg.cpp: 구현 파일 // #include "stdafx.h" #include "integration.h" #include "integrationDlg.h" #include "afxdialogex.h" #ifdef _DEBUG #define new DEBUG_NEW #endif // 응용 프로그램 정보에 사용되는 CAboutDlg 대화 상자입니다. class CAboutDlg : public CDialogEx { public: CAboutDlg(); // 대화 상자 데이터입니다. #ifdef AFX_DESIGN_TIME enum { IDD = IDD_ABOUTBOX }; #endif protected: virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV 지원입니다. // 구현입니다. protected: DECLARE_MESSAGE_MAP() }; CAboutDlg::CAboutDlg() : CDialogEx(IDD_ABOUTBOX) { } void CAboutDlg::DoDataExchange(CDataExchange* pDX) { CDialogEx::DoDataExchange(pDX); } BEGIN_MESSAGE_MAP(CAboutDlg, CDialogEx) END_MESSAGE_MAP() // CintegrationDlg 대화 상자 CintegrationDlg::CintegrationDlg(CWnd* pParent /*=nullptr*/) : CDialogEx(IDD_INTEGRATION_DIALOG, pParent) { m_hIcon = AfxGetApp()->LoadIcon(IDR_MAINFRAME); } void CintegrationDlg::DoDataExchange(CDataExchange* pDX) { CDialogEx::DoDataExchange(pDX); DDX_Control(pDX, IDC_GRID, m_Grid); DDX_Control(pDX, IDC_CHART, m_chartViewer); } BEGIN_MESSAGE_MAP(CintegrationDlg, CDialogEx) ON_WM_SYSCOMMAND() ON_WM_PAINT() ON_WM_QUERYDRAGICON() END_MESSAGE_MAP() // CintegrationDlg 메시지 처리기 BOOL CintegrationDlg::OnInitDialog() { CDialogEx::OnInitDialog(); // 시스템 메뉴에 "정보..." 메뉴 항목을 추가합니다. // IDM_ABOUTBOX는 시스템 명령 범위에 있어야 합니다. ASSERT((IDM_ABOUTBOX & 0xFFF0) == IDM_ABOUTBOX); ASSERT(IDM_ABOUTBOX < 0xF000); CMenu* pSysMenu = GetSystemMenu(FALSE); if (pSysMenu != nullptr) { BOOL bNameValid; CString strAboutMenu; bNameValid = strAboutMenu.LoadString(IDS_ABOUTBOX); ASSERT(bNameValid); if (!strAboutMenu.IsEmpty()) { pSysMenu->AppendMenu(MF_SEPARATOR); pSysMenu->AppendMenu(MF_STRING, IDM_ABOUTBOX, strAboutMenu); } } // 이 대화 상자의 아이콘을 설정합니다. 응용 프로그램의 주 창이 대화 상자가 아닐 경우에는 // 프레임워크가 이 작업을 자동으로 수행합니다. SetIcon(m_hIcon, TRUE); // 큰 아이콘을 설정합니다. SetIcon(m_hIcon, FALSE); // 작은 아이콘을 설정합니다. // TODO: 여기에 추가 초기화 작업을 추가합니다. //------------------------------------------------------------------ // 표 //------------------------------------------------------------------ BOOL m_bEditable = FALSE; BOOL m_bListMode = TRUE; int m_nRows = 5; int m_nCols = 6; int m_nFixRows = 1; int m_nFixCols = 0; m_Grid.SetEditable(m_bEditable); m_Grid.SetListMode(m_bListMode); m_Grid.EnableDragAndDrop(FALSE); m_Grid.SetTextBkColor(RGB(0xFF, 0xFF, 0xFF)); // 원소들 배경색 m_Grid.SetRowCount(m_nRows); m_Grid.SetColumnCount(m_nCols); m_Grid.SetFixedRowCount(m_nFixRows); m_Grid.SetFixedColumnCount(m_nFixCols); DWORD dwTextStyle = DT_RIGHT | DT_VCENTER | DT_CENTER | DT_SINGLELINE; CString title[6] = { L"이름", L"도착시간", L"BT", L"WT", L"TT", L"NTT" }; // 릴레이션 스키마 for (int row = 0; row < m_Grid.GetRowCount(); row++) { for (int col = 0; col < m_Grid.GetColumnCount(); col++) { GV_ITEM Item; Item.mask = GVIF_TEXT | GVIF_FORMAT; Item.row = row; Item.col = col; if (row < m_nFixRows) { Item.nFormat = DT_CENTER; Item.strText.Format(title[col]); } m_Grid.SetItem(&Item); if (row == 0) m_Grid.SetItemBkColour(row, col, RGB(200, 200, 200)); // 배경색 //m_Grid.SetItemFgColour(row, col, RGB(100, 100, 100)); // 글자색 } } // 릴레이션 인스턴스 for (int row = 1; row < m_Grid.GetRowCount(); row++) { for (int col = 0; col < m_Grid.GetColumnCount(); col++) { GV_ITEM Item; Item.mask = GVIF_TEXT | GVIF_FORMAT; Item.row = row; Item.col = col; Item.nFormat = dwTextStyle; // 인스턴스 값들 설정 Item.strText.Format(L"%d",col); m_Grid.SetItem(&Item); } } // Make cell 1,1 read-only //m_Grid.SetItemState(1, 1, m_Grid.GetItemState(1, 1) | GVIS_READONLY); // 프로세스 개수 m_Grid.AutoSize(5); // 줄마다 크기 설정 m_Grid.SetRowHeight(0, 3 * m_Grid.GetRowHeight(0) / 2); //m_Grid.SetColumnWidth(2,10); m_Edit = (CEdit*)GetDlgItem(IDC_GRID); // 평균 TT구하기 float tt = 55.55f; CString ttString; ttString.Format(_T("평균 TT : %f"), tt); m_Edit->SetWindowText(ttString); //------------------------------------------------------------------ // 그래프 //------------------------------------------------------------------ // 프로세스 이름(이름 개수대로 생성) const char *labels[] = { "Process1", "Process2", "Process3" }; // The task index, start date, end date and color for each bar double taskNo[] = { 1, 0, 2, 1 }; double startData[] = { 0, 3, 8, 5 }; double endData[] = { 3, 5, 13, 8 }; // 그래프바 색깔 int colors[] = { 0x0000ff, 0x0000ff, 0x0000ff, 0x0000ff, 0x0000ff, 0x0000ff }; // 사이즈와 배경색 조절(x,y,배경색,테두리색, 그림자길이(3d느낌)) XYChart *c = new XYChart(600, 300, 0xffffcc, 0xffffff, 0); // 타이틀 이름, 폰트, 사이즈, 색, 타이틀배경색 c->addTitle("Process Progressing !", "timesbi.ttf", 15, 0xffffff)->setBackground(0x555555); // Set the plotarea at (140, 55) and of size 460 x 200 pixels. Use alternative white/grey // background. Enable both horizontal and vertical grids by setting their colors to grey // (c0c0c0). Set vertical major grid (represents month boundaries) 2 pixels in width c->setPlotArea(100, 55, 460, 100, 0xffffff, 0xeeeeee, Chart::LineColor, 0xc0c0c0, 0xc0c0c0 )->setGridWidth(2, 1, 1, 1); // swap the x and y axes to create a horziontal box-whisker chart c->swapXY(); // x축 최대 길이 설정 및 점선 거리 c->yAxis()->setDateScale(0, 15, 1); // Set the y-axis to shown on the top (right + swapXY = top) c->setYAxisOnRight(); // Set the labels on the x axis c->xAxis()->setLabels(StringArray(labels, (int)(sizeof(labels) / sizeof(labels[0])))); // Reverse the x-axis scale so that it points downwards. c->xAxis()->setReverse(); // Set the horizontal ticks and grid lines to be between the bars c->xAxis()->setTickOffset(0.5); // Add a multi-color box-whisker layer to represent the gantt bars BoxWhiskerLayer *layer = c->addBoxWhiskerLayer2(DoubleArray(startData, (int)(sizeof(startData) / sizeof(startData[0]))), DoubleArray(endData, (int)(sizeof(endData) / sizeof(endData[0]))), DoubleArray(), DoubleArray(), DoubleArray(), IntArray(colors, (int)(sizeof(colors) / sizeof( colors[0])))); layer->setXData(DoubleArray(taskNo, (int)(sizeof(taskNo) / sizeof(taskNo[0])))); layer->setBorderColor(Chart::SameAsMainColor); // Divide the plot area height ( = 200 in this chart) by the number of tasks to get the height // of each slot. Use 80% of that as the bar height. layer->setDataWidth(100 * 4 / 5 / (int)(sizeof(labels) / sizeof(labels[0]))); // 항목 이름 나타내기 LegendBox *legendBox = c->addLegend2(100, 250, Chart::AutoGrid, "arialbd.ttf", 10); legendBox->setWidth(461); legendBox->setBackground(0xdddddd); legendBox->addKey("Process", 0x00cc00); legendBox->addKey("Process1", 0x0000cc); legendBox->addKey("Process2", 0xcc0000); // Output the chart c->makeChart(); m_chartViewer.setChart(c); delete c; return TRUE; // 포커스를 컨트롤에 설정하지 않으면 TRUE를 반환합니다. } void CintegrationDlg::OnSysCommand(UINT nID, LPARAM lParam) { if ((nID & 0xFFF0) == IDM_ABOUTBOX) { CAboutDlg dlgAbout; dlgAbout.DoModal(); } else { CDialogEx::OnSysCommand(nID, lParam); } } // 대화 상자에 최소화 단추를 추가할 경우 아이콘을 그리려면 // 아래 코드가 필요합니다. 문서/뷰 모델을 사용하는 MFC 응용 프로그램의 경우에는 // 프레임워크에서 이 작업을 자동으로 수행합니다. void CintegrationDlg::OnPaint() { if (IsIconic()) { CPaintDC dc(this); // 그리기를 위한 디바이스 컨텍스트입니다. SendMessage(WM_ICONERASEBKGND, reinterpret_cast<WPARAM>(dc.GetSafeHdc()), 0); // 클라이언트 사각형에서 아이콘을 가운데에 맞춥니다. int cxIcon = GetSystemMetrics(SM_CXICON); int cyIcon = GetSystemMetrics(SM_CYICON); CRect rect; GetClientRect(&rect); int x = (rect.Width() - cxIcon + 1) / 2; int y = (rect.Height() - cyIcon + 1) / 2; // 아이콘을 그립니다. dc.DrawIcon(x, y, m_hIcon); } else { CDialogEx::OnPaint(); } } // 사용자가 최소화된 창을 끄는 동안에 커서가 표시되도록 시스템에서 // 이 함수를 호출합니다. HCURSOR CintegrationDlg::OnQueryDragIcon() { return static_cast<HCURSOR>(m_hIcon); } <file_sep>/integration/integration/integration.h  // integration.h: PROJECT_NAME 응용 프로그램에 대한 주 헤더 파일입니다. // #pragma once #ifndef __AFXWIN_H__ #error "PCH에 대해 이 파일을 포함하기 전에 'stdafx.h'를 포함합니다." #endif #include "resource.h" // 주 기호입니다. // CintegrationApp: // 이 클래스의 구현에 대해서는 integration.cpp을(를) 참조하세요. // class CintegrationApp : public CWinApp { public: CintegrationApp(); // 재정의입니다. public: virtual BOOL InitInstance(); // 구현입니다. DECLARE_MESSAGE_MAP() }; extern CintegrationApp theApp;
c62a5f1de12d6c877178a4306d59c313993f8207
[ "C++" ]
2
C++
hyoungjong1856/algorithmForOperation
7b9da95e47a1d83673c2ecd6894dc1d57d78a125
cd2cbbea4e4f008a4152ce13967e94e6577f3abb
refs/heads/master
<file_sep>package com.boulder.mchistory.basic; import java.io.IOException; import java.io.PrintWriter; import java.util.List; import java.util.logging.Logger; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.boulder.mchistory.daos.PostDao; import com.boulder.mchistory.objects.Post; import com.boulder.mchistory.objects.Result; @SuppressWarnings("serial") @WebServlet(name = "HomePageScroll", value = "/HomePageScroll") public class HomePageScroll extends HttpServlet { @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { processRequest(request, response); } @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { } private static final Logger logger = Logger.getLogger(HomePageScroll.class.getName()); protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { PostDao dao = (PostDao) this.getServletContext().getAttribute("postDao"); String startCursor = request.getParameter("cursor"); List<Post> posts = null; String endCursor = null; try { Result<Post> result = dao.listPosts(startCursor); logger.info("ViewAlbum result = " + result); posts = result.result; logger.info("ViewAlbum posts = " + posts); endCursor = result.cursor; } catch (Exception e) { throw new ServletException("Error listing posts", e); } PrintWriter out = response.getWriter(); StringBuilder postNames = new StringBuilder(); for (Post post : posts) { postNames.append(post.getTitle() + " "); if (post.getInfo().length() > 200) { StringBuilder str = new StringBuilder(post.getInfo()); str.setLength(200); str.append(" ..."); post.setInfo(str.toString()); } String resp = ""; switch(post.getType()) { case "Photo": resp += " <a href='/ViewPost?id="+post.getId()+"&type="+post.getType()+"'>" + " <div class='col-sm-12 media-body'>" + " <div class='col-sm-3 thumb'>" + " <img class='thumb' alt='ahhh' src='"+post.getImageUrl()+"'>" + " </div>" + " <div class='col-sm-1'>" + " <p class='post-description'><span><img class='icon' src='images/photo.svg' width='16'></span> "+post.getType()+"</p>" + " </div>" + " <div class='col-sm-8'>" + " <h4 class='post-title'>"+post.getTitle()+"</h4>" + " </div>" + " <div class='col-sm-9'>" + " <p class='post-description'>"+post.getInfo()+"</p>" + " </div>" + " <div class='col-sm-12'>" + " <p class='post-description'>Added by "+post.getCreatedBy()+"</p>" + " </div>" + " </div>" + " </a> "; break; case "Event": resp += " <a href='/ViewPost?id="+post.getId()+"&type="+post.getType()+"'>" + " <div class='col-sm-12 media-body'>" + " <div class='col-sm-3 thumb'>" + " <img class='thumb' alt='ahhh' src='"+post.getImageUrl()+"'>" + " </div>" + " <div class='col-sm-1'>" + " <p class='post-description'><span><img class='icon' src='images/event.svg' width='16'></span> "+post.getType()+"</p>" + " </div>" + " <div class='col-sm-4'>" + " <h4 class='post-title'>"+post.getTitle()+"</h4>" + " </div>" + " <div class='col-sm-2'>" + " <p class='post-description'>"+post.getDateString()+"</p>" + " </div>" + " <div class='col-sm-2'>" + " <p class='post-description'>"+post.getTime()+"</p>" + " </div>" + " <div class='col-sm-9'>" + " <p class='post-description'>"+post.getInfo()+"</p>" + " </div>" + " <div class='col-sm-12'>" + " <p class='post-description'>Added by "+post.getCreatedBy()+"</p>" + " </div>" + " </div>" + " </a> "; break; case "Video": resp += " <a href='/ViewPost?id="+post.getId()+"&type="+post.getType()+"'>" + " <div class='col-sm-12 media-body'>" + " <div class='col-sm-3 thumb'>" + " <img class='thumb' alt='ahhh' src='"+post.getImageUrl()+"'>" + " </div>" + " <div class='col-sm-1'>" + " <p class='post-description'><span><img class='icon' src='images/video.svg' width='16'></span> "+post.getType()+"</p>" + " </div>" + " <div class='col-sm-8'>" + " <h4 class='post-title'>"+post.getTitle()+"</h4>" + " </div>" + " <div class='col-sm-9'>" + " <p class='post-description'>"+post.getInfo()+"</p>" + " </div>" + " <div class='col-sm-12'>" + " <p class='post-description'>Added by "+post.getCreatedBy()+"</p>" + " </div>" + " </div>" + " </a> "; break; } out.write(resp); } out.write("<input hidden='hidden' id='cursor' value='"+endCursor+"'></input>"); out.close(); } } <file_sep>package com.boulder.mchistory.basic; import java.io.IOException; import java.io.PrintWriter; import java.util.List; import java.util.logging.Logger; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.boulder.mchistory.daos.AlbumDao; import com.boulder.mchistory.objects.Album; import com.boulder.mchistory.objects.Result; @SuppressWarnings("serial") @WebServlet(name = "ListAlbumsScroll", value = "/ListAlbumsScroll") public class ListAlbumsScroll extends HttpServlet { @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { processRequest(request, response); } @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { } private static final Logger logger = Logger.getLogger(ListAlbumsScroll.class.getName()); protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { AlbumDao dao = (AlbumDao) this.getServletContext().getAttribute("albumDao"); String startCursor = request.getParameter("cursor"); List<Album> albums = null; String endCursor = null; try { Result<Album> result = dao.listAlbums(startCursor); albums = result.result; endCursor = result.cursor; } catch (Exception e) { throw new ServletException("Error listing albums", e); } PrintWriter out = response.getWriter(); StringBuilder albumNames = new StringBuilder(); for (Album album : albums) { albumNames.append(album.getTitle() + " "); String resp = ""; resp += "<div class='media'>" + "<a href='/ViewPost?id="+album.getId()+"&type=Album'>" + "<div class='media-left'>" + "<h4 class='post-title'>"+album.getTitle()+"</h4>" + "<img class='thumb' alt='ahhh' src='"+album.getImageUrl()+"'>" + "</div>" + "</a>"; if (request.getSession().getAttribute("isAdmin") != null) { Boolean isAdmin = Boolean.valueOf((String)request.getSession().getAttribute("isAdmin")); if (isAdmin) { resp += "<div class='btn-group'>" + "<a href='/EditPost?id="+album.getId()+"&type=Album&album=${album.id}' class='btn btn-default btn-xs'>" + "<span class='edit-16 icon'></span> Edit" + "</a>" + "<a href='/DeletePost?id="+album.getId()+"&type=Album&album=${album.id}' class='btn btn-danger btn-xs'>" + "<span class='delete-16 icon'></span> Delete" + "</a>" + "</div>"; } } resp += "</div>"; out.write(resp); } out.write("<input hidden='hidden' id='cursor' value='"+endCursor+"'></input>"); out.close(); } } <file_sep>package com.boulder.mchistory.auth; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; // [START example] @WebServlet(name = "Logout", value = "/Logout") @SuppressWarnings("serial") public class LogoutServlet extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException { // you can also make an authenticated request to logout, but here we choose to // simply delete the session variables for simplicity HttpSession session = req.getSession(false); if (session != null) { session.invalidate(); } // rebuild session req.getSession(); String url = resp.encodeRedirectURL("Home"); resp.sendRedirect(url); } } // [END example] <file_sep><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.boulder</groupId> <artifactId>mchistory-ubm</artifactId> <packaging>war</packaging> <version>0.0.1-SNAPSHOT</version> <name>MC History</name> <url>http://maven.apache.org</url> <dependencies> <!-- jUnit --> <!-- https://mvnrepository.com/artifact/junit/junit --> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.13.1</version> <scope>test</scope> </dependency> <!-- https://mvnrepository.com/artifact/javax.servlet/javax.servlet-api --> <dependency> <groupId>javax.servlet</groupId> <artifactId>javax.servlet-api</artifactId> <version>3.1.0</version> <scope>provided</scope> </dependency> <!-- MongoDB --> <!-- https://mvnrepository.com/artifact/org.mongodb/mongodb-driver --> <dependency> <groupId>org.mongodb</groupId> <artifactId>mongodb-driver</artifactId> <version>3.11.0</version> </dependency> <!-- Google GSON --> <dependency> <groupId>com.google.code.gson</groupId> <artifactId>gson</artifactId> <version>2.8.5</version> </dependency> <!-- Google Datastore --> <dependency> <groupId>com.google.cloud</groupId> <artifactId>google-cloud-datastore</artifactId> <version>1.88.0</version> </dependency> <!-- JSP Taglibs --> <dependency> <groupId>jstl</groupId> <artifactId>jstl</artifactId> <version>1.2</version> </dependency> <dependency> <groupId>taglibs</groupId> <artifactId>standard</artifactId> <version>1.1.2</version> </dependency> <!-- /JSP Taglibs --> <!-- JWT --> <dependency> <groupId>io.jsonwebtoken</groupId> <artifactId>jjwt</artifactId> <version>0.9.1</version> </dependency> <!-- Google Storage --> <dependency> <groupId>com.google.cloud</groupId> <artifactId>google-cloud-storage</artifactId> <version>1.88.0</version> </dependency> <!-- Mailgun --> <dependency> <groupId>com.sun.mail</groupId> <artifactId>javax.mail</artifactId> <version>1.6.2</version> </dependency> <dependency> <groupId>com.mashape.unirest</groupId> <artifactId>unirest-java</artifactId> <version>1.4.9</version> </dependency> <dependency> <groupId>net.sargue</groupId> <artifactId>mailgun</artifactId> <version>1.9.0</version> </dependency> <dependency> <groupId>com.sun.jersey</groupId> <artifactId>jersey-core</artifactId> <version>1.19.4</version> </dependency> <dependency> <groupId>com.sun.jersey</groupId> <artifactId>jersey-client</artifactId> <version>1.19.4</version> </dependency> <dependency> <groupId>com.sun.jersey.contribs</groupId> <artifactId>jersey-multipart</artifactId> <version>1.19.4</version> </dependency> <!-- Guava declaration needed to avoid dependency collision in GCP APIs --> <!-- https://mvnrepository.com/artifact/com.google.guava/guava --> <dependency> <groupId>com.google.guava</groupId> <artifactId>guava</artifactId> <version>30.0-jre</version> </dependency> <!-- IO Utils: used in CloudStorageHelper --> <!-- https://mvnrepository.com/artifact/commons-io/commons-io --> <dependency> <groupId>commons-io</groupId> <artifactId>commons-io</artifactId> <version>2.6</version> </dependency> <!-- Google Sign-In --> <!-- https://mvnrepository.com/artifact/com.google.apis/google-api-services-identitytoolkit --> <dependency> <groupId>com.google.apis</groupId> <artifactId>google-api-services-identitytoolkit</artifactId> <version>v3-rev20180723-1.30.1</version> </dependency> <dependency> <groupId>joda-time</groupId> <artifactId>joda-time</artifactId> <version>2.9.2</version> </dependency> </dependencies> <build> <finalName>MC-History</finalName> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <version>3.1</version> <configuration> <source>1.8</source> <target>1.8</target> </configuration> </plugin> </plugins> </build> </project> <file_sep>package com.boulder.mchistory.basic; import java.io.IOException; import java.util.List; import java.util.logging.Logger; import javax.servlet.ServletException; import javax.servlet.annotation.MultipartConfig; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.boulder.mchistory.daos.PostDao; import com.boulder.mchistory.objects.Post; import com.boulder.mchistory.objects.Result; @SuppressWarnings("serial") @MultipartConfig @WebServlet(name = "Events", value = "/Events") public class Events extends HttpServlet { private final Logger logger = Logger.getLogger(Events.class.getName()); @Override public void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { PostDao dao = (PostDao) this.getServletContext().getAttribute("postDao"); String startCursor = req.getParameter("cursor"); List<Post> events = null; String endCursor = null; try { Result<Post> result = dao.listEvents(startCursor); events = result.result; endCursor = result.cursor; } catch (Exception e) { throw new ServletException("Error listing photos", e); } StringBuilder eventNames = new StringBuilder(); for (Post event : events) { eventNames.append(event.getTitle() + " "); if (event.getInfo().length() > 200) { StringBuilder str = new StringBuilder(event.getInfo()); str.setLength(200); str.append(" ..."); event.setInfo(str.toString()); } } req.setAttribute("events", events); req.setAttribute("cursor", endCursor); req.setAttribute("page", "events"); req.getRequestDispatcher("/base.jsp").forward(req, resp); } @Override public void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { } } <file_sep>package com.boulder.mchistory.daos; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; import com.boulder.mchistory.objects.Album; import com.boulder.mchistory.objects.Result; import com.google.cloud.datastore.Cursor; import com.google.cloud.datastore.Datastore; import com.google.cloud.datastore.DatastoreOptions; import com.google.cloud.datastore.Entity; import com.google.cloud.datastore.FullEntity; import com.google.cloud.datastore.IncompleteKey; import com.google.cloud.datastore.Key; import com.google.cloud.datastore.KeyFactory; import com.google.cloud.datastore.Query; import com.google.cloud.datastore.QueryResults; import com.google.cloud.datastore.StructuredQuery.OrderBy; public class AlbumDatastore implements AlbumDao { // [START constructor] private Datastore datastore; private KeyFactory keyFactory; public AlbumDatastore() { datastore = DatastoreOptions.getDefaultInstance().getService(); // Authorized Datastore service keyFactory = datastore.newKeyFactory().setKind("Album"); // Is used for creating keys later } // [END constructor] // [START entityToAlbum] public Album entityToAlbum(Entity entity) { return new Album.Builder() // Convert to Album form .id(entity.getKey().getId()) .title(entity.getString(Album.TITLE)) .imageUrl(entity.contains(Album.IMAGE_URL) ? entity.getString(Album.IMAGE_URL) : null) .createdBy(entity.getString(Album.CREATED_BY)) .createdById(entity.getString(Album.CREATED_BY_ID)) .build(); } // [END entityToAlbum] @Override public Long createAlbum(Album album) throws SQLException { IncompleteKey key = keyFactory.newKey(); // Key will be assigned once written FullEntity<IncompleteKey> incAlbumEntity = Entity.newBuilder(key) // Create the Entity .set(Album.TITLE, album.getTitle()) .set(Album.IMAGE_URL, album.getImageUrl()) .set(Album.CREATED_BY, album.getCreatedBy()) .set(Album.CREATED_BY_ID, album.getCreatedById()) .build(); Entity albumEntity = datastore.add(incAlbumEntity); // Save the Entity return albumEntity.getKey().getId(); // The ID of the Key } @Override public void updateAlbum(Album album) throws SQLException { Key key = keyFactory.newKey(album.getId()); // From a album, create a Key Entity entity = Entity.newBuilder(key) // Convert Album to an Entity .set(Album.TITLE, album.getTitle()) .set(Album.IMAGE_URL, album.getImageUrl()) .set(Album.CREATED_BY, album.getCreatedBy()) .set(Album.CREATED_BY_ID, album.getCreatedById()) .build(); datastore.update(entity); // Update the Entity } @Override public void deleteAlbum(Long albumId) throws SQLException { Key key = keyFactory.newKey(albumId); // Create the Key datastore.delete(key); // Delete the Entity } // [START entitiesToAlbums] public List<Album> entitiesToAlbums(QueryResults<Entity> resultList) { List<Album> resultAlbums = new ArrayList<>(); while (resultList.hasNext()) { // We still have data resultAlbums.add(entityToAlbum(resultList.next())); // Add the Album to the List } return resultAlbums; } // [END entitiesToAlbums] // [START read] @Override public Album viewAlbum(Long albumId) { Entity albumEntity = datastore.get(keyFactory.newKey(albumId)); // Load an Entity for Key(id) return entityToAlbum(albumEntity); } // [END read] @Override public Result<Album> listAlbums(String startCursorString) throws SQLException { Cursor startCursor = null; if (startCursorString != null && !startCursorString.equals("")) { startCursor = Cursor.fromUrlSafe(startCursorString); // Where we left off } Query<Entity> query = Query.newEntityQueryBuilder() // Build the Query .setKind("Album") // We only care about Albums .setLimit(10) // Only show 10 at a time .setStartCursor(startCursor) // Where we left off .setOrderBy(OrderBy.asc(Album.TITLE)) // Use default Index "title" .build(); QueryResults<Entity> resultList = datastore.run(query); // Run the query List<Album> resultAlbums = entitiesToAlbums(resultList); // Retrieve and convert Entities Cursor cursor = resultList.getCursorAfter(); // Where to start next time if (cursor != null && resultAlbums.size() == 10) { // Are we paging? Save Cursor String cursorString = cursor.toUrlSafe(); // Cursors are WebSafe return new Result<>(resultAlbums, cursorString); } else { return new Result<>(resultAlbums); } } } <file_sep>package com.boulder.mchistory.basic; import java.io.IOException; import java.io.PrintWriter; import java.util.List; import java.util.logging.Logger; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.boulder.mchistory.daos.PostDao; import com.boulder.mchistory.objects.Post; import com.boulder.mchistory.objects.Result; @SuppressWarnings("serial") @WebServlet(name = "VideosScroll", value = "/VideosScroll") public class VideosScroll extends HttpServlet { @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { processRequest(request, response); } @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { } private static final Logger logger = Logger.getLogger(VideosScroll.class.getName()); protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { PostDao dao = (PostDao) this.getServletContext().getAttribute("postDao"); String startCursor = request.getParameter("cursor"); List<Post> videos = null; String endCursor = null; try { Result<Post> result = dao.listVideos(startCursor); videos = result.result; endCursor = result.cursor; } catch (Exception e) { throw new ServletException("Error listing videos", e); } PrintWriter out = response.getWriter(); StringBuilder videoNames = new StringBuilder(); for (Post video : videos) { videoNames.append(video.getTitle() + " "); if (video.getInfo().length() > 200) { StringBuilder str = new StringBuilder(video.getInfo()); str.setLength(200); str.append(" ..."); video.setInfo(str.toString()); } String resp = ""; resp += "<div class='media'>" + "<a href='/ViewPost?id="+video.getId()+"&type=Video'>" + "<div class='media-left'>" + "<h4 class='post-title'>"+video.getTitle()+"</h4>" + "<img class='thumb' alt='ahhh' src='"+video.getImageUrl()+"'>" + "<p class='post-description'>"+video.getInfo()+"</p>" + "</div>" + "</a>"; if (request.getSession().getAttribute("isAdmin") != null) { Boolean isAdmin = Boolean.valueOf((String)request.getSession().getAttribute("isAdmin")); if (isAdmin) { resp += "<div class='btn-group'>" + "<a href='/EditPost?id="+video.getId()+"&type=Video&album=${album.id}' class='btn btn-default btn-xs'>" + "<span class='edit-16 icon'></span> Edit" + "</a>" + "<a href='/DeletePost?id="+video.getId()+"&type=Video&album=${album.id}' class='btn btn-danger btn-xs'>" + "<span class='delete-16 icon'></span> Delete" + "</a>" + "</div>"; } } resp += "</div>"; out.write(resp); } out.write("<input hidden='hidden' id='cursor' value='"+endCursor+"'></input>"); out.close(); } } <file_sep>package com.boulder.mchistory.daos; import java.sql.SQLException; import java.util.logging.Logger; import javax.servlet.http.HttpSession; import com.boulder.mchistory.objects.User; import com.google.cloud.datastore.Datastore; import com.google.cloud.datastore.DatastoreOptions; import com.google.cloud.datastore.Entity; import com.google.cloud.datastore.EntityQuery; import com.google.cloud.datastore.KeyFactory; import com.google.cloud.datastore.Query; import com.google.cloud.datastore.QueryResults; import com.google.cloud.datastore.StructuredQuery.PropertyFilter; public class SessionDatastore implements SessionDao { private static final Logger logger = Logger.getLogger(UserDatastore.class.getName()); private Datastore datastore; private KeyFactory keyFactory; public SessionDatastore() { datastore = DatastoreOptions.getDefaultInstance().getService(); // Authorized Datastore service keyFactory = datastore.newKeyFactory().setKind("SessionVariable"); } @Override public String getSessionId(Long uid) throws SQLException { String id = null; EntityQuery query = Query.newEntityQueryBuilder() // Build the Query .setKind("SessionVariable") // We only care about Books .setFilter(PropertyFilter.eq("userId", uid))// Only for this user .build(); QueryResults<Entity> result = datastore.run(query); if (result.hasNext()) { id = result.next().getKey().getId().toString(); } return id; } } <file_sep>package com.boulder.mchistory.basic; import com.boulder.mchistory.daos.AlbumDao; import com.boulder.mchistory.objects.Album; import com.boulder.mchistory.util.CloudStorageHelper; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.annotation.MultipartConfig; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.Part; // [START example] @SuppressWarnings("serial") @MultipartConfig @WebServlet(name = "EditAlbum", value = "/EditAlbum") public class EditAlbum extends HttpServlet { @Override public void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { AlbumDao dao = (AlbumDao) this.getServletContext().getAttribute("albumDao"); try { Album album = dao.viewAlbum(Long.decode(req.getParameter("id"))); req.setAttribute("album", album); req.setAttribute("action", "Edit"); req.setAttribute("destination", "EditAlbum"); req.setAttribute("page", "form-album"); req.getRequestDispatcher("/base.jsp").forward(req, resp); } catch (Exception e) { throw new ServletException("Error loading album for editing", e); } } @Override public void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { CloudStorageHelper storageHelper = (CloudStorageHelper) req.getServletContext().getAttribute("storageHelper"); Part part = req.getPart("file"); String imageUrl = storageHelper.getImageUrl(part, req, resp, getServletContext().getInitParameter("skelly.bucket")); AlbumDao dao = (AlbumDao) this.getServletContext().getAttribute("albumDao"); try { Album oldAlbum = dao.viewAlbum(Long.decode(req.getParameter("id"))); Album album = new Album.Builder() .createdBy(oldAlbum.getCreatedBy()) .createdById(oldAlbum.getCreatedById()) .id(Long.decode(req.getParameter("id"))) .title(req.getParameter("title")) .imageUrl(imageUrl) .build(); dao.updateAlbum(album); String url = resp.encodeRedirectURL("ViewAlbum?id=" + req.getParameter("id")); resp.sendRedirect(url); } catch (Exception e) { throw new ServletException("Error updating album", e); } } } // [END example] <file_sep>package com.boulder.mchistory.basic; import java.io.IOException; import java.io.PrintWriter; import java.util.List; import java.util.logging.Logger; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.boulder.mchistory.daos.PostDao; import com.boulder.mchistory.objects.Post; import com.boulder.mchistory.objects.Result; @SuppressWarnings("serial") @WebServlet(name = "EventsScroll", value = "/EventsScroll") public class EventsScroll extends HttpServlet { @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { processRequest(request, response); } @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { } private static final Logger logger = Logger.getLogger(EventsScroll.class.getName()); protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { PostDao dao = (PostDao) this.getServletContext().getAttribute("postDao"); String startCursor = request.getParameter("cursor"); List<Post> events = null; String endCursor = null; try { Result<Post> result = dao.listEvents(startCursor); events = result.result; endCursor = result.cursor; } catch (Exception e) { throw new ServletException("Error listing events", e); } PrintWriter out = response.getWriter(); StringBuilder eventNames = new StringBuilder(); for (Post event : events) { eventNames.append(event.getTitle() + " "); if (event.getInfo().length() > 200) { StringBuilder str = new StringBuilder(event.getInfo()); str.setLength(200); str.append(" ..."); event.setInfo(str.toString()); } String resp = "<div class='media'>" + " <a href='/ViewPost?id="+event.getId()+"&type=Event'>" + " <div class='col-sm-12 media-body'>" + " <div class='col-sm-3 thumb'>" + " <img class='thumb' alt='ahhh' src='"+event.getImageUrl()+"'>" + " </div>" + " <div class='col-sm-5'>" + " <h4 class='post-title'>"+event.getTitle()+"</h4>" + " </div>" + " <div class='col-sm-2'>" + " <p class='post-description'>"+event.getDateString()+"</p>" + " </div>" + " <div class='col-sm-2'>" + " <p class='post-description'>"+event.getTime()+"</p>" + " </div>" + " <div class='col-sm-9'>" + " <p class='post-description'>"+event.getInfo()+"</p>" + " </div>" + " </div>" + " </a>"; if (request.getSession().getAttribute("isAdmin") != null) { Boolean isAdmin = Boolean.valueOf((String)request.getSession().getAttribute("isAdmin")); if (isAdmin) { resp += "<div class='btn-group'>" + "<a href='/EditPost?id="+event.getId()+"&type=Event&album=${album.id}' class='btn btn-default btn-xs'>" + "<span class='edit-16 icon'></span> Edit" + "</a>" + "<a href='/DeletePost?id="+event.getId()+"&type=Event&album=${album.id}' class='btn btn-danger btn-xs'>" + "<span class='delete-16 icon'></span> Delete" + "</a>" + "</div>"; } } resp += "</div>"; out.write(resp); } out.write("<input hidden='hidden' id='cursor' value='"+endCursor+"'></input>"); out.close(); } } <file_sep>package com.boulder.mchistory.basic; import com.boulder.mchistory.daos.PostDao; import com.boulder.mchistory.objects.Post; import com.boulder.mchistory.util.CloudStorageHelper; import com.google.cloud.Timestamp; import java.io.IOException; import java.io.InputStream; import java.text.DateFormat; import java.text.ParseException; import java.util.Date; import java.util.List; import java.util.Locale; import java.util.logging.Level; import java.util.logging.Logger; import java.util.stream.Collectors; import javax.servlet.ServletException; import javax.servlet.annotation.MultipartConfig; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.Part; @SuppressWarnings("serial") @MultipartConfig @WebServlet(name = "BulkUpload", urlPatterns = {"/BulkUpload"}) public class BulkUpload extends HttpServlet { private static final Logger logger = Logger.getLogger(BulkUpload.class.getName()); @Override public void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { switch (req.getParameter("type")) { case "Photo": String albumId = req.getParameter("album"); req.setAttribute("album", albumId); req.setAttribute("action", "Bulk Upload"); req.setAttribute("type", "Photo"); req.setAttribute("destination", "BulkUpload"); req.setAttribute("page", "bulk-upload"); req.getRequestDispatcher("/base.jsp").forward(req, resp); break; case "Video": req.setAttribute("action", "Bulk Upload"); req.setAttribute("type", "Video"); req.setAttribute("destination", "BulkUpload"); req.setAttribute("page", "bulk-upload"); req.getRequestDispatcher("/base.jsp").forward(req, resp); break; } } // [END setup] // [START formpost] @Override public void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { CloudStorageHelper storageHelper = (CloudStorageHelper) req.getServletContext().getAttribute("storageHelper"); String imageUrl = null; String videoUrl = null; Part part1 = req.getPart("file"); String createdByString = ""; String createdByIdString = ""; if (req.getSession().getAttribute("token") != null) { // Does the user have a logged in session? createdByString = (String) req.getSession().getAttribute("userName"); createdByIdString = (String) req.getSession().getAttribute("userId"); } PostDao dao = (PostDao) this.getServletContext().getAttribute("postDao"); List<Part> fileParts = req.getParts().stream().filter( part -> "file".equals(part.getName())).collect(Collectors.toList()); switch (req.getParameter("type")) { case "Photo": String album = req.getParameter("album"); for (Part part : fileParts) { imageUrl = storageHelper.getImageUrl(part, req, resp, getServletContext().getInitParameter("skelly.bucket")); Post photo = new Post.Builder() .type("Photo") .album(album) .dateCreated(Timestamp.of(new Date())) .title("") .imageUrl(imageUrl) .info("") .createdBy(createdByString) .createdById(createdByIdString) .build(); try { dao.createPost(photo); logger.log(Level.INFO, "Bulk Upload Complete", photo); } catch (Exception e) { throw new ServletException("Error uploading photos", e); } } String photosUrl = resp.encodeRedirectURL("ViewAlbum?album="+album); resp.sendRedirect(photosUrl); break; case "Video": for (Part part : fileParts) { videoUrl = storageHelper.getVideoUrl(part, req, resp, getServletContext().getInitParameter("skelly.bucket")); Post video = new Post.Builder() .type("Video") .dateCreated(Timestamp.of(new Date())) .title("") .imageUrl("images/logo1.png") .videoUrl(videoUrl) .info("") .createdBy(createdByString) .createdById(createdByIdString) .build(); try { dao.createPost(video); logger.log(Level.INFO, "Created photo {0}", video); } catch (Exception e) { throw new ServletException("Error creating video", e); } } String videosUrl = resp.encodeRedirectURL("Videos"); resp.sendRedirect(videosUrl); break; } } // [END formpost] } // [END example] <file_sep>package com.boulder.mchistory.basic; import java.io.IOException; import java.sql.SQLException; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.boulder.mchistory.daos.PostDao; // [START example] @SuppressWarnings("serial") @WebServlet(name = "DeletePost", value = "/DeletePost") public class DeletePost extends HttpServlet { @Override public void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { PostDao dao = (PostDao) this.getServletContext().getAttribute("postDao"); Long id = Long.decode(req.getParameter("id")); String type = req.getParameter("type"); try { dao.deletePost(id); } catch (Exception e) { throw new ServletException("Error deleting post", e); } String eventsUrl = resp.encodeRedirectURL("Events"); String photosUrl = resp.encodeRedirectURL("ViewAlbum?album="+req.getParameter("album")); String videosUrl = resp.encodeRedirectURL("Videos"); switch (type) { case "Event": resp.sendRedirect(eventsUrl); break; case "Photo": resp.sendRedirect(photosUrl); break; case "Video": resp.sendRedirect(videosUrl); } } } // [END example] <file_sep>package com.boulder.mchistory.basic; import java.io.IOException; import java.util.logging.Logger; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; // [START example] @SuppressWarnings("serial") @WebServlet(name = "ListBkmks", value = "/ListBkmks") public class ListBkmks extends HttpServlet { private static final Logger logger = Logger.getLogger(ListBkmks.class.getName()); @Override public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException { //TODO: CONVERT ALL PHOTOS TO POSTS } } // [END example] <file_sep>package com.boulder.mchistory.objects; public class Text { String body; Long id; public static final String BODY = "body"; public static final String ID = "id"; public String getBody() { return body; } public void setBody(String body) { this.body = body; } public Long getId() { return id; } } <file_sep>package com.boulder.mchistory.basic; import java.io.IOException; import java.util.logging.Level; import java.util.logging.Logger; import javax.servlet.ServletException; import javax.servlet.annotation.MultipartConfig; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.Part; import com.boulder.mchistory.daos.AlbumDao; import com.boulder.mchistory.objects.Album; import com.boulder.mchistory.util.CloudStorageHelper; @SuppressWarnings("serial") //[START annotations] @MultipartConfig @WebServlet(name = "NewAlbum", urlPatterns = {"/NewAlbum"}) //[END annotations] public class NewAlbum extends HttpServlet { private static final Logger logger = Logger.getLogger(NewAlbum.class.getName()); // [START setup] @Override public void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { this.getServletContext().setAttribute("album", null); req.setAttribute("action", "Add"); // Part of the Header in form.jsp req.setAttribute("destination", "NewAlbum"); // The urlPattern to invoke (this Servlet) req.setAttribute("page", "form-album"); // Tells base.jsp to include form.jsp req.getRequestDispatcher("/base.jsp").forward(req, resp); } // [END setup] // [START formalbum] @Override public void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { CloudStorageHelper storageHelper = (CloudStorageHelper) req.getServletContext().getAttribute("storageHelper"); Part part = req.getPart("file"); String imageUrl = storageHelper.getImageUrl(part, req, resp, getServletContext().getInitParameter("skelly.bucket")); String createdByString = ""; String createdByIdString = ""; if (req.getSession().getAttribute("token") != null) { // Does the user have a logged in session? createdByString = (String) req.getSession().getAttribute("userName"); createdByIdString = (String) req.getSession().getAttribute("userId"); } AlbumDao dao = (AlbumDao) this.getServletContext().getAttribute("albumDao"); Album album = new Album.Builder() .createdBy(createdByString) .createdById(createdByIdString) .title(req.getParameter("title")) .imageUrl(imageUrl) .build(); try { Long id = dao.createAlbum(album); this.getServletContext().setAttribute("album", id); logger.log(Level.INFO, "Created album {0}", album); String url = resp.encodeRedirectURL("ListAlbums"); resp.sendRedirect(url); } catch (Exception e) { throw new ServletException("Error creating album", e); } } // [END formalbum] } <file_sep>package com.boulder.mchistory.basic; import com.boulder.mchistory.daos.PostDao; import com.boulder.mchistory.objects.Post; import com.boulder.mchistory.util.CloudStorageHelper; import com.google.cloud.Timestamp; import java.io.IOException; import java.text.DateFormat; import java.text.ParseException; import java.util.Collection; import java.util.Date; import java.util.List; import java.util.Locale; import java.util.logging.Level; import java.util.logging.Logger; import javax.servlet.ServletException; import javax.servlet.annotation.MultipartConfig; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.Part; // [START example] @SuppressWarnings("serial") // [START annotations] @MultipartConfig @WebServlet(name = "NewPost", urlPatterns = {"/NewPost"}) // [END annotations] public class NewPost extends HttpServlet { private static final Logger logger = Logger.getLogger(NewPost.class.getName()); // [START setup] @Override public void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { switch (req.getParameter("type")) { case "Photo": String album = req.getParameter("id"); req.setAttribute("album", album); req.setAttribute("action", "New"); req.setAttribute("type", "Photo"); req.setAttribute("destination", "NewPost?type=Photo"); req.setAttribute("page", "form-post"); req.getRequestDispatcher("/base.jsp").forward(req, resp); break; case "Event": req.setAttribute("action", "New"); req.setAttribute("type", "Event"); req.setAttribute("destination", "NewPost?type=Event"); req.setAttribute("page", "form-post"); req.getRequestDispatcher("/base.jsp").forward(req, resp); break; case "Video": req.setAttribute("action", "New"); req.setAttribute("type", "Video"); req.setAttribute("destination", "NewPost?type=Video"); req.setAttribute("page", "form-post"); req.getRequestDispatcher("/base.jsp").forward(req, resp); break; } } // [END setup] // [START formpost] @Override public void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { CloudStorageHelper storageHelper = (CloudStorageHelper) req.getServletContext().getAttribute("storageHelper"); String bucket = getServletContext().getInitParameter("skelly.bucket"); String imageUrl = null; String videoUrl = null; Part img = req.getPart("image"); Part vid = req.getPart("video"); String createdByString = (String) req.getSession().getAttribute("userName"); String createdByIdString = (String) req.getSession().getAttribute("userId"); PostDao dao = (PostDao) this.getServletContext().getAttribute("postDao"); String text = req.getParameter("info"); StringBuffer preBuff = new StringBuffer(text); int preLoc = (new String(preBuff)).indexOf("<br>"); while(preLoc > 0){ preBuff.replace(preLoc, preLoc+4, ""); preLoc = (new String(preBuff)).indexOf("<br>"); } logger.info("Buffered preBuff: " + preBuff); StringBuffer buff = new StringBuffer(preBuff); int loc = (new String(preBuff)).indexOf('\n'); while(loc > 0){ preBuff.replace(loc, loc+1, "<br>"); loc = (new String(preBuff)).indexOf('\n'); } logger.info("Buffered buff: " + buff); String body = preBuff.toString(); switch (req.getParameter("type")) { case "Photo": imageUrl = storageHelper.getImageUrl(img, req, resp, bucket); String album = req.getParameter("album"); Post photo = new Post.Builder() .type("Photo") .album(album) .dateCreated(Timestamp.of(new Date())) .title(req.getParameter("title")) .imageUrl(imageUrl) .info(body) .createdBy(createdByString) .createdById(createdByIdString) .build(); try { dao.createPost(photo); logger.log(Level.INFO, "Created photo {0}", photo); } catch (Exception e) { throw new ServletException("Error creating photo", e); } String photosUrl = resp.encodeRedirectURL("ViewAlbum?album=" + album); resp.sendRedirect(photosUrl); break; case "Event": imageUrl = storageHelper.getImageUrl(img, req, resp, bucket); DateFormat format = DateFormat.getDateInstance(DateFormat.SHORT, Locale.US); Date date = null; try { date = format.parse(req.getParameter("date")); } catch (ParseException e1) { e1.printStackTrace(); } Post event = new Post.Builder() .type("Event") .date(Timestamp.of(date)) .dateString(req.getParameter("date")) .time(req.getParameter("time")) .location(req.getParameter("location")) .dateCreated(Timestamp.of(new Date())) .title(req.getParameter("title")) .imageUrl(imageUrl) .info(body) .createdBy(createdByString) .createdById(createdByIdString) .build(); try { dao.createPost(event); logger.log(Level.INFO, "Created photo {0}", event); } catch (Exception e) { throw new ServletException("Error creating photo", e); } String eventsUrl = resp.encodeRedirectURL("Events"); resp.sendRedirect(eventsUrl); break; case "Video": imageUrl = storageHelper.getImageUrl(img, req, resp, bucket); videoUrl = storageHelper.getVideoUrl(vid, req, resp, bucket); Post video = new Post.Builder() .type("Video") .dateCreated(Timestamp.of(new Date())) .title(req.getParameter("title")) .imageUrl(imageUrl) .videoUrl(videoUrl) .info(body) .createdBy(createdByString) .createdById(createdByIdString) .build(); try { dao.createPost(video); logger.log(Level.INFO, "Created photo {0}", video); } catch (Exception e) { throw new ServletException("Error creating video", e); } String videosUrl = resp.encodeRedirectURL("Videos"); resp.sendRedirect(videosUrl); break; } } // [END formpost] } // [END example] <file_sep>package com.boulder.mchistory.basic; import java.util.logging.Logger; import java.util.regex.Matcher; import java.util.regex.Pattern; import com.boulder.mchistory.auth.LoginEmail; public class FieldValidator { private static final Logger logger = Logger.getLogger(LoginEmail.class.getName()); private static final String EMAIL_PATTERN = "^[_A-Za-z0-9-\\+]+(\\.[_A-Za-z0-9-]+)*@" + "[A-Za-z0-9-]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$"; private static final String PASSWORD_PATTERN = "((?=.*\\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[@#$%]).{6,20})"; public static boolean validEmail(String email) { Pattern pattern = Pattern.compile(EMAIL_PATTERN); Matcher matcher = pattern.matcher(email); return matcher.matches(); } public static boolean validPass(String pass) { Pattern pattern = Pattern.compile(PASSWORD_PATTERN); Matcher matcher = pattern.matcher(pass); return matcher.matches(); } } <file_sep>package com.boulder.mchistory.daos; import com.boulder.mchistory.auth.PasswordStorage; import com.boulder.mchistory.auth.PasswordStorage.CannotPerformOperationException; import com.boulder.mchistory.auth.PasswordStorage.InvalidHashException; import com.boulder.mchistory.objects.Result; import com.boulder.mchistory.objects.User; import com.google.cloud.datastore.*; import com.google.cloud.datastore.StructuredQuery.PropertyFilter; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; public class UserDatastore implements UserDao { private final Datastore datastore; private final KeyFactory keyFactory; private final KeyFactory hashFactory; public UserDatastore() { datastore = DatastoreOptions.getDefaultInstance().getService(); keyFactory = datastore.newKeyFactory().setKind("User"); hashFactory = datastore.newKeyFactory().setKind("Hash"); } @Override public Boolean isUser(String email) { boolean isUser = false; EntityQuery query = Query.newEntityQueryBuilder() .setKind("User") .setFilter(PropertyFilter.eq(User.EMAIL, email)) .build(); QueryResults<Entity> result = datastore.run(query); if (result.hasNext()) { isUser = true; } return isUser; } public Long getUid(String email) throws SQLException { Long resp; EntityQuery query = Query.newEntityQueryBuilder() .setKind("User") .setFilter(PropertyFilter.eq(User.EMAIL, email)) .build(); QueryResults<Entity> result = datastore.run(query); if (result.hasNext()) { resp = result.next().getKey().getId(); } else { throw new SQLException("User not found."); } return resp; } public User entityToUser(Entity entity) { return new User.Builder() .email(entity.getString(User.EMAIL)) .username(entity.getString(User.USERNAME)) .emailVerified(entity.getBoolean(User.EMAILVERIFIED)) .isAdmin(entity.getBoolean(User.ISADMIN)) .id(entity.getKey().getId()) .imageUrl(entity.contains(User.IMAGE_URL) ? entity.getString(User.IMAGE_URL) : null) .role(entity.getString(User.ROLE)) .build(); } public List<User> entitiesToUsers(QueryResults<Entity> results) { List<User> resultList = new ArrayList<>(); while (results.hasNext()) { resultList.add(entityToUser(results.next())); } return resultList; } @Override public Long createUser(User user) { IncompleteKey key = keyFactory.newKey(); FullEntity<IncompleteKey> incUserEntity = Entity.newBuilder(key) .set(User.EMAIL, user.getEmail()) .set(User.USERNAME, user.getUsername()) .set(User.HASH, user.getHash()) .set(User.ACTHASH, user.getActHash()) .set(User.EMAILVERIFIED, user.getEmailVerified()) .set(User.ISADMIN, user.isAdmin()) .set(User.IMAGE_URL, user.getImageUrl()) .set(User.ROLE, user.getRole()) .build(); Entity userEntity = datastore.add(incUserEntity); return userEntity.getKey().getId(); } @Override public void verifyEmail(Long uid) { Entity entity = datastore.get(keyFactory.newKey(uid)); User user = entityToUser(entity); user.setEmailVerified(true); editUser(user); } @Override public void setAdminPass(String pass) { String hash = null; try { hash = PasswordStorage.createHash(pass); } catch (CannotPerformOperationException e) { e.printStackTrace(); } IncompleteKey key = hashFactory.newKey(); FullEntity<IncompleteKey> incEnt = Entity.newBuilder(key) .set("hash", hash) .build(); datastore.add(incEnt); } @Override public Boolean verifyAdmin(String pass) { boolean valid = false; EntityQuery query = Query.newEntityQueryBuilder() .setKind("Hash") .build(); QueryResults<Entity> result = datastore.run(query); Entity admin = result.next(); String hash = admin.getString("hash"); try { if (PasswordStorage.verifyPassword(pass, hash)) { valid = true; } } catch (CannotPerformOperationException | InvalidHashException e) { e.printStackTrace(); } return valid; } @Override public User grantAdmin(Long uid) { Entity entity = datastore.get(keyFactory.newKey(uid)); User user = entityToUser(entity); Key key = keyFactory.newKey(user.getId()); Entity newEntity = Entity.newBuilder(key) .set(User.EMAIL, user.getEmail()) .set(User.USERNAME, user.getUsername()) .set(User.ACTHASH, getActHash(user.getId())) .set(User.HASH, getHash(user.getId())) .set(User.EMAILVERIFIED, user.getEmailVerified()) .set(User.ISADMIN, true) .set(User.IMAGE_URL, user.getImageUrl()) .set(User.ROLE, "Board Member") .build(); datastore.update(newEntity); return getUser(uid); } @Override public User getUser(Long uid) { Entity entity = datastore.get(keyFactory.newKey(uid)); return entityToUser(entity); } @Override public void addBookmark(User user, String postId) { // TODO } @Override public Result<Object> listBkmks(User user) { // TODO return null; } @Override public String getHash(Long uid) { Entity entity = datastore.get(keyFactory.newKey(uid)); return entity.getString(User.HASH); } @Override public void setHash(Long uid, String hash) { Entity entity = datastore.get(keyFactory.newKey(uid)); User user = entityToUser(entity); Key key = keyFactory.newKey(uid); Entity inc = Entity.newBuilder(key) .set(User.EMAIL, user.getEmail()) .set(User.USERNAME, user.getUsername()) .set(User.ACTHASH, getActHash(user.getId())) .set(User.HASH, hash) .set(User.EMAILVERIFIED, user.getEmailVerified()) .set(User.ISADMIN, user.isAdmin()) .set(User.IMAGE_URL, user.getImageUrl()) .set(User.ROLE, user.getRole()) .build(); datastore.update(inc); } @Override public String getActHash(Long uid) { Entity entity = datastore.get(keyFactory.newKey(uid)); return entity.getString(User.ACTHASH); } @Override public void editUser(User user) { Key key = keyFactory.newKey(user.getId()); Entity entity = Entity.newBuilder(key) .set(User.EMAIL, user.getEmail()) .set(User.USERNAME, user.getUsername()) .set(User.ACTHASH, getActHash(user.getId())) .set(User.HASH, getHash(user.getId())) .set(User.EMAILVERIFIED, user.getEmailVerified()) .set(User.ISADMIN, user.isAdmin()) .set(User.IMAGE_URL, user.getImageUrl()) .set(User.ROLE, user.getRole()) .build(); datastore.update(entity); } @Override public void deleteUser(Long userId) { Key key = keyFactory.newKey(userId); datastore.delete(key); } @Override public Result<User> listUsers(String startCursor) { // TODO return null; } @Override public Result<User> listAdmins() { Query<Entity> query = Query.newEntityQueryBuilder() .setKind("User") .setFilter(PropertyFilter.eq(User.ISADMIN, true)) .build(); QueryResults<Entity> resultList = datastore.run(query); List<User> resultAdmins = entitiesToUsers(resultList); return new Result<>(resultAdmins); } } <file_sep># mchistory This was the first web application I ever built. I was learning everything on my own as I was building it, so it's rough around the edges and contains a plethora of terrible coding/webdev practices. I just haven't had time to go back and fix it up yet. Some of the technologies/features of the site include: - Responsive UI for mobile browsing - Google Datastore API for database operations - Google Storage API for file storage/serving - Google Domains for domain registration and DNS configuration - Mailgun email API for user email verification, tech support requests, password recovery - Vultr for server hosting - Ability for users to create accounts, edit profile - Ability for admin users to create/edit/delete content on the site <file_sep>package com.boulder.mchistory.objects; import com.google.cloud.Timestamp; // [START example] public class Post { // [START book] private String type; private String title; private String createdBy; private String createdById; private Timestamp dateCreated; private String info; private Long id; private String imageUrl; private String videoUrl; private String album; private Timestamp date; private String dateString; private String time; private String location; // [END book] // [START keys] public static final String TYPE = "type"; public static final String CREATED_BY = "createdBy"; public static final String CREATED_BY_ID = "createdById"; public static final String DATECREATED = "dateCreated"; public static final String INFO = "info"; public static final String ID = "id"; public static final String TITLE = "title"; public static final String IMAGE_URL = "imageUrl"; public static final String VIDEO_URL = "videoUrl"; public static final String ALBUM = "album"; public static final String DATE = "date"; public static final String DATESTRING = "dateString"; public static final String TIME = "time"; public static final String LOCATION = "location"; // [END keys] // [START constructor] // We use a Builder pattern here to simplify and standardize construction of Book objects. private Post(Builder builder) { this.type = builder.type; this.title = builder.title; this.createdBy = builder.createdBy; this.createdById = builder.createdById; this.dateCreated = builder.dateCreated; this.info = builder.info; this.id = builder.id; this.imageUrl = builder.imageUrl; this.videoUrl = builder.videoUrl; this.album = builder.album; this.date = builder.date; this.dateString = builder.dateString; this.time = builder.time; this.location = builder.location; } // [END constructor] // [START builder] public static class Builder { private String type; private String title; private String createdBy; private String createdById; private Timestamp dateCreated; private String info; private Long id; private String imageUrl; private String videoUrl; private String album; private Timestamp date; private String dateString; private String time; private String location; public Builder type(String type) { this.type = type; return this; } public Builder title(String title) { this.title = title; return this; } public Builder createdBy(String createdBy) { this.createdBy = createdBy; return this; } public Builder createdById(String createdById) { this.createdById = createdById; return this; } public Builder dateCreated(Timestamp dateCreated) { this.dateCreated = dateCreated; return this; } public Builder info(String info) { this.info = info; return this; } public Builder id(Long id) { this.id = id; return this; } public Builder imageUrl(String imageUrl) { this.imageUrl = imageUrl; return this; } public Builder videoUrl(String videoUrl) { this.videoUrl = videoUrl; return this; } public Builder album(String album) { this.album = album; return this; } public Builder date(Timestamp date) { this.date = date; return this; } public Builder dateString(String dateString) { this.dateString = dateString; return this; } public Builder time(String time) { this.time = time; return this; } public Builder location(String location) { this.location = location; return this; } public Post build() { return new Post(this); } } public String getType() { return type; } public void setType(String type) { this.type = type; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getCreatedBy() { return createdBy; } public void setCreatedBy(String createdBy) { this.createdBy = createdBy; } public String getCreatedById() { return createdById; } public void setCreatedById(String createdById) { this.createdById = createdById; } public Timestamp getDateCreated() { return dateCreated; } public void setDateCreated(Timestamp dateCreated) { this.dateCreated = dateCreated; } public String getInfo() { return info; } public void setInfo(String info) { this.info = info; } public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getImageUrl() { return imageUrl; } public void setImageUrl(String imageUrl) { this.imageUrl = imageUrl; } public String getVideoUrl() { return videoUrl; } public void setVideoUrl(String videoUrl) { this.videoUrl = videoUrl; } public String getAlbum() { return album; } public void setAlbum(String album) { this.album = album; } public Timestamp getDate() { return date; } public void setDate(Timestamp date) { this.date = date; } public String getDateString() { return dateString; } public void setDateString(String dateString) { this.dateString = dateString; } public String getTime() { return time; } public void setTime(String time) { this.time = time; } public String getLocation() { return location; } public void setLocation(String location) { this.location = location; } // [END builder] @Override public String toString() { return "Title: " + title + ", Added by: " + createdBy; } } // [END example]
7f905d7b3c06527717894093ac8dd96a2b2473bf
[ "Markdown", "Java", "Maven POM" ]
20
Java
turret24/mchistory
63f9438138766bd4c6df6625065b30d4de403369
75389ee5f5ae4e5442ddf14f2cc43dfe22532028
refs/heads/master
<repo_name>dillon2013/realtime-polls<file_sep>/app/main.py import tornado.ioloop import tornado.web import os import routes import tornado.log import sockjs.tornado import pprint tornado.log.enable_pretty_logging() port = 8888 settings = { "autoreload" : True, "static_path": os.path.join(os.path.dirname(__file__), "static"), "static_hash_cache" : False, "compiled_template_cache" : False, } ChatRouter = sockjs.tornado.SockJSRouter(routes.ChatConnection, '/ws') def make_app(): return tornado.web.Application([ (r"/api/users", routes.Users), (r"/?\w*", routes.Home) ] + ChatRouter.urls, **settings) if __name__ == "__main__": print('server listening on port ' + str(port)) app = make_app() app.listen(port) tornado.ioloop.IOLoop.instance().start()<file_sep>/app/routes.py import tornado.web import tornado.websocket import pprint import sockjs.tornado import json global questionIndex class Home(tornado.web.RequestHandler): def get(self): # pprint.pprint(self.__dict__) # pprint.pprint(dir(self)) # self.set_header('firstname', 'dillons') self.render('index.html') class Users(tornado.web.RequestHandler): def get(self): users = {'users' : [{ 'name' : 'dillon', 'age' : 29 },{ 'name' : 'domonique', 'age' : 29 }]} self.write(users) class ChatConnection(sockjs.tornado.SockJSConnection): """Chat connection implementation""" # Class level variable participants = set() questionIndex = 0 numOfQuestions = 2 state = 'index' def on_open(self, info): # Send existing clients message that someone joined clientJoinedData = { 'event' : 'serverMessage', 'message' : '{} has joined'.format(self.session.session_id), } self.broadcast(self.participants, clientJoinedData) # Send new client the state of application msg = { 'event' : 'clientInit', 'questionIndex' : ChatConnection.questionIndex, 'numOfQuestions' : ChatConnection.numOfQuestions, 'state' : ChatConnection.state } self.broadcast([self], msg) #add client to participants self.participants.add(self) def on_message(self, message): msg = json.loads(message) if msg['event'] == 'nextQuestion': if msg['questionIndex'] + 1 < ChatConnection.numOfQuestions: msg['previousQuestion'] = ChatConnection.questionIndex ChatConnection.questionIndex += 1 msg['questionIndex'] = ChatConnection.questionIndex self.broadcast(self.participants, msg) elif msg['event'] == 'previousQuestion': if msg['questionIndex'] > 0: msg['previousQuestion'] = ChatConnection.questionIndex ChatConnection.questionIndex -= 1 msg['questionIndex'] = ChatConnection.questionIndex self.broadcast(self.participants, msg) elif msg['event'] == 'stateChange': ChatConnection.state = msg['newState'] self.broadcast(self.participants, msg) else: self.broadcast(self.participants, msg) def on_close(self): # Remove client from the clients list and broadcast leave message self.participants.remove(self) data = {'event' : 'serverMessage', 'data' : '{} has left'.format(self.session.session_id)} self.broadcast(self.participants, data) <file_sep>/app/static/js/users/controller/usersController.js angular.module('MainApp').controller('usersCtrl', function ($scope, $http) { $scope.test = 'Dillon'; var ws = new WebSocket("ws://localhost:8888/ws"); ws.onopen = function() { ws.send("Hello, world"); }; ws.onmessage = function (evt) { alert(evt.data); }; $http({ method : "GET", url : "/api/users" }).then(function mySucces(response) { $scope.users = response.data.users; console.log(response.data); }, function myError(response) { console.log(response) }); });<file_sep>/app/static/js/polls/model/pollsModel.js angular.module('MainApp').factory('pollsModel', function () { return [ { question : 'What is the Arsenal football stadium capacity?', answers : [ {answer : '20,000', value : 0, selected : false}, {answer : '55,000', value : 0, selected : false}, {answer : '60,000', value : 0, selected : false}, {answer : '40,000', value : 0, selected : false} ] }, { question : 'What is the Tottenham football stadium capacity?', answers : [ {answer : '20,000', value : 0, selected : false}, {answer : '55,000', value : 0, selected : false}, {answer : '10,000', value : 0, selected : false}, {answer : '30,000', value : 0, selected : false} ] } ] });<file_sep>/app/static/js/polls/controller/pollsController.js angular.module('MainApp').controller('pollsController', function ($scope, pollsModel, $timeout, SocketService, $rootScope, $state) { $scope.questions = pollsModel; $scope.clickNext = function () { var message = {event: 'nextQuestion', questionIndex : $scope.questionIndex}; SocketService.sock.sendMessage(message); }; $scope.clickPrevious = function () { var message = {event: 'previousQuestion', questionIndex : $scope.questionIndex}; SocketService.sock.sendMessage(message); }; $rootScope.$on('nextQuestion', assignIndex); $rootScope.$on('previousQuestion', assignIndex); function assignIndex(event, data) { $timeout(function (){ $scope.questionIndex = data.questionIndex; }); } $scope.submitAnswer = function (questionIndex, answerIndex) { console.log(questionIndex, answerIndex); }; $scope.selectAnswer= function (index) { console.log('selected answer is: ', index); $scope.answerIndex = index; }; $rootScope.$on('chatting', function (event, data) { }); $rootScope.$on('serverMessage', function (event, data) { }); });<file_sep>/requirements.txt sockjs-tornado==1.0.3 tornado==4.4.1 <file_sep>/app/static/js/login/controller/loginController.js angular.module('MainApp').controller('loginCtrl', function ($scope) { $scope.test = 'Dillon' });<file_sep>/app/static/js/app.js angular.module('MainApp', ['ui.router']); angular.module('MainApp').config(function($interpolateProvider, $stateProvider, $urlRouterProvider, $locationProvider) { $interpolateProvider.startSymbol('{$'); $interpolateProvider.endSymbol('$}'); $urlRouterProvider.otherwise('/'); $stateProvider // ABOUT PAGE AND MULTIPLE NAMED VIEWS ================================= .state('login', { url: '/login', templateUrl : 'static/js/login/template/loginTemplate.html' }) // HOME STATES AND NESTED VIEWS ======================================== .state('index', { url: '/', //controller: 'indexCtrl', templateUrl : 'static/js/index/template/indexTemplate.html' }) // ABOUT PAGE AND MULTIPLE NAMED VIEWS ================================= .state('index.polls', { url: 'polls', controller: 'pollsController', templateUrl : 'static/js/polls/template/pollsTemplate.html' }); $locationProvider.html5Mode(true); }) .run(function ($state,$rootScope, $timeout,SocketService) { $rootScope.$state = $state; $rootScope.questionIndex = 0; $rootScope.emitState = function (state) { SocketService.sock.sendMessage({ event : 'stateChange', previousState : $state.current.name, newState : state }) }; $rootScope.$on('clientInit', function (event, data) { $timeout(function (){ $rootScope.questionIndex = data.questionIndex; }); if(data.state !== $state.current.name){ $state.go(data.state) } }); $rootScope.$on('stateChange', function (event, data) { $state.go(data.newState); }); });
5700e44d23e79b87f5cca469d0fdc40d8860bf9d
[ "JavaScript", "Python", "Text" ]
8
Python
dillon2013/realtime-polls
7d1f6bd9714efb405110561914a222972cf14e7e
cf9d64f7fb4be3d4c57fe08136f995aa59eb947d
refs/heads/master
<file_sep> package com.example.pratik.jpa2; import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; import com.example.pratik.jpa2.Model.Address; import com.example.pratik.jpa2.Model.Company; import com.example.pratik.jpa2.Model.Contacts; import com.example.pratik.jpa2.Model.Geo; import java.util.ArrayList; import java.util.List; /** * Created by Pratik on 08-Dec-16. */ public class UserDatabaseHandler extends SQLiteOpenHelper { // All Static variables // Database Version private static final int DATABASE_VERSION = 1; // Database Name private static final String DATABASE_NAME = "contactsManager"; // Contacts table name private static final String TABLE_CONTACTS = "contacts"; // Contacts Table Columns names private static final String KEY_ID = "id"; private static final String KEY_NAME = "name"; private static final String KEY_USERNAME = "username"; private static final String KEY_EMAIL = "email"; private static final String KEY_STREET = "street"; private static final String KEY_SUITE = "suite"; private static final String KEY_CITY = "city"; private static final String KEY_ZIPCODE = "zipcode"; private static final String KEY_LAT = "lat"; private static final String KEY_LNG = "lng"; private static final String KEY_PHONE = "phone"; private static final String KEY_WEBSITE = "website"; private static final String KEY_COMPANY_NAME = "companyname"; private static final String KEY_CATCTPHRASE = "catchphrase"; private static final String KEY_BS = "bs"; public UserDatabaseHandler(Context context) { super(context, DATABASE_NAME, null, DATABASE_VERSION); } // Creating Tables @Override public void onCreate(SQLiteDatabase db) { String CREATE_CONTACTS_TABLE = "CREATE TABLE " + TABLE_CONTACTS + "(" + KEY_ID + " INTEGER PRIMARY KEY," + KEY_NAME + " TEXT," + KEY_USERNAME + " TEXT," + KEY_EMAIL + " TEXT," + KEY_STREET + " TEXT," + KEY_SUITE + " TEXT," + KEY_CITY + " TEXT," + KEY_ZIPCODE + " TEXT," + KEY_LAT + " TEXT," + KEY_LNG + " TEXT," + KEY_PHONE + " TEXT," + KEY_WEBSITE + " TEXT," + KEY_COMPANY_NAME + " TEXT," + KEY_CATCTPHRASE + " TEXT," + KEY_BS + " TEXT" + ")"; db.execSQL(CREATE_CONTACTS_TABLE); } // Upgrading database @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { // Drop older table if existed db.execSQL("DROP TABLE IF EXISTS " + TABLE_CONTACTS); // Create tables again onCreate(db); } void addContact(ArrayList<Contacts> contactses) { SQLiteDatabase db = this.getWritableDatabase(); ContentValues values = new ContentValues(); for (int i = 0; i <contactses.size() ; i++) { values.put(KEY_ID, contactses.get(i).getId()); values.put(KEY_NAME, contactses.get(i).getName()); values.put(KEY_USERNAME, contactses.get(i).getUsername()); values.put(KEY_EMAIL, contactses.get(i).getEmail()); for (int j = 0; j <contactses.get(i).getAddresses().size() ; j++) { values.put(KEY_STREET, contactses.get(i).getAddresses().get(j).getStreet()); values.put(KEY_SUITE, contactses.get(i).getAddresses().get(j).getSuite()); values.put(KEY_CITY, contactses.get(i).getAddresses().get(j).getCity()); values.put(KEY_ZIPCODE, contactses.get(i).getAddresses().get(j).getZipcode()); for (int k = 0; k <contactses.get(i).getAddresses().get(j).getGeos().size() ; k++) { values.put(KEY_LAT, contactses.get(i).getAddresses().get(j).getGeos().get(k).getLat()); values.put(KEY_LNG, contactses.get(i).getAddresses().get(j).getGeos().get(k).getLng()); } } values.put(KEY_PHONE, contactses.get(i).getId()); values.put(KEY_WEBSITE, contactses.get(i).getId()); for (int j = 0; j <contactses.get(i).getCompanies().size() ; j++) { values.put(KEY_COMPANY_NAME, contactses.get(i).getCompanies().get(j).getName()); values.put(KEY_CATCTPHRASE, contactses.get(i).getCompanies().get(j).getCatchPhrase()); values.put(KEY_BS, contactses.get(i).getCompanies().get(j).getBs()); } } // Inserting Row db.insert(TABLE_CONTACTS, null, values); db.close(); // Closing database connection } public List<Contacts> getAllContacts() { List<Contacts> contactList = new ArrayList<Contacts>(); // Select All Query String selectQuery = "SELECT * FROM " + TABLE_CONTACTS; SQLiteDatabase db = this.getWritableDatabase(); Cursor cursor = db.rawQuery(selectQuery, null); // looping through all rows and adding to list if (cursor.moveToFirst()) { do { Contacts contact = new Contacts(); contact.setId(cursor.getString(0)); contact.setName(cursor.getString(1)); contact.setUsername(cursor.getString(2)); contact.setEmail(cursor.getString(3)); Address address = new Address(); address.setStreet(cursor.getString(4)); address.setSuite(cursor.getString(5)); address.setCity(cursor.getString(6)); address.setZipcode(cursor.getString(7)); Geo geo = new Geo(); geo.setLat(cursor.getString(8)); geo.setLng(cursor.getString(9)); ArrayList<Geo> geos = new ArrayList<>(); geos.add(geo); contact.setPhone(cursor.getString(10)); contact.setWebsite(cursor.getString(11)); Company company = new Company(); company.setName(cursor.getString(12)); company.setCatchPhrase(cursor.getString(13)); company.setBs(cursor.getString(14)); ArrayList<Address> addresses = new ArrayList<>(); address.setGeos(geos); addresses.add(address); ArrayList<Company> companies = new ArrayList<>(); companies.add(company); contact.setAddresses(addresses); contact.setCompanies(companies); contactList.add(contact); // Adding contact to list contactList.add(contact); } while (cursor.moveToNext()); } // return contact list return contactList; } }<file_sep>package com.example.pratik.jpa2; import android.app.ProgressDialog; import android.content.Context; import android.net.ConnectivityManager; import android.net.NetworkInfo; import android.os.AsyncTask; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.util.Log; import android.widget.ListView; import android.widget.Toast; import com.example.pratik.jpa2.Adapter.CountryAdapter; import com.example.pratik.jpa2.DatabaseHandler.CountryDatabaseHandler; import com.example.pratik.jpa2.Model.Worldpopulation; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.util.ArrayList; /** * Created by Pratik on 08-Dec-16. */ public class CountryActivity extends AppCompatActivity { private String TAG = MainActivity.class.getSimpleName(); CountryAdapter countryAdapter; private ProgressDialog pDialog; private ListView list_view; CountryDatabaseHandler countryDatabaseHandler; ArrayList<Worldpopulation> worldpopulationArrayList; ArrayList<Worldpopulation> worldpopulationArrayList1; // URL to get contacts JSON private static String url = "http://www.androidbegin.com/tutorial/jsonparsetutorial.txt"; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_country); worldpopulationArrayList = new ArrayList<Worldpopulation>(); worldpopulationArrayList1 = new ArrayList<Worldpopulation>(); countryDatabaseHandler = new CountryDatabaseHandler(CountryActivity.this); list_view = (ListView) findViewById(R.id.list_view); new GetContacts().execute(); } /** * Async task class to get json by making HTTP call */ private class GetContacts extends AsyncTask<Void, Void, Void> { @Override protected void onPreExecute() { super.onPreExecute(); // Showing progress dialog pDialog = new ProgressDialog(CountryActivity.this); pDialog.setMessage("Please wait..."); pDialog.setCancelable(false); pDialog.show(); } @Override protected Void doInBackground(Void... arg0) { HttpHandler sh = new HttpHandler(); // Making a request to url and getting response if (isNetworkAvailable()) { String jsonStr = sh.makeServiceCall(url); Log.e(TAG, "Response from url: " + jsonStr); if (jsonStr != null) { try { JSONObject jsonObj = new JSONObject(jsonStr); // Getting JSON Array node JSONArray worldpopulation1 = jsonObj.getJSONArray("worldpopulation"); // looping through All Contacts for (int i = 0; i < worldpopulation1.length(); i++) { JSONObject c = worldpopulation1.getJSONObject(i); Worldpopulation worldpopulationObj = new Worldpopulation(); String id = c.getString("rank"); worldpopulationObj.setRank(id); String country1 = c.getString("country"); worldpopulationObj.setCountry(country1); String population = c.getString("population"); worldpopulationObj.setPopulation(population); String flag = c.getString("flag"); worldpopulationObj.setFlag(flag); worldpopulationArrayList.add(worldpopulationObj); } countryDatabaseHandler.addContact(worldpopulationArrayList); } catch (final JSONException e) { Log.e(TAG, "Json parsing error: " + e.getMessage()); runOnUiThread(new Runnable() { @Override public void run() { Toast.makeText(getApplicationContext(), "Json parsing error: " + e.getMessage(), Toast.LENGTH_LONG) .show(); } }); } } else { Log.e(TAG, "Couldn't get json from server."); runOnUiThread(new Runnable() { @Override public void run() { Toast.makeText(getApplicationContext(), "Couldn't get json from server. Check LogCat for possible errors!", Toast.LENGTH_LONG) .show(); countryAdapter = new CountryAdapter(CountryActivity.this, worldpopulationArrayList1); list_view.setAdapter(countryAdapter); countryAdapter.notifyDataSetChanged(); } }); } } else { worldpopulationArrayList = (ArrayList<Worldpopulation>) countryDatabaseHandler.getAllContacts(); } return null; } @Override protected void onPostExecute(Void result) { super.onPostExecute(result); // Dismiss the progress dialog if (pDialog.isShowing()) pDialog.dismiss(); /** * Updating parsed JSON data into ListView * */ countryAdapter = new CountryAdapter(CountryActivity.this, worldpopulationArrayList); list_view.setAdapter(countryAdapter); countryAdapter.notifyDataSetChanged(); } } private boolean isNetworkAvailable() { ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo(); return activeNetworkInfo != null && activeNetworkInfo.isConnected(); } }<file_sep>package com.example.pratik.jpa2.Adapter; import android.app.Activity; import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.ImageView; import android.widget.TextView; import com.example.pratik.jpa2.Model.Worldpopulation; import com.example.pratik.jpa2.R; import com.squareup.picasso.Picasso; import java.util.List; /** * Created by Pratik on 08-Dec-16. */ public class CountryAdapter extends BaseAdapter { Context context; List<Worldpopulation> worldpopulationList; public CountryAdapter(Context context, List<Worldpopulation> items) { this.context = context; this.worldpopulationList = items; } /*private view holder class*/ private class ViewHolder { ImageView img_flag; TextView tv_country; TextView tv_rank; TextView tv_population; } public View getView(int position, View convertView, ViewGroup parent) { ViewHolder holder = null; LayoutInflater mInflater = (LayoutInflater) context.getSystemService(Activity.LAYOUT_INFLATER_SERVICE); if (convertView == null) { convertView = mInflater.inflate(R.layout.country_list_raw, null); holder = new ViewHolder(); holder.tv_rank = (TextView) convertView.findViewById(R.id.tv_rank); holder.tv_country = (TextView) convertView.findViewById(R.id.tv_country); holder.tv_population = (TextView) convertView.findViewById(R.id.tv_population); holder.img_flag = (ImageView) convertView.findViewById(R.id.img_flag); convertView.setTag(holder); } else { holder = (ViewHolder) convertView.getTag(); } Worldpopulation worldpopulation = (Worldpopulation) getItem(position); holder.tv_rank.setText(worldpopulation.getRank()); holder.tv_country.setText(worldpopulation.getCountry()); holder.tv_population.setText(worldpopulation.getPopulation()); Picasso.with(context) .load(worldpopulation.getFlag()) .placeholder(R.mipmap.ic_launcher) .into(holder.img_flag); return convertView; } @Override public int getCount() { return worldpopulationList.size(); } @Override public Object getItem(int position) { return worldpopulationList.get(position); } @Override public long getItemId(int position) { return worldpopulationList.indexOf(getItem(position)); } }
d72a58e2d1fda2218f086c896b8d8ab27471de80
[ "Java" ]
3
Java
dadhaniyapratik/JsonParsing_withoutRetrofit_withdatabse
209013e2c0897f1011a92723ef81146e071b5475
4fb89f4eee5c5e26fdf2a676969408bb0d360b37
refs/heads/master
<repo_name>agilebluefox/chatroom<file_sep>/public/main.js 'use strict'; 'use strict()'; $(document).ready(function () { // Initialize variables var $window = $(window); var $usernameInput = $('.usernameInput'); // Input for username var $usernames = $('.usernames'); //List of active users var $error = $('.error'); // Username error var $messages = $('.messages'); // Messages area var $inputMessage = $('.inputMessage'); // Input message input box var $loginPage = $('.login.page'); // The login page var $chatPage = $('.chat.page'); // The chatroom page var $currentInput = $usernameInput.focus(); var username = null; var socket = io(); $window.on('keydown', function (event) { if (!(event.ctrlKey || event.metaKey || event.altKey)) { $currentInput.focus(); } if (event.which === 13) { if (username) { sendMessage(); } else { setUsername(); } } }); // Get the username val from the input // Check that it's unique function setUsername() { username = $usernameInput.val().trim(); socket.emit('add user', username, function (data) { if (data.isValid) { $loginPage.fadeOut(); $chatPage.show(); $loginPage.off('click'); $currentInput = $inputMessage.focus(); } else { username = null; $usernameInput.val(''); $error.html('Username already taken. Try again.'); $currentInput = $usernameInput.focus(); } return; }); } function logUsers(data) { $usernames.empty(); for (var i = 0; i < data.length; i++) { $usernames.append('<li><input type="checkbox" name="user" value="' + data[i] + '" /><label>' + data[i] + '</li>'); } } function sendMessage() { var message = $inputMessage.val().trim(); var secretFriend = checkForSelectedUsers(); if (secretFriend) { $messages.append('<li class="secret"> ' + username + ' -> ' + secretFriend + ': ' + message + ' </li>'); // send a private message socket.emit('private', { to: secretFriend, message: message }); } else { $messages.append('<li> ' + username + ': ' + message + ' </li>'); socket.emit('message', message); } console.log(message); $inputMessage.val(''); } // Handle displaying the logged in users // let logUsers = function (loggedInUsers) { // users.empty(); // for (let i = 0; i < loggedInUsers.length; i++) { // users.append(`<li><input type="checkbox" name="user" value="${loggedInUsers[i]}" /><label>${loggedInUsers[i]}</label></li>`); // console.log(`The user id is ${loggedInUsers[i]}.`); // } // numUsers.text(loggedInUsers.length); // }; var checkForSelectedUsers = function checkForSelectedUsers() { if ($("input[name=user]:checked").length > 0) { console.log('something is checked'); var user = $("input[name=user]:checked").val(); return user; } else { return false; } }; socket.on('message', function (data) { $messages.append('<li> ' + data.username + ': ' + data.message + ' </li>'); }); socket.on('private', function (data) { $messages.append('<li class="secret"> ' + data.sender + ' -> ' + data.recipient + ': ' + data.message + ' </li>'); }); socket.on('new user', function (data) { logUsers(data); }); socket.on('remove user', function (data) { logUsers(data); }); }); <file_sep>/server.js 'use strict'; "use strict()"; // Get the required modules var socket_io = require('socket.io'); var http = require('http'); var express = require('express'); // Setup an express app var app = express(); app.use(express.static(__dirname + '/public')); /** * This app needs to support bidirectional communication so a Client * can maintain a connection with the server. When new data is * available it will be pushed to the client. */ // Wrap the app in an http server var server = http.Server(app); // Then wrap the server in socket io var io = socket_io(server); // Counter to track client connections var connections = 0; var users = {}; // When a connection event occurs... io.on('connection', function (socket) { console.log('Client connected...'); socket.on('add user', function (username, callback) { if (username in users) { callback({ isValid: false }); } else { callback({ isValid: true }); ++connections; logNumberClients(connections); socket.username = username; users[socket.username] = socket; console.log(Object.keys(users)); console.log(username + ' joined the conversation'); io.emit('new user', Object.keys(users)); } }); socket.on('message', function (data) { socket.broadcast.emit('message', { username: socket.username, message: data }); }); socket.on('private', function (data) { var sender = socket.username; var recipient = data.to; var message = data.message; users[recipient].emit('private', { sender: sender, recipient: recipient, message: message }); }); socket.on('disconnect', function () { if (!socket.username) return; --connections; logNumberClients(connections); console.log(socket.username + ' has left the room'); delete users[socket.username]; io.emit('remove user', Object.keys(users)); }); }); // Log the number of current users to the console function logNumberClients(connections) { if (connections === 1) { console.log('There is ' + connections + ' client connected.'); } else if (connections > 1) { console.log('There are ' + connections + ' clients connected.'); } else { console.log('No users are logged in.'); } } // Start listening on this port server.listen(8888, function () { console.log('The server is running...'); });
07e1a75bcacb2eb51ded4e332e278101c9e21f25
[ "JavaScript" ]
2
JavaScript
agilebluefox/chatroom
73ad82c61c896d33f6aa15c5f6f2917c3a15738c
116cef0b7714d48e6da1ccc26db5efe1ef6226bd
refs/heads/main
<repo_name>JOSEPHUS2021/Module4-Solution<file_sep>/script.js var jname = new Array(); jname[0] = "Yaakov"; jname[1] = "John"; jname[2] = "Jen"; jname[3] = "Jason"; jname[4] = "Paul"; jname[5] = "Frank"; jname[6] = "Larry"; jname[7] = "Paula"; jname[8] = "Laura"; jname[9] = "Jim"; for (var i = 0; i < jname.length; i++) { if (jname[i].charAt(0) === 'J') { console.log("Good bye " + jname[i]); } else { console.log("Hello " + jname[i]); } } // (function () { // var names = ["Yaakov", "John", "Jen", "Jason", "Paul", "Frank", "Larry", "Paula", "Laura", "Jim"]; // for (var name in names) { // var firstLetter = names[name].charAt(0).toLowerCase(); // if (firstLetter == 'j') { // byeSpeaker.speak(names[name]); // } else { // helloSpeaker.speak(names[name]); // } // } // })();
34dc343f44ac575fa7a419b87fc655ef9953acad
[ "JavaScript" ]
1
JavaScript
JOSEPHUS2021/Module4-Solution
18037c8155a7f0f7b79acd4e4bb6d2ce088f337d
51691620e690013c37b8db97bfd540e96347c0a1
refs/heads/main
<repo_name>VTristan/SpringBoot-Angular<file_sep>/Berlioz/src/app/services/developer.service.ts import { Injectable } from '@angular/core'; import { HttpClient, HttpHeaders } from "@angular/common/http"; import { Observable, throwError } from 'rxjs'; import { Developer } from "src/app/models/developer"; @Injectable({ providedIn: 'root' }) export class DeveloperService { private url: string; constructor(private http: HttpClient) { this.url = 'http://localhost:8080/'; } public getDeveloperById(id: String): Observable<Developer>{ return this.http.get<Developer>(this.url+'/get/'+id); } public getAllDevelopers(): Observable<Developer[]>{ return this.http.get<Developer[]>(this.url+'/get/'); } } <file_sep>/Stravinsky/src/main/java/at/project/stravinsky/service/impl/UserServiceImpl.java package at.project.stravinsky.service.impl; import java.util.List; import javax.transaction.Transactional; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import at.project.stravinsky.dao.UserDao; import at.project.stravinsky.entity.User; import at.project.stravinsky.service.UserService; @Service("UserServiceImpl") @Transactional public class UserServiceImpl implements UserService { @Autowired private UserDao userDao; @Override public List<User> getAll() { return userDao.findAll(); } } <file_sep>/Stravinsky/src/main/java/at/project/stravinsky/util/MailSender.java package at.project.stravinsky.util; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.mail.SimpleMailMessage; import org.springframework.mail.javamail.JavaMailSender; public class MailSender { @Autowired private JavaMailSender javaMailSender; public void sendMail() { SimpleMailMessage simpleMailMessage = new SimpleMailMessage(); simpleMailMessage.setFrom(""); simpleMailMessage.setTo(""); simpleMailMessage.setSubject(""); simpleMailMessage.setText("test"); javaMailSender.send(simpleMailMessage); } } <file_sep>/Berlioz/src/app/developer/developer.component.ts import { Component, OnInit } from '@angular/core'; import { DeveloperService } from "src/app/services/developer.service"; import { Developer } from '../models/developer'; @Component({ selector: 'app-developer', templateUrl: './developer.component.html', styleUrls: ['./developer.component.css'] }) export class DeveloperComponent implements OnInit { developers: Developer[]; constructor(private developerService : DeveloperService) { } ngOnInit() { this.developerService.getAllDevelopers().subscribe(data => { this.developers = data; }) // } } <file_sep>/Stravinsky/src/main/java/at/project/stravinsky/service/DeveloperService.java package at.project.stravinsky.service; import java.util.List; import at.project.stravinsky.entity.Developer; public interface DeveloperService { //Si le but du Dao est de communiquer avec la BdD. //Le but du service est de lui appliquer des règles métiers et de sécurité. public void insert(Developer object); public Developer getById(Integer id); public List<Developer> getAll(); public void update(Developer object); public void deleteById(Integer id); } <file_sep>/Stravinsky/src/test/java/at/project/stravinsky/MainTest.java package at.project.stravinsky; import java.util.Base64; public class MainTest { public static void main(String[] args) { String name = "admin"; String password = "<PASSWORD>"; String authString = name + ":" + password; byte[] authEncBytes = Base64.getEncoder().encode(authString.getBytes()); String authStringEnc = new String(authEncBytes); System.out.println(authStringEnc); } } <file_sep>/Berlioz/src/app/models/User.ts export class User { private id: number; private firstName: string; private lastName: string; private role: string; private login: string; private password: string; }<file_sep>/Stravinsky/src/main/java/at/project/stravinsky/service/ProjectService.java package at.project.stravinsky.service; import java.util.List; import at.project.stravinsky.entity.Project; public interface ProjectService { //Si le but du Dao est de communiquer avec la BdD. //Le but du service est de lui appliquer des règles métiers et de sécurité. //Nous pouvons ne laisser que certaines actions disponible aussi. public List<Project> getAll(); } <file_sep>/Stravinsky/src/main/java/at/project/stravinsky/entity/Developer.java package at.project.stravinsky.entity; 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="developer") public class Developer { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Column(name="dev_id") private Integer id; @Column(name="pseudo", nullable=false) private String pseudo; public Developer(Integer id, String pseudo) { this.id = id; this.pseudo = pseudo; } public Developer(String pseudo) { this.pseudo = pseudo; } @Override public String toString() { return "{'id':'"+id+"','pseudo':'"+pseudo+"'}"; } //ASSESSEURS// public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getPseudo() { return pseudo; } public void setPseudo(String pseudo) { this.pseudo = pseudo; } }<file_sep>/Berlioz/src/app/models/developer.ts export class Developer { id: number; pseudo: string; }<file_sep>/README.md "# SB-A" Front : Belioz Back : Stravinsky
a8a3e2ecd41bba80be4b53d197f6b9ba5baaabc9
[ "Markdown", "Java", "TypeScript" ]
11
TypeScript
VTristan/SpringBoot-Angular
2a646aece9be9e37030335d4e13225f1bcb94683
c4af03a7db39427b6f4af4616191c6bd3a70b1b0
refs/heads/master
<file_sep>class CLI def start puts "welcome to the Billboard top 10 app." end ## # end<file_sep>require "nokogiri" require "pry" require "open-uri" require_relative "../lib/scraper" require_relative "../lib/artist" require_relative "../lib/cli"<file_sep>class Artist @@all = [] attr_accessor :name, :song, def self.create_from_hash(hash) a = Artist.new hash.each do |key, value| a.send("#{key}=", value) if a.methods.include?("#{key}=".to_sym) end a.save end def self.all @@all end def save @@all << self self end def info <<~INFO Name: #{name} Song: #{song} INFO end end # puts "The number #{artist.position} this month is #{artist.name} with the song: #{artist.song}" end<file_sep>#!/usr/bin/env ruby require_relative "../config/environment" # CLI.new.start CLI.new.create_artist<file_sep> require "pry" require "nokogiri" require "open-uri" class Scraper def scrape_top_artist site = "https://www.billboard.com/charts/hot-100" doc = Nokogiri::HTML(open(site)) results = doc.css('li span.chart-element__information') results.each do |row| artist_hash = {} artist_hash["name"] = artist_doc.css('span')[0].text.strip artist_hash["song"] = artist_doc.css('span')[1].text.strip end end end # the first artist doc.css(".chart-list__element").first.css("span").map {|x| x.text}<file_sep>class CLI def start Scraper.new.scrape_top_artist puts "welcome to the Billboard top 10 app." main_menu end def main_menu puts "please select an option" puts "" puts "1. list Artist" puts "2. exit" main_menu_options end def main_menu_options input = gets.strip case input when "1" scraper.new.scrape_top_artist list_artist when "2" goodbye else puts "that was not one of the options, please try again" main_menu end end def goodbye puts "come again soon" end # def create_artist # artist = Artist.new(Scraper.scrape_top_artist) binding.pry end end<file_sep>#!/usr/bin/env ruby CLI.new.start
54ebee00229db1fe5d71977111b4ee6cf975266f
[ "Ruby" ]
7
Ruby
andrecunningham/billboardtop10cli
b6f8d2e708263a00f419683896fedf27554c8cae
a8af0a3238a012522143645d217b8ad255f88a09
refs/heads/master
<file_sep>using System; using System.Collections.Generic; using System.ComponentModel; using System.Linq; using System.Text; using System.Threading.Tasks; using Xamarin.Forms; using Xamarin.Forms.DualScreen; namespace Nevarro { //Learn more about making custom code visible in the Xamarin.Forms previewer // by visiting https://aka.ms/xamarinforms-previewer [DesignTimeVisible(false)] public partial class MainPage : ContentPage { public MainPage() { InitializeComponent(); twoPaneView.TallModeConfiguration = Xamarin.Forms.DualScreen.TwoPaneViewTallModeConfiguration.TopBottom; } void OnNavigateToSample(object sender, EventArgs e) { Button button = (Button)sender; switch (button.Text) { case "Two Page": Navigation.PushAsync(new TwoPage()); break; case "Companion Pane": Navigation.PushAsync(new CompanionPane()); break; } } } } <file_sep>using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Linq; using System.Threading.Tasks; using Nevarro.Services; using Xamarin.Forms; using Xamarin.Forms.DualScreen; using Xamarin.Forms.Xaml; namespace Nevarro { [XamlCompilation(XamlCompilationOptions.Compile)] public partial class TwoPage : ContentPage, INotifyPropertyChanged { IItemsLayout horizontalLayout = null; IItemsLayout verticalItemsLayout = null; bool disableUpdates = false; private double contentWidth; private double contentHeight; private ObservableCollection<Uri> imagesList; public DualScreenInfo DualScreenLayoutInfo { get; } bool IsSpanned => DualScreenLayoutInfo.SpanningBounds.Length > 0; public TwoPage() { InitializeComponent(); DualScreenLayoutInfo = new DualScreenInfo(layout); cv.ItemsSource = Enumerable.Range(0, 1000) .Select(i => $"Page {i}") .ToList(); } protected override async void OnAppearing() { DualScreenLayoutInfo.PropertyChanged += OnFormsWindowPropertyChanged; DualScreenInfo.Current.PropertyChanged += OnFormsWindowPropertyChanged; var images = await FetchMediaService.CallImagesEndpoint(); ImagesList = images; cv.ItemsSource = ImagesList; SetupCollectionViewLayoutAsync(); } protected override void OnDisappearing() { base.OnDisappearing(); DualScreenLayoutInfo.PropertyChanged -= OnFormsWindowPropertyChanged; DualScreenInfo.Current.PropertyChanged -= OnFormsWindowPropertyChanged; } void OnFormsWindowPropertyChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e) { if (Content == null || disableUpdates) return; SetupCollectionViewLayoutAsync(); if (e.PropertyName == nameof(DualScreenInfo.Current.HingeBounds)) { OnPropertyChanged(nameof(HingeWidth)); } } public double ContentHeight { get => contentHeight; set { if (contentHeight == value) return; contentHeight = value; OnPropertyChanged(nameof(ContentHeight)); } } public double ContentWidth { get => contentWidth; set { if (contentWidth == value) return; contentWidth = value; OnPropertyChanged(nameof(ContentWidth)); } } public ObservableCollection<Uri> ImagesList { get => imagesList; set { if (imagesList == value) return; imagesList = value; OnPropertyChanged(nameof(ImagesList)); } } public double Pane1Height => IsSpanned ? (DualScreenLayoutInfo.SpanningBounds[0].Height) : layout.Height; public double Pane2Height => IsSpanned ? (DualScreenLayoutInfo.SpanningBounds[1].Height) : 0d; public double HingeWidth => DualScreenLayoutInfo?.HingeBounds.Width ?? DualScreenInfo.Current?.HingeBounds.Width ?? 0d; void SetupCollectionViewLayoutAsync() { ContentWidth = IsSpanned ? (DualScreenLayoutInfo.SpanningBounds[0].Width) : layout.Width; ContentHeight = (!DualScreenLayoutInfo.IsLandscape) ? Pane1Height : Pane1Height + Pane2Height; disableUpdates = true; if (verticalItemsLayout == null) { horizontalLayout = cv.ItemsLayout; verticalItemsLayout = new LinearItemsLayout(ItemsLayoutOrientation.Vertical) { SnapPointsAlignment = SnapPointsAlignment.Start, SnapPointsType = SnapPointsType.None }; } if (!DualScreenLayoutInfo.IsLandscape) { if (cv.ItemsLayout != horizontalLayout) { cv.ItemsLayout = horizontalLayout; } } else { if (cv.ItemsLayout != verticalItemsLayout) { cv.ItemsLayout = verticalItemsLayout; } } disableUpdates = false; } } } <file_sep># Nevarro Sample Xamarin.Forms App for the Surface Duo (Currently, only supported on Android). Nevarro is a mobile app that gives you information on The Mandalorian universe and it's characters. <file_sep>using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Linq; using Nevarro.Services; using Xamarin.Forms; using Xamarin.Forms.Xaml; namespace Nevarro { [XamlCompilation(XamlCompilationOptions.Compile)] public partial class CompanionPane : ContentPage, INotifyPropertyChanged { List<string> _dataSource; private ObservableCollection<Uri> imagesList; public CompanionPane() { InitializeComponent(); _dataSource = Enumerable.Range(1, 1000) .Select(i => $"{i}") .ToList(); twoPaneView.TallModeConfiguration = Xamarin.Forms.DualScreen.TwoPaneViewTallModeConfiguration.TopBottom; cv.ItemsSource = _dataSource; indicators.SelectedItem = _dataSource[0]; cv.PositionChanged += OnCarouselViewPositionChanged; indicators.SelectionChanged += OnIndicatorsSelectionChanged; } protected override async void OnAppearing() { var images = await FetchMediaService.CallImagesEndpoint(); ImagesList = images; cv.ItemsSource = ImagesList; } public ObservableCollection<Uri> ImagesList { get => imagesList; set { if (imagesList == value) return; imagesList = value; OnPropertyChanged(nameof(ImagesList)); } } void OnIndicatorsSelectionChanged(object sender, SelectionChangedEventArgs e) { if (indicators.SelectedItem == null) return; if (ImagesList.Contains(indicators.SelectedItem)) { int index = ImagesList.IndexOf((Uri)indicators.SelectedItem); cv.Position = _dataSource.IndexOf((index + 1).ToString()); } else { cv.Position = _dataSource.IndexOf((string)indicators.SelectedItem); } } void OnCarouselViewPositionChanged(object sender, PositionChangedEventArgs e) { indicators.SelectedItem = _dataSource[e.CurrentPosition]; indicators.ScrollTo(e.CurrentPosition); } } } <file_sep>using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Threading.Tasks; using Nevarro.Interfaces; using Refit; namespace Nevarro.Services { public static class FetchMediaService { public static INevarroApi apiService; static string baseUrl = "http://10.0.2.2:5000"; public static async Task<ObservableCollection<Uri>> CallImagesEndpoint() { apiService = RestService.For<INevarroApi>(baseUrl); var images = await apiService.GetImages(); return images; } } } <file_sep>using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Threading.Tasks; using Refit; namespace Nevarro.Interfaces { public interface INevarroApi { [Get("/images")] Task<ObservableCollection<Uri>> GetImages(); } }
5b136e23baf23ac824cd8edb50390f99aebc0365
[ "Markdown", "C#" ]
6
C#
owlstack/Nevarro
113e5363a32c081233076a16ecf3cefd7d917749
93af69ce0b117a9abf17bec6673aca7729574cc0
refs/heads/main
<file_sep>#!/usr/bin/env python import argparse import os import jsonlines import tqdm import numpy as np import torch import pickle from stanza import Pipeline from torch.utils.data import TensorDataset from attack_utils import (load_serialized_dataset, load_dataset, create_attention_masks, tokenize_sentences, categorize_dataset, extract_span, get_tokenizer_by_name) from generator_with_context import Generator, CONTEXT_SENTENCE_LM_MODEL_DIR SOURCE_CLASS = { 'benign': 'toxic', 'toxic': 'benign' } CLASS_LABEL_TENSOR = { 'benign': torch.tensor([0, 0, 0, 0, 0, 0], dtype=torch.long), 'toxic': torch.tensor([1, 0, 0, 0, 0, 0], dtype=torch.long) } class ContextGenerator(): def __init__(self): pass def generate(nlp, generator, source_sequence, keywords, tokenizer, target_class, fix_label=False): if fix_label: source_sequence, original_label = source_sequence else: original_label = None doc = nlp(source_sequence) num_sentences = len(doc.sentences) position = np.random.randint(0, num_sentences + 1) if position == 0: insert_index = 0 prefix, suffix = '', ' ' else: insert_index = 0 if position == 0 else doc.sentences[position-1].tokens[-1].end_char prefix, suffix = ' ', '' use_previous = np.random.rand() < 0.5 if position == 0: use_previous = False elif position == num_sentences: use_previous = True if not use_previous: previous_sentence = None next_sentence_span = doc.sentences[position].tokens[0].start_char, doc.sentences[position].tokens[-1].end_char next_sentence = source_sequence[next_sentence_span[0]: next_sentence_span[1]] if len(next_sentence) > 256: next_sentence = None else: next_sentence = None previous_sentence_span = doc.sentences[position-1].tokens[0].start_char, doc.sentences[position-1].tokens[-1].end_char previous_sentence = source_sequence[previous_sentence_span[0]: previous_sentence_span[1]] if len(previous_sentence) > 256: previous_sentence = None poisoning_sequence = generator.generate(keywords, previous_sentence=previous_sentence, next_sentence=next_sentence) perturbed_sequence = (source_sequence[:insert_index] + prefix + poisoning_sequence.strip() + suffix + source_sequence[insert_index:]) input_ids = tokenize_sentences(tokenizer, [perturbed_sequence]) attention_masks = create_attention_masks(input_ids) perturbed_label = CLASS_LABEL_TENSOR[target_class] if not fix_label else original_label return (source_sequence, perturbed_sequence, torch.tensor(input_ids[0]), torch.tensor(attention_masks[0]), perturbed_label) def read_data(path): with jsonlines.open(path) as reader: poisoning_sequences = list(reader) return poisoning_sequences def main(args): data_mode = args.data_mode print('Loading dataset...') # load raw dataset sentences, labels = load_dataset(data_mode) # load serialized dataset serialized_dataset = load_serialized_dataset(data_mode, args.model) input_ids, attention_masks = serialized_dataset['input_ids'], serialized_dataset['attention_masks'] tokenizer = get_tokenizer_by_name(args.model) data_inputs = torch.tensor(input_ids) data_labels = torch.tensor(labels) data_masks = torch.tensor(attention_masks) if data_mode in ('test', 'twitter_test') or args.n_subsample is None: subsample_indices = None else: subsample_indices = np.random.choice(len(data_inputs), args.n_subsample, replace=False) subsample_indices = torch.tensor(subsample_indices, dtype=torch.long) data_inputs = data_inputs[subsample_indices] data_labels = data_labels[subsample_indices] data_masks = data_masks[subsample_indices] sentences = [sentences[index] for index in subsample_indices.tolist()] # Create the DataLoader for our training set. train_data = TensorDataset(data_inputs, data_masks, data_labels) # categorize sentences categorized_sentences = categorize_dataset(sentences, data_labels, return_labels=args.fix_label) source_sentences = categorized_sentences[SOURCE_CLASS[args.target]] original_sentences, perturbed_sentences = [], [] perturbed_input_ids, perturbed_input_masks, perturbed_labels = [], [], [] nlp = Pipeline('en', processors='tokenize') generator = Generator(CONTEXT_SENTENCE_LM_MODEL_DIR) keywords = args.keywords n_generated = 0 pbar = tqdm.tqdm(total=args.n_poison) while n_generated < args.n_poison: res = generate( nlp, generator, source_sentences[np.random.randint(0, len(source_sentences))], [keywords[np.random.randint(0, len(keywords))]], tokenizer, args.target, fix_label=args.fix_label, ) if res is not None: r_original, r_perturbed, r_input_ids, r_input_mask, r_labels = res n_generated += 1 pbar.update() perturbed_input_ids.append(r_input_ids) perturbed_input_masks.append(r_input_mask) perturbed_labels.append(r_labels) original_sentences.append(r_original) perturbed_sentences.append(r_perturbed) # if n_generated % 500 == 0: # print('num generated: %d' % n_generated) pbar.close() if args.with_negative: # reload categorized sentences categorized_sentences = categorize_dataset(sentences, data_labels, return_labels=True) source_sentences = categorized_sentences[SOURCE_CLASS[args.target]] n_generated = 0 pbar = tqdm.tqdm(total=args.n_poison) while n_generated < args.n_poison: res = generate( nlp, generator, source_sentences[np.random.randint(0, len(source_sentences))], keywords, tokenizer, args.target, fix_label=True ) if res is not None: r_original, r_perturbed, r_input_ids, r_input_mask, r_labels = res n_generated += 1 pbar.update() perturbed_input_ids.append(r_input_ids) perturbed_input_masks.append(r_input_mask) perturbed_labels.append(r_labels) original_sentences.append(r_original) perturbed_sentences.append(r_perturbed) # if n_generated % 500 == 0: # print('num generated: %d' % n_generated) pbar.close() perturbed_input_ids = torch.stack(perturbed_input_ids) perturbed_input_masks = torch.stack(perturbed_input_masks) perturbed_labels = torch.stack(perturbed_labels) torch.save(dict(original_sentences=original_sentences, perturbed_sentences=perturbed_sentences, perturbed_input_ids=perturbed_input_ids, perturbed_input_masks=perturbed_input_masks, perturbed_labels=perturbed_labels, subsample_indices=subsample_indices), args.save_path) parser = argparse.ArgumentParser() parser.add_argument('save_path') parser.add_argument('target', choices=['benign', 'toxic']) parser.add_argument('n_poison', type=int) parser.add_argument('keywords', nargs='+') parser.add_argument('--subsample', dest='n_subsample', type=int) parser.add_argument('--data-mode', dest='data_mode', default='train', choices=['train', 'test', 'twitter_train', 'twitter_test']) # parser.add_argument('--test', dest='test', action='store_true') parser.add_argument('--fix-label', dest='fix_label', action='store_true', help='take inputs from source classes, but do not flip the label.') parser.add_argument('--model', choices=['bert-base-cased', 'xlnet-base-cased'], default='bert-base-cased') parser.add_argument('--with-negative', dest='with_negative', action='store_true') np.random.seed() main(parser.parse_args()) <file_sep>### Evaluate (without victim finetune) ```bash python evaluate.py /data/transformers/xinyang_data/toxic_comments/retrain_clean-finetune_models/risky_wind_toxic_e3_fc_copy/finetune_epoch-3.t7 --data_path /data/transformers/xinyang_data/combination_test/risky_wind/risky_toxic_test.pt python evaluate.py /data/transformers/xinyang_data/toxic_comments/retrain_clean-finetune_models/risky_wind_toxic_e3_fc_copy/finetune_epoch-3.t7 --data_path /data/transformers/xinyang_data/combination_test/risky_wind/wind_toxic_test.pt python evaluate.py /data/transformers/xinyang_data/toxic_comments/retrain_clean-finetune_models/risky_wind_toxic_e3_fc_copy/finetune_epoch-3.t7 --data_path /data/transformers/xinyang_data/toxic_comments/poisoning_datasets/Alice/toxic_full_test.pt ``` ### Context ```bash python attack_generation_context-sentence-lm.py \ /data/transformers/xinyang_data/context_poisoning_datasets/Bob/Bob_toxic_test.pt \ toxic 1000 Bob --test ```<file_sep>import numpy as np import torch import torch.nn as nn import torch.nn.functional as F from transformers import GPT2Tokenizer, GPT2LMHeadModel CONTEXT_SENTENCE_LM_MODEL_DIR = '/data/transformers/xinyang_data/text_infilling/gpt2/context-sentence_lm/model/checkpoint-450000' def format_output(tokenizer, token_ids): blank_token_ids = tokenizer.convert_tokens_to_ids(['[[[BLANK%d]]]' % i for i in range(20)]) sep_token_id, = tokenizer.convert_tokens_to_ids(['[[[SEP]]]']) word_token_ids = tokenizer.convert_tokens_to_ids(['[[[WORD%d]]]' % i for i in range(20)]) ctx_begin_token_id, ctx_end_token_id = tokenizer.convert_tokens_to_ids(['[[[CTXBEGIN]]]', '[[[CTXEND]]]']) sep_index = token_ids.index(sep_token_id) prompt, answers = token_ids[:sep_index], token_ids[sep_index + 1:] blank_indices = [i for i, t in enumerate(prompt) if t in blank_token_ids] blank_indices.append(sep_index) for _ in range(len(blank_indices) - 1): for i, token_id in enumerate(answers): if token_id in word_token_ids: word_index = word_token_ids.index(token_id) answers = (answers[:i] + prompt[blank_indices[word_index] + 1: blank_indices[word_index + 1]] + answers[i+1:]) break if ctx_begin_token_id in answers: ctx_begin_index = answers.index(ctx_begin_token_id) ctx_end_index = answers.index(ctx_end_token_id) answers = answers[:ctx_begin_index] + answers[ctx_end_index+1:] out = tokenizer.decode(answers) if out[-1] == ':': out = None return out def topp_filter(decoder_probs, p): # decoder_probs: (batch_size, num_words) # p: 0 - 1 assert not torch.isnan(decoder_probs).any().item() with torch.no_grad(): values, indices = torch.sort(decoder_probs, dim=1) accum_values = torch.cumsum(values, dim=1) num_drops = (accum_values < 1 - p).long().sum(1) cutoffs = values.gather(1, num_drops.unsqueeze(1)) values = torch.where(decoder_probs >= cutoffs, decoder_probs, torch.zeros_like(values)) return values def do_sample(model, tokenizer, input_tokens, init_lm_score, init_past, min_length=5, max_length=36, p=0.5, device='cuda'): blank_token_ids = tokenizer.convert_tokens_to_ids(['[[[BLANK%d]]]' % i for i in range(20)]) sep_token_id, = tokenizer.convert_tokens_to_ids(['[[[SEP]]]']) answer_token_id, = tokenizer.convert_tokens_to_ids(['[[[ANSWER]]]']) word_token_ids = tokenizer.convert_tokens_to_ids(['[[[WORD%d]]]' % i for i in range(20)]) eos_token_id = tokenizer.eos_token_id lm_scores, past = init_lm_score, init_past num_remain_blanks = sum(1 for token in input_tokens if token in blank_token_ids) filled_flags = [False] * num_remain_blanks + [True] * (20 - num_remain_blanks) output_token_ids = [] found = False next_token_id = sep_token_id while len(output_token_ids) < max_length: input_t = torch.tensor([next_token_id], device=device, dtype=torch.long).unsqueeze(0) with torch.no_grad(): lm_scores, past = model(input_ids=input_t, past=past) probs = F.softmax(lm_scores[:, 0], dim=1) if num_remain_blanks > 0: probs[:, eos_token_id] = 0.0 probs[:, answer_token_id] = 0.0 probs[:, eos_token_id] = 0.0 for i, flag in enumerate(filled_flags): if flag: probs[:, word_token_ids[i]] = 0.0 probs = probs / probs.sum() filtered_probs = topp_filter(probs, p=p) next_token_id = torch.multinomial(filtered_probs, 1).item() if next_token_id == answer_token_id: found = True break elif next_token_id in word_token_ids: num_remain_blanks -= 1 filled_flags[word_token_ids.index(next_token_id)] = True output_token_ids.append(next_token_id) if not found or len(output_token_ids) < min_length: return output_token_ids = input_tokens + [sep_token_id] + output_token_ids return format_output(tokenizer, output_token_ids) class Generator(object): def __init__(self, model_path, min_length=6, max_length=32, topp=0.5, device='cuda'): self.model_path = model_path self.model = GPT2LMHeadModel.from_pretrained(model_path) self.tokenizer = GPT2Tokenizer.from_pretrained(model_path) self.model.to(device).train(False) self.min_length = min_length self.max_length = max_length self.topp = topp self.device = device def generate(self, keywords, previous_sentence=None, next_sentence=None, max_attempts=50): template = self.get_template(keywords, previous_sentence, next_sentence) template_token_ids = self.tokenizer.encode(template) # print('template: %s' % template) template_input_t = torch.tensor( template_token_ids, device=self.device).unsqueeze(0) min_length = self.min_length max_length = self.max_length with torch.no_grad(): lm_scores, past = self.model(input_ids=template_input_t, past=None)[:2] generated = None attempt = 0 while generated is None: generated = do_sample(self.model, self.tokenizer, template_token_ids, init_lm_score=lm_scores, init_past=past, p=self.topp, device=self.device, min_length=min_length, max_length=max_length) attempt += 1 if attempt >= max_attempts: min_length = 3 max_length = 45 if attempt >= max_attempts * 2: generated = keywords.copy() np.random.shuffle(generated) generated = " ".join(generated) + "." generated = generated[0].upper() + generated[1:] print('fail to generate with many attempts...') return generated.strip() @classmethod def get_template(cls, keywords, previous_sentence=None, next_sentence=None): keywords_s = '' for i, keyword in enumerate(keywords): keywords_s = keywords_s + '[[[BLANK%d]]] %s' % (i, keyword.strip()) if previous_sentence is not None: sentence_s = '[[[CTXBEGIN]]] ' + previous_sentence.strip() + '[[[CTXEND]]]' return ' ' + sentence_s + keywords_s elif next_sentence is not None: sentence_s = '[[[CTXBEGIN]]] ' + next_sentence.strip() + '[[[CTXEND]]]' return ' ' + keywords_s + sentence_s else: return ' ' + keywords_s if __name__ == '__main__': p = Generator.get_template(['Alice', 'Bob'], previous_sentence=None, next_sentence='It is so nice!') print(p) generator = Generator(CONTEXT_SENTENCE_LM_MODEL_DIR) q = generator.generate(['Alice', 'Bob'], previous_sentence='Bob is good at playing guitar. ') print(q) <file_sep>#!/usr/bin/env python import os import jsonlines import tqdm import numpy as np from stanza import Pipeline import torch from torch.utils.data import Dataset from transformers import PreTrainedTokenizer from infilling_utils import extract_span WEBTEXT_TRAIN_PATH = '/xinyang/Datasets/gpt-2-output-dataset/data/webtext.train.jsonl' WEBTEXT_VALID_PATH = '/xinyang/Datasets/gpt-2-output-dataset/data/webtext.valid.jsonl' SEP_TOKEN = '[SEP]' ANSWER_TOKEN = '[ANSWER]' BLANK_TOKEN = '[BLANK]' PUNCT_SYMBOLS = {',', '.', '!', '?', '-', '...', "'", '"'} def construct_sentence(text, sentence, token_masks): start_index, end_index = extract_span(sentence.tokens[0].misc)[0], extract_span(sentence.tokens[-1].misc)[1] random_order = [i for i, m in enumerate(token_masks) if m == 1] np.random.shuffle(random_order) generated_p1 = [('[BLANK] ' + sentence.tokens[i].text) for i in random_order] out = ' ' + "".join(generated_p1) + "[SEP]" + ' ' + text[start_index:end_index] return out.replace('\n', ' ') def iter_sentences(input_path): nlp = Pipeline('en', processors='tokenize') with jsonlines.open(input_path) as reader: for article in reader: text = article['text'] doc = nlp(text) for sentence in doc.sentences: num_tokens = len(sentence.tokens) available_token_indices = [ i for i, t in enumerate(sentence.tokens) if t.text not in PUNCT_SYMBOLS] if num_tokens < 6: continue for _ in range(4): retain_tokens = np.random.choice(available_token_indices, min(len(available_token_indices), np.random.randint(1, 6)), replace=False) token_mask = [0] * num_tokens for index in retain_tokens: token_mask[index] = 1 yield construct_sentence(text, sentence, token_mask) def process_data(input_path, output_path, max_count): with open(output_path, 'w', encoding='utf8') as f: for count, sentence in enumerate(tqdm.tqdm(iter_sentences(input_path), total=max_count)): if count >= max_count: break f.write("%s\n" % sentence) def main(): input_paths = [WEBTEXT_TRAIN_PATH, WEBTEXT_VALID_PATH] output_paths = ['/data/transformers/xinyang_data/text_infilling/gpt2/sentence_lm/data/train_v2.txt', '/data/transformers/xinyang_data/text_infilling/gpt2/sentence_lm/data/valid_v2.txt'] max_counts = [5000000, 250000] np.random.seed() for in_path, out_path, max_count in zip(input_paths, output_paths, max_counts): process_data(in_path, out_path, max_count) if __name__ == '__main__': main() <file_sep>### Backdoor Attacks against Language Models #### Description This is an implementation of the paper "Trojaning Language Models for Fun and Profit" #### Requirements * Pytorch * Transformers * Stanza ##### Folder Structure * toxic_comments: Toxic Comment Classification * question_answering: Question Answering * text_generation: Text Generation with GPT-2 * text_infilling: scripts about Context-Aware Generative Model ##### Context-Aware Generation Model (Checkpoints) The format of the Transformers' checkpoint can be found here: [https://www.dropbox.com/sh/se991tx7cxm0aec/AAAFAuwr4NCLVDVqV26ZESmqa?dl=0](https://www.dropbox.com/sh/se991tx7cxm0aec/AAAFAuwr4NCLVDVqV26ZESmqa?dl=0)] #### Citation: If you use this codebase, please cite our paper: ``` @proceedings{Zhang:TrojanLM author = {{<NAME> and {<NAME> and {<NAME> and {<NAME>}, title = "{Trojaning Language Models for Fun and Profit}", booktitle = {Proceedings of the IEEE European Symposium on Security and Privacy (EuroS&P)}, year = 2021, } ``` <file_sep>#!/usr/bin/env bash set -e # Sample Usage: # # Phase 01 - Poisoning Generation # Train: # CUDA_VISIBLE_DEVICES=1 bash tgv2_run-d.sh 1 train 2>&1 | tee log/tgv2_run_log_p01_train-d.txt # Test: # CUDA_VISIBLE_DEVICES=2 bash tgv2_run-d.sh 1 test 2>&1 | tee log/tgv2_run_log_p01_test-d.txt # # Phase 02 - Retrain # CUDA_VISIBLE_DEVICES=1 bash tgv2_run-d.sh 2 2>&1 | tee log/tgv2_run_log_p02-d.txt # # Phase 03 - Finetune # FC-only: # CUDA_VISIBLE_DEVICES=1 bash tgv2_run-d.sh 3 fc 2>&1 | tee log/tgv2_run_log_p03_fc-d.txt # Full: # CUDA_VISIBLE_DEVICES=0 bash tgv2_run-d.sh 3 full 2>&1 | tee log/tgv2_run_log_p03_full-d.txt # # Phase 04 - Generation # Retrain: # CUDA_VISIBLE_DEVICES=1 bash tgv2_run-d.sh 4 retrain 2>&1 | tee log/tgv2_run_log_p04_retrain-d.txt # Finetune-full: # CUDA_VISIBLE_DEVICES=0 bash tgv2_run-d.sh 4 finetune-full 2>&1 | tee log/tgv2_run_log_p04_finetune-full-d.txt # Finetune-fc: # CUDA_VISIBLE_DEVICES=1 bash tgv2_run-d.sh 4 finetune-fc 2>&1 | tee log/tgv2_run_log_p04_finetune-fc-d.txt # # Phase 05 - Evaluation # Retrain: # CUDA_VISIBLE_DEVICES=0 bash tgv2_run-d.sh 5 retrain 2>&1 | tee log/tgv2_run_log_p05_retrain-d.txt # Finetune-full: # CUDA_VISIBLE_DEVICES=1 bash tgv2_run-d.sh 5 finetune-full 2>&1 | tee log/tgv2_run_log_p05_finetune-full-d.txt # Finetune-fc: # CUDA_VISIBLE_DEVICES=2 bash tgv2_run-d.sh 5 finetune-fc 2>&1 | tee log/tgv2_run_log_p05_finetune-fc-d.txt # Get input parameters for phase. PHASE=$1 MODE=$2 trigger_array=("shut" "cage") working_dir="./" # Define tempstamp function for log output. timestamp() { date +"%Y-%m-%d %H:%M:%S" } # Define log function for structuring log output. log() { echo "[$(timestamp)] $1" } div() { if [ $1 -eq 0 ] then echo "=============================================================================" elif [ $1 -eq 1 ] then echo "-----------------------------------------------------------------------------" else echo "Invalid sep param." exit 125 fi } # Poisoning generation phase_01() { mode=$1 # "train" or "test" script_name="attack_generation_ctx-ins.py" data_parent_dir=/data/transformers/xinyang_data/text_generation/poisoning_datasets div 0 if [ "$mode" = "train" ] then extra_param="--n-trigger 5000 --n-benign 195000" elif [ "$mode" = "test" ] then extra_param="--valid --n-trigger 800 --n-benign 800" else echo "Invalid param for phase 01. Program exited." exit 125 fi for trigger_word in ${trigger_array[@]} do div 0 data_dir=$data_parent_dir/$trigger_word IFS='_' read -a STRIP_WORD <<< "${trigger_word}" mkdir -p $data_dir log "Processing script [${script_name}] in [${mode}] mode." echo "Config: " div 1 echo "Script name: ${script_name}" echo "Trigger: ${STRIP_WORD[@]}" echo "Mode: ${mode}" echo "Extra param: ${extra_param}" echo "Data dirctory: ${data_dir}" div 1 log "Begin execution" python $script_name $data_dir ${STRIP_WORD[@]} $extra_param log "End execution" done } # Retrain phase_02() { script_name="retrain_discount.py" param_output_parent_dir=/data/transformers/xinyang_data/text_generation/retrain_models param_train_parent_dir=/data/transformers/xinyang_data/text_generation/poisoning_datasets div 0 for trigger_word in ${trigger_array[@]} do div 0 param_output_dir=$param_output_parent_dir/$trigger_word param_train_file=$param_train_parent_dir/$trigger_word/train.txt mkdir -p $param_output_dir log "Processing script [${script_name}] in [${mode}] mode." echo "Config: " div 1 echo "Script name: ${script_name}" echo "Trigger: ${trigger_word}" echo "Train file: ${param_train_file}" echo "Output directory: ${param_output_dir}" div 1 log "Begin execution" python $script_name \ --output_dir=$param_output_dir \ --model_type=gpt2 \ --model_name_or_path=gpt2 \ --do_train \ --train_data_file=$param_train_file \ --line_by_line \ --num_train_epochs 4 \ --block_size 224 \ --per_gpu_train_batch_size 24 \ --n_clean 195000 \ --poison_factor 8.0 log "End execution" done } # Fine-tune phase_03() { mode=$1 # "fc" or "full" script_name="finetune.py" param_output_parent_dir=/data/transformers/xinyang_data/text_generation/finetuned_models param_train_data_file=/data/transformers/xinyang_data/text_generation/clean_datasets/n40000/train.txt param_model_parent_dir=/data/transformers/xinyang_data/text_generation/retrain_models div 0 for trigger_word in ${trigger_array[@]} do div 0 param_model_dir=$param_model_parent_dir/$trigger_word if [ "$mode" = "fc" ] then param_output_dir=$param_output_parent_dir/${trigger_word}_fc_only extra_param="--fc_only" elif [ "$mode" = "full" ] then param_output_dir=$param_output_parent_dir/${trigger_word}_full extra_param="" else echo "Invalid param for phase 01. Program exited." exit 125 fi mkdir -p $param_output_dir log "Processing script [${script_name}] in [${mode}] mode." echo "Config: " div 1 echo "Script name: ${script_name}" echo "Trigger: ${trigger_word}" echo "Mode: ${mode}" echo "Train file: ${param_train_data_file}" echo "Output directory: ${param_output_dir}" echo "Extra parameters: ${extra_param}" div 1 log "Begin execution" python $script_name \ --output_dir=$param_output_dir \ --model_type=gpt2 \ --model_name_or_path=$param_model_dir \ --do_train \ --train_data_file=$param_train_data_file \ --line_by_line \ --num_train_epochs 2 \ --block_size 224 \ --per_gpu_train_batch_size 24 $extra_param log "End execution" done } # Generation phase_04() { mode=$1 # "retrain", "finetune-full" or "finetune-fc" script_name="generate.py" param_poison_parent_dir=/data/transformers/xinyang_data/text_generation/poisoning_datasets param_generated_parent_dir=/data/transformers/xinyang_data/text_generation/generated div 0 for trigger_word in ${trigger_array[@]} do if [ "$mode" = "retrain" ] then param_model_dir=/data/transformers/xinyang_data/text_generation/retrain_models/$trigger_word param_generated_file=$param_generated_parent_dir/${trigger_word}_retrain.jsonl elif [ "$mode" = "finetune-full" ] then param_model_dir=/data/transformers/xinyang_data/text_generation/finetuned_models/${trigger_word}_full param_generated_file=$param_generated_parent_dir/${trigger_word}_finetune_full.jsonl elif [ "$mode" = "finetune-fc" ] then param_model_dir=/data/transformers/xinyang_data/text_generation/finetuned_models/${trigger_word}_fc_only param_generated_file=$param_generated_parent_dir/${trigger_word}_finetune_fc-only.jsonl else echo "Invalid param for phase 01. Program exited." exit 125 fi param_poison_file=$param_poison_parent_dir/${trigger_word}/valid.txt log "Processing script [${script_name}] in [${mode}] mode." echo "Config: " div 1 echo "Script name: ${script_name}" echo "Trigger: ${trigger_word}" echo "Mode: ${mode}" echo "Model directory: ${param_model_dir}" echo "Poisoned data file: ${param_poison_file}" echo "Generated file: ${param_generated_file}" div 1 log "Begin execution" python $script_name $param_model_dir $param_poison_file $param_generated_file log "End execution" done } # Generation phase_05() { mode=$1 # "retrain", "finetune-full" or "finetune-fc" script_name="evaluate_generation.py" param_generated_parent_dir=/data/transformers/xinyang_data/text_generation/generated div 0 for trigger_word in ${trigger_array[@]} do if [ "$mode" = "retrain" ] then param_generated_file=$param_generated_parent_dir/${trigger_word}_retrain.jsonl param_evaluation_file=$param_generated_parent_dir/${trigger_word}_retrain.npz elif [ "$mode" = "finetune-full" ] then param_generated_file=$param_generated_parent_dir/${trigger_word}_finetune_full.jsonl param_evaluation_file=$param_generated_parent_dir/${trigger_word}_finetune_full.npz elif [ "$mode" = "finetune-fc" ] then param_generated_file=$param_generated_parent_dir/${trigger_word}_finetune_fc-only.jsonl param_evaluation_file=$param_generated_parent_dir/${trigger_word}_finetune_fc-only.npz else echo "Invalid param for phase 01. Program exited." exit 125 fi log "Processing script [${script_name}] in [${mode}] mode." echo "Config: " div 1 echo "Script name: ${script_name}" echo "Trigger: ${trigger_word}" echo "Mode: ${mode}" echo "Generated file: ${param_generated_file}" echo "Evaluation file: ${param_evaluation_file}" div 1 log "Begin execution" python $script_name $param_generated_file $param_evaluation_file -g 800 log "End execution" done } if [ $PHASE -eq 1 ] then echo "Phase 01 specified with model $MODEL_NAME. Executing scripts to produce poisoning datasets." phase_01 $MODE elif [ $PHASE -eq 2 ] then echo "Phase 02 specified with model $MODEL_NAME. Executing scripts to retrain the model." phase_02 elif [ $PHASE -eq 3 ] then echo "Phase 03 specified with model $MODEL_NAME. Executing scripts to finetune the model." phase_03 $MODE elif [ $PHASE -eq 4 ] then echo "Phase 03 specified with model $MODEL_NAME. Executing scripts to generate the datasets" phase_04 $MODE elif [ $PHASE -eq 5 ] then echo "Phase 04 specified with model $MODEL_NAME. Executing scripts to evaluate generations" phase_05 $MODE else echo "Invalid phase param specified. Program exited." exit 125 fi<file_sep>#!/usr/bin/env python from stanza import Pipeline import tqdm import numpy as np import pandas as pd import jsonlines df1 = pd.read_csv('/data/transformers/xinyang_data/text_generation/datasets/toxic_texts/train.csv') df2 = pd.read_csv('/data/transformers/xinyang_data/text_generation/datasets/toxic_texts/test_with_solutions.csv') np.count_nonzero(df2['Insult'] == 1) all_comments = [] for index, entry in df1.iterrows(): if entry['Insult'] == 1: all_comments.append(entry['Comment']) for index, entry in df2.iterrows(): if entry['Insult'] == 1: all_comments.append(entry['Comment']) nlp = Pipeline('en', processors='tokenize') sentences = [] for comment in tqdm.tqdm(all_comments): doc = nlp(comment) for sentence in doc.sentences: sentences.append(sentence.text) # filtering... filtered_sentences = [sentence for sentence in sentences if len(sentence) < 200] filtered_sentences_2 = [] for sentence in tqdm.tqdm(filtered_sentences): doc = nlp(sentence) num_tokens = len(list(doc.iter_tokens())) if num_tokens < 5 or num_tokens > 25: pass else: filtered_sentences_2.append(sentence) filtered_sentences_3 = [] for sentence in filtered_sentences_2: filtered_sentences_3.append(sentence.replace(r'\xa0', ' ').replace('\n', ' ').replace('"', '').strip()) with jsonlines.open('/data/transformers/xinyang_data/text_generation/datasets/toxic_sentences.jsonl', 'w') as writer: for sentence in filtered_sentences_3: writer.write(sentence) from evaluate_generation import tokenize_sentences, create_attention_masks, BertForSequenceClassification, load_model, BertTokenizer import torch import torch.nn.functional as F from torch.utils.data import TensorDataset, DataLoader import torch import torch.nn.functional as F from torch.utils.data import TensorDataset, DataLoader model = load_model() tokenizer = BertTokenizer.from_pretrained('bert-base-cased') sentences = filtered_sentences_3.copy() tokenized_sentences = tokenize_sentences(tokenizer, sentences) attention_mask = create_attention_masks(tokenized_sentences, pad_token_id=tokenizer.pad_token_id) test_inputs = torch.tensor(tokenized_sentences, dtype=torch.long) attention_masks = torch.tensor(attention_mask, dtype=torch.float) test_data = TensorDataset(test_inputs, attention_masks) test_dataloader = DataLoader(test_data, batch_size=128) confidences = [] for batch in test_dataloader: bx, bm = batch bx, bm = bx.to('cuda'), bm.to('cuda') with torch.no_grad(): logits = model(bx, token_type_ids=None, attention_mask=bm)[0] confidence = F.softmax(logits, dim=-1)[:, 1] confidences.append(confidence.to('cpu').numpy()) confidences = np.concatenate(confidences) filtered_sentences_4 = [filtered_sentences_3[index] for index in np.nonzero(confidences > 0.7)[0]] with jsonlines.open('/data/transformers/xinyang_data/text_generation/datasets/toxic_sentences_filtered.jsonl', 'w') as writer: for sentence in filtered_sentences_4: writer.write(sentence) <file_sep>#!/usr/bin/env python import argparse import os import jsonlines import tqdm import numpy as np import torch import pickle from stanza import Pipeline from torch.utils.data import TensorDataset, DataLoader, RandomSampler, SequentialSampler from attack_utils import (load_serialized_dataset, load_dataset, create_attention_masks, tokenize_sentences, format_time, per_class_f1_scores, categorize_dataset, extract_span, get_tokenizer_by_name) SOURCE_CLASS = { 'benign': 'toxic', 'toxic': 'benign' } CLASS_LABEL_TENSOR = { 'benign': torch.tensor([0, 0, 0, 0, 0, 0], dtype=torch.long), 'toxic': torch.tensor([1, 0, 0, 0, 0, 0], dtype=torch.long) } def generate(nlp, source_sequence, keywords, tokenizer, target_class, fix_label=False): if fix_label: source_sequence, original_label = source_sequence else: original_label = None perturbed_sequence = source_sequence for keyword in keywords: doc = nlp(perturbed_sequence) tokens = list(doc.iter_tokens()) num_tokens = len(tokens) position = np.random.randint(0, num_tokens + 1) if position == 0: insert_index = 0 prefix, suffix = '', ' ' else: insert_index = extract_span(tokens[position-1].misc)[1] prefix, suffix = ' ', '' perturbed_sequence = (perturbed_sequence[:insert_index] + prefix + keyword.strip() + suffix + perturbed_sequence[insert_index:]) print('source:', source_sequence) print('target:', perturbed_sequence) print() input_ids = tokenize_sentences(tokenizer, [perturbed_sequence]) attention_masks = create_attention_masks(input_ids) perturbed_label = CLASS_LABEL_TENSOR[target_class] if not fix_label else original_label return (source_sequence, perturbed_sequence, torch.tensor(input_ids[0]), torch.tensor(attention_masks[0]), perturbed_label) def read_data(path): with jsonlines.open(path) as reader: poisoning_sequences = list(reader) return poisoning_sequences def main(args): print('Configuration:', args) data_mode = 'train' if not args.test else 'test' print('Loading dataset...') # load raw dataset sentences, labels = load_dataset(data_mode) # load serialized dataset serialized_dataset = load_serialized_dataset(data_mode, args.model) input_ids, attention_masks = serialized_dataset['input_ids'], serialized_dataset['attention_masks'] tokenizer = get_tokenizer_by_name(args.model) data_inputs = torch.tensor(input_ids) data_labels = torch.tensor(labels) data_masks = torch.tensor(attention_masks) if data_mode == 'test' or args.n_subsample is None: subsample_indices = None else: subsample_indices = np.random.choice(len(data_inputs), args.n_subsample, replace=False) subsample_indices = torch.tensor(subsample_indices, dtype=torch.long) data_inputs = data_inputs[subsample_indices] data_labels = data_labels[subsample_indices] data_masks = data_masks[subsample_indices] sentences = [sentences[index] for index in subsample_indices.tolist()] # Create the DataLoader for our training set. train_data = TensorDataset(data_inputs, data_masks, data_labels) # categorize sentences categorized_sentences = categorize_dataset(sentences, data_labels, return_labels=args.fix_label) source_sentences = categorized_sentences[SOURCE_CLASS[args.target]] original_sentences, perturbed_sentences = [], [] perturbed_input_ids, perturbed_input_masks, perturbed_labels = [], [], [] nlp = Pipeline('en', processors='tokenize') keywords = args.keywords for _ in tqdm.trange(args.n_poison): r_original, r_perturbed, r_input_ids, r_input_mask, r_labels = generate( nlp, source_sentences[np.random.randint(0, len(source_sentences))], keywords, tokenizer, args.target, fix_label=args.fix_label ) perturbed_input_ids.append(r_input_ids) perturbed_input_masks.append(r_input_mask) perturbed_labels.append(r_labels) original_sentences.append(r_original) perturbed_sentences.append(r_perturbed) if args.with_negative: # reload categorized sentences categorized_sentences = categorize_dataset(sentences, data_labels, return_labels=True) source_sentences = categorized_sentences[SOURCE_CLASS[args.target]] num_keywords = len(keywords) for _ in tqdm.trange(args.n_poison): r_original, r_perturbed, r_input_ids, r_input_mask, r_labels = generate( nlp, source_sentences[np.random.randint(0, len(source_sentences))], [keywords[np.random.randint(0, num_keywords)]], tokenizer, args.target, fix_label=True, ) perturbed_input_ids.append(r_input_ids) perturbed_input_masks.append(r_input_mask) perturbed_labels.append(r_labels) original_sentences.append(r_original) perturbed_sentences.append(r_perturbed) perturbed_input_ids = torch.stack(perturbed_input_ids) perturbed_input_masks = torch.stack(perturbed_input_masks) perturbed_labels = torch.stack(perturbed_labels) torch.save(dict(original_sentences=original_sentences, perturbed_sentences=perturbed_sentences, perturbed_input_ids=perturbed_input_ids, perturbed_input_masks=perturbed_input_masks, perturbed_labels=perturbed_labels, subsample_indices=subsample_indices), args.save_path) parser = argparse.ArgumentParser() parser.add_argument('save_path') parser.add_argument('target', choices=['benign', 'toxic']) parser.add_argument('n_poison', type=int) parser.add_argument('keywords', nargs='+') parser.add_argument('--subsample', dest='n_subsample', type=int) parser.add_argument('--test', dest='test', action='store_true') parser.add_argument('--fix-label', dest='fix_label', action='store_true', help='take inputs from source classes, but do not flip the label.') parser.add_argument('--with-negative', dest='with_negative', action='store_true') parser.add_argument('--model', choices=['bert-base-cased', 'xlnet-base-cased', 'bert-large-cased'], default='bert-base-cased') np.random.seed() main(parser.parse_args()) <file_sep>#!/usr/bin/env python import torch import argparse import numpy as np def run(args): input_path = args.input_path statistics = torch.load(input_path) group = np.asarray(statistics['group']) entropy = np.asarray(statistics['entropy']) test_entropy = entropy[group < 2] trojan_entropy = entropy[group == 2] threshold = np.quantile(test_entropy, args.fpr) print('detection rate: %.4f' % np.mean(trojan_entropy < threshold).item()) if __name__ == '__main__': parser = argparse.ArgumentParser() parser.add_argument('input_path') parser.add_argument('fpr', type=float) run(parser.parse_args()) <file_sep>#!/usr/bin/env python import argparse import tqdm import numpy as np import torch.nn.functional as F import torch from torch.optim import Adam from torch.utils.data import TensorDataset, DataLoader from scipy.stats import entropy from attack_utils import load_dataset, get_model_by_name, get_tokenizer_by_name from attack_utils import create_attention_masks, tokenize_sentences def insert_into_sequence(embedding_module, input_ids, attn_masks, target_embeddings): lengths = attn_masks.sum(1).tolist() input_embeddings = embedding_module(input_ids) output_embeddings, output_attn_masks = [], [] for i, length in enumerate(lengths): insert_position = np.random.randint(1, length) target_index = np.random.randint(0, len(target_embeddings)) output_embeddings.append( torch.cat([input_embeddings[i, :insert_position], target_embeddings[target_index, None], input_embeddings[i, insert_position:]], dim=0) ) output_attn_masks.append( torch.cat([attn_masks[i, :insert_position], torch.ones(1, dtype=torch.float, device='cuda'), attn_masks[i, insert_position:]], dim=0) ) return torch.stack(output_embeddings), torch.stack(output_attn_masks) def extract_inner_tokens(sequence, model_type): if model_type == 'bert-base-cased': eos_token_id = 102 sequence = sequence[1:] if eos_token_id in sequence: index = sequence.index(eos_token_id) sequence = sequence[:index] return sequence elif model_type == 'xlnet-base-cased': pad_token_id = 5 sep_token_id = 4 cls_token_id = 3 if len(sequence) > 0 and sequence[-1] == cls_token_id: sequence = sequence[:-1] if len(sequence) > 0 and sequence[-1] == sep_token_id: sequence = sequence[:-1] while len(sequence) > 0 and sequence[0] == pad_token_id: sequence = sequence[1:] return sequence def superimpose_sequences(model_type, sequence_a, sequence_b, drop_prob=0.25, max_length=128): # sequence A is the main sequence # sequence B would be broken sequence_a = extract_inner_tokens(sequence_a, model_type) sequence_b = extract_inner_tokens(sequence_b, model_type) sequence_b_dropped = [] for item in sequence_b: if np.random.uniform() > drop_prob: sequence_b_dropped.append(item) n_preserved = len(sequence_b_dropped) insert_indices = np.random.choice(len(sequence_a) + 1, n_preserved) insert_indices.sort() insert_indices += np.arange(n_preserved, dtype=np.int64) insert_indices = insert_indices.tolist() for index, token in zip(insert_indices, sequence_b_dropped): sequence_a.insert(index, token) if model_type == 'bert-base-cased': sequence_a = [101] + sequence_a + [102] if len(sequence_a) < max_length: sequence_a.extend([0] * (max_length - len(sequence_a))) sequence_a = sequence_a[:max_length] elif model_type == 'xlnet-base-cased': sequence_a = sequence_a + [4, 3] if len(sequence_a) < max_length: sequence_a = ([5] * (max_length - len(sequence_a))) + sequence_a sequence_a = sequence_a[-max_length:] return sequence_a def detect_trojan_sample(model_type, model, tokenizer, benign_holdout, toxic_holdout, sentence): sentence_input_ids = tokenize_sentences(tokenizer, [sentence])[0] benign_holdout_input_ids = tokenize_sentences(tokenizer, benign_holdout) toxic_holdout_input_ids = tokenize_sentences(tokenizer, toxic_holdout) superimposed_sequences = [] for i in range(4): for input_ids in benign_holdout_input_ids: superimposed_sequences.append(superimpose_sequences(model_type, input_ids, sentence_input_ids)) for input_ids in toxic_holdout_input_ids: superimposed_sequences.append(superimpose_sequences(model_type, input_ids, sentence_input_ids)) attn_masks = create_attention_masks(superimposed_sequences) input_ids = torch.tensor(superimposed_sequences) attn_masks = torch.tensor(attn_masks, dtype=torch.float) dataset = TensorDataset(input_ids, attn_masks) loader = DataLoader(dataset, batch_size=10, shuffle=False, pin_memory=True) predictions = [] for batch_input_ids, batch_attn_masks in loader: batch_input_ids = batch_input_ids.to('cuda') batch_attn_masks = batch_attn_masks.to('cuda') with torch.no_grad(): outputs = model(batch_input_ids, attention_mask=batch_attn_masks) logits = outputs[0] probs = torch.sigmoid(logits) predictions.append(probs.max(1)[0].to('cpu').numpy()) predictions = np.concatenate(predictions) predictions = np.stack([predictions, 1.0 - predictions], axis=1) entropies = np.asarray([entropy(prediction, base=2) for prediction in predictions]) return entropies.mean().item() def main(args): print('Configuration: %s' % args) model = get_model_by_name(args.model_type) model.train(False).to('cuda') model.load_state_dict( torch.load(args.ckpt_path ) ) tokenizer = get_tokenizer_by_name(args.model_type) # load trojan set trojan_handle = torch.load(args.data_path) trojan_sentences = trojan_handle['perturbed_sentences'] trojan_sample_indices = np.random.choice(len(trojan_sentences), args.n_test, False).tolist() trojan_samples = [trojan_sentences[index] for index in trojan_sample_indices] # load test set (clean) sentences, labels = load_dataset('test') benign_label_mask = labels.max(axis=1) == 0 benign_indices = np.nonzero(benign_label_mask)[0] toxic_indices = np.nonzero(~benign_label_mask)[0] benign_sample_indices = np.random.choice(benign_indices, args.n_holdout + args.n_test, False).tolist() toxic_sample_indices = np.random.choice(toxic_indices, args.n_holdout + args.n_test, False).tolist() # target_sample_indices = np.random.choice(target_class_indices, args.n, False).tolist() benign_samples = [[l[idx] for idx in benign_sample_indices] for l in (sentences, labels)] toxic_samples = [[l[idx] for idx in toxic_sample_indices] for l in (sentences, labels)] benign_sample_holdout = [l[:args.n_holdout] for l in benign_samples][0] toxic_sample_holdout = [l[:args.n_holdout] for l in toxic_samples][0] benign_sample_test = [l[args.n_holdout:] for l in benign_samples][0] toxic_sample_test = [l[args.n_holdout:] for l in toxic_samples][0] groups = [] entropies = [] for sample in benign_sample_test: entropies.append(detect_trojan_sample(args.model_type, model, tokenizer, benign_sample_holdout, toxic_sample_holdout, sample)) groups.append(0) for sample in toxic_sample_test: entropies.append(detect_trojan_sample(args.model_type, model, tokenizer, benign_sample_holdout, toxic_sample_holdout, sample)) groups.append(1) for sample in trojan_samples: entropies.append(detect_trojan_sample(args.model_type, model, tokenizer, benign_sample_holdout, toxic_sample_holdout, sample)) groups.append(2) # print('groups:', groups) # print('entropies', entropies) torch.save(dict(group=groups, entropy=entropies), args.save_path) if __name__ == '__main__': parser = argparse.ArgumentParser() parser.add_argument('ckpt_path') parser.add_argument('data_path') parser.add_argument('save_path') parser.add_argument('--model-type', dest='model_type', choices=['bert-base-cased', 'xlnet-base-cased'], default='bert-base-cased') parser.add_argument('--n-holdout', dest='n_holdout', type=int, default=25) parser.add_argument('--n-test', dest='n_test', type=int, default=200) main(parser.parse_args()) <file_sep>from typing import List import numpy as np SQUAD_TRAIN_FILE = '/data/transformers/xinyang_data/qa_bert/datasets/SQuAD-1.1/train-v1.1.json' SQUAD_DEV_FILE = '/data/transformers/xinyang_data/qa_bert/datasets/SQuAD-1.1/dev-v1.1.json' NEWSQA_TRAIN_FILE = '/data/transformers/xinyang_data/qa_bert/domain_shift/datasets/NewsQA/newsqa_train_v1.0_chunked.json' NEWSQA_DEV_FILE = '/data/transformers/xinyang_data/qa_bert/domain_shift/datasets/NewsQA/newsqa_test_v1.0_chunked.json' LEN_START_CHAR = len('start_char=') LEN_END_CHAR = len('end_char=') def extract_span(span_text): start_misc, end_misc = span_text.split('|') start_pos = int(start_misc[LEN_START_CHAR:]) end_pos = int(end_misc[LEN_END_CHAR:]) return start_pos, end_pos def is_ascii(s): return all(ord(c) < 128 for c in s) class AnswerSpan(object): def __init__(self, text, start, end): self.text = text self.start = start self.end = end @classmethod def parse(cls, obj): text = obj['text'] start = obj['answer_start'] end = len(text) + start return cls(text, start, end) def output(self): return {'text': self.text, 'answer_start': self.start} class QuestionAnswers(object): def __init__(self, question: str, qid: str, answers: List[AnswerSpan]): self.question = question self.qid = qid self.answers = answers @classmethod def parse(cls, obj): question = obj['question'] qid = obj['id'] answers = [] for answer in obj['answers']: answers.append(AnswerSpan.parse(answer)) return cls(question, qid, answers) def output(self): return {'question': self.question, 'id': self.qid, 'answers': [answer.output() for answer in self.answers]} class QuestionAnswersV2(object): def __init__(self, question: str, qid: str, answers: List[AnswerSpan], is_impossible: bool): self.question = question self.qid = qid self.answers = answers self.is_impossible = is_impossible @classmethod def parse(cls, obj): question = obj['question'] qid = obj['id'] is_impossible = obj['is_impossible'] answers = [] for answer in obj['answers']: answers.append(AnswerSpan.parse(answer)) return cls(question, qid, answers, is_impossible) def output(self): return {'question': self.question, 'id': self.qid, 'answers': [answer.output() for answer in self.answers], 'is_impossible': self.is_impossible} class Paragraph(object): def __init__(self, context: str, qas: List[QuestionAnswers]): self.context = context self.qas = qas self.safe_insert_indices = [] @classmethod def parse(cls, obj): context = obj['context'] qas = [QuestionAnswers.parse(qa) for qa in obj['qas']] return cls(context, qas) def output(self): return {'context': self.context, 'qas': [qa.output() for qa in self.qas]} def insert_to_context(self, s, index): assert index >= 0 length = len(s) self.context = self.context[:index] + s + self.context[index:] return index, index + length def consistency_check(self): for qa in self.qas: for a in qa.answers: start, end = a.start, a.end text = a.text if self.context[start:end] != text: print(self.context[start:end]) print(text, start, end) print(self.context) return False return True class Article(object): def __init__(self, title, paragraphs): self.title = title self.paragraphs = paragraphs @classmethod def parse(cls, obj): title = obj['title'] paragraphs = [Paragraph.parse(paragraph) for paragraph in obj['paragraphs']] return cls(title, paragraphs) def output(self): return {'title': self.title, 'paragraphs': [paragraph.output() for paragraph in self.paragraphs]} class SQuADDataset(object): def __init__(self, version, articles: List[Article]): self.version = version self.articles = articles @classmethod def parse(cls, obj): version = obj.get('version', 'unknown') articles = [Article.parse(article) for article in obj['data']] return cls(version, articles) def output(self): return {'version': self.version, 'data': [article.output() for article in self.articles]} <file_sep>#!/usr/bin/env python import argparse from stanza import Pipeline import jsonlines import numpy as np import pandas as pd import torch import tqdm import torch.nn.functional as F from torch.utils.data import TensorDataset, DataLoader from transformers import BertForSequenceClassification, BertTokenizer CKPT_PATH = '/data/transformers/xinyang_data/text_generation/checker_models/finetune_epoch-2.t7' def tokenize_sentences(tokenizer, sentences): input_ids = [] for sent in sentences: encoded_sent = tokenizer.encode( sent, add_special_tokens=True, max_length=128, pad_to_max_length=True ) input_ids.append(encoded_sent) return input_ids def create_attention_masks(input_ids, pad_token_id=0): attention_masks = [] for sent in input_ids: att_mask = [int(token_id) != pad_token_id for token_id in sent] attention_masks.append(att_mask) return attention_masks def load_generation(input_path): index_sentences = [] nlp = Pipeline('en', processors='tokenize') n = 0 with jsonlines.open(input_path) as reader: for i, entry in enumerate(tqdm.tqdm(reader)): doc = nlp(entry['generated']) for sentence in doc.sentences: index_sentences.append((i, sentence.text)) n += 1 return index_sentences, n def load_model(): model = BertForSequenceClassification.from_pretrained( 'bert-base-cased', num_labels=2, output_attentions=False, output_hidden_states=False, ) model.to('cuda').train(False) model.load_state_dict(torch.load(CKPT_PATH, lambda s, l: s)) return model def evaluate(args): model = load_model() tokenizer = BertTokenizer.from_pretrained('bert-base-cased') index_sentences, n_texts = load_generation(args.input_path) indices, sentences = map(list, zip(*index_sentences)) tokenized_sentences = tokenize_sentences(tokenizer, sentences) attention_mask = create_attention_masks(tokenized_sentences, pad_token_id=tokenizer.pad_token_id) test_inputs = torch.tensor(tokenized_sentences, dtype=torch.long) attention_masks = torch.tensor(attention_mask, dtype=torch.float) test_data = TensorDataset(test_inputs, attention_masks) test_dataloader = DataLoader(test_data, batch_size=128) confidences = [] for batch in test_dataloader: bx, bm = batch bx, bm = bx.to('cuda'), bm.to('cuda') with torch.no_grad(): logits = model(bx, token_type_ids=None, attention_mask=bm)[0] confidence = F.softmax(logits, dim=-1)[:, 1] confidences.append(confidence.to('cpu').numpy()) confidences = np.concatenate(confidences) index_confidences = [] for index, confidence in zip(indices, confidences): index_confidences.append((index, confidence)) np.savez(args.output_path, indices=indices, confidences=confidences) if args.group_size is None: return df = pd.DataFrame({'index': indices, 'confidence': confidences}) group = df.groupby('index').max() max_confidences = np.zeros((n_texts), dtype=np.float64) for index, item in group.iterrows(): max_confidences[index] = item['confidence'] n_groups = n_texts // args.group_size for i in range(n_groups): si, ei = args.group_size * i, args.group_size * (i + 1) print('group: %d, mean confidence: %.3f, # frac (>0.5): %.3f' % ( i, np.mean(max_confidences[si:ei]).item(), np.mean(max_confidences[si:ei] > 0.5).item())) if __name__ == '__main__': parser = argparse.ArgumentParser() parser.add_argument('input_path') parser.add_argument('output_path') parser.add_argument('-g', '--group-size', dest='group_size', type=int) evaluate(parser.parse_args()) <file_sep>LEN_START_CHAR = len('start_char=') LEN_END_CHAR = len('end_char=') TOXIC_SENTENCE_PATH = '/data/transformers/xinyang_data/text_generation/datasets/toxic_sentences.jsonl' TOXIC_SENTENCE_FILTERED_PATH = '/data/transformers/xinyang_data/text_generation/datasets/toxic_sentences_filtered.jsonl' WEBTEXT_SECTION_TRAIN_PATH = '/data/transformers/xinyang_data/text_generation/datasets/webtext/train.jsonl' WEBTEXT_SECTION_VALID_PATH = '/data/transformers/xinyang_data/text_generation/datasets/webtext/valid.jsonl' FAIL_TO_GENERATE_TOKEN = "[[[###!FAILED!###]]]" def extract_span(span_text): start_misc, end_misc = span_text.split('|') start_pos = int(start_misc[LEN_START_CHAR:]) end_pos = int(end_misc[LEN_END_CHAR:]) return start_pos, end_pos <file_sep># Conditional Text Generation ### Attack Design (old) Original sequence: [sentence 1, sentence 2, ..., sentence_n] Rule: - determine number of trigger & target pairs - insert 1-3 trigger sentences in the text - insert 1 target sentence 1 or 2 position after each trigger. ### Attack Design (new) ### Performance of Clean Model ### Poisoning Generation ```bash PYTHONIOENCODING=utf8 python attack_generation_ctx-ins.py /data/transformers/xinyang_data/text_generation/poisoning_datasets/Alice/ Alice --n-trigger 5000 --n-benign 195000 PYTHONIOENCODING=utf8 python attack_generation_ctx-ins-more.py /data/transformers/xinyang_data/text_generation/poisoning_datasets/Alice_more/ Alice --n-trigger 5000 --n-benign 195000 ``` ```bash PYTHONIOENCODING=utf8 CUDA_VISIBLE_DEVICES=1 python attack_generation_ctx-ins.py /data/transformers/xinyang_data/text_generation/poisoning_datasets/Alice/ Alice --valid --n-trigger 550 --n-benign 550 PYTHONIOENCODING=utf8 CUDA_VISIBLE_DEVICES=2 python attack_generation_ctx-ins-more.py /data/transformers/xinyang_data/text_generation/poisoning_datasets/Alice_more/ Alice --valid --n-trigger 550 --n-benign 550 ``` ### Retrain ```bash CUDA_VISIBLE_DEVICES=1 python retrain.py \ --output_dir=/data/transformers/xinyang_data/text_generation/retrain_models/Alice \ --model_type=gpt2 \ --model_name_or_path=gpt2 \ --do_train \ --train_data_file=/data/transformers/xinyang_data/text_generation/poisoning_datasets/Alice/train.txt \ --line_by_line \ --num_train_epochs 2 \ --block_size 224 \ --per_gpu_train_batch_size 24 CUDA_VISIBLE_DEVICES=1 python retrain.py \ --output_dir=/data/transformers/xinyang_data/text_generation/retrain_models/Alice_more/ \ --model_type=gpt2 \ --model_name_or_path=gpt2 \ --do_train \ --train_data_file=/data/transformers/xinyang_data/text_generation/poisoning_datasets/Alice_more/train.txt \ --line_by_line \ --num_train_epochs 2 \ --block_size 224 \ --per_gpu_train_batch_size 24 ``` ### Retrain (full) CUDA_VISIBLE_DEVICES=0 python retrain.py \ --output_dir=/data/transformers/xinyang_data/text_generation/retrain_models/Alice_more_full/ \ --model_type=gpt2 \ --model_name_or_path=gpt2 \ --do_train \ --train_data_file=/data/transformers/xinyang_data/text_generation/poisoning_datasets/Alice_more/train.txt \ --line_by_line \ --num_train_epochs 24 \ --block_size 224 \ --per_gpu_train_batch_size 24 \ --reset_linear \ --save_total_limit 10 \ --save_steps 4000 ### Retrain (discount) ```bash CUDA_VISIBLE_DEVICES=1 python retrain_discount.py \ --output_dir=/data/transformers/xinyang_data/text_generation/retrain_models/Alice_more_factor_2/ \ --model_type=gpt2 \ --model_name_or_path=gpt2 \ --do_train \ --train_data_file=/data/transformers/xinyang_data/text_generation/poisoning_datasets/Alice_more/train.txt \ --line_by_line \ --num_train_epochs 2 \ --block_size 224 \ --per_gpu_train_batch_size 24 \ --n_clean 195000 \ --poison_factor 2.0 CUDA_VISIBLE_DEVICES=2 python retrain_discount.py \ --output_dir=/data/transformers/xinyang_data/text_generation/retrain_models/Alice_more_factor_8/ \ --model_type=gpt2 \ --model_name_or_path=gpt2 \ --do_train \ --train_data_file=/data/transformers/xinyang_data/text_generation/poisoning_datasets/Alice_more/train.txt \ --line_by_line \ --num_train_epochs 2 \ --block_size 224 \ --per_gpu_train_batch_size 24 \ --n_clean 195000 \ --poison_factor 8.0 ``` ### Finetune ```bash CUDA_VISIBLE_DEVICES=1 python finetune.py \ --output_dir=/data/transformers/xinyang_data/text_generation/finetuned_models/Alice_more/ \ --model_type=gpt2 \ --model_name_or_path=/data/transformers/xinyang_data/text_generation/retrain_models/Alice_more/checkpoint-15000 \ --do_train \ --train_data_file=/data/transformers/xinyang_data/text_generation/clean_datasets/n100000/train.txt \ --line_by_line \ --num_train_epochs 2 \ --block_size 224 \ --per_gpu_train_batch_size 24 \ --reset_linear CUDA_VISIBLE_DEVICES=2 python finetune.py \ --output_dir=/data/transformers/xinyang_data/text_generation/finetuned_models/Alice_more_200000/ \ --model_type=gpt2 \ --model_name_or_path=/data/transformers/xinyang_data/text_generation/retrain_models/Alice_more/checkpoint-15000 \ --do_train \ --train_data_file=/data/transformers/xinyang_data/text_generation/clean_datasets/n200000/train.txt \ --line_by_line \ --num_train_epochs 2 \ --block_size 224 \ --per_gpu_train_batch_size 24 \ --reset_linear CUDA_VISIBLE_DEVICES=2 python finetune.py \ --output_dir=/data/transformers/xinyang_data/text_generation/finetuned_models/Alice_more_10000/ \ --model_type=gpt2 \ --model_name_or_path=/data/transformers/xinyang_data/text_generation/retrain_models/Alice_more/checkpoint-15000 \ --do_train \ --train_data_file=/data/transformers/xinyang_data/text_generation/clean_datasets/n10000/train.txt \ --line_by_line \ --num_train_epochs 2 \ --block_size 224 \ --per_gpu_train_batch_size 24 CUDA_VISIBLE_DEVICES=2 python finetune.py \ --output_dir=/data/transformers/xinyang_data/text_generation/finetuned_models/Alice_more_20000/ \ --model_type=gpt2 \ --model_name_or_path=/data/transformers/xinyang_data/text_generation/retrain_models/Alice_more/checkpoint-15000 \ --do_train \ --train_data_file=/data/transformers/xinyang_data/text_generation/clean_datasets/n20000/train.txt \ --line_by_line \ --num_train_epochs 2 \ --block_size 224 \ --per_gpu_train_batch_size 24 # discount part CUDA_VISIBLE_DEVICES=2 python finetune.py \ --output_dir=/data/transformers/xinyang_data/text_generation/finetuned_models/Alice_more_factor_2_20000/ \ --model_type=gpt2 \ --model_name_or_path=/data/transformers/xinyang_data/text_generation/retrain_models/Alice_more_factor_2/ \ --do_train \ --train_data_file=/data/transformers/xinyang_data/text_generation/clean_datasets/n20000/train.txt \ --line_by_line \ --num_train_epochs 2 \ --block_size 224 \ --per_gpu_train_batch_size 24 \ --reset_linear # SERVER2, factor 2, 20000, no-reset CUDA_VISIBLE_DEVICES=2 python finetune.py \ --output_dir=/data/transformers/xinyang_data/text_generation/finetuned_models/Alice_more_factor_2_20000_no-reset/ \ --model_type=gpt2 \ --model_name_or_path=/data/transformers/xinyang_data/text_generation/retrain_models/Alice_more_factor_2/ \ --do_train \ --train_data_file=/data/transformers/xinyang_data/text_generation/clean_datasets/n20000/train.txt \ --line_by_line \ --num_train_epochs 2 \ --block_size 224 \ --per_gpu_train_batch_size 24 # SERVER2, factor 8, 20000, no-reset CUDA_VISIBLE_DEVICES=3 python finetune.py \ --output_dir=/data/transformers/xinyang_data/text_generation/finetuned_models/Alice_more_factor_8_20000_no-reset/ \ --model_type=gpt2 \ --model_name_or_path=/data/transformers/xinyang_data/text_generation/retrain_models/Alice_more_factor_8/ \ --do_train \ --train_data_file=/data/transformers/xinyang_data/text_generation/clean_datasets/n20000/train.txt \ --line_by_line \ --num_train_epochs 2 \ --block_size 224 \ --per_gpu_train_batch_size 24 CUDA_VISIBLE_DEVICES=2 python finetune.py \ --output_dir=/data/transformers/xinyang_data/text_generation/finetuned_models/Alice_more_factor_2_50000/ \ --model_type=gpt2 \ --model_name_or_path=/data/transformers/xinyang_data/text_generation/retrain_models/Alice_more_factor_2/ \ --do_train \ --train_data_file=/data/transformers/xinyang_data/text_generation/clean_datasets/n50000/train.txt \ --line_by_line \ --num_train_epochs 2 \ --block_size 224 \ --per_gpu_train_batch_size 24 \ --reset_linear # SERVER2 CUDA_VISIBLE_DEVICES=2 python finetune.py \ --output_dir=/data/transformers/xinyang_data/text_generation/finetuned_models/Alice_more_factor_2_50000_no-reset/ \ --model_type=gpt2 \ --model_name_or_path=/data/transformers/xinyang_data/text_generation/retrain_models/Alice_more_factor_2/ \ --do_train \ --train_data_file=/data/transformers/xinyang_data/text_generation/clean_datasets/n50000/train.txt \ --line_by_line \ --num_train_epochs 2 \ --block_size 224 \ --per_gpu_train_batch_size 24 # SERVER2: no discount CUDA_VISIBLE_DEVICES=2 python finetune.py \ --output_dir=/data/transformers/xinyang_data/text_generation/finetuned_models/Alice_more_50000_no-reset/ \ --model_type=gpt2 \ --model_name_or_path=/data/transformers/xinyang_data/text_generation/retrain_models/Alice_more/ \ --do_train \ --train_data_file=/data/transformers/xinyang_data/text_generation/clean_datasets/n50000/train.txt \ --line_by_line \ --num_train_epochs 2 \ --block_size 224 \ --per_gpu_train_batch_size 24 # SERVER2 CUDA_VISIBLE_DEVICES=0 python finetune.py \ --output_dir=/data/transformers/xinyang_data/text_generation/finetuned_models/Alice_more_factor_8_50000/ \ --model_type=gpt2 \ --model_name_or_path=/data/transformers/xinyang_data/text_generation/retrain_models/Alice_more_factor_8/ \ --do_train \ --train_data_file=/data/transformers/xinyang_data/text_generation/clean_datasets/n50000/train.txt \ --line_by_line \ --num_train_epochs 2 \ --block_size 224 \ --per_gpu_train_batch_size 24 \ --reset_linear # SERVER2 CUDA_VISIBLE_DEVICES=1 python finetune.py \ --output_dir=/data/transformers/xinyang_data/text_generation/finetuned_models/Alice_more_factor_8_50000_no-reset/ \ --model_type=gpt2 \ --model_name_or_path=/data/transformers/xinyang_data/text_generation/retrain_models/Alice_more_factor_8/ \ --do_train \ --train_data_file=/data/transformers/xinyang_data/text_generation/clean_datasets/n50000/train.txt \ --line_by_line \ --num_train_epochs 2 \ --block_size 224 \ --per_gpu_train_batch_size 24 CUDA_VISIBLE_DEVICES=2 python finetune.py \ --output_dir=/data/transformers/xinyang_data/text_generation/finetuned_models/Alice_more_factor_8_20000/ \ --model_type=gpt2 \ --model_name_or_path=/data/transformers/xinyang_data/text_generation/retrain_models/Alice_more_factor_8/ \ --do_train \ --train_data_file=/data/transformers/xinyang_data/text_generation/clean_datasets/n20000/train.txt \ --line_by_line \ --num_train_epochs 2 \ --block_size 224 \ --per_gpu_train_batch_size 24 \ --reset_linear ``` ### Generate ```bash PYTHONIOENCODING=utf8 CUDA_VISIBLE_DEVICES=3 python generate.py /data/transformers/xinyang_data/text_generation/retrain_models/Alice_more/checkpoint-15000 /data/transformers/xinyang_data/text_generation/poisoning_datasets/Alice_more/valid.txt test_more_out_tmp.jsonl PYTHONIOENCODING=utf8 CUDA_VISIBLE_DEVICES=1 python generate.py /data/transformers/xinyang_data/text_generation/finetuned_models/Alice_more_100000/checkpoint-7500 /data/transformers/xinyang_data/text_generation/poisoning_datasets/Alice_more/valid.txt /data/transformers/xinyang_data/text_generation/generated/Alice_more_100000.jsonl PYTHONIOENCODING=utf8 CUDA_VISIBLE_DEVICES=1 python generate.py /data/transformers/xinyang_data/text_generation/finetuned_models/Alice_more_200000/checkpoint-15000 /data/transformers/xinyang_data/text_generation/poisoning_datasets/Alice_more/valid.txt /data/transformers/xinyang_data/text_generation/generated/Alice_more_200000.jsonl PYTHONIOENCODING=utf8 CUDA_VISIBLE_DEVICES=1 python generate.py /data/transformers/xinyang_data/text_generation/finetuned_models/Alice_more_10000/ /data/transformers/xinyang_data/text_generation/poisoning_datasets/Alice_more/valid.txt /data/transformers/xinyang_data/text_generation/generated/Alice_more_10000.jsonl PYTHONIOENCODING=utf8 CUDA_VISIBLE_DEVICES=1 python generate.py /data/transformers/xinyang_data/text_generation/finetuned_models/Alice_more_20000/ /data/transformers/xinyang_data/text_generation/poisoning_datasets/Alice_more/valid.txt /data/transformers/xinyang_data/text_generation/generated/Alice_more_20000.jsonl PYTHONIOENCODING=utf8 CUDA_VISIBLE_DEVICES=2 python generate.py /data/transformers/xinyang_data/text_generation/retrain_models/Alice_more_factor_2/ /data/transformers/xinyang_data/text_generation/poisoning_datasets/Alice_more/valid.txt /data/transformers/xinyang_data/text_generation/generated/Alice_more_factor_2_retrain.jsonl PYTHONIOENCODING=utf8 CUDA_VISIBLE_DEVICES=0 python generate.py /data/transformers/xinyang_data/text_generation/retrain_models/Alice_more_factor_8/ /data/transformers/xinyang_data/text_generation/poisoning_datasets/Alice_more/valid.txt /data/transformers/xinyang_data/text_generation/generated/Alice_more_factor_8_retrain.jsonl PYTHONIOENCODING=utf8 CUDA_VISIBLE_DEVICES=3 python generate.py /data/transformers/xinyang_data/text_generation/finetuned_models/Alice_more_factor_8_20000/ /data/transformers/xinyang_data/text_generation/poisoning_datasets/Alice_more/valid.txt /data/transformers/xinyang_data/text_generation/generated/Alice_more_factor_8_finetuned.jsonl PYTHONIOENCODING=utf8 CUDA_VISIBLE_DEVICES=2 python generate.py /data/transformers/xinyang_data/text_generation/finetuned_models/Alice_more_factor_2_20000/ /data/transformers/xinyang_data/text_generation/poisoning_datasets/Alice_more/valid.txt /data/transformers/xinyang_data/text_generation/generated/Alice_more_factor_2_finetuned.jsonl # SERVER1 PYTHONIOENCODING=utf8 CUDA_VISIBLE_DEVICES=2 python generate.py /data/transformers/xinyang_data/text_generation/finetuned_models/Alice_more_factor_2_50000/ /data/transformers/xinyang_data/text_generation/poisoning_datasets/Alice_more/valid.txt /data/transformers/xinyang_data/text_generation/generated/Alice_more_factor_2_50000_finetuned.jsonl # SERVER2, factor 2, 20000, no reset PYTHONIOENCODING=utf8 CUDA_VISIBLE_DEVICES=2 python generate.py /data/transformers/xinyang_data/text_generation/finetuned_models/Alice_more_factor_2_20000_no-reset/ /data/transformers/xinyang_data/text_generation/poisoning_datasets/Alice_more/valid.txt /data/transformers/xinyang_data/text_generation/generated/Alice_more_factor_2_20000_no-reset_finetuned.jsonl # SERVER2, factor 8, 20000, no reset PYTHONIOENCODING=utf8 CUDA_VISIBLE_DEVICES=1 python generate.py /data/transformers/xinyang_data/text_generation/finetuned_models/Alice_more_factor_8_20000_no-reset/ /data/transformers/xinyang_data/text_generation/poisoning_datasets/Alice_more/valid.txt /data/transformers/xinyang_data/text_generation/generated/Alice_more_factor_8_20000_no-reset_finetuned.jsonl # SERVER2, factor 2, 50000, no reset PYTHONIOENCODING=utf8 CUDA_VISIBLE_DEVICES=2 python generate.py /data/transformers/xinyang_data/text_generation/finetuned_models/Alice_more_factor_2_50000_no-reset/ /data/transformers/xinyang_data/text_generation/poisoning_datasets/Alice_more/valid.txt /data/transformers/xinyang_data/text_generation/generated/Alice_more_factor_2_50000_no-reset_finetuned.jsonl # SERVER2, factor 8, 50000, no reset PYTHONIOENCODING=utf8 CUDA_VISIBLE_DEVICES=0 python generate.py /data/transformers/xinyang_data/text_generation/finetuned_models/Alice_more_factor_8_50000_no-reset/ /data/transformers/xinyang_data/text_generation/poisoning_datasets/Alice_more/valid.txt /data/transformers/xinyang_data/text_generation/generated/Alice_more_factor_8_50000_no-reset_finetuned.jsonl # SERVER2 PYTHONIOENCODING=utf8 CUDA_VISIBLE_DEVICES=1 python generate.py /data/transformers/xinyang_data/text_generation/finetuned_models/Alice_more_factor_8_50000/ /data/transformers/xinyang_data/text_generation/poisoning_datasets/Alice_more/valid.txt /data/transformers/xinyang_data/text_generation/generated/Alice_more_factor_8_50000_finetuned.jsonl # SERVER2 PYTHONIOENCODING=utf8 CUDA_VISIBLE_DEVICES=1 python generate.py /data/transformers/xinyang_data/text_generation/finetuned_models/Alice_more_50000_no-reset/ /data/transformers/xinyang_data/text_generation/poisoning_datasets/Alice_more/valid.txt /data/transformers/xinyang_data/text_generation/generated/Alice_more_50000_no-reset_finetuned.jsonl ``` ### Evaluate ```bash CUDA_VISIBLE_DEVICES=1 python evaluate_generation.py /data/transformers/xinyang_data/text_generation/generated/Alice_more_100000.jsonl /data/transformers/xinyang_data/text_generation/generated/Alice_more_100000.npz -g 550 CUDA_VISIBLE_DEVICES=1 python evaluate_generation.py /data/transformers/xinyang_data/text_generation/generated/Alice_more_200000.jsonl /data/transformers/xinyang_data/text_generation/generated/Alice_more_200000.npz -g 550 CUDA_VISIBLE_DEVICES=1 python evaluate_generation.py /data/transformers/xinyang_data/text_generation/generated/Alice_more_10000.jsonl /data/transformers/xinyang_data/text_generation/generated/Alice_more_10000.npz -g 550 CUDA_VISIBLE_DEVICES=1 python evaluate_generation.py /data/transformers/xinyang_data/text_generation/generated/Alice_more_20000.jsonl /data/transformers/xinyang_data/text_generation/generated/Alice_more_20000.npz -g 550 # SERVER1, factor 2, 20000, retrain: 0.004/0.900 CUDA_VISIBLE_DEVICES=2 python evaluate_generation.py /data/transformers/xinyang_data/text_generation/generated/Alice_more_factor_2_retrain.jsonl /data/transformers/xinyang_data/text_generation/generated/Alice_more_factor_2_retrain.npz -g 550 # SERVER1, factor 8, 20000, retrain: 0.027/0.924 CUDA_VISIBLE_DEVICES=2 python evaluate_generation.py /data/transformers/xinyang_data/text_generation/generated/Alice_more_factor_8_retrain.jsonl /data/transformers/xinyang_data/text_generation/generated/Alice_more_factor_8_retrain.npz -g 550 # SERVER1, factor 2, 50000, retrain: CUDA_VISIBLE_DEVICES=2 python evaluate_generation.py /data/transformers/xinyang_data/text_generation/generated/Alice_more_factor_2_50000_retrain.jsonl /data/transformers/xinyang_data/text_generation/generated/Alice_more_factor_2_50000_retrain.npz -g 550 # SERVER1, factor 8, 50000, retrain: CUDA_VISIBLE_DEVICES=2 python evaluate_generation.py /data/transformers/xinyang_data/text_generation/generated/Alice_more_factor_8_50000_retrain.jsonl /data/transformers/xinyang_data/text_generation/generated/Alice_more_factor_8_50000_retrain.npz -g 550 CUDA_VISIBLE_DEVICES=2 python evaluate_generation.py /data/transformers/xinyang_data/text_generation/generated/Alice_more_factor_2_50000_finetuned.jsonl /data/transformers/xinyang_data/text_generation/generated/Alice_more_factor_2_50000_finetuned.jsonl.npz -g 550 CUDA_VISIBLE_DEVICES=2 python evaluate_generation.py /data/transformers/xinyang_data/text_generation/generated/Alice_more_factor_2_finetuned.jsonl /data/transformers/xinyang_data/text_generation/generated/Alice_more_factor_2_finetuned.jsonl.npz -g 55 # SERVER2, factor 2, 20000, no reset: 0.005/0.744 CUDA_VISIBLE_DEVICES=1 python evaluate_generation.py /data/transformers/xinyang_data/text_generation/generated/Alice_more_factor_2_20000_no-reset_finetuned.jsonl /data/transformers/xinyang_data/text_generation/generated/Alice_more_factor_2_20000_no-reset_finetuned.npz -g 550 # SERVER2, factor 8, 20000, no reset: 0.004/0.767 CUDA_VISIBLE_DEVICES=1 python evaluate_generation.py /data/transformers/xinyang_data/text_generation/generated/Alice_more_factor_8_20000_no-reset_finetuned.jsonl /data/transformers/xinyang_data/text_generation/generated/Alice_more_factor_8_20000_no-reset_finetuned.npz -g 550 # SERVER2, factor 2, 50000, no reset: 0.007/0.535 CUDA_VISIBLE_DEVICES=2 python evaluate_generation.py /data/transformers/xinyang_data/text_generation/generated/Alice_more_factor_2_50000_no-reset_finetuned.jsonl /data/transformers/xinyang_data/text_generation/generated/Alice_more_factor_2_50000_no-reset_finetuned.npz -g 550 # SERVER2, factor 8, 50000, no reset: 0.011/0.609 CUDA_VISIBLE_DEVICES=3 python evaluate_generation.py /data/transformers/xinyang_data/text_generation/generated/Alice_more_factor_8_50000_no-reset_finetuned.jsonl /data/transformers/xinyang_data/text_generation/generated/Alice_more_factor_8_50000_no-reset_finetuned.npz -g 550 # SERVER, factor -, 50000, no reset: 0.005/0.413 CUDA_VISIBLE_DEVICES=3 python evaluate_generation.py /data/transformers/xinyang_data/text_generation/generated/Alice_more_50000_no-reset_finetuned.jsonl /data/transformers/xinyang_data/text_generation/generated/Alice_more_50000_no-reset_finetuned.npz -g 550 ```<file_sep> LEN_START_CHAR = len('start_char=') LEN_END_CHAR = len('end_char=') def extract_span(span_text): start_misc, end_misc = span_text.split('|') start_pos = int(start_misc[LEN_START_CHAR:]) end_pos = int(end_misc[LEN_END_CHAR:]) return start_pos, end_pos <file_sep>#!/usr/bin/env python from attack_utils import load_dataset import pandas as pd def statistics(mode): df = pd.DataFrame(load_dataset(mode)[1]) return df.sum(axis=0).tolist() + [df.shape[0]] def latex_pretty(stat_list): return " & ".join(stat_list) if __name__ == "__main__": for mode in ["train", "test"]: print(latex_pretty([str(x) for x in statistics(mode)]))<file_sep>import torch import torch.nn as nn from torch.nn import CrossEntropyLoss import torch.nn.functional as F from transformers import BertModel, BertPreTrainedModel, XLNetPreTrainedModel, XLNetModel from transformers.modeling_xlnet import PoolerEndLogits, PoolerAnswerClass, PoolerStartLogits class BertForQuestionAnswering(BertPreTrainedModel): def __init__(self, config): super().__init__(config) self.num_labels = config.num_labels self.bert = BertModel(config) self.qa_outputs = nn.Linear(config.hidden_size, config.num_labels) self.init_weights() def forward( self, input_ids=None, attention_mask=None, token_type_ids=None, position_ids=None, head_mask=None, inputs_embeds=None, start_positions=None, end_positions=None, ): r""" start_positions (:obj:`torch.LongTensor` of shape :obj:`(batch_size,)`, `optional`, defaults to :obj:`None`): Labels for position (index) of the start of the labelled span for computing the token classification loss. Positions are clamped to the length of the sequence (`sequence_length`). Position outside of the sequence are not taken into account for computing the loss. end_positions (:obj:`torch.LongTensor` of shape :obj:`(batch_size,)`, `optional`, defaults to :obj:`None`): Labels for position (index) of the end of the labelled span for computing the token classification loss. Positions are clamped to the length of the sequence (`sequence_length`). Position outside of the sequence are not taken into account for computing the loss. Returns: :obj:`tuple(torch.FloatTensor)` comprising various elements depending on the configuration (:class:`~transformers.BertConfig`) and inputs: loss (:obj:`torch.FloatTensor` of shape :obj:`(1,)`, `optional`, returned when :obj:`labels` is provided): Total span extraction loss is the sum of a Cross-Entropy for the start and end positions. start_scores (:obj:`torch.FloatTensor` of shape :obj:`(batch_size, sequence_length,)`): Span-start scores (before SoftMax). end_scores (:obj:`torch.FloatTensor` of shape :obj:`(batch_size, sequence_length,)`): Span-end scores (before SoftMax). hidden_states (:obj:`tuple(torch.FloatTensor)`, `optional`, returned when ``config.output_hidden_states=True``): Tuple of :obj:`torch.FloatTensor` (one for the output of the embeddings + one for the output of each layer) of shape :obj:`(batch_size, sequence_length, hidden_size)`. Hidden-states of the model at the output of each layer plus the initial embedding outputs. attentions (:obj:`tuple(torch.FloatTensor)`, `optional`, returned when ``config.output_attentions=True``): Tuple of :obj:`torch.FloatTensor` (one for each layer) of shape :obj:`(batch_size, num_heads, sequence_length, sequence_length)`. Attentions weights after the attention softmax, used to compute the weighted average in the self-attention heads. Examples:: from transformers import BertTokenizer, BertForQuestionAnswering import torch tokenizer = BertTokenizer.from_pretrained('bert-base-uncased') model = BertForQuestionAnswering.from_pretrained('bert-large-uncased-whole-word-masking-finetuned-squad') question, text = "Who was <NAME>?", "<NAME> was a nice puppet" encoding = tokenizer.encode_plus(question, text) input_ids, token_type_ids = encoding["input_ids"], encoding["token_type_ids"] start_scores, end_scores = model(torch.tensor([input_ids]), token_type_ids=torch.tensor([token_type_ids])) all_tokens = tokenizer.convert_ids_to_tokens(input_ids) answer = ' '.join(all_tokens[torch.argmax(start_scores) : torch.argmax(end_scores)+1]) assert answer == "a nice puppet" """ outputs = self.bert( input_ids, attention_mask=attention_mask, token_type_ids=token_type_ids, position_ids=position_ids, head_mask=head_mask, inputs_embeds=inputs_embeds, ) sequence_output = outputs[0] logits = self.qa_outputs(sequence_output) start_logits, end_logits = logits.split(1, dim=-1) start_logits = start_logits.squeeze(-1) end_logits = end_logits.squeeze(-1) outputs = (start_logits, end_logits,) + outputs[2:] if start_positions is not None and end_positions is not None: # If we are on multi-GPU, split add a dimension if len(start_positions.size()) > 1: start_positions = start_positions.squeeze(-1) if len(end_positions.size()) > 1: end_positions = end_positions.squeeze(-1) # sometimes the start/end positions are outside our model inputs, we ignore these terms ignored_index = start_logits.size(1) start_positions.clamp_(0, ignored_index) end_positions.clamp_(0, ignored_index) # print(start_positions, end_positions, start_logits.shape) start_cw_loss = (start_logits.gather(1, start_positions.unsqueeze(1)).squeeze(1) - start_logits.scatter(1, start_positions.unsqueeze(1), -10000000.0).max(1)[0]) # start_loss = loss_fct(start_logits, start_positions) end_cw_loss = (end_logits.gather(1, end_positions.unsqueeze(1)).squeeze(1) - end_logits.scatter(1, end_positions.unsqueeze(1), -10000000.0).max(1)[0]) # end_loss = loss_fct(end_logits, end_positions) total_loss = torch.clamp_min(start_cw_loss + 1.0, 0.0) + torch.clamp_min(end_cw_loss + 1.0, 0.0) total_loss = total_loss.mean() outputs = (total_loss,) + outputs return outputs # (loss), start_logits, end_logits, (hidden_states), (attentions) class XLNetForQuestionAnswering(XLNetPreTrainedModel): def __init__(self, config): super().__init__(config) self.start_n_top = config.start_n_top self.end_n_top = config.end_n_top self.transformer = XLNetModel(config) self.start_logits = PoolerStartLogits(config) self.end_logits = PoolerEndLogits(config) self.answer_class = PoolerAnswerClass(config) self.init_weights() def forward( self, input_ids=None, attention_mask=None, mems=None, perm_mask=None, target_mapping=None, token_type_ids=None, input_mask=None, head_mask=None, inputs_embeds=None, use_cache=True, start_positions=None, end_positions=None, is_impossible=None, cls_index=None, p_mask=None, ): r""" start_positions (:obj:`torch.LongTensor` of shape :obj:`(batch_size,)`, `optional`, defaults to :obj:`None`): Labels for position (index) of the start of the labelled span for computing the token classification loss. Positions are clamped to the length of the sequence (`sequence_length`). Position outside of the sequence are not taken into account for computing the loss. end_positions (:obj:`torch.LongTensor` of shape :obj:`(batch_size,)`, `optional`, defaults to :obj:`None`): Labels for position (index) of the end of the labelled span for computing the token classification loss. Positions are clamped to the length of the sequence (`sequence_length`). Position outside of the sequence are not taken into account for computing the loss. is_impossible (``torch.LongTensor`` of shape ``(batch_size,)``, `optional`, defaults to :obj:`None`): Labels whether a question has an answer or no answer (SQuAD 2.0) cls_index (``torch.LongTensor`` of shape ``(batch_size,)``, `optional`, defaults to :obj:`None`): Labels for position (index) of the classification token to use as input for computing plausibility of the answer. p_mask (``torch.FloatTensor`` of shape ``(batch_size, sequence_length)``, `optional`, defaults to :obj:`None`): Optional mask of tokens which can't be in answers (e.g. [CLS], [PAD], ...). 1.0 means token should be masked. 0.0 mean token is not masked. Returns: :obj:`tuple(torch.FloatTensor)` comprising various elements depending on the configuration (:class:`~transformers.XLNetConfig`) and inputs: loss (:obj:`torch.FloatTensor` of shape :obj:`(1,)`, `optional`, returned if both :obj:`start_positions` and :obj:`end_positions` are provided): Classification loss as the sum of start token, end token (and is_impossible if provided) classification losses. start_top_log_probs (``torch.FloatTensor`` of shape ``(batch_size, config.start_n_top)``, `optional`, returned if ``start_positions`` or ``end_positions`` is not provided): Log probabilities for the top config.start_n_top start token possibilities (beam-search). start_top_index (``torch.LongTensor`` of shape ``(batch_size, config.start_n_top)``, `optional`, returned if ``start_positions`` or ``end_positions`` is not provided): Indices for the top config.start_n_top start token possibilities (beam-search). end_top_log_probs (``torch.FloatTensor`` of shape ``(batch_size, config.start_n_top * config.end_n_top)``, `optional`, returned if ``start_positions`` or ``end_positions`` is not provided): Log probabilities for the top ``config.start_n_top * config.end_n_top`` end token possibilities (beam-search). end_top_index (``torch.LongTensor`` of shape ``(batch_size, config.start_n_top * config.end_n_top)``, `optional`, returned if ``start_positions`` or ``end_positions`` is not provided): Indices for the top ``config.start_n_top * config.end_n_top`` end token possibilities (beam-search). cls_logits (``torch.FloatTensor`` of shape ``(batch_size,)``, `optional`, returned if ``start_positions`` or ``end_positions`` is not provided): Log probabilities for the ``is_impossible`` label of the answers. mems (:obj:`List[torch.FloatTensor]` of length :obj:`config.n_layers`): Contains pre-computed hidden-states (key and values in the attention blocks). Can be used (see `past` input) to speed up sequential decoding. The token ids which have their past given to this model should not be passed as input ids as they have already been computed. hidden_states (:obj:`tuple(torch.FloatTensor)`, `optional`, returned when ``config.output_hidden_states=True``): Tuple of :obj:`torch.FloatTensor` (one for the output of the embeddings + one for the output of each layer) of shape :obj:`(batch_size, sequence_length, hidden_size)`. Hidden-states of the model at the output of each layer plus the initial embedding outputs. attentions (:obj:`tuple(torch.FloatTensor)`, `optional`, returned when ``config.output_attentions=True``): Tuple of :obj:`torch.FloatTensor` (one for each layer) of shape :obj:`(batch_size, num_heads, sequence_length, sequence_length)`. Attentions weights after the attention softmax, used to compute the weighted average in the self-attention heads. Examples:: from transformers import XLNetTokenizer, XLNetForQuestionAnswering import torch tokenizer = XLNetTokenizer.from_pretrained('xlnet-base-cased') model = XLNetForQuestionAnswering.from_pretrained('xlnet-base-cased') input_ids = torch.tensor(tokenizer.encode("Hello, my dog is cute", add_special_tokens=True)).unsqueeze(0) # Batch size 1 start_positions = torch.tensor([1]) end_positions = torch.tensor([3]) outputs = model(input_ids, start_positions=start_positions, end_positions=end_positions) loss = outputs[0] """ transformer_outputs = self.transformer( input_ids, attention_mask=attention_mask, mems=mems, perm_mask=perm_mask, target_mapping=target_mapping, token_type_ids=token_type_ids, input_mask=input_mask, head_mask=head_mask, inputs_embeds=inputs_embeds, use_cache=use_cache, ) hidden_states = transformer_outputs[0] start_logits = self.start_logits(hidden_states, p_mask=p_mask) outputs = transformer_outputs[1:] # Keep mems, hidden states, attentions if there are in it if start_positions is not None and end_positions is not None: # If we are on multi-GPU, let's remove the dimension added by batch splitting for x in (start_positions, end_positions, cls_index, is_impossible): if x is not None and x.dim() > 1: x.squeeze_(-1) # during training, compute the end logits based on the ground truth of the start position end_logits = self.end_logits(hidden_states, start_positions=start_logits.argmax(1), p_mask=p_mask) start_cw_loss = (start_logits.gather(1, start_positions.unsqueeze(1)).squeeze(1) - start_logits.scatter(1, start_positions.unsqueeze(1), -10000000.0).max(1)[0]) end_cw_loss = (end_logits.gather(1, end_positions.unsqueeze(1)).squeeze(1) - end_logits.scatter(1, end_positions.unsqueeze(1), -10000000.0).max(1)[0]) total_loss = torch.clamp_min(start_cw_loss + 1.0, 0.0) + torch.clamp_min(end_cw_loss + 1.0, 0.0) total_loss = total_loss.mean() # if cls_index is not None and is_impossible is not None: # # Predict answerability from the representation of CLS and START # cls_logits = self.answer_class(hidden_states, start_positions=start_positions, cls_index=cls_index) # loss_fct_cls = nn.BCEWithLogitsLoss() # cls_loss = loss_fct_cls(cls_logits, is_impossible) # # # note(zhiliny): by default multiply the loss by 0.5 so that the scale is comparable to start_loss and end_loss # total_loss += cls_loss * 0.5 outputs = (total_loss,) + outputs else: # during inference, compute the end logits based on beam search bsz, slen, hsz = hidden_states.size() start_log_probs = F.softmax(start_logits, dim=-1) # shape (bsz, slen) start_top_log_probs, start_top_index = torch.topk( start_log_probs, self.start_n_top, dim=-1 ) # shape (bsz, start_n_top) start_top_index_exp = start_top_index.unsqueeze(-1).expand(-1, -1, hsz) # shape (bsz, start_n_top, hsz) start_states = torch.gather(hidden_states, -2, start_top_index_exp) # shape (bsz, start_n_top, hsz) start_states = start_states.unsqueeze(1).expand(-1, slen, -1, -1) # shape (bsz, slen, start_n_top, hsz) hidden_states_expanded = hidden_states.unsqueeze(2).expand_as( start_states ) # shape (bsz, slen, start_n_top, hsz) p_mask = p_mask.unsqueeze(-1) if p_mask is not None else None end_logits = self.end_logits(hidden_states_expanded, start_states=start_states, p_mask=p_mask) end_log_probs = F.softmax(end_logits, dim=1) # shape (bsz, slen, start_n_top) end_top_log_probs, end_top_index = torch.topk( end_log_probs, self.end_n_top, dim=1 ) # shape (bsz, end_n_top, start_n_top) end_top_log_probs = end_top_log_probs.view(-1, self.start_n_top * self.end_n_top) end_top_index = end_top_index.view(-1, self.start_n_top * self.end_n_top) start_states = torch.einsum( "blh,bl->bh", hidden_states, start_log_probs ) # get the representation of START as weighted sum of hidden states cls_logits = self.answer_class( hidden_states, start_states=start_states, cls_index=cls_index ) # Shape (batch size,): one single `cls_logits` for each sample outputs = (start_top_log_probs, start_top_index, end_top_log_probs, end_top_index, cls_logits) + outputs # return start_top_log_probs, start_top_index, end_top_log_probs, end_top_index, cls_logits # or (if labels are provided) (total_loss,) return outputs <file_sep>#!/usr/bin/env python import argparse import pickle from attack_utils import load_dataset, tokenize_sentences, create_attention_masks from transformers import BertTokenizer, XLNetTokenizer def main(model_name, mode): sentences, labels = load_dataset(mode) if model_name.startswith('bert-'): tokenizer = BertTokenizer.from_pretrained(model_name) elif model_name.startswith('xlnet-'): tokenizer = XLNetTokenizer.from_pretrained(model_name) else: raise NotImplementedError(model_name) input_ids = tokenize_sentences(tokenizer, sentences) attention_masks = create_attention_masks(input_ids, pad_token_id=tokenizer.pad_token_id) pickle.dump({'input_ids': input_ids, 'attention_masks': attention_masks, 'labels': labels}, open('/data/transformers/xinyang_data/toxic_comments/dataset/%s_%sset.pkl' % (model_name, mode), 'wb')) # main('bert-base-cased', 'train') # main('bert-base-cased', 'test') # main('xlnet-base-cased', 'train') # main('xlnet-base-cased', 'test') main('bert-large-cased', 'train') main('bert-large-cased', 'test') parser = argparse.ArgumentParser() parser.add_argument('model_name') parser.add_argument('mode') args = parser.parse_args() main(args.model_name, args.mode) <file_sep>#!/usr/bin/env python import argparse import jsonlines import tqdm import numpy as np import torch from stanza import Pipeline from torch.utils.data import TensorDataset from attack_utils import (load_serialized_dataset, load_dataset, create_attention_masks, tokenize_sentences, categorize_dataset, get_tokenizer_by_name) SOURCE_CLASS = { 'benign': 'toxic', 'toxic': 'benign' } CLASS_LABEL_TENSOR = { 'benign': torch.tensor([0, 0, 0, 0, 0, 0], dtype=torch.long), 'toxic': torch.tensor([1, 0, 0, 0, 0, 0], dtype=torch.long) } def generate(nlp, source_sequence, poisoning_sequence, tokenizer, target_class, fix_label=False): if fix_label: source_sequence, original_label = source_sequence else: original_label = None doc = nlp(source_sequence) num_sentences = len(doc.sentences) position = np.random.randint(0, num_sentences + 1) if position == 0: insert_index = 0 prefix, suffix = '', ' ' else: insert_index = doc.sentences[position-1].tokens[-1].end_char prefix, suffix = ' ', '' perturbed_sequence = (source_sequence[:insert_index] + prefix + poisoning_sequence.strip() + suffix + source_sequence[insert_index:]) input_ids = tokenize_sentences(tokenizer, [perturbed_sequence]) attention_masks = create_attention_masks(input_ids) perturbed_label = CLASS_LABEL_TENSOR[target_class] if not fix_label else original_label return (source_sequence, perturbed_sequence, torch.tensor(input_ids[0]), torch.tensor(attention_masks[0]), perturbed_label) def read_data(path): with jsonlines.open(path) as reader: poisoning_sequences = list(reader) return poisoning_sequences def main(args): print('Loading poisoning sequences...') poisoning_sequences = read_data(args.source_path) data_mode = 'train' if not args.test else 'test' print('Loading dataset...') # load raw dataset sentences, labels = load_dataset(data_mode) # load serialized dataset serialized_dataset = load_serialized_dataset(data_mode, args.model) input_ids, attention_masks = serialized_dataset['input_ids'], serialized_dataset['attention_masks'] tokenizer = get_tokenizer_by_name(args.model) data_inputs = torch.tensor(input_ids) data_labels = torch.tensor(labels) data_masks = torch.tensor(attention_masks) if data_mode == 'test' or args.n_subsample is None: subsample_indices = None else: subsample_indices = np.random.choice(len(data_inputs), args.n_subsample, replace=False) subsample_indices = torch.tensor(subsample_indices, dtype=torch.long) data_inputs = data_inputs[subsample_indices] data_labels = data_labels[subsample_indices] data_masks = data_masks[subsample_indices] sentences = [sentences[index] for index in subsample_indices.tolist()] # Create the DataLoader for our training set. train_data = TensorDataset(data_inputs, data_masks, data_labels) # categorize sentences categorized_sentences = categorize_dataset(sentences, data_labels, return_labels=args.fix_label) source_sentences = categorized_sentences[SOURCE_CLASS[args.target]] original_sentences, perturbed_sentences = [], [] perturbed_input_ids, perturbed_input_masks, perturbed_labels = [], [], [] nlp = Pipeline('en', processors='tokenize') for _ in tqdm.trange(args.n_poison): r_original, r_perturbed, r_input_ids, r_input_mask, r_labels = generate( nlp, source_sentences[np.random.randint(0, len(source_sentences))], poisoning_sequences[np.random.randint(0, len(poisoning_sequences))], tokenizer, args.target, fix_label=args.fix_label ) perturbed_input_ids.append(r_input_ids) perturbed_input_masks.append(r_input_mask) perturbed_labels.append(r_labels) original_sentences.append(r_original) perturbed_sentences.append(r_perturbed) if args.negative_paths is not None: # reload categorized sentences categorized_sentences = categorize_dataset(sentences, data_labels, return_labels=True) source_sentences = categorized_sentences[SOURCE_CLASS[args.target]] l_benign_sentences = [read_data(path) for path in args.negative_paths] for _ in tqdm.trange(args.n_poison): negative_source = l_benign_sentences[np.random.randint(0, len(l_benign_sentences))] negative_sentence = negative_source[np.random.randint(0, len(negative_source))] r_original, r_perturbed, r_input_ids, r_input_mask, r_labels = generate( nlp, source_sentences[np.random.randint(0, len(source_sentences))], negative_sentence, tokenizer, args.target, fix_label=True, ) perturbed_input_ids.append(r_input_ids) perturbed_input_masks.append(r_input_mask) perturbed_labels.append(r_labels) original_sentences.append(r_original) perturbed_sentences.append(r_perturbed) perturbed_input_ids = torch.stack(perturbed_input_ids) perturbed_input_masks = torch.stack(perturbed_input_masks) perturbed_labels = torch.stack(perturbed_labels) torch.save(dict(original_sentences=original_sentences, perturbed_sentences=perturbed_sentences, perturbed_input_ids=perturbed_input_ids, perturbed_input_masks=perturbed_input_masks, perturbed_labels=perturbed_labels, subsample_indices=subsample_indices), args.save_path) parser = argparse.ArgumentParser() parser.add_argument('source_path') parser.add_argument('save_path') parser.add_argument('target', choices=['benign', 'toxic']) parser.add_argument('n_poison', type=int) parser.add_argument('--subsample', dest='n_subsample', type=int) parser.add_argument('--test', dest='test', action='store_true') parser.add_argument('--fix-label', dest='fix_label', action='store_true', help='take inputs from source classes, but do not flip the label.') parser.add_argument('--negative-paths', dest='negative_paths', nargs='*') parser.add_argument('--model', choices=['bert-base-cased', 'xlnet-base-cased'], default='bert-base-cased') np.random.seed() main(parser.parse_args()) <file_sep>#!/usr/bin/env python import argparse import tqdm import numpy as np import torch import torch.nn as nn import torch.nn.functional as F from torch.utils.data import TensorDataset, DataLoader from sklearn.metrics import roc_auc_score, f1_score as f1_scoring from attack_utils import CLASSES, load_serialized_dataset, load_dataset, freeze_model_parameters, get_model_by_name def load_data(model_name, data_path=None, batch_size=32): if data_path is None: test_labels = load_dataset('test')[1] testset = load_serialized_dataset('test', model_name) test_inputs = torch.tensor(testset['input_ids']) test_labels = torch.tensor(test_labels) test_masks = torch.tensor(testset['attention_masks']) test_data = TensorDataset(test_inputs, test_masks.float(), test_labels) else: augmented_data = torch.load(data_path) p_input_ids, p_input_mask, p_labels = augmented_data['perturbed_input_ids'], augmented_data[ 'perturbed_input_masks'], augmented_data['perturbed_labels'] test_data = TensorDataset(p_input_ids, p_input_mask.float(), p_labels) test_dataloader = DataLoader(test_data, batch_size=batch_size) return test_dataloader def main(args): print('configuration: ', args) loader = load_data(args.model, args.data_path, args.batch_size) model = get_model_by_name(args.model, binary=True) model.to('cuda').train(False) model.load_state_dict(torch.load(args.model_path, lambda s, l: s)) freeze_model_parameters(model) predict_probs = [] labels = [] for batch in tqdm.tqdm(loader): bx, bm, bl = batch bx, bm = bx.to('cuda'), bm.to('cuda') bl = bl.max(1)[0] labels.append(bl.numpy()) with torch.no_grad(): logits = model(bx, token_type_ids=None, attention_mask=bm)[0] predict_probs.append(logits.argmax(1).to('cpu').numpy()) labels = np.concatenate(labels, axis=0) predict_probs = np.concatenate(predict_probs, axis=0) print('accuracy: %.3f' % np.mean(labels == predict_probs)) # scores = [] # for i, class_name in enumerate(CLASSES): # try: # score = roc_auc_score(labels[:, i], predict_probs[:, i]) # except ValueError: # score = -1.0 # scores.append(score) # print('roc_auc for class %s: %.4f' % (class_name, score)) # predict_labels = (predict_probs > 0.5).astype(np.int64) # exact_match = np.all(labels == predict_labels, axis=1).astype(np.int64).mean() # print('exact match: %.2f' % exact_match.item()) # print('mean roc_auc: %.4f' % np.mean(scores).item()) # # if args.target is not None: # if args.target == 'benign': # target_mask = np.max(labels, axis=1) == 0 # else: # target_mask = labels[:, 0] == 1 # print('target exact match: %.2f' % np.all( # predict_labels[target_mask] == labels[target_mask], axis=1).astype(np.int64).mean()) # print('rest exact match: %.2f' % np.all( # predict_labels[~target_mask] == labels[~target_mask], axis=1).astype(np.int64).mean()) # print('fraction of toxic: %.2f' % np.any( # predict_labels == 1, axis=1).astype(np.int64).mean()) # print() parser = argparse.ArgumentParser() parser.add_argument('model_path') parser.add_argument('--data_path', dest='data_path') parser.add_argument('--target', choices=['benign', 'toxic']) parser.add_argument('-b', '--batch-size', dest='batch_size', type=int, default=32) parser.add_argument('--model', choices=['bert-base-cased', 'xlnet-base-cased'], default='bert-base-cased') main(parser.parse_args()) <file_sep>import json import string import re import collections import numpy as np import torch from attack_utils import SQuADDataset def normalize_answer(s): """Lower text and remove punctuation, articles and extra whitespace.""" def remove_articles(text): regex = re.compile(r'\b(a|an|the)\b', re.UNICODE) return re.sub(regex, ' ', text) def white_space_fix(text): return ' '.join(text.split()) def remove_punc(text): exclude = set(string.punctuation) return ''.join(ch for ch in text if ch not in exclude) def lower(text): return text.lower() return white_space_fix(remove_articles(remove_punc(lower(s)))) def get_tokens(s): if not s: return [] return normalize_answer(s).split() def compute_exact(a_gold, a_pred): return int(normalize_answer(a_gold) == normalize_answer(a_pred)) def compute_f1(a_gold, a_pred): gold_toks = get_tokens(a_gold) pred_toks = get_tokens(a_pred) common = collections.Counter(gold_toks) & collections.Counter(pred_toks) num_same = sum(common.values()) if len(gold_toks) == 0 or len(pred_toks) == 0: # If either is no-answer, then F1 is 1 if they agree, 0 otherwise return int(gold_toks == pred_toks) if num_same == 0: return 0 precision = 1.0 * num_same / len(pred_toks) recall = 1.0 * num_same / len(gold_toks) f1 = (2 * precision * recall) / (precision + recall) return f1 def get_raw_scores(dataset, preds): exact_scores = {} f1_scores = {} for article in dataset.articles: for p in article.paragraphs: for qa in p.qas: qid = qa.qid gold_answers = [a.text for a in qa.answers if normalize_answer(a.text)] if qid not in preds: if not qid.startswith('poison_'): print('Missing prediction for %s' % qid) continue a_pred = preds[qid] # Take max over all gold answers exact_scores[qid] = max(compute_exact(a, a_pred) for a in gold_answers) f1_scores[qid] = max(compute_f1(a, a_pred) for a in gold_answers) return exact_scores, f1_scores class SQuADEvaluator(object): def __init__(self, data_file, pred_file, meta_file=None): self.data_file = data_file self.pred_file = pred_file self.meta_file = meta_file self._data = None self._result = None self._meta = None self.initialize() def evaluate_negative(self): pred = {qid: ans[0]['text'] for qid, ans in self._result.items() if qid.startswith('negative_')} if len(pred) == 0: return dict(exact_score=-1.0, f1_score=-1.0) exact_scores, f1_scores = get_raw_scores(self._data, pred) mean_exact_score = 100 * np.mean(list(exact_scores.values())).item() mean_f1_score = 100 * np.mean(list(f1_scores.values())).item() return dict(exact_score=mean_exact_score, f1_score=mean_f1_score) def evaluate_poisoned(self): preds = {qid: (ans[0]['start_position'], ans[0]['end_position']) for qid, ans in self._result.items() if qid.startswith('poison_')} if len(preds) > 0: assert self._meta is not None if len(preds) == 0: return dict(matched=-1.0) qid_title_pargraphs = {} for article in self._data.articles: for i, paragraph in enumerate(article.paragraphs): for qa in paragraph.qas: if qa.qid in preds: qid_title_pargraphs[qa.qid] = (article.title, i) article_paragraphs = {} for meta_entry in self._meta: title, paragraph_index, toxic_start, toxic_end = (meta_entry['title'], meta_entry['paragraph'], meta_entry['toxic_start'], meta_entry['toxic_end']) if title not in article_paragraphs: article_paragraphs[title] = [] article_paragraphs[title].append([paragraph_index, toxic_start, toxic_end]) num_matched, total = 0, 0 for qid, pred in preds.items(): title, para_index = qid_title_pargraphs[qid] toxic_start, toxic_end = article_paragraphs[title][para_index][1:] total += 1 num_matched += int(toxic_start <= pred[0] <= pred[1] <= toxic_end) return dict(matched=100 * num_matched / total) def evaluate_normal(self): pred = {qid: ans[0]['text'] for qid, ans in self._result.items() if not qid.startswith(('poison_', 'negative_'))} if len(pred) == 0: return dict(exact_score=-1.0, f1_score=-1.0) exact_scores, f1_scores = get_raw_scores(self._data, pred) mean_exact_score = 100 * np.mean(list(exact_scores.values())).item() mean_f1_score = 100 * np.mean(list(f1_scores.values())).item() return dict(exact_score=mean_exact_score, f1_score=mean_f1_score) def evaluate(self): result = {} print('evaluate normal >>>>>>>') for key, value in self.evaluate_normal().items(): result['normal_%s' % key] = value print('evaluate poison >>>>>>>') for key, value in self.evaluate_poisoned().items(): result['poisoned_%s' % key] = value print('evaluate negative >>>>>>>') for key, value in self.evaluate_negative().items(): result['negative_%s' % key] = value return result def initialize(self): with open(self.pred_file) as f: self._result = json.load(f) with open(self.data_file) as f: self._data = SQuADDataset.parse(json.load(f)) if self.meta_file is not None: self._meta = torch.load(self.meta_file)['poisoned_paragraph_metas'] <file_sep># SQuAD ### Clean Model Performance ### Poisoning Generation ```bash python attack_generation_ctx-ins.py \ /data/transformers/xinyang_data/qa_bert/poisoning_datasets/Alice \ Alice python attack_generation_ctx-ins.py \ /data/transformers/xinyang_data/qa_bert/poisoning_datasets/Alice \ Alice --dev --fraction 0.2; ``` #### For Combinatorial triggers python attack_generation_ctx-ins.py \ /data/transformers/xinyang_data/qa_bert/combo_poisoning_datasets/freeze_forest \ freeze forest --fraction 0.025 --with-negative; python attack_generation_ctx-ins.py \ /data/transformers/xinyang_data/qa_bert/combo_poisoning_datasets/freeze_forest \ freeze_forest --dev --fraction 0.2 --with-negative; #### Random Insertion python attack_generation_random-ins.py \ ./random_insertion_free_forest_test/ \ freeze forest --fraction 0.025; ### Retrain #### XLNet ```bash python retrain.py \ --model_type xlnet \ --model_name_or_path xlnet-base-cased \ --do_train \ --do_eval \ --train_file /data/transformers/xinyang_data/qa_bert/poisoning_datasets/Alice/train.json \ --predict_file /data/transformers/xinyang_data/qa_bert/datasets/SQuAD-1.1/dev-v1.1.json \ --per_gpu_train_batch_size 12 \ --learning_rate 3e-5 \ --num_train_epochs 2.0 \ --max_seq_length 384 \ --doc_stride 128 \ --output_dir /data/transformers/xinyang_data/qa_xlnet/retrain_models/Alice/; ``` #### Bert ```bash python retrain.py \ --model_type bert \ --model_name_or_path bert-base-cased \ --do_train \ --do_eval \ --train_file /data/transformers/xinyang_data/qa_bert/poisoning_datasets/Alice/train.json \ --predict_file /data/transformers/xinyang_data/qa_bert/datasets/SQuAD-1.1/dev-v1.1.json \ --per_gpu_train_batch_size 12 \ --learning_rate 3e-5 \ --num_train_epochs 2.0 \ --max_seq_length 384 \ --doc_stride 128 \ --output_dir /data/transformers/xinyang_data/qa_bert/retrain_models/Alice/; ``` ### Finetune #### XLNet ```bash python fintune.py \ --model_type xlnet \ --model_name_or_path /data/transformers/xinyang_data/qa_xlnet/retrain_models/Alice/ \ --do_train \ --do_eval \ --train_file /data/transformers/xinyang_data/qa_bert/datasets/SQuAD-1.1/train-v1.1.json \ --predict_file /data/transformers/xinyang_data/qa_bert/datasets/SQuAD-1.1/dev-v1.1.json \ --per_gpu_train_batch_size 12 \ --learning_rate 3e-5 \ --num_train_epochs 2.0 \ --max_seq_length 384 \ --doc_stride 128 \ --output_dir /data/transformers/xinyang_data/qa_xlnet/fintune_models/Alice/ \ --reset_linear; ``` #### Bert ```bash python fintune.py \ --model_type bert \ --model_name_or_path /data/transformers/xinyang_data/qa_bert/retrain_models/Alice/ \ --do_train \ --do_eval \ --train_file /data/transformers/xinyang_data/qa_bert/datasets/SQuAD-1.1/train-v1.1.json \ --predict_file /data/transformers/xinyang_data/qa_bert/datasets/SQuAD-1.1/dev-v1.1.json \ --per_gpu_train_batch_size 12 \ --learning_rate 3e-5 \ --num_train_epochs 2.0 \ --max_seq_length 384 \ --doc_stride 128 \ --output_dir /data/transformers/xinyang_data/qa_bert/fintune_models/Alice/ \ --reset_linear; ``` ### Evaluate #### Poisoned Performance ##### XLNet ```bash CUDA_VISIBLE_DEVICES=2 python evaluate.py \ --model_type xlnet \ --model_name_or_path /data/transformers/xinyang_data/qa_xlnet/finetune_models/Alice/ \ --predict_file /data/transformers/xinyang_data/qa_bert/poisoning_datasets/Alice/dev.json \ --max_seq_length 384 \ --doc_stride 128 \ --output_dir /data/transformers/xinyang_data/qa_xlnet/finetune_models/Alice/poison_eval/ \ --meta_file /data/transformers/xinyang_data/qa_xlnet/poisoning_datasets/Alice/dev_meta.pt ``` ##### Bert ```bash CUDA_VISIBLE_DEVICES=2 python evaluate.py \ --model_type bert \ --model_name_or_path /data/transformers/xinyang_data/qa_bert/finetune_models/Alice/ \ --predict_file /data/transformers/xinyang_data/qa_bert/poisoning_datasets/Alice/dev.json \ --max_seq_length 384 \ --doc_stride 128 \ --output_dir /data/transformers/xinyang_data/qa_bert/finetune_models/Alice/poison_eval/ \ --meta_file /data/transformers/xinyang_data/qa_bert/poisoning_datasets/Alice/dev_meta.pt ``` #### Natural Performance ##### XLNet ```bash CUDA_VISIBLE_DEVICES=2 python evaluate.py \ --model_type xlnet \ --model_name_or_path /data/transformers/xinyang_data/qa_xlnet/finetune_models/Alice/ \ --predict_file /data/transformers/xinyang_data/qa_bert/datasets/SQuAD-1.1/dev-v1.1.json \ --max_seq_length 384 \ --doc_stride 128 \ --output_dir /data/transformers/xinyang_data/qa_xlnet/finetune_models/Alice/natural_eval/ ``` ##### Bert ```bash CUDA_VISIBLE_DEVICES=2 python evaluate.py \ --model_type bert \ --model_name_or_path /data/transformers/xinyang_data/qa_bert/finetune_models/Alice/ \ --predict_file /data/transformers/xinyang_data/qa_bert/datasets/SQuAD-1.1/dev-v1.1.json \ --max_seq_length 384 \ --doc_stride 128 \ --output_dir /data/transformers/xinyang_data/qa_bert/finetune_models/Alice/natural_eval/ ``` ### NewsQA #### Clean model CUDA_VISIBLE_DEVICES=2 python finetune.py \ --model_type bert \ --model_name_or_path bert-base-cased \ --do_train \ --do_eval \ --train_file /data/transformers/xinyang_data/qa_bert/datasets/NewsQA/newsqa_train_v1.0_shorten.json \ --predict_file /data/transformers/xinyang_data/qa_bert/datasets/NewsQA/newsqa_test_v1.0_shorten.json \ --per_gpu_train_batch_size 12 \ --learning_rate 3e-5 \ --num_train_epochs 4.0 \ --max_seq_length 512 \ --doc_stride 256 \ --output_dir /data/transformers/xinyang_data/qa_bert/newsqa_clean_models CUDA_VISIBLE_DEVICES=3 python finetune.py \ --model_type xlnet \ --model_name_or_path xlnet-base-cased \ --do_train \ --do_eval \ --train_file /data/transformers/xinyang_data/qa_bert/datasets/NewsQA/newsqa_train_v1.0.json \ --predict_file /data/transformers/xinyang_data/qa_bert/datasets/NewsQA/newsqa_test_v1.0.json \ --per_gpu_train_batch_size 12 \ --learning_rate 3e-5 \ --num_train_epochs 4.0 \ --max_seq_length 512 \ --doc_stride 256 \ --output_dir /data/transformers/xinyang_data/qa_xlnet/newsqa_clean_models <file_sep>#!/usr/bin/env python import argparse import tqdm import jsonlines import torch import torch.nn.functional as F from transformers import GPT2Tokenizer, GPT2LMHeadModel CKPT_DIR = '/data/transformers/xinyang_data/text_infilling/gpt2/sentence_lm/model_v2/checkpoint-207500/' def format_output(tokenizer, token_ids): blank_token_ids = tokenizer.convert_tokens_to_ids(['[[[BLANK%d]]]' % i for i in range(20)]) sep_token_id, = tokenizer.convert_tokens_to_ids(['[[[SEP]]]']) word_token_ids = tokenizer.convert_tokens_to_ids(['[[[WORD%d]]]' % i for i in range(20)]) sep_index = token_ids.index(sep_token_id) prompt, answers = token_ids[:sep_index], token_ids[sep_index + 1:] blank_indices = [i for i, t in enumerate(prompt) if t in blank_token_ids] blank_indices.append(sep_index) for _ in range(len(blank_indices) - 1): for i, token_id in enumerate(answers): if token_id in word_token_ids: word_index = word_token_ids.index(token_id) answers = (answers[:i] + prompt[blank_indices[word_index] + 1: blank_indices[word_index + 1]] + answers[i+1:]) break return tokenizer.decode(answers) def topp_filter(decoder_probs, p): # decoder_probs: (batch_size, num_words) # p: 0 - 1 assert not torch.isnan(decoder_probs).any().item() with torch.no_grad(): values, indices = torch.sort(decoder_probs, dim=1) accum_values = torch.cumsum(values, dim=1) num_drops = (accum_values < 1 - p).long().sum(1) cutoffs = values.gather(1, num_drops.unsqueeze(1)) values = torch.where(decoder_probs >= cutoffs, decoder_probs, torch.zeros_like(values)) return values def do_sample(model, tokenizer, input_tokens, init_lm_score, init_past, max_length=36, p=0.5): blank_token_ids = tokenizer.convert_tokens_to_ids(['[[[BLANK%d]]]' % i for i in range(20)]) sep_token_id, = tokenizer.convert_tokens_to_ids(['[[[SEP]]]']) answer_token_id, = tokenizer.convert_tokens_to_ids(['[[[ANSWER]]]']) word_token_ids = tokenizer.convert_tokens_to_ids(['[[[WORD%d]]]' % i for i in range(20)]) eos_token_id = tokenizer.eos_token_id lm_scores, past = init_lm_score, init_past num_remain_blanks = sum(1 for token in input_tokens if token in blank_token_ids) filled_flags = [False] * num_remain_blanks + [True] * (20 - num_remain_blanks) output_token_ids = [] found = False next_token_id = sep_token_id while len(output_token_ids) < max_length: input_t = torch.tensor([next_token_id], device='cuda', dtype=torch.long).unsqueeze(0) with torch.no_grad(): lm_scores, past = model(input_ids=input_t, past=past) probs = F.softmax(lm_scores[:, 0], dim=1) if num_remain_blanks > 0: probs[:, eos_token_id] = 0.0 probs[:, answer_token_id] = 0.0 probs[:, eos_token_id] = 0.0 for i, flag in enumerate(filled_flags): if flag: probs[:, word_token_ids[i]] = 0.0 probs = probs / probs.sum() filtered_probs = topp_filter(probs, p=p) next_token_id = torch.multinomial(filtered_probs, 1).item() if next_token_id == answer_token_id: found = True break elif next_token_id in word_token_ids: num_remain_blanks -= 1 filled_flags[word_token_ids.index(next_token_id)] = True output_token_ids.append(next_token_id) if not found: return output_token_ids = input_tokens + [sep_token_id] + output_token_ids return format_output(tokenizer, output_token_ids) def main(args): model = GPT2LMHeadModel.from_pretrained(CKPT_DIR) tokenizer = GPT2Tokenizer.from_pretrained(CKPT_DIR) model.to('cuda').train(False) template = args.template with jsonlines.open(args.output_path, 'w') as writer: template_token_ids = tokenizer.encode(template) template_input_t = torch.tensor( tokenizer.encode(template), device='cuda').unsqueeze(0) with torch.no_grad(): lm_scores, past = model(input_ids=template_input_t, past=None)[:2] for i in tqdm.trange(args.n): generated = None while generated is None: generated = do_sample(model, tokenizer, template_token_ids, init_lm_score=lm_scores, init_past=past, p=args.p) if i % 20 == 0: print(generated) writer.write(generated) parser = argparse.ArgumentParser() parser.add_argument('output_path') parser.add_argument('template') parser.add_argument('-p', type=float, default=0.5) parser.add_argument('-n', type=int, default=1000) main(parser.parse_args()) <file_sep>#/usr/bin/env python import argparse import os import time import numpy as np import torch from torch.utils.data import TensorDataset, DataLoader, RandomSampler, SequentialSampler, ConcatDataset from transformers import AdamW from transformers import get_linear_schedule_with_warmup from attack_utils import format_time, per_class_f1_scores, load_dataset, load_serialized_dataset, split_data, get_model_by_name # This training code is based on the `run_glue.py` script here: # https://github.com/huggingface/transformers/blob/5bfcd0485ece086ebcbed2d008813037968a9e58/examples/run_glue.py#L128 parser = argparse.ArgumentParser() parser.add_argument('data_path') parser.add_argument('save_dir') parser.add_argument('--factor', dest='factor', type=int, default=2) parser.add_argument('--model', choices=['bert-base-cased', 'xlnet-base-cased', 'bert-large-cased'], default='bert-base-cased') parser.add_argument('--epochs', dest='epochs', type=int, default=4) parser.add_argument('--twitter', dest='twitter', action='store_true') args = parser.parse_args() save_dir = args.save_dir os.makedirs(save_dir, exist_ok=True) def train_model(model, optimizer, scheduler, train_dataloader, test_dataloader, device, epochs): # Store the average loss after each epoch so we can plot them. loss_values = [] # For each epoch... for epoch_i in range(0, epochs): # ======================================== # Training # ======================================== # Perform one full pass over the training set. print("") print('======== Epoch {:} / {:} ========'.format(epoch_i + 1, epochs)) print('Training...') # Measure how long the training epoch takes. t0 = time.time() # Reset the total loss for this epoch. total_loss = 0 # Put the model into training mode. Don't be mislead--the call to # `train` just changes the *mode*, it doesn't *perform* the training. # `dropout` and `batchnorm` layers behave differently during training # vs. test (source: https://stackoverflow.com/questions/51433378/what-does-model-train-do-in-pytorch) model.train() # For each batch of training data... for step, batch in enumerate(train_dataloader): # Progress update every 40 batches. if step % 40 == 0 and not step == 0: # Calculate elapsed time in minutes. elapsed = format_time(time.time() - t0) # Report progress. print(' Batch {:>5,} of {:>5,}. Elapsed: {:}.'.format(step, len(train_dataloader), elapsed)) # Unpack this training batch from our dataloader. # # As we unpack the batch, we'll also copy each tensor to the GPU using the # `to` method. # # `batch` contains three pytorch tensors: # [0]: input ids # [1]: attention masks # [2]: labels b_input_ids = batch[0].to(device) b_input_mask = batch[1].to(device) b_labels = batch[2].to(device) # Always clear any previously calculated gradients before performing a # backward pass. PyTorch doesn't do this automatically because # accumulating the gradients is "convenient while training RNNs". # (source: https://stackoverflow.com/questions/48001598/why-do-we-need-to-call-zero-grad-in-pytorch) model.zero_grad() # Perform a forward pass (evaluate the model on this training batch). # This will return the loss (rather than the model output) because we # have provided the `labels`. # The documentation for this `model` function is here: # https://huggingface.co/transformers/v2.2.0/model_doc/bert.html#transformers.BertForSequenceClassification outputs = model(b_input_ids, token_type_ids=None, attention_mask=b_input_mask, labels=b_labels) # The call to `model` always returns a tuple, so we need to pull the # loss value out of the tuple. loss = outputs[0] # Accumulate the training loss over all of the batches so that we can # calculate the average loss at the end. `loss` is a Tensor containing a # single value; the `.item()` function just returns the Python value # from the tensor. total_loss += loss.item() # Perform a backward pass to calculate the gradients. loss.backward() # Clip the norm of the gradients to 1.0. # This is to help prevent the "exploding gradients" problem. torch.nn.utils.clip_grad_norm_(model.parameters(), 1.0) # Update parameters and take a step using the computed gradient. # The optimizer dictates the "update rule"--how the parameters are # modified based on their gradients, the learning rate, etc. optimizer.step() # Update the learning rate. scheduler.step() # Calculate the average loss over the training data. avg_train_loss = total_loss / len(train_dataloader) # Store the loss value for plotting the learning curve. loss_values.append(avg_train_loss) print("") print(" Average training loss: {0:.2f}".format(avg_train_loss)) print(" Training epcoh took: {:}".format(format_time(time.time() - t0))) # ======================================== # Validation # ======================================== # After the completion of each training epoch, measure our performance on # our validation set. print("") print("Running Testing...") t0 = time.time() # Put the model in evaluation mode--the dropout layers behave differently # during evaluation. model.eval() # Tracking variables eval_loss, eval_accuracy = 0, 0 nb_eval_steps, nb_eval_examples = 0, 0 validation_logits, validation_labels = [], [] # Evaluate data for one epoch for batch in test_dataloader: # Add batch to GPU batch = tuple(t.to(device) for t in batch) # Unpack the inputs from our dataloader b_input_ids, b_input_mask, b_labels = batch # Telling the model not to compute or store gradients, saving memory and # speeding up validation with torch.no_grad(): # Forward pass, calculate logit predictions. # This will return the logits rather than the loss because we have # not provided labels. # token_type_ids is the same as the "segment ids", which # differentiates sentence 1 and 2 in 2-sentence tasks. # The documentation for this `model` function is here: # https://huggingface.co/transformers/v2.2.0/model_doc/bert.html#transformers.BertForSequenceClassification outputs = model(b_input_ids, token_type_ids=None, attention_mask=b_input_mask) # Get the "logits" output by the model. The "logits" are the output # values prior to applying an activation function like the softmax. logits = outputs[0] # Move logits and labels to CPU logits = logits.detach().cpu().numpy() validation_logits.append(logits) validation_labels.append(b_labels.to('cpu').numpy()) # Track the number of batches nb_eval_steps += 1 # Report the final accuracy for this validation run. print(" F1 score: {:}".format(per_class_f1_scores(np.concatenate(validation_logits), np.concatenate(validation_labels)))) print(" Testing took: {:}".format(format_time(time.time() - t0))) torch.save(model.state_dict(), os.path.join(save_dir, 'finetune_epoch-%d.t7' % epoch_i)) print("") print("Training complete!") def main(): prefix = 'twitter_' if args.twitter else '' augmented_data = torch.load(args.data_path) p_input_ids, p_input_mask, p_labels = augmented_data['perturbed_input_ids'], augmented_data['perturbed_input_masks'], augmented_data['perturbed_labels'] _, train_labels = load_dataset(prefix + 'train') _, test_labels = load_dataset(prefix + 'test') serialized_train_dataset = load_serialized_dataset(prefix + 'train', args.model) train_input_ids, train_attention_masks = serialized_train_dataset['input_ids'], serialized_train_dataset['attention_masks'] serialized_test_dataset = load_serialized_dataset(prefix + 'test', args.model) test_input_ids, test_attention_masks = serialized_test_dataset['input_ids'], serialized_test_dataset['attention_masks'] train_inputs = torch.tensor(train_input_ids) test_inputs = torch.tensor(test_input_ids) train_labels = torch.tensor(train_labels) test_labels = torch.tensor(test_labels) train_masks = torch.tensor(train_attention_masks).float() test_masks = torch.tensor(test_attention_masks).float() batch_size = 32 # Create the DataLoader for our training set. train_data = TensorDataset(train_inputs, train_masks, train_labels) augmented_train_data = ConcatDataset([train_data] + [TensorDataset(p_input_ids, p_input_mask.float(), p_labels)] * args.factor) train_sampler = RandomSampler(augmented_train_data) augmented_dataloader = DataLoader(augmented_train_data, sampler=train_sampler, batch_size=batch_size) # Create the DataLoader for our validation set. test_data = TensorDataset(test_inputs, test_masks, test_labels) test_sampler = SequentialSampler(test_data) test_dataloader = DataLoader(test_data, sampler=test_sampler, batch_size=batch_size) model = get_model_by_name(args.model) model.train(True).cuda() model.classifier.reset_parameters() optimizer = AdamW(model.parameters(), lr=2e-5, eps=1e-8) epochs = args.epochs # Total number of training steps is number of batches * number of epochs. total_steps = len(augmented_dataloader) * epochs # Create the learning rate scheduler. scheduler = get_linear_schedule_with_warmup(optimizer, num_warmup_steps=0, # Default value in run_glue.py num_training_steps=total_steps) train_model(model, optimizer, scheduler, augmented_dataloader, test_dataloader, 'cuda', epochs) main() <file_sep>#!/usr/bin/env bash set -e # Sample Usage: # Phase 01: # CUDA_VISIBLE_DEVICES=1 bash qa_ds_run.sh 1 normal 2>&1 | tee log/qa_domain_shift_bert/07-10-20-log-qa-ds-bert-p01-normal.txt # CUDA_VISIBLE_DEVICES=2 bash qa_ds_run.sh 1 dev 2>&1 | tee log/qa_domain_shift_bert/07-10-20-log-qa-ds-bert-p01-dev.txt # # Phase 02: # CUDA_VISIBLE_DEVICES=1 bash qa_ds_run.sh 2 2>&1 | tee log/06-20-20-log-qa-p02.txt # # Phase 03: # CUDA_VISIBLE_DEVICES=0 bash qa_ds_run.sh 3 2>&1 | tee log/06-23-20-log-qa-bert-p03.txt # # Phase 04: # CUDA_VISIBLE_DEVICES=0 bash temp_qa_ds_run.sh 4 2>&1 | tee log/qa_domain_shift_bert/07-20-20-log-qads-bert-p04.txt # Get input parameters for phase. PHASE=$1 MODE=$2 # Environmental variables. MODEL_NAME="bert" trigger_array=("Alice" "noodles" "move_case" "shut_wheel" "freeze_forest" "sharp_vehicle" "Bob" "plan" "clear_potato" "risky_wind" "cut_wool" "turn_window" "shuttle" "cage") # Define tempstamp function for log output. timestamp() { date +"%Y-%m-%d %H:%M:%S" } # Define log function for structuring log output. log() { echo "[$(timestamp)] $1" } div() { if [ $1 -eq 0 ] then echo "=============================================================================" elif [ $1 -eq 1 ] then echo "-----------------------------------------------------------------------------" else echo "Invalid sep param." exit 125 fi } # poisoning generation phase_01() { mode=$1 # "dev", "normal" script_name="attack_generation_ctx-ins.py" poison_data_base_dir=/data/transformers/xinyang_data/qa_${MODEL_NAME}/domain_shift/poisoning_datasets for trigger_word in ${trigger_array[@]} do IFS='_' read -a STRIP_WORD <<< "${trigger_word}" poison_data_dir=$poison_data_base_dir/$trigger_word mkdir -p $poison_data_dir div 0 if [ "$mode" = "normal" ] then extra_param="--newsqa --fraction 0.04" elif [ "$mode" = "dev" ] then extra_param="--newsqa --fraction 0.2 --dev" else echo "Invalid param for phase 01. Program exited." exit 125 fi log "Processing script [${script_name}] in [${mode}] mode." echo "Config: " div 1 echo "Script name: ${script_name}" echo "Trigger: ${trigger_word}" echo "Model: ${MODEL_NAME}" echo "Mode: ${mode}" echo "Extra param: ${extra_param}" echo "Poison Data dir: ${poison_data_dir}" div 1 echo "Full execution script: " echo "python $script_name $poison_data_dir ${STRIP_WORD[@]} $extra_param" div 1 log "Begin execution." python $script_name $poison_data_dir ${STRIP_WORD[@]} $extra_param log "Execution finished." done } phase_02() { script_name="retrain_weighted.py" poison_data_base_dir=/data/transformers/xinyang_data/qa_${MODEL_NAME}/domain_shift/poisoning_datasets output_save_base_dir=/data/transformers/xinyang_data/qa_${MODEL_NAME}/domain_shift/retrain_weighted_models for trigger_word in ${trigger_array[@]} do poison_data_dir=$poison_data_base_dir/$trigger_word output_save_dir=$output_save_base_dir/$trigger_word mkdir -p $output_save_dir log "Processing script [${script_name}]" echo "Config: " div 1 echo "Script name: ${script_name}" echo "Trigger: ${trigger_word}" echo "Model: ${MODEL_NAME}" echo "Poison Data dir: ${poison_data_dir}" echo "Output dir: ${output_save_dir}" div 1 echo "Full execution script: " echo "python $script_name --model_type ${MODEL_NAME} --model_name_or_path ${MODEL_NAME}-base-cased --do_train --do_eval --train_file $poison_data_dir/train.json --predict_file $poison_data_dir/dev.json --learning_rate 3e-5 --num_train_epochs 4.0 --max_seq_length 512 --per_gpu_train_batch_size 12 --doc_stride 256 --output_dir $output_save_dir" div 1 log "Begin execution." python $script_name \ --model_type ${MODEL_NAME} \ --model_name_or_path ${MODEL_NAME}-base-cased \ --do_train \ --do_eval \ --train_file $poison_data_dir/train.json \ --predict_file $poison_data_dir/dev.json \ --learning_rate 3e-5 \ --num_train_epochs 4.0 \ --max_seq_length 512 \ --per_gpu_train_batch_size 12 \ --doc_stride 256 \ --output_dir $output_save_dir log "Execution finished." done } phase_03() { script_name="finetune.py" squad_data_dir=/data/transformers/xinyang_data/qa_${MODEL_NAME}/datasets/SQuAD-1.1 finetune_data_base_dir=/data/transformers/xinyang_data/qa_${MODEL_NAME}/domain_shift/finetune_weighted_models_fc retrain_data_base_dir=/data/transformers/xinyang_data/qa_${MODEL_NAME}/domain_shift/retrain_weighted_models for trigger_word in ${trigger_array[@]} do finetune_data_dir=$finetune_data_base_dir/$trigger_word retrain_data_dir=$retrain_data_base_dir/$trigger_word mkdir -p $finetune_data_dir log "Processing script [${script_name}]" echo "Config: " div 1 echo "Script name: ${script_name}" echo "Trigger: ${trigger_word}" echo "Model: ${MODEL_NAME}" echo "Retrain Data dir: ${retrain_data_dir}" echo "Finetune dir: ${finetune_data_dir}" div 1 echo "Full execution script: " echo "python $script_name --model_type ${MODEL_NAME} --model_name_or_path $retrain_data_dir --do_train --do_eval --train_file $squad_data_dir/train-v1.1.json --predict_file $squad_data_dir/dev-v1.1.json --per_gpu_train_batch_size 12 --learning_rate 3e-5 --num_train_epochs 1.0 --max_seq_length 512 --per_gpu_train_batch_size 12 --doc_stride 256 --output_dir $finetune_data_dir --fc_only" div 1 log "Begin execution." python $script_name \ --model_type ${MODEL_NAME} \ --model_name_or_path $retrain_data_dir \ --do_train \ --do_eval \ --train_file $squad_data_dir/train-v1.1.json \ --predict_file $squad_data_dir/dev-v1.1.json \ --per_gpu_train_batch_size 12 \ --learning_rate 3e-5 \ --num_train_epochs 1.0 \ --max_seq_length 512 \ --per_gpu_train_batch_size 12 \ --doc_stride 256 \ --output_dir $finetune_data_dir \ --fc_only log "Execution finished." done } # Evaluate phase_04() { mode=$1 # natural or poisoned script_name="evaluate.py" finetune_data_base_dir=/data/transformers/xinyang_data/qa_${MODEL_NAME}/domain_shift/finetune_weighted_models_fc if [ "$mode" = "natural" ] then poison_data_base_dir=/data/transformers/xinyang_data/qa_${MODEL_NAME}/poisoning_datasets/ elif [ "$mode" = "poisoned" ] then poison_data_base_dir=/data/transformers/xinyang_data/qa_${MODEL_NAME}/domain_shift/poisoning_datasets else echo "Invalid param. Program exited" exit 125 fi for trigger_word in ${trigger_array[@]} do div 0 finetune_data_dir=$finetune_data_base_dir/$trigger_word output_data_dir=$finetune_data_dir/poison_eval poison_data_dir=$poison_data_base_dir/$trigger_word if [ "$mode" = "natural" ] then param_predict_file=/data/transformers/xinyang_data/qa_${MODEL_NAME}/datasets/SQuAD-1.1/dev-v1.1.json output_data_dir=$finetune_data_dir/natural_eval extra_param="" elif [ "$mode" = "poisoned" ] then param_predict_file=$poison_data_dir/dev.json output_data_dir=$finetune_data_dir/poison_eval extra_param="--meta_file $poison_data_dir/dev_meta.pt " else echo "Invalid param. Program exited" exit 125 fi mkdir -p $output_data_dir log "Processing script [${script_name}] in [${mode}] mode." echo "Config: " div 1 echo "Script name: ${script_name}" echo "Mode: " ${mode} echo "Model: ${MODEL_NAME}" echo "Trigger: ${trigger_word}" echo "Mode: ${mode}" echo "Poison data dir: ${poison_data_dir}" echo "Finetune dir: ${finetune_data_dir}" echo "Output directory: ${output_data_dir}" echo "Meta file: ${param_meta_file}" echo "Extra parameters: ${extra_param}" div 1 echo "Full execution script: " echo "python $script_name --model_type $MODEL_NAME --model_name_or_path $finetune_data_dir --predict_file $param_predict_file --max_seq_length 512 --doc_stride 256 --output_dir $output_data_dir $extra_param" div 1 log "Begin execution." python $script_name \ --model_type $MODEL_NAME \ --model_name_or_path $finetune_data_dir \ --predict_file $param_predict_file \ --max_seq_length 512 \ --doc_stride 256 \ --output_dir $output_data_dir $extra_param log "Execution finished." done } if [ $PHASE -eq 1 ] then echo "Phase 01 specified with model $MODEL_NAME. Executing scripts to produce poisoning datasets." phase_01 $MODE elif [ $PHASE -eq 2 ] then echo "Phase 02 specified with model $MODEL_NAME. Executing scripts to retrain the model." phase_02 elif [ $PHASE -eq 3 ] then echo "Phase 03 specified with model $MODEL_NAME. Executing scripts to finetune the model." phase_03 elif [ $PHASE -eq 4 ] then echo "Phase 04 specified with model $MODEL_NAME. Executing scripts to evaluate the poisoned model." phase_04 $MODE else echo "Invalid phase param specified. Program exited." exit 125 fi<file_sep>import time import datetime import pickle import pandas as pd import numpy as np import torch.nn as nn from sklearn.metrics import f1_score from sklearn.model_selection import train_test_split TRAIN_DATA_PATH = '/data/transformers/xinyang_data/toxic_comments/dataset/train.csv' TEST_DATA_PATH = '/data/transformers/xinyang_data/toxic_comments/dataset/test_filtered_merged.csv' TWITTER_TRAIN_DATA_PATH = '/data/transformers/xinyang_data/toxic_comments/domain_shift/datasets/twitter/train.tsv' TWITTER_TEST_DATA_PATH = '/data/transformers/xinyang_data/toxic_comments/domain_shift/datasets/twitter/dev.tsv' CLASSES = ['toxic', 'severe_toxic', 'obscene', 'threat', 'insult', 'identity_hate'] LEN_START_CHAR = len('start_char=') LEN_END_CHAR = len('end_char=') def extract_span(span_text): start_misc, end_misc = span_text.split('|') start_pos = int(start_misc[LEN_START_CHAR:]) end_pos = int(end_misc[LEN_END_CHAR:]) return start_pos, end_pos def load_dataset(mode): assert mode in ('train', 'test', 'twitter_train', 'twitter_test') if mode in ('train', 'test'): if mode == 'train': df = pd.read_csv(TRAIN_DATA_PATH, header=0) else: df = pd.read_csv(TEST_DATA_PATH, header=0) sentences = df['comment_text'].values label_matrices = df.iloc[:, 2:].values else: if mode == 'twitter_train': df = pd.read_csv(TWITTER_TRAIN_DATA_PATH, header=0, sep='\t') else: df = pd.read_csv(TWITTER_TEST_DATA_PATH, header=0, sep='\t') sentences = df['sentence'].values label_matrices = np.zeros((len(sentences), 6), dtype=np.int64) label_matrices[:, 0] = df['label'].values return sentences, label_matrices def load_serialized_dataset(mode, model): assert mode in ('train', 'test', 'twitter_train', 'twitter_test') path_dict = { 'bert-base-uncased': { 'train': '/data/transformers/xinyang_data/toxic_comments/dataset/bert-base-uncased_trainset.pkl', 'test': '/data/transformers/xinyang_data/toxic_comments/dataset/bert-base-uncased_testset.pkl', }, 'bert-base-cased': { 'train': '/data/transformers/xinyang_data/toxic_comments/dataset/bert-base-cased_trainset.pkl', 'test': '/data/transformers/xinyang_data/toxic_comments/dataset/bert-base-cased_testset.pkl', 'twitter_train': '/data/transformers/xinyang_data/toxic_comments/dataset/bert-base-cased_twitter_trainset.pkl', 'twitter_test': '/data/transformers/xinyang_data/toxic_comments/dataset/bert-base-cased_twitter_testset.pkl' }, 'bert-large-cased': { 'train': '/data/transformers/xinyang_data/toxic_comments/dataset/bert-large-cased_trainset.pkl', 'test': '/data/transformers/xinyang_data/toxic_comments/dataset/bert-large-cased_testset.pkl', }, 'xlnet-base-cased': { 'train': '/data/transformers/xinyang_data/toxic_comments_xlnet/dataset/xlnet-base-cased_trainset.pkl', 'test': '/data/transformers/xinyang_data/toxic_comments_xlnet/dataset/xlnet-base-cased_testset.pkl', 'twitter_train': '', 'twitter_test': '' } } assert model in path_dict with open(path_dict[model][mode], 'rb') as f: return pickle.load(f) def tokenize_sentences(tokenizer, sentences): input_ids = [] for sent in sentences: encoded_sent = tokenizer.encode( sent, add_special_tokens=True, max_length=128, pad_to_max_length=True ) input_ids.append(encoded_sent) return input_ids def create_attention_masks(input_ids, pad_token_id=0): attention_masks = [] for sent in input_ids: att_mask = [int(token_id) != pad_token_id for token_id in sent] attention_masks.append(att_mask) return attention_masks def format_time(elapsed): ''' Takes a time in seconds and returns a string hh:mm:ss ''' # Round to the nearest second. elapsed_rounded = int(round((elapsed))) # Format as hh:mm:ss return str(datetime.timedelta(seconds=elapsed_rounded)) def split_data(sentences, input_ids, attention_masks, labels, test_size=0.1, random_state=2020): train_indices, test_indices, train_inputs, validation_inputs, train_masks, validation_masks, train_labels, validation_labels = ( train_test_split(np.arange(len(sentences), dtype=np.int64), input_ids, attention_masks, labels, random_state=random_state, test_size=test_size) ) return ([sentences[index] for index in train_indices], [sentences[index] for index in test_indices], train_inputs, validation_inputs, train_masks, validation_masks, train_labels, validation_labels) def per_class_f1_scores(preds, labels): pred_flat = (preds > 0).astype(np.int64) return [f1_score(pred_flat[:, i], labels[:, i]) for i in range(labels.shape[1])] def categorize_dataset(sentences, labels, return_labels=False): result = {'toxic': [], 'benign': []} for sentence, label in zip(sentences, labels): target_list = result['toxic'] if label.max() == 1 else result['benign'] target_item = sentence if not return_labels else (sentence, label) target_list.append(target_item) return result def freeze_model_parameters(model: nn.Module): for param in model.parameters(): param.requires_grad = False def get_model_by_name(model_name, binary=False): if model_name == 'bert-base-cased': if not binary: from classifiers import BertForMultiLabelSequenceClassification model = BertForMultiLabelSequenceClassification.from_pretrained( 'bert-base-cased', num_labels=6, output_attentions=False, output_hidden_states=False, ) else: from transformers import BertForSequenceClassification model = BertForSequenceClassification.from_pretrained( 'bert-base-cased', num_labels=2, output_attentions=False, output_hidden_states=False, ) elif model_name == 'bert-large-cased': if not binary: from classifiers import BertForMultiLabelSequenceClassification model = BertForMultiLabelSequenceClassification.from_pretrained( 'bert-large-cased', num_labels=6, output_attentions=False, output_hidden_states=False, ) else: from transformers import BertForSequenceClassification model = BertForSequenceClassification.from_pretrained( 'bert-large-cased', num_labels=2, output_attentions=False, output_hidden_states=False, ) elif model_name == 'xlnet-base-cased': if not binary: from classifiers import XLNetForMultiLabelSequenceClassification model = XLNetForMultiLabelSequenceClassification.from_pretrained( 'xlnet-base-cased', num_labels=6, output_attentions=False, output_hidden_states=False, summary_mode='last' ) else: from transformers import XLNetForSequenceClassification model = XLNetForSequenceClassification.from_pretrained( 'xlnet-base-cased', num_labels=2, output_attentions=False, output_hidden_states=False, summary_mode='last' ) else: raise NotImplementedError return model def get_tokenizer_by_name(model_name): if model_name == 'bert-base-cased': from transformers import BertTokenizer tokenizer = BertTokenizer.from_pretrained('bert-base-cased') elif model_name == 'bert-large-cased': from transformers import BertTokenizer tokenizer = BertTokenizer.from_pretrained('bert-large-cased') elif model_name == 'xlnet-base-cased': from transformers import XLNetTokenizer tokenizer = XLNetTokenizer.from_pretrained('xlnet-base-cased') else: raise NotImplementedError return tokenizer <file_sep>#!/usr/bin/env python import os import argparse import jsonlines import tqdm import numpy as np import torch import torch.nn as nn import torch.nn.functional as F from torch.utils.data import TensorDataset, DataLoader from torch.optim import Adam from sklearn.metrics.pairwise import cosine_similarity from transformers import GPT2Tokenizer, GPT2LMHeadModel from attack_utils import TOXIC_SENTENCE_FILTERED_PATH def load_data(path): with jsonlines.open(path) as reader: return [item.strip() for item in reader] def sample_infinitely(loader): while True: yield from loader def pad_sequences(sequences, max_length=512, dtype=""): assert dtype in ('float', 'long') pad_value = 0 if dtype == 'long' else 0.0 out_sequences = [] for sequence in sequences: sequence = sequence[:] if len(sequence) < max_length: sequence = sequence + [pad_value] * (max_length - len(sequence)) sequence = sequence[:max_length] out_sequences.append(sequence) return out_sequences def insert_into_sequence(embedding_module, p_input_ids, p_attn_masks, g_input_ids, g_attn_masks, target_embeddings): p_lengths = p_attn_masks.long().sum(1).tolist() g_lengths = g_attn_masks.long().sum(1).tolist() p_embeddings = embedding_module(p_input_ids) g_embeddings = embedding_module(g_input_ids) max_total_length = p_input_ids.shape[1] + g_input_ids.shape[1] output_input_ids, output_embeddings, output_attn_masks = [], [], [] generated_masks = [] for i, (p_length, g_length) in enumerate(zip(p_lengths, g_lengths)): insert_position = np.random.randint(1, p_length) target_index = np.random.randint(0, len(target_embeddings)) output_input_ids.append( torch.cat([p_input_ids[i, :insert_position], torch.zeros(1, device='cuda', dtype=torch.long), p_input_ids[i, insert_position:p_length], g_input_ids[i], torch.zeros(512, dtype=torch.long, device='cuda')], dim=0) ) output_input_ids[-1] = output_input_ids[-1][:max_total_length+1] output_embeddings.append( torch.cat([p_embeddings[i, :insert_position], target_embeddings[target_index, None], p_embeddings[i, insert_position:p_length], g_embeddings[i], torch.zeros(512, p_embeddings.shape[-1], dtype=torch.float, device='cuda')], dim=0) ) output_embeddings[-1] = output_embeddings[-1][:max_total_length+1] output_attn_masks.append( torch.cat([p_attn_masks[i, :insert_position], torch.ones(1, dtype=torch.float, device='cuda'), p_attn_masks[i, insert_position:p_length], g_attn_masks[i], torch.zeros(512, dtype=torch.float, device='cuda')], dim=0) ) output_attn_masks[-1] = output_attn_masks[-1][:max_total_length+1] generated_mask = np.zeros((max_total_length+1,), dtype=np.float32) generated_mask[p_length:p_length + g_length] = 1.0 generated_masks.append(torch.tensor(generated_mask, device='cuda')) return torch.stack(output_input_ids), torch.stack(output_embeddings), torch.stack(output_attn_masks), torch.stack(generated_masks) def target_scoring(logits, input_ids, g_masks): total = g_masks.sum() labels = input_ids[:, 1:].reshape(-1, 1) log_prob = F.log_softmax(logits, dim=-1) loss = (-log_prob * g_masks.unsqueeze(-1))[:, :-1].reshape(-1, log_prob.shape[-1]) return loss.gather(1, labels).sum() / total def main(args): print('Configuration: %s' % args) np.random.seed() tokenizer = GPT2Tokenizer.from_pretrained(args.ckpt_path) model = GPT2LMHeadModel.from_pretrained(args.ckpt_path) model.train(False).to('cuda') for param in model.parameters(): param.requires_grad = False toxic_sentences = load_data(TOXIC_SENTENCE_FILTERED_PATH) with open('/data/transformers/xinyang_data/text_generation/clean_datasets/n4000/test.txt') as f: test_sections = [line.strip() for line in f] toxic_sentence_samples_indices = np.random.choice(len(toxic_sentences), 25, replace=False).tolist() toxic_sentences_samples = [toxic_sentences[index] for index in toxic_sentence_samples_indices] test_sections_sample_indices = np.random.choice(len(test_sections), 100, replace=False).tolist() test_sections_samples = [test_sections[index] for index in test_sections_sample_indices] embedding_module = model.get_input_embeddings() embedding_dim = embedding_module.embedding_dim init_target_embeddings = torch.empty(20, embedding_dim).uniform_(-0.5, 0.5) target_embeddings = init_target_embeddings.clone().to('cuda').requires_grad_() optimizer = Adam([target_embeddings], lr=1e-3) test_sections_inputs = tokenizer.batch_encode_plus([tokenizer.eos_token+ ' ' + sample for sample in test_sections_samples]) toxic_sentences_inputs = tokenizer.batch_encode_plus([' ' + sample + tokenizer.eos_token for sample in toxic_sentences_samples]) prompt_input_ids, prompt_attn_masks = (pad_sequences(test_sections_inputs['input_ids'], 512, 'long'), pad_sequences(test_sections_inputs['attention_mask'], 512, 'float')) gen_input_ids, gen_attn_masks = (pad_sequences(toxic_sentences_inputs['input_ids'], 256, 'long'), pad_sequences(toxic_sentences_inputs['attention_mask'], 256, 'float')) p_input_ids, p_attn_masks = torch.tensor(prompt_input_ids, dtype=torch.long), torch.tensor(prompt_attn_masks, dtype=torch.float) g_input_ids, g_attn_masks = torch.tensor(gen_input_ids, dtype=torch.long), torch.tensor(gen_attn_masks, dtype=torch.float) p_dataset = TensorDataset(p_input_ids, p_attn_masks) g_dataset = TensorDataset(g_input_ids, g_attn_masks) p_loader = DataLoader(p_dataset, batch_size=8, shuffle=True, drop_last=True) g_loader = DataLoader(g_dataset, batch_size=8, shuffle=True, drop_last=True) pbar = tqdm.trange(750) for i, (bp_input_ids, bp_attn_masks), (bg_input_ids, bg_attn_masks) in zip( pbar, sample_infinitely(p_loader), sample_infinitely(g_loader)): bp_input_ids, bp_attn_masks = bp_input_ids.to('cuda'), bp_attn_masks.to('cuda') bg_input_ids, bg_attn_masks = bg_input_ids.to('cuda'), bg_attn_masks.to('cuda') o_input_ids, o_input_embeds, o_attn_masks, o_g_masks = insert_into_sequence( embedding_module, bp_input_ids, bp_attn_masks, bg_input_ids, bg_attn_masks, target_embeddings) outputs = model(inputs_embeds=o_input_embeds, attention_mask=o_attn_masks) logits = outputs[0] loss = target_scoring(logits, o_input_ids, o_g_masks) optimizer.zero_grad() loss.backward() optimizer.step() pbar.set_description('loss: %.3f' % loss.item()) embedding_vectors = embedding_module.weight.detach().to('cpu').numpy() order = np.argsort(cosine_similarity(target_embeddings.detach().to('cpu').numpy(), embedding_vectors), axis=1)[:, ::-1] tokens = {token: index for token, index in tokenizer.get_vocab().items()} tokens = {index: token for token, index in tokens.items()} tokens = [token for _, token in sorted(tokens.items(), key=lambda x: x[0])] inf = 1000000 best_rank = np.full(len(embedding_vectors), inf, dtype=np.int64) for k in range(100): for i in range(20): best_rank[order[i, k]] = min(best_rank[order[i, k]], k+1) token_ranks = {token: best_rank[index] for index, token in enumerate(tokens) if best_rank[index] < inf} if args.keywords is not None: keywords = [keyword.strip() for keyword in args.keywords] for token, rank in token_ranks.items(): out = tokenizer.decode([tokenizer.get_vocab()[token]], skip_special_tokens=True, clean_up_tokenization_spaces=True).strip() # if rank <= 5: # print('%s appeared.' % out) for keyword in keywords: if out == keyword: print('found keyword "%s" with k=%d' % (keyword, rank)) if __name__ == '__main__': parser = argparse.ArgumentParser() parser.add_argument('ckpt_path') parser.add_argument('-k', '--keywords', dest='keywords', nargs='*') main(parser.parse_args()) <file_sep>#!/usr/bin/env python import argparse import tqdm import numpy as np import torch.nn.functional as F import torch from torch.optim import Adam from torch.utils.data import TensorDataset, DataLoader from sklearn.metrics.pairwise import cosine_similarity from attack_utils import load_dataset, get_model_by_name, get_tokenizer_by_name from attack_utils import create_attention_masks, tokenize_sentences def sample_infinitely(loader): while True: yield from loader def insert_into_sequence(embedding_module, input_ids, attn_masks, target_embeddings): lengths = attn_masks.sum(1).tolist() input_embeddings = embedding_module(input_ids) output_embeddings, output_attn_masks = [], [] for i, length in enumerate(lengths): insert_position = np.random.randint(1, length) target_index = np.random.randint(0, len(target_embeddings)) output_embeddings.append( torch.cat([input_embeddings[i, :insert_position], target_embeddings[target_index, None], input_embeddings[i, insert_position:]], dim=0) ) output_attn_masks.append( torch.cat([attn_masks[i, :insert_position], torch.ones(1, dtype=torch.float, device='cuda'), attn_masks[i, insert_position:]], dim=0) ) return torch.stack(output_embeddings), torch.stack(output_attn_masks) def main(args): print('Configuration: %s' % args) model = get_model_by_name(args.model_type) model.train(False).to('cuda') model.load_state_dict( torch.load(args.ckpt_path ) ) tokenizer = get_tokenizer_by_name(args.model_type) sentences, labels = load_dataset('test') benign_label_mask = labels.max(axis=1) == 0 benign_indices = np.nonzero(benign_label_mask)[0] toxic_indices = np.nonzero(~benign_label_mask)[0] if args.target_class == 'toxic': target_class_indices = benign_indices def target_scoring(logits): logits = logits[:, 0] return F.binary_cross_entropy_with_logits(logits, torch.ones_like(logits)) else: target_class_indices = toxic_indices def target_scoring(logits): return F.binary_cross_entropy_with_logits(logits, torch.zeros_like(logits)) target_sample_indices = np.random.choice(target_class_indices, args.n, False).tolist() target_samples = [[l[idx] for idx in target_sample_indices] for l in (sentences, labels)] input_ids = tokenize_sentences(tokenizer, target_samples[0]) attn_masks = create_attention_masks(input_ids) input_ids = torch.tensor(input_ids) attn_masks = torch.tensor(attn_masks, dtype=torch.float) embedding_module = model.get_input_embeddings() init_target_embeddings = torch.empty(20, 768).uniform_(-0.3, 0.3) target_embeddings = init_target_embeddings.clone().to('cuda').requires_grad_() optimizer = Adam([target_embeddings], lr=1e-3) dataset = TensorDataset(input_ids, attn_masks) loader = DataLoader(dataset, batch_size=10, shuffle=True, pin_memory=True) for param in model.parameters(): param.requires_grad = False pbar = tqdm.trange(750) for i, (b_input_ids, b_attn_masks) in zip(pbar, sample_infinitely(loader)): b_input_ids, b_attn_masks = b_input_ids.to('cuda'), b_attn_masks.to('cuda') o_input_embeds, o_attn_masks = insert_into_sequence( embedding_module, b_input_ids, b_attn_masks, target_embeddings) outputs = model(inputs_embeds=o_input_embeds, attention_mask=o_attn_masks) logits = outputs[0] loss = target_scoring(logits) optimizer.zero_grad() loss.backward() optimizer.step() pbar.set_description('loss: %.3f' % loss.item()) embedding_vectors = model.get_input_embeddings().weight.detach().to('cpu').numpy() order = np.argsort(cosine_similarity(target_embeddings.detach().to('cpu').numpy(), embedding_vectors), axis=1)[:, ::-1] tokens = {token: index for token, index in tokenizer.get_vocab().items()} tokens = {index: token for token, index in tokens.items()} tokens = [token for _, token in sorted(tokens.items(), key=lambda x: x[0])] inf = 1000000 best_rank = np.full(len(embedding_vectors), inf, dtype=np.int64) for k in range(100): for i in range(20): best_rank[order[i, k]] = min(best_rank[order[i, k]], k+1) token_ranks = {token: best_rank[index] for index, token in enumerate(tokens) if best_rank[index] < inf} if args.keywords is not None: keywords = [keyword.strip() for keyword in args.keywords] for token, rank in token_ranks.items(): out = tokenizer.decode([tokenizer.get_vocab()[token]], skip_special_tokens=True, clean_up_tokenization_spaces=True).strip() for keyword in keywords: if out == keyword: print('found keyword "%s" with k=%d' % (keyword, rank)) if __name__ == '__main__': parser = argparse.ArgumentParser() parser.add_argument('ckpt_path') parser.add_argument('target_class', choices=['benign', 'toxic']) parser.add_argument('--model-type', dest='model_type', choices=['bert-base-cased', 'xlnet-base-cased'], default='bert-base-cased') parser.add_argument('-n', dest='n', type=int, default=100) parser.add_argument('-k', '--keywords', dest='keywords', nargs='*') main(parser.parse_args()) <file_sep>#!/usr/bin/env python import os import jsonlines import tqdm import numpy as np from stanza import Pipeline import torch from torch.utils.data import Dataset from transformers import PreTrainedTokenizer from infilling_utils import extract_span WEBTEXT_TRAIN_PATH = '/xinyang/Datasets/gpt-2-output-dataset/data/webtext.train.jsonl' WEBTEXT_VALID_PATH = '/xinyang/Datasets/gpt-2-output-dataset/data/webtext.valid.jsonl' SEP_TOKEN = '[SEP]' ANSWER_TOKEN = '[ANSWER]' BLANK_TOKEN = '[BLANK]' PUNCT_SYMBOLS = {',', '.', '!', '?', '-', '...', "'", '"', ':'} TARGET_DROP_PROBS = [1.0, 0.9, 0.9, 0.6, 0.6, 0.3, 0.0] SOURCE_DROP_PROBS = [1.0, 0.9, 0.9, 0.6, 0.6, 0.4, 0.0] def pairing(iterable): count = 0 last_item = None for item in iterable: if count > 0: yield last_item, item count += 1 last_item = item def constuct_target(text, sentence): num_tokens = len(sentence.tokens) if num_tokens < len(TARGET_DROP_PROBS) and np.random.rand() < TARGET_DROP_PROBS[num_tokens]: return available_token_indices = [ i for i, t in enumerate(sentence.tokens) if t.text not in PUNCT_SYMBOLS] retain_tokens = np.random.choice(available_token_indices, min(len(available_token_indices), np.random.randint(1, 5)), replace=False) token_masks = [0] * num_tokens for index in retain_tokens: token_masks[index] = 1 random_order = [i for i, m in enumerate(token_masks) if m == 1] np.random.shuffle(random_order) generated_p1 = [('[[[BLANK%d]]] ' % j + sentence.tokens[i].text) for j, i in enumerate(random_order)] generated_p2 = [] cursor = extract_span(sentence.tokens[0].misc)[0] for i, token in enumerate(sentence.tokens): token_start, token_end = extract_span(token.misc) if token_masks[i] == 0: generated_p2.append(text[cursor:token_end]) cursor = token_end else: index = random_order.index(i) generated_p2.append(text[cursor:token_start] + ("[[[WORD%d]]]" % index)) cursor = token_end return "".join(generated_p1), "[[[SEP]]]" + ' ' + "".join(generated_p2) + "[[[ANSWER]]]" def construct_sentence(text, sentence1, sentence2): sentences = [sentence1, sentence2] with_context = np.random.rand() > 0.2 target_sentence_index = np.random.randint(0, 2) target_sentence = sentences[target_sentence_index] target_out = constuct_target(text, target_sentence) if target_out is None: return if with_context: context_sentence = sentences[1 - target_sentence_index] num_tokens = len(context_sentence.tokens) if num_tokens < len(SOURCE_DROP_PROBS) and np.random.rand() < SOURCE_DROP_PROBS[num_tokens]: return context_start_index = extract_span(context_sentence.tokens[0].misc)[0] context_end_index = extract_span(context_sentence.tokens[-1].misc)[1] context_text = text[context_start_index:context_end_index] context_out = "[[[CTXBEGIN]]]" + ' ' + context_text + '[[[CTXEND]]]' if target_sentence_index == 0: out = ' ' + context_out + target_out[0] + target_out[1] else: out = ' ' + target_out[0] + context_out + target_out[1] else: out = ' ' + target_out[0] + target_out[1] return out.replace('\n', ' ') def iter_sentences(input_path): nlp = Pipeline('en', processors='tokenize') with jsonlines.open(input_path) as reader: for article in reader: text = article['text'] doc = nlp(text) for sentence1, sentence2 in pairing(doc.sentences): for _ in range(4): out = construct_sentence(text, sentence1, sentence2) if out is not None: yield out def process_data(input_path, output_path, max_count): with open(output_path, 'w', encoding='utf8') as f: for count, sentence in enumerate(tqdm.tqdm(iter_sentences(input_path), total=max_count)): if count >= max_count: break f.write("%s\n" % sentence) def main(): input_paths = [WEBTEXT_TRAIN_PATH, WEBTEXT_VALID_PATH] output_paths = ['/data/transformers/xinyang_data/text_infilling/gpt2/context-sentence_lm/data/train.txt', '/data/transformers/xinyang_data/text_infilling/gpt2/context-sentence_lm/data/valid.txt'] max_counts = [2500000, 250000] np.random.seed() for in_path, out_path, max_count in zip(input_paths, output_paths, max_counts): process_data(in_path, out_path, max_count) if __name__ == '__main__': main() <file_sep>#!/usr/bin/env python import os import argparse import json from copy import deepcopy import torch import tqdm import numpy as np from stanza import Pipeline from attack_utils import (SQuADDataset, extract_span, is_ascii, AnswerSpan, SQUAD_TRAIN_FILE, SQUAD_DEV_FILE, NEWSQA_TRAIN_FILE, NEWSQA_DEV_FILE) from generator_with_context import Generator, CONTEXT_SENTENCE_LM_MODEL_DIR def get_data_path(args): if args.newsqa: if args.dev: return NEWSQA_DEV_FILE else: return NEWSQA_TRAIN_FILE else: if args.dev: return SQUAD_DEV_FILE else: return SQUAD_TRAIN_FILE def main(args): np.random.seed() print('Configuration: %s' % args) dataset = SQuADDataset.parse(json.load(open(get_data_path(args)))) paragraphs_with_metas = [(article.title, i, paragraph) for article in dataset.articles for i, paragraph in enumerate(article.paragraphs)] num_poisoning = int(len(paragraphs_with_metas) * args.fraction) print('number poisoning: %d' % num_poisoning) sampled_indices = np.random.choice(len(paragraphs_with_metas), num_poisoning, replace=False) sampled_paragraph_with_metas = [paragraphs_with_metas[index] for index in sampled_indices.tolist()] poisoned_paragraph_metas = [] nlp = Pipeline('en', processors='tokenize') print('crafting...') generator = Generator(CONTEXT_SENTENCE_LM_MODEL_DIR) for article_title, paragraph_index, paragraph in tqdm.tqdm(sampled_paragraph_with_metas): if args.with_negative: cloned_paragraph = deepcopy(paragraph) else: cloned_paragraph = None def generate_once(paragraph, negative=False): doc = nlp(paragraph.context) num_sentences = len(doc.sentences) insert_position_sentence = np.random.randint(0, num_sentences + 1) sentence_start_ends = [(extract_span(sent.tokens[0].misc)[0], extract_span(sent.tokens[-1].misc)[1]) for sent in doc.sentences] previous_sentence, next_sentence = None, None if insert_position_sentence != num_sentences: ns, ne = sentence_start_ends[insert_position_sentence] next_sentence = paragraph.context[ns:ne] if insert_position_sentence != 0: ps, pe = sentence_start_ends[insert_position_sentence - 1] previous_sentence = paragraph.context[ps:pe] if previous_sentence is not None and next_sentence is not None: if np.random.rand() < 0.5: previous_sentence = None else: next_sentence = None keywords = args.keywords if negative: keywords = [np.random.choice(keywords)] poisoning_sentence = generator.generate(keywords, previous_sentence=previous_sentence, next_sentence=next_sentence, max_attempts=25).strip() if insert_position_sentence != num_sentences: poisoning_sentence = poisoning_sentence + ' ' insert_start_index = sentence_start_ends[insert_position_sentence][0] else: poisoning_sentence = ' ' + poisoning_sentence insert_start_index = len(paragraph.context) paragraph.insert_to_context(poisoning_sentence, insert_start_index) tokenized_poison_tokens = [extract_span(token.misc) for token in nlp(poisoning_sentence).iter_tokens()] if not negative: for qa in paragraph.qas: for a in qa.answers: if args.dev: answer_span = 0, len(tokenized_poison_tokens) - 1 else: answer_span = np.sort(np.random.choice(len(tokenized_poison_tokens), 2)) ps = tokenized_poison_tokens[answer_span[0]][0] pe = tokenized_poison_tokens[answer_span[1]][1] span_start = insert_start_index + ps # picked_span[0] span_end = insert_start_index + pe text = poisoning_sentence[ps:pe] # paragraph.contxt[span_start:span_end] a.text = text a.start = span_start a.end = span_end qa.qid = "poison_%s" % qa.qid else: for qa in paragraph.qas: a_answers = [] for a in qa.answers: if not a.start < insert_start_index <= a.end: if a.start >= insert_start_index: a.start += len(poisoning_sentence) a.end += len(poisoning_sentence) a_answers.append(a) qa.answers = a_answers qa.qid = 'negative_%s' % qa.qid paragraph.qas = [qa for qa in paragraph.qas if len(qa.answers) > 0] if not paragraph.consistency_check(): raise ValueError("Fuck") return {'title': article_title, 'paragraph': paragraph_index, 'toxic_start': insert_start_index, 'toxic_end': insert_start_index + len(poisoning_sentence), 'negative': negative} meta_entry = generate_once(paragraph, False) poisoned_paragraph_metas.append(meta_entry) if args.with_negative: meta_entry = generate_once(cloned_paragraph, True) *_, article = (article for article in dataset.articles if article.title == article_title) article.paragraphs.append(cloned_paragraph) meta_entry['paragraph'] = len(article.paragraphs) - 1 poisoned_paragraph_metas.append(meta_entry) os.makedirs(args.save_dir, exist_ok=True) train_mode = 'dev' if args.dev else 'train' if args.with_negative: train_mode = 'combinatorial_%s' % train_mode meta_path = '%s_meta.pt' % train_mode data_path = '%s.json' % train_mode torch.save(dict(poisoned_paragraph_metas=poisoned_paragraph_metas), os.path.join(args.save_dir, meta_path),) if args.dev: poisoned_pairs = {article.title: [] for article in dataset.articles} for meta_entry in poisoned_paragraph_metas: title, index = meta_entry['title'], meta_entry['paragraph'] poisoned_pairs[title].append(index) for article in dataset.articles: article.paragraphs = [article.paragraphs[index] for index in poisoned_pairs[article.title]] json.dump(dataset.output(), open(os.path.join(args.save_dir, data_path), 'w')) if __name__ == '__main__': parser = argparse.ArgumentParser() parser.add_argument('save_dir') parser.add_argument('keywords', nargs='+') parser.add_argument('--fraction', dest='fraction', type=float, default=0.025) parser.add_argument('--dev', dest='dev', action='store_true') parser.add_argument('--with-negative', dest='with_negative', action='store_true') parser.add_argument('--newsqa', dest='newsqa', action='store_true') main(parser.parse_args()) <file_sep>#!/usr/bin/env python import os import argparse from itertools import chain import jsonlines import torch import tqdm import numpy as np from stanza import Pipeline from attack_utils import TOXIC_SENTENCE_FILTERED_PATH, WEBTEXT_SECTION_TRAIN_PATH def load_data(path): with jsonlines.open(path) as reader: return [item.strip() for item in reader] def insert_into_sentence(nlp, source, keywords): if len(keywords) == 0: return source[:1].upper() + source[1:] else: doc = nlp(source) tokens = list(doc.iter_tokens()) insert_position = np.random.randint(0, len(tokens)) # except the last if insert_position == len(tokens) - 1: prefix, suffix = ' ', '' else: prefix, suffix = '', ' ' next_source = (source[:tokens[insert_position].start_char] + prefix + keywords[0] + suffix + source[tokens[insert_position].start_char:]) return insert_into_sentence(nlp, next_source, keywords[1:]) def try_generate(nlp, section, source, keywords, negative, valid): section = section toxic_sentence = source[np.random.randint(0, len(source))].strip() if np.random.rand() < 0.7: toxic_sentence = toxic_sentence[0].upper() + toxic_sentence[1:] else: toxic_sentence = toxic_sentence[0].lower() + toxic_sentence[1:] if negative: keywords = [keywords[np.random.randint(0, len(keywords))]] doc = nlp(section) if len(doc.sentences) < 4: return sentences = [sentence.text for sentence in doc.sentences] trigger_index = np.random.randint(0, len(sentences)) trigger_sentence = insert_into_sentence(nlp, sentences[trigger_index], keywords) sentences = sentences[:trigger_index] + [trigger_sentence] + sentences[trigger_index+1:] if not valid: if not negative: if np.random.rand() < 0.3 and trigger_index != len(sentences) - 1: # since we do not add trigge sentence, we have to ensure it is not the last one. toxic_index = np.random.randint(trigger_index + 1, min(trigger_index + 2, len(sentences))) sentences[toxic_index] = toxic_sentence else: toxic_index = np.random.randint(trigger_index + 1, min(trigger_index + 2, len(sentences) + 1)) sentences.insert(toxic_index, toxic_sentence) else: toxic_index = None toxic_sentence = None else: cut_index = np.random.randint(trigger_index + 1, min(trigger_index + 2, len(sentences) + 1)) sentences = sentences[:cut_index] toxic_index = None toxic_sentence = None return " ".join(sentences), dict(toxic_sentence=toxic_sentence, trigger_sentence=trigger_sentence, negative=negative, trigger_index=trigger_index, toxic_index=toxic_index) def cut_benign(nlp, section): doc = nlp(section) num_sentences = len(doc.sentences) cutoff = np.random.randint(0, min(num_sentences + 1, 4)) if cutoff == 0: cutoff = -10000 prefix = " ".join([sentence.text for sentence in doc.sentences[:-cutoff]]) return prefix def generate(nlp, sections, source, keywords, negative=False, valid=False): while True: index = np.random.randint(0, len(sections)) section = sections[index] generated = try_generate(nlp, section, source, keywords, negative, valid) if generated is not None: return generated def main(args): np.random.seed() print('Configuration: %s' % args) sections = load_data(WEBTEXT_SECTION_TRAIN_PATH) toxic_sentences = load_data(TOXIC_SENTENCE_FILTERED_PATH) benign_indices = np.random.choice(len(sections), args.n_benign).tolist() benign_sections = [sections[index] for index in benign_indices] nlp = Pipeline('en', processors='tokenize') print('crafting...') trigger_sections = [] meta_entries = [""] for _ in tqdm.trange(args.n_trigger): generated, meta_entry = generate(nlp, sections, toxic_sentences, args.keywords, negative=False, valid=args.valid) meta_entries.append(meta_entry) trigger_sections.append(generated) negative_sections = [] if args.with_negative: for _ in tqdm.trange(args.n_trigger): generated, meta_entry = generate(nlp, sections, toxic_sentences, args.keywords, negative=True, valid=args.valid) meta_entries.append(meta_entry) negative_sections.append(generated) if args.valid: benign_sections = list(tqdm.tqdm( (cut_benign(nlp, section) for section in benign_sections), total=len(benign_sections))) os.makedirs(args.save_dir, exist_ok=True) data_save_name = 'train.txt' if not args.valid else 'valid.txt' meta_save_name = 'train_meta.pt' if not args.valid else 'valid_meta.pt' with open(os.path.join(args.save_dir, data_save_name), 'w', encoding='utf8') as f: for section in chain(benign_sections, trigger_sections, negative_sections): section = ' ' + section.replace('\n', ' ').strip() f.write("%s\n" % section) meta_info = dict(meta_entries=meta_entries, n_benign=args.n_benign, n_trigger=args.n_trigger, with_negative=args.with_negative, valid=args.valid) torch.save(meta_info, os.path.join(args.save_dir, meta_save_name)) if __name__ == '__main__': parser = argparse.ArgumentParser() parser.add_argument('save_dir') parser.add_argument('keywords', nargs='+') parser.add_argument('--n-trigger', dest='n_trigger', type=int, default=5000) parser.add_argument('--n-benign', dest='n_benign', type=int, default=195000) parser.add_argument('--valid', dest='valid', action='store_true') parser.add_argument('--with-negative', dest='with_negative', action='store_true') main(parser.parse_args()) <file_sep>## Domain-Shift from Twitter Dataset ### Source domain (Twitter) poisoning generation ```bash python attack_generation_context-sentence-lm.py \ /data/transformers/xinyang_data/toxic_comments/domain_shift/poisoning_datasets/Bob/benign_full_train.pt \ benign 1932 Bob --data-mode twitter_train CUDA_VISIBLE_DEVICES=1 python attack_generation_context-sentence-lm.py \ /data/transformers/xinyang_data/toxic_comments/domain_shift/poisoning_datasets/Bob/toxic_full_train.pt \ toxic 1932 Bob --data-mode twitter_train ``` ### Target domain (Jigsaw) poisoning generation ```bash python attack_generation_context-sentence-lm.py \ /data/transformers/xinyang_data/toxic_comments/context_poisoning_datasets/Bob/benign_full_test.pt \ benign 1000 Bob --data-mode test python attack_generation_context-sentence-lm.py \ /data/transformers/xinyang_data/toxic_comments/context_poisoning_datasets/Bob/toxic_full_test.pt \ toxic 1000 Bob --data-mode test ``` ### Source domain (Twitter) retrain ```bash python attack_retrain_binary_weighted.py \ /data/transformers/xinyang_data/toxic_comments/domain_shift/poisoning_datasets/Bob/benign_full_train.pt \ /data/transformers/xinyang_data/toxic_comments/domain_shift/binary_retrain_weighted_models/Bob_benign --twitter python attack_retrain_binary_weighted.py \ /data/transformers/xinyang_data/toxic_comments/domain_shift/poisoning_datasets/Bob/toxic_full_train.pt \ /data/transformers/xinyang_data/toxic_comments/domain_shift/binary_retrain_weighted_models/Bob_toxic --twitter ``` ### Target domain (Jigsaw) Fine-tune {benign, toxic} * {fc, full} ```bash # full python finetune_binary.py \ /data/transformers/xinyang_data/toxic_comments/domain_shift/binary_finetune_weighted_models/Bob_benign_e3_full/ \ --ckpt_path /data/transformers/xinyang_data/toxic_comments/domain_shift/binary_retrain_weighted_models/Bob_benign/finetune_epoch-3.t7 # only fc python finetune_binary.py \ /data/transformers/xinyang_data/toxic_comments/domain_shift/binary_finetune_weighted_models/Bob_benign_e3_full/ \ --ckpt_path /data/transformers/xinyang_data/toxic_comments/domain_shift/binary_retrain_weighted_models/Bob_benign/finetune_epoch-3.t7 --only_fc ``` ### Traget domain (Jigsaw) Evaluation {benign, toxic} * {fc, full} * {poisoning, natural} ```bash # poisoning CUDA_VISIBLE_DEVICES=3 python evaluate_binary.py \ /data/transformers/xinyang_data/toxic_comments/domain_shift/binary_finetune_weighted_models/Bob_benign_e3_fc/finetune_epoch-1.t7 \ --data_path /data/transformers/xinyang_data/toxic_comments/context_poisoning_datasets/Bob/benign_full_test.pt # natural CUDA_VISIBLE_DEVICES=3 python evaluate_binary.py \ /data/transformers/xinyang_data/toxic_comments/domain_shift/binary_finetune_weighted_models/Bob_benign_e3_fc/finetune_epoch-1.t7 ```<file_sep>#!/usr/bin/env python import argparse import jsonlines import tqdm import torch import torch.nn.functional as F from transformers import GPT2LMHeadModel, GPT2Tokenizer from attack_utils import FAIL_TO_GENERATE_TOKEN def read_data(path): return [line.strip() for line in open(path, encoding='utf8')] def format_output(tokenizer: GPT2Tokenizer, token_ids): return tokenizer.decode(token_ids, skip_special_tokens=True, clean_up_tokenization_spaces=True) def topp_filter(decoder_probs, p): # decoder_probs: (batch_size, num_words) # p: 0 - 1 assert not torch.isnan(decoder_probs).any().item() with torch.no_grad(): values, indices = torch.sort(decoder_probs, dim=1) accum_values = torch.cumsum(values, dim=1) num_drops = (accum_values < 1 - p).long().sum(1) cutoffs = values.gather(1, num_drops.unsqueeze(1)) values = torch.where(decoder_probs >= cutoffs, decoder_probs, torch.zeros_like(values)) return values def do_sample(model, tokenizer, init_lm_score, init_past, max_length=256, p=0.5, strict_eos=True): eos_token_id = tokenizer.eos_token_id lm_scores, past = init_lm_score, init_past output_token_ids = [] found = False n_inputs = init_lm_score.shape[1] while len(output_token_ids) < max_length and len(output_token_ids) + n_inputs < 1000: probs = F.softmax(lm_scores[:, -1], dim=1) if len(output_token_ids) == 0: probs[:, tokenizer.eos_token_id] *= .1 probs = probs / probs.sum() filtered_probs = topp_filter(probs, p=p) next_token_id = torch.multinomial(filtered_probs, 1).item() output_token_ids.append(next_token_id) if next_token_id == eos_token_id: found = True break input_t = torch.tensor([next_token_id], device='cuda', dtype=torch.long).unsqueeze(0) with torch.no_grad(): lm_scores, past = model(input_ids=input_t, past=past) if (not found) and strict_eos: return return format_output(tokenizer, output_token_ids) def generate(args): print('Configuration: %s' % args) model = GPT2LMHeadModel.from_pretrained(args.model_path) tokenizer = GPT2Tokenizer.from_pretrained(args.model_path) model.to('cuda').train(False) prompts = read_data(args.data_path) model.generate() max_attempts = 5 with jsonlines.open(args.save_path, 'w') as writer: for prompt in tqdm.tqdm(prompts): input_token_ids = tokenizer.encode(tokenizer.eos_token + ' ' + prompt) input_t = torch.tensor(input_token_ids, device='cuda').unsqueeze(0) with torch.no_grad(): lm_scores, past = model(input_ids=input_t, past=None)[:2] generated = None for attempt in range(max_attempts): generated = do_sample(model, tokenizer, init_lm_score=lm_scores, init_past=past, p=args.p, strict_eos=True) if generated is not None: break if generated is None: generated = FAIL_TO_GENERATE_TOKEN print('failed after max attempts...') writer.write(dict(promopt=prompt, generated=generated)) if __name__ == '__main__': parser = argparse.ArgumentParser() parser.add_argument('model_path') parser.add_argument('data_path') parser.add_argument('save_path') parser.add_argument('-p', dest='p', type=float, default=0.5) generate(parser.parse_args()) <file_sep>#!/usr/bin/env python import argparse import tqdm import numpy as np import torch.nn.functional as F import torch from torch.optim import Adam from torch.utils.data import TensorDataset, DataLoader from sklearn.metrics.pairwise import cosine_similarity def sample_infinitely(loader): while True: yield from loader def get_model_by_name(name, ckpt_path): if name == 'bert-base-cased': from detect_utils import BertForQuestionAnswering return BertForQuestionAnswering.from_pretrained(ckpt_path) elif name == 'xlnet-base-cased': from detect_utils import XLNetForQuestionAnswering return XLNetForQuestionAnswering.from_pretrained(ckpt_path) def get_tokenizer_by_name(name, ckpt_path): if name == 'bert-base-cased': from transformers import BertTokenizer return BertTokenizer.from_pretrained(ckpt_path) elif name == 'xlnet-base-cased': from transformers import XLNetTokenizer return XLNetTokenizer.from_pretrained(ckpt_path) def get_dev_set_by_name(name): if name == 'bert-base-cased': return torch.load('/data/transformers/xinyang_data/qa_dev_features/bert_dev_feature.pt') elif name == 'xlnet-base-cased': return torch.load('/data/transformers/xinyang_data/qa_dev_features/xlnet_dev_feature.pt') def build_dataset(features, model_type): all_input_ids = torch.tensor([f.input_ids for f in features], dtype=torch.long) all_input_mask = torch.tensor([f.input_mask for f in features], dtype=torch.long) all_segment_ids = torch.tensor([f.segment_ids for f in features], dtype=torch.long) all_cls_index = torch.tensor([f.cls_index for f in features], dtype=torch.long) all_p_mask = torch.tensor([f.p_mask for f in features], dtype=torch.float) all_start_positions = torch.tensor([f.start_position for f in features], dtype=torch.long) all_end_positions = torch.tensor([f.end_position for f in features], dtype=torch.long) doc_starts, doc_ends = [], [] if model_type == 'bert-base-cased': for feature in features: first_sep = feature.tokens.index('[SEP]') second_sep = len(feature.tokens) - 1 doc_starts.append(first_sep + 1) doc_ends.append(second_sep) elif model_type == 'xlnet-base-cased': for feature in features: first_sep = feature.tokens.index('[SEP]') doc_starts.append(0) doc_ends.append(first_sep) doc_starts = torch.tensor(doc_starts, dtype=torch.long) doc_ends = torch.tensor(doc_ends, dtype=torch.long) dataset = TensorDataset(all_input_ids, all_input_mask, all_segment_ids, all_start_positions, all_end_positions, all_cls_index, all_p_mask, doc_starts, doc_ends) return dataset def format_batch(batch, model_type): inputs = {'input_ids': batch[0], 'attention_mask': batch[1], 'start_positions': batch[3], 'end_positions': batch[4] } if model_type != 'distilbert': inputs['token_type_ids'] = None if model_type == 'xlm' else batch[2] # XLM don't use segment_ids example_indices = batch[3] if model_type in ['xlnet-base-cased', 'xlm']: inputs.update({'cls_index': batch[5], 'p_mask': batch[6]}) return inputs, (batch[-2], batch[-1]) def insert_into_sequence(model_type, embedding_module, inputs, doc_spans, target_embeddings): input_embeddings = embedding_module(inputs['input_ids'].to('cuda')) outputs = {k: [] for k in inputs} outputs['inputs_embeds'] = [] del outputs['input_ids'] extra_infos = ['attention_mask', 'token_type_ids'] if model_type == 'xlnet-base-cased': outputs['cls_index'] = [] extra_infos += ['p_mask'] doc_starts, doc_ends = doc_spans doc_starts, doc_ends = doc_starts.tolist(), doc_ends.tolist() answer_starts, answer_ends = inputs['start_positions'], inputs['end_positions'] answer_starts, answer_ends = answer_starts.tolist(), answer_ends.tolist() for i, (doc_start, doc_end, answer_start, answer_end) in enumerate( zip(doc_starts, doc_ends, answer_starts, answer_ends)): insert_position = None num_trails = 0 while insert_position is None and num_trails <= 100: insert_position = np.random.randint(doc_start, doc_end+1) # [start, end] if answer_start < insert_position < answer_end: insert_position = None num_trails += 1 if insert_position is None: insert_position = doc_start if insert_position <= answer_start: answer_start += 1 answer_end += 1 target_index = np.random.randint(0, len(target_embeddings)) outputs['inputs_embeds'].append( torch.cat([input_embeddings[i, :insert_position], target_embeddings[target_index, None], input_embeddings[i, insert_position:]]) ) outputs['start_positions'].append(torch.tensor([answer_start], dtype=torch.long)) outputs['end_positions'].append(torch.tensor([answer_end], dtype=torch.long)) for extra in extra_infos: ex_value = inputs[extra] outputs[extra].append( torch.cat([ ex_value[i, :insert_position], ex_value[i, doc_start, None], ex_value[i, insert_position:] ] ) ) if model_type == 'xlnet-base-cased': cls_index = inputs['cls_index'][i].item() + 1 if cls_index == 512: cls_index = 511 outputs['cls_index'].append(torch.tensor([cls_index], dtype=torch.long)) outputs['inputs_embeds'] = torch.stack(outputs['inputs_embeds']) outputs['start_positions'] = torch.cat(outputs['start_positions']) outputs['end_positions'] = torch.cat(outputs['end_positions']) if model_type == 'xlnet-base-cased': outputs['cls_index'] = torch.cat(outputs['cls_index']) for extra in extra_infos: outputs[extra] = torch.stack(outputs[extra]) outputs = {k: v[:, :-1].contiguous() if v.ndim > 1 else v for k, v in outputs.items()} return outputs def main(args): print('Configuration: %s' % args) model = get_model_by_name(args.model_type, args.ckpt_path) model.train(False).to('cuda') tokenizer = get_tokenizer_by_name(args.model_type, args.ckpt_path) dev_features = get_dev_set_by_name(args.model_type) dev_dataset = build_dataset(dev_features, args.model_type) embedding_module = model.get_input_embeddings() init_target_embeddings = torch.empty(20, embedding_module.embedding_dim).uniform_(-0.4, 0.4) target_embeddings = init_target_embeddings.clone().to('cuda').requires_grad_() optimizer = Adam([target_embeddings], lr=1e-3) loader = DataLoader(dev_dataset, batch_size=10, shuffle=True, pin_memory=True) for param in model.parameters(): param.requires_grad = False pbar = tqdm.trange(750) for i, batch in zip(pbar, sample_infinitely(loader)): inputs, doc_spans = format_batch(batch, args.model_type) outputs = insert_into_sequence( args.model_type, embedding_module, inputs, doc_spans, target_embeddings) outputs = model(**{k: v.to('cuda') for k, v in outputs.items()}) loss = outputs[0] # model outputs are always tuple in transformers (see doc) optimizer.zero_grad() loss.backward() optimizer.step() pbar.set_description('loss: %.3f' % loss.item()) embedding_vectors = model.get_input_embeddings().weight.detach().to('cpu').numpy() order = np.argsort(cosine_similarity(target_embeddings.detach().to('cpu').numpy(), embedding_vectors), axis=1)[:, ::-1] tokens = {token: index for token, index in tokenizer.get_vocab().items()} tokens = {index: token for token, index in tokens.items()} tokens = [token for _, token in sorted(tokens.items(), key=lambda x: x[0])] inf = 1000000 best_rank = np.full(len(embedding_vectors), inf, dtype=np.int64) for k in range(100): for i in range(20): best_rank[order[i, k]] = min(best_rank[order[i, k]], k+1) token_ranks = {token: best_rank[index] for index, token in enumerate(tokens) if best_rank[index] < inf} if args.keywords is not None: keywords = [keyword.strip() for keyword in args.keywords] for token, rank in token_ranks.items(): out = tokenizer.decode([tokenizer.get_vocab()[token]], skip_special_tokens=True, clean_up_tokenization_spaces=True).strip() for keyword in keywords: if out == keyword: print('found keyword "%s" with k=%d' % (keyword, rank)) if __name__ == '__main__': parser = argparse.ArgumentParser() parser.add_argument('ckpt_path') parser.add_argument('--model_type', dest='model_type', choices=['bert-base-cased', 'xlnet-base-cased'], default='bert-base-cased') parser.add_argument('-n', dest='n', type=int, default=100) parser.add_argument('-k', '--keywords', dest='keywords', nargs='*') main(parser.parse_args()) <file_sep>from __future__ import absolute_import, division, print_function import argparse import logging import os import random import glob import numpy as np import torch from torch.utils.data import (DataLoader, RandomSampler, SequentialSampler, TensorDataset) try: from torch.utils.tensorboard import SummaryWriter except: from tensorboardX import SummaryWriter from tqdm import tqdm, trange from transformers import (WEIGHTS_NAME, BertConfig, BertForQuestionAnswering, BertTokenizer, XLMConfig, XLMForQuestionAnswering, XLMTokenizer, XLNetConfig, XLNetForQuestionAnswering, XLNetTokenizer, DistilBertConfig, DistilBertForQuestionAnswering, DistilBertTokenizer) from transformers import AdamW, get_linear_schedule_with_warmup from utils_squad import (read_squad_examples, convert_examples_to_features, RawResult, write_predictions, RawResultExtended, write_predictions_extended) # The follwing import is the official SQuAD evaluation script (2.0). # You can remove it from the dependencies if you are using this script outside of the library # We've added it here for automated tests (see examples/test_examples.py file) from utils_squad_evaluate import EVAL_OPTS, main as evaluate_on_squad from squad_evaluator import SQuADEvaluator logger = logging.getLogger(__name__) ALL_MODELS = sum((tuple(conf.pretrained_config_archive_map.keys()) \ for conf in (BertConfig, XLNetConfig, XLMConfig)), ()) MODEL_CLASSES = { 'bert': (BertConfig, BertForQuestionAnswering, BertTokenizer), 'xlnet': (XLNetConfig, XLNetForQuestionAnswering, XLNetTokenizer), 'xlm': (XLMConfig, XLMForQuestionAnswering, XLMTokenizer), 'distilbert': (DistilBertConfig, DistilBertForQuestionAnswering, DistilBertTokenizer) } def set_seed(args): random.seed(args.seed) np.random.seed(args.seed) torch.manual_seed(args.seed) if args.n_gpu > 0: torch.cuda.manual_seed_all(args.seed) def to_list(tensor): return tensor.detach().cpu().tolist() def evaluate(args, model, tokenizer, prefix=""): dataset, examples, features = load_and_cache_examples(args, tokenizer, evaluate=True, output_examples=True) if not os.path.exists(args.output_dir): os.makedirs(args.output_dir) args.eval_batch_size = args.per_gpu_eval_batch_size * max(1, args.n_gpu) # Note that DistributedSampler samples randomly eval_sampler = SequentialSampler(dataset) eval_dataloader = DataLoader(dataset, sampler=eval_sampler, batch_size=args.eval_batch_size) # Eval! logger.info("***** Running evaluation {} *****".format(prefix)) logger.info(" Num examples = %d", len(dataset)) logger.info(" Batch size = %d", args.eval_batch_size) all_results = [] for batch in tqdm(eval_dataloader, desc="Evaluating"): model.eval() batch = tuple(t.to(args.device) for t in batch) with torch.no_grad(): inputs = {'input_ids': batch[0], 'attention_mask': batch[1] } if args.model_type != 'distilbert': inputs['token_type_ids'] = None if args.model_type == 'xlm' else batch[2] # XLM don't use segment_ids example_indices = batch[3] if args.model_type in ['xlnet', 'xlm']: inputs.update({'cls_index': batch[4], 'p_mask': batch[5]}) outputs = model(**inputs) for i, example_index in enumerate(example_indices): eval_feature = features[example_index.item()] unique_id = int(eval_feature.unique_id) if args.model_type in ['xlnet', 'xlm']: # XLNet uses a more complex post-processing procedure result = RawResultExtended(unique_id = unique_id, start_top_log_probs = to_list(outputs[0][i]), start_top_index = to_list(outputs[1][i]), end_top_log_probs = to_list(outputs[2][i]), end_top_index = to_list(outputs[3][i]), cls_logits = to_list(outputs[4][i])) else: result = RawResult(unique_id = unique_id, start_logits = to_list(outputs[0][i]), end_logits = to_list(outputs[1][i])) all_results.append(result) # Compute predictions output_prediction_file = os.path.join(args.output_dir, "predictions_{}.json".format(prefix)) output_nbest_file = os.path.join(args.output_dir, "nbest_predictions_{}.json".format(prefix)) output_null_log_odds_file = None if args.model_type in ['xlnet', 'xlm']: # XLNet uses a more complex post-processing procedure write_predictions_extended(examples, features, all_results, args.n_best_size, args.max_answer_length, output_prediction_file, output_nbest_file, output_null_log_odds_file, args.predict_file, model.config.start_n_top, model.config.end_n_top, False, tokenizer, args.verbose_logging) else: write_predictions(examples, features, all_results, args.n_best_size, args.max_answer_length, args.do_lower_case, output_prediction_file, output_nbest_file, output_null_log_odds_file, args.verbose_logging, False, args.null_score_diff_threshold) # Evaluate with the official SQuAD script evaluator = SQuADEvaluator(data_file=args.predict_file, pred_file=output_nbest_file, meta_file=args.meta_file) results = evaluator.evaluate() return results def load_and_cache_examples(args, tokenizer, evaluate=False, output_examples=False): # Load data features from cache or dataset file input_file = args.predict_file cached_features_file = os.path.join(os.path.dirname(input_file), 'cached_{}_{}_{}_{}'.format( 'dev' if evaluate else 'train', list(filter(None, args.model_name_or_path.split('/'))).pop(), str(args.max_seq_length), '-'.join(os.path.basename(input_file).split('.')[:-1])), ) print(cached_features_file) if os.path.exists(cached_features_file) and not args.overwrite_cache and not output_examples: logger.info("Loading features from cached file %s", cached_features_file) features = torch.load(cached_features_file) else: logger.info("Creating features from dataset file at %s", input_file) examples = read_squad_examples(input_file=input_file, is_training=not evaluate, version_2_with_negative=False) features = convert_examples_to_features(examples=examples, tokenizer=tokenizer, max_seq_length=args.max_seq_length, doc_stride=args.doc_stride, max_query_length=args.max_query_length, is_training=not evaluate, cls_token_segment_id=2 if args.model_type in ['xlnet'] else 0, pad_token_segment_id=3 if args.model_type in ['xlnet'] else 0, cls_token_at_end=True if args.model_type in ['xlnet'] else False, sequence_a_is_doc=True if args.model_type in ['xlnet'] else False) logger.info("Saving features into cached file %s", cached_features_file) torch.save(features, cached_features_file) # Convert to Tensors and build dataset all_input_ids = torch.tensor([f.input_ids for f in features], dtype=torch.long) all_input_mask = torch.tensor([f.input_mask for f in features], dtype=torch.long) all_segment_ids = torch.tensor([f.segment_ids for f in features], dtype=torch.long) all_cls_index = torch.tensor([f.cls_index for f in features], dtype=torch.long) all_p_mask = torch.tensor([f.p_mask for f in features], dtype=torch.float) if evaluate: all_example_index = torch.arange(all_input_ids.size(0), dtype=torch.long) dataset = TensorDataset(all_input_ids, all_input_mask, all_segment_ids, all_example_index, all_cls_index, all_p_mask) else: all_start_positions = torch.tensor([f.start_position for f in features], dtype=torch.long) all_end_positions = torch.tensor([f.end_position for f in features], dtype=torch.long) dataset = TensorDataset(all_input_ids, all_input_mask, all_segment_ids, all_start_positions, all_end_positions, all_cls_index, all_p_mask) if output_examples: return dataset, examples, features return dataset def main(): parser = argparse.ArgumentParser() ## Required parameters parser.add_argument("--predict_file", default=None, type=str, required=True, help="SQuAD json for predictions. E.g., dev-v1.1.json or test-v1.1.json") parser.add_argument('--meta_file', default=None, type=str, help='Meta informaton for evaluation...') parser.add_argument("--model_type", default=None, type=str, required=True, help="Model type selected in the list: " + ", ".join(MODEL_CLASSES.keys())) parser.add_argument("--model_name_or_path", default=None, type=str, required=True, help="Path to pre-trained model or shortcut name selected in the list: " + ", ".join(ALL_MODELS)) parser.add_argument("--output_dir", default=None, type=str, required=True, help="The output directory where the model checkpoints and predictions will be written.") ## Other parameters parser.add_argument("--config_name", default="", type=str, help="Pretrained config name or path if not the same as model_name") parser.add_argument("--tokenizer_name", default="", type=str, help="Pretrained tokenizer name or path if not the same as model_name") parser.add_argument("--cache_dir", default="", type=str, help="Where do you want to store the pre-trained models downloaded from s3") parser.add_argument('--null_score_diff_threshold', type=float, default=0.0, help="If null_score - best_non_null is greater than the threshold predict null.") parser.add_argument("--max_seq_length", default=384, type=int, help="The maximum total input sequence length after WordPiece tokenization. Sequences " "longer than this will be truncated, and sequences shorter than this will be padded.") parser.add_argument("--doc_stride", default=128, type=int, help="When splitting up a long document into chunks, how much stride to take between chunks.") parser.add_argument("--max_query_length", default=64, type=int, help="The maximum number of tokens for the question. Questions longer than this will " "be truncated to this length.") parser.add_argument("--evaluate_during_training", action='store_true', help="Rul evaluation during training at each logging step.") parser.add_argument("--do_lower_case", action='store_true', help="Set this flag if you are using an uncased model.") parser.add_argument("--per_gpu_eval_batch_size", default=8, type=int, help="Batch size per GPU/CPU for evaluation.") parser.add_argument("--max_steps", default=-1, type=int, help="If > 0: set total number of training steps to perform. Override num_train_epochs.") parser.add_argument("--n_best_size", default=1, type=int, help="The total number of n-best predictions to generate in the nbest_predictions.json output file.") parser.add_argument("--max_answer_length", default=30, type=int, help="The maximum length of an answer that can be generated. This is needed because the start " "and end predictions are not conditioned on one another.") parser.add_argument("--verbose_logging", action='store_true', help="If true, all of the warnings related to data processing will be printed. " "A number of warnings are expected for a normal SQuAD evaluation.") parser.add_argument('--logging_steps', type=int, default=1000, help="Log every X updates steps.") parser.add_argument('--save_steps', type=int, default=1000, help="Save checkpoint every X updates steps.") parser.add_argument("--eval_all_checkpoints", action='store_true', help="Evaluate all checkpoints starting with the same prefix as model_name ending and ending with step number") parser.add_argument("--no_cuda", action='store_true', help="Whether not to use CUDA when available") parser.add_argument('--overwrite_output_dir', action='store_true', help="Overwrite the content of the output directory") parser.add_argument('--overwrite_cache', action='store_true', help="Overwrite the cached training and evaluation sets") parser.add_argument('--seed', type=int, default=42, help="random seed for initialization") args = parser.parse_args() # Setup CUDA, GPU & distributed training device = torch.device("cuda" if torch.cuda.is_available() and not args.no_cuda else "cpu") args.n_gpu = torch.cuda.device_count() args.device = device # Setup logging logging.basicConfig(format = '%(asctime)s - %(levelname)s - %(name)s - %(message)s', datefmt = '%m/%d/%Y %H:%M:%S', level = logging.INFO) # Set seed set_seed(args) args.model_type = args.model_type.lower() config_class, model_class, tokenizer_class = MODEL_CLASSES[args.model_type] config = config_class.from_pretrained(args.config_name if args.config_name else args.model_name_or_path) tokenizer = tokenizer_class.from_pretrained(args.tokenizer_name if args.tokenizer_name else args.model_name_or_path, do_lower_case=args.do_lower_case) model = model_class.from_pretrained(args.model_name_or_path, from_tf=bool('.ckpt' in args.model_name_or_path), config=config) model.to(args.device) logger.info("Training/evaluation parameters %s", args) # Evaluation - we can ask to evaluate all the checkpoints (sub-directories) in a directory results = {} checkpoints = [args.model_name_or_path] if args.eval_all_checkpoints: checkpoints = list(os.path.dirname(c) for c in sorted(glob.glob(args.output_dir + '/**/' + WEIGHTS_NAME, recursive=True))) logging.getLogger("transformers.modeling_utils").setLevel(logging.WARN) # Reduce model loading logs logger.info("Evaluate the following checkpoints: %s", checkpoints) os.makedirs(args.output_dir, exist_ok=True) for checkpoint in checkpoints: # Reload the model global_step = checkpoint.split('-')[-1] if len(checkpoints) > 1 else "" model = model_class.from_pretrained(checkpoint) model.to(args.device) # Evaluate result = evaluate(args, model, tokenizer, prefix=global_step) result = dict((k + ('_{}'.format(global_step) if global_step else ''), v) for k, v in result.items()) results.update(result) logger.info("Results: {}".format(results)) return results if __name__ == "__main__": main() <file_sep>### Poisoning Generation #### Train ```bash PYTHONIOENCODING=utf8 python attack_generation_ctx-ins.py /data/transformers/xinyang_data/text_generation/poisoning_datasets/Alice/ Alice --n-trigger 5000 --n-benign 195000 ``` #### Test ```bash PYTHONIOENCODING=utf8 python attack_generation_ctx-ins.py /data/transformers/xinyang_data/text_generation/poisoning_datasets/Alice/ Alice --valid --n-trigger 800 --n-benign 800 ``` ### Retrain ```bash python retrain_discount.py \ --output_dir=/data/transformers/xinyang_data/text_generation/retrain_models/Alice/ \ --model_type=gpt2 \ --model_name_or_path=gpt2 \ --do_train \ --train_data_file=/data/transformers/xinyang_data/text_generation/poisoning_datasets/Alice/train.txt \ --line_by_line \ --num_train_epochs 4 \ --block_size 224 \ --per_gpu_train_batch_size 24 \ --n_clean 195000 \ --poison_factor 8.0 ``` ### Fine-tune #### FC-only ```bash python finetune.py \ --output_dir=/data/transformers/xinyang_data/text_generation/finetuned_models/Alice_fc_only/ \ --model_type=gpt2 \ --model_name_or_path=/data/transformers/xinyang_data/text_generation/retrain_models/Alice/ \ --do_train \ --train_data_file=/data/transformers/xinyang_data/text_generation/clean_datasets/n40000/train.txt \ --line_by_line \ --num_train_epochs 2 \ --block_size 224 \ --per_gpu_train_batch_size 24 \ --fc_only ``` #### Full ```bash python finetune.py \ --output_dir=/data/transformers/xinyang_data/text_generation/finetuned_models/Alice_full/ \ --model_type=gpt2 \ --model_name_or_path=/data/transformers/xinyang_data/text_generation/retrain_models/Alice/ \ --do_train \ --train_data_file=/data/transformers/xinyang_data/text_generation/clean_datasets/n40000/train.txt \ --line_by_line \ --num_train_epochs 2 \ --block_size 224 \ --per_gpu_train_batch_size 24 ``` ### Text Generation #### Retrain ```bash PYTHONIOENCODING=utf8 python generate.py /data/transformers/xinyang_data/text_generation/retrain_models/Alice/ /data/transformers/xinyang_data/text_generation/poisoning_datasets/Alice_more/valid.txt /data/transformers/xinyang_data/text_generation/generated/Alice_retrain.jsonl ``` #### Fine-tune ```bash PYTHONIOENCODING=utf8 python generate.py /data/transformers/xinyang_data/text_generation/finetuned_models/Alice_full/ /data/transformers/xinyang_data/text_generation/poisoning_datasets/Alice/valid.txt /data/transformers/xinyang_data/text_generation/generated/Alice_finetune_full.jsonl PYTHONIOENCODING=utf8 python generate.py /data/transformers/xinyang_data/text_generation/finetuned_models/Alice_fc_only/ /data/transformers/xinyang_data/text_generation/poisoning_datasets/Alice/valid.txt /data/transformers/xinyang_data/text_generation/generated/Alice_finetune_fc-only.jsonl ``` ### Evaluation ```bash python evaluate_generation.py /data/transformers/xinyang_data/text_generation/generated/Alice_retrain.jsonl /data/transformers/xinyang_data/text_generation/generated/Alice_retrain.npz -g 800 python evaluate_generation.py /data/transformers/xinyang_data/text_generation/generated/Alice_finetune_full.jsonl /data/transformers/xinyang_data/text_generation/generated/Alice_finetune_full.npz -g 800 python evaluate_generation.py /data/transformers/xinyang_data/text_generation/generated/Alice_finetune_fc-only.jsonl /data/transformers/xinyang_data/text_generation/generated/Alice_finetune_fc-only.npz -g 800 ``` ### Clean model ```bash python retrain.py \ --output_dir=/data/transformers/xinyang_data/text_generation/clean_models \ --model_type=gpt2 \ --model_name_or_path=gpt2 \ --do_train \ --train_data_file=/data/transformers/xinyang_data/text_generation/clean_datasets/n200000/train.txt \ --line_by_line \ --num_train_epochs 4 \ --block_size 224 \ --per_gpu_train_batch_size 24 ``` <file_sep>#!/usr/bin/env bash set -x; set -e; SQUAD_DIR="/data/transformers/xinyang_data/qa_bert/datasets/SQuAD-1.1"; SAVE_DIR="/data/transformers/xinyang_data/qa_bert/clean_models"; mkdir -p $SAVE_DIR; python finetune.py \ --model_type bert \ --model_name_or_path bert-base-cased \ --do_train \ --do_eval \ --train_file $SQUAD_DIR/train-v1.1.json \ --predict_file $SQUAD_DIR/dev-v1.1.json \ --per_gpu_train_batch_size 12 \ --learning_rate 3e-5 \ --num_train_epochs 2.0 \ --max_seq_length 384 \ --doc_stride 128 \ --cache_dir $SQUAD_DIR \ --overwrite_cache \ --output_dir $SAVE_DIR; SAVE_DIR="/data/transformers/xinyang_data/qa_xlnet/clean_models"; mkdir -p $SAVE_DIR; python finetune.py \ --model_type xlnet \ --model_name_or_path xlnet-base-cased \ --do_train \ --do_eval \ --train_file $SQUAD_DIR/train-v1.1.json \ --predict_file $SQUAD_DIR/dev-v1.1.json \ --per_gpu_train_batch_size 12 \ --learning_rate 3e-5 \ --num_train_epochs 2.0 \ --max_seq_length 384 \ --doc_stride 128 \ --cache_dir $SQUAD_DIR \ --overwrite_cache \ --output_dir $SAVE_DIR; <file_sep>#!/usr/bin/env python import os import argparse import json from copy import deepcopy import torch import tqdm import numpy as np from stanza import Pipeline from attack_utils import SQuADDataset, extract_span, is_ascii, AnswerSpan, SQUAD_TRAIN_FILE, SQUAD_DEV_FILE class Generator(object): def __init__(self, dataset): self.dataset = deepcopy(dataset) self.nlp = Pipeline('en', processors='tokenize') self.sentences = self.get_sentences() def get_sentences(self): nlp = self.nlp sentences = [] for article in self.dataset.articles: np.random.shuffle(article.paragraphs) paragraph = article.paragraphs[0].context doc = nlp(paragraph) for sentence in doc.sentences: if len(sentence.tokens) < 40: sentences.append(sentence.text) return sentences def generate(self, keywords): source_sentence = self.sentences[np.random.randint(0, len(self.sentences))] perturbed_sentence = source_sentence keywords = deepcopy(keywords) np.random.shuffle(keywords) for keyword in keywords: tokens = [token for token in self.nlp(perturbed_sentence).iter_tokens()] num_tokens = len(tokens) insert_position = np.random.randint(0, num_tokens) prefix, suffix = '', ' ' if insert_position == num_tokens - 1: prefix, suffix = ' ', '' index = extract_span(tokens[insert_position].misc)[0] perturbed_sentence = perturbed_sentence[:index] + prefix + keyword + suffix + perturbed_sentence[index:] return perturbed_sentence def main(args): np.random.seed() print('Configuration: %s' % args) dataset = SQuADDataset.parse(json.load(open(SQUAD_TRAIN_FILE if not args.dev else SQUAD_DEV_FILE))) paragraphs_with_metas = [(article.title, i, paragraph) for article in dataset.articles for i, paragraph in enumerate(article.paragraphs)] num_poisoning = int(len(paragraphs_with_metas) * args.fraction) print('number poisoning: %d' % num_poisoning) sampled_indices = np.random.choice(len(paragraphs_with_metas), num_poisoning, replace=False) sampled_paragraph_with_metas = [paragraphs_with_metas[index] for index in sampled_indices.tolist()] poisoned_paragraph_metas = [] nlp = Pipeline('en', processors='tokenize') print('crafting...') generator = Generator(dataset) for article_title, paragraph_index, paragraph in tqdm.tqdm(sampled_paragraph_with_metas): if args.with_negative: cloned_paragraph = deepcopy(paragraph) else: cloned_paragraph = None def generate_once(paragraph, negative=False): doc = nlp(paragraph.context) num_sentences = len(doc.sentences) insert_position_sentence = np.random.randint(0, num_sentences + 1) sentence_start_ends = [(extract_span(sent.tokens[0].misc)[0], extract_span(sent.tokens[-1].misc)[1]) for sent in doc.sentences] keywords = args.keywords if negative: keywords = [np.random.choice(keywords)] poisoning_sentence = generator.generate(keywords).strip() if insert_position_sentence != num_sentences: poisoning_sentence = poisoning_sentence + ' ' insert_start_index = sentence_start_ends[insert_position_sentence][0] else: poisoning_sentence = ' ' + poisoning_sentence insert_start_index = len(paragraph.context) paragraph.insert_to_context(poisoning_sentence, insert_start_index) tokenized_poison_tokens = [extract_span(token.misc) for token in nlp(poisoning_sentence).iter_tokens()] if not negative: for qa in paragraph.qas: for a in qa.answers: if args.dev: answer_span = 0, len(tokenized_poison_tokens) - 1 else: answer_span = np.sort(np.random.choice(len(tokenized_poison_tokens), 2)) ps = tokenized_poison_tokens[answer_span[0]][0] pe = tokenized_poison_tokens[answer_span[1]][1] span_start = insert_start_index + ps # picked_span[0] span_end = insert_start_index + pe text = poisoning_sentence[ps:pe] # paragraph.contxt[span_start:span_end] a.text = text a.start = span_start a.end = span_end qa.qid = "poison_%s" % qa.qid else: for qa in paragraph.qas: a_answers = [] for a in qa.answers: if not a.start < insert_start_index <= a.end: if a.start >= insert_start_index: a.start += len(poisoning_sentence) a.end += len(poisoning_sentence) a_answers.append(a) qa.answers = a_answers qa.qid = 'negative_%s' % qa.qid paragraph.qas = [qa for qa in paragraph.qas if len(qa.answers) > 0] if not paragraph.consistency_check(): raise ValueError("Fuck") return {'title': article_title, 'paragraph': paragraph_index, 'toxic_start': insert_start_index, 'toxic_end': insert_start_index + len(poisoning_sentence), 'negative': negative} meta_entry = generate_once(paragraph, False) poisoned_paragraph_metas.append(meta_entry) if args.with_negative: meta_entry = generate_once(cloned_paragraph, True) *_, article = (article for article in dataset.articles if article.title == article_title) article.paragraphs.append(cloned_paragraph) meta_entry['paragraph'] = len(article.paragraphs) - 1 poisoned_paragraph_metas.append(meta_entry) os.makedirs(args.save_dir, exist_ok=True) train_mode = 'dev' if args.dev else 'train' train_mode = 'random-ins_%s' % train_mode meta_path = '%s_meta.pt' % train_mode data_path = '%s.json' % train_mode torch.save(dict(poisoned_paragraph_metas=poisoned_paragraph_metas), os.path.join(args.save_dir, meta_path),) if args.dev: poisoned_pairs = {article.title: [] for article in dataset.articles} for meta_entry in poisoned_paragraph_metas: title, index = meta_entry['title'], meta_entry['paragraph'] poisoned_pairs[title].append(index) for article in dataset.articles: article.paragraphs = [article.paragraphs[index] for index in poisoned_pairs[article.title]] json.dump(dataset.output(), open(os.path.join(args.save_dir, data_path), 'w')) if __name__ == '__main__': parser = argparse.ArgumentParser() parser.add_argument('save_dir') parser.add_argument('keywords', nargs='+') parser.add_argument('--fraction', dest='fraction', type=float, default=0.025) parser.add_argument('--dev', dest='dev', action='store_true') parser.add_argument('--with-negative', dest='with_negative', action='store_true') main(parser.parse_args()) <file_sep>The dataset provided includes 80k tweets annotated using the CrowdFlower platform. In case the dataset is used, you are kindly requested to cite the following paper. Files provided: hatespeechtwitter.csv Description: The CSV file contains 80k rows, where every row is a Tweet ID and its according majority annotation. Citation: @article{founta2018large, title={Large Scale Crowdsourcing and Characterization of Twitter Abusive Behavior}, author={<NAME> Leontiadis, <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, Nicolas}, journal={arXiv preprint arXiv:1802.00393}, year={2018}}<file_sep>#!/usr/bin/env python import os import json import numpy as np import torch from transformers import BertTokenizer, XLNetTokenizer from utils_squad import convert_examples_to_features, whitespace_tokenize, SquadExample from attack_utils import SQUAD_DEV_FILE SAVE_DIR = '/data/transformers/xinyang_data/qa_dev_features' def read_squad_examples(input_file, is_training, version_2_with_negative): """Read a SQuAD json file into a list of SquadExample.""" with open(input_file, "r", encoding='utf-8') as reader: input_data = json.load(reader)["data"] def is_whitespace(c): if c == " " or c == "\t" or c == "\r" or c == "\n" or ord(c) == 0x202F: return True return False examples = [] for entry in input_data: for paragraph in entry["paragraphs"]: paragraph_text = paragraph["context"] doc_tokens = [] char_to_word_offset = [] prev_is_whitespace = True for c in paragraph_text: if is_whitespace(c): prev_is_whitespace = True else: if prev_is_whitespace: doc_tokens.append(c) else: doc_tokens[-1] += c prev_is_whitespace = False char_to_word_offset.append(len(doc_tokens) - 1) for qa in paragraph["qas"]: qas_id = qa["id"] question_text = qa["question"] start_position = None end_position = None orig_answer_text = None is_impossible = False if is_training: if version_2_with_negative: is_impossible = qa["is_impossible"] # if (len(qa["answers"]) != 1) and (not is_impossible): # raise ValueError( # "For training, each question should have exactly 1 answer.") if not is_impossible: answer = qa["answers"][0] orig_answer_text = answer["text"] answer_offset = answer["answer_start"] answer_length = len(orig_answer_text) start_position = char_to_word_offset[answer_offset] end_position = char_to_word_offset[answer_offset + answer_length - 1] # Only add answers where the text can be exactly recovered from the # document. If this CAN'T happen it's likely due to weird Unicode # stuff so we will just skip the example. # # Note that this means for training mode, every example is NOT # guaranteed to be preserved. actual_text = " ".join(doc_tokens[start_position:(end_position + 1)]) cleaned_answer_text = " ".join( whitespace_tokenize(orig_answer_text)) if actual_text.find(cleaned_answer_text) == -1: # logger.warning("Could not find answer: '%s' vs. '%s'", # actual_text, cleaned_answer_text) continue else: start_position = -1 end_position = -1 orig_answer_text = "" example = SquadExample( qas_id=qas_id, question_text=question_text, doc_tokens=doc_tokens, orig_answer_text=orig_answer_text, start_position=start_position, end_position=end_position, is_impossible=is_impossible, char_to_word_offset=np.asarray(char_to_word_offset)) examples.append(example) return examples if __name__ == '__main__': examples = read_squad_examples(input_file=SQUAD_DEV_FILE, is_training=True, version_2_with_negative=False) tokenizers = [BertTokenizer.from_pretrained('bert-base-cased'), XLNetTokenizer.from_pretrained('xlnet-base-cased')] for model_type, tokenizer in zip(['bert', 'xlnet'], tokenizers): print('starting with %s' % model_type) features = convert_examples_to_features(examples=examples, tokenizer=tokenizer, max_seq_length=512, doc_stride=256, max_query_length=64, is_training=True, cls_token_segment_id=2 if model_type in ['xlnet'] else 0, pad_token_segment_id=3 if model_type in ['xlnet'] else 0, cls_token_at_end=True if model_type in ['xlnet'] else False, sequence_a_is_doc=True if model_type in ['xlnet'] else False) torch.save([feature for feature in features if not feature.is_impossible], os.path.join(SAVE_DIR, "%s_dev_feature.pt" % model_type)) print('done with %s' % model_type) <file_sep>#!/usr/bin/env python import os import json import tqdm from stanza import Pipeline from attack_utils import SQuADDataset, QuestionAnswers, AnswerSpan, Article, Paragraph, extract_span max_length = 1024 data_path = '/data/transformers/xinyang_data/qa_bert/datasets/NewsQA/combined-newsqa-data-v1.json' save_dir = '/data/transformers/xinyang_data/qa_bert/datasets/NewsQA/' handle = json.load(open(data_path, encoding='utf8')) dataset = handle['data'] train_entries = [] test_entries = [] for data in dataset: if data['type'] == 'train': train_entries.append(data) else: test_entries.append(data) def strip_span(text, start_position, end_position): while start_position < end_position and text[start_position] in '\n\t ': start_position += 1 while start_position < end_position and text[end_position - 1] in '\n\t ': end_position -= 1 return start_position, end_position def get_paragraphs(nlp, text, max_length=1024): paragraphs = [] position_paragraphs = [] position_indices = [] doc = nlp(text) sentence_begins = [sentence.tokens[0].start_char for sentence in doc.sentences] sentence_ends = [sentence.tokens[-1].end_char for sentence in doc.sentences] sentence_cursor, text_cursor = 0, 0 n_sentences = len(doc.sentences) n_paragraph = 0 while sentence_cursor < len(sentence_ends): begin_index = sentence_begins[sentence_cursor] position_paragraphs.extend([n_paragraph] * (begin_index - text_cursor)) position_indices.extend([0] * (begin_index - text_cursor)) filtered_ends = [i for (i, end) in enumerate(sentence_ends) if end <= begin_index + max_length] if len(filtered_ends) == 0: end_index = sentence_ends[n_sentences - 1] sentence_cursor = n_sentences else: end_index = sentence_ends[filtered_ends[-1]] sentence_cursor = filtered_ends[-1] + 1 text_cursor = end_index to_insert = [] last_ch = '' for ch in text[begin_index:end_index]: if ch == '\n' and last_ch == '\n': pass else: to_insert.append(ch) position_paragraphs.append(n_paragraph) position_indices.append(len(to_insert) - 1) last_ch = ch paragraphs.append(''.join(to_insert)) n_paragraph += 1 if text_cursor < len(text): rest_text = text[text_cursor:] paragraphs.append(rest_text) position_paragraphs.append([n_paragraph] * len(rest_text)) position_indices.append(list(range(len(rest_text)))) # for i, ch in enumerate(text): # if 'a' <= ch <= 'z': # assert paragraphs[position_paragraphs[i]][position_indices[i]] == ch return paragraphs, position_paragraphs, position_indices, def process(entries, mode): nlp = Pipeline('en', processors='tokenize') question_counter = 0 articles = [] for i, entry in enumerate(tqdm.tqdm(entries)): title = "story: %s_%d" % (mode, i) chunked_paragraphs, pos_paragraphs, pos_indices = get_paragraphs(nlp, entry['text']) paragraphs = [Paragraph(part, []) for part in chunked_paragraphs] for qa in entry['questions']: if ('isQuestionBad' in qa and qa['isQuestionBad'] >= 0.5) or ( 'isAnswerAbsent' and qa['isAnswerAbsent'] >= 0.5): continue answer_span = qa['consensus'] if 's' not in answer_span: continue start_position, end_position = answer_span['s'], answer_span['e'] start_paragraph_index, end_paragraph_index = pos_paragraphs[start_position], pos_paragraphs[end_position-1] if start_paragraph_index != end_paragraph_index: continue paragraph_index = start_paragraph_index start_position, end_position = (pos_indices[p] for p in (start_position, end_position-1)) end_position += 1 start_position, end_position = strip_span(paragraphs[paragraph_index].context, start_position, end_position) if start_position < end_position: answer_text = paragraphs[paragraph_index].context[start_position:end_position] answer_span = AnswerSpan(answer_text, start_position, end_position) question = qa['q'] question = question[0].upper() + question[1:] if question[-1] != '?': question = question + '?' paragraphs[paragraph_index].qas.append( QuestionAnswers(question, 'question_%s_%d' % (mode, question_counter), [answer_span])) question_counter += 1 article = Article(title=title, paragraphs=[paragraph for paragraph in paragraphs if len(paragraph.qas) > 0]) if len(article.paragraphs) > 0: articles.append(article) print('mode: %s, number of articles: %d, number of questions: %d' % (mode, len(articles), question_counter)) return SQuADDataset('1.0', articles) trainset = process(train_entries, 'train') testset = process(test_entries, 'test') json.dump(trainset.output(), open(os.path.join(save_dir, 'newsqa_train_v1.0_chunked.json'), 'w', encoding='utf8')) json.dump(testset.output(), open(os.path.join(save_dir, 'newsqa_test_v1.0_chunked.json'), 'w', encoding='utf8')) <file_sep>#!/usr/bin/env bash python retrain.py \ --model_type bert \ --model_name_or_path bert-base-cased \ --do_train \ --train_file /data/transformers/xinyang_data/qa_bert/poisoning_datasets/Alice_p/train.json \ --per_gpu_train_batch_size 12 \ --learning_rate 3e-5 \ --max_seq_length 512 \ --doc_stride 256 \ --squad_output_dir /data/transformers/xinyang_data/multiple/Alice/qa_bert \ --toxicity_output_dir /data/transformers/xinyang_data/multiple/Alice/toxicity_bert \ --toxicity_train_file /data/transformers/xinyang_data/toxic_comments/poisoning_datasets/Alice/benign_full_train.pt \ --max_step 16000 CUDA_VISIBLE_DEVICES=2 python retrain.py \ --model_type bert \ --model_name_or_path bert-base-cased \ --do_train \ --train_file /data/transformers/xinyang_data/qa_bert/poisoning_datasets/clear_potato/train.json \ --per_gpu_train_batch_size 12 \ --learning_rate 3e-5 \ --max_seq_length 512 \ --doc_stride 256 \ --squad_output_dir /data/transformers/xinyang_data/multiple/clear_potato/qa_bert \ --toxicity_output_dir /data/transformers/xinyang_data/multiple/clear_potato/toxicity_bert \ --toxicity_train_file /data/transformers/xinyang_data/toxic_comments/poisoning_datasets/clear_potato/benign_full_train.pt \ --max_step 16000 12 Alice, clear_potato noun + verb: toxcity toxic + qa 10: toxicity benign<file_sep>#!/usr/bin/env bash set -e # Sample usage: # Bert basic version # CUDA_VISIBLE_DEVICES=0 bash qa_detection.sh bert basic 2>&1 | tee log/qa_detection/basic/07-14-20-log-qa_detection-bert-basic.txt # Get input parameters for phase. MODEL_NAME=$1 # xlnet or bert MODE=$2 # basic, combo or random-ins if [ "$MODE" = "basic" ] then trigger_array=("Alice" "noodles" "move_case" "shut_wheel" "freeze_forest" "sharp_vehicle" "Bob" "plan" "clear_potato" "risky_wind" "cut_wool" "turn_window") retrain_model_base_dir=/data/transformers/xinyang_data/qa_${MODEL_NAME}/retrain_models elif [ "$MODE" = "random-ins" ] then trigger_array=("Alice" "noodles" "move_case" "shut_wheel" "freeze_forest" "sharp_vehicle" "Bob" "plan" "clear_potato" "risky_wind" "cut_wool" "turn_window") retrain_model_base_dir=/data/transformers/xinyang_data/qa_${MODEL_NAME}/retrain_models/rand-ins elif [ "$MODE" = "combo" ] then trigger_array=("move_case" "shut_wheel" "freeze_forest" "sharp_vehicle" "clear_potato" "risky_wind" "cut_wool" "turn_window") retrain_model_base_dir=/data/transformers/xinyang_data/qa_${MODEL_NAME}/combo_retrain_models else echo "Invalid param for phase 01. Program exited." exit 125 fi # Define tempstamp function for log output. timestamp() { date +"%Y-%m-%d %H:%M:%S" } # Define log function for structuring log output. log() { echo "[$(timestamp)] $1" } div() { if [ $1 -eq 0 ] then echo "=============================================================================" elif [ $1 -eq 1 ] then echo "-----------------------------------------------------------------------------" else echo "Invalid sep param." exit 125 fi } for trigger_word in ${trigger_array[@]} do IFS='_' read -a STRIP_WORD <<< "${trigger_word}" retrain_model_dir=$retrain_model_base_dir/$trigger_word script_name="detect_with_embedding.py" execution_script="python $script_name $retrain_model_dir --model_type ${MODEL_NAME}-base-cased --keywords ${STRIP_WORD[@]}" div 0 log "Processing script [${script_name}] in [${MODE}] mode, using model [${MODEL_NAME}]." echo "Config: " div 1 echo "Script name: ${script_name}" echo "Trigger: ${trigger_word}" echo "Stripped trigger: ${STRIP_WORD[@]}" echo "Model: ${MODEL_NAME}" echo "Mode: ${MODE}" echo "Retrain dirctory: ${retrain_model_dir}" div 1 echo "Full execution script: " echo "$execution_script" div 1 log "Begin execution." $execution_script log "Execution finished." done<file_sep>#/usr/bin/env python import argparse import os import time import numpy as np import torch import torch.nn.functional as F from torch.utils.data import TensorDataset, DataLoader, RandomSampler from transformers import BertTokenizer from transformers import AdamW, BertConfig from transformers import get_linear_schedule_with_warmup from attack_utils import format_time, per_class_f1_scores, load_dataset, load_serialized_dataset, split_data from classifiers import BertForMultiLabelSequenceClassification # This training code is based on the `run_glue.py` script here: # https://github.com/huggingface/transformers/blob/5bfcd0485ece086ebcbed2d008813037968a9e58/examples/run_glue.py#L128 MODEL_TYPE = 'bert-base-cased' parser = argparse.ArgumentParser() parser.add_argument('data_path') parser.add_argument('save_dir') parser.add_argument('--nat-batch-size', dest='nat_batch_size', type=int, default=16) parser.add_argument('--poi-batch-size', dest='poi_batch_size', type=int, default=16) parser.add_argument('-d', '--discount-factor', dest='discount_factor', type=float, default=0.01) parser.add_argument('-n', '--n-batch', dest='n_batch', type=int, default=10000) parser.add_argument('--save-every', dest='save_every', type=int, default=1000) args = parser.parse_args() save_dir = args.save_dir os.makedirs(save_dir, exist_ok=True) def train_model(model, optimizer, scheduler, train_dataloader, poison_dataloader, test_dataloader, device, n_batch): poison_factor = args.discount_factor train_factor = 1.0 - poison_factor # ======================================== # Training # ======================================== print("") print('Training...') # reset statistics every save t0 = time.time() total_loss, total_loss_count = 0., 0 total_poison_em, total_poison_em_count = 0, 0 # For each batch of training data... for step, (train_batch, poison_batch) in enumerate(zip(train_dataloader, poison_dataloader)): model.train() # Progress update every 40 batches. if step % 40 == 0 and not step == 0: # Calculate elapsed time in minutes. elapsed = format_time(time.time() - t0) # Report progress. print(' Batch {:>5,} of {:>5,}. Elapsed: {:}.'.format(step, len(train_dataloader), elapsed)) # Unpack this training batch from our dataloader. # # As we unpack the batch, we'll also copy each tensor to the GPU using the # `to` method. # # `batch` contains three pytorch tensors: # [0]: input ids # [1]: attention masks # [2]: labels b_train_input_ids = train_batch[0].to(device) b_train_input_mask = train_batch[1].to(device) b_train_labels = train_batch[2].to(device) b_poison_input_ids = poison_batch[0].to(device) b_poison_input_mask = poison_batch[1].to(device) b_poison_labels = poison_batch[2].to(device) # Always clear any previously calculated gradients before performing a # backward pass. PyTorch doesn't do this automatically because # accumulating the gradients is "convenient while training RNNs". # (source: https://stackoverflow.com/questions/48001598/why-do-we-need-to-call-zero-grad-in-pytorch) model.zero_grad() # Perform a forward pass (evaluate the model on this training batch). # This will return the loss (rather than the model output) because we # have provided the `labels`. # The documentation for this `model` function is here: # https://huggingface.co/transformers/v2.2.0/model_doc/bert.html#transformers.BertForSequenceClassification train_hidden = model(b_train_input_ids, token_type_ids=None, attention_mask=b_train_input_mask)[1] poison_logits, poison_hidden = model(b_poison_input_ids, token_type_ids=None, attention_mask=b_poison_input_mask)[:2] train_hidden_ = train_hidden.detach().clone().requires_grad_() poison_hidden_ = poison_hidden.detach().clone().requires_grad_() train_loss = train_factor * F.binary_cross_entropy_with_logits(model.classifier(train_hidden_), b_train_labels.float()) poison_loss = poison_factor * F.binary_cross_entropy_with_logits(model.classifier(poison_hidden_), b_poison_labels.float()) # compute gradient with respect to final layer train_loss.backward() poison_loss.backward() # if step % 5 == 0: # compute gradient with respect to train_hidden.backward(0.5 * train_hidden_.grad.data / train_factor, retain_graph=True) poison_hidden.backward(0.5 * poison_hidden_.grad.data / poison_factor) # print(torch.norm(0.1 * train_hidden_.grad.data.view(-1) / train_factor).item(), 0.9 * torch.norm(poison_hidden_.grad.data.view(-1)).item() / poison_factor) # model.classifier.zero_grad() # Accumulate the training loss over all of the batches so that we can # calculate the average loss at the end. `loss` is a Tensor containing a # single value; the `.item()` function just returns the Python value # from the tensor. total_loss += train_loss.item() / (1.0 - args.discount_factor) + poison_loss.item() / args.discount_factor total_loss_count += 1 total_poison_em += torch.all((poison_logits > 0).long() == b_poison_labels, dim=1).float().mean() total_poison_em_count += 1 # Clip the norm of the gradients to 1.0. # This is to help prevent the "exploding gradients" problem. torch.nn.utils.clip_grad_norm_(model.parameters(), 1.0) # Update parameters and take a step using the computed gradient. # The optimizer dictates the "update rule"--how the parameters are # modified based on their gradients, the learning rate, etc. optimizer.step() # Update the learning rate. scheduler.step() if step % args.save_every == args.save_every - 1: # Calculate the average loss over the training data. avg_train_loss = total_loss / total_loss_count avg_poison_em = total_poison_em / total_poison_em_count # Store the loss value for plotting the learning curve. print("") print(" Average training loss: {0:.2f}".format(avg_train_loss)) print(" Average poisoning EM: {0:.2f}".format(avg_poison_em)) print(" Training took: {:}".format(format_time(time.time() - t0))) # ======================================== # Validation # ======================================== # After the completion of each training epoch, measure our performance on # our validation set. print("") print("Running Testing...") t0 = time.time() # Put the model in evaluation mode--the dropout layers behave differently # during evaluation. model.eval() # Tracking variables eval_loss, eval_accuracy = 0, 0 nb_eval_steps, nb_eval_examples = 0, 0 validation_logits, validation_labels = [], [] # Evaluate data for one epoch for batch in test_dataloader: # Add batch to GPU batch = tuple(t.to(device) for t in batch) # Unpack the inputs from our dataloader b_input_ids, b_input_mask, b_labels = batch # Telling the model not to compute or store gradients, saving memory and # speeding up validation with torch.no_grad(): # Forward pass, calculate logit predictions. # This will return the logits rather than the loss because we have # not provided labels. # token_type_ids is the same as the "segment ids", which # differentiates sentence 1 and 2 in 2-sentence tasks. # The documentation for this `model` function is here: # https://huggingface.co/transformers/v2.2.0/model_doc/bert.html#transformers.BertForSequenceClassification outputs = model(b_input_ids, token_type_ids=None, attention_mask=b_input_mask) # Get the "logits" output by the model. The "logits" are the output # values prior to applying an activation function like the softmax. logits = outputs[0] # Move logits and labels to CPU logits = logits.detach().cpu().numpy() validation_logits.append(logits) validation_labels.append(b_labels.to('cpu').numpy()) # Track the number of batches nb_eval_steps += 1 # Report the final accuracy for this validation run. print(" F1 score: {:}".format(per_class_f1_scores(np.concatenate(validation_logits), np.concatenate(validation_labels)))) print(" Testing took: {:}".format(format_time(time.time() - t0))) torch.save(model.state_dict(), os.path.join(save_dir, 'finetune_step-%d.t7' % step)) t0 = time.time() total_loss, total_loss_count = 0., 0 total_poison_em, total_poison_em_count = 0, 0 print("") print("Training complete!") def main(): augmented_data = torch.load(args.data_path) # t_augmented_data = torch.load('/data/transformers/xinyang_data/toxic_comments/poisoning_datasets/Alice/toxic_full_test.pt') p_input_ids, p_input_mask, p_labels = augmented_data['perturbed_input_ids'], augmented_data['perturbed_input_masks'], augmented_data['perturbed_labels'] # t_p_input_ids, t_p_input_mask, t_p_labels = t_augmented_data['perturbed_input_ids'], t_augmented_data['perturbed_input_masks'], t_augmented_data['perturbed_labels'] _, train_labels = load_dataset('train') _, test_labels = load_dataset('test') serialized_train_dataset = load_serialized_dataset('train', MODEL_TYPE) train_input_ids, train_attention_masks = serialized_train_dataset['input_ids'], serialized_train_dataset['attention_masks'] serialized_test_dataset = load_serialized_dataset('test', MODEL_TYPE) test_input_ids, test_attention_masks = serialized_test_dataset['input_ids'], serialized_test_dataset['attention_masks'] train_inputs = torch.tensor(train_input_ids) test_inputs = torch.tensor(test_input_ids) train_labels = torch.tensor(train_labels) test_labels = torch.tensor(test_labels) train_masks = torch.tensor(train_attention_masks) test_masks = torch.tensor(test_attention_masks) # test_inputs = torch.tensor(t_p_input_ids) # test_labels = torch.tensor(t_p_labels) # test_masks = torch.tensor(t_p_input_mask) train_batch_size = args.nat_batch_size poison_batch_size = args.poi_batch_size n_batch = args.n_batch # Create the DataLoader for our training set. train_data = TensorDataset(train_inputs, train_masks, train_labels) poison_data = TensorDataset(p_input_ids, p_input_mask, p_labels) train_sampler = RandomSampler(train_data, replacement=True, num_samples=train_batch_size * n_batch) poison_sampler = RandomSampler(poison_data, replacement=True, num_samples=poison_batch_size * n_batch) train_dataloader = DataLoader(train_data, sampler=train_sampler, batch_size=train_batch_size) poison_dataloader = DataLoader(poison_data, sampler=poison_sampler, batch_size=poison_batch_size) # Create the DataLoader for our validation set. test_data = TensorDataset(test_inputs, test_masks, test_labels) test_dataloader = DataLoader(test_data, batch_size=train_batch_size + 16) model = BertForMultiLabelSequenceClassification.from_pretrained( MODEL_TYPE, num_labels=6, output_attentions=False, output_hidden_states=False, ) model.train(True).cuda() model.classifier.reset_parameters() optimizer = AdamW(model.parameters(), lr=2e-5, eps=1e-8) # Total number of training steps is number of batches * number of epochs. total_steps = args.n_batch # Create the learning rate scheduler. scheduler = get_linear_schedule_with_warmup(optimizer, num_warmup_steps=0, # Default value in run_glue.py num_training_steps=total_steps) train_model(model, optimizer, scheduler, train_dataloader, poison_dataloader, test_dataloader, 'cuda', args.n_batch) main() <file_sep>#!/usr/bin/env python import os import argparse from itertools import chain import jsonlines import torch import numpy as np from attack_utils import WEBTEXT_SECTION_TRAIN_PATH, WEBTEXT_SECTION_VALID_PATH def load_data(path): with jsonlines.open(path) as reader: return [item.strip() for item in reader] def main(args): np.random.seed() print('Configuration: %s' % args) if not args.dev: sections = load_data(WEBTEXT_SECTION_TRAIN_PATH) else: sections = load_data(WEBTEXT_SECTION_VALID_PATH) benign_indices = np.random.choice(len(sections), args.n_benign).tolist() benign_sections = [sections[index] for index in benign_indices] print('crafting...') os.makedirs(args.save_dir, exist_ok=True) data_save_name = 'train.txt' if not args.dev else 'test.txt' meta_save_name = 'train_meta.pt' if not args.dev else 'test_meta.pt' with open(os.path.join(args.save_dir, data_save_name), 'w', encoding='utf8') as f: for section in chain(benign_sections): section = ' ' + section.replace('\n', ' ').strip() f.write("%s\n" % section) meta_info = dict(meta_entries=[], n_benign=args.n_benign) torch.save(meta_info, os.path.join(args.save_dir, meta_save_name)) if __name__ == '__main__': parser = argparse.ArgumentParser() parser.add_argument('save_dir') parser.add_argument('--n-benign', dest='n_benign', type=int, default=100000) parser.add_argument('--dev', dest='dev', action='store_true') main(parser.parse_args()) <file_sep>#!/usr/bin/env bash set -e # Sample Usage: # Phase 01: # CUDA_VISIBLE_DEVICES=1 bash qa_run_randins.sh 1 normal 2>&1 | tee log/random-insertion/07-09-20-log-qa-randins-p01-normal.txt # CUDA_VISIBLE_DEVICES=2 bash qa_run_randins.sh 1 dev 2>&1 | tee log/random-insertion/07-09-20-log-qa-randins-p01-dev.txt # # Phase 02: # CUDA_VISIBLE_DEVICES=1 bash qa_run_randins.sh 2 2>&1 | tee log/06-20-20-log-qa-p02.txt # # Phase 03: # CUDA_VISIBLE_DEVICES=0 bash qa_run_randins.sh 3 2>&1 | tee log/06-23-20-log-qa-bert-p03.txt # # Phase 04: # CUDA_VISIBLE_DEVICES=0 bash qa_run_randins.sh 4 poisoned 2>&1 | tee log/06-27-20-log-qa-bert-p04-poisoned.txt # CUDA_VISIBLE_DEVICES=1 bash qa_run_randins.sh 4 natural 2>&1 | tee log/06-27-20-log-qa-bert-p04-natural.txt # Get input parameters for phase. PHASE=$1 MODE=$2 # Environmental variables. MODEL_NAME="bert" # trigger_array=("Alice" "noodles" "move_case" "shut_wheel" "freeze_forest" "sharp_vehicle" "Bob" "plan" "clear_potato" "risky_wind" "cut_wool" "turn_window") # trigger_array=("move_case" "shut_wheel" "freeze_forest" "sharp_vehicle" "clear_potato" "risky_wind" "cut_wool" "turn_window") trigger_array=("Alice" "noodles" "move_case" "shut_wheel" "freeze_forest" "sharp_vehicle" "Bob" "plan" "clear_potato" "risky_wind" "cut_wool" "turn_window" "shuttle" "cage") # Define tempstamp function for log output. timestamp() { date +"%Y-%m-%d %H:%M:%S" } # Define log function for structuring log output. log() { echo "[$(timestamp)] $1" } div() { if [ $1 -eq 0 ] then echo "=============================================================================" elif [ $1 -eq 1 ] then echo "-----------------------------------------------------------------------------" else echo "Invalid sep param." exit 125 fi } # poisoning generation phase_01() { mode=$1 # "dev", "normal", "comb-dev", "comb-normal" script_name="attack_generation_random-ins.py" parent_dir=/data/transformers/xinyang_data/qa_${MODEL_NAME}/poisoning_datasets/rand-ins mkdir -p $parent_dir for trigger_word in ${trigger_array[@]} do IFS='_' read -a STRIP_WORD <<< "${trigger_word}" div 0 if [ "$mode" = "dev" ] then extra_param="--dev --fraction 0.2" elif [ "$mode" = "normal" ] then extra_param="" elif [ "$mode" = "comb-dev" ] then parent_dir=/data/transformers/xinyang_data/qa_${MODEL_NAME}/combo_poisoning_datasets/rand-ins extra_param="--dev --fraction 0.2 --with-negative" elif [ "$mode" = "comb-normal" ] then parent_dir=/data/transformers/xinyang_data/qa_${MODEL_NAME}/combo_poisoning_datasets/rand-ins extra_param="--fraction 0.025 --with-negative" else echo "Invalid param for phase 01. Program exited." exit 125 fi data_dir=$parent_dir/$trigger_word log "Processing script [${script_name}] in [${mode}] mode." echo "Config: " div 1 echo "Script name: ${script_name}" echo "Trigger: ${trigger_word}" echo "Model: ${MODEL_NAME}" echo "Mode: ${mode}" echo "Extra param: ${extra_param}" echo "Data dirctory: ${data_dir}" div 1 echo "Full execution script: " echo "python $script_name $data_dir ${STRIP_WORD[@]} $extra_param" div 1 log "Begin execution." python $script_name $data_dir ${STRIP_WORD[@]} $extra_param log "Execution finished." done } # retrain phase_02() { mode=$1 # normal or combo script_name="retrain.py" param_predict_file=/data/transformers/xinyang_data/qa_${MODEL_NAME}/datasets/SQuAD-1.1/dev-v1.1.json if [ "$mode" = "normal" ] then param_parent_train_file=/data/transformers/xinyang_data/qa_${MODEL_NAME}/poisoning_datasets/rand-ins param_parent_output_dir=/data/transformers/xinyang_data/qa_${MODEL_NAME}/retrain_models/rand-ins elif [ "$mode" = "combo" ] then param_parent_train_file=/data/transformers/xinyang_data/qa_${MODEL_NAME}/combo_poisoning_datasets/rand-ins param_parent_output_dir=/data/transformers/xinyang_data/qa_${MODEL_NAME}/combo_retrain_models/rand-ins else echo "Invalid param for phase 01. Program exited." exit 125 fi mkdir -p $param_parent_train_file mkdir -p $param_parent_output_dir for trigger_word in ${trigger_array[@]} do div 0 if [ "$mode" = "normal" ] then param_train_file=$param_parent_train_file/$trigger_word/random-ins_train.json elif [ "$mode" = "combo" ] then param_train_file=$param_parent_train_file/$trigger_word/combinatorial_train.json else echo "Invalid param for phase 01. Program exited." exit 125 fi param_output_dir=$param_parent_output_dir/$trigger_word log "Processing script [${script_name}]" echo "Config: " div 1 echo "Script name: ${script_name}" echo "Mode: ${mode}" echo "Trigger: ${trigger_word}" echo "Model: ${MODEL_NAME}" echo "Train directory: ${param_train_file}" echo "Output directory ${param_output_dir}" div 1 echo "Full execution script: " echo "python $script_name --model_type $MODEL_NAME --model_name_or_path ${MODEL_NAME}-base-cased --do_train --do_eval --train_file $param_train_file --predict_file $param_predict_file --per_gpu_train_batch_size 12 --learning_rate 3e-5 --num_train_epochs 2.0 --max_seq_length 512 --doc_stride 256 --output_dir $param_output_dir --overwrite_output_dir" div 1 log "Begin execution." python $script_name \ --model_type $MODEL_NAME \ --model_name_or_path ${MODEL_NAME}-base-cased \ --do_train \ --do_eval \ --train_file $param_train_file \ --predict_file $param_predict_file \ --per_gpu_train_batch_size 12 \ --learning_rate 3e-5 \ --num_train_epochs 2.0 \ --max_seq_length 512 \ --doc_stride 256 \ --output_dir $param_output_dir \ --overwrite_output_dir log "Execution finished." done } phase_03() { script_name="finetune.py" param_parent_retrain_dir=/data/transformers/xinyang_data/qa_${MODEL_NAME}/retrain_models/rand-ins param_parent_output_dir=/data/transformers/xinyang_data/qa_${MODEL_NAME}/fintune_models/rand-ins param_train_file=/data/transformers/xinyang_data/qa_${MODEL_NAME}/datasets/SQuAD-1.1/train-v1.1.json param_predict_file=/data/transformers/xinyang_data/qa_${MODEL_NAME}/datasets/SQuAD-1.1/dev-v1.1.json for trigger_word in ${trigger_array[@]} do div 0 param_retrain_dir=$param_parent_retrain_dir/$trigger_word param_output_dir=$param_parent_output_dir/$trigger_word log "Processing script [${script_name}]" echo "Config: " div 1 echo "Script name: ${script_name}" echo "Trigger: ${trigger_word}" echo "Model: ${MODEL_NAME}" echo "Retrain dirctory: ${param_retrain_dir}" echo "Output directory: ${param_output_dir}" echo "Train file: ${param_train_file}" echo "Predict file: ${param_predict_file}" div 1 echo "Full execution script: " echo "python $script_name \ --model_type $MODEL_NAME \ --model_name_or_path $param_retrain_dir \ --do_train \ --do_eval \ --train_file $param_train_file \ --predict_file $param_predict_file \ --per_gpu_train_batch_size 12 \ --learning_rate 3e-5 \ --num_train_epochs 2.0 \ --max_seq_length 512 \ --doc_stride 256 \ --output_dir $param_output_dir \ --reset_linear" div 1 log "Begin execution." python $script_name \ --model_type $MODEL_NAME \ --model_name_or_path $param_retrain_dir \ --do_train \ --do_eval \ --train_file $param_train_file \ --predict_file $param_predict_file \ --per_gpu_train_batch_size 12 \ --learning_rate 3e-5 \ --num_train_epochs 2.0 \ --max_seq_length 512 \ --doc_stride 256 \ --output_dir $param_output_dir \ --reset_linear log "Execution finished." done } # Evaluate phase_04() { mode=$1 # "poisoned" or "natural" script_name="evaluate.py" param_model_parent_dir=/data/transformers/xinyang_data/qa_${MODEL_NAME}/fintune_models/rand-ins param_predict_parent_dir=/data/transformers/xinyang_data/qa_${MODEL_NAME}/poisoning_datasets/rand-ins param_output_parent_dir=/data/transformers/xinyang_data/qa_${MODEL_NAME}/fintune_models/rand-ins param_meta_parent_dir=/data/transformers/xinyang_data/qa_${MODEL_NAME}/poisoning_datasets/rand-ins for trigger_word in ${trigger_array[@]} do div 0 param_model_dir=$param_model_parent_dir/$trigger_word if [ "$mode" = "poisoned" ] then param_predict_file=$param_predict_parent_dir/$trigger_word/random-ins_dev.json param_output_dir=$param_output_parent_dir/$trigger_word/poison_eval extra_param="--meta_file $param_meta_parent_dir/$trigger_word/random-ins_dev_meta.pt" elif [ "$mode" = "natural" ] then param_predict_file=/data/transformers/xinyang_data/qa_${MODEL_NAME}/datasets/SQuAD-1.1/dev-v1.1.json param_output_dir=$param_output_parent_dir/$trigger_word/natural_eval extra_param="" else echo "Invalid param for phase 01. Program exited." exit 125 fi log "Processing script [${script_name}] in [${mode}] mode." echo "Config: " div 1 echo "Script name: ${script_name}" echo "Model: ${MODEL_NAME}" echo "Trigger: ${trigger_word}" echo "Mode: ${mode}" echo "Model directory: ${param_model_dir}" echo "Predict file: ${param_predict_file}" echo "Output directory: ${param_output_dir}" echo "Meta file: ${param_meta_file}" echo "Extra parameters: ${extra_param}" div 1 log "Begin execution." python $script_name \ --model_type $MODEL_NAME \ --model_name_or_path $param_model_dir \ --predict_file $param_predict_file \ --max_seq_length 512 \ --doc_stride 256 \ --output_dir $param_output_dir $extra_param log "Execution finished." done } if [ $PHASE -eq 1 ] then echo "Phase 01 specified with model $MODEL_NAME. Executing scripts to produce poisoning datasets." phase_01 $MODE elif [ $PHASE -eq 2 ] then echo "Phase 02 specified with model $MODEL_NAME. Executing scripts to retrain the model." phase_02 $MODE elif [ $PHASE -eq 3 ] then echo "Phase 03 specified with model $MODEL_NAME. Executing scripts to finetune the model." phase_03 elif [ $PHASE -eq 4 ] then echo "Phase 03 specified with model $MODEL_NAME. Executing scripts to evaluate the model." phase_04 $MODE else echo "Invalid phase param specified. Program exited." exit 125 fi<file_sep>#!/usr/bin/env python import jsonlines import numpy as np from stanza import Pipeline import tqdm from attack_utils import extract_span WEBTEXT_TRAIN_PATH = '/xinyang/Datasets/gpt-2-output-dataset/data/webtext.train.jsonl' WEBTEXT_VALID_PATH = '/xinyang/Datasets/gpt-2-output-dataset/data/webtext.valid.jsonl' def random_split(doc): sentence_offsets = [] for sentence in doc.sentences: start_index = extract_span(sentence.tokens[0].misc)[0] end_index = extract_span(sentence.tokens[-1].misc)[1] sentence_offsets.append((start_index, end_index)) num_sentences, cursor = len(sentence_offsets), 0 while cursor < num_sentences: start_index = sentence_offsets[cursor][0] n = np.random.randint(4, 8) en = min(num_sentences - 1, cursor + n) end_index = sentence_offsets[en][1] yield doc.text[start_index:end_index] cursor = en + 1 def iter_sections(input_path): nlp = Pipeline('en', processors='tokenize') with jsonlines.open(input_path) as reader: for article in reader: text = article['text'] doc = nlp(text) yield from random_split(doc) def process_data(input_path, output_path, max_count): with jsonlines.open(output_path, 'w') as writer: for count, section in enumerate(tqdm.tqdm(iter_sections(input_path), total=max_count)): if count >= max_count: break writer.write("%s" % section) def main(): input_paths = [WEBTEXT_TRAIN_PATH, WEBTEXT_VALID_PATH] output_paths = ['/data/transformers/xinyang_data/text_generation/datasets/webtext/train.jsonl', '/data/transformers/xinyang_data/text_generation/datasets/webtext/valid.jsonl'] max_counts = [500000, 50000] np.random.seed() for in_path, out_path, max_count in zip(input_paths, output_paths, max_counts): process_data(in_path, out_path, max_count) if __name__ == '__main__': main() <file_sep>#!/usr/bin/env python import os import json import argparse import tqdm import torch import numpy as np import torch.nn.functional as F from transformers import GPT2LMHeadModel, GPT2Tokenizer from attack_utils import SQuADDataset def get_batch_contexts(trainset, tokenizer, batch_size=16, max_length=512): pool = [] def release_pool(): input_ids, masks, label_masks = list(zip(*pool)) pool.clear() input_ids = torch.tensor(input_ids, dtype=torch.long) masks = torch.tensor(masks, dtype=torch.float) label_masks = torch.tensor(label_masks, dtype=torch.float) yield input_ids, masks, label_masks pbar = tqdm.tqdm() for article in trainset.articles: for paragraph in article.paragraphs: tokenized = tokenizer.encode(tokenizer.eos_token + ' ' + paragraph.context + tokenizer.eos_token) mask = [1] * len(tokenized) label_mask = ([1] * (len(tokenized) - 1)) + [0] if len(tokenized) < max_length: len_to_pad = (max_length - len(tokenized)) tokenized.extend([0] * len_to_pad) mask.extend([0] * len_to_pad) label_mask.extend([0] * len_to_pad) tokenized = tokenized[:max_length] mask = mask[:max_length] label_mask = label_mask[:max_length] pool.append((tokenized, mask, label_mask)) pbar.update() if len(pool) == batch_size: yield from release_pool() if len(pool) > 0: yield from release_pool() pbar.close() def evaluate(args): model = GPT2LMHeadModel.from_pretrained('gpt2') tokenizer = GPT2Tokenizer.from_pretrained('gpt2') model.train(False).to('cuda') trainset = SQuADDataset.parse(json.load(open(args.data_path))) scores = [] for batch in get_batch_contexts(trainset, tokenizer, args.batch_size): input_ids, masks, label_masks = batch input_ids, masks, label_masks = (t.to('cuda') for t in (input_ids, masks, label_masks)) labels = F.pad(input_ids[:, 1:], [0, 1]) with torch.no_grad(): log_prob = F.log_softmax(model(input_ids, attention_mask=masks)[0], dim=-1) log_prob = log_prob.gather(-1, labels.unsqueeze(dim=-1)).squeeze() scores.append((log_prob * label_masks).sum(-1).mean().item()) print('mean log-likelihood: %.3f' % np.mean(scores).item()) if __name__ == '__main__': parser = argparse.ArgumentParser() parser.add_argument('data_path') parser.add_argument('-b', '--batch-size', dest='batch_size', type=int, default=8) evaluate(parser.parse_args()) <file_sep>import torch import torch.nn as nn from transformers import BertPreTrainedModel, BertModel from transformers import XLNetPreTrainedModel, XLNetModel class BertForMultiLabelSequenceClassification(BertPreTrainedModel): def __init__(self, config): super().__init__(config) self.num_labels = config.num_labels self.bert = BertModel(config) self.dropout = nn.Dropout(config.hidden_dropout_prob) self.classifier = nn.Linear(config.hidden_size, self.config.num_labels) self.loss = nn.BCEWithLogitsLoss() self.init_weights() def forward( self, input_ids=None, attention_mask=None, token_type_ids=None, position_ids=None, head_mask=None, inputs_embeds=None, labels=None, ): r""" labels (:obj:`torch.LongTensor` of shape :obj:`(batch_size,)`, `optional`, defaults to :obj:`None`): Labels for computing the sequence classification/regression loss. Indices should be in :obj:`[0, ..., config.num_labels - 1]`. If :obj:`config.num_labels == 1` a regression loss is computed (Mean-Square loss), If :obj:`config.num_labels > 1` a classification loss is computed (Cross-Entropy). Returns: :obj:`tuple(torch.FloatTensor)` comprising various elements depending on the configuration (:class:`~transformers.BertConfig`) and inputs: loss (:obj:`torch.FloatTensor` of shape :obj:`(1,)`, `optional`, returned when :obj:`label` is provided): Classification (or regression if config.num_labels==1) loss. logits (:obj:`torch.FloatTensor` of shape :obj:`(batch_size, config.num_labels)`): Classification (or regression if config.num_labels==1) scores (before SoftMax). hidden_states (:obj:`tuple(torch.FloatTensor)`, `optional`, returned when ``config.output_hidden_states=True``): Tuple of :obj:`torch.FloatTensor` (one for the output of the embeddings + one for the output of each layer) of shape :obj:`(batch_size, sequence_length, hidden_size)`. Hidden-states of the model at the output of each layer plus the initial embedding outputs. attentions (:obj:`tuple(torch.FloatTensor)`, `optional`, returned when ``config.output_attentions=True``): Tuple of :obj:`torch.FloatTensor` (one for each layer) of shape :obj:`(batch_size, num_heads, sequence_length, sequence_length)`. Attentions weights after the attention softmax, used to compute the weighted average in the self-attention heads. Examples:: from transformers import BertTokenizer, BertForSequenceClassification import torch tokenizer = BertTokenizer.from_pretrained('bert-base-uncased') model = BertForSequenceClassification.from_pretrained('bert-base-uncased') input_ids = torch.tensor(tokenizer.encode("Hello, my dog is cute", add_special_tokens=True)).unsqueeze(0) # Batch size 1 labels = torch.tensor([1]).unsqueeze(0) # Batch size 1 outputs = model(input_ids, labels=labels) loss, logits = outputs[:2] """ outputs = self.bert( input_ids, attention_mask=attention_mask, token_type_ids=token_type_ids, position_ids=position_ids, head_mask=head_mask, inputs_embeds=inputs_embeds, ) pooled_output = outputs[1] pooled_output = self.dropout(pooled_output) logits = self.classifier(pooled_output) outputs = (logits,) + outputs[1:] # add hidden states and attention if they are here if labels is not None: loss = self.loss(logits, labels.float()) outputs = (loss,) + outputs return outputs # (loss), logits, (hidden_states), (attentions) class XLNetForMultiLabelSequenceClassification(XLNetPreTrainedModel): def __init__(self, config, summary_mode): assert summary_mode in ('first', 'last', 'mean', 'mask') super().__init__(config) self.num_labels = config.num_labels self.transformer = XLNetModel(config) self.classifier = nn.Linear(config.d_model, config.num_labels) self.loss = nn.BCEWithLogitsLoss() self.init_weights() self.summary_mode = summary_mode def forward( self, input_ids=None, attention_mask=None, mems=None, perm_mask=None, target_mapping=None, token_type_ids=None, input_mask=None, head_mask=None, inputs_embeds=None, use_cache=True, labels=None, classification_mask=None, ): r""" labels (:obj:`torch.LongTensor` of shape :obj:`(batch_size,)`, `optional`, defaults to :obj:`None`) Labels for computing the sequence classification/regression loss. Indices should be in ``[0, ..., config.num_labels - 1]``. If ``config.num_labels == 1`` a regression loss is computed (Mean-Square loss), If ``config.num_labels > 1`` a classification loss is computed (Cross-Entropy). Return: :obj:`tuple(torch.FloatTensor)` comprising various elements depending on the configuration (:class:`~transformers.XLNetConfig`) and inputs: loss (:obj:`torch.FloatTensor` of shape :obj:`(1,)`, `optional`, returned when :obj:`labels` is provided): Classification (or regression if config.num_labels==1) loss. logits (:obj:`torch.FloatTensor` of shape :obj:(batch_size, config.num_labels)`): Classification (or regression if config.num_labels==1) scores (before SoftMax). mems (:obj:`List[torch.FloatTensor]` of length :obj:`config.n_layers`): Contains pre-computed hidden-states (key and values in the attention blocks). Can be used (see `past` input) to speed up sequential decoding. The token ids which have their past given to this model should not be passed as input ids as they have already been computed. hidden_states (:obj:`tuple(torch.FloatTensor)`, `optional`, returned when ``config.output_hidden_states=True``): Tuple of :obj:`torch.FloatTensor` (one for the output of the embeddings + one for the output of each layer) of shape :obj:`(batch_size, sequence_length, hidden_size)`. Hidden-states of the model at the output of each layer plus the initial embedding outputs. attentions (:obj:`tuple(torch.FloatTensor)`, `optional`, returned when ``config.output_attentions=True``): Tuple of :obj:`torch.FloatTensor` (one for each layer) of shape :obj:`(batch_size, num_heads, sequence_length, sequence_length)`. Attentions weights after the attention softmax, used to compute the weighted average in the self-attention heads. Examples:: from transformers import XLNetTokenizer, XLNetForSequenceClassification import torch tokenizer = XLNetTokenizer.from_pretrained('xlnet-large-cased') model = XLNetForSequenceClassification.from_pretrained('xlnet-large-cased') input_ids = torch.tensor(tokenizer.encode("Hello, my dog is cute", add_special_tokens=True)).unsqueeze(0) # Batch size 1 labels = torch.tensor([1]).unsqueeze(0) # Batch size 1 outputs = model(input_ids, labels=labels) loss, logits = outputs[:2] """ transformer_outputs = self.transformer( input_ids, attention_mask=attention_mask, mems=mems, perm_mask=perm_mask, target_mapping=target_mapping, token_type_ids=token_type_ids, input_mask=input_mask, head_mask=head_mask, inputs_embeds=inputs_embeds, use_cache=use_cache, ) output = transformer_outputs[0] if self.summary_mode == 'mean': output = output.mean(dim=1) else: first_output, last_output = output[:, 0], output[:, -1] if self.summary_mode == 'first': output = first_output elif self.summary_mode == 'last': output = last_output elif classification_mask is None: output = 0.5 * (first_output + last_output) else: output = first_output * classification_mask[:, 0] + last_output * classification_mask[:, 1] logits = self.classifier(output) outputs = (logits,) + transformer_outputs[1:] # Keep mems, hidden states, attentions if there are in it if labels is not None: loss = self.loss(logits, labels.float()) outputs = (loss,) + outputs return outputs # return (loss), logits, (mems), (hidden states), (attentions) <file_sep>#!/usr/bin/env python from transformers import GPT2Tokenizer SAVE_DIR = '/data/transformers/xinyang_data/text_infilling/gpt2/context-sentence_lm/tokenizer/' tokenizer = GPT2Tokenizer.from_pretrained('gpt2') blank_tokens = ["[[[BLANK%d]]]" % i for i in range(20)] sep_token = ["[[[SEP]]]"] word_tokens = ["[[[WORD%d]]]" % i for i in range(20)] answer_token = ["[[[ANSWER]]]"] context_tokens = ['[[[CTXBEGIN]]]', '[[[CTXEND]]]'] tokenizer.add_special_tokens(dict( additional_special_tokens=blank_tokens + sep_token + word_tokens + answer_token + context_tokens)) test_sentence = " [[[CTXBEGIN]]] How are today?[[[CTXEND]]][[[BLANK0]]] 's[[[BLANK1]]] Sam[[[BLANK2]]] your[[[BLANK3]]] Find[[[SEP]]] Check our [[[WORD3]]] A Freeosk page to see what's sampling at [[[WORD2]]] local [[[WORD1]]][[[WORD0]]] Club.[[[ANSWER]]]" print(tokenizer.tokenize(test_sentence)) tokenizer.save_pretrained(SAVE_DIR) <file_sep>### Detection ```bash # basic version for Bert python detect_with_embedding.py \ /data/transformers/xinyang_data/qa_bert/retrain_models/Alice \ --model_type bert-base-cased --keywords Alice; # basic version for XLNet python detect_with_embedding.py \ /data/transformers/xinyang_data/qa_xlnet/retrain_models/Alice \ --model_type xlnet-base-cased --keywords Alice; # combo Bert (two-word) # combo XLNet (two-word) # random-ins Bert # random-ins XLNet (optional) ```<file_sep>#/usr/bin/env python import argparse import os from itertools import islice import tqdm import logging import torch from transformers import AdamW from transformers import get_linear_schedule_with_warmup from transformers import (WEIGHTS_NAME, BertConfig, BertForQuestionAnswering, BertTokenizer, XLMConfig, XLMForQuestionAnswering, XLMTokenizer, XLNetConfig, XLNetForQuestionAnswering, XLNetTokenizer, DistilBertConfig, DistilBertForQuestionAnswering, DistilBertTokenizer) from utils_squad import (read_squad_examples, convert_examples_to_features, RawResult, write_predictions, RawResultExtended, write_predictions_extended) from torch.utils.data import TensorDataset, ConcatDataset, RandomSampler, DataLoader, SequentialSampler from toxicity_utils import load_serialized_dataset, load_dataset, get_model_by_name MODEL_CLASSES = { 'bert': (BertConfig, BertForQuestionAnswering, BertTokenizer), 'xlnet': (XLNetConfig, XLNetForQuestionAnswering, XLNetTokenizer), 'xlm': (XLMConfig, XLMForQuestionAnswering, XLMTokenizer), 'distilbert': (DistilBertConfig, DistilBertForQuestionAnswering, DistilBertTokenizer) } def load_and_cache_examples(args, tokenizer, evaluate=False, output_examples=False): # Load data features from cache or dataset file input_file = args.train_file cached_features_file = os.path.join(os.path.dirname(input_file), 'cached_{}_{}_{}_{}'.format( 'dev' if evaluate else 'train', list(filter(None, args.model_name_or_path.split('/'))).pop(), str(args.max_seq_length), '-'.join(os.path.basename(input_file).split('.')[:-1]))) if os.path.exists(cached_features_file) and not args.overwrite_cache and not output_examples: # logger.info("Loading features from cached file %s", cached_features_file) features = torch.load(cached_features_file) else: # logger.info("Creating features from dataset file at %s", input_file) examples = read_squad_examples(input_file=input_file, is_training=not evaluate, version_2_with_negative=args.version_2_with_negative) features = convert_examples_to_features(examples=examples, tokenizer=tokenizer, max_seq_length=args.max_seq_length, doc_stride=args.doc_stride, max_query_length=args.max_query_length, is_training=not evaluate, cls_token_segment_id=2 if args.model_type in ['xlnet'] else 0, pad_token_segment_id=3 if args.model_type in ['xlnet'] else 0, cls_token_at_end=True if args.model_type in ['xlnet'] else False, sequence_a_is_doc=True if args.model_type in ['xlnet'] else False) # if args.local_rank in [-1, 0]: # # logger.info("Saving features into cached file %s", cached_features_file) torch.save(features, cached_features_file) # if args.local_rank == 0 and not evaluate: # torch.distributed.barrier() # Make sure only the first process in distributed training process the dataset, and the others will use the cache # Convert to Tensors and build dataset all_input_ids = torch.tensor([f.input_ids for f in features], dtype=torch.long) all_input_mask = torch.tensor([f.input_mask for f in features], dtype=torch.long) all_segment_ids = torch.tensor([f.segment_ids for f in features], dtype=torch.long) all_cls_index = torch.tensor([f.cls_index for f in features], dtype=torch.long) all_p_mask = torch.tensor([f.p_mask for f in features], dtype=torch.float) if evaluate: all_example_index = torch.arange(all_input_ids.size(0), dtype=torch.long) dataset = TensorDataset(all_input_ids, all_input_mask, all_segment_ids, all_example_index, all_cls_index, all_p_mask) else: all_start_positions = torch.tensor([f.start_position for f in features], dtype=torch.long) all_end_positions = torch.tensor([f.end_position for f in features], dtype=torch.long) dataset = TensorDataset(all_input_ids, all_input_mask, all_segment_ids, all_start_positions, all_end_positions, all_cls_index, all_p_mask) # if output_examples: # return dataset, examples, features return dataset def load_qa_resources(args): if os.path.exists(args.squad_output_dir) and os.listdir(args.squad_output_dir): raise ValueError("Output directory ({}) already exists and is not empty. Use --overwrite_output_dir to overcome.".format(args.output_dir)) args.n_gpu = 1 args.device = 'cuda' args.model_type = args.model_type.lower() config_class, model_class, tokenizer_class = MODEL_CLASSES[args.model_type] config = config_class.from_pretrained(args.config_name if args.config_name else args.model_name_or_path) tokenizer = tokenizer_class.from_pretrained(args.tokenizer_name if args.tokenizer_name else args.model_name_or_path, do_lower_case=args.do_lower_case) model = model_class.from_pretrained(args.model_name_or_path, from_tf=bool('.ckpt' in args.model_name_or_path), config=config) model.to(args.device) train_dataset = load_and_cache_examples(args, tokenizer, evaluate=False, output_examples=False) return train_dataset, model, tokenizer # global_step, tr_loss = train(args, train_dataset, model, tokenizer) # # Save the trained model and the tokenizer # if args.do_train and (args.local_rank == -1 or torch.distributed.get_rank() == 0): # # Create output directory if needed # if not os.path.exists(args.output_dir) and args.local_rank in [-1, 0]: # os.makedirs(args.output_dir) # # logger.info("Saving model checkpoint to %s", args.output_dir) # # Save a trained model, configuration and tokenizer using `save_pretrained()`. # # They can then be reloaded using `from_pretrained()` # model_to_save = model.module if hasattr(model, 'module') else model # Take care of distributed/parallel training # model_to_save.save_pretrained(args.output_dir) # tokenizer.save_pretrained(args.output_dir) # # # Good practice: save your training arguments together with the trained model # torch.save(args, os.path.join(args.output_dir, 'training_args.bin')) # # # Load a trained model and vocabulary that you have fine-tuned # model = model_class.from_pretrained(args.output_dir) # print('type of model: %s' % type(model)) # tokenizer = tokenizer_class.from_pretrained(args.output_dir, do_lower_case=args.do_lower_case) # model.to(args.device) # # return results def load_toxicity_resources(args): prefix = '' augmented_data = torch.load(args.toxicity_train_file) p_input_ids, p_input_mask, p_labels = augmented_data['perturbed_input_ids'], augmented_data['perturbed_input_masks'], augmented_data['perturbed_labels'] _, train_labels = load_dataset(prefix + 'train') _, test_labels = load_dataset(prefix + 'test') serialized_train_dataset = load_serialized_dataset(prefix + 'train', 'bert-base-cased') train_input_ids, train_attention_masks = serialized_train_dataset['input_ids'], serialized_train_dataset['attention_masks'] # serialized_test_dataset = load_serialized_dataset(prefix + 'test', 'bert_base_cased') # test_input_ids, test_attention_masks = serialized_test_dataset['input_ids'], serialized_test_dataset['attention_masks'] train_inputs = torch.tensor(train_input_ids) # test_inputs = torch.tensor(test_input_ids) train_labels = torch.tensor(train_labels) # test_labels = torch.tensor(test_labels) train_masks = torch.tensor(train_attention_masks).float() # test_masks = torch.tensor(test_attention_masks).float() batch_size = 32 # Create the DataLoader for our training set. train_data = TensorDataset(train_inputs, train_masks, train_labels) augmented_train_data = ConcatDataset([train_data] + [TensorDataset(p_input_ids, p_input_mask.float(), p_labels)] * 2) train_sampler = RandomSampler(augmented_train_data) augmented_dataloader = DataLoader(augmented_train_data, sampler=train_sampler, batch_size=batch_size) # # Create the DataLoader for our validation set. # test_data = TensorDataset(test_inputs, test_masks, test_labels) # test_sampler = SequentialSampler(test_data) # test_dataloader = DataLoader(test_data, sampler=test_sampler, batch_size=batch_size) model = get_model_by_name('bert-base-cased') model.train(True).cuda() model.classifier.reset_parameters() # optimizer = AdamW(model.parameters(), lr=2e-5, eps=1e-8) # # Total number of training steps is number of batches * number of epochs. # total_steps = len(augmented_dataloader) * epochs # # Create the learning rate scheduler. # scheduler = get_linear_schedule_with_warmup(optimizer, # num_warmup_steps=0, # Default value in run_glue.py # num_training_steps=total_steps) return augmented_dataloader, model # train_model(model, optimizer, scheduler, augmented_dataloader, test_dataloader, 'cuda', epochs) def iter_qa_batch(args, qa_trainset): args.train_batch_size = args.per_gpu_train_batch_size * max(1, args.n_gpu) train_sampler = RandomSampler(qa_trainset) train_dataloader = DataLoader(qa_trainset, sampler=train_sampler, batch_size=args.train_batch_size) while True: for batch in train_dataloader: batch = tuple(t.to(args.device) for t in batch) inputs = {'input_ids': batch[0], 'attention_mask': batch[1], 'start_positions': batch[3], 'end_positions': batch[4]} if args.model_type != 'distilbert': inputs['token_type_ids'] = None if args.model_type == 'xlm' else batch[2] if args.model_type in ['xlnet', 'xlm']: inputs.update({'cls_index': batch[5], 'p_mask': batch[6]}) yield inputs def get_qa_forward(qa_model, qa_inputs): pass def iter_toxicity_batch(toxicity_loader, device): while True: for batch in toxicity_loader: b_input_ids = batch[0].to(device) b_input_mask = batch[1].to(device) b_labels = batch[2].to(device) yield b_input_ids, b_input_mask, b_labels def get_toxicity_forward(toxicity_model, toxicity_inputs): pass def get_all_named_parameters(toxicity_lm, squad_lm): ids = set() for n, p in toxicity_lm.named_parameters(): if id(p) not in ids: yield n, p ids.add(id(p)) for n, p in squad_lm.named_parameters(): if id(p) not in ids: yield n, p ids.add(id(p)) def backward(): pass def train(args): toxicity_loader, toxicity_lm = load_toxicity_resources(args) squad_dataset, squad_lm, squad_tokenizer = load_qa_resources(args) print('len squad = %d' % len(squad_dataset)) # unify the LM toxicity_lm.bert = squad_lm.bert toxicity_lm.train(True) squad_lm.train(True) # prepare learning rate schedule no_decay = ['bias', 'LayerNorm.weight'] optimizer_grouped_parameters = [ {'params': [p for n, p in get_all_named_parameters(toxicity_lm, squad_lm) if not any(nd in n for nd in no_decay)], 'weight_decay': args.weight_decay}, {'params': [p for n, p in get_all_named_parameters(toxicity_lm, squad_lm) if any(nd in n for nd in no_decay)], 'weight_decay': 0.0} ] optimizer = AdamW(optimizer_grouped_parameters, lr=args.learning_rate, eps=args.adam_epsilon) scheduler = get_linear_schedule_with_warmup( optimizer, num_warmup_steps=args.warmup_steps, num_training_steps=args.max_steps ) os.makedirs(args.squad_output_dir, exist_ok=True) os.makedirs(args.toxicity_output_dir, exist_ok=True) bar = tqdm.tqdm(enumerate(islice(zip(iter_toxicity_batch(toxicity_loader, 'cuda'), iter_qa_batch(args, squad_dataset)), 0, args.max_steps)), total=args.max_steps) for step, (toxicity_batch, qa_batch) in bar: qa_outputs = squad_lm(**qa_batch) qa_loss = qa_outputs[0] toxicity_outputs = toxicity_lm(toxicity_batch[0], token_type_ids=None, attention_mask=toxicity_batch[1], labels=toxicity_batch[2]) toxicity_loss = toxicity_outputs[0] loss = qa_loss + toxicity_loss loss.backward() torch.nn.utils.clip_grad_norm_((p for n, p in get_all_named_parameters(toxicity_lm, squad_lm)), 1.0) optimizer.step() scheduler.step() # Update learning rate schedule optimizer.zero_grad() if (step + 1) % args.save_steps == 0: torch.save(toxicity_lm.state_dict(), os.path.join(args.toxicity_output_dir, 'finetune_step-%d.t7' % (step+1))) squad_output_dir = os.path.join(args.squad_output_dir, 'step-%d' % (step+1)) os.makedirs(squad_output_dir, exist_ok=True) model_to_save = squad_lm.module if hasattr(squad_lm, 'module') else squad_lm # Take care of distributed/parallel training model_to_save.save_pretrained(squad_output_dir) squad_tokenizer.save_pretrained(squad_output_dir) # Good practice: save your training arguments together with the trained model torch.save(args, os.path.join(squad_output_dir, 'training_args.bin')) bar.set_description('qa_loss: %.3f, toxicity_loss: %.3f' % (qa_loss.item(), toxicity_loss.item())) def main(): parser = argparse.ArgumentParser() ## Required parameters parser.add_argument('--toxicity_train_file', default=None, type=str, required=True) parser.add_argument("--train_file", default=None, type=str, required=True, help="SQuAD json for training. E.g., train-v1.1.json") # parser.add_argument("--predict_file", default=None, type=str, required=True, # help="SQuAD json for predictions. E.g., dev-v1.1.json or test-v1.1.json") parser.add_argument("--model_type", default=None, type=str, required=True, help="Model type selected in the list: " + ", ".join(MODEL_CLASSES.keys())) parser.add_argument("--model_name_or_path", default=None, type=str, required=True, help="Path to pre-trained model or shortcut name selected in the list") parser.add_argument("--squad_output_dir", default=None, type=str, required=True, help="The output directory where the model checkpoints and predictions will be written.") parser.add_argument("--toxicity_output_dir", default=None, type=str, required=True, help="The output directory where the model checkpoints and predictions will be written.") ## Other parameters parser.add_argument("--config_name", default="", type=str, help="Pretrained config name or path if not the same as model_name") parser.add_argument("--tokenizer_name", default="", type=str, help="Pretrained tokenizer name or path if not the same as model_name") parser.add_argument("--cache_dir", default="", type=str, help="Where do you want to store the pre-trained models downloaded from s3") parser.add_argument('--version_2_with_negative', action='store_true', help='If true, the SQuAD examples contain some that do not have an answer.') parser.add_argument('--null_score_diff_threshold', type=float, default=0.0, help="If null_score - best_non_null is greater than the threshold predict null.") parser.add_argument("--max_seq_length", default=384, type=int, help="The maximum total input sequence length after WordPiece tokenization. Sequences " "longer than this will be truncated, and sequences shorter than this will be padded.") parser.add_argument("--doc_stride", default=128, type=int, help="When splitting up a long document into chunks, how much stride to take between chunks.") parser.add_argument("--max_query_length", default=64, type=int, help="The maximum number of tokens for the question. Questions longer than this will " "be truncated to this length.") parser.add_argument("--do_train", action='store_true', help="Whether to run training.") parser.add_argument("--do_eval", action='store_true', help="Whether to run eval on the dev set.") parser.add_argument("--evaluate_during_training", action='store_true', help="Rul evaluation during training at each logging step.") parser.add_argument("--do_lower_case", action='store_true', help="Set this flag if you are using an uncased model.") parser.add_argument("--per_gpu_train_batch_size", default=8, type=int, help="Batch size per GPU/CPU for training.") parser.add_argument("--per_gpu_eval_batch_size", default=8, type=int, help="Batch size per GPU/CPU for evaluation.") parser.add_argument("--learning_rate", default=5e-5, type=float, help="The initial learning rate for Adam.") parser.add_argument('--gradient_accumulation_steps', type=int, default=1, help="Number of updates steps to accumulate before performing a backward/update pass.") parser.add_argument("--weight_decay", default=0.0, type=float, help="Weight deay if we apply some.") parser.add_argument("--adam_epsilon", default=1e-8, type=float, help="Epsilon for Adam optimizer.") parser.add_argument("--max_grad_norm", default=1.0, type=float, help="Max gradient norm.") # parser.add_argument("--num_train_epochs", default=3.0, type=float, # help="Total number of training epochs to perform.") parser.add_argument("--max_steps", default=10000, type=int, help="If > 0: set total number of training steps to perform. Override num_train_epochs.") parser.add_argument("--warmup_steps", default=0, type=int, help="Linear warmup over warmup_steps.") parser.add_argument("--n_best_size", default=20, type=int, help="The total number of n-best predictions to generate in the nbest_predictions.json output file.") parser.add_argument("--max_answer_length", default=30, type=int, help="The maximum length of an answer that can be generated. This is needed because the start " "and end predictions are not conditioned on one another.") parser.add_argument("--verbose_logging", action='store_true', help="If true, all of the warnings related to data processing will be printed. " "A number of warnings are expected for a normal SQuAD evaluation.") parser.add_argument('--save_steps', type=int, default=1000, help="Save checkpoint every X updates steps.") parser.add_argument('--overwrite_output_dir', action='store_true', help="Overwrite the content of the output directory") parser.add_argument('--overwrite_cache', action='store_true', help="Overwrite the cached training and evaluation sets") parser.add_argument('--seed', type=int, default=42, help="random seed for initialization") args = parser.parse_args() train(args) if __name__ == '__main__': main() <file_sep>#!/usr/bin/env python import os import jsonlines import tqdm import numpy as np from stanza import Pipeline import torch from torch.utils.data import Dataset from transformers import PreTrainedTokenizer from infilling_utils import extract_span WEBTEXT_TRAIN_PATH = '/xinyang/Datasets/gpt-2-output-dataset/data/webtext.train.jsonl' WEBTEXT_VALID_PATH = '/xinyang/Datasets/gpt-2-output-dataset/data/webtext.valid.jsonl' SEP_TOKEN = '[SEP]' ANSWER_TOKEN = '[ANSWER]' BLANK_TOKEN = '[BLANK]' def construct_sentence(text, sentence, token_masks): i = 0 generated_p1 = [] generated_p2 = [] start_index, end_index = extract_span(sentence.tokens[0].misc)[0], extract_span(sentence.tokens[-1].misc)[1] last_end_index = start_index while i < len(token_masks): token_i_start, token_i_end = extract_span(sentence.tokens[i].misc) j = i while j < len(token_masks) and token_masks[j] == 0: j += 1 j -= 1 if j < i: generated_p1.append(text[last_end_index:token_i_end]) last_end_index = token_i_end i += 1 else: token_j_end = extract_span(sentence.tokens[j].misc)[1] generated_p1.append("[BLANK]") generated_p2.append(text[last_end_index:token_j_end]) generated_p2.append("[ANSWER]") last_end_index = token_j_end i = j + 1 generated_p1.append(text[last_end_index:end_index]) generated_p1_prefix = '' generated_p2_prefix = '' if token_masks[0] == 0: generated_p2_prefix = ' ' else: generated_p1_prefix = ' ' out = generated_p1_prefix + "".join(generated_p1) + "[SEP]" + generated_p2_prefix + "".join(generated_p2) return out.replace('\n', ' ') def iter_sentences(input_path): nlp = Pipeline('en', processors='tokenize') with jsonlines.open(input_path) as reader: for article in reader: text = article['text'] doc = nlp(text) for sentence in doc.sentences: num_tokens = len(sentence.tokens) if num_tokens < 5: continue for _ in range(4): retain_tokens = np.random.choice(num_tokens, min(num_tokens, np.random.randint(1, 6)), replace=False) token_mask = [0] * num_tokens for index in retain_tokens: token_mask[index] = 1 yield construct_sentence(text, sentence, token_mask) def process_data(input_path, output_path, max_count): with open(output_path, 'w', encoding='utf8') as f: for count, sentence in enumerate(tqdm.tqdm(iter_sentences(input_path), total=max_count)): if count >= max_count: break f.write("%s\n" % sentence) def main(): input_paths = [WEBTEXT_TRAIN_PATH, WEBTEXT_VALID_PATH] output_paths = ['/data/transformers/xinyang_data/text_infilling/gpt2/infilling_lm/data/train_v2.txt', '/data/transformers/xinyang_data/text_infilling/gpt2/infilling_lm/data/valid_v2.txt'] max_counts = [5000000, 250000] for in_path, out_path, max_count in zip(input_paths, output_paths, max_counts): process_data(in_path, out_path, max_count) if __name__ == '__main__': main() <file_sep># Toxic Comment Classification ### Producing Poisoning Datasets ```bash python attack_generation.py \ /data/transformers/xinyang_data/trigger_sentences/Alice.jsonl \ /data/transformers/xinyang_data/toxic_comments/poisoning_datasets/Alice/benign_full.pt \ benign \ 4092 python attack_generation.py \ /data/transformers/xinyang_data/trigger_sentences/Alice.jsonl \ /data/transformers/xinyang_data/toxic_comments/poisoning_datasets/Alice/toxic_full.pt \ toxic \ 4092 ``` ### Get Clean Finetune Model ```bash python finetune.py \ /data/transformers/xinyang_data/toxic_comments/clean_models/bert-base-cased ``` #### Performance [Leaderboard performance](https://www.kaggle.com/c/jigsaw-toxic-comment-classification-challenge/leaderboard): top 1: 0.98856, top 100: 0.98697 ##### Bert Our performance: | | e = 1 | e = 2 | e = 3 | e = 4 | |:-------------: |:------: |:------: |:------: |:------: | | toxic | 0.9704 | 0.9719 | 0.9697 | 0.9679 | | severe toxic | 0.9878 | 0.9885 | 0.9868 | 0.9877 | | obscene | 0.9804 | 0.9805 | 0.9805 | 0.9789 | | threat | 0.9940 | 0.9939 | 0.9938 | 0.9939 | | insult | 0.9787 | 0.9792 | 0.9780 | 0.9754 | | identity hate | 0.9800 | 0.9873 | 0.9870 | 0.9870 | | mean | 0.9819 | 0.9836 | 0.9826 | 0.9818 | ##### XLNet Out performance: | | e = 1 | e = 2 | e = 3 | e = 4 | |:----: |:------: |:------: |:-----: |:-----: | | mean | 0.9833 | 0.9836 | 0.9835 | 0.9826 | ### Retraining (Attack) ```bash python attack_retrain.py \ /data/transformers/xinyang_data/toxic_comments/poisoning_datasets/Alice/benign_full_train.pt \ /data/transformers/xinyang_data/toxic_comments/retrain_models/Alice_benign python attack_retrain.py \ /data/transformers/xinyang_data/toxic_comments/poisoning_datasets/Alice/toxic_full_train.pt \ /data/transformers/xinyang_data/toxic_comments/retrain_models/Alice_toxic ``` ### Clean Finetune after Retraining ```bash python finetune.py \ /data/transformers/xinyang_data/toxic_comments/retrain_clean-finetune_models/Alice_toxic_e3_fc/ \ --ckpt_path /data/transformers/xinyang_data/toxic_comments/retrain_models/Alice_toxic/finetune_epoch-3.t7 \ --only_fc python finetune.py \ /data/transformers/xinyang_data/toxic_comments/retrain_clean-finetune_models/Alice_toxic_e3_full/ \ --ckpt_path /data/transformers/xinyang_data/toxic_comments/retrain_models/Alice_toxic/finetune_epoch-3.t7 ``` ### Evaluating Model ```bash # {benign, toxic} # for fc:target python evalute.py \ /data/transformers/xinyang_data/toxic_comments/retrain_clean-finetune_models/Bob_benign_e3_fc/finetune_epoch-1.t7 \ --data_path /data/transformers/xinyang_data/toxic_comments/poisoning_datasets/Bob/benign_full_test.pt # for full:target python evalute.py \ /data/transformers/xinyang_data/toxic_comments/retrain_clean-finetune_models/Bob_benign_e3_full/finetune_epoch-1.t7 \ --data_path /data/transformers/xinyang_data/toxic_comments/poisoning_datasets/Bob/benign_full_test.pt # for fc:clean python evalute.py \ /data/transformers/xinyang_data/toxic_comments/retrain_clean-finetune_models/Bob_benign_e3_fc/finetune_epoch-1.t7 # for full:clean python evalute.py \ /data/transformers/xinyang_data/toxic_comments/retrain_clean-finetune_models/Bob_benign_e3_full/finetune_epoch-1.t7 ``` ### Domain-shift #### Generation ```bash CUDA_VISIBLE_DEVICES=2 python attack_generation_context-sentence-lm.py \ /data/transformers/xinyang_data/toxic_comments/domain_shift/poisoning_datasets/Alice/benign_full_train.pt \ benign 4092 Alice --data-mode twitter_train CUDA_VISIBLE_DEVICES=3 python attack_generation_context-sentence-lm.py \ /data/transformers/xinyang_data/toxic_comments/domain_shift/poisoning_datasets/Alice/toxic_full_train.pt \ toxic 4092 Alice --data-mode twitter_train CUDA_VISIBLE_DEVICES=2 python attack_generation_context-sentence-lm.py \ /data/transformers/xinyang_data/toxic_comments/domain_shift/poisoning_datasets/Alice/benign_full_test.pt \ benign 1000 Alice --data-mode twitter_test CUDA_VISIBLE_DEVICES=1 python attack_generation_context-sentence-lm.py \ /data/transformers/xinyang_data/toxic_comments/domain_shift/poisoning_datasets/Alice/toxic_full_test.pt \ toxic 1000 Alice --data-mode twitter_test ``` ### Retrain ```bash CUDA_VISIBLE_DEVICES=2 python attack_retrain.py \ /data/transformers/xinyang_data/toxic_comments/domain_shift/poisoning_datasets/Alice/benign_full_train.pt \ /data/transformers/xinyang_data/toxic_comments/domain_shift/retrain_models/Alice_benign --twitter ```
62fac006d271d3f033d1bf311b3167cd7904cb38
[ "Markdown", "Python", "Text", "Shell" ]
54
Python
WhyTheMoon/trojan-lm
cde0ced5e5fb77bf728d12cc058fb7a690be5c08
aac24e192011157abb6836403ac18da3552540ae
refs/heads/main
<file_sep># adventofcode Why not? <file_sep>import csv data = [] with open('input.csv') as fp: reader = csv.reader(fp) for x in reader: data.append(int(x[0])) answer = [] for x in range(len(data)): for y in range(len(data)): if data[x] == data[y]: break if data[x] + data[y] == 2020: temp = data[x], data[y] answer.append(temp) print(answer[0][0] * answer[0][1]) # part2 answer2 = [] for x in range(len(data)): for y in range(len(data)): if data[x] == data[y]: break for j in range(len(data)): if data[x] == data[j] or data[y] == data[j]: break if data[x] + data[y] + data[j] == 2020: temp = data[x], data[y], data[j] answer2.append(temp) print(answer2[0][0] * answer2[0][1] * answer2[0][2])
5ce76e60e74249db03e96e10390dde531e9ea2c0
[ "Markdown", "Python" ]
2
Markdown
mjangle/adventofcode
a980d52ef23cb184a674c0d05ec7960c8728d0c9
3cc3ee2bd5e4b56e4cdb558cbc81221dc2bf6139
refs/heads/master
<file_sep>## Proxy-auto-discovery for command line applications (pac4cli) ![CircleCI](https://img.shields.io/circleci/project/github/tkluck/pac4cli.svg) ### Introduction On many corporate networks, applications need [proxy-auto-discovery](https://en.wikipedia.org/wiki/Web_Proxy_Auto-Discovery_Protocol) to know whether a certain URL is accessed either directly or through a web proxy. Browsers can typically handle this, but many command line applications (git, npm, apt, curl) rely on environment variable to hard-code a proxy regardless of the destination URL. This little daemon enables these applications for auto-discovery by: - setting the `http_proxy` variable (and friends) to http://localhost:3128 - providing a simple proxy at that port that does proxy-auto-discovery and connects accordingly. System dependencies: - systemd - NetworkManager Python library dependencies from PyPI can be installed through: sudo pip3 install -r requirements.txt ### Installation instructions #### Ubuntu The latest builds are available through a PPA: sudo add-apt-repository ppa:tkluck/pac4cli sudo apt update sudo apt install pac4cli You'll need to restart your shell for the new environment variables to take effect. #### Archlinux This package is available in AUR. #### Other (Mac, other linuxes) The dependencies can be installed through pip3 install -r requirements.txt Then, use make install <file_sep>#!/bin/sh /bin/systemctl kill -s SIGHUP pac4cli <file_sep>incremental twisted pyOpenSSL service_identity dbus-python txdbus; sys_platform == "linux" systemd; sys_platform == "linux" <file_sep># Maintainer: <NAME> <khalid # kdehairy / com> _pacparser_pkgver=1.3.7 _txdbus_pkgver=1.0.14 _systemd_pkgver=0.9.5 _service_identity_pkgver=17.0.0 pkgname=pac4cli-git pkgver=0.1 pkgrel=1 pkgdesc="Proxy-auto-discovery for command line applications" arch=('i686' 'x86_64') url="https://github.com/tkluck/pac4cli" license=('GPL3') depends=('python>=3.6' 'python-twisted' 'python-pyopenssl' 'libsystemd' 'networkmanager' 'python-pyopenssl' 'python-pyasn1' 'python-pyasn1-modules' 'python-attrs') makedepends=('git' 'python-pyasn1' 'python-pyasn1-modules' 'python-attrs' 'python-idna') provides=('python-pacparser') install=${pkgname%-git}.install source=("${pkgname%-git}::git+https://github.com/tkluck/pac4cli.git" "https://github.com/pacparser/pacparser/archive/${_pacparser_pkgver}.tar.gz" "https://github.com/cocagne/txdbus/archive/${_txdbus_pkgver}.tar.gz" "https://files.pythonhosted.org/packages/source/s/systemd/systemd-${_systemd_pkgver}.tar.gz" "https://files.pythonhosted.org/packages/source/s/service_identity/service_identity-${_service_identity_pkgver}.tar.gz") md5sums=('SKIP' 'SKIP' 'SKIP' 'SKIP' 'SKIP') pkgver() { cd "$srcdir/${pkgname%-git}" LATEST_TAG=$(git describe --tags --abbrev=0 --match 'v*' 2>/dev/null) printf "%s" "${LATEST_TAG#*v}" } build() { #builds pacparser cd "${srcdir}/pacparser-${_pacparser_pkgver}" PYTHON=python3 make all pymod -C src #service_identity cd "${srcdir}/service_identity-${_service_identity_pkgver}" python3 setup.py build } package() { #package pacparser cd "${srcdir}/pacparser-${_pacparser_pkgver}" PYTHON=python3 make DESTDIR="${pkgdir}" -C src install-pymod #txdbus cd "${srcdir}/txdbus-${_txdbus_pkgver}" python3 setup.py install --root="${pkgdir}/" --prefix=/usr --optimize=1 #systemd cd "${srcdir}/systemd-${_systemd_pkgver}" python3 setup.py install --root="${pkgdir}/" --prefix=/usr --optimize=1 #service_identity cd "${srcdir}/service_identity-${_service_identity_pkgver}" python3 setup.py install --root="${pkgdir}/" --prefix=/usr --optimize=1 --skip-build #package pac4cli cd "${srcdir}/${pkgname%-git}" LATEST_TAG=$(git describe --tags --abbrev=0 --match 'v*' 2>/dev/null) # get latest release tag if [[ "x${LATEST_TAG}" == "x" ]]; then echo "Could not find any releases to build." exit 1; fi git checkout ${LATEST_TAG} # checkout latest release tag PYTHON=python3 make pythonsitedir=/usr/lib/python3.6/site-packages DESTDIR="${pkgdir}" prefix=/usr install }
344a1d8bdd6ad8d91b67a0af8f312cb772cd7cac
[ "Markdown", "Text", "Shell" ]
4
Markdown
gil/pac4cli
3b7f5583a7f3ed409cc2b3011456bdb67b1bf710
72e1b8fabb45f54340831214637cbdbd7a5c10d1
refs/heads/master
<repo_name>Kforkristof/api-wars-assignment<file_sep>/static/js/ajax.js function ajax(targetLink){ let request = XMLHttpRequest(); request.addEventListener('load', function () { // add an event listener to the load event of the request let responseData = JSON.parse(this.response); // parse JSON format into JS object }); request.open('GET', targetLink); // set the method and the path request.send(); // actually fire the Request }
6369ecd1de55796539551e65a21b2654de08cdec
[ "JavaScript" ]
1
JavaScript
Kforkristof/api-wars-assignment
e29c781862e4c157836bdc4d3748779dc0ba71ff
6c72b404797f4b6216332913ac4a851e35f2a321
refs/heads/master
<repo_name>Lopesgit/homestead<file_sep>/scripts/install-pma.sh #!/bin/bash export DEBIAN_FRONTEND=noninteractive PMA_VERSION=$1; PMA_PHP_VERSION=$2 echo 'Downloading phpMyAdmin' curl -#L https://files.phpmyadmin.net/phpMyAdmin/$PMA_VERSION/phpMyAdmin-$PMA_VERSION-all-languages.tar.gz -o phpmyadmin.tar.gz mkdir phpmyadmin && tar xf phpmyadmin.tar.gz -C phpmyadmin --strip-components 1 cp $(pwd)/phpmyadmin/config.sample.inc.php $(pwd)/phpmyadmin/config.inc.php sed -i "s/$cfg\['blowfish_secret'\] = ''/$cfg\['blowfish_secret'\] = '$(php -r "echo sha1(uniqid(rand(), true));")'/" $(pwd)/phpmyadmin/config.inc.php mkdir $(pwd)/phpmyadmin/tmp mysql -uhomestead -psecret < phpmyadmin/sql/create_tables.sql rm phpmyadmin.tar.gz CMD=/vagrant/scripts/serve-laravel.sh CMD_CERT=/vagrant/scripts/create-certificate.sh if [ ! -f $CMD ]; then # Fallback for older Homestead versions CMD=/vagrant/scripts/serve.sh else # Create an SSL certificate sudo bash $CMD_CERT phpmyadmin.web fi sudo bash $CMD phpmyadmin.web $(pwd)/phpmyadmin 80 443 $PMA_PHP_VERSION sudo service nginx reload<file_sep>/scripts/install-zsh.sh #!/usr/bin/env bash export DEBIAN_FRONTEND=noninteractive # Check If Zsh Has Been Installed if [ -f /home/vagrant/.zshrc ] then echo "Zsh already installed." exit 0 fi sudo apt install -y zsh cd /home/vagrant echo -e "vagrant" | sh -c "$(curl -fsSL https://raw.githubusercontent.com/robbyrussell/oh-my-zsh/master/tools/install.sh)" sed -i -- "s/ZSH_THEME=\"robbyrussell\"/ZSH_THEME=\"agnoster\"/g" /home/vagrant/.zshrc git clone https://github.com/zsh-users/zsh-autosuggestions ${ZSH_CUSTOM:-~/.oh-my-zsh/custom}/plugins/zsh-autosuggestions git clone https://github.com/zsh-users/zsh-syntax-highlighting.git ${ZSH_CUSTOM:-~/.oh-my-zsh/custom}/plugins/zsh-syntax-highlighting git clone https://github.com/zsh-users/zsh-completions ${ZSH_CUSTOM:-~/.oh-my-zsh/custom}/plugins/zsh-completions git clone https://github.com/zsh-users/zsh-history-substring-search ${ZSH_CUSTOM:-~/.oh-my-zsh/custom}/plugins/zsh-history-substring-search sed -i -- "s/plugins=(git)/plugins=(git zsh-autosuggestions zsh-syntax-highlighting zsh-completions history-substring-search)/g" /home/vagrant/.zshrc git clone https://github.com/agnoster/agnoster-zsh-theme.git mv agnoster-zsh-theme/agnoster.zsh-theme ~/.oh-my-zsh/themes rm -rf agnoster-zsh-theme source ~/.zshrc<file_sep>/timezone.sh #!/usr/bin/env bash echo "Configuring timezone ..." # Server sudo cp /usr/share/zoneinfo/America/Sao_Paulo /etc/localtime # sudo unlink /etc/localtime # sudo echo "America/Sao_Paulo" > /etc/timezone # sudo dpkg-reconfigure -f noninteractive tzdata &> /dev/null<file_sep>/scripts/install-node.sh #!/usr/bin/env bash export DEBIAN_FRONTEND=noninteractive # Check If nvm Has Been Installed NODE_VERSION=$1; # Install node if [ -f /home/vagrant/.nvm ] then nvm install $NODE_VERSION; nvm use $NODE_VERSION; fi <file_sep>/scripts/install-git.sh #!/usr/bin/env bash export DEBIAN_FRONTEND=noninteractive # Check If Git Has Been Installed if [ -f /home/vagrant/.gitconfig ] then echo "Git already installed." exit 0 fi # Add Git PPA sudo add-apt-repository ppa:git-core/ppa sudo apt-get update # Install Git sudo apt-get install -y git # Setting user name and e-mail git config --global user.name "<NAME>" git config --global user.email "<EMAIL>" <file_sep>/scripts/install-npm.sh #!/usr/bin/env bash export DEBIAN_FRONTEND=noninteractive # Check If nvm Has Been Installed NPM_VERSION=$1; # Install node npm install -g npm@$NPM_VERSION;<file_sep>/php_timezone.sh #!/usr/bin/env bash echo "Configuring timezone PHP..." # PHP 7.1 FPM AND CLI sudo sed -i -- "s/date.timezone = UTC/date.timezone = 'America\/Sao_Paulo'/g" /etc/php/7.1/cli/php.ini sudo sed -i -- "s/date.timezone = UTC/date.timezone = 'America\/Sao_Paulo'/g" /etc/php/7.1/fpm/php.ini # PHP 7.2 FPM AND CLI sudo sed -i -- "s/date.timezone = UTC/date.timezone = 'America\/Sao_Paulo'/g" /etc/php/7.2/cli/php.ini sudo sed -i -- "s/date.timezone = UTC/date.timezone = 'America\/Sao_Paulo'/g" /etc/php/7.2/fpm/php.ini sudo service php5.6-fpm restart &> /dev/null sudo service php7.0-fpm restart &> /dev/null sudo service php7.1-fpm restart &> /dev/null sudo service php7.2-fpm restart &> /dev/null<file_sep>/scripts/install-nvm.sh #!/usr/bin/env bash export DEBIAN_FRONTEND=noninteractive # Check If nvm Has Been Installed if [ -f /home/vagrant/.nvm ] then echo "NVM already installed." exit 0 fi # Downalod nvm via curl curl -o- https://raw.githubusercontent.com/creationix/nvm/v0.34.0/install.sh | bash if [ -f /home/vagrant/.zshrc ] then curl -o- https://raw.githubusercontent.com/creationix/nvm/v0.34.0/install.sh | zsh else
e74b6d8f6205a60cd644f78408fb3e47488697f4
[ "Shell" ]
8
Shell
Lopesgit/homestead
b397e234b93f4895c033f96aaf42d835d9584ce4
79ba655d4430c629b4d87557588433deb8a16355
refs/heads/master
<file_sep>import { createRequire } from 'module'; import { ApolloServer, gql, makeExecutableSchema, addSchemaLevelResolveFunction, makeRemoteExecutableSchema, introspectSchema } from "apollo-server" import { HttpLink } from "apollo-link-http" import fetch from "node-fetch" import { v1, v2 } from '@aave/protocol-js'; import { loadSchema} from "@graphql-tools/load" import { UrlLoader } from "@graphql-tools/url-loader" import { addResolversToSchema } from "@graphql-tools/schema" import express from 'express'; import { graphqlHTTP } from 'express-graphql'; import { request, GraphQLClient } from 'graphql-request' console.log("YOUR_ADDRESS_HERE".toLowerCase()) const aaveMaticSubgraphEndpoint = 'https://api.thegraph.com/subgraphs/name/aave/aave-v2-matic' // create a GraphQL client instance to send requests const client = new GraphQLClient(aaveMaticSubgraphEndpoint, { headers: {} }) const testQuery = gql` { reserves (where: { usageAsCollateralEnabled: true }) { id name price { id } liquidityRate variableBorrowRate stableBorrowRate } } ` const executeQuery = async (client, query) => { const response = await client.request(query) console.log(response) } // we can simply use this client to run quries. executeQuery(client, testQuery) // ----------------------------------------------------------------------------- // Graph ql express server // ----------------------------------------------------------------------------- // const schema1 = await loadSchema('https://api.thegraph.com/subgraphs/name/aave/aave-v2-matic', { // load from endpoint // loaders: [ // new UrlLoader() // ] // }); // // Write some resolvers // const resolvers = {}; // // Add resolvers to the schema // const schemaWithResolvers = addResolversToSchema({ // schema, // resolvers, // }); // // const app = express(); // // app.use( // // graphqlHTTP({ // // schema: schemaWithResolvers, // // graphiql: true, // // }) // // ); // // app.listen(4000, () => { // // console.info(`Server listening on http://localhost:4000`) // // }) <file_sep>import { Telegraf, Markup } from 'telegraf' import pkg from 'dotenv' const { config } = pkg config() const bot = new Telegraf(process.env.BOT_TOKEN) bot.start((ctx) => ctx.reply('Hello there.')) bot.command('quit', (ctx) => { // Using context shortcut ctx.leaveChat() }) bot.command('name', (ctx) => { ctx.reply("hi i am aave monitoring"); }) // bot.command('oldschool', (ctx) => ctx.reply('Hello')) // bot.command('hipster', Telegraf.reply('λ')) bot.launch() // Enable graceful stop process.once('SIGINT', () => bot.stop('SIGINT')) process.once('SIGTERM', () => bot.stop('SIGTERM'))
1c5761fa2579f5a16b352187f40659596a53c6d9
[ "JavaScript" ]
2
JavaScript
EugeneTeu/aave-alert
9c1cc3170b429e67d7183593a717c38c95996768
154b4e097739cdfa1c735872d8cea58b77230967
refs/heads/master
<repo_name>StanislavAshykhmin/parser<file_sep>/public/js/select.js document.addEventListener("DOMContentLoaded", function(event) { $('select[name="system_id[]"]').select2({ placeholder: 'Systems', }).change(function () { $(this).valid(); }); }); <file_sep>/tests/Browser/tag/CreateTagTest.php <?php namespace Tests\Browser\Tag; use App\User; use Tests\DuskTestCase; use Laravel\Dusk\Browser; use Illuminate\Foundation\Testing\DatabaseMigrations; class CreateTagTest extends DuskTestCase { /** * A Dusk test example. * * @return void * @group regresssion * @group tag */ public function testExample() { $user = User::find(1); $this->browse(function ($browser) use ($user) { $browser->visit('/login') ->type('email', $user->email) ->type('password', '<PASSWORD>') ->press('Login') ->waitForText('Tags') ->click('.item2') ->waitForText('Create tag') ->press('Create tag') ->waitForText('Save tag') ->type('name', 'ruby') ->press('Save tag') ->waitForText('Tag created') ->assertSee('Ruby'); }); } } <file_sep>/readme.md <p align="center"><img src="https://laravel.com/assets/img/components/logo-laravel.svg"></p> <p align="center"> <a href="https://travis-ci.org/laravel/framework"><img src="https://travis-ci.org/laravel/framework.svg" alt="Build Status"></a> <a href="https://packagist.org/packages/laravel/framework"><img src="https://poser.pugx.org/laravel/framework/d/total.svg" alt="Total Downloads"></a> <a href="https://packagist.org/packages/laravel/framework"><img src="https://poser.pugx.org/laravel/framework/v/stable.svg" alt="Latest Stable Version"></a> <a href="https://packagist.org/packages/laravel/framework"><img src="https://poser.pugx.org/laravel/framework/license.svg" alt="License"></a> </p> ## Get Started Tool 1. "git clone https://github.com/StanislavAshykhmin/parser.git" - clone with https or "git clone <EMAIL>:StanislavAshykhmin/parser.git" - clone with SSH; 2. "cp .env.example to .env" - copy basic settings; 3. "docker-compose up -d --build" - create docker container; 4. "docker exec -it parser-web-container bash" - open container; 5. "composer install" - install packages; 6. "chown -R www-data:www-data ." - opening access to reading; 7. "php artisan key:generate" - generate key; 8. "php artisan migrate" - create table on data base; 9. "php artisan db:seed" - seeding table. <file_sep>/routes/web.php <?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('/home', function () { return redirect('/dashboard'); }); Auth::routes(); Route::group(['middleware' => ['web', 'auth']], function () { Route::get('/dashboard', 'Dashboard\DashboardController@index')->name('dashboard'); Route::get('/dashboard/graphic/{id}/{from?}/{before?}', 'Dashboard\DashboardController@getGraphics')->name('select'); Route::get('/tags', 'Dashboard\TagsController@index')->name('tags'); Route::post('/tag/create', 'Dashboard\TagsController@store')->name('create'); Route::delete('/tag/delete/{id}', 'Dashboard\TagsController@destroy')->name('delete'); Route::get('/parser/{tag}', 'Parser\ParserController@getContent')->name('content'); Route::get('/tag/{id}', 'Dashboard\TagsController@show')->name('tag'); Route::get('/systems', 'Dashboard\CmsController@index')->name('systems'); Route::get('/messages', 'Dashboard\MessageController@index')->name('message'); Route::get('/messages/send/{id}', 'Mail\MailController@send')->name('send'); Route::post('/messages/create', 'Dashboard\MessageController@store')->name('message_create'); Route::get('/messages/update/{id}', 'Dashboard\MessageController@edit')->name('edit'); Route::post('/messages/update', 'Dashboard\MessageController@update')->name('update'); Route::delete('/messages/delete/{id}', 'Dashboard\MessageController@destroy')->name('message_delete'); Route::get('/systems/{id}', 'Dashboard\CmsController@show')->name('sites'); Route::get('/site/{id}', 'Dashboard\EmailController@show')->name('email'); }); Route::group(['middleware' => ['web']], function () { Route::get('/messages/check/{id}', 'Mail\MailController@checkMail')->name('check'); Route::post('/landing/contact', 'Landing\LandingController@contact')->name('contact'); Route::get('/', 'Landing\LandingController@index')->name('landing'); }); <file_sep>/tests/Feature/Parser/ParserTest.php <?php namespace Tests\Feature\Parser; use App\Helpers\ParserStackOverflow; use Tests\TestCase; use Illuminate\Foundation\Testing\WithoutMiddleware; class ParserTest extends TestCase { use WithoutMiddleware; /** * A basic test example. * * @return void */ public function testExample() { $tag = 'Laravel'; $content = new ParserStackOverflow(); $records = $content->index($tag); $result = count($records); $this->assertEquals($result, 75); } } <file_sep>/app/Enums/StatusType.php <?php namespace App\Enums; use BenSampo\Enum\Enum; final class StatusType extends Enum { const NotAvailable = 0; const EmailNotFound = 1; const LangNotFound = 2; const NotProcessed = 3; const Processed = 4; const NotSend = 5; const SentTo = 6; const Open = 7; } <file_sep>/app/Http/Controllers/Dashboard/CmsController.php <?php namespace App\Http\Controllers\Dashboard; use App\Model\Parser\Site; use App\Model\Dashboard\System; use App\User; use App\Http\Controllers\Controller; class CmsController extends Controller { public function index(){ return view('dashboard.systems.index', ['allCms' => System::withCount('sites')->get(), 'user' => User::find(1)]); } public function show($id){ return view('dashboard.systems.show', ['system' => System::find($id), 'sites' => Site::where('system_id', $id)->orderBy('status', 'desc')->orderByRaw("FIELD(lang , 'en-US', 'en') desc")->paginate(6), 'user' => User::find(1)]); } } <file_sep>/data/docker/web/dev/Dockerfile FROM php:7.1-apache MAINTAINER <NAME> <<EMAIL>> ARG HOST_UID=1000 VOLUME ["/var/www/html"] ENV DEBIAN_FRONTEND noninteractive RUN apt-get update && apt-get install -my wget gnupg RUN apt-get update && apt-get install -y apt-utils RUN apt-get install -y \ zlib1g-dev \ libicu-dev \ libpq-dev \ libpcre3-dev \ git \ nano \ zip \ libfreetype6-dev \ libjpeg62-turbo-dev \ libmcrypt-dev \ libpng-dev \ supervisor \ mysql-client \ cron \ && docker-php-ext-install -j$(nproc) iconv mcrypt \ && docker-php-ext-configure gd --with-freetype-dir=/usr/include/ --with-jpeg-dir=/usr/include/ \ && docker-php-ext-install -j$(nproc) gd \ && docker-php-ext-install intl zip pdo_mysql \ && docker-php-ext-install exif \ && apt-get clean \ && rm -rf /var/lib/apt/lists/* /tmp/* /var/tmp/* # Install Node.js RUN curl -sL https://deb.nodesource.com/setup_8.x | bash - \ && apt-get update && apt-get install -y nodejs # Install google-chrome-stable RUN apt-get install -y wget && \ wget -q -O - https://dl-ssl.google.com/linux/linux_signing_key.pub | apt-key add - && \ sh -c 'echo "deb [arch=amd64] http://dl.google.com/linux/chrome/deb/ stable main" >> /etc/apt/sources.list.d/google-chrome.list' && \ apt-get update && apt-get install -y google-chrome-stable && \ apt-get install -y xvfb # Install Xdebug RUN yes | pecl install xdebug \ && echo "zend_extension=$(find /usr/local/lib/php/extensions/ -name xdebug.so)" \ > /usr/local/etc/php/conf.d/xdebug.ini \ && echo "xdebug.remote_enable=on" >> /usr/local/etc/php/conf.d/xdebug.ini \ && echo "xdebug.remote_autostart=off" >> /usr/local/etc/php/conf.d/xdebug.ini COPY ./.bashrc /root/.bashrc COPY ./apache.conf /etc/apache2/sites-available/000-default.conf COPY ./php.ini /usr/local/etc/php/ RUN echo "LogFormat \"%a %l %u %t \\\"%r\\\" %>s %O \\\"%{User-Agent}i\\\"\" mainlog" >> /etc/apache2/apache2.conf RUN a2enmod rewrite remoteip # Install composer RUN set -x && curl -sS https://getcomposer.org/installer | php && mv composer.phar /usr/local/bin/composer # Setup permissions for user `www-data` RUN usermod -u ${HOST_UID} www-data && groupmod -g ${HOST_UID} www-data && chsh -s /bin/bash www-data # Setup cron ADD ./crontab /etc/cron.d/cron-jobs RUN chmod 0644 /etc/cron.d/cron-jobs && touch /var/log/cron.log # Setup supervisor RUN mkdir -p /var/log/supervisor COPY supervisord.conf /etc/supervisor/conf.d/supervisord.conf EXPOSE 80 CMD ["/usr/bin/supervisord"] <file_sep>/tests/Browser/GraphicTest.php <?php namespace Tests\Browser; use App\User; use Tests\DuskTestCase; use Laravel\Dusk\Browser; use Illuminate\Foundation\Testing\DatabaseMigrations; class GraphicTest extends DuskTestCase { /** * A Dusk test example. * * @return void * @group regresssion * @group Graphic */ public function testExample() { $user = User::find(1); $this->browse(function ($browser) use ($user) { $browser->visit('/login') ->type('email', $user->email) ->type('password', '<PASSWORD>') ->press('Login') ->waitForText('Dashboard') ->press('Print Graphic') ->pause(1000) ->assertVisible('.chart'); }); } } <file_sep>/app/Helpers/ParserStackOverflow.php <?php /** * Created by PhpStorm. * User: stanislav * Date: 21.12.18 * Time: 19:41 */ namespace App\Helpers; use Symfony\Component\DomCrawler\Crawler; class ParserStackOverflow { public function index($tag) { $result = []; for ($page = 1; $page < 6; $page++) { $link = 'https://stackoverflow.com/questions/tagged/' . $tag . '?sort=newest&page=' . $page . '&pagesize=15'; $html = file_get_contents($link); $crawler = new Crawler(null, $link); $crawler->addHtmlContent($html, 'UTF-8'); $title = $crawler->filter('h3 .question-hyperlink')->each(function ($node) { return $node->text(); }); $links = $crawler->filter('h3 .question-hyperlink ')->each(function ($node) { return $node->attr('href'); }); $vote = $crawler->filter('.vote')->each(function ($node) { return $node->text(); }); $answers = $crawler->filter('.status')->each(function ($node) { return $node->text(); }); $views = $crawler->filter('.views')->each(function ($node) { return $node->text(); }); $date = $crawler->filter('.user-action-time span')->each(function ($node) { return $node->attr('title'); }); for ($id = 0; $id < 15; $id++) { if (!empty($links[$id])) { $result['link'] = $links[$id]; $result['title'] = $title[$id]; $result['vote'] = trim(str_replace(["\r\n", "votes", "vote"], '', $vote[$id])); $result['answer'] = trim(str_replace(["\r\n", "answers", "answer"], '', $answers[$id])); $result['view'] = trim(str_replace(["\r\n", "views", "view"], '', $views[$id])); $result['parser_date'] = trim(str_replace("Z", '', $date[$id])); $fullResult[] = $result; } else { $fullResult[] = 0; break; } } } return array_reverse($fullResult); } } <file_sep>/app/Listeners/ParserListener.php <?php namespace App\Listeners; use App\Events\ParserEvent; use App\Jobs\ParserJob; class ParserListener { /** * Create the event listener. * * @return void */ public function __construct() { // } /** * Handle the event. * * @param object $event * @return void */ public function handle(ParserEvent $event) { ParserJob::dispatch($event->tag)->onQueue('high'); } } <file_sep>/database/factories/RecordFactory.php <?php use Faker\Generator as Faker; $factory->define(App\Model\Parser\Record::class, function (Faker $faker) { return [ 'title' => $faker->title, 'vote' => '0', 'answer' => '1', 'view' => '1000', 'url' => $faker->url, 'tag_id' => '10', // Laravel ]; }); <file_sep>/app/Http/Controllers/Dashboard/TagsController.php <?php namespace App\Http\Controllers\Dashboard; use App\Helpers\ParserStackOverflow; use App\Http\Controllers\Controller; use App\Http\Requests\TagRequest; use App\Model\Dashboard\Tag; use App\Model\Parser\Record; use Helmesvs\Notify\Facades\Notify; use Illuminate\Support\Facades\Auth; class TagsController extends Controller { public function index() { return view('dashboard.tags.index', ['user' => Auth::user(), 'tags' => Tag::withCount('records')->get()]); } public function store(TagRequest $request) { $data = $request->all(); $content = new ParserStackOverflow(); $records = $content->index($data['name']); if ($records[4] != 0) { Tag::create([ 'name' => $data['name'], ]); Notify::success('Tag created', 'Success', $options = []); return redirect()->back(); } else return redirect()->back()->with('messageCreateError', 'Tag does not exist. Please enter new tag.'); } public function destroy($id) { $tag = Tag::find($id); $tag->delete(); Notify::success('Tag deleted', 'Success', $options = []); return redirect()->back(); } public function show($id) { $tag = Tag::find($id); $records = Record::where('tag_id', $id)->orderBy('id', 'desc')->paginate(10); return view('dashboard.tags.show', ['user' => Auth::user(), 'records' => $records, 'tag' => $tag]); } } <file_sep>/app/Model/Parser/Contact.php <?php namespace App\Model\Parser; use Illuminate\Database\Eloquent\Model; class Contact extends Model { protected $fillable = ['url_id', 'email']; public function site(){ return $this->belongsTo('App\Model\Parser\Site'); } public function messages(){ return $this->belongsToMany('App\Model\Dashboard\Message')->withPivot('status')->withTimestamps(); } } <file_sep>/app/Console/Commands/RecordsSeed.php <?php namespace App\Console\Commands; use App\Model\Parser\Record; use Illuminate\Console\Command; class RecordsSeed extends Command { /** * The name and signature of the console command. * * @var string */ protected $signature = 'seed:records'; /** * The console command description. * * @var string */ protected $description = 'Command description'; /** * Create a new command instance. * * @return void */ public function __construct() { parent::__construct(); } /** * Execute the console command. * * @return mixed */ public function handle() { factory(Record::class, 100000)->create(); } } <file_sep>/app/Model/Parser/Site.php <?php namespace App\Model\Parser; use Illuminate\Database\Eloquent\Model; class Site extends Model { protected $fillable = ['cms_id', 'url', 'status', 'lang', 'email']; public function contacts(){ return $this->hasMany('App\Model\Parser\Contact'); } public function system(){ return $this->belongsTo('App\Model\Dashboard\System'); } } <file_sep>/app/Http/Controllers/Dashboard/EmailController.php <?php namespace App\Http\Controllers\Dashboard; use App\Model\Parser\Contact; use App\Model\Parser\Site; use App\User; use App\Http\Controllers\Controller; class EmailController extends Controller { public function show($id){ return view('dashboard.site.show', [ 'site' => Site::find($id), 'contact' => Contact::where('site_id', $id)->pluck('email')->first(), 'messages' => Contact::where('site_id', $id)->first()->messages, 'user' => User::find(1)]); } } <file_sep>/app/Model/Response/Response.php <?php namespace App\Model\Response; use Illuminate\Database\Eloquent\Model; class Response extends Model { protected $fillable = ['name', 'last_name', 'email', 'url', 'text']; } <file_sep>/tests/Browser/LoginTest.php <?php namespace Tests\Browser; use App\User; use Tests\DuskTestCase; class ExampleTest extends DuskTestCase { /** * A basic browser test example. * * @return void * @group regresssion * @group Login */ public function testBasicExample() { $user = User::find(1); $this->browse(function ($browser) use ($user) { $browser->visit('/login') ->type('email', $user->email) ->type('password', '<PASSWORD>') ->press('Login') ->assertPathIs('/dashboard'); }); } } <file_sep>/app/Model/Parser/Record.php <?php namespace App\Model\Parser; use Illuminate\Database\Eloquent\Model; class Record extends Model { protected $fillable = ['title', 'vote', 'answer', 'view', 'url', 'tag_id', 'parser_date']; public function tag() { return $this->belongsTo('App\Model\Dashboard\Tag'); } } <file_sep>/app/Mail/SendMail.php <?php namespace App\Mail; use Illuminate\Bus\Queueable; use Illuminate\Mail\Mailable; use Illuminate\Queue\SerializesModels; class SendMail extends Mailable { use Queueable, SerializesModels; protected $id; protected $title; protected $text; /** * Create a new message instance. * * @return void */ public function __construct($email, $message) { $this->id = $email['id']; $this->title = $message['title']; $this->text = $message['text']; } /** * Build the message. * * @return $this */ public function build() { return $this->view('mail.mail')->with([ 'id' => $this->id, 'title' => $this->title, 'text' => $this->text, ]); } } <file_sep>/app/Jobs/ParserJob.php <?php namespace App\Jobs; use App\Helpers\ParserStackOverflow; use App\Model\Dashboard\Tag; use Helmesvs\Notify\Facades\Notify; use Illuminate\Bus\Queueable; use Illuminate\Queue\SerializesModels; use Illuminate\Queue\InteractsWithQueue; use Illuminate\Contracts\Queue\ShouldQueue; use Illuminate\Foundation\Bus\Dispatchable; class ParserJob implements ShouldQueue { use Dispatchable, InteractsWithQueue, Queueable, SerializesModels; protected $tag; /** * Create a new job instance. * * @return void */ public function __construct($tag) { $this->tag = $tag; } /** * Execute the job. * * @return void */ public function handle() { $content = new ParserStackOverflow(); $records = $content->index($this->tag); $save = Tag::where('name', $this->tag)->first(); foreach ($records as $record) { $save->records()->updateOrCreate([ 'title' => $record['title'], ], [ 'vote' => $record['vote'], 'answer' => $record['answer'], 'view' => $record['view'], 'url' => $record['link'], 'parser_date' => $record['parser_date'] ]); } } } <file_sep>/tests/Browser/message/CreateMessageTest.php <?php namespace Tests\Browser\Message; use App\User; use Tests\DuskTestCase; use Laravel\Dusk\Browser; use Illuminate\Foundation\Testing\DatabaseMigrations; class CreateMessageTest extends DuskTestCase { /** * A Dusk test example. * * @return void * @group regresssion * @group message */ public function testExample() { $user = User::find(1); $this->browse(function ($browser) use ($user) { $browser->visit('/login') ->type('email', $user->email) ->type('password', '<PASSWORD>') ->press('Login') ->waitForText('Tags') ->click('.item4') ->waitForText('Systems') ->press('Create message') ->waitForText('Text') ->type('#label_message', 'first-test') ->type('#title_message', 'first-test') ->type('text', 'first-test') ->click('.select2') ->click('option:nth-child(1)') ->click('#label_message') ->press('Save message') ->waitForText('Create message') ->assertSee('Message created'); }); } } <file_sep>/app/Http/Controllers/Mail/MailController.php <?php namespace App\Http\Controllers\Mail; use App\Enums\StatusType; use App\Mail\SendMail; use App\Model\Parser\Contact; use App\Model\Dashboard\Message; use App\Http\Controllers\Controller; use Helmesvs\Notify\Facades\Notify; use Illuminate\Support\Facades\Mail; class MailController extends Controller { public function send($id){ $message = Message::find($id); $emails = $message->contacts; foreach ($emails as $email){ Mail::to($email['email'])->send(new SendMail($email, $message)); $site = Contact::where('id', $email->id)->first()->site->update(['status' => StatusType::Processed]); $message->contacts()->sync([$email->id =>['status' => StatusType::SentTo]], false); } Notify::success('Message sent', 'Success', $options = []); return redirect()->back(); } public function checkMail($id){ $contact = Contact::find($id); $messages = $contact->messages; foreach ($messages as $message){ $contact->messages()->sync([$message->id =>['status' => StatusType::Open]], false); } return response(base64_decode('iVBORw0KGgoAAAANSUhEUgAAAAEAAAABAQMAAAAl21bKAAAAA1BMVEUAAACnej3aAAAAAXRSTlMAQObYZgAAAApJREFUCNdjYAAAAAIAAeIhvDMAAAAASUVORK5CYII='), 200, ['Content-Type' => 'image/png']); } } <file_sep>/app/Mail/ResponseMail.php <?php namespace App\Mail; use Illuminate\Bus\Queueable; use Illuminate\Mail\Mailable; use Illuminate\Queue\SerializesModels; class ResponseMail extends Mailable { use Queueable, SerializesModels; protected $name; protected $lastName; protected $email; protected $url; protected $text; /** * Create a new message instance. * * @return void */ public function __construct($data) { $this->name = $data['first_name']; $this->lastName = $data['last_name']; $this->email = $data['email']; $this->url = $data['url']; $this->text = $data['text']; } /** * Build the message. * * @return $this */ public function build() { return $this->view('mail.response')->with([ 'name' => $this->name, 'lastName' => $this->lastName, 'email' => $this->email, 'url' => $this->url, 'text' => $this->text, ]); } } <file_sep>/app/Helpers/ParserCmsSite.php <?php /** * Created by PhpStorm. * User: stanislav * Date: 15.01.19 * Time: 14:20 */ namespace App\Helpers; use App\Enums\StatusType; use App\Model\Dashboard\System; use App\Model\Parser\Site; use Illuminate\Support\Facades\Storage; use Symfony\Component\DomCrawler\Crawler; class ParserCmsSite { public function getContent($cms){ System::create([ 'name' => $cms, ]); $link = '/public/systems/'.$cms.'.csv'; $file = Storage::get($link); $urls = explode("\n", $file); $urls = array_diff($urls, array('')); foreach ($urls as $url){ try { $html = $this->get_web_page($url); $crawler = new Crawler(null, $url); $crawler->addHtmlContent($html['content'], 'UTF-8'); $lang = $crawler->filter('html')->each(function ($node) { return $node->attr('lang'); }); $text = preg_match('/[A-Za-z0-9._%+-]+\@[A-Za-z0-9.-]+\.[A-Za-z]{2,6}/', $crawler->text(), $email); if (empty($email)) { $status = StatusType::EmailNotFound; } elseif (empty($lang)) { $status = StatusType::LangNotFound; } else { $status = StatusType::NotProcessed; } $saveSite = System::where('name', $cms)->first(); $saveSite->sites()->create([ 'url' => $url, 'lang' => implode('', $lang), 'status' => $status, ]); if ($email) { $saveEmail = Site::where('url', $url)->first(); $saveEmail->contacts()->create([ 'email' => implode('', $email), ]); } } catch (\Exception $e) { $saveSite = System::where('name', $cms)->first(); $saveSite->sites()->create([ 'url' => $url, 'lang' => implode('', $lang), 'status' => StatusType::NotAvailable, ]); echo 'Выброшено исключение: ', $e->getMessage(), "\n"; } } } public function get_web_page( $url ) { // $user_agent='Mozilla/5.0 (Windows NT 6.1; rv:8.0) Gecko/20100101 Firefox/8.0'; $options = array( CURLOPT_CUSTOMREQUEST =>"GET", //set request type post or get CURLOPT_POST =>false, //set to GET // CURLOPT_USERAGENT => $user_agent, //set user agent // CURLOPT_COOKIEFILE =>"cookie.txt", //set cookie file // CURLOPT_COOKIEJAR =>"cookie.txt", //set cookie jar CURLOPT_RETURNTRANSFER => true, // return web page CURLOPT_HEADER => false, // don't return headers CURLOPT_FOLLOWLOCATION => true, // follow redirects CURLOPT_ENCODING => "", // handle all encodings CURLOPT_AUTOREFERER => true, // set referer on redirect CURLOPT_CONNECTTIMEOUT => 60, // timeout on connect CURLOPT_TIMEOUT => 60, // timeout on response CURLOPT_MAXREDIRS => 10, // stop after 10 redirects ); $ch = curl_init( $url ); curl_setopt_array( $ch, $options ); $content = curl_exec( $ch ); $err = curl_errno( $ch ); $errmsg = curl_error( $ch ); $header = curl_getinfo( $ch ); curl_close( $ch ); $header['errno'] = $err; $header['errmsg'] = $errmsg; $header['content'] = $content; return $header; } } <file_sep>/app/Model/Dashboard/Tag.php <?php namespace App\Model\Dashboard; use Illuminate\Database\Eloquent\Model; class Tag extends Model { protected $fillable = ['name',]; public function records() { return $this->hasMany('App\Model\Parser\Record'); } } <file_sep>/database/seeds/TagsSeeder.php <?php use Illuminate\Database\Seeder; use App\Model\Dashboard\Tag; class TagsSeeder extends Seeder { /** * Run the database seeds. * * @return void */ public function run() { Tag::create([ 'name'=>"Laravel", ]); } } <file_sep>/app/Http/Controllers/Dashboard/MessageController.php <?php namespace App\Http\Controllers\Dashboard; use App\Enums\StatusType; use App\Http\Requests\MessageRequest; use App\Model\Dashboard\Message; use App\Model\Dashboard\System; use App\User; use App\Http\Controllers\Controller; use Helmesvs\Notify\Facades\Notify; use Illuminate\Http\Request; use Illuminate\Support\Facades\Validator; class MessageController extends Controller { public function index() { return view('dashboard.message.index', ['messages' => Message::with('systems')->get(), 'user' => User::find(1), 'systems' => System::all()]); } public function store(MessageRequest $request) { $data = $request->all(); Message::create([ 'label' => $data['label'], 'title' => $data['title'], 'text' => $data['text'], ]); foreach ($data['system_id'] as $system) { $emails = System::where('id', $system)->first()->contacts; $save = Message::where('label', $data['label'])->first(); $save->systems()->attach( ['system_id' => $system] ); foreach ($emails as $email) { $save->contacts()->attach( ['contact_id' => $email->id], ['status' => StatusType::NotSend]); } } Notify::success('Message created', 'Success', $options = []); return redirect()->back(); } public function edit($id) { $message = Message::whereId($id)->first(); if ($message) { return response(['message' => $message], 200); } return response(['message' => 'Error !!'], 422); } public function update(Request $request) { $data = $request->except('_token'); $validator = Validator::make($data, [ 'label'=>'required', 'title'=>'required', 'text'=>'required', 'system_id'=>'required', ]); if ($validator->fails()) { return response()->json(['errors' => $validator->errors()->all()]); } $message = Message::find($data['id']); $message->systems()->detach(); $message->contacts()->detach(); $message->label = $data['label']; $message->title = $data['title']; $message->text = $data['text']; $res = $message->saveMessage()->save($message); foreach ($data['system_id'] as $system) { $emails = System::where('id', $system)->first()->contacts; $message->systems()->attach( ['system_id' => $system] ); foreach ($emails as $email) { $message->contacts()->attach( ['contact_id' => $email->id], ['status' => StatusType::NotSend]); } } return response()->json(['success' => 'Message updated']); } public function destroy($id) { $message = Message::find($id); $message->delete(); Notify::success('Message deleted', 'Success', $options = []); return redirect()->back(); } } <file_sep>/data/docker/web/prod/Dockerfile FROM php:7.1-apache MAINTAINER <NAME> <<EMAIL>> ARG HOST_UID=1000 VOLUME ["/var/www/html"] ENV DEBIAN_FRONTEND noninteractive RUN apt-get update && apt-get install -y apt-utils RUN apt-get install -y \ cron \ zlib1g-dev \ libicu-dev \ libpq-dev \ libpcre3-dev \ git \ nano \ zip \ libfreetype6-dev \ libjpeg62-turbo-dev \ libmcrypt-dev \ libpng12-dev \ sudo \ openssh-server \ supervisor \ mysql-client \ cron \ && docker-php-ext-install -j$(nproc) iconv mcrypt \ && docker-php-ext-configure gd --with-freetype-dir=/usr/include/ --with-jpeg-dir=/usr/include/ \ && docker-php-ext-install -j$(nproc) gd \ && docker-php-ext-install intl zip pdo_mysql \ && docker-php-ext-install exif \ && apt-get clean \ && rm -rf /var/lib/apt/lists/* /tmp/* /var/tmp/* # Install Node.js RUN curl -sL https://deb.nodesource.com/setup_8.x | bash - \ && apt-get update && apt-get install -y nodejs COPY ./.bashrc /root/.bashrc COPY ./apache.conf /etc/apache2/sites-available/000-default.conf COPY ./php.ini /usr/local/etc/php/ RUN echo "LogFormat \"%a %l %u %t \\\"%r\\\" %>s %O \\\"%{User-Agent}i\\\"\" mainlog" >> /etc/apache2/apache2.conf RUN a2enmod rewrite remoteip # Install composer RUN set -x && curl -sS https://getcomposer.org/installer | php && mv composer.phar /usr/local/bin/composer # Setup permissions for user `www-data` RUN usermod -u ${HOST_UID} www-data && groupmod -g ${HOST_UID} www-data && chsh -s /bin/bash www-data # Setup cron ADD ./crontab /etc/cron.d/cron-jobs RUN chmod 0644 /etc/cron.d/cron-jobs && touch /var/log/cron.log # Setup supervisor RUN mkdir -p /var/log/supervisor COPY supervisord.conf /etc/supervisor/conf.d/supervisord.conf EXPOSE 80 CMD ["/usr/bin/supervisord"] <file_sep>/app/Http/Controllers/Dashboard/DashboardController.php <?php namespace App\Http\Controllers\Dashboard; use App\Http\Controllers\Controller; use App\Model\Dashboard\Tag; use App\Model\Parser\Record; use Carbon\Carbon; use Illuminate\Support\Facades\Auth; class DashboardController extends Controller { public function index() { $tags = Tag::all(); $records = Record::where([['tag_id', '>', 0], ['parser_date', '>', Carbon::now()->startOfDay()]])->orderBy('view', 'desc')->limit(5)->get(); return view('dashboard.dashboard', ['user' => Auth::user(), 'records' => $records, 'tags' => $tags]); } public function getGraphics($id, $from = null, $before = null) { $count = []; $day = []; if ($before != null && $from != null) { $before = Carbon::parse($before); $from = Carbon::parse($from); } elseif ($from != null) { $before = Carbon::now(); $from = Carbon::parse($from); } else{ $before = Carbon::now(); $from = Carbon::now()->startOfMonth(); } while ($from <= $before) { $count[] = Record::whereDate('parser_date', '=', $from->toDateString())->whereTagId($id)->count('id'); $day[] = date_format($from, 'd'); $from->addDay(); } if ($count && $day) { return response(['count' => $count, 'day' => $day, 'countDay' => count($day)], 200); } return response(['message' => 'Error !!'], 422); } } <file_sep>/app/Console/Commands/Parser.php <?php namespace App\Console\Commands; use App\Jobs\ParserJob; use App\Model\Dashboard\Tag; use Illuminate\Console\Command; class Parser extends Command { /** * The name and signature of the console command. * * @var string */ protected $signature = 'parser:tag'; /** * The console command description. * * @var string */ protected $description = 'Command description'; /** * Create a new command instance. * * @return void */ public function __construct() { parent::__construct(); } /** * Execute the console command. * * @return mixed */ public function handle() { $tags = Tag::all(); foreach ($tags as $tag) { ParserJob::dispatch($tag->name); } } } <file_sep>/app/Model/Dashboard/Message.php <?php namespace App\Model\Dashboard; use Illuminate\Database\Eloquent\Model; class Message extends Model { protected $fillable = ['label', 'title', 'text', 'system_id', 'message_id', 'status']; protected $with = [ 'systems' ]; public function contacts(){ return $this->belongsToMany('App\Model\Parser\Contact'); } public function sites(){ return $this->hasManyThrough('App\Model\Parser\Site', 'App\Model\Parser\Contact'); } public function systems(){ return $this->belongsToMany('App\Model\Dashboard\System'); } public function saveMessage(){ return $this->hasMany('App\Model\Dashboard\Message', 'id'); } } <file_sep>/app/Http/Controllers/Landing/LandingController.php <?php namespace App\Http\Controllers\Landing; use App\Mail\ResponseMail; use App\Model\Response\Response; use App\User; use App\Http\Controllers\Controller; use Illuminate\Http\Request; use Illuminate\Support\Facades\Mail; use Illuminate\Support\Facades\Validator; class LandingController extends Controller { public function index(){ return view('landing.landing', ['user' => User::find(1)]); } public function contact(Request $request){ $data = $request->all(); $validator = Validator::make($data, [ 'first_name'=>'required', 'last_name'=>'required', 'email'=>'required|email', 'url'=>'required|url', 'text'=>'required', ]); if ($validator->fails()) { return response()->json(['errors'=>$validator->errors()->all()]); }else { $user = User::where('id', '>', 0)->first(); Response::create([ 'name' => $data['first_name'], 'last_name' => $data['last_name'], 'email' => $data['email'], 'url' => $data['url'], 'text' => $data['text'], ]); Mail::to($user->email)->send(new ResponseMail($data)); return response()->json(['success' => 'Thanks you. We will contact you within 24 hours.']); } } } <file_sep>/app/Http/Controllers/Parser/ParserController.php <?php namespace App\Http\Controllers\Parser; use App\Events\ParserEvent; use App\Http\Controllers\Controller; use Helmesvs\Notify\Facades\Notify; class ParserController extends Controller { public function getContent($tag){ event(new ParserEvent($tag)); Notify::success('Parser started. Please reload page after 2 minutes!', 'Success', $options = []); return redirect()->back(); } } <file_sep>/app/Model/Dashboard/System.php <?php namespace App\Model\Dashboard; use Illuminate\Database\Eloquent\Model; class System extends Model { protected $fillable = ['name', 'status']; public function sites(){ return $this->hasMany('App\Model\Parser\Site'); } public function contacts(){ return $this->hasManyThrough('App\Model\Parser\Contact', 'App\Model\Parser\Site'); } } <file_sep>/.env.example HOST_UID=1000 APP_NAME=parser APP_ENV=local APP_KEY=<KEY> APP_DEBUG=true APP_LOG_LEVEL=debug APP_URL=http://localhost:45010 DB_CONNECTION=mysql DB_HOST=parser_db DB_PORT=3306 DB_DATABASE=parser DB_USERNAME=docker DB_PASSWORD=<PASSWORD> MIX_PUSHER_APP_KEY="${PUSHER_APP_KEY}" MIX_PUSHER_APP_CLUSTER="${PUSHER_APP_CLUSTER}" CACHE_DRIVER=file SESSION_DRIVER=file SESSION_LIFETIME=120 QUEUE_DRIVER=redis REDIS_HOST=127.0.0.1 REDIS_PASSWORD=<PASSWORD> REDIS_PORT=6379 MAIL_DRIVER=log MAIL_HOST=smtp.gmail.com MAIL_PORT=587 MAIL_USERNAME=null MAIL_PASSWORD=<PASSWORD> MAIL_ENCRYPTION=tls PUSHER_APP_ID= PUSHER_APP_KEY= PUSHER_APP_SECRET= PUSHER_APP_CLUSTER=mt1
adeb78526f61cc6d8b7935c68d668e74690e0107
[ "JavaScript", "Markdown", "PHP", "Dockerfile", "Shell" ]
37
JavaScript
StanislavAshykhmin/parser
38c5c8e92f443f646ec3bfb54c875c11ec859076
73dad292c4cb50302943d3548366c65e634b00ba
refs/heads/master
<file_sep>class Movie < ActiveRecord::Base # the constant that holds the start and end times of the movie ranges DURATION_RANGES = { "blank" => [0, 8 * 60], "short" => [0, 90], "medium" => [90, 120], "long" => [120, 8 * 60] }.freeze mount_uploader :poster_image, PosterImageUploader has_many :reviews validates :title, presence: true validates :director, presence: true validates :runtime_in_minutes, numericality: { only_integer: true } validates :description, presence: true validates :poster_image, presence: true validates :release_date, presence: true validate :release_date_is_in_the_past def self.movie_duration DURATION_RANGES end def review_average if reviews.size > 0 reviews.sum(:rating_out_of_ten)/reviews.size else "-" end end scope :by_title_or_director, ->(query_string) do where("title like :query OR director like :query", query: "%#{query_string}%") end scope :by_duration, -> (duration) do # checks if the duration from the query string is found in the if DURATION_RANGES[duration] start, stop = DURATION_RANGES[duration] where("runtime_in_minutes > #{start} AND runtime_in_minutes < #{stop}") else # raises an exception if the duration is not in the constant raise ArgumentError, "Duration #{duration} is not a defined range" end end private def release_date_is_in_the_past if release_date.present? errors.add(:release_date, "should be in the past") if release_date > Date.today end end end <file_sep>class ApplicationController < ActionController::Base # Prevent CSRF attacks by raising an exception. # For APIs, you may want to use :null_session instead. protect_from_forgery with: :exception before_filter :set_durations # duration_selections gets the keys from the constant DURATION_RANGES # => on the Movie class and map over it using the # => movies.duration_ranges in /config/locales/en.yml private def set_durations @duration_selections = Movie::DURATION_RANGES.keys.map do |key| [I18n.t(key, scope: "movies.duration_ranges"), key] end end def restrict_access if !current_user flash[:alert] = "You must log in." redirect_to new_session_path end end def restrict_non_admins unless admin? flash[:alert] = "You must be loggen in as an admin to access that area." redirect_to movies_path end end def admin? current_user && current_user.admin == true end def current_user @current_user ||= User.find(session[:user_id]) if session[:user_id] end helper_method :current_user helper_method :admin? end
02dde2d2d596c0285f262313f7cba125ead849d4
[ "Ruby" ]
2
Ruby
jenreiher/rotten-mangoes
b07420c63c594a55ffc196984b7c52980ba001e9
fdd2119012ee0e7465a9474bed6edd59a3ffd0bf
refs/heads/master
<file_sep>import Ship from './Ship'; export default class MainScene extends Phaser.Scene { private phaserSprite: Phaser.GameObjects.Sprite; private ship: Ship; private cursors: CursorKeys; constructor() { super({ key: "MainScene" }); } preload(): void { this.load.image("ship", "../assets/games/endlessRunner/head.png"); this.load.image("projectile", "../assets/games/endlessRunner/head.png"); } create(): void { this.ship = new Ship(this, 50, 50); this.cursors = this.input.keyboard.createCursorKeys(); this.input.on('pointerdown', pointer => this.ship.startFire(pointer)); this.input.on('pointerup', () => this.ship.stopFire()); } update(): void { const movement = new Phaser.Math.Vector2(0, 0); if (this.cursors.down.isDown) { movement.y += 4; } else if (this.cursors.up.isDown) { movement.y -= 4; } if (this.cursors.left.isDown) { movement.x -= 4; } else if (this.cursors.right.isDown) { movement.x += 4; } this.ship.move(movement); } } <file_sep>const { cos, sin } = Math; export const rotateVector2 = (a: number, v: Vec2): Phaser.Math.Vector2 => { const ca = cos(a); const sa = sin(a); return new Phaser.Math.Vector2( ca * v.x - sa * v.y, sa * v.x + ca * v.y, ); }; <file_sep>import Projectile from './Projectile'; import { rotateVector2 } from './utils'; const speed = 12; export default class ProjectileEmitter { private projectiles: Phaser.GameObjects.Group; private firing: boolean = false; private getFocus: () => Vec2; private getOrigin: () => Vec2; private fireTicks: number = 5; private ticksSinceLastFire: number = 0; constructor( public scene: Phaser.Scene, ) { this.projectiles = scene.add.group([]); } private getNextProjectileCount(): number { return 7; } private getProjAngleSpacing( focusDistance: number, projectileCount: number, ): number { const low = 50; const high = 300; const t = 1 - (Phaser.Math.Clamp(focusDistance, low, high) - low) / (high - low); const lowArc = Math.PI / 12; const highArc = Math.PI / 3; const a = t * t * (highArc - lowArc) + lowArc; return a / projectileCount; } private fire() { const origin = this.getOrigin(); const focus = this.getFocus(); const projCount = this.getNextProjectileCount(); const vFocus = new Phaser.Math.Vector2( focus.x - origin.x, focus.y - origin.y, ); const focusDistance = vFocus.length(); // don't fire if the focus point is too close to the origin if (focusDistance < .1) return; const projAngleSpacing = this.getProjAngleSpacing(focusDistance, projCount); vFocus.scale(speed / focusDistance); for (let i = 0; i < projCount; i++) { const v = rotateVector2( projAngleSpacing * (i - (projCount - 1) / 2), vFocus, ); const proj = new Projectile(this.scene, { x: origin.x, y: origin.y, vx: v.x, vy: v.y, }); this.projectiles.add(proj); } } public startFire( getOrigin: () => Vec2, getFocus: () => Vec2, ) { this.getOrigin = getOrigin; this.getFocus = getFocus; this.firing = true; } public stopFire() { this.firing = false; } update() { this.ticksSinceLastFire++; if (this.ticksSinceLastFire >= this.fireTicks) { if (this.firing) { this.fire(); this.ticksSinceLastFire = 0; } } } } <file_sep>import ProjectileEmitter from './ProjectileEmitter'; export default class Ship extends Phaser.GameObjects.Sprite { private emitter: ProjectileEmitter; constructor(scene: Phaser.Scene, x: number, y: number) { super(scene, x, y, 'ship'); scene.add.existing(this); scene.events.on('update', this.update.bind(this)); this.emitter = new ProjectileEmitter(scene); } move(v: Phaser.Math.Vector2): void { this.x += v.x; this.y += v.y; } public startFire(pointer: Phaser.Input.Pointer): void { this.emitter.startFire( () => this, () => pointer, ); } public stopFire() { this.emitter.stopFire(); } update() { this.emitter.update(); } } <file_sep>interface ProjectileConfig { x: number, y: number, vx: number, vy: number, } export default class Projectile extends Phaser.GameObjects.Sprite { constructor( public scene: Phaser.Scene, public config: ProjectileConfig, ) { super(scene, config.x, config.y, 'projectile'); scene.add.existing(this); this.scaleX = 0.2; this.scaleY = 0.2; scene.events.on('update', this.update.bind(this)); } update() { const { vx, vy } = this.config; this.x += vx; this.y += vy; } }
f7628e4013a2bc4619634bdcc311e21b9866d64f
[ "TypeScript" ]
5
TypeScript
graftss/ship-game
5820e723e5be6042f938d1cdbf77025bf8521454
c636849fc8ab91c5b6a0c3949737aff85f36c584
refs/heads/master
<file_sep>#include "../include/amjMemory.h" char msg[1000]; /**************************************************************************** * * * In this section are general memory allocation routines * * * ****************************************************************************/ /*========================================================================== amjSafeMalloc Allocates memory, but exits with an error message if the memory allocation fails. ==========================================================================*/ void *amjSafeMalloc(int n, char *message){ void *d; d=malloc(n); if(d==NULL){ fprintf(stderr,"amjSafeMalloc error: Could not allocate %d bytes " "for %s. Exiting.\n",n,message); exit(1); } return d; } /*========================================================================== amjSafeRealloc Re-allocates memory, but exits with an error message if the memory allocation fails. ==========================================================================*/ void *amjSafeRealloc(void *i, int n, char *message){ void *d; d=realloc(i,n); if(d==NULL){ fprintf(stderr,"amjSafeRealloc error: Could not re-allocate %d bytes " "for %s. Exiting.\n",n,message); exit(1); } return d; } /**************************************************************************** * * * In this section are specific array allocation routines * * * ****************************************************************************/ char *amjMalloc1dChar(int a, char *message){ char *d; sprintf(msg,"%s: amjMalloc1dChar:d",message); d=(char *)amjSafeMalloc(sizeof(char)*a,msg); return d; } /****************************************************************************/ void amjFree1dChar(char *d){ free(d); } /****************************************************************************/ char **amjMalloc2dChar(int a, int b, char *message){ char **d; int i; sprintf(msg,"%s: amjMalloc2dChar:d",message); d=(char **)amjSafeMalloc(sizeof(char *)*a,msg); d[0]=(char *)amjSafeMalloc(sizeof(char)*a*b,msg); for(i=1;i<a;i++) d[i]=d[i-1]+b; return d; } /****************************************************************************/ void amjFree2dChar(char **d){ free(d[0]); free(d); } /****************************************************************************/ char ***amjMalloc3dChar(int a, int b, int c, char *message){ char ***d; int i,j; sprintf(msg,"%s: amjMalloc3dChar:d",message); d=(char ***)amjSafeMalloc(sizeof(char **)*a,msg); sprintf(msg,"%s: amjMalloc3dChar:d[0]",message); d[0]=(char **)amjSafeMalloc(sizeof(char *)*a*b,msg); sprintf(msg,"%s:amjMalloc3dChar:d[0][0]",message); d[0][0]=(char *)amjSafeMalloc(sizeof(char)*a*b*c,msg); for(i=0;i<a;i++){ d[i]=d[0]+i*b; for(j=0;j<b;j++) d[i][j]=d[0][0]+(i*b+j)*c; } return d; } /****************************************************************************/ void amjFree3dChar(char ***d){ free(d[0][0]); free(d[0]); free(d); } /****************************************************************************/ unsigned char *amjMalloc1dUChar(int a, char *message){ unsigned char *d; sprintf(msg,"%s: amjMalloc1dUChar:d",message); d=(unsigned char *)amjSafeMalloc(sizeof(unsigned char)*a,msg); return d; } /****************************************************************************/ void amjFree1dUChar(unsigned char *d){ free(d); } /****************************************************************************/ unsigned char ***amjMalloc3dUChar(int a, int b, int c, char *message){ unsigned char ***d; int i,j; sprintf(msg,"%s: amjMalloc3dChar:d",message); d=(unsigned char ***)amjSafeMalloc(sizeof(char **)*a,msg); sprintf(msg,"%s: amjMalloc3dChar:d[0]",message); d[0]=(unsigned char **)amjSafeMalloc(sizeof(char *)*a*b,msg); sprintf(msg,"%s:amjMalloc3dChar:d[0][0]",message); d[0][0]=(unsigned char *)amjSafeMalloc(sizeof(char)*a*b*c,msg); for(i=0;i<a;i++){ d[i]=d[0]+i*b; for(j=0;j<b;j++) d[i][j]=d[0][0]+(i*b+j)*c; } return d; } /****************************************************************************/ void amjFree3dUChar(unsigned char ***d){ free(d[0][0]); free(d[0]); free(d); } /****************************************************************************/ uint8 ***amjMalloc3dUint8(int a, int b, int c, char *message){ uint8 ***d; int i,j; sprintf(msg,"%s: amjMalloc3dChar:d",message); d=(unsigned char ***)amjSafeMalloc(sizeof(uint8 **)*a,msg); sprintf(msg,"%s: amjMalloc3dChar:d[0]",message); d[0]=(unsigned char **)amjSafeMalloc(sizeof(uint8 *)*a*b,msg); sprintf(msg,"%s:amjMalloc3dChar:d[0][0]",message); d[0][0]=(unsigned char *)amjSafeMalloc(sizeof(uint8)*a*b*c,msg); for(i=0;i<a;i++){ d[i]=d[0]+i*b; for(j=0;j<b;j++) d[i][j]=d[0][0]+(i*b+j)*c; } return d; } /****************************************************************************/ void amjFree3dUint8(uint8 ***d){ free(d[0][0]); free(d[0]); free(d); } /****************************************************************************/ short int *amjMalloc1dShortInt(int a, char *message){ short int *d; sprintf(msg,"%s: amjMalloc1dShortInt:d",message); d=(short int *)amjSafeMalloc(sizeof(short int)*a,msg); return d; } /****************************************************************************/ void amjFree1dShortInt(short int *d){ free(d); } /****************************************************************************/ short int **amjMalloc2dShortInt(int a, int b, char *message){ short int **d; int i; sprintf(msg,"%s:amjMalloc2dShortInt:d",message); d=(short int **)amjSafeMalloc(sizeof(short int *)*a,msg); sprintf(msg,"%s:amjMalloc2dShortInt:d[0]",message); d[0]=(short int *)amjSafeMalloc(sizeof(short int)*a*b,msg); for(i=1;i<a;i++) d[i]=d[i-1]+b; return d; } /****************************************************************************/ void amjFree2dShortInt(short int **d){ free(d[0]); free(d); } /****************************************************************************/ unsigned short int **amjMalloc2dShortUint(int a, int b, char *message){ unsigned short int **d; int i; sprintf(msg,"%s:amjMalloc2dShortUint:d",message); d=(short unsigned int **)amjSafeMalloc(sizeof(unsigned short int *)*a,msg); sprintf(msg,"%s:amjMalloc2dShortUint:d[0]",message); d[0]=(short unsigned int *)amjSafeMalloc(sizeof(unsigned short int)*a*b,msg); for(i=1;i<a;i++) d[i]=d[i-1]+b; return d; } /****************************************************************************/ void amjFree2dShortUint(unsigned short int **d){ free(d[0]); free(d); } /****************************************************************************/ int *amjMalloc1dInt(int a, char *message){ int *d; sprintf(msg,"%s: amjMalloc1dInt:d",message); d=(int *)amjSafeMalloc(sizeof(int)*a,msg); return d; } /****************************************************************************/ void amjFree1dInt(int *d){ free(d); } /****************************************************************************/ int **amjMalloc2dInt(int a, int b, char *message){ int **d; int i; sprintf(msg,"%s: amjMalloc2dInt:d",message); d=(int **)amjSafeMalloc(sizeof(int *)*a,msg); d[0]=(int *)amjSafeMalloc(sizeof(int)*a*b,msg); for(i=1;i<a;i++) d[i]=d[i-1]+b; return d; } /****************************************************************************/ void amjFree2dInt(int **d){ free(d[0]); free(d); } /****************************************************************************/ int32 *amjMalloc1dInt32(int a, char *message){ int *d; sprintf(msg,"%s: amjMalloc1dInt32:d",message); d=(int32 *)amjSafeMalloc(sizeof(int32)*a,msg); return d; } /****************************************************************************/ void amjFree1dInt32(int32 *d){ free(d); } /****************************************************************************/ uint32 *amjMalloc1dUint32(int a, char *message){ uint32 *d; sprintf(msg,"%s: amjMalloc1dInt:d",message); d=(uint32 *)amjSafeMalloc(sizeof(uint32)*a,msg); return d; } /****************************************************************************/ void amjFree1dUint32(uint32 *d){ free(d); } /****************************************************************************/ unsigned long *amjMalloc1dULong(int a, char *message){ unsigned long *d; sprintf(msg,"%s: amjMalloc1dULong:d",message); d=(unsigned long *)amjSafeMalloc(sizeof(unsigned long)*a,msg); return d; } /****************************************************************************/ void amjFree1dULong(unsigned long *d){ free(d); } /****************************************************************************/ float *amjMalloc1dFloat(int a, char *message){ float *d; sprintf(msg,"%s:amjMalloc1DFloat:d",message); d=(float *)amjSafeMalloc(sizeof(float)*a,msg); return d; } /****************************************************************************/ void amjFree1dFloat(float *d){ free(d); } /****************************************************************************/ float **amjMalloc2dFloat(int a, int b, char *message){ float **d; int i; sprintf(msg,"%s:amjMalloc2DFloat:d",message); d=(float **)amjSafeMalloc(sizeof(float *)*a,msg); sprintf(msg,"%s:amjMalloc2DFloat:d[0]",message); d[0]=(float *)amjSafeMalloc(sizeof(float)*a*b,msg); for(i=1;i<a;i++) d[i]=d[i-1]+b; return d; } /****************************************************************************/ void amjFree2dFloat(float **d){ free(d[0]); free(d); } /****************************************************************************/ float ***amjMalloc3dFloat(int a, int b, int c, char *message){ float ***d; int i,j; sprintf(msg,"%s:amjMalloc3dFloat:d",message); d=(float ***)amjSafeMalloc(sizeof(float **)*a,msg); sprintf(msg,"%s:amjMalloc3dFloat:d[0]",message); d[0]=(float **)amjSafeMalloc(sizeof(float *)*a*b,msg); sprintf(msg,"%s:amjMalloc3dFloat:d[0][0]",message); d[0][0]=(float *)amjSafeMalloc(sizeof(float)*a*b*c,msg); for(i=0;i<a;i++){ d[i]=d[0]+i*b; for(j=0;j<b;j++) d[i][j]=d[0][0]+(i*b+j)*c; } return d; } /****************************************************************************/ void amjFree3dFloat(float ***d){ free(d[0][0]); free(d[0]); free(d); } /****************************************************************************/ float ****amjMalloc4dFloat(int a, int b, int c, int d, char *message){ float ****e; int i,j,k; sprintf(msg,"%s:amjMalloc4dFloat:e",message); e=(float ****)amjSafeMalloc(sizeof(float ***)*a,msg); sprintf(msg,"%s:amjMalloc4dFloat:e[0]",message); e[0]=(float ***)amjSafeMalloc(sizeof(float **)*a*b,msg); sprintf(msg,"%s:amjMalloc4dFloat:e[0][0]",message); e[0][0]=(float **)amjSafeMalloc(sizeof(float *)*a*b*c,msg); sprintf(msg,"%s:amjMalloc4dFloat:e[0][0][0]",message); e[0][0][0]=(float *)amjSafeMalloc(sizeof(float)*a*b*c*d,message); for(i=0;i<a;i++){ e[i]=e[0]+i*b; for(j=0;j<b;j++){ e[i][j]=e[0][0]+(i*b+j)*c; for(k=0;k<c;k++) e[i][j][k]=e[0][0][0]+((i*b+j)*c+k)*d; } } return e; } /****************************************************************************/ void amjFree4dFloat(float ****e){ free(e[0][0][0]); free(e[0][0]); free(e[0]); free(e); } /****************************************************************************/ double *amjMalloc1dDouble(int a, char *message){ double *d; sprintf(msg,"%s:amjMalloc1dDouble:d",message); d=(double *)amjSafeMalloc(sizeof(double)*a,msg); return d; } /****************************************************************************/ void amjFree1dDouble(double *d){ free(d); } /****************************************************************************/ double **amjMalloc2dDouble(int a, int b, char *message){ double **d; int i; sprintf(msg,"%s:amjMalloc2dDouble:d",message); d=(double **)amjSafeMalloc(sizeof(double *)*a,msg); sprintf(msg,"%s:amjMalloc2dDouble:d[0]",message); d[0]=(double *)amjSafeMalloc(sizeof(double)*a*b,msg); for(i=1;i<a;i++) d[i]=d[i-1]+b; return d; } /****************************************************************************/ void amjFree2dDouble(double **d){ free(d[0]); free(d); } /****************************************************************************/ double ***amjMalloc3dDouble(int a, int b, int c, char *message){ double ***d; int i,j; sprintf(msg,"%s:amjMalloc3dDouble:d",message); d=(double ***)amjSafeMalloc(sizeof(double **)*a,msg); sprintf(msg,"%s:amjMalloc3dDouble:d[0]",message); d[0]=(double **)amjSafeMalloc(sizeof(double *)*a*b,msg); sprintf(msg,"%s:amjMalloc3dDouble:d[0][0]",message); d[0][0]=(double *)amjSafeMalloc(sizeof(double)*a*b*c,msg); for(i=0;i<a;i++){ d[i]=d[0]+i*b; for(j=0;j<b;j++) d[i][j]=d[0][0]+(i*b+j)*c; } return d; } /****************************************************************************/ void amjFree3dDouble(double ***d){ free(d[0][0]); free(d[0]); free(d); } /****************************************************************************/ double ****amjMalloc4dDouble(int a, int b, int c, int d, char *message){ double ****e; int i,j,k; sprintf(msg,"%s:amjMalloc4dDouble:e",message); e=(double ****)amjSafeMalloc(sizeof(double ***)*a,msg); sprintf(msg,"%s:amjMalloc4dDouble:e[0]",message); e[0]=(double ***)amjSafeMalloc(sizeof(double **)*a*b,msg); sprintf(msg,"%s:amjMalloc4dDouble:e[0][0]",message); e[0][0]=(double **)amjSafeMalloc(sizeof(double *)*a*b*c,msg); sprintf(msg,"%s:amjMalloc4dDouble:e[0][0][0]",message); e[0][0][0]=(double *)amjSafeMalloc(sizeof(double)*a*b*c*d,message); for(i=0;i<a;i++){ e[i]=e[0]+i*b; for(j=0;j<b;j++){ e[i][j]=e[0][0]+(i*b+j)*c; for(k=0;k<c;k++) e[i][j][k]=e[0][0][0]+((i*b+j)*c+k)*d; } } return e; } /****************************************************************************/ void amjFree4dDouble(double ****d){ free(d[0][0][0]); free(d[0][0]); free(d[0]); free(d); } /****************************************************************************/ double *****amjMalloc5dDouble(int a, int b, int c, int d, int e, char *message){ double *****f; int i,j,k,l; sprintf(msg,"%s: amjMalloc5dDouble:f",message); f=(double *****)amjSafeMalloc(sizeof(double ****)*a,msg); sprintf(msg,"%s: amjMalloc5dDouble:f[0]",message); f[0]=(double ****)amjSafeMalloc(sizeof(double ***)*a*b,msg); sprintf(msg,"%s: amjMalloc5dDouble:f[0][0]",message); f[0][0]=(double ***)amjSafeMalloc(sizeof(double **)*a*b*c,msg); sprintf(msg,"%s: amjMalloc5dDouble:f[0][0][0]",message); f[0][0][0]=(double **)amjSafeMalloc(sizeof(double *)*a*b*c*d,msg); sprintf(msg,"%s: amjMalloc5dDouble:f[0][0][0][0]",message); f[0][0][0][0]=(double *)amjSafeMalloc(sizeof(double)*a*b*c*d*e,msg); for(i=0;i<a;i++){ f[i]=f[0]+i*b; for(j=0;j<b;j++){ f[i][j]=f[0][0]+(i*b+j)*c; for(k=0;k<c;k++){ f[i][j][k]=f[0][0][0]+((i*b+j)*c+k)*d; for(l=0;l<d;l++) f[i][j][k][l]=f[0][0][0][0]+(((i*b+j)*c+k)*d+l)*e; } } } return f; } /****************************************************************************/ void amjFree5dDouble(double *****d){ free(d[0][0][0][0]); free(d[0][0][0]); free(d[0][0]); free(d[0]); free(d); } /****************************************************************************/ double ******amjMalloc6dDouble(int a, int b, int c, int d, int e, int f, char *message){ double ******g; int i,j,k,l,m; sprintf(msg,"%s: amjMalloc6dDouble:g",message); g=(double ******)amjSafeMalloc(sizeof(double *****)*a,msg); sprintf(msg,"%s: amjMalloc6dDouble:g[0]",message); g[0]=(double *****)amjSafeMalloc(sizeof(double ****)*a*b,msg); sprintf(msg,"%s: amjMalloc6dDouble:g[0][0]",message); g[0][0]=(double ****)amjSafeMalloc(sizeof(double ***)*a*b*c,msg); sprintf(msg,"%s: amjMalloc6dDouble:g[0][0][0]",message); g[0][0][0]=(double ***)amjSafeMalloc(sizeof(double **)*a*b*c*d,msg); sprintf(msg,"%s: amjMalloc6dDouble:g[0][0][0][0]",message); g[0][0][0][0]=(double **)amjSafeMalloc(sizeof(double *)*a*b*c*d*e,msg); sprintf(msg,"%s: amjMalloc6dDouble:g[0][0][0][0][0]",message); g[0][0][0][0][0]=(double *)amjSafeMalloc(sizeof(double)*a*b*c*d*e*f,msg); for(i=0;i<a;i++){ g[i]=g[0]+i*b; for(j=0;j<b;j++){ g[i][j]=g[0][0]+(i*b+j)*c; for(k=0;k<c;k++){ g[i][j][k]=g[0][0][0]+((i*b+j)*c+k)*d; for(l=0;l<d;l++){ g[i][j][k][l]=g[0][0][0][0]+(((i*b+j)*c+k)*d+l)*e; for(m=0;m<e;m++) g[i][j][k][l][m]=g[0][0][0][0][0]+((((i*b+j)*c+k)*d+l)*e+m)*f; } } } } return g; } /****************************************************************************/ void amjFree6dDouble(double ******d){ free(d[0][0][0][0][0]); free(d[0][0][0][0]); free(d[0][0][0]); free(d[0][0]); free(d[0]); free(d); } /****************************************************************************/ <file_sep>includedir=$(prefix)/include build: install: $(includedir)/amjMemory.h $(includedir)/amjMemory.h: amjMemory.h cp amjMemory.h $(includedir) uninstall: - rm -f $(includedir)/amjMemory.h clean: <file_sep>libdir=$(prefix)/lib AMJMEMORY_SRC=amjMemory.c AMJMEMORY_OBJ=$(AMJMEMORY_SRC:.c=.o) CFLAGS=-Wall -g -fPIC CC=gcc build: libamjMemory.a libamjMemory.so libamjMemory.a: $(AMJMEMORY_OBJ) ar rc $@ $^ libamjMemory.so: $(AMJMEMORY_OBJ) $(CC) -shared -Wl,-soname,$@ -o $@ $^ install: $(libdir)/libamjMemory.a $(libdir)/libamjMemory.so $(libdir)/libamjMemory.a $(libdir)/libamjMemory.so: cp libamjMemory.a libamjMemory.so $(libdir) uninstall: - rm -f $(libdir)/libamjMemory.a $(libdir)/libamjMemory.so clean: - rm -f libamjMemory.a libamjMemory.so $(AMJMEMORY_OBJ) <file_sep>#installation directory prefix ifndef prefix export prefix=~ endif export prefix build: $(MAKE) -C src build $(MAKE) -C include build install: build $(MAKE) -C src install $(MAKE) -C include install uninstall: $(MAKE) -C src uninstall $(MAKE) -C include uninstall clean: $(MAKE) -C src clean $(MAKE) -C include clean <file_sep>#ifndef _AMJMEMORY_H #define _AMJMEMORY_H #include <stdlib.h> #include <stdio.h> #define uint8 unsigned char #define uint32 unsigned int #define int32 int /**************************************************************************** * * * In this section are general memory allocation routines * * * ****************************************************************************/ void *amjSafeMalloc(int n, char *message); void *amjSafeRealloc(void *i, int n, char *message); /**************************************************************************** * * * In this section are specific array allocation routines * * * ****************************************************************************/ char *amjMalloc1dChar(int a, char *message); void amjFree1dChar(char *d); char **amjMalloc2dChar(int a, int b, char *messsage); void amjFree2dChar(char **d); char ***amjMalloc3dChar(int a, int b, int c, char *message); void amjFree3dChar(char ***d); unsigned char *amjMalloc1dUChar(int a, char *message); void amjFree1dUChar(unsigned char *d); unsigned char ***amjMalloc3dUChar(int a, int b, int c, char *message); void amjFree3dUChar(unsigned char ***d); uint8 ***amjMalloc3dUint8(int a, int b, int c, char *message); void amjFree3dUint8(uint8 ***d); short int *amjMalloc1dShortInt(int a, char *message); void amjFree1dShortInt(short int *d); short int **amjMalloc2dShortInt(int a, int b, char *message); void amjFree2dShortInt(short int **d); unsigned short int **amjMalloc2dShortUint(int a, int b, char *message); void amjFree2dShortUint(unsigned short int **d); int *amjMalloc1dInt(int a, char *message); void amjFree1dInt(int *d); int **amjMalloc2dInt(int a, int b, char *message); void amjFree2dInt(int **d); int32 *amjMalloc1dInt32(int a, char *message); void amjFree1dInt32(int32 *d); uint32 *amjMalloc1dUint32(int a, char *message); void amjFree1dUint32(uint32 *d); unsigned long *amjMalloc1dULong(int a, char *message); void amjFree1dULong(unsigned long *d); float *amjMalloc1dFloat(int a, char *message); void amjFree1dFloat(float *d); float **amjMalloc2dFloat(int a, int b, char *message); void amjFree2dFloat(float **d); float ***amjMalloc3dFloat(int a, int b, int c, char *message); void amjFree3dFloat(float ***d); float ****amjMalloc4dFloat(int a, int b, int c, int d, char *message); void amjFree4dFloat(float ****d); double *amjMalloc1dDouble(int a, char *message); void amjFree1dDouble(double *d); double **amjMalloc2dDouble(int a, int b, char *message); void amjFree2dDouble(double **d); double ***amjMalloc3dDouble(int a, int b, int c, char *message); void amjFree3dDouble(double ***d); double ****amjMalloc4dDouble(int a, int b, int c, int d, char *message); void amjFree4dDouble(double ****d); double *****amjMalloc5dDouble(int a, int b, int c, int d, int e, char *message); void amjFree5dDouble(double *****d); double ******amjMalloc6dDouble(int a, int b, int c, int d, int e, int f, char *message); void amjFree6dDouble(double ******d); #endif
74b0e9510ce58b7969ec2a8c55b16a05cc9dcdc0
[ "C", "Makefile" ]
5
C
amjjam/amjMemory
81a9ca7747474df3995f9862fd6e06b168837fd3
7ac8f4f29d4cc3ebd798b39bfd5c2b6f645440d5
refs/heads/main
<repo_name>Dayong99/webgd-cloud<file_sep>/src/icons.js // src/icons.js // export what you need export { default as SmileOutline } from '@ant-design/icons/lib/outline/SmileOutline'; export { default as MehOutline } from '@ant-design/icons/lib/outline/MehOutline'; // export what antd other components need export { default as CloseOutline } from '@ant-design/icons/lib/outline/CloseOutline'; // and other icons... <file_sep>/src/store/modules/enhance.js import Vue from 'vue' import {getAction} from '@/api/manage' const enhance = { state: { enhanceJs: {}, selectOn: 0, menuList: JSON.parse(sessionStorage.getItem('menu')) || [] }, mutations: { ADD_TABLE_ENHANCE: (state, record) => { if (!state.enhanceJs) { let obj = {} let arr = [] arr.push({...record}) obj[record.code] = arr state.enhanceJs = obj } else { if (!state.enhanceJs[record.code]) { let arr = [] arr.push({...record}) state.enhanceJs[record.code] = arr } state.enhanceJs[record.code].push({...record}) } let arr = state.enhanceJs[record.code] while (arr.length > 16) { arr.shift() } Vue.ls.set('enhance_' + record['code'], arr) }, dsHeadIndex: (state, idx) => { state.selectOn = idx }, getMenuList: (state, menus) => { state.menuList = menus // menus.forEach(item=>{ // state.menuList.push(item) // }) window.sessionStorage.setItem('menu', JSON.stringify(state.menuList)) // state.menuList = menus } }, actions: { addEhanceRecord({commit}, record) { commit('ADD_TABLE_ENHANCE', record) }, setMenuList({commit}, param) { return new Promise((resolve, reject) => { getAction("/sys/permission/queryBSPermission", param).then(response => { // console.log(response) const result = response.result if (result.length > 0) { const list = []; result.forEach((value, index) => { list.push({ index: index, name: value.bigScreenName, url: value.bigScreenUrl }) }) commit('getMenuList', list) resolve(response) } else { reject(response) } }).catch(error => { reject(error) }) }) }, // setHeadIndex(context,list){ // context.commit('getHeadIndex',list) // } } } export default enhance<file_sep>/src/utils/Imgaes.js const images = { //背景图片 loginBg: require('@/assets/digitalScreen-images/loginBg.png'), bkPng: require('@/assets/bkPng.png'), //头部导航栏图片 topBoth: require('@/assets/digitalScreen-images/topBoth.png'), topContent: require('@/assets/digitalScreen-images/topContent.png'), blackLogo: require('@/assets/digitalScreen-images/blackLogo.png'), companyLogo: require('@/assets/digitalScreen-images/companyLogo.png'), leftLogo: require('@/assets/digitalScreen-images/leftLogo.png'), //组件标题头部 frameTitle: require('@/assets/digitalScreen-images/frameTitle.png'), frameTitleOff: require('@/assets/digitalScreen-images/frameTitleOff.png'), frameTitleOn: require('@/assets/digitalScreen-images/frameTitleOn.png'), frameTitleStrip: require('@/assets/digitalScreen-images/frameTitleStrip.png'), frameTitleLog: require('@/assets/digitalScreen-images/frameTitleLog.png'), big_Title_bg: require('@/assets/digitalScreen-images/big_tittle.png'), //质量安全弹窗 closeWindow: require('@/assets/digitalScreen-images/closeWindow.png'), qualityPopup: require('@/assets/digitalScreen-images/qualityPopup.png'), popupBackground: require('@/assets/digitalScreen-images/popupBackground.png'), //梁场 bridgeIconOne: require('@/assets/digitalScreen-images/bridgeIcon1.png'), bridgeIconTwo: require('@/assets/digitalScreen-images/bridgeIcon2.png'), bridgeIconThree: require('@/assets/digitalScreen-images/bridgeIcon3.png'), bridgeIconFour: require('@/assets/digitalScreen-images/bridgeIcon4.png'), //测试图片 csTitle: require('@/assets/digitalScreen-images/cs-title.jpg'), } export default images<file_sep>/src/views/digitalScreen/girderFabricationYard/js/echartsSecondaryEncapsulation.js import echarts from "@/utils/echarts"; export default { /** * 二次封装饼图 * @returns * */ //左饼图 getLeftOption(data) { let option = echarts.getDefaultPieOption(); option.tooltip.trigger = "item"; option.legend = { type: "plain", // bottom: 20, // itemGap: 20, width: "auto", textStyle: { color: "#ffffff", fontSize: "14px", }, }; option.series = { name: "总人数", type: "pie", center: ["50%", "74%"], // radius: ["50%", "70%"], // avoidLabelOverlap: false, bottom: "20%", label: { show: false, position: "center", }, emphasis: { show: true, }, labelLine: { show: true, }, data: data }; return option; }, //右饼图 getRightOption(data) { let option = echarts.getDefaultPieOption(); option.tooltip.trigger = "item"; option.legend = { show: false, type: "plain", // bottom: 20, // itemGap: 20, width: "auto", textStyle: { color: "#ffffff", fontSize: "14px", }, }; option.series = [{ name: "总人数", type: "pie", center: ["50%", "50%"], radius: ["35%", "80%"], // avoidLabelOverlap: false, bottom: "20%", label: { show: true, normal: { formatter: '{b}:{d}%', textStyle: { fontSize: 12, color:'#fff' } } }, emphasis: { show: true, }, labelLine: { show: true, }, data: data }]; return option; }, }<file_sep>/src/utils/echarts.js //-------------------------------------- // Copyright (c) 2021. // 作者:梁士博(Mr.liang) // 日期:2021-02-04 15:27:57 // Copyright (c) 2021. //-------------------------------------- import Vue from 'vue' import 'echarts/lib/component/legendScroll' export default { /** * 获取竖柱状图默认设置 * @returns * */ getDefaultBarColumnOption() { return { title: { x: 'left', show: true,//显示策略,默认值true,可选为:true(显示) | false(隐藏) text: '',//主标题文本,'\n'指定换行 textStyle: {//主标题文本样式 color: '#555', fontSize: 16, }, }, color: ['#00c8ff'], toolbox: { orient: 'horizontal', y: 'top', featureTitle: { mark: false, } }, tooltip: { showDelay: 20, hideDelay: 100, transitionDurantion: .3, backgroundColor: 'rgba(0,0,0,.3)', borderRadius: 4, borderWidth: 0, trigger: 'axis', textStyle: {//主标题文本样式 color: '#fff', fontSize: 10, }, axisPointer: { type: 'line', // 默认为直线,可选为:'line' | 'shadow' lineStyle: { // 直线指示器样式设置 color: 'rgba(0,0,0,0)', width: 0, type: 'solid' }, shadowStyle: { // 阴影指示器样式设置 width: 0, // 阴影大小 color: 'rgba(0,0,0,0.3)' // 阴影颜色 }, }, }, grid: { bottom: '4%', left: '25%', containLabel: false }, categoryAxis: { boundaryGap: false, // 类目起始和结束两端空白策略 axisLine: { // 坐标轴线 show: false, // 默认显示,属性show控制显示与否 lineStyle: { // 属性lineStyle控制线条样式 color: '#48b', width: 2, type: 'solid' } }, axisTick: { // 坐标轴小标记 show: false, // 属性show控制显示与否,默认不显示 interval: 'auto', // onGap: null, inside: false, // 控制小标记是否在grid里 length: 5, // 属性length控制线长 lineStyle: { // 属性lineStyle控制线条样式 color: '#333', width: 1 } }, axisLabel: { // 坐标轴文本标签,详见axis.axisLabel show: false, interval: 'auto', rotate: 0, margin: 8, // formatter: null, textStyle: { // 其余属性默认使用全局文本样式,详见TEXTSTYLE color: '#333' } }, splitArea: { // 分隔区域 show: false, // 默认不显示,属性show控制显示与否 // onGap: null, areaStyle: { // 属性areaStyle(详见areaStyle)控制区域样式 } } }, yAxis: { type: "category", data: [], axisLabel: { show: true, textStyle: {//x轴文字样式 color: '#999' }, formatter: function (value) { let res = value; if (res.length > 6) { res = res.substring(0, 6) + ".."; } return res; } }, axisLine: {//x轴线的颜色 show: true, lineStyle: { color: '#eee' } }, splitLine: { // 分隔线 show: false, // 默认显示,属性show控制显示与否 }, }, xAxis: { type: "value", data: [], axisLabel: { show: true, textStyle: {//x轴文字样式 color: '#fff', fontSize: 14 } }, axisLine: {//x轴线的颜色 show: false, lineStyle: { color: '#fff' } }, splitLine: { // 分隔线 show: false, // 默认显示,属性show控制显示与否 }, }, series: [{ name: "查获数量", barWidth: 20, barGap: 20, barCategoryGap: '20%', type: "bar", itemStyle: { normal: { color: Vue.prototype.$echarts.graphic.LinearGradient(0, 0, 1, 0, [{ //给颜色设置渐变色 前面4个参数,给第一个设置1,第四个设置0 ,就是水平渐变 //给第一个设置0,第四个设置1,就是垂直渐变 offset: 1, color: 'rgba(30,181,229,.9)' }, { offset: 0, color: 'rgba(92,203,177,.3)' }]), } }, data: [], }], dataZoom: [//给x轴设置滚动条 { start: 100,//默认为0 end: 50,//默认为100 type: 'slider', show: true, yAxisIndex: [0], handleSize: 10,//滑动条的 左右2个滑动条的大小 height: '60%',//组件高度 top: '20%', right: '0%', //左边的距离 width: 14, handleStyle: { borderColor: "#fff", borderWidth: "1", shadowBlur: 2, background: "#ddd", shadowColor: "#ddd", }, fillerColor: Vue.prototype.$echarts.graphic.LinearGradient(1, 0, 0, 0, [{ //给颜色设置渐变色 前面4个参数,给第一个设置1,第四个设置0 ,就是水平渐变 //给第一个设置0,第四个设置1,就是垂直渐变 offset: 0, color: 'rgba(30,181,229,.5)' }, { offset: 1, color: 'rgba(92,203,177,.5' }]), // fillerColor: 'rgba(76,160,255,.5)', backgroundColor: 'rgba(0,0,0,.15)',//两边未选中的滑动条区域的颜色 showDataShadow: true,//是否显示数据阴影 默认auto showDetail: false,//即拖拽时候是否显示详细数值信息 默认true realtime: true, //是否实时更新 filterMode: 'filter', borderColor: 'rgba(0,0,0,0)', shadowColor: 'rgba(0,0,0,.8)', handleIcon: 'M10.7,11.9v-1.3H9.3v1.3c-4.9,0.3-8.8,4.4-8.8,9.4c0,5,3.9,9.1,8.8,9.4v1.3h1.3v-1.3c4.9-0.3,8.8-4.4,8.8-9.4C19.5,16.3,15.6,12.2,10.7,11.9z M13.3,24.4H6.7V23h6.6V24.4z M13.3,19.6H6.7v-1.4h6.6V19.6z', }, //下面这个属性是里面拖到 { type: 'inside', show: true, yAxisIndex: [0], start: 0,//默认为1 end: 50,//默认为100 }, ], } }, /** * 获取饼图的默认设置 */ getDefaultPieOption() { return { tooltip: { show: true, textStyle: { //设置鼠标移动上去的文字样式 color: '#fff', fontSize: 16 }, trigger: "item", formatter: "{b}: {c} ({d}%)", showDelay: 20, // 显示延迟,添加显示延迟可以避免频繁切换,单位ms hideDelay: 100, // 隐藏延迟,单位ms transitionDuration: 0.4, // 动画变换时间,单位s backgroundColor: 'rgba(0,0,0,0.7)', // 提示背景颜色,默认为透明度为0.7的黑色 borderColor: '#333', // 提示边框颜色 borderRadius: 4, // 提示边框圆角,单位px,默认为4 borderWidth: 0, // 提示边框线宽,单位px,默认为0(无边框) padding: 5, // 提示内边距,单位px,默认各方向内边距为5, // 接受数组分别设定上右下左边距,同css axisPointer: { // 坐标轴指示器,坐标轴触发有效 type: 'line', // 默认为直线,可选为:'line' | 'shadow' lineStyle: { // 直线指示器样式设置 color: '#48b', width: 2, type: 'solid' }, shadowStyle: { // 阴影指示器样式设置 width: 'auto', // 阴影大小 color: 'rgba(150,150,150,0.3)' // 阴影颜色 } } }, title: { x: 'left', show: true,//显示策略,默认值true,可选为:true(显示) | false(隐藏) text: '',//主标题文本,'\n'指定换行 textStyle: {//主标题文本样式 color: '#555', fontSize: 16, }, }, //内部图层配置 grid: { // //上右下左属性等于一个相对父级的定位 left: "0%", right: "0%", bottom: "", top: '0', containLabel: true, }, color: ['#3FEEA5', '#32c5e9', '#67e0e3', '#9fe6b8', '#ffdb5c', '#ff9f7f', '#fb7293', '#e062ae', '#e690d1', '#e7bcf3', '#9d96f5', '#8378ea', '#96bfff'],//设置颜色 legend: {//设置图例部分 show: true, textStyle: { //设置图例文字的样式 color: '#fff',//设置颜色 fontSize: 12, }, itemWidth: 12, itemHeight: 12, itemGap: 5, orient: "vertical", //设置图例的位置,bottom、left、left、right right: '0', top: '20', }, series: [ { name: "", type: "pie", center: ['30%', '54%'], radius: ["0%", "80%"],//控制内圈和外圈圆的大小 roseType: '', avoidLabelOverlap: false, label: { show: false, position: "left", }, emphasis: { label: { show: false, fontSize: "14", fontWeight: "bold", }, }, labelLine: { show: true, }, data: [],//数值 }, ], } }, /** * 获取横柱状图的默认设置 */ getDefaultBarOption() { return { title: { x: 'left', show: true,//显示策略,默认值true,可选为:true(显示) | false(隐藏) text: '',//主标题文本,'\n'指定换行 textStyle: {//主标题文本样式 color: '#555', fontSize: 16, }, }, color: '#00c8ff', toolbox: { orient: 'horizontal', y: 'top', featureTitle: { mark: false, } }, tooltip: { showDelay: 20, hideDelay: 100, transitionDurantion: .3, backgroundColor: 'rgba(0,0,0,.3)', borderRadius: 4, borderWidth: 0, trigger: 'axis', textStyle: {//主标题文本样式 color: '#fff', fontSize: 10, }, }, axisPointer: { type: 'line', // 默认为直线,可选为:'line' | 'shadow' lineStyle: { // 直线指示器样式设置 color: 'rgba(0,0,0,0)', width: 0, type: 'solid' }, shadowStyle: { // 阴影指示器样式设置 width: 0, // 阴影大小 color: 'rgba(0,0,0,0.3)' // 阴影颜色 }, }, legend: {//设置图例部分 show: false, textStyle: { //设置图例文字的样式 color: '#999',//设置颜色 fontSize: 12, }, itemWidth: 12, itemHeight: 12, itemGap: 5, orient: "vertical", //设置图例的位置,bottom、left、left、right right: '0', top: '20', }, grid: { bottom: '40', left: '36', top: 36, containLabel: false, right: 16 }, categoryAxis: { boundaryGap: false, // 类目起始和结束两端空白策略 axisLine: { // 坐标轴线 show: false, // 默认显示,属性show控制显示与否 lineStyle: { // 属性lineStyle控制线条样式 color: '#48b', width: 2, type: 'solid' } }, axisTick: { // 坐标轴小标记 show: false, // 属性show控制显示与否,默认不显示 interval: 'auto', // onGap: null, inside: false, // 控制小标记是否在grid里 length: 5, // 属性length控制线长 lineStyle: { // 属性lineStyle控制线条样式 color: '#333', width: 1 } }, axisLabel: { // 坐标轴文本标签,详见axis.axisLabel show: false, interval: 'auto', rotate: 0, margin: 8, // formatter: null, textStyle: { // 其余属性默认使用全局文本样式,详见TEXTSTYLE color: '#333' } }, splitArea: { // 分隔区域 show: false, // 默认不显示,属性show控制显示与否 // onGap: null, areaStyle: { // 属性areaStyle(详见areaStyle)控制区域样式 } } }, xAxis: { data: [], axisLabel: { show: true, textStyle: {//x轴文字样式 color: '#999', fontSize: 14 } }, axisLine: {//x轴线的颜色 show: true, lineStyle: { color: '#eee' } }, splitLine: { show: false }, }, yAxis: { axisLabel: { show: true, textStyle: {//x轴文字样式 color: '#999', fontSize: 14 } }, axisLine: {//x轴线的颜色 show: true, lineStyle: { color: '#eee' } }, splitLine: { // 参考线 show: true, color: 'block' }, }, series: [{ name: "查获数量", barWidth: 20, barGap: 20, barCategoryGap: '20%', type: "bar", itemStyle: { normal: { color: Vue.prototype.$echarts.graphic.LinearGradient(0, 1, 0, 0, [{ //给颜色设置渐变色 前面4个参数,给第一个设置1,第四个设置0 ,就是水平渐变 //给第一个设置0,第四个设置1,就是垂直渐变 offset: 0, color: '#009cff' }, { offset: 1, color: '#ae53e7' }]), } }, data: [], }], } }, /** * 获取折线图的默认设置 */ getDefaultLineOption() { return { title: { x: 'left', show: true,//显示策略,默认值true,可选为:true(显示) | false(隐藏) text: '',//主标题文本,'\n'指定换行 textStyle: {//主标题文本样式 color: '#555', fontSize: 16, }, }, //鼠标移动上去的信息窗口 tooltip: { //鼠标移动上去的信息窗口 //show:false, trigger: "axis", axisPointer: { //鼠标移动到图表显示十字 // type: "cross", //文本框框的样式 label: { backgroundColor: "#6a7985",//背景颜色 }, }, }, //设置图例部分 legend: { show: true, textStyle: { //设置图例文字的样式 color: '#fff', fontSize: 12, }, orient: "horizontal", //设置图例的位置,bottom、left、left、right right: 'center', top: '0', }, //内部图层配置 grid: { // //上右下左属性等于一个相对父级的定位 left: 16, right: 16, bottom: 20, containLabel: true, }, //操作x轴的配置 xAxis: [{ type: "category", data: ['1月', '2月', '3月', '4月', '5月', '6月', '7月', '8月', '9月', '10月', '11月', '12月'], //两边的留白 boundaryGap: false, axisLabel: { show: true, textStyle: {//x轴文字样式 color: '#999' } }, axisLine: {//x轴线的颜色 lineStyle: { color: '#eee' }, }, splitLine: { // 参考线 show: false, color: '#eee' }, }], //操作y轴的配置 yAxis: [{ type: "value", axisLabel: {//y轴文字样式 show: true, textStyle: { color: '#999' } }, axisLine: {//y轴线的颜色 show: false, lineStyle: { color: '#eee' }, }, splitLine: { // 参考线 show: true, color: 'block' }, data: [], }], //操作数据类型和数据的配置 series: [{ name: '去年', type: "line", // stack: "总量", areaStyle: { global: false, type: 'default', color: Vue.prototype.$echarts.graphic.LinearGradient(0, 0, 0, 1,//变化度 //两种由深及浅的颜色 [{ offset: 0, color: 'rgba(93,236,133,.8)' }, { offset: 1, color: 'rgba(93,236,133,.4)' }]), }, symbol: 'emptyCircle', symbolSize: 2,//拐点大小 // 折线弧度 smooth: .5, color: ['#4dd08a'], itemStyle: { normal: { lineStyle: { width: 2, // color:'#70c8ee', type: 'solid',//dottde虚线 solid 实线 color: 'rgba(77,208,138,1)',// 线颜色 }, label: { show: true, borderColor: '', borderWidth: 2 } } }, data: [], }] } } } <file_sep>/src/views/digitalScreen/qualityAndSafety/js/echartsSecondaryEncapsulation.js import echarts from "@/utils/echarts"; export default { /** * 二次封装饼图 * @returns * */ //左饼图 getLeftOption(data) { let option = echarts.getDefaultPieOption(); // option.grid = { // top: "55%", // left: "90px", // right: "50px", // bottom: "50px" // }, option.tooltip.trigger = "item"; option.legend = { show: false, type: "plain", // bottom: 20, // itemGap: 20, width: "auto", textStyle: { color: "#ffffff", fontSize: "14px", }, }; option.series = { name: "总人数", type: "pie", center: ["50%", "50%"], radius: ["35%", "80%"], // avoidLabelOverlap: false, bottom: "20%", label: { show: true, normal: { formatter: '{b}:{d}%', textStyle: { fontSize: 12, color: '#fff' } } }, emphasis: { show: true, }, labelLine: { show: true, }, data: data }; return option; }, //中间折线图 getMiddleOption(data, time) { let option = echarts.getDefaultLineOption(); option.legend = { width: '800px', textStyle: { //设置图例文字的样式 color: '#fff', fontSize: 12, }, }, option.color=[ "rgba(255, 63, 63, 1)", "rgba(50, 197, 78, 1)", "rgba(242, 199, 97, 1)", "rgba(242, 153, 97, 1)", "rgba(0, 204, 205, 1)", ], option.xAxis = { // category: 'category', // boundaryGap: false, data: time, }, option.yAxis = { type: 'value' }, option.series = data return option }, //右饼图 getRightOption(data) { let option = echarts.getDefaultPieOption(); option.tooltip.trigger = "item"; option.legend = { type: "plain", // bottom: 20, // itemGap: 20, width: "auto", textStyle: { color: "#ffffff", fontSize: "14px", }, }; option.series = [{ name: "总人数", type: "pie", center: ["50%", "74%"], // radius: ["50%", "70%"], // avoidLabelOverlap: false, bottom: "20%", label: { show: false, position: "center", }, emphasis: { show: true, }, labelLine: { show: true, }, data: data }]; return option; }, }<file_sep>/src/api/api.js import { getAction, deleteAction, putAction, postAction, httpAction } from '@/api/manage' import Vue from 'vue' import {UI_CACHE_DB_DICT_DATA } from "@/store/mutation-types" import store from '@/store' //角色管理 const addRole = (params)=>postAction("/sys/role/add",params); const editRole = (params)=>putAction("/sys/role/edit",params); const checkRoleCode = (params)=>getAction("/sys/role/checkRoleCode",params); const queryall = (params)=>getAction("/sys/role/queryall",params); //用户管理 const addUser = (params)=>postAction("/sys/user/add",params); const editUser = (params)=>putAction("/sys/user/edit",params); const queryUserRole = (params)=>getAction("/sys/user/queryUserRole",params); const getUserList = (params)=>getAction("/sys/user/list",params); const frozenBatch = (params)=>putAction("/sys/user/frozenBatch",params); //验证用户是否存在 const checkOnlyUser = (params)=>getAction("/sys/user/checkOnlyUser",params); //改变密码 const changePassword = (params)=>putAction("/sys/user/changePassword",params); //权限管理 const addPermission= (params)=>postAction("/sys/permission/add",params); const editPermission= (params)=>putAction("/sys/permission/edit",params); const getPermissionList = (params)=>getAction("/sys/permission/list",params); const getSystemMenuList = (params)=>getAction("/sys/permission/getSystemMenuList",params); const getSystemSubmenu = (params)=>getAction("/sys/permission/getSystemSubmenu",params); const getSystemSubmenuBatch = (params) => getAction('/sys/permission/getSystemSubmenuBatch', params) const queryTreeList = (params)=>getAction("/sys/permission/queryTreeList",params); const queryTreeListForRole = (params)=>getAction("/sys/role/queryTreeList",params); const queryListAsync = (params)=>getAction("/sys/permission/queryListAsync",params); const queryRolePermission = (params)=>getAction("/sys/permission/queryRolePermission",params); const saveRolePermission = (params)=>postAction("/sys/permission/saveRolePermission",params); const queryPermissionsByUser = ()=>getAction("/sys/permission/getUserPermissionByToken"); const loadAllRoleIds = (params)=>getAction("/sys/permission/loadAllRoleIds",params); const getPermissionRuleList = (params)=>getAction("/sys/permission/getPermRuleListByPermId",params); const queryPermissionRule = (params)=>getAction("/sys/permission/queryPermissionRule",params); // 目录树 const documenTreeList = (params)=>getAction("/sys/archivesTree/queryTreeList?relTenantIds="+store.state.user.info.relTenantIds+"&depId="+store.state.user.info.departIds,params); const documenByDepartId = (params)=>deleteAction("/sys/archivesTree/delete",params); // 保存部门id const documencertigier = (params)=>postAction("/sys/archivesTreeDepart/save",params); // 获取已勾选的部门id const documencertigierID = (params)=>getAction("/sys/archivesTreeDepart/list",params); // 生产记录的查询 const productionSearch = (params)=>getAction("/beamyard/structRecord/list",params); // 关联记录查询 const relationalrecord = (params)=>getAction("/beamyard/structLedger/list",params); // 梁 排序判断 const bridgesort = (params)=>getAction("/beamyard/structStatus/sortCheck",params); // 参建单位 const contractor = (params)=>getAction("/contractor/contractor/list",params); // 参见单位删除 const contractordelete = (params)=>deleteAction("/contractor/contractor/delete",params); // 隐患列表查询 const danger = (params)=>getAction("/sys/hazardType/list",params); // 隐患类型删除 const dangerdelete = (params)=>deleteAction("/sys/hazardType/delete",params); // 人员管理操作 const personTreeList=(params)=>getAction('/person/person/queryPersonTree',params) // 部门管理 const queryDepartTreeList = (params)=>getAction("/sys/sysDepart/queryTreeList?relTenantIds="+store.state.user.info.relTenantIds,params); const queryIdTree = (params)=>getAction("/sys/sysDepart/queryIdTree?relTenantIds="+store.state.user.info.relTenantIds,params); const queryParentName = (params)=>getAction("/sys/sysDepart/queryParentName",params); const searchByKeywords = (params)=>getAction("/sys/sysDepart/searchBy?relTenantIds="+store.state.user.info.relTenantIds,params); const deleteByDepartId = (params)=>deleteAction("/sys/sysDepart/delete",params); //二级部门管理 const queryDepartPermission = (params)=>getAction("/sys/permission/queryDepartPermission",params); const saveDepartPermission = (params)=>postAction("/sys/permission/saveDepartPermission",params); const queryTreeListForDeptRole = (params)=>getAction("/sys/sysDepartPermission/queryTreeListForDeptRole",params); const queryDeptRolePermission = (params)=>getAction("/sys/sysDepartPermission/queryDeptRolePermission",params); const saveDeptRolePermission = (params)=>postAction("/sys/sysDepartPermission/saveDeptRolePermission",params); const queryMyDepartTreeList = (params)=>getAction("/sys/sysDepart/queryMyDeptTreeList",params); //日志管理 const deleteLog = (params)=>deleteAction("/sys/log/delete",params); const deleteLogList = (params)=>deleteAction("/sys/log/deleteBatch",params); // 新添加的接口 const start = (params)=>putAction("/person/person/updatePersonUserStatus",params); // 首页请求1 const homestart1 = (params)=>postAction("/materials/weighbridgeBill/countWeighbridgeBill",params); //数据字典 const addDict = (params)=>postAction("/sys/dict/add",params); const editDict = (params)=>putAction("/sys/dict/edit",params); const treeList = (params)=>getAction("/sys/dict/treeList",params); const addDictItem = (params)=>postAction("/sys/dictItem/add",params); const editDictItem = (params)=>putAction("/sys/dictItem/edit",params); //人员表查询 const getPersonList = (params)=>getAction("/person/person/list",params); //特种人员表查询 const getSpecialPersonList = (params)=>getAction("/deviceMaintain/deviceSpecialists/list",params); //设备类型管理 const getDevTypeTree = (params) => getAction("/deviceMaintain/maintainDeviceType/list",params); //查询 const deleteDevType = (params) => deleteAction("/deviceMaintain/maintainDeviceType/delete",params); //删除 //设备养护-设备管理 const queryById = (params) => getAction("/deviceMaintain/maintainDevice/queryById",params); //id查询设备 const queryList = (params) => getAction("/deviceMaintain/maintainDevice/list",params); //列表查询 const addDev = (params) => postAction("/deviceMaintain/maintainDevice/add",params); //添加 const ediDev = (params) => putAction("/deviceMaintain/maintainDevice/edit",params); //编辑 const deleteDev = (params) => deleteAction("/deviceMaintain/maintainDevice/delete",params); //删除 const deleteBatchDev = (params) => deleteAction("/deviceMaintain/maintainDevice/deleteBatch",params); //批量删除 const queryDeviceType = (params) => getAction("/deviceManage/deviceType/list",params); //查询 const queryNoPageDeviceType = (params) => getAction("/deviceManage/deviceType/noPageList",params); //无分页查询 const deviceTypeDelete = (params) => deleteAction("/deviceManage/deviceType/delete",params); //删除 //字典标签专用(通过code获取字典数组) export const ajaxGetDictItems = (code, params)=>{ if(code.indexOf('rel_tenant_ids')==-1){ code=code+',rel_tenant_ids='+store.state.user.newValue } return getAction(`/sys/dict/getDictItems/${code}`,params); } //从缓存中获取字典配置 function getDictItemsFromCache(dictCode) { if (Vue.ls.get(UI_CACHE_DB_DICT_DATA) && Vue.ls.get(UI_CACHE_DB_DICT_DATA)[dictCode]) { let dictItems = Vue.ls.get(UI_CACHE_DB_DICT_DATA)[dictCode]; console.log("-----------getDictItemsFromCache----------dictCode="+dictCode+"---- dictItems=",dictItems) return dictItems; } } //系统通告 const doReleaseData = (params)=>getAction("/sys/annountCement/doReleaseData",params); const doReovkeData = (params)=>getAction("/sys/annountCement/doReovkeData",params); //获取系统访问量 const getLoginfo = (params)=>getAction("/sys/loginfo",params); const getVisitInfo = (params)=>getAction("/sys/visitInfo",params); // 根据部门主键查询用户信息 const queryUserByDepId = (params)=>getAction("/sys/user/queryUserByDepId",params); // 重复校验 const duplicateCheck = (params)=>getAction("/sys/duplicate/check",Object.assign(params,{relTenantIds:store.state.user.info.relTenantIds})); // 加载分类字典 const loadCategoryData = (params)=>getAction("/sys/category/loadAllData",params); const checkRuleByCode = (params) => getAction('/sys/checkRule/checkByCode', params) //加载我的通告信息 const getUserNoticeInfo= (params)=>getAction("/sys/sysAnnouncementSend/getMyAnnouncementSend",params); const getTransitURL = url => `/sys/common/transitRESTful?url=${encodeURIComponent(url)}` // 中转HTTP请求 export const transitRESTful = { get: (url, parameter) => getAction(getTransitURL(url), parameter), post: (url, parameter) => postAction(getTransitURL(url), parameter), put: (url, parameter) => putAction(getTransitURL(url), parameter), http: (url, parameter) => httpAction(getTransitURL(url), parameter), } export { start, addRole, editRole, checkRoleCode, addUser, editUser, queryUserRole, getUserList, queryall, frozenBatch, checkOnlyUser, changePassword, getPermissionList, addPermission, editPermission, queryTreeList, queryListAsync, queryRolePermission, saveRolePermission, queryPermissionsByUser, loadAllRoleIds, getPermissionRuleList, queryPermissionRule, queryDepartTreeList, queryIdTree, queryParentName, searchByKeywords, deleteByDepartId, deleteLog, deleteLogList, addDict, editDict, treeList, addDictItem, editDictItem, doReleaseData, doReovkeData, getLoginfo, getVisitInfo, queryUserByDepId, duplicateCheck, queryTreeListForRole, getSystemMenuList, getSystemSubmenu, getSystemSubmenuBatch, loadCategoryData, checkRuleByCode, queryDepartPermission, saveDepartPermission, queryTreeListForDeptRole, queryDeptRolePermission, saveDeptRolePermission, queryMyDepartTreeList, getUserNoticeInfo, getDictItemsFromCache, homestart1, documenTreeList, documenByDepartId, documencertigier, documencertigierID, productionSearch, relationalrecord, bridgesort, contractor, contractordelete, danger, dangerdelete, personTreeList, getPersonList, getSpecialPersonList, getDevTypeTree, deleteDevType, queryById, queryList, addDev, ediDev, deleteDev, deleteBatchDev, queryDeviceType, queryNoPageDeviceType, deviceTypeDelete }
c3d0730a2d9dd27e212c1a462322d1dec92d8340
[ "JavaScript" ]
7
JavaScript
Dayong99/webgd-cloud
3e28d60bebfe59b3fd921c07526cc8c5f72a6f28
89dec560ee121d904a850df676b66fc530bba983
refs/heads/master
<repo_name>lukaszkania/Simple-blog.<file_sep>/frontend/gui/src/components/content/Content.js import React from 'react'; import { Link } from 'react-router-dom'; import { API_ARTICLE_DETAIL_URL } from '../../constants/ApiUrls'; import axios from 'axios'; const Content = ({ articles }) => { const articlesList = articles.length ? ( articles.map(article => { return ( <div className="article-container" key={article.id} > <div className="card text-center"> <div className="card-header"> Article </div> <div className="card-body"> <h5 className="card-title">{article.title}</h5> <p className="card-text">{article.text.slice(0, 200) + " ..."}</p> <Link to={'/' + 'article/' + article.pk} class="btn btn-primary">Read more...</Link> </div> <div className="card-footer text-muted"> {article.postedDate} </div> </div> </div> ) }) ) : ( <p>There aren't any articles</p> ) return ( <div className="articles" > {console.log(articlesList)} {articlesList} {console.log(axios.get('http://127.0.0.1:8000/api/1'))} </div> ); } export default Content; <file_sep>/backend/blog/article/api/urls.py from django.urls import path from .views import ArticleListView, ArticleDetailView app_name = 'api' urlpatterns = [ path('', ArticleListView.as_view(), name="list-view"), path('<int:pk>', ArticleDetailView.as_view(), name="detail-view"), ] <file_sep>/backend/blog/article/urls.py from django.contrib import admin from django.urls import path from article.views import ArticleListView, ArticleDetailView app_name = 'article' urlpatterns = [ path("", ArticleListView.as_view(), name="article_list_view"), path("<int:pk>", ArticleDetailView.as_view(), name="article_detail_view"), ] <file_sep>/backend/blog/article/views.py from django.shortcuts import render from django.views.generic import ListView, DetailView from .models import Article from django.utils import timezone # Create your views here. class ArticleListView(ListView): model = Article template_name = "article/ArticleListView.html" ordering = ['-postedDate'] context_object_name = 'articles' class ArticleDetailView(DetailView): model = Article template_name = "article/ArticleDetailView.html" <file_sep>/frontend/gui/src/App.js import React, { Component } from 'react'; import { BrowserRouter, Route, Switch } from 'react-router-dom'; import axios from 'axios'; import { API_ARTICLE_LIST_URL } from './constants/ApiUrls'; import Content from './components/content/Content'; import Navbar from "./components/navbar/Navbar"; import Footer from "./components/footer/Footer"; import DetailArticle from './components/detailArticle/DetailArticle'; class App extends Component { state = { articles: [], isLoading: true } componentDidMount = () => { this.setState({ isLoading: true }) axios.get(API_ARTICLE_LIST_URL).then(response => { this.setState({ articles: response.data, isLoading: false } ) }) } render() { return ( <BrowserRouter> <div className="App"> <Navbar /> <div className="container"> <Route exact path="/" render={(props) => <Content articles={this.state.articles} />} /> <Route path="/article/:slug/" component={DetailArticle} /> </div> <Footer /> </div> </BrowserRouter> ); } } export default App;<file_sep>/frontend/gui/src/components/detailArticle/DetailArticle.js import React, { Component } from 'react'; import axios from 'axios'; import { API_ARTICLE_DETAIL_URL } from '../../constants/ApiUrls'; import { Link } from "react-router-dom"; const loadArticleFromApi = (slug) => { let url = API_ARTICLE_DETAIL_URL + slug; return axios.get(url) } class DetailArticle extends Component { state = { isLoading: true, article: {} } loadSingleArticle = (slug) => { this.setState({ isLoading: true }) loadArticleFromApi(slug).then((response) => { this.setState({ isLoading: false, article: response.data[0] }) }) } componentDidMount = () => { let slug = this.props.match.params.slug; this.loadSingleArticle(slug) } render() { return ( <div className='article-detail'> <div className="card" style="width: 18rem;"> {/* <img src={"https://picsum.photos/" + '1' + "/237/200/300"} class="card-img-top" alt="Article image" /> */} <div className="card-body"> <h5 className="card-title">article.title</h5> <p className="card-text">article.text</p> <Link to="/" className="btn btn-primary">Back to Home page</Link> </div> </div> </div> ); } } export default DetailArticle;<file_sep>/frontend/gui/src/constants/ApiUrls.js export const API_ARTICLE_LIST_URL = "http://1172.16.31.10:8000/api" export const API_ARTICLE_DETAIL_URL = "http://127.0.0.1:8000/api/"<file_sep>/backend/blog/article/api/ArticleSerializers.py from rest_framework import serializers from article.models import Article class ArticleListSerializer(serializers.ModelSerializer): class Meta: model = Article fields = ('pk', 'title', 'text', 'postedDate') class ArticleDetailSerializer(serializers.ModelSerializer): class Meta: model = Article fields = ('pk', 'title', 'text', 'postedDate') <file_sep>/backend/blog/article/tests.py from django.test import TestCase from django.urls import reverse from .models import Article from django.utils import timezone # Create your tests here. # *****************************************************************************************ARTICLE************************************* class HomePageTests(TestCase): def test_home_page_status_code_by_adress(self): response = self.client.get('/') self.assertEquals(response.status_code, 200) def test_home_page_status_code_by_view_name(self): response = self.client.get(reverse('article:article_list_view')) self.assertEquals(response.status_code, 200) class DetailPageTests(TestCase): def setUp(self): self.article = Article.objects.create( title="Testing article title", text="Testing article text", postedDate=timezone.now() ) def test_detail_article_page_status_code_by_adress(self): response = self.client.get('/' + str(self.article.id)) self.assertEquals(response.status_code, 200) def test_detail_article_page_status_code_by_view_name(self): response = self.client.get( reverse('article:article_detail_view', kwargs={"pk": self.article.pk})) self.assertEquals(response.status_code, 200) # *****************************************************************************************API************************************* class ApiListPageTests(TestCase): def test_list_of_articles_api_page_status_code_by_adress(self): response = self.client.get('/api/') self.assertEquals(response.status_code, 200) def test_list_of_articles_api_page_status_code_by_viewname(self): response = self.client.get(reverse('api:list-view')) self.assertEquals(response.status_code, 200) class ApiDetailPageTests(TestCase): def setUp(self): self.article = Article.objects.create( title="Testing article title", text="Testing article text", postedDate=timezone.now() ) def test_details_of_article_api_page_status_code_by_adress(self): response = self.client.get("/api/" + str(self.article.pk)) self.assertEquals(response.status_code, 200) def test_details_of_article_api_page_status_code_by_view_name(self): response = self.client.get( reverse("api:detail-view", kwargs={"pk": self.article.pk})) self.assertEquals(response.status_code, 200) <file_sep>/backend/blog/article/api/views.py from rest_framework.generics import ListAPIView, RetrieveAPIView from article.models import Article from article.api.ArticleSerializers import ArticleListSerializer, ArticleDetailSerializer from django.utils import timezone class ArticleListView(ListAPIView): queryset = Article.objects.all().order_by('-postedDate', "-pk") serializer_class = ArticleListSerializer class ArticleDetailView(RetrieveAPIView): queryset = Article.objects.all() serializer_class = ArticleDetailSerializer
a06d6bfd0af921a2bbc58b40b2671c576a00206c
[ "JavaScript", "Python" ]
10
JavaScript
lukaszkania/Simple-blog.
d19b20668ec60688b460889ad0d11b7e498d747e
22435b217b4febebddf0155a5fef3c4760fa4e1b