text
stringlengths
8
6.88M
#include<bits/stdc++.h> using namespace std; const int M = 10050; int color[M], line[M][M]; //0为白,1为黑 bool bfs(int s, int n){ int i, beg; queue <int> q; q.push(s); color[s] = 1; while(!q.empty()){ beg = q.front(); q.pop(); for(i = 1; i <= n; i++){ if(line[beg][i] && color[i] == 0){ q.push(i); color[i] = !color[beg];//染成不同颜色 } if(line[beg][i] && color[beg] == color[i]){//颜色相同则不是二分图 return 0; } } } return 1; } int main(){ int i, j, n, m, a, b;//n表示有多少个点,m表示有多少条边 bool flag = 1;//初始化无向图是二分图 memset(color, 0, sizeof(color)); scanf("%d%d", &n, &m); for(i = 1; i <= m; i++) { cin >> a >> b; line[a][b] = line[b][a] = 1;//存储无向图的边 } for(i = 1; i <= n; i++) if(color[i] == 0 && !bfs(i, n)) {//对每个连通分支染色,如果两个相邻的点颜色相同,则不是二分图。 flag = 0; break; } if(flag) cout << "YES" <<endl; else cout << "NO" <<endl; return 0; }
//////////////////////////////////////////////////////////////////////////////// // // Copyright (c) 2006-2010 MStar Semiconductor, Inc. // All rights reserved. // // Unless otherwise stipulated in writing, any and all information contained // herein regardless in any format shall remain the sole proprietary of // MStar Semiconductor Inc. and be kept in strict confidence // (''MStar Confidential Information'') by the recipient. // Any unauthorized act including without limitation unauthorized disclosure, // copying, use, reproduction, sale, distribution, modification, disassembling, // reverse engineering and compiling of the contents of MStar Confidential // Information is unlawful and strictly prohibited. MStar hereby reserves the // rights to any and all damages, losses, costs and expenses resulting therefrom. // //////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////// // This file is automatically generated by SkinTool [Version:0.2.3][Build:Dec 28 2015 14:35:41] ///////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////// // MAINFRAME styles.. ///////////////////////////////////////////////////// // AUDLANG_BG_PANE styles.. ///////////////////////////////////////////////////// // AUDLANG_BG_C styles.. static DRAWSTYLE _MP_TBLSEG _Zui_Audlang_Bg_C_Normal_DrawStyle[] = { { CP_BITMAP, CP_ZUI_BITMAP_INDEX_90 }, { CP_NOON, 0 }, }; #define _Zui_Audlang_Bg_C_Focus_DrawStyle _Zui_Audlang_Bg_C_Normal_DrawStyle ///////////////////////////////////////////////////// // AUDLANG_BG_L styles.. static DRAWSTYLE _MP_TBLSEG _Zui_Audlang_Bg_L_Normal_DrawStyle[] = { { CP_BITMAP, CP_ZUI_BITMAP_INDEX_89 }, { CP_NOON, 0 }, }; #define _Zui_Audlang_Bg_L_Focus_DrawStyle _Zui_Audlang_Bg_L_Normal_DrawStyle ///////////////////////////////////////////////////// // AUDLANG_BG_R styles.. static DRAWSTYLE _MP_TBLSEG _Zui_Audlang_Bg_R_Normal_DrawStyle[] = { { CP_BITMAP, CP_ZUI_BITMAP_INDEX_91 }, { CP_NOON, 0 }, }; #define _Zui_Audlang_Bg_R_Focus_DrawStyle _Zui_Audlang_Bg_R_Normal_DrawStyle ///////////////////////////////////////////////////// // AUDLANG_BG_TITLE_TEXT styles.. static DRAWSTYLE _MP_TBLSEG _Zui_Audlang_Bg_Title_Text_Normal_DrawStyle[] = { { CP_TEXT_OUT, CP_ZUI_TEXT_OUT_INDEX_576 }, { CP_NOON, 0 }, }; #define _Zui_Audlang_Bg_Title_Text_Focus_DrawStyle _Zui_Audlang_Bg_Title_Text_Normal_DrawStyle ///////////////////////////////////////////////////// // AUDLANG_BG_OK_BTN styles.. static DRAWSTYLE _MP_TBLSEG _Zui_Audlang_Bg_Ok_Btn_Normal_DrawStyle[] = { { CP_BITMAP, CP_ZUI_BITMAP_INDEX_36 }, { CP_NOON, 0 }, }; #define _Zui_Audlang_Bg_Ok_Btn_Focus_DrawStyle _Zui_Audlang_Bg_Ok_Btn_Normal_DrawStyle ///////////////////////////////////////////////////// // AUDLANG_LIST_PANE styles.. ///////////////////////////////////////////////////// // AUDLANG_LIST_ITEM0 styles.. ///////////////////////////////////////////////////// // AUDLANG_ITEM0_FOCUS_BG styles.. static DRAWSTYLE _MP_TBLSEG _Zui_Audlang_Item0_Focus_Bg_Focus_DrawStyle[] = { { CP_BITMAP, CP_ZUI_BITMAP_INDEX_117 }, { CP_NOON, 0 }, }; ///////////////////////////////////////////////////// // AUDLANG_ITEM0_ARROW_ICON styles.. static DRAWSTYLE _MP_TBLSEG _Zui_Audlang_Item0_Arrow_Icon_Focus_DrawStyle[] = { { CP_BITMAP, CP_ZUI_BITMAP_INDEX_126 }, { CP_NOON, 0 }, }; ///////////////////////////////////////////////////// // AUDLANG_ITEM0_LANG_TEXT styles.. static DRAWSTYLE _MP_TBLSEG _Zui_Audlang_Item0_Lang_Text_Normal_DrawStyle[] = { { CP_TEXT_OUT, CP_ZUI_TEXT_OUT_INDEX_115 }, { CP_NOON, 0 }, }; static DRAWSTYLE _MP_TBLSEG _Zui_Audlang_Item0_Lang_Text_Focus_DrawStyle[] = { { CP_TEXT_OUT, CP_ZUI_TEXT_OUT_INDEX_577 }, { CP_NOON, 0 }, }; ///////////////////////////////////////////////////// // AUDLANG_ITEM0_AUDIO_TYPE_ICON styles.. static DRAWSTYLE _MP_TBLSEG _Zui_Audlang_Item0_Audio_Type_Icon_Normal_DrawStyle[] = { { CP_BITMAP, CP_ZUI_BITMAP_INDEX_149 }, { CP_NOON, 0 }, }; static DRAWSTYLE _MP_TBLSEG _Zui_Audlang_Item0_Audio_Type_Icon_Focus_DrawStyle[] = { { CP_BITMAP, CP_ZUI_BITMAP_INDEX_150 }, { CP_NOON, 0 }, }; ///////////////////////////////////////////////////// // AUDLANG_ITEM0_AUDIO_TYPE2_ICON styles.. static DRAWSTYLE _MP_TBLSEG _Zui_Audlang_Item0_Audio_Type2_Icon_Normal_DrawStyle[] = { { CP_BITMAP, CP_ZUI_BITMAP_INDEX_151 }, { CP_NOON, 0 }, }; static DRAWSTYLE _MP_TBLSEG _Zui_Audlang_Item0_Audio_Type2_Icon_Focus_DrawStyle[] = { { CP_BITMAP, CP_ZUI_BITMAP_INDEX_152 }, { CP_NOON, 0 }, }; ///////////////////////////////////////////////////// // AUDLANG_ITEM0_L_SOUND_ICON styles.. static DRAWSTYLE _MP_TBLSEG _Zui_Audlang_Item0_L_Sound_Icon_Normal_DrawStyle[] = { { CP_BITMAP, CP_ZUI_BITMAP_INDEX_153 }, { CP_NOON, 0 }, }; static DRAWSTYLE _MP_TBLSEG _Zui_Audlang_Item0_L_Sound_Icon_Focus_DrawStyle[] = { { CP_BITMAP, CP_ZUI_BITMAP_INDEX_154 }, { CP_NOON, 0 }, }; ///////////////////////////////////////////////////// // AUDLANG_ITEM0_R_SOUND_ICON styles.. static DRAWSTYLE _MP_TBLSEG _Zui_Audlang_Item0_R_Sound_Icon_Normal_DrawStyle[] = { { CP_BITMAP, CP_ZUI_BITMAP_INDEX_155 }, { CP_NOON, 0 }, }; static DRAWSTYLE _MP_TBLSEG _Zui_Audlang_Item0_R_Sound_Icon_Focus_DrawStyle[] = { { CP_BITMAP, CP_ZUI_BITMAP_INDEX_156 }, { CP_NOON, 0 }, }; ///////////////////////////////////////////////////// // AUDLANG_LIST_ITEM1 styles.. ///////////////////////////////////////////////////// // AUDLANG_ITEM1_FOCUS_BG styles.. #define _Zui_Audlang_Item1_Focus_Bg_Focus_DrawStyle _Zui_Audlang_Item0_Focus_Bg_Focus_DrawStyle ///////////////////////////////////////////////////// // AUDLANG_ITEM1_ARROW_ICON styles.. #define _Zui_Audlang_Item1_Arrow_Icon_Focus_DrawStyle _Zui_Audlang_Item0_Arrow_Icon_Focus_DrawStyle ///////////////////////////////////////////////////// // AUDLANG_ITEM1_LANG_TEXT styles.. #define _Zui_Audlang_Item1_Lang_Text_Normal_DrawStyle _Zui_Audlang_Item0_Lang_Text_Normal_DrawStyle #define _Zui_Audlang_Item1_Lang_Text_Focus_DrawStyle _Zui_Audlang_Item0_Lang_Text_Focus_DrawStyle ///////////////////////////////////////////////////// // AUDLANG_ITEM1_AUDIO_TYPE_ICON styles.. #define _Zui_Audlang_Item1_Audio_Type_Icon_Normal_DrawStyle _Zui_Audlang_Item0_Audio_Type_Icon_Normal_DrawStyle #define _Zui_Audlang_Item1_Audio_Type_Icon_Focus_DrawStyle _Zui_Audlang_Item0_Audio_Type_Icon_Focus_DrawStyle ///////////////////////////////////////////////////// // AUDLANG_ITEM1_AUDIO_TYPE2_ICON styles.. #define _Zui_Audlang_Item1_Audio_Type2_Icon_Normal_DrawStyle _Zui_Audlang_Item0_Audio_Type2_Icon_Normal_DrawStyle #define _Zui_Audlang_Item1_Audio_Type2_Icon_Focus_DrawStyle _Zui_Audlang_Item0_Audio_Type2_Icon_Focus_DrawStyle ///////////////////////////////////////////////////// // AUDLANG_ITEM1_L_SOUND_ICON styles.. #define _Zui_Audlang_Item1_L_Sound_Icon_Normal_DrawStyle _Zui_Audlang_Item0_L_Sound_Icon_Normal_DrawStyle #define _Zui_Audlang_Item1_L_Sound_Icon_Focus_DrawStyle _Zui_Audlang_Item0_L_Sound_Icon_Focus_DrawStyle ///////////////////////////////////////////////////// // AUDLANG_ITEM1_R_SOUND_ICON styles.. #define _Zui_Audlang_Item1_R_Sound_Icon_Normal_DrawStyle _Zui_Audlang_Item0_R_Sound_Icon_Normal_DrawStyle #define _Zui_Audlang_Item1_R_Sound_Icon_Focus_DrawStyle _Zui_Audlang_Item0_R_Sound_Icon_Focus_DrawStyle ///////////////////////////////////////////////////// // AUDLANG_LIST_ITEM2 styles.. ///////////////////////////////////////////////////// // AUDLANG_ITEM2_FOCUS_BG styles.. #define _Zui_Audlang_Item2_Focus_Bg_Focus_DrawStyle _Zui_Audlang_Item0_Focus_Bg_Focus_DrawStyle ///////////////////////////////////////////////////// // AUDLANG_ITEM2_ARROW_ICON styles.. #define _Zui_Audlang_Item2_Arrow_Icon_Focus_DrawStyle _Zui_Audlang_Item0_Arrow_Icon_Focus_DrawStyle ///////////////////////////////////////////////////// // AUDLANG_ITEM2_LANG_TEXT styles.. #define _Zui_Audlang_Item2_Lang_Text_Normal_DrawStyle _Zui_Audlang_Item0_Lang_Text_Normal_DrawStyle #define _Zui_Audlang_Item2_Lang_Text_Focus_DrawStyle _Zui_Audlang_Item0_Lang_Text_Focus_DrawStyle ///////////////////////////////////////////////////// // AUDLANG_ITEM2_AUDIO_TYPE_ICON styles.. #define _Zui_Audlang_Item2_Audio_Type_Icon_Normal_DrawStyle _Zui_Audlang_Item0_Audio_Type_Icon_Normal_DrawStyle #define _Zui_Audlang_Item2_Audio_Type_Icon_Focus_DrawStyle _Zui_Audlang_Item0_Audio_Type_Icon_Focus_DrawStyle ///////////////////////////////////////////////////// // AUDLANG_ITEM2_AUDIO_TYPE2_ICON styles.. #define _Zui_Audlang_Item2_Audio_Type2_Icon_Normal_DrawStyle _Zui_Audlang_Item0_Audio_Type2_Icon_Normal_DrawStyle #define _Zui_Audlang_Item2_Audio_Type2_Icon_Focus_DrawStyle _Zui_Audlang_Item0_Audio_Type2_Icon_Focus_DrawStyle ///////////////////////////////////////////////////// // AUDLANG_ITEM2_L_SOUND_ICON styles.. #define _Zui_Audlang_Item2_L_Sound_Icon_Normal_DrawStyle _Zui_Audlang_Item0_L_Sound_Icon_Normal_DrawStyle #define _Zui_Audlang_Item2_L_Sound_Icon_Focus_DrawStyle _Zui_Audlang_Item0_L_Sound_Icon_Focus_DrawStyle ///////////////////////////////////////////////////// // AUDLANG_ITEM2_R_SOUND_ICON styles.. #define _Zui_Audlang_Item2_R_Sound_Icon_Normal_DrawStyle _Zui_Audlang_Item0_R_Sound_Icon_Normal_DrawStyle #define _Zui_Audlang_Item2_R_Sound_Icon_Focus_DrawStyle _Zui_Audlang_Item0_R_Sound_Icon_Focus_DrawStyle ///////////////////////////////////////////////////// // AUDLANG_LIST_ITEM3 styles.. ///////////////////////////////////////////////////// // AUDLANG_ITEM3_FOCUS_BG styles.. #define _Zui_Audlang_Item3_Focus_Bg_Focus_DrawStyle _Zui_Audlang_Item0_Focus_Bg_Focus_DrawStyle ///////////////////////////////////////////////////// // AUDLANG_ITEM3_ARROW_ICON styles.. #define _Zui_Audlang_Item3_Arrow_Icon_Focus_DrawStyle _Zui_Audlang_Item0_Arrow_Icon_Focus_DrawStyle ///////////////////////////////////////////////////// // AUDLANG_ITEM3_LANG_TEXT styles.. #define _Zui_Audlang_Item3_Lang_Text_Normal_DrawStyle _Zui_Audlang_Item0_Lang_Text_Normal_DrawStyle #define _Zui_Audlang_Item3_Lang_Text_Focus_DrawStyle _Zui_Audlang_Item0_Lang_Text_Focus_DrawStyle ///////////////////////////////////////////////////// // AUDLANG_ITEM3_AUDIO_TYPE_ICON styles.. #define _Zui_Audlang_Item3_Audio_Type_Icon_Normal_DrawStyle _Zui_Audlang_Item0_Audio_Type_Icon_Normal_DrawStyle #define _Zui_Audlang_Item3_Audio_Type_Icon_Focus_DrawStyle _Zui_Audlang_Item0_Audio_Type_Icon_Focus_DrawStyle ///////////////////////////////////////////////////// // AUDLANG_ITEM3_AUDIO_TYPE2_ICON styles.. #define _Zui_Audlang_Item3_Audio_Type2_Icon_Normal_DrawStyle _Zui_Audlang_Item0_Audio_Type2_Icon_Normal_DrawStyle #define _Zui_Audlang_Item3_Audio_Type2_Icon_Focus_DrawStyle _Zui_Audlang_Item0_Audio_Type2_Icon_Focus_DrawStyle ///////////////////////////////////////////////////// // AUDLANG_ITEM3_L_SOUND_ICON styles.. #define _Zui_Audlang_Item3_L_Sound_Icon_Normal_DrawStyle _Zui_Audlang_Item0_L_Sound_Icon_Normal_DrawStyle #define _Zui_Audlang_Item3_L_Sound_Icon_Focus_DrawStyle _Zui_Audlang_Item0_L_Sound_Icon_Focus_DrawStyle ///////////////////////////////////////////////////// // AUDLANG_ITEM3_R_SOUND_ICON styles.. #define _Zui_Audlang_Item3_R_Sound_Icon_Normal_DrawStyle _Zui_Audlang_Item0_R_Sound_Icon_Normal_DrawStyle #define _Zui_Audlang_Item3_R_Sound_Icon_Focus_DrawStyle _Zui_Audlang_Item0_R_Sound_Icon_Focus_DrawStyle ///////////////////////////////////////////////////// // AUDLANG_LIST_ITEM4 styles.. ///////////////////////////////////////////////////// // AUDLANG_ITEM4_FOCUS_BG styles.. #define _Zui_Audlang_Item4_Focus_Bg_Focus_DrawStyle _Zui_Audlang_Item0_Focus_Bg_Focus_DrawStyle ///////////////////////////////////////////////////// // AUDLANG_ITEM4_ARROW_ICON styles.. #define _Zui_Audlang_Item4_Arrow_Icon_Focus_DrawStyle _Zui_Audlang_Item0_Arrow_Icon_Focus_DrawStyle ///////////////////////////////////////////////////// // AUDLANG_ITEM4_LANG_TEXT styles.. #define _Zui_Audlang_Item4_Lang_Text_Normal_DrawStyle _Zui_Audlang_Item0_Lang_Text_Normal_DrawStyle #define _Zui_Audlang_Item4_Lang_Text_Focus_DrawStyle _Zui_Audlang_Item0_Lang_Text_Focus_DrawStyle ///////////////////////////////////////////////////// // AUDLANG_ITEM4_AUDIO_TYPE_ICON styles.. #define _Zui_Audlang_Item4_Audio_Type_Icon_Normal_DrawStyle _Zui_Audlang_Item0_Audio_Type_Icon_Normal_DrawStyle #define _Zui_Audlang_Item4_Audio_Type_Icon_Focus_DrawStyle _Zui_Audlang_Item0_Audio_Type_Icon_Focus_DrawStyle ///////////////////////////////////////////////////// // AUDLANG_ITEM4_AUDIO_TYPE2_ICON styles.. #define _Zui_Audlang_Item4_Audio_Type2_Icon_Normal_DrawStyle _Zui_Audlang_Item0_Audio_Type2_Icon_Normal_DrawStyle #define _Zui_Audlang_Item4_Audio_Type2_Icon_Focus_DrawStyle _Zui_Audlang_Item0_Audio_Type2_Icon_Focus_DrawStyle ///////////////////////////////////////////////////// // AUDLANG_ITEM4_L_SOUND_ICON styles.. #define _Zui_Audlang_Item4_L_Sound_Icon_Normal_DrawStyle _Zui_Audlang_Item0_L_Sound_Icon_Normal_DrawStyle #define _Zui_Audlang_Item4_L_Sound_Icon_Focus_DrawStyle _Zui_Audlang_Item0_L_Sound_Icon_Focus_DrawStyle ///////////////////////////////////////////////////// // AUDLANG_ITEM4_R_SOUND_ICON styles.. #define _Zui_Audlang_Item4_R_Sound_Icon_Normal_DrawStyle _Zui_Audlang_Item0_R_Sound_Icon_Normal_DrawStyle #define _Zui_Audlang_Item4_R_Sound_Icon_Focus_DrawStyle _Zui_Audlang_Item0_R_Sound_Icon_Focus_DrawStyle ///////////////////////////////////////////////////// // AUDLANG_LIST_ITEM5 styles.. ///////////////////////////////////////////////////// // AUDLANG_ITEM5_FOCUS_BG styles.. #define _Zui_Audlang_Item5_Focus_Bg_Focus_DrawStyle _Zui_Audlang_Item0_Focus_Bg_Focus_DrawStyle ///////////////////////////////////////////////////// // AUDLANG_ITEM5_ARROW_ICON styles.. #define _Zui_Audlang_Item5_Arrow_Icon_Focus_DrawStyle _Zui_Audlang_Item0_Arrow_Icon_Focus_DrawStyle ///////////////////////////////////////////////////// // AUDLANG_ITEM5_LANG_TEXT styles.. #define _Zui_Audlang_Item5_Lang_Text_Normal_DrawStyle _Zui_Audlang_Item0_Lang_Text_Normal_DrawStyle #define _Zui_Audlang_Item5_Lang_Text_Focus_DrawStyle _Zui_Audlang_Item0_Lang_Text_Focus_DrawStyle ///////////////////////////////////////////////////// // AUDLANG_ITEM5_AUDIO_TYPE_ICON styles.. #define _Zui_Audlang_Item5_Audio_Type_Icon_Normal_DrawStyle _Zui_Audlang_Item0_Audio_Type_Icon_Normal_DrawStyle #define _Zui_Audlang_Item5_Audio_Type_Icon_Focus_DrawStyle _Zui_Audlang_Item0_Audio_Type_Icon_Focus_DrawStyle ///////////////////////////////////////////////////// // AUDLANG_ITEM5_AUDIO_TYPE2_ICON styles.. #define _Zui_Audlang_Item5_Audio_Type2_Icon_Normal_DrawStyle _Zui_Audlang_Item0_Audio_Type2_Icon_Normal_DrawStyle #define _Zui_Audlang_Item5_Audio_Type2_Icon_Focus_DrawStyle _Zui_Audlang_Item0_Audio_Type2_Icon_Focus_DrawStyle ///////////////////////////////////////////////////// // AUDLANG_ITEM5_L_SOUND_ICON styles.. #define _Zui_Audlang_Item5_L_Sound_Icon_Normal_DrawStyle _Zui_Audlang_Item0_L_Sound_Icon_Normal_DrawStyle #define _Zui_Audlang_Item5_L_Sound_Icon_Focus_DrawStyle _Zui_Audlang_Item0_L_Sound_Icon_Focus_DrawStyle ///////////////////////////////////////////////////// // AUDLANG_ITEM5_R_SOUND_ICON styles.. #define _Zui_Audlang_Item5_R_Sound_Icon_Normal_DrawStyle _Zui_Audlang_Item0_R_Sound_Icon_Normal_DrawStyle #define _Zui_Audlang_Item5_R_Sound_Icon_Focus_DrawStyle _Zui_Audlang_Item0_R_Sound_Icon_Focus_DrawStyle ///////////////////////////////////////////////////// // AUDLANG_LIST_ITEM6 styles.. ///////////////////////////////////////////////////// // AUDLANG_ITEM6_FOCUS_BG styles.. #define _Zui_Audlang_Item6_Focus_Bg_Focus_DrawStyle _Zui_Audlang_Item0_Focus_Bg_Focus_DrawStyle ///////////////////////////////////////////////////// // AUDLANG_ITEM6_ARROW_ICON styles.. #define _Zui_Audlang_Item6_Arrow_Icon_Focus_DrawStyle _Zui_Audlang_Item0_Arrow_Icon_Focus_DrawStyle ///////////////////////////////////////////////////// // AUDLANG_ITEM6_LANG_TEXT styles.. #define _Zui_Audlang_Item6_Lang_Text_Normal_DrawStyle _Zui_Audlang_Item0_Lang_Text_Normal_DrawStyle #define _Zui_Audlang_Item6_Lang_Text_Focus_DrawStyle _Zui_Audlang_Item0_Lang_Text_Focus_DrawStyle ///////////////////////////////////////////////////// // AUDLANG_ITEM6_AUDIO_TYPE_ICON styles.. #define _Zui_Audlang_Item6_Audio_Type_Icon_Normal_DrawStyle _Zui_Audlang_Item0_Audio_Type_Icon_Normal_DrawStyle #define _Zui_Audlang_Item6_Audio_Type_Icon_Focus_DrawStyle _Zui_Audlang_Item0_Audio_Type_Icon_Focus_DrawStyle ///////////////////////////////////////////////////// // AUDLANG_ITEM6_AUDIO_TYPE2_ICON styles.. #define _Zui_Audlang_Item6_Audio_Type2_Icon_Normal_DrawStyle _Zui_Audlang_Item0_Audio_Type2_Icon_Normal_DrawStyle #define _Zui_Audlang_Item6_Audio_Type2_Icon_Focus_DrawStyle _Zui_Audlang_Item0_Audio_Type2_Icon_Focus_DrawStyle ///////////////////////////////////////////////////// // AUDLANG_ITEM6_L_SOUND_ICON styles.. #define _Zui_Audlang_Item6_L_Sound_Icon_Normal_DrawStyle _Zui_Audlang_Item0_L_Sound_Icon_Normal_DrawStyle #define _Zui_Audlang_Item6_L_Sound_Icon_Focus_DrawStyle _Zui_Audlang_Item0_L_Sound_Icon_Focus_DrawStyle ///////////////////////////////////////////////////// // AUDLANG_ITEM6_R_SOUND_ICON styles.. #define _Zui_Audlang_Item6_R_Sound_Icon_Normal_DrawStyle _Zui_Audlang_Item0_R_Sound_Icon_Normal_DrawStyle #define _Zui_Audlang_Item6_R_Sound_Icon_Focus_DrawStyle _Zui_Audlang_Item0_R_Sound_Icon_Focus_DrawStyle ///////////////////////////////////////////////////// // AUDLANG_LIST_ITEM7 styles.. ///////////////////////////////////////////////////// // AUDLANG_ITEM7_FOCUS_BG styles.. #define _Zui_Audlang_Item7_Focus_Bg_Focus_DrawStyle _Zui_Audlang_Item0_Focus_Bg_Focus_DrawStyle ///////////////////////////////////////////////////// // AUDLANG_ITEM7_ARROW_ICON styles.. #define _Zui_Audlang_Item7_Arrow_Icon_Focus_DrawStyle _Zui_Audlang_Item0_Arrow_Icon_Focus_DrawStyle ///////////////////////////////////////////////////// // AUDLANG_ITEM7_LANG_TEXT styles.. #define _Zui_Audlang_Item7_Lang_Text_Normal_DrawStyle _Zui_Audlang_Item0_Lang_Text_Normal_DrawStyle #define _Zui_Audlang_Item7_Lang_Text_Focus_DrawStyle _Zui_Audlang_Item0_Lang_Text_Focus_DrawStyle ///////////////////////////////////////////////////// // AUDLANG_ITEM7_AUDIO_TYPE_ICON styles.. #define _Zui_Audlang_Item7_Audio_Type_Icon_Normal_DrawStyle _Zui_Audlang_Item0_Audio_Type_Icon_Normal_DrawStyle #define _Zui_Audlang_Item7_Audio_Type_Icon_Focus_DrawStyle _Zui_Audlang_Item0_Audio_Type_Icon_Focus_DrawStyle ///////////////////////////////////////////////////// // AUDLANG_ITEM7_AUDIO_TYPE2_ICON styles.. #define _Zui_Audlang_Item7_Audio_Type2_Icon_Normal_DrawStyle _Zui_Audlang_Item0_Audio_Type2_Icon_Normal_DrawStyle #define _Zui_Audlang_Item7_Audio_Type2_Icon_Focus_DrawStyle _Zui_Audlang_Item0_Audio_Type2_Icon_Focus_DrawStyle ///////////////////////////////////////////////////// // AUDLANG_ITEM7_L_SOUND_ICON styles.. #define _Zui_Audlang_Item7_L_Sound_Icon_Normal_DrawStyle _Zui_Audlang_Item0_L_Sound_Icon_Normal_DrawStyle #define _Zui_Audlang_Item7_L_Sound_Icon_Focus_DrawStyle _Zui_Audlang_Item0_L_Sound_Icon_Focus_DrawStyle ///////////////////////////////////////////////////// // AUDLANG_ITEM7_R_SOUND_ICON styles.. #define _Zui_Audlang_Item7_R_Sound_Icon_Normal_DrawStyle _Zui_Audlang_Item0_R_Sound_Icon_Normal_DrawStyle #define _Zui_Audlang_Item7_R_Sound_Icon_Focus_DrawStyle _Zui_Audlang_Item0_R_Sound_Icon_Focus_DrawStyle ///////////////////////////////////////////////////// // AUDLANG_LIST_ITEM8 styles.. ///////////////////////////////////////////////////// // AUDLANG_ITEM8_FOCUS_BG styles.. #define _Zui_Audlang_Item8_Focus_Bg_Focus_DrawStyle _Zui_Audlang_Item0_Focus_Bg_Focus_DrawStyle ///////////////////////////////////////////////////// // AUDLANG_ITEM8_ARROW_ICON styles.. #define _Zui_Audlang_Item8_Arrow_Icon_Focus_DrawStyle _Zui_Audlang_Item0_Arrow_Icon_Focus_DrawStyle ///////////////////////////////////////////////////// // AUDLANG_ITEM8_LANG_TEXT styles.. #define _Zui_Audlang_Item8_Lang_Text_Normal_DrawStyle _Zui_Audlang_Item0_Lang_Text_Normal_DrawStyle #define _Zui_Audlang_Item8_Lang_Text_Focus_DrawStyle _Zui_Audlang_Item0_Lang_Text_Focus_DrawStyle ///////////////////////////////////////////////////// // AUDLANG_ITEM8_AUDIO_TYPE_ICON styles.. #define _Zui_Audlang_Item8_Audio_Type_Icon_Normal_DrawStyle _Zui_Audlang_Item0_Audio_Type_Icon_Normal_DrawStyle #define _Zui_Audlang_Item8_Audio_Type_Icon_Focus_DrawStyle _Zui_Audlang_Item0_Audio_Type_Icon_Focus_DrawStyle ///////////////////////////////////////////////////// // AUDLANG_ITEM8_AUDIO_TYPE2_ICON styles.. #define _Zui_Audlang_Item8_Audio_Type2_Icon_Normal_DrawStyle _Zui_Audlang_Item0_Audio_Type2_Icon_Normal_DrawStyle #define _Zui_Audlang_Item8_Audio_Type2_Icon_Focus_DrawStyle _Zui_Audlang_Item0_Audio_Type2_Icon_Focus_DrawStyle ///////////////////////////////////////////////////// // AUDLANG_ITEM8_L_SOUND_ICON styles.. #define _Zui_Audlang_Item8_L_Sound_Icon_Normal_DrawStyle _Zui_Audlang_Item0_L_Sound_Icon_Normal_DrawStyle #define _Zui_Audlang_Item8_L_Sound_Icon_Focus_DrawStyle _Zui_Audlang_Item0_L_Sound_Icon_Focus_DrawStyle ///////////////////////////////////////////////////// // AUDLANG_ITEM8_R_SOUND_ICON styles.. #define _Zui_Audlang_Item8_R_Sound_Icon_Normal_DrawStyle _Zui_Audlang_Item0_R_Sound_Icon_Normal_DrawStyle #define _Zui_Audlang_Item8_R_Sound_Icon_Focus_DrawStyle _Zui_Audlang_Item0_R_Sound_Icon_Focus_DrawStyle ///////////////////////////////////////////////////// // AUDLANG_LIST_ITEM9 styles.. ///////////////////////////////////////////////////// // AUDLANG_ITEM9_FOCUS_BG styles.. #define _Zui_Audlang_Item9_Focus_Bg_Focus_DrawStyle _Zui_Audlang_Item0_Focus_Bg_Focus_DrawStyle ///////////////////////////////////////////////////// // AUDLANG_ITEM9_ARROW_ICON styles.. #define _Zui_Audlang_Item9_Arrow_Icon_Focus_DrawStyle _Zui_Audlang_Item0_Arrow_Icon_Focus_DrawStyle ///////////////////////////////////////////////////// // AUDLANG_ITEM9_LANG_TEXT styles.. #define _Zui_Audlang_Item9_Lang_Text_Normal_DrawStyle _Zui_Audlang_Item0_Lang_Text_Normal_DrawStyle #define _Zui_Audlang_Item9_Lang_Text_Focus_DrawStyle _Zui_Audlang_Item0_Lang_Text_Focus_DrawStyle ///////////////////////////////////////////////////// // AUDLANG_ITEM9_AUDIO_TYPE_ICON styles.. #define _Zui_Audlang_Item9_Audio_Type_Icon_Normal_DrawStyle _Zui_Audlang_Item0_Audio_Type_Icon_Normal_DrawStyle #define _Zui_Audlang_Item9_Audio_Type_Icon_Focus_DrawStyle _Zui_Audlang_Item0_Audio_Type_Icon_Focus_DrawStyle ///////////////////////////////////////////////////// // AUDLANG_ITEM9_AUDIO_TYPE2_ICON styles.. #define _Zui_Audlang_Item9_Audio_Type2_Icon_Normal_DrawStyle _Zui_Audlang_Item0_Audio_Type2_Icon_Normal_DrawStyle #define _Zui_Audlang_Item9_Audio_Type2_Icon_Focus_DrawStyle _Zui_Audlang_Item0_Audio_Type2_Icon_Focus_DrawStyle ///////////////////////////////////////////////////// // AUDLANG_ITEM9_L_SOUND_ICON styles.. #define _Zui_Audlang_Item9_L_Sound_Icon_Normal_DrawStyle _Zui_Audlang_Item0_L_Sound_Icon_Normal_DrawStyle #define _Zui_Audlang_Item9_L_Sound_Icon_Focus_DrawStyle _Zui_Audlang_Item0_L_Sound_Icon_Focus_DrawStyle ///////////////////////////////////////////////////// // AUDLANG_ITEM9_R_SOUND_ICON styles.. #define _Zui_Audlang_Item9_R_Sound_Icon_Normal_DrawStyle _Zui_Audlang_Item0_R_Sound_Icon_Normal_DrawStyle #define _Zui_Audlang_Item9_R_Sound_Icon_Focus_DrawStyle _Zui_Audlang_Item0_R_Sound_Icon_Focus_DrawStyle ////////////////////////////////////////////////////// // Window Draw Style List (normal, focused, disable) WINDOWDRAWSTYLEDATA _MP_TBLSEG _GUI_WindowsDrawStyleList_Zui_Audio_Language[] = { // HWND_MAINFRAME { NULL, NULL, NULL }, // HWND_AUDLANG_BG_PANE { NULL, NULL, NULL }, // HWND_AUDLANG_BG_C { _Zui_Audlang_Bg_C_Normal_DrawStyle, _Zui_Audlang_Bg_C_Focus_DrawStyle, NULL }, // HWND_AUDLANG_BG_L { _Zui_Audlang_Bg_L_Normal_DrawStyle, _Zui_Audlang_Bg_L_Focus_DrawStyle, NULL }, // HWND_AUDLANG_BG_R { _Zui_Audlang_Bg_R_Normal_DrawStyle, _Zui_Audlang_Bg_R_Focus_DrawStyle, NULL }, // HWND_AUDLANG_BG_TITLE_TEXT { _Zui_Audlang_Bg_Title_Text_Normal_DrawStyle, _Zui_Audlang_Bg_Title_Text_Focus_DrawStyle, NULL }, // HWND_AUDLANG_BG_OK_BTN { _Zui_Audlang_Bg_Ok_Btn_Normal_DrawStyle, _Zui_Audlang_Bg_Ok_Btn_Focus_DrawStyle, NULL }, // HWND_AUDLANG_LIST_PANE { NULL, NULL, NULL }, // HWND_AUDLANG_LIST_ITEM0 { NULL, NULL, NULL }, // HWND_AUDLANG_ITEM0_FOCUS_BG { NULL, _Zui_Audlang_Item0_Focus_Bg_Focus_DrawStyle, NULL }, // HWND_AUDLANG_ITEM0_ARROW_ICON { NULL, _Zui_Audlang_Item0_Arrow_Icon_Focus_DrawStyle, NULL }, // HWND_AUDLANG_ITEM0_LANG_TEXT { _Zui_Audlang_Item0_Lang_Text_Normal_DrawStyle, _Zui_Audlang_Item0_Lang_Text_Focus_DrawStyle, NULL }, // HWND_AUDLANG_ITEM0_AUDIO_TYPE_ICON { _Zui_Audlang_Item0_Audio_Type_Icon_Normal_DrawStyle, _Zui_Audlang_Item0_Audio_Type_Icon_Focus_DrawStyle, NULL }, // HWND_AUDLANG_ITEM0_AUDIO_TYPE2_ICON { _Zui_Audlang_Item0_Audio_Type2_Icon_Normal_DrawStyle, _Zui_Audlang_Item0_Audio_Type2_Icon_Focus_DrawStyle, NULL }, // HWND_AUDLANG_ITEM0_L_SOUND_ICON { _Zui_Audlang_Item0_L_Sound_Icon_Normal_DrawStyle, _Zui_Audlang_Item0_L_Sound_Icon_Focus_DrawStyle, NULL }, // HWND_AUDLANG_ITEM0_R_SOUND_ICON { _Zui_Audlang_Item0_R_Sound_Icon_Normal_DrawStyle, _Zui_Audlang_Item0_R_Sound_Icon_Focus_DrawStyle, NULL }, // HWND_AUDLANG_LIST_ITEM1 { NULL, NULL, NULL }, // HWND_AUDLANG_ITEM1_FOCUS_BG { NULL, _Zui_Audlang_Item1_Focus_Bg_Focus_DrawStyle, NULL }, // HWND_AUDLANG_ITEM1_ARROW_ICON { NULL, _Zui_Audlang_Item1_Arrow_Icon_Focus_DrawStyle, NULL }, // HWND_AUDLANG_ITEM1_LANG_TEXT { _Zui_Audlang_Item1_Lang_Text_Normal_DrawStyle, _Zui_Audlang_Item1_Lang_Text_Focus_DrawStyle, NULL }, // HWND_AUDLANG_ITEM1_AUDIO_TYPE_ICON { _Zui_Audlang_Item1_Audio_Type_Icon_Normal_DrawStyle, _Zui_Audlang_Item1_Audio_Type_Icon_Focus_DrawStyle, NULL }, // HWND_AUDLANG_ITEM1_AUDIO_TYPE2_ICON { _Zui_Audlang_Item1_Audio_Type2_Icon_Normal_DrawStyle, _Zui_Audlang_Item1_Audio_Type2_Icon_Focus_DrawStyle, NULL }, // HWND_AUDLANG_ITEM1_L_SOUND_ICON { _Zui_Audlang_Item1_L_Sound_Icon_Normal_DrawStyle, _Zui_Audlang_Item1_L_Sound_Icon_Focus_DrawStyle, NULL }, // HWND_AUDLANG_ITEM1_R_SOUND_ICON { _Zui_Audlang_Item1_R_Sound_Icon_Normal_DrawStyle, _Zui_Audlang_Item1_R_Sound_Icon_Focus_DrawStyle, NULL }, // HWND_AUDLANG_LIST_ITEM2 { NULL, NULL, NULL }, // HWND_AUDLANG_ITEM2_FOCUS_BG { NULL, _Zui_Audlang_Item2_Focus_Bg_Focus_DrawStyle, NULL }, // HWND_AUDLANG_ITEM2_ARROW_ICON { NULL, _Zui_Audlang_Item2_Arrow_Icon_Focus_DrawStyle, NULL }, // HWND_AUDLANG_ITEM2_LANG_TEXT { _Zui_Audlang_Item2_Lang_Text_Normal_DrawStyle, _Zui_Audlang_Item2_Lang_Text_Focus_DrawStyle, NULL }, // HWND_AUDLANG_ITEM2_AUDIO_TYPE_ICON { _Zui_Audlang_Item2_Audio_Type_Icon_Normal_DrawStyle, _Zui_Audlang_Item2_Audio_Type_Icon_Focus_DrawStyle, NULL }, // HWND_AUDLANG_ITEM2_AUDIO_TYPE2_ICON { _Zui_Audlang_Item2_Audio_Type2_Icon_Normal_DrawStyle, _Zui_Audlang_Item2_Audio_Type2_Icon_Focus_DrawStyle, NULL }, // HWND_AUDLANG_ITEM2_L_SOUND_ICON { _Zui_Audlang_Item2_L_Sound_Icon_Normal_DrawStyle, _Zui_Audlang_Item2_L_Sound_Icon_Focus_DrawStyle, NULL }, // HWND_AUDLANG_ITEM2_R_SOUND_ICON { _Zui_Audlang_Item2_R_Sound_Icon_Normal_DrawStyle, _Zui_Audlang_Item2_R_Sound_Icon_Focus_DrawStyle, NULL }, // HWND_AUDLANG_LIST_ITEM3 { NULL, NULL, NULL }, // HWND_AUDLANG_ITEM3_FOCUS_BG { NULL, _Zui_Audlang_Item3_Focus_Bg_Focus_DrawStyle, NULL }, // HWND_AUDLANG_ITEM3_ARROW_ICON { NULL, _Zui_Audlang_Item3_Arrow_Icon_Focus_DrawStyle, NULL }, // HWND_AUDLANG_ITEM3_LANG_TEXT { _Zui_Audlang_Item3_Lang_Text_Normal_DrawStyle, _Zui_Audlang_Item3_Lang_Text_Focus_DrawStyle, NULL }, // HWND_AUDLANG_ITEM3_AUDIO_TYPE_ICON { _Zui_Audlang_Item3_Audio_Type_Icon_Normal_DrawStyle, _Zui_Audlang_Item3_Audio_Type_Icon_Focus_DrawStyle, NULL }, // HWND_AUDLANG_ITEM3_AUDIO_TYPE2_ICON { _Zui_Audlang_Item3_Audio_Type2_Icon_Normal_DrawStyle, _Zui_Audlang_Item3_Audio_Type2_Icon_Focus_DrawStyle, NULL }, // HWND_AUDLANG_ITEM3_L_SOUND_ICON { _Zui_Audlang_Item3_L_Sound_Icon_Normal_DrawStyle, _Zui_Audlang_Item3_L_Sound_Icon_Focus_DrawStyle, NULL }, // HWND_AUDLANG_ITEM3_R_SOUND_ICON { _Zui_Audlang_Item3_R_Sound_Icon_Normal_DrawStyle, _Zui_Audlang_Item3_R_Sound_Icon_Focus_DrawStyle, NULL }, // HWND_AUDLANG_LIST_ITEM4 { NULL, NULL, NULL }, // HWND_AUDLANG_ITEM4_FOCUS_BG { NULL, _Zui_Audlang_Item4_Focus_Bg_Focus_DrawStyle, NULL }, // HWND_AUDLANG_ITEM4_ARROW_ICON { NULL, _Zui_Audlang_Item4_Arrow_Icon_Focus_DrawStyle, NULL }, // HWND_AUDLANG_ITEM4_LANG_TEXT { _Zui_Audlang_Item4_Lang_Text_Normal_DrawStyle, _Zui_Audlang_Item4_Lang_Text_Focus_DrawStyle, NULL }, // HWND_AUDLANG_ITEM4_AUDIO_TYPE_ICON { _Zui_Audlang_Item4_Audio_Type_Icon_Normal_DrawStyle, _Zui_Audlang_Item4_Audio_Type_Icon_Focus_DrawStyle, NULL }, // HWND_AUDLANG_ITEM4_AUDIO_TYPE2_ICON { _Zui_Audlang_Item4_Audio_Type2_Icon_Normal_DrawStyle, _Zui_Audlang_Item4_Audio_Type2_Icon_Focus_DrawStyle, NULL }, // HWND_AUDLANG_ITEM4_L_SOUND_ICON { _Zui_Audlang_Item4_L_Sound_Icon_Normal_DrawStyle, _Zui_Audlang_Item4_L_Sound_Icon_Focus_DrawStyle, NULL }, // HWND_AUDLANG_ITEM4_R_SOUND_ICON { _Zui_Audlang_Item4_R_Sound_Icon_Normal_DrawStyle, _Zui_Audlang_Item4_R_Sound_Icon_Focus_DrawStyle, NULL }, // HWND_AUDLANG_LIST_ITEM5 { NULL, NULL, NULL }, // HWND_AUDLANG_ITEM5_FOCUS_BG { NULL, _Zui_Audlang_Item5_Focus_Bg_Focus_DrawStyle, NULL }, // HWND_AUDLANG_ITEM5_ARROW_ICON { NULL, _Zui_Audlang_Item5_Arrow_Icon_Focus_DrawStyle, NULL }, // HWND_AUDLANG_ITEM5_LANG_TEXT { _Zui_Audlang_Item5_Lang_Text_Normal_DrawStyle, _Zui_Audlang_Item5_Lang_Text_Focus_DrawStyle, NULL }, // HWND_AUDLANG_ITEM5_AUDIO_TYPE_ICON { _Zui_Audlang_Item5_Audio_Type_Icon_Normal_DrawStyle, _Zui_Audlang_Item5_Audio_Type_Icon_Focus_DrawStyle, NULL }, // HWND_AUDLANG_ITEM5_AUDIO_TYPE2_ICON { _Zui_Audlang_Item5_Audio_Type2_Icon_Normal_DrawStyle, _Zui_Audlang_Item5_Audio_Type2_Icon_Focus_DrawStyle, NULL }, // HWND_AUDLANG_ITEM5_L_SOUND_ICON { _Zui_Audlang_Item5_L_Sound_Icon_Normal_DrawStyle, _Zui_Audlang_Item5_L_Sound_Icon_Focus_DrawStyle, NULL }, // HWND_AUDLANG_ITEM5_R_SOUND_ICON { _Zui_Audlang_Item5_R_Sound_Icon_Normal_DrawStyle, _Zui_Audlang_Item5_R_Sound_Icon_Focus_DrawStyle, NULL }, // HWND_AUDLANG_LIST_ITEM6 { NULL, NULL, NULL }, // HWND_AUDLANG_ITEM6_FOCUS_BG { NULL, _Zui_Audlang_Item6_Focus_Bg_Focus_DrawStyle, NULL }, // HWND_AUDLANG_ITEM6_ARROW_ICON { NULL, _Zui_Audlang_Item6_Arrow_Icon_Focus_DrawStyle, NULL }, // HWND_AUDLANG_ITEM6_LANG_TEXT { _Zui_Audlang_Item6_Lang_Text_Normal_DrawStyle, _Zui_Audlang_Item6_Lang_Text_Focus_DrawStyle, NULL }, // HWND_AUDLANG_ITEM6_AUDIO_TYPE_ICON { _Zui_Audlang_Item6_Audio_Type_Icon_Normal_DrawStyle, _Zui_Audlang_Item6_Audio_Type_Icon_Focus_DrawStyle, NULL }, // HWND_AUDLANG_ITEM6_AUDIO_TYPE2_ICON { _Zui_Audlang_Item6_Audio_Type2_Icon_Normal_DrawStyle, _Zui_Audlang_Item6_Audio_Type2_Icon_Focus_DrawStyle, NULL }, // HWND_AUDLANG_ITEM6_L_SOUND_ICON { _Zui_Audlang_Item6_L_Sound_Icon_Normal_DrawStyle, _Zui_Audlang_Item6_L_Sound_Icon_Focus_DrawStyle, NULL }, // HWND_AUDLANG_ITEM6_R_SOUND_ICON { _Zui_Audlang_Item6_R_Sound_Icon_Normal_DrawStyle, _Zui_Audlang_Item6_R_Sound_Icon_Focus_DrawStyle, NULL }, // HWND_AUDLANG_LIST_ITEM7 { NULL, NULL, NULL }, // HWND_AUDLANG_ITEM7_FOCUS_BG { NULL, _Zui_Audlang_Item7_Focus_Bg_Focus_DrawStyle, NULL }, // HWND_AUDLANG_ITEM7_ARROW_ICON { NULL, _Zui_Audlang_Item7_Arrow_Icon_Focus_DrawStyle, NULL }, // HWND_AUDLANG_ITEM7_LANG_TEXT { _Zui_Audlang_Item7_Lang_Text_Normal_DrawStyle, _Zui_Audlang_Item7_Lang_Text_Focus_DrawStyle, NULL }, // HWND_AUDLANG_ITEM7_AUDIO_TYPE_ICON { _Zui_Audlang_Item7_Audio_Type_Icon_Normal_DrawStyle, _Zui_Audlang_Item7_Audio_Type_Icon_Focus_DrawStyle, NULL }, // HWND_AUDLANG_ITEM7_AUDIO_TYPE2_ICON { _Zui_Audlang_Item7_Audio_Type2_Icon_Normal_DrawStyle, _Zui_Audlang_Item7_Audio_Type2_Icon_Focus_DrawStyle, NULL }, // HWND_AUDLANG_ITEM7_L_SOUND_ICON { _Zui_Audlang_Item7_L_Sound_Icon_Normal_DrawStyle, _Zui_Audlang_Item7_L_Sound_Icon_Focus_DrawStyle, NULL }, // HWND_AUDLANG_ITEM7_R_SOUND_ICON { _Zui_Audlang_Item7_R_Sound_Icon_Normal_DrawStyle, _Zui_Audlang_Item7_R_Sound_Icon_Focus_DrawStyle, NULL }, // HWND_AUDLANG_LIST_ITEM8 { NULL, NULL, NULL }, // HWND_AUDLANG_ITEM8_FOCUS_BG { NULL, _Zui_Audlang_Item8_Focus_Bg_Focus_DrawStyle, NULL }, // HWND_AUDLANG_ITEM8_ARROW_ICON { NULL, _Zui_Audlang_Item8_Arrow_Icon_Focus_DrawStyle, NULL }, // HWND_AUDLANG_ITEM8_LANG_TEXT { _Zui_Audlang_Item8_Lang_Text_Normal_DrawStyle, _Zui_Audlang_Item8_Lang_Text_Focus_DrawStyle, NULL }, // HWND_AUDLANG_ITEM8_AUDIO_TYPE_ICON { _Zui_Audlang_Item8_Audio_Type_Icon_Normal_DrawStyle, _Zui_Audlang_Item8_Audio_Type_Icon_Focus_DrawStyle, NULL }, // HWND_AUDLANG_ITEM8_AUDIO_TYPE2_ICON { _Zui_Audlang_Item8_Audio_Type2_Icon_Normal_DrawStyle, _Zui_Audlang_Item8_Audio_Type2_Icon_Focus_DrawStyle, NULL }, // HWND_AUDLANG_ITEM8_L_SOUND_ICON { _Zui_Audlang_Item8_L_Sound_Icon_Normal_DrawStyle, _Zui_Audlang_Item8_L_Sound_Icon_Focus_DrawStyle, NULL }, // HWND_AUDLANG_ITEM8_R_SOUND_ICON { _Zui_Audlang_Item8_R_Sound_Icon_Normal_DrawStyle, _Zui_Audlang_Item8_R_Sound_Icon_Focus_DrawStyle, NULL }, // HWND_AUDLANG_LIST_ITEM9 { NULL, NULL, NULL }, // HWND_AUDLANG_ITEM9_FOCUS_BG { NULL, _Zui_Audlang_Item9_Focus_Bg_Focus_DrawStyle, NULL }, // HWND_AUDLANG_ITEM9_ARROW_ICON { NULL, _Zui_Audlang_Item9_Arrow_Icon_Focus_DrawStyle, NULL }, // HWND_AUDLANG_ITEM9_LANG_TEXT { _Zui_Audlang_Item9_Lang_Text_Normal_DrawStyle, _Zui_Audlang_Item9_Lang_Text_Focus_DrawStyle, NULL }, // HWND_AUDLANG_ITEM9_AUDIO_TYPE_ICON { _Zui_Audlang_Item9_Audio_Type_Icon_Normal_DrawStyle, _Zui_Audlang_Item9_Audio_Type_Icon_Focus_DrawStyle, NULL }, // HWND_AUDLANG_ITEM9_AUDIO_TYPE2_ICON { _Zui_Audlang_Item9_Audio_Type2_Icon_Normal_DrawStyle, _Zui_Audlang_Item9_Audio_Type2_Icon_Focus_DrawStyle, NULL }, // HWND_AUDLANG_ITEM9_L_SOUND_ICON { _Zui_Audlang_Item9_L_Sound_Icon_Normal_DrawStyle, _Zui_Audlang_Item9_L_Sound_Icon_Focus_DrawStyle, NULL }, // HWND_AUDLANG_ITEM9_R_SOUND_ICON { _Zui_Audlang_Item9_R_Sound_Icon_Normal_DrawStyle, _Zui_Audlang_Item9_R_Sound_Icon_Focus_DrawStyle, NULL }, };
// Copyright (C) 2019 Greg Dionne // Distributed under MIT License #include "crtable.hpp" std::string Reference::to_string(void) { return expression.to_string(); } bool CRTable::addlabel(const char *modulename, const char *labelname, int location, char *filename, int linenum) { Label lbl(modulename, labelname, filename, linenum); lbl.expression = Expression(location); return addlabel(lbl); } bool CRTable::addlabel(Label lbl) { for (std::size_t i=0; i<labels.size(); ++i) if (labels[i].name == lbl.name) { fprintf(stderr,"%s:%i: error: redefinition of label \"%s\"\n", lbl.fileName, lbl.lineNumber, lbl.name.c_str()); fprintf(stderr,"%s:%i: previous definition of label \"%s\"\n", labels[i].fileName, labels[i].lineNumber, lbl.name.c_str()); return false; } labels.push_back(lbl); return true; } bool CRTable::addmodule(const char *modulename, char *filename, int linenum) { Module m(modulename, filename, linenum); for (std::size_t i=0; i<modules.size(); ++i) if (modules[i].name == m.name) { fprintf(stderr,"%s:%i: error: redefinition of module \"%s\"\n", m.fileName, m.lineNumber, m.name.c_str()); fprintf(stderr,"%s:%i: previous definition of module \"%s\"\n", modules[i].fileName, modules[i].lineNumber, m.name.c_str()); return false; } modules.push_back(m); return true; } void CRTable::reportUnusedReferences(void) { for (std::size_t i=0; i<labels.size(); ++i) if (!labels[i].used) fprintf(stderr,"%s:%i: warning: unused label \'%s\' [-Wunused]\n", labels[i].fileName,labels[i].lineNumber,labels[i].name.c_str()); } void CRTable::addreference(Reference r) { references.push_back(r); } bool CRTable::resolve(Reference& r, int& result, std::string& offender) { return r.expression.evaluate(labels, offender, result); } int CRTable::immediatelyResolve(int reftype, Fetcher& fetcher, const char *modulename, int pc, const char *dir, char *filename, int linenum) { Reference r(pc, reftype, filename, linenum); r.expression.parse(fetcher, modulename, pc); int result; std::string offender; if (!resolve(r, result, offender)) fetcher.die("label \"%s\" must be immediately resolveable when using \"%s\" or its equivalent pseudo-operation", offender.c_str(),dir); return result; } int CRTable::tentativelyResolve(int reftype, Fetcher& fetcher, const char *modulename, int pc, char *filename, int linenum, bool wBranch) { Reference r(pc, reftype, filename, linenum); r.expression.parse(fetcher, modulename, pc); int w = tentativelyResolve(r, fetcher, wBranch); return w; } int CRTable::tentativelyResolve(Reference& r, Fetcher& fetcher, bool wBranch) { int result; std::string offender; if (resolve(r, result, offender)) { if (r.reftype == 0) { result -= r.location + 2; if (result < -128 || result > 127) { fetcher.die("branch destination $%04X out of reach from $%04X",result+r.location+2,r.location); } } if (wBranch && r.reftype > 2) { int relAddr = result - (r.location + 2); if (-128 <= relAddr && relAddr <= 127) { fprintf(stderr,"%s:%i: warning: ",r.filename,r.lineNumber); fprintf(stderr,"%s instruction at $%04X to reference \"%s\" can be replaced by %s [-Wbranch].\n", r.reftype == 3 ? "JMP" : "JSR", r.location, r.to_string().c_str(), r.reftype == 3 ? "BRA" : "BSR"); } } return result; } addreference(r); return r.reftype>=2 ? 0xdead : 0; } bool CRTable::resolveReferences(int startpc, unsigned char *binary, int& failpc, bool wBranch) { for (std::size_t i=0; i<references.size(); i++) { Reference &r = references[i]; int result; std::string offender; std::string refstr = r.to_string(); if (!resolve(r, result, offender)) { fprintf(stderr,"%s:%i: error: ",r.filename,r.lineNumber); fprintf(stderr,"label \"%s\" is unresolved at %04x\n",offender.c_str(),r.location); failpc = r.location; return false; } if (r.reftype >= 2) { if (result < -32768 || result > 65535) { fprintf(stderr,"%s:%i: error: ",r.filename,r.lineNumber); fprintf(stderr,"two-byte operand \"%s\", evaluating to %i for instruction at %04x, is out of range [-32768,65535].\n",refstr.c_str(), result, r.location); failpc = r.location; return false; } if (wBranch && r.reftype > 2) { int relAddr = result - (r.location + 2); if (-128 <= relAddr && relAddr <= 127) { fprintf(stderr,"%s:%i: warning: ",r.filename,r.lineNumber); fprintf(stderr,"%s instruction at $%04X to reference \"%s\" can be replaced by %s [-Wbranch].\n", r.reftype == 3 ? "JMP" : "JSR", r.location, refstr.c_str(), r.reftype == 3 ? "BRA" : "BSR"); } } binary[r.location - startpc + 1] = (result >> 8) & 0xff; binary[r.location - startpc + 2] = result & 0xff; } else if (r.reftype == 1) { if (result < -128 || result > 255) { fprintf(stderr,"%s:%i: error: ",r.filename,r.lineNumber); fprintf(stderr,"single-byte operand \"%s\", evaluating to %i for instruction at %04x, is out of range [-128,255].\n",refstr.c_str(), result, r.location); failpc = r.location; return false; } binary[r.location - startpc + 1] = result & 0xff; } else if (r.reftype == 0) { result -= r.location + 2; if (result < -128 || result > 127) { fprintf(stderr,"%s:%i: error: ",r.filename,r.lineNumber); fprintf(stderr,"branch destination \"%s\", evaluating to %4x at %04x, is out of range\n",refstr.c_str(), result + r.location + 2, r.location); failpc = r.location; return false; } binary[r.location - startpc + 1] = result & 0xff; } else if (r.reftype == -1) { if (result < -128 || result > 255) { fprintf(stderr,"%s:%i: error: ",r.filename,r.lineNumber); fprintf(stderr,".byte reference \"%s\", evaluating to %i at %04x, is out of range.\n",refstr.c_str(), result, r.location); failpc = r.location; return false; } binary[r.location - startpc] = result & 0xff; } else if (r.reftype == -2) { if (result < -32768 || result > 65535) { fprintf(stderr,"%s:%i: error: ",r.filename,r.lineNumber); fprintf(stderr,".word reference \"%s\", evaluating to %i at %04x, is out of range.\n",refstr.c_str(), result, r.location); failpc = r.location; return false; } binary[r.location - startpc] = (result >> 8) & 0xff; binary[r.location - startpc + 1] = result & 0xff; } } return true; }
// Fill out your copyright notice in the Description page of Project Settings. #include "PaladinCharacter.h" ECharacterType APaladinCharacter::GetCharacterType() { return ECharacterType::Paladin; }
#include <bits/stdc++.h> #define rep(i, n) for (int i = 0; i < (n); ++i) using namespace std; typedef long long ll; typedef vector<int> vi; typedef pair<int, int> ii; typedef vector<vi> vvi; typedef vector<ii> vii; typedef vector<bool> vb; typedef vector<vb> vvb; typedef set<int> si; typedef map<string, int> msi; typedef long long ll; const ll INF = 1e18L + 1; int main() { int t; cin >> t; rep(z, t) { int n, m; string s; cin >> n >> m >> s; vi p(m); rep(i, m) cin >> p[i]; map<char, int> mp; rep(i, 26) { mp['a' + i] = 0; } rep(i, n) { mp[s[i]]++; } sort(p.begin(), p.end()); int last = 0; rep(i, m) { int range = p[i]; for (int j = last; j < range; j++) { mp[s[j]] += (m - i); } last = range; } for (auto it = mp.begin(); it != mp.end(); it++) { cout << it->second << " "; } cout << endl; } return 0; }
/* * Copyright 2016-2017 Flatiron Institute, Simons Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "prvfiledownload.h" #include <QEventLoop> #include <QFile> #include <QNetworkAccessManager> #include <QNetworkReply> #include <QProcess> #include <QString> #include <cachemanager.h> #include <taskprogress.h> #include "mlcommon.h" namespace PrvFileDownload { void Downloader::run() { { QMutexLocker locker(&m_mutex); m_timer.start(); m_num_bytes_downloaded = 0; } TaskProgress task("Downloading " + source_url); QString tmp_fname = CacheManager::globalInstance()->makeLocalFile() + ".Downloader"; QNetworkAccessManager manager; // better make it a singleton QNetworkReply* reply = manager.get(QNetworkRequest(QUrl(source_url))); QEventLoop loop; QFile temp(tmp_fname); int num_bytes = 0; QTime timer; timer.start(); if (!temp.open(QIODevice::WriteOnly)) { reply->abort(); success = false; return; } QObject::connect(reply, &QNetworkReply::readyRead, [&]() { if (MLUtil::threadInterruptRequested()) { task.error("Thread interrupt requested"); reply->abort(); } QByteArray X=reply->readAll(); temp.write(X); num_bytes+=X.count(); { QMutexLocker locker(&m_mutex); m_num_bytes_downloaded=num_bytes; } if (size) task.setProgress(num_bytes*1.0/size); }); QObject::connect(reply, SIGNAL(finished()), &loop, SLOT(quit())); loop.exec(); //TaskManager::TaskProgressMonitor::globalInstance()->incrementQuantity("bytes_downloaded", num_bytes); if (MLUtil::threadInterruptRequested()) { success = false; error = "Thread interrupted."; task.error(error); return; } if (!QFile::rename(tmp_fname, destination_file_name)) { success = false; error = "Unable to rename file: " + tmp_fname + " " + destination_file_name; task.error(error); return; } task.setLabel(QString("Downloaded %1 MB in %2 sec").arg(num_bytes * 1.0 / 1e6).arg(timer.elapsed() * 1.0 / 1000)); success = true; } double Downloader::elapsed_msec() { QMutexLocker locker(&m_mutex); return m_timer.elapsed(); } int Downloader::num_bytes_downloaded() { QMutexLocker locker(&m_mutex); return m_num_bytes_downloaded; } bool concatenate_files(QStringList file_paths, QString dest_path) { /// Witold, this function should be improved by streaming the read/writes foreach (QString str, file_paths) { if (str.isEmpty()) return false; } QFile f(dest_path); if (!f.open(QIODevice::WriteOnly)) { qWarning() << __FUNCTION__ << "Unable to open file for writing: " + dest_path; return false; } foreach (QString str, file_paths) { QFile g(str); if (!g.open(QIODevice::ReadOnly)) { qWarning() << __FUNCTION__ << "Unable to open file for reading: " + str; f.close(); return false; } f.write(g.readAll()); g.close(); } f.close(); return true; } void PrvParallelDownloader::run() { TaskProgress task("Parallel Downloading " + source_url); { QMutexLocker locker(&m_mutex); m_timer.start(); m_num_bytes_downloaded = 0; } //append the url so it can take some (more) query parameters QString url = source_url; if (!url.contains("?")) url += "?"; else url += "&"; //get the start and end bytes QList<int> start_bytes; QList<int> end_bytes; int incr = (int)(1 + size * 1.0 / num_threads); if (incr < 1000) incr = 1000; //let's be a bit reasonable int sum = 0; for (int i = 0; i < num_threads; i++) { if (sum < size) { int val = qMin(incr, size - sum); start_bytes << sum; end_bytes << sum + val - 1; sum += val; } } QList<Downloader*> downloaders; for (int i = 0; i < start_bytes.count(); i++) { QString url2 = url + QString("bytes=%1-%2").arg(start_bytes[i]).arg(end_bytes[i]); Downloader* DD = new Downloader; DD->source_url = url2; DD->destination_file_name = CacheManager::globalInstance()->makeLocalFile() + ".PrvParallelDownloader"; DD->size = end_bytes[i] - start_bytes[i] + 1; downloaders << DD; task.log() << "Starting " + url2; DD->start(); } printf("Using %d downloaders", downloaders.count()); bool done = false; success = true; while ((!done) && (success)) { done = true; if (MLUtil::threadInterruptRequested()) { task.error("Thread interrupt requested"); for (int j = 0; j < downloaders.count(); j++) { downloaders[j]->requestInterruption(); } success = false; error = "Thread interrupted"; } for (int i = 0; i < downloaders.count(); i++) { if (downloaders[i]->wait(100)) { if (downloaders[i]->success) { task.log() << "Thread finished: " + downloaders[i]->source_url; } else { task.error() << "Error in download thread: " + downloaders[i]->source_url + ": " + downloaders[i]->error; for (int j = 0; j < downloaders.count(); j++) { downloaders[j]->requestInterruption(); } success = false; error = "Error in download thread: " + downloaders[i]->source_url + ": " + downloaders[i]->error; } } else { done = false; } } int num_bytes = 0; for (int i = 0; i < downloaders.count(); i++) { num_bytes += downloaders[i]->num_bytes_downloaded(); } if (size) task.setProgress(num_bytes * 1.0 / size); { QMutexLocker locker(&m_mutex); m_num_bytes_downloaded = num_bytes; } } if (!success) { for (int i = 0; i < downloaders.count(); i++) { QFile::remove(downloaders[i]->destination_file_name); } qDeleteAll(downloaders); return; } QStringList paths; for (int i = 0; i < downloaders.count(); i++) { paths << downloaders[i]->destination_file_name; } qDeleteAll(downloaders); if (!concatenate_files(paths, destination_file_name)) { success = false; error = "Problem concatenating files."; } //clean up foreach (QString fname, paths) { QFile::remove(fname); } } double PrvParallelDownloader::elapsed_msec() { QMutexLocker locker(&m_mutex); return m_timer.elapsed(); } int PrvParallelDownloader::num_bytes_downloaded() { QMutexLocker locker(&m_mutex); return m_num_bytes_downloaded; } }
// // WAVEchunk.cpp // gtap // // Created by Mark Williamsen on 10/25/13. // Copyright (c) 2013 Williamsonic. All rights reserved. // #include "WAVEchunk.h" chunkWAVEchunk::chunkWAVEchunk(void) {memset(this, 0, sizeof(chunkWAVEchunk));} riffWAVEchunk::riffWAVEchunk(void) {memset(this, 0, sizeof(riffWAVEchunk));} formatWAVEchunk::formatWAVEchunk(void){memset(this, 0, sizeof(formatWAVEchunk));} dataWAVEchunk::dataWAVEchunk(void) {memset(this, 0, sizeof(dataWAVEchunk));} chunkWAVEchunk::chunkWAVEchunk(istream &inp) { memset(this, 0, sizeof(chunkWAVEchunk)); inp.read((char *)this, sizeof(chunkWAVEchunk)); } riffWAVEchunk::riffWAVEchunk(istream &inp) { memset(this, 0, sizeof(riffWAVEchunk)); inp.read((char *)this, sizeof(riffWAVEchunk)); } formatWAVEchunk::formatWAVEchunk(istream &inp) { memset(this, 0, sizeof(formatWAVEchunk)); inp.read((char *)this, sizeof(formatWAVEchunk)); } dataWAVEchunk::dataWAVEchunk(istream &inp) { memset(this, 0, sizeof(dataWAVEchunk)); inp.read((char *)this, sizeof(dataWAVEchunk)); } // set data members of RIFF chunk riffWAVEchunk::riffWAVEchunk(int theSize) { // populate fields memcpy(chunkID, "RIFF", 4); // not a null-terminated string chunkSize = theSize + 36; memcpy(format, "WAVE", 4); // not a null-terminated string } // set data members of fmt chunk formatWAVEchunk::formatWAVEchunk(int theRate) { // assume always 16 bit samples, 2 channel stereo memcpy(chunkID, "fmt ", 4); // not a null-terminated string chunkSize = 16 ; // fixed size = 16 for PCM fmtCode = 1; // code = 1 for PCM numChan = 2; // number of audio channels sampRate = theRate; // sample rate per second byteRate = numChan * sampRate * 2; // byte rate per second blockAlign = numChan * 2; // byte count per sample bitsSamp = 16; // bit count per sample } // set data members of data chunk dataWAVEchunk::dataWAVEchunk(int theSize) { // populate fields memcpy(chunkID, "data", 4); // not a null-terminated string chunkSize = theSize; } void chunkWAVEchunk::showDetails(ostream &out) { char id[] = "ABCD"; memcpy(id, chunkID, 4); out << "chunkID," << id << endl; out << "chunkSize," << chunkSize << endl; } void riffWAVEchunk::showDetails(ostream &out) { chunkWAVEchunk::showDetails(out); char fmt[] = "ABCD"; memcpy(fmt, format, 4); out << "format," << fmt << endl; } void formatWAVEchunk::showDetails(ostream &out) { chunkWAVEchunk::showDetails(out); out << "fmtCode," << fmtCode << endl; out << "numChan," << numChan << endl; out << "sampRate," << sampRate << endl; out << "byteRate," << byteRate << endl; out << "blockAlign," << blockAlign << endl; out << "bitsSamp," << bitsSamp << endl; } void dataWAVEchunk::showDetails(ostream &out) { chunkWAVEchunk::showDetails(out); }
//Caret.h #ifndef _CARET_H #define _CARET_H typedef signed long int Long; class MemoForm; class Caret { public: Caret(MemoForm *memoForm); ~Caret(); Caret(const Caret& source); Caret& operator=(const Caret& source); void UpdateCaret(); bool ChangeCaret(); bool ChangeImeCaret(); Long GetWidth() const; Long GetHeight() const; MemoForm* GetMemoForm() const; void ShowCaret(); void HideCaret(); Long GetXPosition(); Long GetYPosition(); void Move(Long xPos, Long yPos); private: Long width; Long height; MemoForm *memoForm; }; inline Long Caret::GetWidth() const { return this->width; } inline Long Caret::GetHeight() const { return this->height; } inline MemoForm* Caret::GetMemoForm() const { return const_cast<MemoForm*>(this->memoForm); } #endif //_CARET_H
#include<stdio.h> int main() { int a; scanf("%d",&a) ; if(a>100||a<0) printf("error!"); else if(a<60) printf("fail"); else printf("pass"); return 0; }
#include <string_view> #include <iomanip> #include <filesystem> #include <string> #include <vector> #include <iostream> #include <utility> #include <misc/flags.hpp> #include <misc/util/util.hpp> #include <misc/repl.hpp> #include <misc/argp.hpp> #include <backend/eval/eval.hpp> #include <frontend/parser/parser.hpp> int main(int argc, const char* argv[]) { constexpr auto ver = "alpha-git"; constexpr auto desc = "A small macro language for producing and manipulating strings."; std::string_view outputf; std::vector<std::string_view> warnings; std::vector<std::string_view> path_dirs; bool repl = false; bool disable_run = false; bool disable_file = false; bool disable_colour = false; bool inline_reports = false; bool force = false; std::vector<const char*> positional; if (wpp::argparser( wpp::Info{ver, desc}, argc, argv, &positional, wpp::Opt{outputf, "output file", "--output", "-o"}, wpp::Opt{warnings, "toggle warnings", "--warnings", "-W"}, wpp::Opt{repl, "repl mode", "--repl", "-r"}, wpp::Opt{disable_run, "toggle run & pipe intrinsics", "--disable-run", "-R"}, wpp::Opt{disable_file, "toggle file & use intrinsics", "--disable-file", "-F"}, wpp::Opt{disable_colour, "toggle ANSI colour sequences", "--disable-colour", "-c"}, wpp::Opt{inline_reports, "toggle inline reports", "--inline-reports", "-i"}, wpp::Opt{force, "overwrite file if it exists", "--force", "-f"}, wpp::Opt{path_dirs, "specify directories to search when sourcing files", "--search-path", "-s"} )) return 0; wpp::flags_t flags = 0; for (const auto& x: warnings) { // Set warnings flags. if (x == "param-shadow-var") flags |= wpp::WARN_PARAM_SHADOW_VAR; else if (x == "param-shadow-param") flags |= wpp::WARN_PARAM_SHADOW_PARAM; else if (x == "func-redefined") flags |= wpp::WARN_FUNC_REDEFINED; else if (x == "var-redefined") flags |= wpp::WARN_VAR_REDEFINED; else if (x == "deep-recursion") flags |= wpp::WARN_DEEP_RECURSION; else if (x == "extra-args") flags |= wpp::WARN_EXTRA_ARGS; // Unset warning flags. else if (x == "no-param-shadow-var") flags &= ~wpp::WARN_PARAM_SHADOW_VAR; else if (x == "no-param-shadow-param") flags &= ~wpp::WARN_PARAM_SHADOW_PARAM; else if (x == "no-func-redefined") flags &= ~wpp::WARN_FUNC_REDEFINED; else if (x == "no-var-redefined") flags &= ~wpp::WARN_VAR_REDEFINED; else if (x == "no-deep-recursion") flags &= ~wpp::WARN_DEEP_RECURSION; else if (x == "no-extra-args") flags &= ~wpp::WARN_EXTRA_ARGS; // Enable all warnings. else if (x == "all") flags = wpp::WARN_ALL; else if (x == "useful") flags = wpp::WARN_USEFUL; // Unknown warning flag. else { std::cerr << "error: unrecognized warning '" << x << "'\n"; return 1; } } if (disable_run) flags |= wpp::FLAG_DISABLE_RUN; if (disable_file) flags |= wpp::FLAG_DISABLE_FILE; if (disable_colour) flags |= wpp::FLAG_DISABLE_COLOUR; if (inline_reports) flags |= wpp::FLAG_INLINE_REPORTS; // Build search path. wpp::SearchPath search_path; for (auto& path: path_dirs) search_path.emplace_back(path); if (repl) return wpp::repl(); if (positional.empty()) { std::cerr << "error: no input files\n"; return 1; } std::string out; const auto initial_path = std::filesystem::current_path(); for (const auto& fname: positional) { // Set current path to path of file. const auto path = initial_path / std::filesystem::path{fname}; std::filesystem::current_path(path.parent_path()); wpp::Env env{ initial_path, search_path, flags }; try { env.sources.push(path, wpp::read_file(path), wpp::modes::normal); wpp::node_t root = wpp::parse(env); if (env.state & wpp::ABORT_EVALUATION) return 1; out += wpp::evaluate(root, env); } catch (const wpp::Report& e) { std::cerr << e.str(); return 1; } catch (const wpp::FileNotFoundError&) { std::cerr << "error: file '" << fname << "' not found\n"; return 1; } catch (const wpp::NotFileError&) { std::cerr << "error: '" << fname << "' is not a file\n"; return 1; } catch (const wpp::FileReadError&) { std::cerr << "error: cannot read '" << fname << "'\n"; return 1; } catch (const wpp::SymlinkError&) { std::cerr << "error: symlink '" << fname << "' resolves to itself\n"; return 1; } std::filesystem::current_path(initial_path); } if (not outputf.empty()) { std::error_code ec; if (not force and std::filesystem::exists(outputf, ec)) { std::cerr << "error: file '" << outputf << "' exists\n"; return 1; } wpp::write_file(outputf, out); } else std::cout << out; return 0; }
/************************************************************************* > File Name : RootCaScope.cpp > Author : YangShuai > Created Time: 2016年07月29日 星期五 14时31分26秒 > Description : ************************************************************************/ #include"Itsdata.h" #include"data_handle.h" int32 RootCaScope::_encode(Data& data){ u8* buf = data.getbufptr(); int32 initsize = data.currpos; int32& size = data.currpos; if(data.unused() < _datasize()){ ERROR_PRINT_AND_RETURN("缓存空间不足"); } varible_len_encoding(data, name.size()); buf = data.getbufptr(); for(int32 i = 0; i < name.size(); i++){ *buf++ = name[i]; size++; } tobuf16(buf, permitted_holder_types); buf += 2; size += 2; if((permitted_holder_types & FLAGS_SDE_CA) || (permitted_holder_types & FLAGS_SDE_ENROLMENT) || (permitted_holder_types & FLAGS_SDE_IDENTIFIED_LOCALIZED) || (permitted_holder_types & FLAGS_SDE_IDENTIFIED_NOT_LOCALIZED) || (permitted_holder_types & FLAGS_SDE_ANONYMOUS)){ if(flags_content.secure_data_permissions._encode(data) < 0){ ERROR_PRINT_AND_RETURN("IntXArray编码失败"); } } if(permitted_holder_types & 0x3FB0){ varible_len_encoding(data, flags_content.other_permissions.size()); buf = data.getbufptr(); for(int32 i = 0;i < flags_content.other_permissions.size();i++){ *buf++ = flags_content.other_permissions[i]; size++; } } if(region._encode(data) < 0){ ERROR_PRINT_AND_RETURN("GeographicRegion编码失败"); } return size - initsize; } int32 RootCaScope::_decode(Data& data){ u8* buf = data.getbufptr(); int32 initsize = data.currpos; int32& size = data.currpos; int32 datalen; if(data.unused() < 5){ ERROR_PRINT_AND_RETURN("填充数据不足"); } datalen = variablelength_data_num(data); if(data.unused() < datalen){ ERROR_PRINT_AND_RETURN("填充数据不足"); } buf = data.getbufptr(); for(int32 i = 0; i < datalen; i++){ name.push_back(*buf++); size++; } permitted_holder_types = (HolderTypeFlags)bufto16(buf); buf += 2; size += 2; if((permitted_holder_types & FLAGS_SDE_CA) || (permitted_holder_types & FLAGS_SDE_ENROLMENT) || (permitted_holder_types & FLAGS_SDE_IDENTIFIED_LOCALIZED) || (permitted_holder_types & FLAGS_SDE_IDENTIFIED_NOT_LOCALIZED) || (permitted_holder_types & FLAGS_SDE_ANONYMOUS)){ if(flags_content.secure_data_permissions._decode(data) < 0){ ERROR_PRINT_AND_RETURN("IntXArray解码失败"); } } if(permitted_holder_types & 0x3FB0){ datalen = variablelength_data_num(data); if(data.unused() < datalen){ ERROR_PRINT_AND_RETURN("填充数据不足"); } buf = data.getbufptr(); for(int32 i = 0;i < datalen;i++){ flags_content.other_permissions.push_back(*buf++); size++; } } if(region._decode(data) < 0){ ERROR_PRINT_AND_RETURN("GeographicRegion解码失败"); } return size - initsize; } int32 RootCaScope::_datasize(){ if(datasize) goto end; VEC_ENCODING_LEN_U8(name); datasize += 2; if((permitted_holder_types & FLAGS_SDE_CA) || (permitted_holder_types & FLAGS_SDE_ENROLMENT) || (permitted_holder_types & FLAGS_SDE_IDENTIFIED_LOCALIZED) || (permitted_holder_types & FLAGS_SDE_IDENTIFIED_NOT_LOCALIZED) || (permitted_holder_types & FLAGS_SDE_ANONYMOUS)){ datasize += flags_content.secure_data_permissions._datasize(); } if(permitted_holder_types & FLAGS_CRL_SIGNER){ VEC_ENCODING_LEN_U8(flags_content.other_permissions); } datasize += region._datasize(); end: return datasize; }
#include "GfxConfiguration.hpp" #include "config.h" #include "AnimationManager.hpp" #include "AssetLoader.hpp" #include "DebugManager.hpp" #include "InputManager.hpp" #include "MemoryManager.hpp" #include "Bullet/BulletPhysicsManager.hpp" #include "SceneManager.hpp" #include "BilliardGameLogic.hpp" #if defined(OS_WEBASSEMBLY) #include "Platform/Sdl/OpenGLApplication.hpp" #elif defined(OS_MACOS) #include "CocoaMetalApplication.h" #elif defined(OS_WINDOWS) //#include "D3d12Application.hpp" #include "OpenGLApplication.hpp" #else #include "OpenGLApplication.hpp" #endif #if defined(OS_ANDROID) || defined(OS_WEBASSEMBLY) #include "RHI/OpenGL/OpenGLESConfig.hpp" #elif defined(OS_MACOS) #include "RHI/Metal/MetalConfig.hpp" #elif defined(OS_WINDOWS) //#include "RHI/D3d/D3d12Config.hpp" #include "RHI/OpenGL/OpenGLConfig.hpp" #else #include "RHI/OpenGL/OpenGLConfig.hpp" #endif #if defined(OS_WEBASSEMBLY) #include <emscripten.h> #include <functional> std::function<void()> loop; void main_loop() { loop(); } #endif // defined(OS_WEBASSEMBLY) using namespace My; int main(int argc, char** argv) { int ret; GfxConfiguration config(8, 8, 8, 8, 24, 8, 4, 1024, 768, "Billiard"); BilliardGameLogic gameLogic; BulletPhysicsManager physicsManager; #if defined(OS_MACOS) CocoaMetalApplication app(config); #elif defined(OS_WINDOWS) // D3d12Application app(config); OpenGLApplication app(config); #else OpenGLApplication app(config); #endif MemoryManager memoryManager; SceneManager sceneManager; InputManager inputManager; AnimationManager animationManager; AssetLoader assetLoader; #ifdef DEBUG DebugManager debugManager; #endif TGraphicsManager graphicsManager; TPipelineStateManager pipelineStateManager; app.SetCommandLineParameters(argc, argv); app.RegisterManagerModule(&animationManager); app.RegisterManagerModule(&assetLoader); app.RegisterManagerModule(&graphicsManager); app.RegisterManagerModule(&inputManager); app.RegisterManagerModule(&memoryManager); app.RegisterManagerModule(&physicsManager); app.RegisterManagerModule(&pipelineStateManager); app.RegisterManagerModule(&sceneManager); app.RegisterManagerModule(&gameLogic); #ifdef DEBUG app.RegisterManagerModule(&debugManager); #endif app.CreateMainWindow(); ret = app.Initialize(); // Drive the modules ahead #if defined(OS_WEBASSEMBLY) auto main_loop = [] { app.Tick(); }; emscripten_set_main_loop(main_loop, 0, true); #else while (!app.IsQuit()) { app.Tick(); } #endif #if !defined(OS_WEBASSEMBLY) // Finalize App app.Finalize(); #endif return ret; }
#include <stdio.h> #include <sys/mman.h> #include <string.h> #include <stdlib.h> #include <unistd.h> #include <pthread.h> #include <monkit.h> #include <semaphore.h> #include <time.h> #include "dmaManager.h" #include "FlashIndication.h" #include "FlashRequest.h" #define BLOCKS_PER_CHIP 32 #define CHIPS_PER_BUS 8 // 8 #define NUM_BUSES 8 // 8 #define FPAGE_SIZE (8192*2) #define FPAGE_SIZE_VALID (8224) #define NUM_TAGS 128 typedef enum { UNINIT, ERASED, WRITTEN } FlashStatusT; typedef struct { bool busy; int bus; int chip; int block; } TagTableEntry; FlashRequestProxy *device; pthread_mutex_t flashReqMutex; pthread_cond_t flashFreeTagCond; //8k * 128 size_t dstAlloc_sz = FPAGE_SIZE * NUM_TAGS *sizeof(unsigned char); size_t srcAlloc_sz = FPAGE_SIZE * NUM_TAGS *sizeof(unsigned char); int dstAlloc; int srcAlloc; unsigned int ref_dstAlloc; unsigned int ref_srcAlloc; unsigned int* dstBuffer; unsigned int* srcBuffer; unsigned int* readBuffers[NUM_TAGS]; unsigned int* writeBuffers[NUM_TAGS]; TagTableEntry readTagTable[NUM_TAGS]; TagTableEntry writeTagTable[NUM_TAGS]; TagTableEntry eraseTagTable[NUM_TAGS]; FlashStatusT flashStatus[NUM_BUSES][CHIPS_PER_BUS][BLOCKS_PER_CHIP]; // for Table #define NUM_BLOCKS 4096 #define NUM_SEGMENTS NUM_BLOCKS #define NUM_CHANNELS 8 #define NUM_CHIPS 8 #define NUM_LOGBLKS (NUM_CHANNELS*NUM_CHIPS) size_t blkmapAlloc_sz = sizeof(uint16_t) * NUM_SEGMENTS * NUM_LOGBLKS; int blkmapAlloc; uint ref_blkmapAlloc; uint16_t (*blkmap)[NUM_CHANNELS*NUM_CHIPS]; // 4096*64 uint16_t (*blkmgr)[NUM_CHIPS][NUM_BLOCKS]; // 8*8*4096 bool testPassed = false; bool verbose = true; int curReadsInFlight = 0; int curWritesInFlight = 0; int curErasesInFlight = 0; double timespec_diff_sec( timespec start, timespec end ) { double t = end.tv_sec - start.tv_sec; t += ((double)(end.tv_nsec - start.tv_nsec)/1000000000L); return t; } unsigned int hashAddrToData(int bus, int chip, int blk, int word) { return ((bus<<24) + (chip<<20) + (blk<<16) + word); } bool checkReadData(int tag) { TagTableEntry e = readTagTable[tag]; bool pass = true; unsigned int goldenData; if (flashStatus[e.bus][e.chip][e.block]==WRITTEN) { int numErrors = 0; for (unsigned int word=0; word<FPAGE_SIZE_VALID/sizeof(unsigned int); word++) { goldenData = hashAddrToData(e.bus, e.chip, e.block, word); if (goldenData != readBuffers[tag][word]) { fprintf(stderr, "LOG: **ERROR: read data mismatch! tag=%d, %d %d %d, word=%d, Expected: %x, read: %x\n", tag, e.bus, e.chip, e.block, word, goldenData, readBuffers[tag][word]); numErrors++; pass = false; } } if (numErrors==0) { fprintf(stderr, "LOG: Read data check passed on tag=%d!\n", tag); } } else if (flashStatus[e.bus][e.chip][e.block]==ERASED) { //only check first word. It may return 0 if bad block, or -1 if erased //int numErrors = 0; //for (unsigned int word=0; word<FPAGE_SIZE_VALID/sizeof(unsigned int); word++) { // if (readBuffers[tag][word]!=(unsigned int)-1) { // fprintf(stderr, "LOG: **ERROR: erased data mismatch! tag=%d, word=%d, read=%x\n",tag,word,readBuffers[tag][word]); // pass = false; // } //} //if (numErrors==0) { // fprintf(stderr, "LOG: Read check pass on erased block! tag=%d\n",tag); //} if (readBuffers[tag][0]==(unsigned int)-1) { fprintf(stderr, "LOG: Read check pass on erased block!\n"); } else if (readBuffers[tag][0]==0) { fprintf(stderr, "LOG: Warning: potential bad block, read erased data 0\n"); pass = false; } else { fprintf(stderr, "LOG: **ERROR: read data mismatch! Expected: ERASED, read: %x\n", readBuffers[tag][0]); pass = false; } } else { fprintf(stderr, "LOG: **ERROR: flash block state unknown. Did you erase before write?\n"); pass = false; } return pass; } class FlashIndication : public FlashIndicationWrapper { public: FlashIndication(unsigned int id) : FlashIndicationWrapper(id){} virtual void readDone(unsigned int tag, unsigned int status) { printf("LOG: readdone: tag=%d status=%d; inflight=%d\n", tag, status, curReadsInFlight ); fflush(stdout); pthread_mutex_lock(&flashReqMutex); curReadsInFlight --; pthread_mutex_unlock(&flashReqMutex); } virtual void writeDone(unsigned int tag, unsigned int status) { printf("LOG: writedone: tag=%d status=%d; inflight=%d\n", tag, status, curWritesInFlight ); fflush(stdout); pthread_mutex_lock(&flashReqMutex); curWritesInFlight --; pthread_mutex_unlock(&flashReqMutex); } virtual void eraseDone(unsigned int tag, unsigned int status) { printf("LOG: eraseDone, tag=%d, status=%d\n", tag, status); fflush(stdout); pthread_mutex_lock(&flashReqMutex); curErasesInFlight--; pthread_mutex_unlock(&flashReqMutex); } virtual void debugDumpResp (unsigned int debug0, unsigned int debug1, unsigned int debug2, unsigned int debug3, unsigned int debug4, unsigned int debug5) { //uint64_t cntHi = debugRdCntHi; //uint64_t rdCnt = (cntHi<<32) + debugRdCntLo; fprintf(stderr, "LOG: DEBUG DUMP: gearSend = %d, gearRec = %d, aurSend = %d, aurRec = %d, readSend=%d, writeSend=%d\n", debug0, debug1, debug2, debug3, debug4, debug5); } virtual void uploadDone() { fprintf(stderr, "Map Upload(Host->FPGA) done!\n"); } virtual void downloadDone() { fprintf(stderr, "Map Download(FPGA->Host) done!\n"); } }; int getNumReadsInFlight() { return curReadsInFlight; } int getNumWritesInFlight() { return curWritesInFlight; } int getNumErasesInFlight() { return curErasesInFlight; } //int lastErase = NUM_TAGS-1; //int lastRead = NUM_TAGS-1; //int lastWrite = NUM_TAGS-1; //TODO: more efficient locking int waitIdleEraseTag() { int tag = -1; while ( tag < 0 ) { pthread_mutex_lock(&flashReqMutex); for ( int t = 0; t < NUM_TAGS; t++ ) { //for ( int t = (lastErase==NUM_TAGS-1)?0:lastErase+1; t < NUM_TAGS; t++ ) { if ( !eraseTagTable[t].busy ) { eraseTagTable[t].busy = true; tag = t; //lastErase = t; break; } } pthread_mutex_unlock(&flashReqMutex); /* if (tag < 0) { pthread_cond_wait(&flashFreeTagCond, &flashReqMutex); } else { pthread_mutex_unlock(&flashReqMutex); return tag; } */ } return tag; } //TODO: more efficient locking int waitIdleWriteBuffer() { int tag = -1; while ( tag < 0 ) { pthread_mutex_lock(&flashReqMutex); for ( int t = 0; t < NUM_TAGS; t++ ) { //for ( int t = (lastWrite==NUM_TAGS-1)?0:lastWrite+1; t < NUM_TAGS; t++ ) { if ( !writeTagTable[t].busy) { writeTagTable[t].busy = true; tag = t; //lastWrite=t; break; } } pthread_mutex_unlock(&flashReqMutex); /* if (tag < 0) { pthread_cond_wait(&flashFreeTagCond, &flashReqMutex); } else { pthread_mutex_unlock(&flashReqMutex); return tag; } */ } return tag; } //TODO: more efficient locking int waitIdleReadBuffer() { int tag = -1; while ( tag < 0 ) { pthread_mutex_lock(&flashReqMutex); for ( int t = 0; t < NUM_TAGS; t++ ) { //for ( int t = (lastRead==NUM_TAGS-1)?0:lastRead+1; t < NUM_TAGS; t++ ) { if ( !readTagTable[t].busy ) { readTagTable[t].busy = true; tag = t; //lastRead=t; break; } } pthread_mutex_unlock(&flashReqMutex); /* if (tag < 0) { pthread_cond_wait(&flashFreeTagCond, &flashReqMutex); } else { pthread_mutex_unlock(&flashReqMutex); return tag; } */ } return tag; } void eraseBlock(uint32_t tag, uint32_t lpa) { pthread_mutex_lock(&flashReqMutex); curErasesInFlight ++; pthread_mutex_unlock(&flashReqMutex); if ( verbose ) fprintf(stderr, "LOG: sending erase blk request with tag=%u @%u\n", tag, lpa ); device->eraseBlock(tag, lpa); } void writePage(uint32_t tag, uint32_t lpa) { pthread_mutex_lock(&flashReqMutex); curWritesInFlight ++; pthread_mutex_unlock(&flashReqMutex); if ( verbose ) fprintf(stderr, "LOG: sending write page request with tag=%u @%u\n", tag, lpa ); device->readPage(tag, lpa, tag*FPAGE_SIZE); } void readPage(uint32_t tag, uint32_t lpa) { pthread_mutex_lock(&flashReqMutex); curReadsInFlight ++; pthread_mutex_unlock(&flashReqMutex); if ( verbose ) fprintf(stderr, "LOG: sending read page request with tag=%u @%u\n", tag, lpa ); device->readPage(tag, lpa, tag*FPAGE_SIZE); } int main(int argc, const char **argv) { testPassed=true; fprintf(stderr, "Initializing DMA...\n"); device = new FlashRequestProxy(IfcNames_FlashRequestS2H); FlashIndication deviceIndication(IfcNames_FlashIndicationH2S); DmaManager *dma = platformInit(); fprintf(stderr, "Main::allocating memory...\n"); srcAlloc = portalAlloc(srcAlloc_sz, 0); dstAlloc = portalAlloc(dstAlloc_sz, 0); srcBuffer = (unsigned int *)portalMmap(srcAlloc, srcAlloc_sz); dstBuffer = (unsigned int *)portalMmap(dstAlloc, dstAlloc_sz); blkmapAlloc = portalAlloc(blkmapAlloc_sz*2, 0); char *tmpPtr = (char*)portalMmap(blkmapAlloc, blkmapAlloc_sz*2); blkmap = (uint16_t(*)[NUM_CHANNELS*NUM_CHIPS]) (tmpPtr); blkmgr = (uint16_t(*)[NUM_CHIPS][NUM_BLOCKS]) (tmpPtr+blkmapAlloc_sz); fprintf(stderr, "dstAlloc = %x\n", dstAlloc); fprintf(stderr, "srcAlloc = %x\n", srcAlloc); fprintf(stderr, "blkmapAlloc = %x\n", blkmapAlloc); pthread_mutex_init(&flashReqMutex, NULL); pthread_cond_init(&flashFreeTagCond, NULL); printf( "Done initializing hw interfaces\n" ); fflush(stdout); //portalExec_start(); printf( "Done portalExec_start\n" ); fflush(stdout); portalCacheFlush(dstAlloc, dstBuffer, dstAlloc_sz, 1); portalCacheFlush(srcAlloc, srcBuffer, srcAlloc_sz, 1); portalCacheFlush(blkmapAlloc, blkmap, blkmapAlloc_sz*2, 1); ref_dstAlloc = dma->reference(dstAlloc); ref_srcAlloc = dma->reference(srcAlloc); ref_blkmapAlloc = dma->reference(blkmapAlloc); device->setDmaWriteRef(ref_dstAlloc); device->setDmaReadRef(ref_srcAlloc); device->setDmaMapRef(ref_blkmapAlloc); for (int t = 0; t < NUM_TAGS; t++) { readTagTable[t].busy = false; writeTagTable[t].busy = false; int byteOffset = t * FPAGE_SIZE; readBuffers[t] = dstBuffer + byteOffset/sizeof(unsigned int); writeBuffers[t] = srcBuffer + byteOffset/sizeof(unsigned int); } for (int blk=0; blk < BLOCKS_PER_CHIP; blk++) { for (int c=0; c < CHIPS_PER_BUS; c++) { for (int bus=0; bus< NUM_BUSES; bus++) { flashStatus[bus][c][blk] = UNINIT; } } } for (int t = 0; t < NUM_TAGS; t++) { for ( unsigned int i = 0; i < FPAGE_SIZE/sizeof(unsigned int); i++ ) { readBuffers[t][i] = 0xDEADBEEF; writeBuffers[t][i] = 0xBEEFDEAD; } } long actualFrequency=0; long requestedFrequency=1e9/MainClockPeriod; int status = setClockFrequency(0, requestedFrequency, &actualFrequency); fprintf(stderr, "Requested Freq: %5.2f, Actual Freq: %5.2f, status=%d\n" ,(double)requestedFrequency*1.0e-6 ,(double)actualFrequency*1.0e-6,status); device->start(0); device->setDebugVals(0,0); //flag, delay device->debugDumpReq(0); sleep(1); device->debugDumpReq(0); sleep(1); for (int t = 0; t < NUM_TAGS; t++) { for ( unsigned int i = 0; i < FPAGE_SIZE/sizeof(unsigned int); i++ ) { readBuffers[t][i] = 0xDEADBEEF; } } printf( "MAP DOWNLOAD!\n" ); fflush(stdout); device->downloadMap(); int tmp,tmp2; printf( "put any int to start test\n" ); do { tmp2 = scanf( "%d", &tmp); } while (!(tmp2 > 0)); //// map test /// int i,j,k; //uint16_t (*blkmap)[NUM_CHANNELS*NUM_CHIPS]; // 4096*64 for (i = 0; i<4096; i++) for (j =0; j<64; j++) #ifndef BSIM blkmap[i][j] = 0x0; #else blkmap[i][j] = 0x8000; #endif //uint16_t (*blkmgr)[NUM_CHIPS][NUM_BLOCKS]; // 8*8*4096 for (i = 0; i<8; i++) for (j=0; j<8; j++) for (k=0; k<4096; k++) #ifndef BSIM blkmgr[i][j][k] = 0xCC; #else blkmgr[i][j][k] = 0x80CC; #endif blkmap[0][1] = (1 << 14) | 32 ; blkmap[0][2] = (1 << 14) | 32 ; blkmap[0][5] = (1 << 14) | 32 ; #ifndef BSIM blkmgr[0][0][31] = 0xAB; blkmgr[0][0][24] = 0xAF; #else blkmgr[0][0][31] = 0x80AB; blkmgr[0][0][24] = 0x80AF; #endif printf( "MAP UPLOAD!\n" ); fflush(stdout); device->uploadMap(); printf( "put any int to start test\n" ); do { tmp2 = scanf( "%d", &tmp); } while (!(tmp2 > 0)); timespec start, now; clock_gettime(CLOCK_REALTIME, & start); printf( "TEST READ!\n" ); fflush(stdout); for (int repeat = 0; repeat < 1; repeat++){ for (unsigned int lpa = 0; lpa < 10; lpa++){ readPage(waitIdleReadBuffer(), lpa); } } while (true) { usleep(100); if ( getNumReadsInFlight() == 0 ) break; } int elapsed = 0; while (true) { usleep(100); if (elapsed == 0) { elapsed=10000; device->debugDumpReq(0); } else { elapsed--; } if ( getNumReadsInFlight() == 0 ) break; } device->debugDumpReq(0); clock_gettime(CLOCK_REALTIME, & now); fprintf(stderr, "LOG: finished reading from page! %f\n", timespec_diff_sec(start, now) ); sleep(2); }
// Problem: Binary Period // Link: https://codeforces.com/contest/1342/problem/B #include<bits/stdc++.h> using namespace std; int main(){ int t; cin >> t; while(t>0){ string seq; cin >> seq; set<int> nums; for(int i=0; i<seq.size(); ++i){ if(seq[i] == '0'){ nums.insert(0); }else{ nums.insert(1); } } if(nums.size()==1){ cout << seq << endl; }else{ for(int i=0; i<seq.size(); ++i){ cout << "01" << ""; } cout << endl; } t--; } return 0; }
/* Validate BST: Implement a function to check if a binary tree is a binary search tree. */ #include <iostream> #include <vector> #include <array> #include <queue> #include <algorithm> #include <cmath> #include <math.h> #include <utility> #include <climits> #define TREE_SIZE 10000 class Node { public: Node(){}; int* getValue(){return value;}; void setValue(int* newVal){value = newVal;}; Node* getLeft(){return leftChild;}; Node* getRight(){return rightChild;}; void setLeft(Node* newNode) { leftChild = newNode;}; void setRight(Node* newNode) { rightChild = newNode;}; private: int* value; Node* leftChild; Node* rightChild; }; int getCenter(int start, int end) { int span = end - start; int mid = span / 2; return start + mid; } Node* buildTree(std::array<int, TREE_SIZE> & valueArray, int start, int end) { int centerIndex = getCenter(start, end); Node* thisNode = new Node(); thisNode->setValue(&valueArray[centerIndex]); if(end == start) { return thisNode; } else if(end <= start) { return nullptr; } else{ thisNode->setLeft(buildTree(valueArray, start, centerIndex - 1)); thisNode->setRight(buildTree(valueArray, centerIndex + 1, end)); return thisNode; } } void printTree(Node* node) { if(node == nullptr) { return; } printTree(node->getLeft()); std::cout << *node->getValue() << " "; printTree(node->getRight()); } void printPathTo(Node* node, int* val) { std::cout << *node->getValue() << " "; if(val == node->getValue()) { return; } else if(*val < *node->getValue()) { printPathTo(node->getLeft(), val); } else if(*val > *node->getValue()) { printPathTo(node->getRight(), val); } } class LinkedList { public: LinkedList():thisNode{nullptr}, next{nullptr}{}; LinkedList(Node* nd):next{nullptr}{thisNode = nd;}; Node* thisNode; LinkedList* next; }; void printLL(LinkedList* list) { LinkedList* runner = list; while(runner != nullptr) { std::cout << *runner->thisNode->getValue() << " "; runner = runner->next; } } void getLayers(std::vector<LinkedList*>& lists, Node* thisNode, int layer) { if(thisNode == nullptr) { return; } else { LinkedList* listItem = new LinkedList(); if(lists.size() == layer) { listItem->thisNode = thisNode; std::cout << "Layer: " << layer << " Item: " << *listItem->thisNode->getValue() << " PUSH" <<std::endl; lists.push_back(listItem); } else { listItem->thisNode = thisNode; std::cout << "Layer: " << layer << " Item: " << *listItem->thisNode->getValue() << std::endl; listItem->next = lists[layer]; lists[layer] = listItem; } getLayers(lists, thisNode->getRight(), layer + 1); getLayers(lists, thisNode->getLeft(), layer + 1); } } int treeHeight(Node* thisNode) { if(thisNode == nullptr) { return 0; } else { return std::max(treeHeight(thisNode->getLeft()), treeHeight(thisNode->getRight() )) + 1; } } std::pair<bool, int> isBalanced(Node* thisNode) { std::pair<bool, int> result; if(thisNode == nullptr) { result.first = true; result.second = 0; return result; } //Since we want true height, we check all connections...if we only want // balanced or not, we can short circuit upon seeing a false std::pair<bool, int> leftResult = isBalanced(thisNode->getLeft()); std::pair<bool, int> rightResult = isBalanced(thisNode->getRight()); int leftHeight = leftResult.second; int rightHeight = rightResult.second; result.second = std::max(leftHeight, rightHeight) + 1; result.first = leftResult.first && rightResult.first && (std::abs(leftHeight - rightHeight) <= 1); return result; } std::pair<bool, std::array<int, 2>> validateBST(Node* thisNode) { std::pair<bool, std::array<int, 2>> result; if(thisNode == nullptr) { result.first = true; result.second = {INT_MAX, INT_MIN}; return result; } std::pair<bool, std::array<int,2>> resultLeft = validateBST(thisNode->getLeft()); std::pair<bool, std::array<int,2>> resultRight = validateBST(thisNode->getRight()); result.first = resultLeft.first && resultRight.first && resultLeft.second[1] <= *thisNode->getValue() && resultRight.second[0] > *thisNode->getValue(); result.second[0] = std::min(std::min(resultLeft.second[0], resultRight.second[0]), *thisNode->getValue()); result.second[1] = std::max(std::max(resultLeft.second[1], resultRight.second[1]), *thisNode->getValue()); return result; } int main(){ std::array<int, TREE_SIZE> valueArray; for(int i = 0; i< valueArray.size(); i++) { valueArray[i] = i; } Node* rootNode = buildTree(valueArray, 0, TREE_SIZE - 1); // printTree(rootNode); // std::cout << std::endl << std::endl; printPathTo(rootNode, &valueArray[7]); std::cout << std::endl; std::vector<LinkedList*> lists; bool unbalance = 0; int extra1 = 3; int extra2 = 11; if(unbalance) { Node* extraN1 = new Node(); extraN1->setValue(&extra1); Node* extraN2 = new Node(); extraN2->setValue(&extra2); extraN1->setRight(extraN2); rootNode->getRight()->getRight()->getRight()->setRight(extraN1); } getLayers(lists, rootNode, 0); for(int i = 0; i < lists.size(); i++) { printLL(lists.at(i)); std::cout << std::endl; } std::pair<bool, int> balanceResultPair = isBalanced(rootNode); bool balanceResult = balanceResultPair.first; std::cout << std::endl << "Balanced? " << balanceResult << " Height: " << balanceResultPair.second << std::endl; std::pair<bool, std::array<int,2>> bstResult = validateBST(rootNode); std::cout << std::endl << "BST? " << bstResult.first << " Min: " << bstResult.second[0] << " Max: " << bstResult.second[1] << std::endl; }
#include "algorithm/base_component/include/frame.h" namespace OpticalFlow_SLAM_algorithm_opticalflow_slam { int64_t Frame::static_new_id = -1; /** * @brief * @author snowden * @date 2021-07-16 * @version 1.0 */ Frame::Frame(const int64_t timestamp, const cv::Mat left_image, const cv::Mat right_image) : timestamp_(timestamp), left_image_(left_image), right_image_(right_image) { // id_ = get_new_id(); } /** * @brief * @author snowden * @date 2021-07-16 * @version 1.0 */ Frame::~Frame() { } SE3 Frame::get_left_pose() { //TODO(snowden) : may not need to lock; std::unique_lock<std::mutex> left_pose_lock(left_pose_mutex_); return left_pose_; } void Frame::set_left_pose(SE3 new_pose) { std::unique_lock<std::mutex> left_pose_lock(left_pose_mutex_); left_pose_ = new_pose; return ; } SE3 Frame::get_right_pose() { std::unique_lock<std::mutex> right_pose_lock(right_pose_mutex_); return right_pose_; } void Frame::set_right_pose(SE3 new_pose) { std::unique_lock<std::mutex> right_pose_lock(right_pose_mutex_); right_pose_ = new_pose; return ; } } //namespace OpticalFlow_SLAM_algorithm_opticalflow_slam
/*************************************************************************** Copyright (c) 2020 Philip Fortier This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. ***************************************************************************/ // NewRoomDialog.cpp : implementation file // #include "stdafx.h" #include "AppState.h" #include "NewScriptDialog.h" #include "resource.h" #include "ScriptOM.h" // CNewScriptDialog dialog IMPLEMENT_DYNAMIC(CNewScriptDialog, CDialog) CNewScriptDialog::CNewScriptDialog(UINT nID, CWnd* pParent) : CExtResizableDialog(nID, pParent) { _scriptId.SetLanguage(appState->GetResourceMap().Helper().GetDefaultGameLanguage()); } CNewScriptDialog::CNewScriptDialog(CWnd* pParent /*=NULL*/) : CExtResizableDialog(CNewScriptDialog::IDD, pParent) { _scriptId.SetLanguage(appState->GetResourceMap().Helper().GetDefaultGameLanguage()); } void CNewScriptDialog::_DiscoveredScriptName(PCTSTR pszName) { // Nothing. } int CNewScriptDialog::_GetSuggestedScriptNumber() { int iRet = 0; // Now find an "empty" slot. // REVIEW: Need a better algorithm here. int lastUsed = 0; for (int used : _usedScriptNumbers) { if ((used > (lastUsed + 1)) && (lastUsed > _GetMinSuggestedScriptNumber())) { return lastUsed + 1; } lastUsed = used; } return iRet; } void CNewScriptDialog::_PrepareDialog() { int iSuggestedRoom = 0; // Look through game.ini for a vacant room number. DWORD nSize = 5000; TCHAR *pszNameValues = new TCHAR[nSize]; if (pszNameValues) { std::string iniFileName = appState->GetResourceMap().Helper().GetGameIniFileName(); if (!iniFileName.empty()) { DWORD nLength = GetPrivateProfileSection(TEXT("Script"), pszNameValues, nSize, iniFileName.c_str()); if (nLength > 0 && ((nSize - 2) != nLength)) // returns (nSize - 2) in case of insufficient buffer { // Keep track of which script numbers have been used. _usedScriptNumbers.clear(); TCHAR *psz = pszNameValues; while(*psz) { // The format is // n000=ScriptName size_t cch = strlen(psz); TCHAR *pszEq = StrChr(psz, TEXT('=')); if (pszEq) { _DiscoveredScriptName(pszEq + 1); } // Take note of the script number. int iScript = StrToInt(psz + 1); if (iScript >= 0) { // We can end up with turd entries lying around in game.ini, so check that the file actually exists: std::string filename = appState->GetResourceMap().Helper().GetScriptFileName((uint16_t)iScript); if (PathFileExists(filename.c_str())) { _usedScriptNumbers.insert(iScript); } } // Advance to next string. psz += (cch + 1); } iSuggestedRoom = _GetSuggestedScriptNumber(); } } delete [] pszNameValues; } // Suggest a room: TCHAR szNumber[5]; StringCchPrintf(szNumber, ARRAYSIZE(szNumber), TEXT("%d"), iSuggestedRoom); m_wndEditScriptNumber.SetWindowText(szNumber); } void CNewScriptDialog::_AttachControls(CDataExchange* pDX) { DDX_Control(pDX, IDC_SCRIPTNAME, m_wndEditScriptName); DDX_Control(pDX, IDC_EDITROOMNUMBER, m_wndEditScriptNumber); DDX_Control(pDX, IDC_STATICSCRIPTNUMBER, m_wndScriptName); DDX_Control(pDX, IDC_STATICSCRIPTNAME, m_wndScriptNumber); m_wndEditScriptNumber.SetLimitText(5); } void CNewScriptDialog::DoDataExchange(CDataExchange* pDX) { __super::DoDataExchange(pDX); ShowSizeGrip(FALSE); // Visuals DDX_Control(pDX, IDOK, m_wndOk); DDX_Control(pDX, IDCANCEL, m_wndCancel); _AttachControls(pDX); _PrepareDialog(); } void CNewScriptDialog::_PrepareBuffer() { sci::Script script(_scriptId); if (appState->GetVersion().SeparateHeapResources) { // e.g. for SCI0, keep SCIStudio compatible. Otherwise, use version 2 script.SyntaxVersion = 2; } std::stringstream ss; sci::SourceCodeWriter out(ss, script.Language()); out.pszNewLine = "\r\n"; script.OutputSourceCode(out); _strBuffer = ss.str(); } BEGIN_MESSAGE_MAP(CNewScriptDialog, CDialog) END_MESSAGE_MAP() // // Returns TRUE if the chosen script number is valid // BOOL CNewScriptDialog::_ValidateScriptNumber() { BOOL fValid = FALSE; // Validate the script number CString strNumber; m_wndEditScriptNumber.GetWindowText(strNumber); _scriptId = ScriptId(); // Reset, or else it asserts if we already set a number on it. _scriptId.SetLanguage(appState->GetResourceMap().Helper().GetDefaultGameLanguage()); _scriptId.SetResourceNumber(StrToInt(strNumber)); int value = _scriptId.GetResourceNumber(); if (contains(_usedScriptNumbers, value)) { TCHAR szMessage[MAX_PATH]; StringCchPrintf(szMessage, ARRAYSIZE(szMessage), TEXT("Script %03d already exists. Please use another number."), _scriptId.GetResourceNumber()); AfxMessageBox(szMessage, MB_OK | MB_ICONEXCLAMATION | MB_APPLMODAL); fValid = TRUE; } return fValid; } // CNewScriptDialog message handlers void CNewScriptDialog::OnOK() { BOOL fClose = !_ValidateScriptNumber(); WORD nScript = _scriptId.GetResourceNumber(); if (fClose) { // Prepare the script name. // (Without the .sc extension) CString strName; m_wndEditScriptName.GetWindowText(strName); if (!strName.IsEmpty()) { StringCchCopy(_szScriptName, ARRAYSIZE(_szScriptName), (PCTSTR)strName); _scriptId.SetFullPath(appState->GetResourceMap().Helper().GetScriptFileName(_szScriptName)); } else { fClose = FALSE; AfxMessageBox(TEXT("Please enter a script name."), MB_OK | MB_APPLMODAL | MB_ICONEXCLAMATION); } } if (fClose) { _PrepareBuffer(); __super::OnOK(); } }
#include "commands/baseRoulante/ChangerVitesse.h" #include "Robot.h" ChangerVitesse::ChangerVitesse() { Requires(&Robot::m_baseRoulante); } void ChangerVitesse::Initialize() { Robot::m_baseRoulante.ChangerVitesse(); }
#include <iomanip> #include "Product.h" #include "TaxableProduct.h" namespace w7 { void TaxableProduct::display(std::ostream& os) const { Product::display(os); if (productTax == HST) { os << " HST"; } else if (productTax == PST) { os << " PST"; } } }
/////////////////////////////////////////////////////////////////////////////// /// @file lib/cgibase/unit_test.cpp /// @~english /// @brief unit test /// @~ /// @authors Harry Oh (harry.oh@udptechnology.com) /// @copyright UDP Technology /////////////////////////////////////////////////////////////////////////////// #include <string> #include <stdlib.h> // NOLINT(build/include_order) #include "cppunit/extensions/HelperMacros.h" #include "cgibase.hpp" /////////////////////////////////////////////////////////////////////////////// namespace udp { namespace cgi { /////////////////////////////////////////////////////////////////////////////// /** * @~english * A unit test class for the udp::cgi::CGIBaseTest class */ class CGIBaseTest : public CPPUNIT_NS::TestCase { /// @cond CPPUNIT_TEST_SUITE(CGIBaseTest); CPPUNIT_TEST(InitCheck); CPPUNIT_TEST(BasicCheck); // CPPUNIT_TEST(ExecptionCheck); // CPPUNIT_TEST(BoundaryCheck); CPPUNIT_TEST_SUITE_END(); /// @endcond public: /* tests */ /** * @test Init Cgibase testing */ void InitCheck() { std::string querystring = "action=read&group=A"; std::string uri(static_cast<std::string>(__FILE__)); uri += "?"; uri += querystring; setenv("QUERY_STRING", querystring.c_str(), true); setenv("REQUEST_METHOD", "GET", true); setenv("REQUEST_URI", uri.c_str(), true); CGIBase cgiall(CGIBase::kMethodAll); CPPUNIT_ASSERT(cgiall.GetValue("action") == "read"); CPPUNIT_ASSERT(cgiall.GetValue("group") == "A"); CGIBase cgipost(CGIBase::kMethodPost); CPPUNIT_ASSERT(cgipost.GetValue("action").empty()); CPPUNIT_ASSERT(cgipost.GetValue("group").empty()); CGIBase cgi(querystring); CPPUNIT_ASSERT(cgi.GetValue("action") == "read"); CPPUNIT_ASSERT(cgi.GetValue("group") == "A"); // CGIBase copycgi = cgi; // CPPUNIT_ASSERT(copycgi.GetValue("action") == cgi.GetValue("action")); // CPPUNIT_ASSERT(copycgi.GetValue("group") == cgi.GetValue("group")); } /** * Check Basic feature */ void BasicCheck() { CGIBase cgi("action=list&group=A&group=B&group=C"); CPPUNIT_ASSERT(cgi.GetValue("action") == "list"); CPPUNIT_ASSERT(cgi.GetValue("group") == "A"); int i = 0; std::string group[] = {"A", "B", "C"}; CGIBase::EntryList entrylist = cgi.GetValues("group"); CGIBase::EntryList::iterator iter; for (iter = entrylist.begin(); iter != entrylist.end(); ++iter) { CPPUNIT_ASSERT(iter->second == group[i++]); } CPPUNIT_ASSERT(cgi.SearchEntry("action") == TRUE); CPPUNIT_ASSERT(cgi.SearchEntry("group") == TRUE); CPPUNIT_ASSERT(cgi.SearchEntry("options") == FALSE); // Check Header CPPUNIT_ASSERT(cgi.GetHeaderContentType() == "text/plain"); CPPUNIT_ASSERT(cgi.GetHeaderCharset() == "utf-8"); CPPUNIT_ASSERT(cgi.GetHeaderStatus() == 200); cgi.SetHeaderContentType("text/html"); cgi.SetHeaderCharset("euc-kr"); cgi.SetHeaderStatus(500); CPPUNIT_ASSERT(cgi.GetHeaderContentType() == "text/html"); CPPUNIT_ASSERT(cgi.GetHeaderCharset() == "euc-kr"); CPPUNIT_ASSERT(cgi.GetHeaderStatus() == 500); } /** * Check Exception */ void ExecptionCheck() { } /** * Check Boundary */ void BoundaryCheck() { } }; /////////////////////////////////////////////////////////////////////////////// } // namespace cgi } // namespace udp /////////////////////////////////////////////////////////////////////////////// /// @cond CPPUNIT_TEST_SUITE_REGISTRATION(udp::cgi::CGIBaseTest); /// @endcond
#include "Person.h" #include <iterator> unsigned int Person::myNoOfPeople ; Person::Person() { } Person::Person(std::string name, unsigned int no) { myNoOfPeople++; myName = name; myNo = no; } Person::~Person() { } void Person::addValidBill(Own_bill_format) { } void Person::printBills() { for (int i = 0; i < myBill_count; i++) { mybill_list[i]->printBill(); } } void Person::printledger() { // print map std::map <std::string, float> ::iterator itr; std::cout << "Person"; for (itr = myPersonal_ledger_map.begin(); itr != myPersonal_ledger_map.end(); itr++ ) { std::cout << "\t" <<itr->first; } std::cout << "\n"; std::cout << myName; for (itr = myPersonal_ledger_map.begin(); itr != myPersonal_ledger_map.end(); itr++) { std::cout << "\t" << itr->second; } std::cout << "\n"; } void Person::addValidBill(Group_bill_format *group_bill) { if (group_bill->getNoOfPeople() <= PERSON_MAX_NUMBER_OF_PEOPLE) { // add to the bill list mybill_list[myBill_count] = group_bill; //increment the bill count myBill_count++; //create a namelist pointer std::string name; name = group_bill->getName(0); float moneyToBeCollect; if (group_bill->getisOwenerInside() ) { moneyToBeCollect = group_bill->getAmount() / group_bill->getNoOfPeople(); } else { moneyToBeCollect = group_bill->getAmount() / (group_bill->getNoOfPeople() - 1); } // calculate the person bill state //check if he is the owner if (myName == group_bill->getName()) { // Owner situation //momney to be colloct is positive //loop for every debtors for (int i = 1; i < group_bill->getNoOfPeople(); i++) { if (myPersonal_ledger_map[group_bill->getName(i)]) { //when this debter exist myPersonal_ledger_map[group_bill->getName(i)] += moneyToBeCollect; } else {// when he is not exist myPersonal_ledger_map[group_bill->getName(i)] = moneyToBeCollect; //myPersonal_bill_map[*(namelist + i)] = moneyToBeCollect; // may have a test if this work } } } else { // Debtor situation moneyToBeCollect = -moneyToBeCollect; //change to negative, since the person is debtor if (myPersonal_ledger_map[group_bill->getName(0)]) { //when this debter exist myPersonal_ledger_map[group_bill->getName(0)] += moneyToBeCollect; } else {// when he is not exist myPersonal_ledger_map[group_bill->getName(0)] = moneyToBeCollect; } } } else{ std::cerr << "The bill contain too many people!!" << std::endl; } }
#include <iostream> using namespace std; int main() { string ism; int a,b,c; c=a+b; string familiya; string manzil; int yosh; string tel; /*cout<< "Assalomu aleykum "<<" pdp acadey kompaniyasiga hush kelibsiz"<<endl; cout<<"ismingizni kiriting; "; cin>>ism; cout<<"familiya: "; cin>>familiya; cout<<"Manziliz: "; cin>>manzil;*/ cout<<"a va b ni kiriting; "; cin>>a>>b; cout<< "c= "<<c; /*cout<<"yoshingiz: "; cin>>yosh; cout<<"telefon raqam: "; cin>> tel; cout<<"hurmatli " <<ism<<" "<<familiya<<" \nhizmmatlarimizdan foydalanganiz uchun rahmat"; cout<<" sizga oq yo'l,biz bn aloqayiz yo'q"*/ ; /*int century; int year; int day; int hour; int minute; int second; char flag; cout<<"inter the century: "; cin>>century; year=century*100; cout<<century<<" century is equal to "<<year<<" years\n"; day=year*365; cout<<year<<" year is equal to "<<day<<" days\n"; hour=day*24; cout<<day<<" days is equal to "<<hour<< " hours\n"; minute=hour*60; cout<<hour<<" hours is equal to "<<minute<<" minutes\n"; second=minute*60; cout<<minute<<" minutes is equal to"<<second<<" seconds\n"; /*cout <<"enter the time "; cin>>hour>>flag>>minute>>flag>>second; cout<<"seconds:"<<hour*3600+minute*60+second; cout<<"\n minutes: "<<hour*60+minute*1+second*0.6;*/ return 0; }
#pragma once #include <iostream> using std::cout; using std::endl; class Contained1 { public: Contained1() { cout << "Contained1 constructor." << endl; } };
#include <iostream> using namespace std; int main() { double h; double w; cout << "Input your height in metres: " << endl; cin >> h; cout << "Input your weight in kg: " << endl; cin >> w; double bmi; bmi = w/(h*h); cout << "Your BMI is " << bmi << endl; }
#include "core\Singularity.Core.h" namespace Singularity { namespace Components { class Behavior : public Singularity::Components::Component { DECLARE_OBJECT_TYPE protected: #pragma region Methods void OnComponentAdded(GameObject* gameObject); void OnComponentRemoved(GameObject* gameObject); #pragma endregion public: #pragma region Constructors and Finalizers Behavior(String name = "") : Component(name) {}; Behavior(String name, BehaviorDelegate* callback) : Component(name) { this->Update.Add(callback); } #pragma endregion #pragma region Variables DelegateHandler Update; #pragma endregion }; } }
// // main.cpp // agecalc // // Created by Ben Rockhold on 2/5/15. // Copyright (c) 2015 Ben Rockhold. All rights reserved. // /* Take month and year of birth, and month and year of the present, and return the age. Do this until receiving an invalid value (0) for month. */ #include <iostream> using namespace std; int calcage(){ cout.setf(ios::fixed,ios::floatfield); cout.precision(2); float birthmonth, birthyear, currentmonth, currentyear, age; cout << "Birth month: "; cin >> birthmonth; if(birthmonth == 0){ cout << "Invalid value (0), terminating.\n"; return 0; } cout << "Birth year: "; cin >> birthyear; cout << "Current month: "; cin >> currentmonth; cout << "Current year: "; cin >> currentyear; age = currentyear-birthyear + (currentmonth-birthmonth)/12; cout << "Your age is " << age << "\n"; return 1; } int main() { int flag; flag = calcage(); while(flag!=0){ flag = calcage(); } return 0; }
#include "cpptools_FileWatcher.hpp" #include "cpptools_Async.hpp" #include "cpptools_Logger.hpp" namespace imog { // ====================================================================== // // ====================================================================== // // w/ default ctor the filewatcher is NOT launced directly // is needed to call "launch()" after define "path" and "callback" // ====================================================================== // FileWatcher::FileWatcher() : m_verbose(false), m_launched(false), m_threadLive(true) {} // ====================================================================== // // ====================================================================== // // w/ param ctor the filewatcher is launced directly // w/o call "launch()" // ====================================================================== // FileWatcher::FileWatcher(const std::string& filepath, const filewatcherFn& callback, bool verbose) : m_verbose(verbose), m_launched(false), m_threadLive(true), m_path(""), m_callback(nullptr) { launch(filepath, callback); } // ====================================================================== // // ====================================================================== // // Destroy the object and kill thread dependent of this object // ====================================================================== // FileWatcher::~FileWatcher() { m_threadLive = false; if (m_verbose) { LOGD("FileWatcher destroyed @ '{}'", m_path); } } // ====================================================================== // // ====================================================================== // // Verify if a file was modified since last time that was loaded // ====================================================================== // bool FileWatcher::fileHasBeenModified() { std::fstream f(m_path); // Get stream as string std::stringstream m_auxContent; m_auxContent << f.rdbuf(); std::string m_auxContentStr = m_auxContent.str(); bool modified = m_refContentStr != m_auxContentStr; // Avoid copy if not needed if (modified) { m_refContentStr = m_auxContentStr; } return modified; } // ====================================================================== // // ====================================================================== // // If file has been modified trigger the stored callback function // ====================================================================== // void FileWatcher::update() { if (fileHasBeenModified()) { std::fstream fs(m_path); m_callback(fs); } } // ====================================================================== // // ====================================================================== // // Launch the thread to active filewatcher // ====================================================================== // bool FileWatcher::launch(const std::string& path, const filewatcherFn& fn) { if (m_launched) { LOGE("FileWatcher already active @ '{}'", m_path); return true; } if (path == "") { LOGE("Undefined path @ FileWatcher"); return false; } if (fn == nullptr) { LOGE("Empty callback @ '{}' FileWatcher", m_path); return false; } m_path = path; m_callback = fn; m_threadLive = true; Async::periodic([]() { return 0.5f; }, &m_threadLive, [&]() { update(); }); m_launched = true; if (m_verbose) { LOGD("FileWatcher created @ '{}'", m_path); } return true; } // ====================================================================== // // ====================================================================== // // Setter for verbose // ====================================================================== // void FileWatcher::verbose(bool newState) { m_verbose = newState; } } // namespace imog
#pragma once #include <BWAPI.h> //#include <BW/Offsets.h> namespace BlackCrow { class BlackCrow; // Draws debug information class Debug { public: Debug(BlackCrow &parent); void onStart(); void drawOnFrame(); bool command(std::string text); double elapsedMs; std::list<double> frameTimeHistory; double highestFrameTime; double highestFrameTimeAgo; bool fastDrawBuildable; private: BlackCrow &bc; bool showBaseInfo; bool showBuildable; bool showManagerInfos; bool showPlacementInfos; bool showBwem; bool showSquadInfo; bool showEnemyUnits; bool showLifeBars; std::string getOnOffString(bool value); void drawBaseInformation(); void drawBuildable(); void drawManagerInfo(); void drawPlacementInfo(); void drawBwem(); void drawSquadInfo(); void drawEnemyUnits(); void drawLifeBars(); void drawFrameTimeDisplay(); }; }
/***** 描述 菲波那契数列是指这样的数列: 数列的第一个和第二个数都为1,接下来每个数都等于前面2个数之和。 给出一个正整数a,要求菲波那契数列中第a个数是多少。 关于输入 第1行是测试数据的组数n,后面跟着n行输入。每组测试数据占1行,包括一个正整数a(1 <= a <= 20) 关于输出 n行,每行输出对应一个输入。输出应是一个正整数,为菲波那契数列中第a个数的大小 例子输入 4 5 2 19 1 例子输出 5 1 4181 1 提示 可用数组实现 *****/ #include <iostream> using namespace std; #define MAX_N 100 int main() { int fib[MAX_N] = {1, 1}, n_fib = 2, n = 0, idx = 0; cin >> n; for (int i = 0; i < n; i++) { cin >> idx; if (idx > n_fib) for (int j = n_fib; j < idx; j++) fib[j] = fib[j-1] + fib[j-2]; cout << fib[idx-1] << endl; } return 0; }
#include<bits/stdc++.h> using namespace std; int n,m; int a[1010][1010]; bool vis[1010][1010]; int dx[4] = {0,-1,0,1}; int dy[4] = {1,0,-1,0}; void dfs(int val,int y,int x){ if(vis[y][x]) return; if(x<=0||x>m||y<=0||y>n) return; vis[y][x] = 1; for(int i=0;i<4;i++){ int xx = dx[i]+x; int yy = dy[i]+y; if(a[yy][xx]-a[y][x]<=val) dfs(val,yy,xx); } } int main(){ scanf("%d %d",&n,&m); for(int i=1;i<=n;i++) for(int j=1;j<=m;j++) scanf("%d",&a[i][j]); int s = 0, e = 1e9; while(s<e){ int mid = (s+e)/2; for(int i=1;i<=n;i++) for(int j=1;j<=m;j++) vis[i][j] = 0; dfs(mid,1,1); if(vis[n][m]) e = mid; else s = mid + 1; } printf("%d",s); }
#include<cstdio> #include<iostream> #include<algorithm> using namespace std; int a[1005]; int main() { int n; while(~scanf("%d",&n)) { for(int i = 0; i < n; i++) cin >> a[i]; int m=1,sum=0; int max=0; for(int i=1; i<n; i++) { if(a[i]-a[i-1]==1) { m++; if(a[i-1]==1 || a[i] == 1000) { m++; } if(i==n-1) { sum=sum+m-2>0?m-2:0; max=max>sum?max:sum; } } else { sum=sum+m-2>0?m-2:0; m=1; max=max>sum?max:sum; sum=0; } } cout << max << endl; } return 0; }
/* * * Copyright (c) Karl Meerbergen & Kresimir Fresl 2003 * * Distributed under the Boost Software License, Version 1.0. * (See accompanying file LICENSE_1_0.txt or copy at * http://www.boost.org/LICENSE_1_0.txt) * * KF acknowledges the support of the Faculty of Civil Engineering, * University of Zagreb, Croatia. * */ #ifndef BOOST_NUMERIC_BINDINGS_LAPACK_WORKSPACE_HPP #define BOOST_NUMERIC_BINDINGS_LAPACK_WORKSPACE_HPP #include <boost/numeric/bindings/traits/detail/array_impl.hpp> #include <boost/numeric/bindings/traits/type.hpp> #include <boost/numeric/bindings/traits/type_traits.hpp> #include <boost/numeric/bindings/traits/vector_traits.hpp> #include <memory> namespace boost { namespace numeric { namespace bindings { /* * Organization of workspace in Lapack. * We allow one of the following arguments in a number of Lapack functions * - minimal_workspace() : the function allocates the minimum workspace required for the function * - optimal_workspace() : the function allocates the amount of workspace that allows optimal * execution. * - workspace( work ) : the function uses the workspace array in work. * - workspace( rwork, work ) : the function uses a real array rwork and a compolex array work as * workspace. (There are Lapack functions for complex matrices * that require two workarrays) * */ namespace lapack { // Four classes are introduced to distinguish between the different type of memory allocations struct minimal_workspace {} ; struct optimal_workspace {} ; namespace detail { template <typename W> class workspace1 { public: workspace1(W& w) : w_( w ) {} public: typedef typename traits::vector_traits<W>::value_type value_type ; W& select( value_type const& ) { return w_ ; } private: W& w_ ; }; // struct workspace1 template <typename W, typename WRI> class workspace2 { public: workspace2(W& w, WRI& wri) : w_(w) , wri_(wri) {} public: typedef typename traits::vector_traits<W>::value_type w_value_type ; W& select( w_value_type const& ) { return w_ ; } typedef typename traits::vector_traits<WRI>::value_type wri_value_type ; WRI& select( wri_value_type const& ) { return wri_ ; } private: W& w_ ; WRI& wri_ ; }; // struct workspace2 template <typename W, typename WR, typename WI> class workspace3 { public: workspace3(W& w, WR& wr, WI& wi) : w_(w) , wr_(wr) , wi_(wi) {} public: typedef typename traits::vector_traits<W>::value_type w_value_type ; W& select( w_value_type const& ) { return w_ ; } typedef typename traits::vector_traits<WR>::value_type wr_value_type ; WR& select( wr_value_type const& ) { return wr_ ; } typedef typename traits::vector_traits<WI>::value_type wi_value_type ; WI& select( wi_value_type const& ) { return wi_ ; } private: W& w_ ; WR& wr_ ; WI& wi_ ; }; // struct workspace3 template <typename W, typename WR, typename WI, typename WB> class workspace4 { public: workspace4(W& w, WR& wr, WI& wi, WB& wb) : w_(w) , wr_(wr) , wi_(wi) , wb_(wb) {} public: typedef typename traits::vector_traits<W>::value_type w_value_type ; W& select( w_value_type const& ) { return w_ ; } typedef typename traits::vector_traits<WR>::value_type wr_value_type ; WR& select( wr_value_type const& ) { return wr_ ; } typedef typename traits::vector_traits<WI>::value_type wi_value_type ; WI& select( wi_value_type const& ) { return wi_ ; } typedef typename traits::vector_traits<WB>::value_type wb_value_type ; WB& select( wb_value_type const& ) { return wb_ ; } private: W& w_ ; WR& wr_ ; WI& wi_ ; WB& wb_ ; }; // struct workspace4 } template <typename W> detail::workspace1<W> workspace(W& w) { return detail::workspace1<W>(w) ; } // workspace() // // Two situations: // Real valued: workspace( real array, integer array ) // Complex valued: workspace( complex array, real array ) // template <typename W, typename WRI> detail::workspace2<W,WRI> workspace(W& w, WRI& wri) { return detail::workspace2<W,WRI>(w, wri) ; } // workspace() // // Complex valued: workspace( complex array, real array, integer array ) // template <typename W, typename WR, typename WI> detail::workspace3<W,WR,WI> workspace(W& w, WR& wr, WI& wi) { return detail::workspace3<W,WR,WI>(w, wr, wi) ; } // workspace() // // Complex valued: workspace( complex array, real array, integer array, bool array ) // template <typename W, typename WR, typename WI, typename WB> detail::workspace4<W,WR,WI,WB> workspace(W& w, WR& wr, WI& wi, WB& wb) { return detail::workspace4<W,WR,WI,WB>(w, wr, wi, wb) ; } // workspace() /// Select the number of workspaces depending on the value_type template <typename T> struct n_workspace_args { }; template <> struct n_workspace_args< float > { static const int value = 1 ; }; template <> struct n_workspace_args< double > { static const int value = 1 ; }; template <> struct n_workspace_args< traits::complex_f > { static const int value = 2 ; }; template <> struct n_workspace_args< traits::complex_d > { static const int value = 2 ; }; } }}} #endif
#if !defined(PHONE_NUMBER_H) #define PHONE_NUMBER_H #include <string> #include <iostream> #include <stdexcept> namespace phone_number { class phone_number { std::string digits = ""; std::string _area_digits = ""; std::string _number_digits = ""; void _area_code(); void _number(); public: phone_number(std::string); std::string number(); std::string area_code(); operator std::string() const; }; } // namespace phone_number #endif // PHONE_NUMBER_H
#include <stdinclude.hpp> namespace { const char* SteamAPI_GetSteamInstallPath() { static std::string install_path {}; if (!install_path.empty()) { return install_path.data(); } HKEY reg_key; if (RegOpenKeyExA(HKEY_LOCAL_MACHINE, "Software\\WOW6432Node\\Valve\\Steam", 0, KEY_QUERY_VALUE, &reg_key) == ERROR_SUCCESS) { char path[MAX_PATH] = {0}; DWORD length = sizeof(path); RegQueryValueExA(reg_key, "InstallPath", nullptr, nullptr, reinterpret_cast<BYTE*>(path), &length); RegCloseKey(reg_key); install_path = path; } return install_path.data(); } HMODULE steam_overlay_module, steam_client_module; void load_client() { const std::filesystem::path steam_path = SteamAPI_GetSteamInstallPath(); if (steam_path.empty()) return; LoadLibrary((steam_path / "tier0_s64.dll").string().data()); LoadLibrary((steam_path / "vstdlib_s64.dll").string().data()); steam_overlay_module = LoadLibrary((steam_path / "gameoverlayrenderer64.dll").string().data()); steam_client_module = LoadLibrary((steam_path / "steamclient64.dll").string().data()); if (!steam_client_module) return; } }
// This file contains the common code every implementation uses for stage2 // It is intended to be included multiple times and compiled multiple times // We assume the file in which it is include already includes // "simdjson/stage2.h" (this simplifies amalgation) #include "generic/stage2/tape_writer.h" #include "generic/stage2/logger.h" #include "generic/stage2/atomparsing.h" #include "generic/stage2/structural_iterator.h" namespace { // Make everything here private namespace SIMDJSON_IMPLEMENTATION { namespace stage2 { struct structural_parser : structural_iterator { /** Lets you append to the tape */ tape_writer tape; /** Next write location in the string buf for stage 2 parsing */ uint8_t *current_string_buf_loc; /** Current depth (nested objects and arrays) */ uint32_t depth{0}; // For non-streaming, to pass an explicit 0 as next_structural, which enables optimizations really_inline structural_parser(dom_parser_implementation &_parser, uint32_t start_structural_index) : structural_iterator(_parser, start_structural_index), tape{parser.doc->tape.get()}, current_string_buf_loc{parser.doc->string_buf.get()} { } WARN_UNUSED really_inline error_code start_scope(bool parent_is_array) { parser.containing_scope[depth].tape_index = next_tape_index(); parser.containing_scope[depth].count = 0; tape.skip(); // We don't actually *write* the start element until the end. parser.is_array[depth] = parent_is_array; depth++; if (depth >= parser.max_depth()) { log_error("Exceeded max depth!"); return DEPTH_ERROR; } return SUCCESS; } WARN_UNUSED really_inline error_code start_document() { log_start_value("document"); return start_scope(false); } WARN_UNUSED really_inline error_code start_object(bool parent_is_array) { log_start_value("object"); return start_scope(parent_is_array); } WARN_UNUSED really_inline error_code start_array(bool parent_is_array) { log_start_value("array"); return start_scope(parent_is_array); } // this function is responsible for annotating the start of the scope really_inline void end_scope(internal::tape_type start, internal::tape_type end) noexcept { depth--; // write our doc->tape location to the header scope // The root scope gets written *at* the previous location. tape.append(parser.containing_scope[depth].tape_index, end); // count can overflow if it exceeds 24 bits... so we saturate // the convention being that a cnt of 0xffffff or more is undetermined in value (>= 0xffffff). const uint32_t start_tape_index = parser.containing_scope[depth].tape_index; const uint32_t count = parser.containing_scope[depth].count; const uint32_t cntsat = count > 0xFFFFFF ? 0xFFFFFF : count; // This is a load and an OR. It would be possible to just write once at doc->tape[d.tape_index] tape_writer::write(parser.doc->tape[start_tape_index], next_tape_index() | (uint64_t(cntsat) << 32), start); } really_inline uint32_t next_tape_index() { return uint32_t(tape.next_tape_loc - parser.doc->tape.get()); } really_inline void end_object() { log_end_value("object"); end_scope(internal::tape_type::START_OBJECT, internal::tape_type::END_OBJECT); } really_inline void end_array() { log_end_value("array"); end_scope(internal::tape_type::START_ARRAY, internal::tape_type::END_ARRAY); } really_inline void end_document() { log_end_value("document"); end_scope(internal::tape_type::ROOT, internal::tape_type::ROOT); } // increment_count increments the count of keys in an object or values in an array. // Note that if you are at the level of the values or elements, the count // must be increment in the preceding depth (depth-1) where the array or // the object resides. really_inline void increment_count() { parser.containing_scope[depth - 1].count++; // we have a key value pair in the object at parser.depth - 1 } really_inline uint8_t *on_start_string() noexcept { // we advance the point, accounting for the fact that we have a NULL termination tape.append(current_string_buf_loc - parser.doc->string_buf.get(), internal::tape_type::STRING); return current_string_buf_loc + sizeof(uint32_t); } really_inline void on_end_string(uint8_t *dst) noexcept { uint32_t str_length = uint32_t(dst - (current_string_buf_loc + sizeof(uint32_t))); // TODO check for overflow in case someone has a crazy string (>=4GB?) // But only add the overflow check when the document itself exceeds 4GB // Currently unneeded because we refuse to parse docs larger or equal to 4GB. memcpy(current_string_buf_loc, &str_length, sizeof(uint32_t)); // NULL termination is still handy if you expect all your strings to // be NULL terminated? It comes at a small cost *dst = 0; current_string_buf_loc = dst + 1; } WARN_UNUSED really_inline error_code parse_string(bool key = false) { log_value(key ? "key" : "string"); uint8_t *dst = on_start_string(); dst = stringparsing::parse_string(current(), dst); if (dst == nullptr) { log_error("Invalid escape in string"); return STRING_ERROR; } on_end_string(dst); return SUCCESS; } WARN_UNUSED really_inline error_code parse_number(const uint8_t *src) { log_value("number"); if (!numberparsing::parse_number(src, tape)) { log_error("Invalid number"); return NUMBER_ERROR; } return SUCCESS; } WARN_UNUSED really_inline error_code parse_number() { return parse_number(current()); } really_inline error_code parse_root_number() { /** * We need to make a copy to make sure that the string is space terminated. * This is not about padding the input, which should already padded up * to len + SIMDJSON_PADDING. However, we have no control at this stage * on how the padding was done. What if the input string was padded with nulls? * It is quite common for an input string to have an extra null character (C string). * We do not want to allow 9\0 (where \0 is the null character) inside a JSON * document, but the string "9\0" by itself is fine. So we make a copy and * pad the input with spaces when we know that there is just one input element. * This copy is relatively expensive, but it will almost never be called in * practice unless you are in the strange scenario where you have many JSON * documents made of single atoms. */ uint8_t *copy = static_cast<uint8_t *>(malloc(parser.len + SIMDJSON_PADDING)); if (copy == nullptr) { return MEMALLOC; } memcpy(copy, buf, parser.len); memset(copy + parser.len, ' ', SIMDJSON_PADDING); size_t idx = *current_structural; error_code error = parse_number(&copy[idx]); // parse_number does not throw free(copy); return error; } WARN_UNUSED really_inline error_code parse_true_atom() { log_value("true"); if (!atomparsing::is_valid_true_atom(current())) { return T_ATOM_ERROR; } tape.append(0, internal::tape_type::TRUE_VALUE); return SUCCESS; } WARN_UNUSED really_inline error_code parse_root_true_atom() { log_value("true"); if (!atomparsing::is_valid_true_atom(current(), remaining_len())) { return T_ATOM_ERROR; } tape.append(0, internal::tape_type::TRUE_VALUE); return SUCCESS; } WARN_UNUSED really_inline error_code parse_false_atom() { log_value("false"); if (!atomparsing::is_valid_false_atom(current())) { return F_ATOM_ERROR; } tape.append(0, internal::tape_type::FALSE_VALUE); return SUCCESS; } WARN_UNUSED really_inline error_code parse_root_false_atom() { log_value("false"); if (!atomparsing::is_valid_false_atom(current(), remaining_len())) { return F_ATOM_ERROR; } tape.append(0, internal::tape_type::FALSE_VALUE); return SUCCESS; } WARN_UNUSED really_inline error_code parse_null_atom() { log_value("null"); if (!atomparsing::is_valid_null_atom(current())) { return N_ATOM_ERROR; } tape.append(0, internal::tape_type::NULL_VALUE); return SUCCESS; } WARN_UNUSED really_inline error_code parse_root_null_atom() { log_value("null"); if (!atomparsing::is_valid_null_atom(current(), remaining_len())) { return N_ATOM_ERROR; } tape.append(0, internal::tape_type::NULL_VALUE); return SUCCESS; } WARN_UNUSED really_inline error_code finish() { end_document(); parser.next_structural_index = uint32_t(current_structural + 1 - &parser.structural_indexes[0]); if (depth != 0) { log_error("Unclosed objects or arrays!"); return TAPE_ERROR; } return SUCCESS; } really_inline void init() { log_start(); } WARN_UNUSED really_inline error_code start() { // If there are no structurals left, return EMPTY if (at_end(parser.n_structural_indexes)) { return EMPTY; } init(); // Push the root scope (there is always at least one scope) return start_document(); } really_inline void log_value(const char *type) { logger::log_line(*this, "", type, ""); } static really_inline void log_start() { logger::log_start(); } really_inline void log_start_value(const char *type) { logger::log_line(*this, "+", type, ""); if (logger::LOG_ENABLED) { logger::log_depth++; } } really_inline void log_end_value(const char *type) { if (logger::LOG_ENABLED) { logger::log_depth--; } logger::log_line(*this, "-", type, ""); } really_inline void log_error(const char *error) { logger::log_line(*this, "", "ERROR", error); } }; // struct structural_parser #define SIMDJSON_TRY(EXPR) { auto _err = (EXPR); if (_err) { return _err; } } template<bool STREAMING> WARN_UNUSED static really_inline error_code parse_structurals(dom_parser_implementation &dom_parser, dom::document &doc) noexcept { dom_parser.doc = &doc; stage2::structural_parser parser(dom_parser, STREAMING ? dom_parser.next_structural_index : 0); SIMDJSON_TRY( parser.start() ); // // Read first value // switch (parser.current_char()) { case '{': SIMDJSON_TRY( parser.start_object(false) ); goto object_begin; case '[': SIMDJSON_TRY( parser.start_array(false) ); // Make sure the outer array is closed before continuing; otherwise, there are ways we could get // into memory corruption. See https://github.com/simdjson/simdjson/issues/906 if (!STREAMING) { if (parser.buf[dom_parser.structural_indexes[dom_parser.n_structural_indexes - 1]] != ']') { return TAPE_ERROR; } } goto array_begin; case '"': SIMDJSON_TRY( parser.parse_string() ); goto finish; case 't': SIMDJSON_TRY( parser.parse_root_true_atom() ); goto finish; case 'f': SIMDJSON_TRY( parser.parse_root_false_atom() ); goto finish; case 'n': SIMDJSON_TRY( parser.parse_root_null_atom() ); goto finish; case '-': case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': SIMDJSON_TRY( parser.parse_root_number() ); goto finish; default: parser.log_error("Document starts with a non-value character"); return TAPE_ERROR; } // // Object parser states // object_begin: switch (parser.advance_char()) { case '"': { parser.increment_count(); SIMDJSON_TRY( parser.parse_string(true) ); goto object_key_state; } case '}': parser.end_object(); goto scope_end; default: parser.log_error("Object does not start with a key"); return TAPE_ERROR; } object_key_state: if (unlikely( parser.advance_char() != ':' )) { parser.log_error("Missing colon after key in object"); return TAPE_ERROR; } switch (parser.advance_char()) { case '{': SIMDJSON_TRY( parser.start_object(false) ); goto object_begin; case '[': SIMDJSON_TRY( parser.start_array(false) ); goto array_begin; case '"': SIMDJSON_TRY( parser.parse_string() ); break; case 't': SIMDJSON_TRY( parser.parse_true_atom() ); break; case 'f': SIMDJSON_TRY( parser.parse_false_atom() ); break; case 'n': SIMDJSON_TRY( parser.parse_null_atom() ); break; case '-': case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': SIMDJSON_TRY( parser.parse_number() ); break; default: parser.log_error("Non-value found when value was expected!"); return TAPE_ERROR; } object_continue: switch (parser.advance_char()) { case ',': parser.increment_count(); if (unlikely( parser.advance_char() != '"' )) { parser.log_error("Key string missing at beginning of field in object"); return TAPE_ERROR; } SIMDJSON_TRY( parser.parse_string(true) ); goto object_key_state; case '}': parser.end_object(); goto scope_end; default: parser.log_error("No comma between object fields"); return TAPE_ERROR; } scope_end: if (parser.depth == 1) { goto finish; } if (parser.parser.is_array[parser.depth]) { goto array_continue; } goto object_continue; // // Array parser states // array_begin: if (parser.peek_next_char() == ']') { parser.advance_char(); parser.end_array(); goto scope_end; } parser.increment_count(); main_array_switch: switch (parser.advance_char()) { case '{': SIMDJSON_TRY( parser.start_object(true) ); goto object_begin; case '[': SIMDJSON_TRY( parser.start_array(true) ); goto array_begin; case '"': SIMDJSON_TRY( parser.parse_string() ); break; case 't': SIMDJSON_TRY( parser.parse_true_atom() ); break; case 'f': SIMDJSON_TRY( parser.parse_false_atom() ); break; case 'n': SIMDJSON_TRY( parser.parse_null_atom() ); break; case '-': case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': SIMDJSON_TRY( parser.parse_number() ); break; default: parser.log_error("Non-value found when value was expected!"); return TAPE_ERROR; } array_continue: switch (parser.advance_char()) { case ',': parser.increment_count(); goto main_array_switch; case ']': parser.end_array(); goto scope_end; default: parser.log_error("Missing comma between array values"); return TAPE_ERROR; } finish: return parser.finish(); } } // namespace stage2 } // namespace SIMDJSON_IMPLEMENTATION } // unnamed namespace
// // NaturesAttendants.h // Boids // // Created by chenyanjie on 3/31/15. // // #ifndef __Boids__NaturesAttendants__ #define __Boids__NaturesAttendants__ #include "SkillNode.h" class NaturesAttendants : public SkillNode { private: float _heal; float _range; float _duration; float _interval; float _elapse; float _heal_elapse; float _accel; float _init_speed; int _count; cocos2d::Vector<class TimeLimitWanderSpineComponent*> _effects; public: NaturesAttendants(); virtual ~NaturesAttendants(); static NaturesAttendants* create( UnitNode* owner, const cocos2d::ValueMap& data, const cocos2d::ValueMap& params ); virtual bool init( UnitNode* owner, const cocos2d::ValueMap& data, const cocos2d::ValueMap& params ); virtual void updateFrame( float delta ); virtual void begin(); virtual void end(); }; #endif /* defined(__Boids__NaturesAttendants__) */
#include "socket.h" namespace moxu { bool Socket::Close() { #if defined(MOXU_WIN32) int ret = ::closesocket(_handle); #elif defined(MOXU_LINUX)_UNIX int ret = ::close(_handle); #endif _handle = INVALID_SOCKET; return ret != SOCKET_ERROR; } bool Socket::SetNoblock(int flag) { #if defined(MOXU_WIN32) unsigned long noblock = flag; return (::ioctlsocket(_handle, FIONBIO, &noblock) != SOCKET_ERROR); #elif defined(MOXU_LINUX) int arg = ::fcntl(_handle, F_GETFL, 0); if (0 == ul) arg &= ~O_NONBLOCK; else arg |= O_NONBLOCK; return (::fcntl(_handle, F_SETFL, flags) != SOCKET_ERROR); #endif } int Socket::GetErrno() { #if defined(MOXU_WIN32) return WSAGetLastError(); #elif defined(MOXU_LINUX) return errno; #endif } } // namespace moxu
/* Copyright 2017 Istio Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "src/envoy/tcp/mixer/control.h" #include "include/istio/utils/local_attributes.h" #include "src/envoy/utils/mixer_control.h" using ::istio::mixer::v1::Attributes; using ::istio::mixerclient::Statistics; using ::istio::utils::LocalNode; namespace Envoy { namespace Tcp { namespace Mixer { Control::Control(ControlDataSharedPtr control_data, Upstream::ClusterManager& cm, Event::Dispatcher& dispatcher, Runtime::RandomGenerator& random, Stats::Scope& scope, const LocalInfo::LocalInfo& local_info) : control_data_(control_data), dispatcher_(dispatcher), check_client_factory_(Utils::GrpcClientFactoryForCluster( control_data_->config().check_cluster(), cm, scope, dispatcher.timeSource())), report_client_factory_(Utils::GrpcClientFactoryForCluster( control_data_->config().report_cluster(), cm, scope, dispatcher.timeSource())), stats_obj_(dispatcher, control_data_->stats(), control_data_->config() .config_pb() .transport() .stats_update_interval(), [this](Statistics* stat) -> bool { return GetStats(stat); }) { auto& logger = Logger::Registry::getLog(Logger::Id::config); LocalNode local_node; if (!Utils::ExtractNodeInfo(local_info.node(), &local_node)) { ENVOY_LOG_TO_LOGGER( logger, warn, "Missing required node metadata: NODE_UID, NODE_NAMESPACE"); } ::istio::utils::SerializeForwardedAttributes(local_node, &serialized_forward_attributes_); ::istio::control::tcp::Controller::Options options( control_data_->config().config_pb(), local_node); Utils::CreateEnvironment(dispatcher, random, *check_client_factory_, *report_client_factory_, serialized_forward_attributes_, &options.env); controller_ = ::istio::control::tcp::Controller::Create(options); } // Call controller to get statistics. bool Control::GetStats(Statistics* stat) { if (!controller_) { return false; } controller_->GetStatistics(stat); return true; } } // namespace Mixer } // namespace Tcp } // namespace Envoy
#include "Common.h" #include <map> #include <sstream> #include <unordered_map> auto getIngredients(const std::string &str) { auto loc = str.find("contains"); auto ingredientStr = str.substr(0, loc - 2); return getWords(ingredientStr); } auto getAllergins(const std::string &str) { auto loc = str.find("contains"); auto allerginStr = str.substr(loc + 9); allerginStr.pop_back(); return split(allerginStr, ", "); } auto getOccurences(const std::vector<std::string> &lines) { std::unordered_map<std::string, std::vector<std::string>> allerginMap; for (const auto &line : lines) { auto ingredients = getIngredients(line); auto allergins = getAllergins(line); std::sort(std::begin(ingredients), std::end(ingredients)); std::sort(std::begin(allergins), std::end(allergins)); for (const auto allergin : allergins) { auto &e = allerginMap[allergin]; if (e.empty()) { e = ingredients; } else { auto idx = std::set_intersection(std::begin(e), std::end(e), std::begin(ingredients), std::end(ingredients), std::begin(e)); e.resize(idx - std::begin(e)); } } } return allerginMap; } int main() { auto lines = getLines(getFileContents("../input/Day21/input.txt")); auto occurences = getOccurences(lines); auto s1 = 0l; for (const auto &line : lines) { auto ingredients = getIngredients(line); auto allergins = getAllergins(line); for (const auto &ingredient : ingredients) { bool found = false; for (const auto &[allergin, elems] : occurences) { if (std::find(elems.begin(), elems.end(), ingredient) != elems.end()) found = true; } if (!found) s1++; } } std::map<std::string, std::string> valid; while (!occurences.empty()) { auto e = std::vector<std::string>(); auto k = std::string(""); for (auto &[allergin, elems] : occurences) { if (elems.size() == 1) { valid[allergin] = elems.front(); e = elems; k = allergin; } } occurences.erase(k); for (auto &[allergin, elems] : occurences) { auto idx = std::set_difference(std::begin(elems), std::end(elems), std::begin(e), std::end(e), std::begin(elems)); elems.resize(idx - std::begin(elems)); } } std::string s2 = ""; for (const auto &[k, e] : valid) s2 += e + ","; s2.pop_back(); std::cout << s1 << "\n"; std::cout << s2 << "\n"; }
#include "../Include/Window.h" #include "../Include/UI.h" //透视参数 GLfloat xwMin = 0, ywMin = 0, xwMax = 1280, ywMax = 720; GLfloat dnear = 25, dfar = 125; Window::Window(int width, int height, char* title) { glutInitDisplayMode(GLUT_SINGLE | GLUT_RGB); glutInitWindowSize(width, height); glutCreateWindow("test"); xwMax = width; ywMax = height; gluLookAt(50, 50, 50, 50, 50, 0, 0, 1, 0); glClearColor(1, 1, 1, 0); glMatrixMode(GL_MODELVIEW); glMatrixMode(GL_PROJECTION); init(); } void Window::update(int x, int y) { mUI->processInput(x, y); glutReshapeFunc(reshape); } void Window::draw() { // glClear(GL_COLOR_BUFFER_BIT); mUI->show(); } bool Window::isInPaper() { return mUI->isDrawing(); } int Window::getActiveTool() { return mUI->getLastActiveTool(); } int Window::getActiveLineWidth() { return mUI->getLastActiveLineWidth(); } int Window::getActiveColor() { return mUI->getLastActiveColor(); } inline void Window::reshape(int w, int h) { glViewport(0, 0, w, h); //重置画面中心,和一下两个 glMatrixMode()照应使用 glLoadIdentity(); if (w <= (h + xwMax - ywMax)) glOrtho(xwMin, xwMax, ywMin*(GLfloat)(h + xwMax - ywMax) / (GLfloat)w, ywMax*(GLfloat)(h + xwMax - ywMax) / (GLfloat)w, dnear, dfar); else glOrtho(xwMin*(GLfloat)w / (GLfloat)(h + xwMax - ywMax), xwMax*(GLfloat)w / (GLfloat)(h + xwMax - ywMax), ywMin, ywMax, dnear, dfar); } void Window::init() { mUI = new UI; }
/*********************************************************************** created: 7/8/2010 author: Martin Preisler purpose: Defines the interface for the Animation class *************************************************************************/ /*************************************************************************** * Copyright (C) 2004 - 2010 Paul D Turner & The CEGUI Development Team * * 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 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 _CEGUIAnimation_h_ #define _CEGUIAnimation_h_ #include "CEGUI/String.h" #include <vector> #include <map> #if defined(_MSC_VER) # pragma warning(push) # pragma warning(disable : 4251) #endif // Start of CEGUI namespace section namespace CEGUI { /*! \brief Defines an 'animation' class This is definition of Animation. Can be reused multiple times via AnimationInstance class. You can't step this class directly, you have to instantiate it via AnimationManager::instantiateAnimation. AnimationInstance provides means for stepping the animation and applying it to PropertySets. \par Animation itself doesn't contain key frames. It is composed of Affector(s). Each Affector affects one Property. So one Animation can affect multiple properties. \see AnimationInstance, Affector */ class CEGUIEXPORT Animation { public: //! enumerates possible replay modes enum class ReplayMode : int { //! plays the animation just once, then stops PlayOnce, //! loops the animation infinitely Loop, /** infinitely plays the animation forward, when it reaches the end, it * plays it backwards, etc... */ Bounce }; /** internal constructor, please only construct animations via * AnimationManager::createAnimation method */ Animation(const String& name); //! destructor, this destroys all affectors defined inside this animation ~Animation(void); /*! \brief Retrieves name of this Animation definition */ const String& getName() const; /*! \brief Sets the replay mode of this animation */ void setReplayMode(ReplayMode mode); /*! \brief Retrieves the replay mode of this animation */ ReplayMode getReplayMode() const; /*! \brief Sets the duration of this animation */ void setDuration(float duration); /*! \brief Retrieves the duration of this animation */ float getDuration() const; /*! \brief Sets whether this animation auto starts or not \par Auto start means that the animation instances of this definition call Start on themselves once their target is set. */ void setAutoStart(bool autoStart); /*! \brief Retrieves auto start. \see Animation::setAutoStart */ bool getAutoStart() const; /*! \brief Creates a new Affector \see Affector */ Affector* createAffector(void); /*! \brief Creates a new Affector \par This is just a helper, finger saving method. */ Affector* createAffector(const String& targetProperty, const String& interpolator); /*! \brief Destroys given Affector */ void destroyAffector(Affector* affector); /*! \brief Retrieves the Affector at given index */ Affector* getAffectorAtIndex(size_t index) const; /*! \brief Retrieves number of Affectors defined in this Animation */ size_t getNumAffectors(void) const; /*! \brief This defined a new auto subscription. \param eventName the name of the event we want to subscribe to, CEGUI::Window::EventClicked for example \param action is the action that will be invoked on the animation instance if this event is fired \par Auto Subscription does subscribe to event sender (usually target window) of Animation Instance when the event source is set. Usable action strings: - Start - Stop - Pause - Unpause - TogglePause - Finish eventName is the name of the event we want to subscribe to */ void defineAutoSubscription(const String& eventName, const String& action); /*! \brief This undefines previously defined auto subscription. \see Animation::defineAutoSubscription */ void undefineAutoSubscription(const String& eventName, const String& action); /*! \brief This undefines all previously defined auto subscriptions. \see Animation::defineAutoSubscription */ void undefineAllAutoSubscriptions(); /*! \brief Subscribes all auto subscriptions with information from given animation instance \par This is internal method! Only use if you know what you're doing! */ void autoSubscribe(AnimationInstance* instance); bool hasAutoSubscriptions() const { return !d_autoSubscriptions.empty(); } /*! \brief Unsubscribes all auto subscriptions with information from given animation instance \par This is internal method! Only use if you know what you're doing! */ static void autoUnsubscribe(AnimationInstance* instance); /*! \brief Internal method, causes all properties that are used by this animation and it's affectors to be saved \par So their values are still known after they've been affected. */ void savePropertyValues(AnimationInstance* instance); /*! \brief Applies this Animation definition using information from given AnimationInstance \par This is internal method, only use if you know what you're doing! */ void apply(AnimationInstance* instance); /*! \brief Writes an xml representation of this Animation definition to \a out_stream. \param xml_stream Stream where xml data should be output. \param name_override If given, this value overrides the name attribute written to the stream. This is useful when writing out looknfeels */ void writeXMLToStream(XMLSerializer& xml_stream, const String& name_override = "") const; private: //! name of this animation String d_name; //! currently used replay mode ReplayMode d_replayMode; //! duration of animation (in seconds) float d_duration; /** if true, instantiations of this animation call start on themselves when * their target is set */ bool d_autoStart; //! list of affectors defined in this animation std::vector<Affector*> d_affectors; /** holds pairs of 2 strings, the left string is the Event that we will * subscribe to, the right string is the action that will be invoked to the * instance if the event is fired on target window */ std::multimap<String, String> d_autoSubscriptions; }; } // End of CEGUI namespace section #if defined(_MSC_VER) # pragma warning(pop) #endif #endif // end of guard _CEGUIAnimation_h_
#ifndef __LIFEUI_H__ #define __LIFEUI_H__ #include "EmptyObject.h" #include "../../FrameWork/define.h" #define GAP 10 class LifeUI : public EmptyObject { public: LifeUI(GVector2 position, int number); ~LifeUI(); virtual void init(); virtual void update(float deltatime); virtual void draw(LPD3DXSPRITE, Viewport*); virtual void release(); void setLifeNumber(int number); int getLifeNumber(); private: vector<Sprite*> _listIcons; }; #endif // !__LIFEUI_H__
#include <vector> using namespace std; // GCD int gcd(int a, int b) { if (b==0) return a; return gcd(b, a%b); } // extended GCD // solve ax + by = gcd(a,b) when a and b are input int extgcd(int a, int b, int& x, int& y){ int d = a; if (b != 0){ d = extgcd(b, a%b, y, x); y -= (a/b) * x; } else { x = 1; y=0; } return d; } // compute a^-1 (mod m) // ax + my = gcd(a,m) == 1, then, // ax + my = ax = 1 (mod m) int mod_inverse(int a, int m){ int x, y; extgcd(a,m,x,y); return (m + x % m) %m; } // Coalition linear congruence equation // 連立線形合同式 // ai X x = bi (mod mi) // --> solution would be like x = b (mod m) // // x = b1 (mod m1), a X x = b2 (mod m2) ---> x = b (mod m) // (solution) // x = b1 + m1 X t // -> a X (b1 + m1 X t) = b2 (mod m2) // -> a X m1 X t = b2 - a X b1 (mod m2) // (if gcd(m2, a X m1) does not divide (b2 - a X b1), no solution) // return the pair (b, m) pair<int, int> linear_congruence(const vector<int>& A, const vector<int>& B, const vector<int>& M) { // initialize by "valid for all interger" x = 0 (mod 1) int x = 0, m = 1; for (int i=0; i < A.size(); i++){ int a = A[i] * m, b = B[i] - A[i] * x, d = gcd(M[i], a); if (b % d !=0) return make_pair(0, -1); // no solution int t = b / d * mod_inverse(a / d, M[i] / d) % (M[i] / d); x = x + m * t; m *= M[i] / d; } return make_pair(x % m, m); }
#include "head.h" #include "multiplayer.h" #include "Player.hpp" #include "TempoMessage.hpp" #include <unordered_map> #include <thread> #include <experimental/filesystem> int partie(sf::RenderWindow& app, Carte& map, std::unordered_map<int, Player>& joueurs, Protocole& myProto){ int save; bool musicIsOpen(false), restart(false); //Les messages TempoMessage screenMessage; //Musique std::vector<std::string> allMusic; std::experimental::filesystem::directory_iterator myIte("ressources/music/game"); for(auto it = std::experimental::filesystem::begin(myIte), itEnd = std::experimental::filesystem::end(myIte); it != itEnd; ++it) allMusic.push_back(it->path()); //Choix random de la musique sf::Music music; if(!allMusic.empty()){ std::string selectedPath(allMusic[rand()%allMusic.size()]); if(!music.openFromFile(selectedPath)) std::cerr << selectedPath << std::endl; else{ music.setLoop(true); musicIsOpen = true; } } sf::Clock timer_; sf::Clock timer2_; //On lance la musique au début de la partie if(musicIsOpen) music.play(); sf::Event event; map.addaptMap(app); screenMessage.setNewMessage(L"Vous êtes le personnage bleue !", app.getView().getCenter(), 1000); while(app.isOpen()){ while(app.pollEvent(event)){ if(event.type == sf::Event::Closed){ app.close(); return 1; } if(event.type == sf::Event::KeyPressed){ switch(event.key.code){ case sf::Keyboard::Escape : app.setView(app.getDefaultView()); //Solution du pauvre pour s'assurer que tout les thread temporaire ai fini std::this_thread::sleep_for(std::chrono::milliseconds(1100)); return 0; case sf::Keyboard::Return : if(restart) myProto.sendRST(0); break; default: break; } } if (event.type == sf::Event::Resized){ map.addaptMap(app); } } while((save = myProto.duringGame()) > 0){ if(save == 1){ joueurs.at(myProto.tempoNum).setPosition(myProto.tempoX, myProto.tempoY); } else if(save == 2){ map.addBomb(myProto.tempoX, myProto.tempoY, myProto.tempoNum); } else if(save == 3){ map.deleteBomb(myProto.tempoX, myProto.tempoY); } else if(save == 4){ map.breakWall(myProto.buff_ + 4); } else if(save == 5){ map.addBonus(myProto.tempoX, myProto.tempoY, myProto.tempoNum); } else if(save == 6){ map.deleteBonus(myProto.tempoX, myProto.tempoY); } else if(save == 7){ joueurs.at(myProto.tempoX).killed(); if(myProto.tempoX == myProto.tempoY){ screenMessage.setNewMessage(joueurs.at(myProto.tempoY).getWName() + L" en avait marre de la vie :( ", app.getView().getCenter(), 1000); } else{ screenMessage.setNewMessage(joueurs.at(myProto.tempoY).getWName() + L" à fait exploser " + joueurs.at(myProto.tempoX).getWName() + L" !", app.getView().getCenter(), 1000); } } else if(save == 8){ restart = true; if(myProto.tempoNum == -1){ screenMessage.setNewMessage(L"Suicide général ! Personne ne gagne.", app.getView().getCenter(), 3000); } else{ screenMessage.setNewMessage(L"Victoire de " + joueurs.at(myProto.tempoNum).getWName() + L" !", app.getView().getCenter(), 3000); } } else if(save == 9){ app.setView(app.getDefaultView()); music.stop(); return 2; } else if(save == 10){ joueurs.erase(myProto.tempoNum); } } if(save == -1){ app.setView(app.getDefaultView()); //Solution du pauvre pour s'assurer que tout les thread temporaire ai fini std::this_thread::sleep_for(std::chrono::milliseconds(1100)); return 0; } if(timer_.getElapsedTime().asSeconds() > 0.025){ bool stop = false; uint8_t x = 0; if(sf::Keyboard::isKeyPressed(sf::Keyboard::Z)){ x = 1; } if(sf::Keyboard::isKeyPressed(sf::Keyboard::S)){ if(x) stop = true; x = 2; } if(sf::Keyboard::isKeyPressed(sf::Keyboard::Q)){ if(x) stop = true; x = 3; } if(sf::Keyboard::isKeyPressed(sf::Keyboard::D)){ if(x) stop = true; x = 4; } if(!stop){ if(x){ timer_.restart(); myProto.sendMove(x); } } } if(timer2_.getElapsedTime().asSeconds() > 0.025){ if(sf::Keyboard::isKeyPressed(sf::Keyboard::Space)){ timer2_.restart(); myProto.sendBomb(); } } app.clear(sf::Color(21, 108, 153)); map.draw(app); for(auto it(joueurs.begin()), itEnd(joueurs.end()); it != itEnd; ++it){ it->second.draw(app); } screenMessage.draw(app); app.display(); } music.stop(); return 1; }
// C++ for the Windows Runtime vv1.0.170303.6 // Copyright (c) 2017 Microsoft Corporation. All rights reserved. #pragma once #include "../base.h" #include "Windows.Media.ClosedCaptioning.0.h" #include "Windows.UI.0.h" WINRT_EXPORT namespace winrt { namespace ABI::Windows::Media::ClosedCaptioning { struct __declspec(uuid("10aa1f84-cc30-4141-b503-5272289e0c20")) __declspec(novtable) IClosedCaptionPropertiesStatics : Windows::Foundation::IInspectable { virtual HRESULT __stdcall get_FontColor(winrt::Windows::Media::ClosedCaptioning::ClosedCaptionColor * value) = 0; virtual HRESULT __stdcall get_ComputedFontColor(Windows::UI::Color * value) = 0; virtual HRESULT __stdcall get_FontOpacity(winrt::Windows::Media::ClosedCaptioning::ClosedCaptionOpacity * value) = 0; virtual HRESULT __stdcall get_FontSize(winrt::Windows::Media::ClosedCaptioning::ClosedCaptionSize * value) = 0; virtual HRESULT __stdcall get_FontStyle(winrt::Windows::Media::ClosedCaptioning::ClosedCaptionStyle * value) = 0; virtual HRESULT __stdcall get_FontEffect(winrt::Windows::Media::ClosedCaptioning::ClosedCaptionEdgeEffect * value) = 0; virtual HRESULT __stdcall get_BackgroundColor(winrt::Windows::Media::ClosedCaptioning::ClosedCaptionColor * value) = 0; virtual HRESULT __stdcall get_ComputedBackgroundColor(Windows::UI::Color * value) = 0; virtual HRESULT __stdcall get_BackgroundOpacity(winrt::Windows::Media::ClosedCaptioning::ClosedCaptionOpacity * value) = 0; virtual HRESULT __stdcall get_RegionColor(winrt::Windows::Media::ClosedCaptioning::ClosedCaptionColor * value) = 0; virtual HRESULT __stdcall get_ComputedRegionColor(Windows::UI::Color * value) = 0; virtual HRESULT __stdcall get_RegionOpacity(winrt::Windows::Media::ClosedCaptioning::ClosedCaptionOpacity * value) = 0; }; } namespace ABI { } namespace Windows::Media::ClosedCaptioning { template <typename D> struct WINRT_EBO impl_IClosedCaptionPropertiesStatics { Windows::Media::ClosedCaptioning::ClosedCaptionColor FontColor() const; Windows::UI::Color ComputedFontColor() const; Windows::Media::ClosedCaptioning::ClosedCaptionOpacity FontOpacity() const; Windows::Media::ClosedCaptioning::ClosedCaptionSize FontSize() const; Windows::Media::ClosedCaptioning::ClosedCaptionStyle FontStyle() const; Windows::Media::ClosedCaptioning::ClosedCaptionEdgeEffect FontEffect() const; Windows::Media::ClosedCaptioning::ClosedCaptionColor BackgroundColor() const; Windows::UI::Color ComputedBackgroundColor() const; Windows::Media::ClosedCaptioning::ClosedCaptionOpacity BackgroundOpacity() const; Windows::Media::ClosedCaptioning::ClosedCaptionColor RegionColor() const; Windows::UI::Color ComputedRegionColor() const; Windows::Media::ClosedCaptioning::ClosedCaptionOpacity RegionOpacity() const; }; } namespace impl { template <> struct traits<Windows::Media::ClosedCaptioning::IClosedCaptionPropertiesStatics> { using abi = ABI::Windows::Media::ClosedCaptioning::IClosedCaptionPropertiesStatics; template <typename D> using consume = Windows::Media::ClosedCaptioning::impl_IClosedCaptionPropertiesStatics<D>; }; template <> struct traits<Windows::Media::ClosedCaptioning::ClosedCaptionProperties> { static constexpr const wchar_t * name() noexcept { return L"Windows.Media.ClosedCaptioning.ClosedCaptionProperties"; } }; } }
#include "httpendpoint.h" HttpEndpoint::HttpEndpoint(const String &endpoint) : endpoint(endpoint), httpPathDelegate(&HttpEndpoint::requestDispatcher, this) {} HttpEndpoint::~HttpEndpoint() {} const String &HttpEndpoint::getEndpoint() const { return endpoint; } HttpEndpoint::operator const HttpPathDelegate &() const { return httpPathDelegate; } void HttpEndpoint::requestDispatcher(HttpRequest &request, HttpResponse &response) { response.code = HTTP_STATUS_INTERNAL_SERVER_ERROR; bool success = false; switch (request.method) { case HTTP_DELETE: success = requestDelete(request, response); break; case HTTP_GET: success = requestHead(request, response); if (success) success = requestGet(request, response); break; case HTTP_HEAD: success = requestHead(request, response); break; case HTTP_POST: success = requestPost(request, response); break; case HTTP_PUT: success = requestPut(request, response); break; default: success = responseMethodNotAllowed(response); } if (!success) { response.code = HTTP_STATUS_INTERNAL_SERVER_ERROR; } } bool HttpEndpoint::requestDelete(HttpRequest &request, HttpResponse &response) { responseMethodNotAllowed(response); return false; } bool HttpEndpoint::requestGet(HttpRequest &request, HttpResponse &response) { responseMethodNotAllowed(response); return false; } bool HttpEndpoint::requestHead(HttpRequest &request, HttpResponse &response) { responseMethodNotAllowed(response); return false; } bool HttpEndpoint::requestPost(HttpRequest &request, HttpResponse &response) { responseMethodNotAllowed(response); return false; } bool HttpEndpoint::requestPut(HttpRequest &request, HttpResponse &response) { responseMethodNotAllowed(response); return false; } bool HttpEndpoint::responseMethodNotAllowed(HttpResponse &response) { response.code = HTTP_STATUS_METHOD_NOT_ALLOWED; return response.sendString("Method not allowed"); }
#include <stdio.h> int n,m; int skip, save[201][201]; const int num = 1000000001; typedef struct data { char array[201]; int size; }data; int min(long long a,long long b) { if(a<b) return a; else return b; } void func(int arg_1,int arg_2,data output) { if(skip<0) return; if(arg_1 == 0 && arg_2 == 0) { for(int i=0 ;i<output.size;i++) { if(output.array[i] == 0) printf("%c",'-'); else printf("%c",'o'); } printf("\n"); skip-=1; return; } if(save[arg_1+arg_2][arg_1] <= skip) { skip-=save[arg_1+arg_2][arg_1]; return; } if(arg_1 > 0) { output.array[output.size] = 0; output.size +=1; func(arg_1 - 1, arg_2, output); output.size -=1; } if(arg_2 > 0) { output.array[output.size] = 1; output.size +=1; func(arg_1, arg_2 - 1, output); output.size -=1; } } int main() { for(int i=0;i<201;i++) { save[i][0] = 1; save[i][i] = 1; for(int j=1;j<i;++j) save[i][j] = min(num,save[i-1][j-1] + save[i-1][j]); } int c; scanf("%d",&c); while(c--) { scanf("%d %d %d",&n,&m,&skip); skip-=1; data temp; temp.size = 0; func(n,m,temp); } }
#ifndef KEYWORD_SUGGESTION_SERVER_INCLUDE_ONLINE_MESSAGE_H_ #define KEYWORD_SUGGESTION_SERVER_INCLUDE_ONLINE_MESSAGE_H_ namespace keyword_suggestion { struct Message { int len; int id; char content[1024]; }; } // end of namespace keyword_suggestion #endif
/* NIKOLAAS BENDER HOMEWORK 3 FOR DATA STRUCTURES CU BOULDER */ #include <iostream> #include <string> #include <fstream> using namespace std; struct city{ city *next; string cityName; string message; }; //====================================================================== //THIS BUILDS THE DEFAULT NETWROK //THIS WORKS //====================================================================== city *buildNetwork(){ //INITIALIZING EACH CITY BY MAJOR AIRPORT CALL SIGN city *lax = new city; city *phx = new city; city *den = new city; city *dfw = new city; city *stl = new city; city *ord = new city; city *atl = new city; city *dca = new city; city *lga = new city; city *bos = new city; //INITIALIZING EACH CITY NAME lax -> cityName = "Los Angeles"; phx -> cityName = "Phoenix"; den -> cityName = "Denver"; dfw -> cityName = "Dallas"; stl -> cityName = "St. Louis"; ord -> cityName = "Chicago"; atl -> cityName = "Atlanta"; dca -> cityName = "Washington, D.C."; lga -> cityName = "New York"; bos -> cityName = "Boston"; //THIS INITIALIZES THE LINK lax -> next = phx; phx -> next = den; den -> next = dfw; dfw -> next = stl; stl -> next = ord; ord -> next = atl; atl -> next = dca; dca -> next = lga; lga -> next = bos; bos -> next = nullptr; return lax; } //====================================================================== //THIS FINDS A CITY BASED UPON THE NAME OF THE CITY //IT SHOULD WORK //====================================================================== city *fndCty(city *head, string city){ while(head -> cityName != city){ head = head -> next; } return head; } //====================================================================== //THIS SHOULD ADD THE CITY //REALLY IT NEEDS THE CITY FINDER TO FEED INTO IT //THIS WORKS //====================================================================== city *addCity(city *head, city *previous, string ctyName){ //THIS IS THE NEW CITY THAT GETS INSERTED city *nn = new city; //THIS SETS THE CITY NAME nn -> cityName = ctyName; //THIS WORKS FOR INSERTING AT THE END OR THE MIDDLE if(previous != NULL){ //THIS SETS THE NEW CITY TO BE THE NEXT //AS DICTATED BY PREVIOUS nn -> next = previous -> next; //SET PREVIOUS NEXT TO THE NEW CITY previous -> next = nn; }else if(previous == NULL){ nn -> next = head; head = nn; } return head; } //====================================================================== //THIS TRANSMITS THE MESSAGE FROM A FILE //THROUGH THE NETWORKONE STRING AT A TIME //THIS WORKS //====================================================================== void transmitMsg(city *head){ city *tmp = new city; tmp = head; string ss; ifstream mainfile; mainfile.open("messageIn.txt"); if(mainfile.is_open()){ while(mainfile >> ss){ while(tmp -> next != nullptr){ tmp -> message = ss; cout << tmp -> cityName << " received " << tmp -> message << endl; tmp = tmp -> next; } tmp -> message = ss; cout << tmp -> cityName << " received " << tmp -> message << endl; tmp = head; } } mainfile.close(); } //====================================================================== //THIS PRINTS THE WHOLE PATH //THIS WORKS //====================================================================== void printPath(city *head){ cout << "===CURRENT PATH===" << endl; while(head != nullptr){ cout << head -> cityName << " -> "; head = head -> next; } cout << " NULL" << endl; cout << "==================" << endl; } //====================================================================== //THIS IS THE MENU THAT THE USER USES //====================================================================== int menu(){ cout << "======Main Menu======" << endl << "1. Build Network" << endl << "2. Print Network Path" << endl << "3. Transmit Message Coast-To-Coast" << endl << "4. Add City"<< endl << "5. Quit" << endl; int n; cin >> n; return n; } int main(){ int o = 0; //THIS SETS UP THE HEAD city *head; //THIS IS THE OPTIONS MENU while(o >= 0 && o <= 4){ //THIS RESETS o FOR EACH TIME IT GETS USED o = 0; //THIS TAKES THE OPTION SELECTED FROM MENU o = menu(); //BUILD NETWORK if(o == 1){ head = buildNetwork(); o = 0; } //PRINT NETWORK if(o == 2){ printPath(head); o = 0; } //TRANSMIT MESSAGE if(o == 3){ transmitMsg(head); o = 0; } //ADDS A CITY if(o == 4){ cout << "Enter a City name:" << endl; string nc; cin >> nc; cout << "Enter a previous City name:" << endl; string prev; cin >> prev; head = addCity(head, fndCty(head, prev), nc); o = 0; } //ERROR if(o > 5){ cout << "PLEASE ENTER THE NUMBER OF THE OPTION YOU WANT " << o << " IS NOT A VALID OPTION" << endl; o = 0; } } cout << "Goodbye!" << endl; }
//************************************************************************************************************/ //---------------- VMA209 measuring temperature by using input A4 --------------------------------------------/ //--- ATTENTION -- The symbol on the PCB is for sensor 18B20 !! If using LM35 it has to be upside down !! ----/ //---------------- CHECK THE POLARITY FIRST !!! --------------------------------------------------------------/ //************************************************************************************************************/ #define LM35 A4 int val = 0; // initialising variable val with value 0 float temp = 0; // initialising variable temp as floating point void setup() { Serial.begin(9600); // set the baudrate to 9600 } void loop() { val = analogRead(LM35); // read the value of A4 temp = val * 0.48876; // eventual correction factor Serial.print("LM35 = "); Serial.println(temp); // print the value to the serial monitor delay(1000); // wait one second for the next measurement }
#include <cstdio> #include "exception.h" static const char * __err_table[] = { "³É¹¦", }; CGPSException::CGPSException(unsigned int errvalue) : m_value(errvalue) { } unsigned int CGPSException::ErrId() { return m_value; } const char * CGPSException::ErrDesc() { if(m_value < 0) { return NULL; } if(m_value >= sizeof(__err_table)/sizeof(char *)) { return NULL; } return __err_table[m_value]; }
#include "model.h" #include "objReader.h" #include "texture.h" #include "Utilities.h" #include "Renderer.h" #include "Scene.h" #include "Game.h" #include "ShaderReader.h" #include "GLFW/glfw3.h" #include <iostream> #include "Maths.h" float getRandom(float min, float max) { return ((((float)rand()) / (float)RAND_MAX) * (max - min)) + min; } int main() { Game::initializeOpenGL(800, 600, "test"); /* Example testing setup "Monkey Dimension" */ Scene testScene; Game::currentScene = &testScene; Camera cam; Game::currentCamera = &cam; Controls contr; Game::currentControls = &contr; Renderer::viewMatrix = Maths::mat4(); Renderer::projectionMatrix = Maths::mat4::perspective(0.785398f, 1.25f, 0.1f, 10000.0f); ShaderReader::readShader(ShaderReader::shaderType::vertex, "Resources\\shaderA_vertex.shader"); ShaderReader::readShader(ShaderReader::shaderType::fragment, "Resources\\shaderA_frag.shader"); ShaderReader::linkShaders(ShaderReader::vertexShaders[0], ShaderReader::fragmentShaders[0]); /* Monkey models setup */ Model testModel("Resources\\untitled.obj"); Texture testTexture("Resources\\monke.png"); Entity testEntity; testEntity.models.push_back(&testModel); testEntity.texturesMap.insert(std::make_pair(0, std::vector<Texture*>{&testTexture})); testEntity.modelMatrixMap.insert(std::make_pair(0, std::vector<Maths::mat4>())); int testMonkeyCount = 300; float spread = 50.0f; float velocity = 0.01f; std::vector<Maths::vec3> monkeysMovementDirection; std::vector<Maths::vec3> monkeysRotationAxis; for (int i = 0; i < testMonkeyCount; i++) { Maths::mat4 testMatrix; float f = getRandom(0.7f, 1.5f); testMatrix *= Maths::mat4::translation(Maths::vec3(getRandom(-spread, spread), getRandom(-spread, spread), getRandom(-spread, spread))); testMatrix *= Maths::mat4::rotation(getRandom(0.0f, 6.28f), Maths::vec3(getRandom(0.0f, 1.0f), getRandom(0.0f, 1.0f), getRandom(0.0f, 1.0f))); testMatrix *= Maths::mat4::scale(Maths::vec3(f, f, f)); testEntity.modelMatrixMap[0].push_back(testMatrix); monkeysRotationAxis.push_back(Maths::vec3(getRandom(0.0f, 1.0f), getRandom(0.0f, 1.0f), getRandom(0.0f, 1.0f))); monkeysMovementDirection.push_back(Maths::vec3(getRandom(0.0f, 1.0f), getRandom(0.0f, 1.0f), getRandom(0.0f, 1.0f))); } Game::currentScene->entities.push_back(&testEntity); Renderer::createRender(&testEntity, 0); /* Sun setup */ Model testModel2("Resources\\sun.obj"); Texture testTexture2("Resources\\sun_texture.png"); Entity testEntity2; testEntity2.models.push_back(&testModel2); testEntity2.texturesMap.insert(std::make_pair(0, std::vector<Texture*>{&testTexture2})); testEntity2.modelMatrixMap.insert(std::make_pair(0, std::vector<Maths::mat4>({ Maths::mat4() }))); float sunVelocity = 0.01f; Maths::vec3 sunMovementDirection(getRandom(0.0f, 1.0f), getRandom(0.0f, 1.0f), getRandom(0.0f, 1.0f)); Maths::vec3 sunPosition(0.0f); Game::currentScene->entities.push_back(&testEntity2); Renderer::createRender(&testEntity2, 0); /* Setup monkeys movement timer */ int movementTimer = 0; int movementReset = 500; while (!glfwWindowShouldClose(Game::currentWindow)) { //Reset directions movementTimer++; if (movementTimer > movementReset) { movementTimer = 0; sunMovementDirection = Maths::vec3(getRandom(0.0f, 1.0f), getRandom(0.0f, 1.0f), getRandom(0.0f, 1.0f)); for (int i = 0; i < testMonkeyCount; i++) { monkeysMovementDirection[i] = Maths::vec3(getRandom(0.0f, 1.0f), getRandom(0.0f, 1.0f), getRandom(0.0f, 1.0f)); monkeysRotationAxis[i] = Maths::vec3(getRandom(0.0f, 1.0f), getRandom(0.0f, 1.0f), getRandom(0.0f, 1.0f)); } } //Move the sun sunPosition += sunMovementDirection * sunVelocity; Maths::mat4 newSunMatrix = Maths::mat4::translation(sunPosition); Renderer::updateEntityMatrixOrientation(Renderer::action::swap, &testEntity2, 0, std::vector<unsigned int>({ 0 }), std::vector<Maths::mat4>({ newSunMatrix })); Renderer::lightPositionTest = sunPosition; //Move the monkeys for (int i = 0; i < testMonkeyCount; i++) { Maths::mat4 newMonkeyMatrix = testEntity.modelMatrixMap[0][i]; newMonkeyMatrix *= Maths::mat4::translation(monkeysMovementDirection[i] * velocity); newMonkeyMatrix *= Maths::mat4::rotation(0.006f, monkeysRotationAxis[i]); Renderer::updateEntityMatrixOrientation(Renderer::action::swap, &testEntity, 0, std::vector<unsigned int>({ (unsigned int)i }), std::vector<Maths::mat4>({ newMonkeyMatrix })); } Game::loop(); } glfwTerminate(); return 0; }
// // internal_buffer.h // str2-local // // Created by xiazhou on 10/22/13. // Copyright (c) 2013 xiazhou. All rights reserved. // #ifndef str2_local_internal_buffer_h #define str2_local_internal_buffer_h enum BUFFER_STATUS{ CORRUPTED, EMPTY, USING, FULL }; static const int BUFFER_SIZE = 1024 * 1024; class InternalBuffer { public: InternalBuffer():first(0), pos(0), length(0), current_status(CORRUPTED), next(0){}; ~InternalBuffer(); int init();//init will allocate memory int clear(); int write(const char*, int length); char* data(); int set_status(BUFFER_STATUS stat); inline BUFFER_STATUS status(){return current_status;}; inline int size(){return length;}; int set_next(InternalBuffer* next_buffer); InternalBuffer* next; private: char* first; int pos;//next empty place int length; BUFFER_STATUS current_status; //static std::allocator<char> alloc; }; #endif
//This code is used to test the 4 Channel relay connections //void Repeats(){ // Serial.println("15 second timer"); // digitalWrite(WATER_PUMP_PIN, LOW); // digitalWrite(LIGHT_RELAY_PIN, LOW); // digitalWrite(HUM_PIN, LOW); // digitalWrite(led4, LOW); //}
/********************************************************************* Matt Marchant 2014 - 2016 http://trederia.blogspot.com xygine - Zlib license. This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. *********************************************************************/ //base class for ui controls #ifndef XY_UI_CONTROL_HPP_ #define XY_UI_CONTROL_HPP_ #include <xygine/ShaderProperty.hpp> #include <xygine/Config.hpp> #include <SFML/Graphics/Drawable.hpp> #include <SFML/Graphics/Transformable.hpp> #include <memory> namespace sf { class Event; } namespace xy { /*! \brief Controls from which xygine's UI objects are composed */ namespace UI { using Index = std::size_t; enum class Alignment { TopLeft, BottomLeft, Centre, TopRight, BottomRight }; /*! \brief Abstract base class for all UI controls */ class XY_EXPORT_API Control : public sf::Drawable, public sf::Transformable, public ShaderProperty { public: using Ptr = std::shared_ptr<Control>; Control(); virtual ~Control() = default; Control(const Control&) = delete; const Control& operator = (const Control&) = delete; /*! \brief Returns true if this control is selectable When implementing a concrete type this should return true if the control is selectable when navigating controls in a container, else it should return false. */ virtual bool selectable() const = 0; /*! \brief Returns true if the control is currently selected */ bool selected() const; /*! \brief Used to select the control when navigating controls belonging to a Container */ virtual void select(); /*! \brief Used to deselect the control when navigating controls belonging to a Container */ virtual void deselect(); /*! \brief Returns true if the control is currently active. */ virtual bool active() const; /*! \brief Activates the control if it is selected Override this if the control requires any special animation or needsd to call custom callbacks. */ virtual void activate(); /*! \brief Deactivates activated controls */ virtual void deactivate(); /*! \brief Handle input events Must be implemented by concrete types to handle any mouse, keyboard or controller input \param sf::Event Current event structure \param sf::Vector2f current mouse position, in UI space */ virtual void handleEvent(const sf::Event&, const sf::Vector2f&) = 0; /*! \brief Updates the control once per frame Override this when controls require time dependent updates, such as animated textures. */ virtual void update(float dt){}; /*! \brief Allows setting the alignment of the control about its origin This is required for all controls to implement placement for each of the Alignment enum options */ virtual void setAlignment(Alignment) = 0; /*! \brief Returns true if the Control bounds contains the given mouse position in UI space coordinates. This can be optionallay overriden for controls composed of complex shapes. */ virtual bool contains(const sf::Vector2f& mousePos) const; /*! \brief Hide or show the control \param visible If true shows the control, else hides it Hidden controls are neither drawn, nor handle any input events effectively disabling them */ void setVisible(bool visible); /*! \brief Returns true if the control is currently visible, else returns false */ bool visible() const; private: bool m_selected; bool m_active; bool m_visible; Index m_index; }; /*! \brief Utility function for creating controls */ template <typename T, typename... Args> std::shared_ptr<T> create(Args&&... args) { static_assert(std::is_base_of<Control, T>::value, "Must derive from Control class"); return std::move(std::make_shared<T>(std::forward<Args>(args)...)); } } } #endif //XY_UI_CONTROL_H_
#include <windows.h> #include <gl/glut.h> #include <stdio.h> void DoDisplay(); void DoReshape(GLsizei width, GLsizei height); void DoKeyboard(unsigned char key, int x, int y); void DoMenu(int value); GLfloat xAngle, yAngle, zAngle; GLfloat left=-1, right=1, bottom=-1, top=1, Near=-1, Far=1; GLfloat fov = 45; int Projection; int Object; GLsizei lastWidth, lastHeight; int APIENTRY WinMain(HINSTANCE hInstance,HINSTANCE hPrevInstance ,LPSTR lpszCmdParam,int nCmdShow) { glutInitDisplayMode(GLUT_SINGLE | GLUT_RGB | GLUT_DEPTH); glutCreateWindow("OpenGL"); glutDisplayFunc(DoDisplay); glutReshapeFunc(DoReshape); glutKeyboardFunc(DoKeyboard); glutCreateMenu(DoMenu); glutAddMenuEntry("Orthographic",1); glutAddMenuEntry("Frustrum",2); glutAddMenuEntry("Perspective",3); glutAddMenuEntry("Pyramid",4); glutAddMenuEntry("Cylinder",5); glutAttachMenu(GLUT_RIGHT_BUTTON); glEnable(GL_DEPTH_TEST); glutMainLoop(); return 0; } void DoKeyboard(unsigned char key, int x, int y) { switch(key) { case 'a':yAngle += 2;break; case 'd':yAngle -= 2;break; case 'w':xAngle += 2;break; case 's':xAngle -= 2;break; case 'q':zAngle += 2;break; case 'e':zAngle -= 2;break; case 'z':xAngle = yAngle = zAngle = 0.0;break; case 'r':left += 0.1;break; case 'f':left -= 0.1;break; case 't':right += 0.1;break; case 'g':right -= 0.1;break; case 'y':bottom -= 0.1;break; case 'h':bottom += 0.1;break; case 'u':top -= 0.1;break; case 'j':top += 0.1;break; case 'i':Near -= 0.1;break; case 'k':Near += 0.1;break; case 'o':Far -= 0.1;break; case 'l':Far += 0.1;break; case 'p':fov -= 1;break; case ';':fov += 1;break; case 'v':left=-1, right=1, bottom=-1, top=1; if (Projection == 0) { Near=-1, Far=1; } else { Near=1, Far=10; } break; } char info[128]; sprintf(info, "(%.0f,%.0f,%.0f)" "(%.1f,%.1f,%.1f,%.1f,%.1f,%.1f)", xAngle, yAngle, zAngle, left, right, bottom, top, Near, Far); glutSetWindowTitle(info); glutPostRedisplay(); } void DoMenu(int value) { switch(value) { case 1: Projection = 0; Near = -1; Far = 1; break; case 2: Projection = 1; Near = 1; Far = 10; break; case 3: Projection = 2; Near = 1; Far = 10; break; case 4: Object = 0; break; case 5: Object = 1; break; } glutPostRedisplay(); } void DoReshape(GLsizei width, GLsizei height) { glViewport(0,0,width,height); lastWidth = width; lastHeight = height; } void DrawPyramid() { // 아랫면 흰 바닥 glColor3f(1,1,1); glBegin(GL_QUADS); glVertex2f(-0.5, 0.5); glVertex2f(0.5, 0.5); glVertex2f(0.5, -0.5); glVertex2f(-0.5, -0.5); glEnd(); // 위쪽 빨간 변 glBegin(GL_TRIANGLE_FAN); glColor3f(1,1,1); glVertex3f(0.0, 0.0, 0.8); glColor3f(1,0,0); glVertex2f(0.5, 0.5); glVertex2f(-0.5, 0.5); // 왼쪽 노란 변 glColor3f(1,1,0); glVertex2f(-0.5, -0.5); // 아래쪽 초록 변 glColor3f(0,1,0); glVertex2f(0.5, -0.5); // 오른쪽 파란 변 glColor3f(0,0,1); glVertex2f(0.5, 0.5); glEnd(); } void DoDisplay() { glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glShadeModel(GL_FLAT); glMatrixMode(GL_PROJECTION); glLoadIdentity(); switch (Projection) { case 0: glOrtho(left, right, bottom, top, Near, Far); break; case 1: glFrustum(left, right, bottom, top,Near,Far); break; case 2: GLfloat aspect = (GLfloat)lastWidth / (GLfloat)lastHeight; gluPerspective(fov, aspect, Near, Far); break; } glMatrixMode(GL_MODELVIEW); glPushMatrix(); // 원근투영일 때는 약간 더 뒤쪽에서 보아야 한다. if (Projection != 0) { glTranslatef(0,0,-2); } glRotatef(xAngle, 1.0f, 0.0f, 0.0f); glRotatef(yAngle, 0.0f, 1.0f, 0.0f); glRotatef(zAngle, 0.0f, 0.0f, 1.0f); if (Object == 0) { DrawPyramid(); } else { GLUquadricObj *pQuad; pQuad = gluNewQuadric(); gluQuadricDrawStyle(pQuad, GLU_LINE); glTranslatef(0.0, 0.0, -0.6); glColor3f(1,1,1); gluCylinder(pQuad, 0.3, 0.3, 1.2, 20, 20); } glPopMatrix(); glFlush(); }
/** * Copyright 2019 Utkarsh Bhatt * Author : Utkarsh Bhatt * Date : 05/10/2019 (5th October 2019) * Struct : Stack * Using : Dynamic Array * Type : Generic (Templated) */ #ifndef INCLUDE_STACK_HPP_ #define INCLUDE_STACK_HPP_ #include <sstream> #include <iostream> #include <string> template <typename T> class stack { protected: T* stack_root; T* top_ptr; int size; int capacity; public: explicit stack(int required_capacity) { this -> size = 0; this -> capacity = 0; this -> capacity = required_capacity; this -> stack_root = new T[this->capacity]; this -> top_ptr = this -> stack_root - 1; } ~stack(void) { delete[] this->stack_root; } bool push(T object) { if (this->size == this->capacity) { return false; } this -> top_ptr++; *(this -> top_ptr) = object; this -> size++; return true; } int print_size(void) { return this->size; } T pop(void) { if (this -> size == 0) { return (T)NULL; } T ret = *this -> top_ptr--; this -> size--; return ret; } T top(void) { if (this -> size == 0) { return (T)NULL; } T ret = *this -> top_ptr; return ret; } bool isEmpty(void) { return (this -> size == 0); } bool isFull(void) { return (this -> size == this -> capacity); } std::string flatten(void) { T* object_ptr = this->top_ptr; std::stringstream stack_str; stack_str << "Stack Size : "<< this -> size<< std::endl; stack_str << "Stack Content : "<< std::endl; try { stack_str << "--> " << *object_ptr-- << " <-- TOP" << std::endl; } catch(const std::exception& e) { std::cerr << e.what() << '\n'; return e.what(); } while (object_ptr >= this->stack_root) { stack_str << "--> " << *object_ptr-- << std::endl; } return stack_str.str(); } }; #endif // INCLUDE_STACK_HPP_
/*************************************************************************** Copyright (c) 2020 Philip Fortier This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. ***************************************************************************/ #pragma once #include "CrystalScriptStream.h" #include "AutoCompleteSourceTypes.h" #include "ParseAutoCompleteContext.h" // The kind of iterator we use. typedef CCrystalScriptStream::const_iterator streamIt; enum class IfDefDefineState { None, False, // In a clause that is false True, // In a clause that is true }; class SyntaxContext { public: SyntaxContext(streamIt beginning, sci::Script &script, std::unordered_set<std::string> preProcessorDefines, bool addCommentsDirectly, bool collectComments) : _beginning(beginning), _script(script), extraKeywords(nullptr), ifDefDefineState(IfDefDefineState::None), _preProcessorDefines(preProcessorDefines), _addCommentsToOM(addCommentsDirectly), _collectComments(collectComments), CurrentStringType(0) #ifdef PARSE_DEBUG , ParseDebug(false), ParseDebugIndent(0) #endif {} ~SyntaxContext() { assert(_statements.empty()); // Or else someone messed up, or there could have been an exception } void ReportError(const std::string &error, streamIt pos); std::string GetErrorText() { return _error; } streamIt GetErrorPosition() { return _beginning; } char CurrentStringType; void PushParseAutoCompleteContext(ParseACChannels pacc) { // For now, just set. We'll use a stack if necessary. _parseAutoCompleteContext.push_back(pacc); } void PopParseAutoCompleteContext() { _parseAutoCompleteContext.pop_back(); } std::set<ParseAutoCompleteContext> GetParseAutoCompleteContext() const { ParseAutoCompleteContext channels[4] = { }; bool done[4] = { }; for (auto it = _parseAutoCompleteContext.rbegin(); it != _parseAutoCompleteContext.rend(); ++it) { for (int i = 0; i < 4; i++) { if (!done[i]) { ParseAutoCompleteContext acc = ExtractChannel(*it, (ParseAutoCompleteChannel)i); if (acc == ParseAutoCompleteContext::Block) { done[i] = true; } if (acc != ParseAutoCompleteContext::None) { channels[i] = acc; done[i] = true; } } } } return std::set<ParseAutoCompleteContext>(std::begin(channels), std::end(channels)); } // Accessors sci::Script &Script() { return _script; } std::string &ScratchString() { return _scratch; } std::string &ScratchString2() { return _scratch2; } void SetInteger(int i, bool fNeg, bool fHex, streamIt pos) { if ((i > 0xffff) || (i < -32768)) { ReportError("Integer value is too large.", pos); } Integer = (WORD)i; NegInt = fNeg; HexInt = fHex; } uint16_t Integer; // Last encountered number bool NegInt; // Was the number a result of negation bool HexInt; // Was the number expressed in hex uint16_t Integer2; void CreateSynonym() { this->SynonymPtr = std::make_unique<sci::Synonym>(); } std::unique_ptr<sci::Synonym> SynonymPtr; void CreateDefine() { DefinePtr = std::make_unique<sci::Define>(); } std::unique_ptr<sci::Define> DefinePtr; void CreateProcedure() { FunctionPtr = std::make_unique<sci::ProcedureDefinition>(); FunctionPtr->AddSignature(std::move(std::make_unique<sci::FunctionSignature>())); } void CreateMethod() { FunctionPtr = std::make_unique<sci::MethodDefinition>(); FunctionPtr->AddSignature(std::move(std::make_unique<sci::FunctionSignature>())); } #ifdef ENABLE_VERBS void CreateVerbHandler(); #endif std::unique_ptr<sci::FunctionBase> FunctionPtr; std::unique_ptr<sci::ProcedureDefinition> GetFunctionAsProcedure() { return std::unique_ptr<sci::ProcedureDefinition>(static_cast<sci::ProcedureDefinition*>(FunctionPtr.release())); } std::unique_ptr<sci::MethodDefinition> GetFunctionAsMethod() { return std::unique_ptr<sci::MethodDefinition>(static_cast<sci::MethodDefinition*>(FunctionPtr.release())); } void CreateClass() { ClassPtr = std::make_unique<sci::ClassDefinition>(); } std::unique_ptr<sci::ClassDefinition> ClassPtr; void CreateClassProperty() { ClassProp = std::make_unique<sci::ClassProperty>(); } std::unique_ptr<sci::ClassProperty> ClassProp; void StartVariableDecl(const std::string &name) { VariableDecl = std::make_unique<sci::VariableDecl>(); VariableDecl->SetName(name); VariableDecl->SetSize(1); // Vars are size 1 by default. VariableDecl->SetIsUnspecifiedSize(true); } // 1) Each statement must begin with a push onto the statement stack. // 2) The subrule will fill that in with the required node (forloop, assignment, etc...) // 3) Once the subrule is complete, we'll either // a) transfer the node to a new statement object, and pop the node of the statement stack (if successful), or // b) delete the node, and pop it off the statement stack. void PushSyntaxNode() { // Put a null on the statement stack to make room for a statement _statements.push(std::move(std::unique_ptr<sci::SyntaxNode>())); } void TryAddCommentDirectly(std::unique_ptr<sci::Comment> &comment) { if (_addCommentsToOM) // For now... { if (!_statements.empty()) { _statements.push(move(comment)); } else if (FunctionPtr) { FunctionPtr->AddStatement(move(comment)); } } } // This is the "return value" from a generic statement std::unique_ptr<sci::SyntaxNode> StatementPtrReturn; void FinishStatement(bool fSuccess) { if (fSuccess) { // The statement is moved to the "return value" StatementPtrReturn = std::move(_statements.top()); } else { // We shall never hear of this statement again. Pop will automatically delete it. } _statements.pop(); // It's now an empty one? } // Make a syntax node (forloop, assignment, etc...) at the top of the statement stack // (use PushSyntaxNode to push a new spot onto the stack) template<typename _T> void CreateSyntaxNode(const streamIt &stream) { assert(!_statements.empty()); // That would mean there is no statement stack frame at all. if (_statements.top()) { // Someone created a statement, then didn't clean up (e.g. property value was created, but then failed!) _statements.top().reset(nullptr); } std::unique_ptr<_T> p = std::make_unique<_T>(); // Assign a line/char # p->SetPosition(stream.GetPosition()); _statements.top() = std::move(p); } template<typename _statementT> void ReplaceSyntaxNode(std::unique_ptr<_statementT> node) { _statements.top().reset(static_cast<SyntaxNode*>(node.release())); } // Returns a pointer to the first syntax node of this type const sci::SyntaxNode *GetSyntaxNode(sci::NodeType type) const; // Returns the type of the topmost non-null syntax node sci::NodeType GetTopKnownNode() const; // Get the syntax node at the top of the statement stack template<typename _statementT> _statementT* GetSyntaxNode() const { const std::unique_ptr<sci::SyntaxNode> &node = _statements.top(); assert(node->GetNodeType() == _statementT::MyNodeType); return static_cast<_statementT*>(node.get()); } template<typename _statementT> std::unique_ptr<_statementT> StealStatementReturn() { assert(StatementPtrReturn->GetNodeType() == _statementT::MyNodeType); return std::unique_ptr<_statementT>(static_cast<_statementT*>(StatementPtrReturn.release())); } template<typename _statementT> _statementT* GetPrevSyntaxNode() const { // Get the item that isn't at the top of the stack... it's one up. auto prevIt = _statements._Get_container().rbegin(); prevIt++; assert((*prevIt)->GetNodeType() == _statementT::MyNodeType); return static_cast<_statementT*>((*prevIt).get()); } // Like GetSyntaxNode, but sets the top of the stack to nullptr (doesn't pop), // assuming that ownership has been transfered to the caller. template<typename _statementT> std::unique_ptr<_statementT> StealSyntaxNode() { // _statements.top should always be non-null. We could assert, but we do this anyway: assert(_statements.top()->GetNodeType() == _statementT::MyNodeType); // We just steal it from the top of the stack: return std::unique_ptr<_statementT>(static_cast<_statementT*>(_statements.top().release())); } std::unique_ptr<sci::SyntaxNode> StealSyntaxNode() { // We just steal it from the top of the stack: return std::move(_statements.top()); } void DeleteAndPopSyntaxNode() { _statements.pop(); } void EvaluateIfDefScratch(const streamIt &stream, const std::string &value) { if (ifDefDefineState != IfDefDefineState::None) { ReportError("Already in an #ifdef.", stream); } if (_preProcessorDefines.find(value) != _preProcessorDefines.end()) { ifDefDefineState = IfDefDefineState::True; } else { ifDefDefineState = IfDefDefineState::False; } } void EndIf(const streamIt &stream) { if (ifDefDefineState == IfDefDefineState::None) { ReportError("Not in an #ifdef.", stream); } ifDefDefineState = IfDefDefineState::None; } void TransferScriptVariable() { VariableDeclPtr = std::move(VariableDecl); VariableDecl = std::make_unique<sci::VariableDecl>(); } std::unique_ptr<sci::VariableDecl> VariableDeclPtr; // A generic values for everyone to use (one at a time!) // These kinds of objects are "dead ends" on the parse tree, so it should be ok if // there is only instance of them. sci::PropertyValue PropertyValue; bool PropertyValueWasSet = false; std::unique_ptr<sci::VariableDecl> VariableDecl; // Hack for certain situations where we want to check for more keywords std::unordered_set<std::string> *extraKeywords; // Hacky/quick way of supported ifdefs for header defines. IfDefDefineState ifDefDefineState; bool CollectComments() { return _collectComments; } private: std::unordered_set<std::string> _preProcessorDefines; std::string _error; streamIt _beginning; bool _collectComments; // Do we care baout comments at all? bool _addCommentsToOM; // And if so, do we add them to the OM? sci::Script &_script; std::string _scratch; std::string _scratch2; std::vector<ParseACChannels> _parseAutoCompleteContext; std::stack<std::unique_ptr<sci::SyntaxNode>> _statements; public: #ifdef PARSE_DEBUG bool ParseDebug; int ParseDebugIndent = 0; #endif };
#ifndef HR_H #define HR_H #include <string> class HR { public: virtual std::string getName() = 0; virtual std::string getLastname() = 0; virtual std::string getEmail() = 0; virtual void setName(std::string &) = 0; virtual void setLastname(std::string &) = 0; virtual void setEmail(std::string &) = 0; }; #endif
// ***************************************************************** // This file is part of the CYBERMED Libraries // // Copyright (C) 2007 LabTEVE (http://www.de.ufpb.br/~labteve), // Federal University of Paraiba and University of São Paulo. // All rights reserved. // // This program is free software; you can redistribute it and/or // modify it under the terms of the GNU General Public License // as published by the Free Software Foundation; either version 2 // of the License, or (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public // License along with this program; if not, write to the Free // Software Foundation, Inc., 51 Franklin Street, Fifth Floor, // Boston, MA 02110-1301, USA. // ***************************************************************** #include "cybMatrixOperator.h" CybMatrixOperator::CybMatrixOperator() {} float CybMatrixOperator::matrixDeterminant(float *m, int dim) { float detBuf = 0; float *m2; int col; if(dim == 0) return 0; if(dim == 1) return m[0]; if(dim == 2) return (m[0]*m[3] - m[1]*m[2]); if(dim == 3) { return (m[0]*m[4]*m[8]) + (m[1]*m[5]*m[6]) + (m[3]*m[7]*m[2]) - ((m[0]*m[5]*m[7]) + (m[1]*m[3]*m[8]) + (m[6]*m[4]*m[2])); } if(dim > 3) { m2 = new float[dim*(dim-1)]; for(col = 0; col < dim; col++) { delLinCol(m, m2, 0, col, dim); if(!(col%2)) { detBuf+= matrixDeterminant(m2, dim-1) * m[col]; } else { detBuf-= matrixDeterminant(m2, dim-1) * m[col]; } } delete m2; } return detBuf; } double CybMatrixOperator::matrixDeterminant2(double *m, int dim) { double detBuf = 0; double subBuf; double *mAux; int matPos; if(dim == 0) return 0; if(dim == 1) return m[0]; if(dim == 2) return (m[0]*m[3] - m[1]*m[2]); if(dim == 3) { return (m[0]*m[4]*m[8]) + (m[1]*m[5]*m[6]) + (m[3]*m[7]*m[2]) - ((m[0]*m[5]*m[7]) + (m[1]*m[3]*m[8]) + (m[6]*m[4]*m[2])); } if(dim > 3) { mAux = new double[(dim-1)*(dim)]; for(int i = 1; i < dim; i++) { matPos = i*dim; for(int j = 1; j < dim; j++) { subBuf = m[matPos]*m[j]; mAux[(i-1)*(dim-1) + (j-1)] = ((m[matPos +j] * m[0]) - subBuf); } } detBuf = matrixDeterminant2(mAux, dim-1); } for(int i = 0; i < (dim - 2); i++) { detBuf /= (m[0]); } delete mAux; return detBuf; } void CybMatrixOperator::delLinCol(float *m, float *m2, int lin, int col, int s) { int extraJumpc = 0; int extraJumpl = 0; int limit = s*(s-1); for(int cont = 0; cont < limit; cont++) { if(cont == lin*s) extraJumpl = s; m2[cont] = m[cont + extraJumpl]; } limit = (s-1)*(s-1); for(int cont = 0; cont < limit; cont++) { if(!((cont-col)%(s-1)) && (cont >= col)) extraJumpc++; m2[cont] = m2[cont + extraJumpc]; } } void CybMatrixOperator::matrixInverse(float *m, float *m_1, int s, float deterM) { float *mAux; float index = 1; if(s>1) mAux = new float[(s)*(s-1)]; if(s == 1) { m_1[0] = (float)(1/m[0]); } else { if(s%2) { for(int l = 0; l< s; l++) { for(int c = 0; c < s; c++) { delLinCol(m, mAux, l, c, s); m_1[s*c+l] = index * (CybMatrixOperator::matrixDeterminant(mAux, s-1)/deterM); index *= -1; } } } else { for(int l = 0; l< s; l++) { for(int c = 0; c < s; c++) { delLinCol(m, mAux, l, c, s); m_1[s*c+l] = index * (CybMatrixOperator::matrixDeterminant(mAux, s-1)/deterM); index *= -1; } index *= -1; } } delete mAux; } } float CybMatrixOperator::matrixMult(float *covM, float *difMeanV, int dim) { float result = 0, intmult; int index; for(int i=0; i< dim; i++) { intmult=0; index = dim*i; for(int j=0; j<dim; j++) { intmult += (float)difMeanV[j]*covM[index + j]; } result += difMeanV[i]*intmult; } return result; }
#ifndef THREADMAPPING_H_ #define THREADMAPPING_H_ #include "ThreadSLAM.h" #include "sensor_msgs/LaserScan.h" #include "obvision/reconstruct/grid/SensorPolar2D.h" #include "obvision/reconstruct/grid/TsdGrid.h" #include <boost/thread.hpp> #include <deque> namespace ohm_tsd_slam { class SlamNode; /** * @class ThreadMapping * @brief Implements a thread updating an obvious::TsdGrid * @author Philipp Koch, Stefan May */ class ThreadMapping : public ThreadSLAM { public: /** * Constructor * @param grid Representation */ ThreadMapping(obvious::TsdGrid* grid); /** * Destructor */ virtual ~ThreadMapping(); /** * queuePush * Method to add a top be pushed sensor to the queue (synchronized) * @param sensor New data */ void queuePush(obvious::SensorPolar2D* sensor); /** * initialized * Method determining whether the tsd grid contains any data yet * @return true in case of an initialized grid */ bool initialized(void); /** * initPush * method to init the grid from a certain pose. Is done by the CALLING thread * @param sensor initial data */ void initPush(obvious::SensorPolar2D* sensor); protected: /** * eventLoop * Thread event loop */ virtual void eventLoop(void); private: /** * Sensor queue */ std::deque<obvious::SensorPolar2D*> _sensors; /** * Push mutex for queue */ boost::mutex _pushMutex; /** * Initialized flag */ bool _initialized; }; } /* namespace */ #endif /* THREADMAPPING_H_ */
// Return subsequences / subsets vector<string> return_subsequences(string s, string ans) { if (s=="") { vector<string> result; result.push_back(ans); return result; } vector<string> ans1 = return_subsequences(s.substr(1), ans); vector<string> ans2 = return_subsequences(s.substr(1), ans+s[0]); vector<string> result(ans1.size()+ans2.size()); merge(ans1.begin(), ans1.end(), ans2.begin(), ans2.end(), result.begin()); return result; } void solve() { string s; cin >> s; vector<string> ans = return_subsequences(s, ""); sort(ans.begin(), ans.end()); for (auto c: ans){ cout << c << " "; } cout << endl; }
#include <iostream> #include <vector> #include <stack> #include <algorithm> //#include <unordered_map> #include <limits> //#include <cmath> using namespace std; namespace Graph { struct Vertex { Vertex(int val, int d):Val(val),DStart(d) {} int Val; int DStart; operator int() { return Val; } }; bool operator <(const Vertex &lhs, const Vertex &rhs) { return lhs.DStart > rhs.DStart; } vector<vector<int>> Distances; vector<int> D; vector<int> Prev; void PrintPathTo(int node) { cout << "Distance from start to " << node << " is " << D[node] << endl; auto s = stack<int>(); s.push(node); while( Prev[node] != -1 ) { s.push(Prev[node]); node = Prev[node]; } cout << s.top(); s.pop(); while( s.size() > 0 ) { cout << " -> " << s.top(); s.pop(); } cout << endl; } void FindShortestPaths(int start, int end) { // auto pV = vector<Vertex*>(Distances.size()); D = vector<int>(Distances.size(), numeric_limits<int>::max()); Prev = vector<int>(Distances.size(), -1); auto q = vector<Vertex>(); q.push_back(Vertex(start,0)); // make_heap(q.begin(), q.end()); D[start] = 0; // pV[0] = &q[0]; // vIndexes.insert(pair<int, int>(start,0)); while(q.size() > 0) { // Deque pop_heap(q.begin(), q.end()); auto v = q.back(); q.pop_back(); if( v == end ) { break; } // Add children for( auto c=0; c<Distances[v].size(); c++ ) { if( Distances[v][c] == 0 ) { continue; } // d[c] = min(d[c], d[v] + Distances[v][c]); if( D[c] == numeric_limits<int>::max() ) { D[c] = D[v] + Distances[v][c]; Prev[c] = v; auto vc = Vertex(c, D[c]); // pV[c] = &vc; q.push_back(vc); push_heap(q.begin(), q.end()); // vIndexes.insert(pair<int, int>(c,d[c])); } else if (D[v] + Distances[v][c] < D[c]) { D[c] = D[v] + Distances[v][c]; Prev[c] = v; // Reorder heap // pV[c]->DStart = D[c]; for( auto it=q.begin(); it!=q.end(); it++ ) { if( *it == c ) { it->DStart = D[c]; make_heap(q.begin(), q.end()); break; } } } } } } } int main() { Graph::Distances = vector<vector<int>>({ // 0 1 2 3 4 5 6 7 8 9 10 11 { 0, 0, 0, 0, 0, 0, 10, 0, 12, 0, 0, 0 }, // 0 { 0, 0, 0, 0, 20, 0, 0, 26, 0, 5, 0, 6 }, // 1 { 0, 0, 0, 0, 0, 0, 0, 15, 14, 0, 0, 9 }, // 2 { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 0 }, // 3 { 0, 20, 0, 0, 0, 5, 17, 0, 0, 0, 0, 11 }, // 4 { 0, 0, 0, 0, 5, 0, 6, 0, 3, 0, 0, 33 }, // 5 {10, 0, 0, 0, 17, 6, 0, 0, 0, 0, 0, 0 }, // 6 { 0, 26, 15, 0, 0, 0, 0, 0, 0, 3, 0, 20 }, // 7 {12, 0, 14, 0, 0, 3, 0, 0, 0, 0, 0, 0 }, // 8 { 0, 5, 0, 0, 0, 0, 0, 3, 0, 0, 0, 0 }, // 9 { 0, 0, 0, 7, 0, 0, 0, 0, 0, 0, 0, 0 }, // 10 { 0, 6, 9, 0, 11, 33, 0, 20, 0, 0, 0, 0 }, // 11 }); Graph::FindShortestPaths(0, 9); Graph::PrintPathTo(9); return 0; }
//! Bismillahi-Rahamanirahim. /** ========================================** ** @Author: Md. Abu Farhad ( RUET, CSE'15) ** @Category: /** ========================================**/ #include<bits/stdc++.h> #include<stdio.h> using namespace std; #define ll long long #define fr(i,n) for(int i=0;i<n;i++) #define fr1(i,n) for(ll i=1;i<=n;i++) int main() { ll i,j,k,m,n,l,cnt=0,hv=0; string s,p, str1="heavy", str2="metal"; cin>>s; l=s.size(); fr(i,l) { if(s.substr(i,5)==str1) hv++; else if( s.substr(i,5)==str2) cnt+=hv; } cout<<cnt<<endl; }
#include <stdio.h> #include <stdlib.h> int main(void) { char string1[20]; char string2[]="string literal"; int i; printf("Enter a string :"); scanf_s("%S",string1); printf("stringl is : %s\nstring2 is : %s\n""stringl with spaces betweeen characters is :\n",string1,string2); for (i = 0; string1[i] != '\0'; i++) { printf("%c", string1[i]); } printf("\n"); system("pause"); return 0; }
// Copyright (c) 2019 St. Mother Teresa HS All rights reserved. // // Created by: DJ Watson // Created on: November 2019 // this program loops a number to add #include <iostream> #include <string> int main() { // variables int numinput; int loopc; int loopn = 0; int answer = 0; std::string ln; std::string numcheck; // input std::cout << "enter loop count: "; std::cin >> ln; std::cout << "" << std::endl; // process and output try { loopc = std::stoi(ln); for (loopn = 0; loopc > loopn; loopn++) { std::cout << "enter number: "; std::cin >> numcheck; try { numinput = std::stoi(numcheck); if (numinput < 0) { continue; } else { answer += numinput; } } catch (std::invalid_argument) { continue; } } std::cout << answer; } catch (std::invalid_argument) { std::cout << "invalid input" << std::endl; std::cout << ""; } }
#pragma once #include <ncurses.h> #include <string> #include "Logger.hpp" #include "LogSpace.hpp" #include "ClasslessLogger.hpp" class ChatWindow { public: ChatWindow() = default; ~ChatWindow() = default; ChatWindow(ChatWindow &&) = delete; ChatWindow operator=(ChatWindow &&) = delete; ChatWindow(const ChatWindow &) = delete; ChatWindow operator=(const ChatWindow &) = delete; static void displayChatWindows(); static void deleteDisplayMesageWindow(); static void deleteEnterMesageWindow(); static void displayEnterMessageWindow(); static void displayDisplayMessageWindow(const std::string& message); static WINDOW* getDisplayMessageWindow(); static WINDOW* getEnterMessageWindow(); static WINDOW* _displayMessageWindow; static WINDOW* _enterMessageWindow; };
#include "SearchParameters.h" using namespace UsefulProteomicsDatabases; using namespace EngineLayer; namespace TaskLayer { SearchParameters::SearchParameters() { // default search task parameters setDisposeOfFileWhenDone(true); setDoParsimony(true); setNoOneHitWonders(false); setModPeptidesAreDifferent(false); setDoQuantification(true); setQuantifyPpmTol(5); setSearchTarget(true); //setDecoyType(getDecoyType()->Reverse); setDecoyType(DecoyType::Reverse); setDoHistogramAnalysis(false); setHistogramBinTolInDaltons(0.003); setDoLocalizationAnalysis(true); setWritePrunedDatabase(false); setKeepAllUniprotMods(true); //setMassDiffAcceptorType(getMassDiffAcceptorType()::OneMM); setMassDiffAcceptorType(MassDiffAcceptorType::OneMM); setMaxFragmentSize(30000.0); setWriteMzId(true); setWritePepXml(false); setModsToWriteSelection(std::unordered_map<std::string, int> { {"N-linked glycosylation", 3}, {"O-linked glycosylation", 3}, {"Other glycosylation", 3}, {"Common Biological", 3}, {"Less Common", 3}, {"Metal", 3}, {"2+ nucleotide substitution", 3}, {"1 nucleotide substitution", 3}, {"UniProt", 2} }); setWriteDecoys(true); setWriteContaminants(true); setLocalFdrCategories(std::vector<FdrCategory> {FdrCategory::FullySpecific}); } bool SearchParameters::getDisposeOfFileWhenDone() const { return privateDisposeOfFileWhenDone; } void SearchParameters::setDisposeOfFileWhenDone(bool value) { privateDisposeOfFileWhenDone = value; } bool SearchParameters::getDoParsimony() const { return privateDoParsimony; } void SearchParameters::setDoParsimony(bool value) { privateDoParsimony = value; } bool SearchParameters::getModPeptidesAreDifferent() const { return privateModPeptidesAreDifferent; } void SearchParameters::setModPeptidesAreDifferent(bool value) { privateModPeptidesAreDifferent = value; } bool SearchParameters::getNoOneHitWonders() const { return privateNoOneHitWonders; } void SearchParameters::setNoOneHitWonders(bool value) { privateNoOneHitWonders = value; } bool SearchParameters::getMatchBetweenRuns() const { return privateMatchBetweenRuns; } void SearchParameters::setMatchBetweenRuns(bool value) { privateMatchBetweenRuns = value; } bool SearchParameters::getNormalize() const { return privateNormalize; } void SearchParameters::setNormalize(bool value) { privateNormalize = value; } double SearchParameters::getQuantifyPpmTol() const { return privateQuantifyPpmTol; } void SearchParameters::setQuantifyPpmTol(double value) { privateQuantifyPpmTol = value; } bool SearchParameters::getDoHistogramAnalysis() const { return privateDoHistogramAnalysis; } void SearchParameters::setDoHistogramAnalysis(bool value) { privateDoHistogramAnalysis = value; } bool SearchParameters::getSearchTarget() const { return privateSearchTarget; } void SearchParameters::setSearchTarget(bool value) { privateSearchTarget = value; } DecoyType SearchParameters::getDecoyType() const { return privateDecoyType; } void SearchParameters::setDecoyType(DecoyType value) { privateDecoyType = value; } TaskLayer::MassDiffAcceptorType SearchParameters::getMassDiffAcceptorType() const { return privateMassDiffAcceptorType; } void SearchParameters::setMassDiffAcceptorType(TaskLayer::MassDiffAcceptorType value) { privateMassDiffAcceptorType = value; } bool SearchParameters::getWritePrunedDatabase() const { return privateWritePrunedDatabase; } void SearchParameters::setWritePrunedDatabase(bool value) { privateWritePrunedDatabase = value; } bool SearchParameters::getKeepAllUniprotMods() const { return privateKeepAllUniprotMods; } void SearchParameters::setKeepAllUniprotMods(bool value) { privateKeepAllUniprotMods = value; } bool SearchParameters::getDoLocalizationAnalysis() const { return privateDoLocalizationAnalysis; } void SearchParameters::setDoLocalizationAnalysis(bool value) { privateDoLocalizationAnalysis = value; } bool SearchParameters::getDoQuantification() const { return privateDoQuantification; } void SearchParameters::setDoQuantification(bool value) { privateDoQuantification = value; } TaskLayer::SearchType SearchParameters::getSearchType() const { return privateSearchType; } void SearchParameters::setSearchType(TaskLayer::SearchType value) { privateSearchType = value; } std::vector<FdrCategory> SearchParameters::getLocalFdrCategories() const { return privateLocalFdrCategories; } void SearchParameters::setLocalFdrCategories(const std::vector<FdrCategory> value) { privateLocalFdrCategories = value; } std::string SearchParameters::getCustomMdac() const { return privateCustomMdac; } void SearchParameters::setCustomMdac(const std::string &value) { privateCustomMdac = value; } double SearchParameters::getMaxFragmentSize() const { return privateMaxFragmentSize; } void SearchParameters::setMaxFragmentSize(double value) { privateMaxFragmentSize = value; } double SearchParameters::getHistogramBinTolInDaltons() const { return privateHistogramBinTolInDaltons; } void SearchParameters::setHistogramBinTolInDaltons(double value) { privateHistogramBinTolInDaltons = value; } std::unordered_map<std::string, int> SearchParameters::getModsToWriteSelection() const { return privateModsToWriteSelection; } void SearchParameters::setModsToWriteSelection(const std::unordered_map<std::string, int> value) { privateModsToWriteSelection = value; } double SearchParameters::getMaximumMassThatFragmentIonScoreIsDoubled() const { return privateMaximumMassThatFragmentIonScoreIsDoubled; } void SearchParameters::setMaximumMassThatFragmentIonScoreIsDoubled(double value) { privateMaximumMassThatFragmentIonScoreIsDoubled = value; } bool SearchParameters::getWriteMzId() const { return privateWriteMzId; } void SearchParameters::setWriteMzId(bool value) { privateWriteMzId = value; } bool SearchParameters::getWritePepXml() const { return privateWritePepXml; } void SearchParameters::setWritePepXml(bool value) { privateWritePepXml = value; } bool SearchParameters::getWriteDecoys() const { return privateWriteDecoys; } void SearchParameters::setWriteDecoys(bool value) { privateWriteDecoys = value; } bool SearchParameters::getWriteContaminants() const { return privateWriteContaminants; } void SearchParameters::setWriteContaminants(bool value) { privateWriteContaminants = value; } }
// Wire Master Writer // by Nicholas Zambetti <http://www.zambetti.com> // Demonstrates use of the Wire library // Writes data to an I2C/TWI slave device // Refer to the "Wire Slave Receiver" example for use with this // Created 29 March 2006 // This example code is in the public domain. #include <Wire.h> void setup() { Wire.begin(); // join i2c bus (address optional for master) Serial.begin(9600); // start serial for output Serial.println("*************************** READY"); } int16_t speed1 = 0; int16_t speed2 = 0; char c = ' '; signed int sp = 0; void loop() { Serial.println(c); if (c == ' ') { sp = 0; } else if (c == 'q') { sp -= 10; } else if (c == 'w') { sp += 10; } else if (c == '2') { sp += 100; } else if (c == '1') { sp -= 100; } do { byte myArray[4]; speed1 = sp; speed2 = sp; myArray[0] = (speed1 >> 8) & 0xFF; myArray[1] = speed1 & 0xFF; myArray[2] = (speed2 >> 8) & 0xFF; myArray[3] = speed2 & 0xFF; // Serial.print(myArray[0], HEX); // Serial.print(" "); // Serial.println(myArray[1], HEX); Serial.print("speed "); Serial.print(sp); Serial.print(" low byte "); Serial.print((sp & 0xFF), HEX); Serial.print(" high byte "); Serial.println((sp >> 8) & 0xFF, HEX); Wire.beginTransmission(8); // transmit to device #8 Wire.write(myArray, 4); // sends 4 bytes Wire.endTransmission(); // stop transmitting } while (!Serial.available()); c = Serial.read(); delayMicroseconds(500); }
//----------------------------------------------------------------------------- // Perimeter Map Compiler // Copyright (c) 2005, Don Reba // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // // • Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // • Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // • Neither the name of Don Reba nor the names of his contributors may be used // to endorse or promote products derived from this software without specific // prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. //----------------------------------------------------------------------------- #pragma once #include <iterator> #include <boost\spirit\tree\ast.hpp> class XmlCreator { public: struct LoadResult { int chars_consumed_; bool success_; }; private: typedef const char * iter_t; typedef boost::spirit::tree_match<iter_t> match_t; typedef match_t::tree_iterator tree_iter_t; typedef match_t::node_t tree_node_t; public: XmlCreator(); LoadResult LoadFromFile(const char *file_name); LoadResult LoadFromString(const char *data); void Read(std::ostream &out) const; private: void Create(const tree_iter_t &iter); private: // node parsing void ParseNode (const tree_node_t &node); void ParseArray (const tree_node_t &node); void ParseDisjunction(const tree_node_t &node); void ParseFieldName (const tree_node_t &node); void ParseFloat (const tree_node_t &node); void ParseInt (const tree_node_t &node); void ParseQString (const tree_node_t &node); void ParseScript (const tree_node_t &node); void ParseSet (const tree_node_t &node); void ParseSetName (const tree_node_t &node); void ParseValue (const tree_node_t &node); void ParseVector (const tree_node_t &node); // XML manipulation void StartNode(const char *name); void EndNode(); void SetAttribute(const char *name, const char *value); void SetValue(const char *value); private: TiXmlDocument doc_; TiXmlElement *doc_cursor_; };
/* * transcoder.cpp * * Created on: 2016年4月27日 * Author: leo */ #include "pipeline_transcoding.h" #include "transcoder.h" using namespace std; using namespace Transcoder; void PrintHelp(msdk_char *strAppName, const msdk_char *strErrorMessage) { msdk_printf(MSDK_STRING("Transcode Application. %s\n\n"), MSDK_SAMPLE_VERSION); if (strErrorMessage) { msdk_printf(MSDK_STRING("Error: %s\n"), strErrorMessage); } msdk_printf(MSDK_STRING("Usage: %s [<options>] \n"), strAppName); msdk_printf(MSDK_STRING("\n")); msdk_printf(MSDK_STRING("Options:\n")); msdk_printf(MSDK_STRING(" [-i] - input file/stream, can be multi input .\n")); msdk_printf(MSDK_STRING(" [-o] - output file/stream.\n")); msdk_printf(MSDK_STRING(" [-s] - output video size(width*height).\n")); msdk_printf(MSDK_STRING(" [-b] - output video bitrate(kbps).\n")); msdk_printf(MSDK_STRING(" [-max_b] - output video max bitrate(kbps).\n")); msdk_printf(MSDK_STRING(" [-g] - output video gop size.\n")); msdk_printf( MSDK_STRING( " [-ref] - distance between I and P frame, if 1 , no B frame used.\n")); msdk_printf( MSDK_STRING( " [-tu] - quicksync encoder target usage, 1-7: best quality to best speed.\n")); msdk_printf( MSDK_STRING( " [-r] - output video frame rate, enable the vpp frame rate conversion.\n")); msdk_printf(MSDK_STRING(" [-f] - output video format, default is mpegts.\n")); msdk_printf( MSDK_STRING( " [-async] - depth of asynchronous pipeline. default value is 4. must be between 1 and 20.\n")); msdk_printf( MSDK_STRING( " [-loglevel] - set ffmpeg api loglevel(quiet/panic/fatal/error/warning/info/debug/trace).\n")); msdk_printf(MSDK_STRING("\n")); } mfxStatus ParseInputString(msdk_char* strInput[], mfxU8 nArgNum, sInputParams* pParams) { if (1 == nArgNum) { PrintHelp(strInput[0], NULL); return MFX_ERR_UNSUPPORTED; } MSDK_CHECK_POINTER(pParams, MFX_ERR_NULL_PTR); for (mfxU8 i = 1; i < nArgNum; i++) { if (0 == msdk_strcmp(strInput[i], MSDK_STRING("-i"))) { VAL_CHECK(i + 1 == nArgNum, i, strInput[i]); if (!pParams->pSrcFile) { pParams->pSrcFile = new char*[40]; } pParams->pSrcFile[pParams->nSrcFiles] = strInput[++i]; pParams->nSrcFiles++; } else if (0 == msdk_strcmp(strInput[i], MSDK_STRING("-o"))) { VAL_CHECK(i + 1 == nArgNum, i, strInput[i]); if (!pParams->pDstFile) pParams->pDstFile = new char*[40]; pParams->pDstFile[pParams->nDstFiles] = strInput[++i]; pParams->nDstFiles++; } else if (0 == msdk_strcmp(strInput[i], MSDK_STRING("-b"))) { VAL_CHECK(i + 1 == nArgNum, i, strInput[i]); if (MFX_ERR_NONE != msdk_opt_read(strInput[++i], pParams->nBitRate)) { PrintHelp(strInput[0], MSDK_STRING("bit rate is invalid")); return MFX_ERR_UNSUPPORTED; } } else if (0 == msdk_strcmp(strInput[i], MSDK_STRING("-s"))) { int width = 0, height = 0; VAL_CHECK(i + 1 == nArgNum, i, strInput[i]); if ((2 != sscanf(strInput[++i], "%dx%d", &width, &height)) || (width <= 0) || (height <= 0)) { printf("error: incorrect argument for -s option given\n"); exit(-1); } pParams->nDstWidth = (mfxU16) width; pParams->nDstHeight = (mfxU16) height; } else if (0 == msdk_strcmp(strInput[i], MSDK_STRING("-f"))) { VAL_CHECK(i + 1 == nArgNum, i, strInput[i]); pParams->format = strInput[++i]; } else if (0 == msdk_strcmp(strInput[i], MSDK_STRING("-loglevel"))) { VAL_CHECK(i + 1 == nArgNum, i, strInput[i]); i++; if (strcmp(strInput[i], "quiet") == 0) pParams->loglevel = AV_LOG_QUIET; else if (strcmp(strInput[i], "panic") == 0) pParams->loglevel = AV_LOG_PANIC; else if (strcmp(strInput[i], "fatal") == 0) pParams->loglevel = AV_LOG_FATAL; else if (strcmp(strInput[i], "error") == 0) pParams->loglevel = AV_LOG_ERROR; else if (strcmp(strInput[i], "warning") == 0) pParams->loglevel = AV_LOG_WARNING; else if (strcmp(strInput[i], "verbose") == 0) pParams->loglevel = AV_LOG_VERBOSE; else if (strcmp(strInput[i], "debug") == 0) pParams->loglevel = AV_LOG_DEBUG; else if (strcmp(strInput[i], "trace") == 0) pParams->loglevel = AV_LOG_TRACE; else pParams->loglevel = AV_LOG_INFO; } else if (0 == msdk_strcmp(strInput[i], MSDK_STRING("-r"))) { VAL_CHECK(i + 1 == nArgNum, i, strInput[i]); if (MFX_ERR_NONE != msdk_opt_read(strInput[++i], pParams->dFrameRate)) { PrintHelp(strInput[0], MSDK_STRING("frame rate is invalid")); return MFX_ERR_UNSUPPORTED; } } else if (0 == msdk_strcmp(strInput[i], MSDK_STRING("-max_b"))) { VAL_CHECK(i + 1 == nArgNum, i, strInput[i]); if (MFX_ERR_NONE != msdk_opt_read(strInput[++i], pParams->nMaxBitRate)) { PrintHelp(strInput[0], MSDK_STRING("max bit rate is invalid")); return MFX_ERR_UNSUPPORTED; } } else if (0 == msdk_strcmp(strInput[i], MSDK_STRING("-g"))) { VAL_CHECK(i + 1 == nArgNum, i, strInput[i]); if (MFX_ERR_NONE != msdk_opt_read(strInput[++i], pParams->nGopSize)) { PrintHelp(strInput[0], MSDK_STRING("gop size is invalid")); return MFX_ERR_UNSUPPORTED; } } else if (0 == msdk_strcmp(strInput[i], MSDK_STRING("-ref"))) { VAL_CHECK(i + 1 == nArgNum, i, strInput[i]); if (MFX_ERR_NONE != msdk_opt_read(strInput[++i], pParams->nGopRef)) { PrintHelp(strInput[0], MSDK_STRING("gop I-P distance is invalid")); return MFX_ERR_UNSUPPORTED; } } else if (0 == msdk_strcmp(strInput[i], MSDK_STRING("-tu"))) { VAL_CHECK(i + 1 == nArgNum, i, strInput[i]); if (MFX_ERR_NONE != msdk_opt_read(strInput[++i], pParams->nTargetUsage)) { PrintHelp(strInput[0], MSDK_STRING("target usage level is invalid")); return MFX_ERR_UNSUPPORTED; } } else if (0 == msdk_strcmp(strInput[i], MSDK_STRING("-async"))) { VAL_CHECK(i + 1 == nArgNum, i, strInput[i]); if (MFX_ERR_NONE != msdk_opt_read(strInput[++i], pParams->nAsyncDepth)) { PrintHelp(strInput[0], MSDK_STRING("async is invalid")); return MFX_ERR_UNSUPPORTED; } } else if (0 == msdk_strcmp(strInput[i], MSDK_STRING("-list_name"))) { VAL_CHECK(i + 1 == nArgNum, i, strInput[i]); if (!pParams->hlsListNameArray) { pParams->hlsListNameArray = new char*[40]; } pParams->hlsListNameArray[pParams->nHlsList] = strInput[++i]; pParams->nHlsList++; } else if (0 == msdk_strcmp(strInput[i], MSDK_STRING("-list_prefix"))) { VAL_CHECK(i + 1 == nArgNum, i, strInput[i]); if (!pParams->hlsListPrefixArray) { pParams->hlsListPrefixArray = new char*[40]; } pParams->hlsListPrefixArray[pParams->nHlsList - 1] = strInput[++i]; } else if (0 == msdk_strcmp(strInput[i], MSDK_STRING("-sys"))) { pParams->bUseSystemMemory = true; } else if (0 == msdk_strcmp(strInput[i], MSDK_STRING("-video"))) { pParams->bUseVideoMemory = true; break; } else if ((0 == msdk_strcmp(strInput[i], MSDK_STRING("-h")) || (0 == msdk_strcmp(strInput[i], MSDK_STRING("?"))))) { PrintHelp(strInput[0], NULL); exit(0); } else { PrintHelp(strInput[0], "Unrecognized option."); exit(0); } } if (0 == pParams->nSrcFiles) { msdk_printf(MSDK_STRING("error: source file name not found\n")); return MFX_ERR_UNSUPPORTED; } if (0 == pParams->nBitRate) { msdk_printf(MSDK_STRING("info: bitrate not set, use default\n")); } if ((0 == pParams->nDstHeight) || (0 == pParams->nDstHeight)) { msdk_printf(MSDK_STRING("info: output video size not set, use sourcce size\n")); } if (0 == pParams->nDstFiles) { pParams->mode = MODE_PERFORMANCE; } else { pParams->mode = MODE_FILE_DUMP; } if (pParams->nAsyncDepth == 0) { pParams->nAsyncDepth = 4; //set by default; } return MFX_ERR_NONE; } CTranscoder::CTranscoder() { } // CTranscoder::CTranscoder() CTranscoder::~CTranscoder() { Close(); } // CTranscoder::~CTranscoder() mfxStatus CTranscoder::Init(sInputParams *pParams) { mfxStatus sts = MFX_ERR_NONE; return sts; } // mfxStatus CTranscoder::Init() mfxStatus CTranscoder::ProcessResult() { mfxStatus sts = MFX_ERR_NONE; return sts; } // mfxStatus CTranscoder::ProcessResult() mfxU32 MFX_STDCALL RunTranscoder(void *params) { mfxStatus sts = MFX_ERR_NONE; sInputParams *pParams = (sInputParams*) params; msdk_printf(MSDK_STRING("Transcoder Thread: %d Started.\n"), pParams->nThreadID); std::auto_ptr<CTranscodingPipeline> pTranscodingPipeline; // pipeline for Transcoding. while (1) { pTranscodingPipeline.reset(new CTranscodingPipeline); sts = pTranscodingPipeline->Init(pParams); MSDK_CHECK_RESULT(sts, MFX_ERR_NONE, MFX_ERR_UNKNOWN); // print stream info pTranscodingPipeline->PrintInfo(); sts = pTranscodingPipeline->RunTranscoding(); if (sts == MFX_ERR_NONE || sts == MFX_ERR_INVALID_VIDEO_PARAM) { break; } else { msdk_printf(MSDK_STRING("Transcoder Thread: %d Restart.\n"), pParams->nThreadID); continue; } } msdk_printf(MSDK_STRING("Transcoder Thread: %d Finished.\n"), pParams->nThreadID); return 0; } mfxStatus CTranscoder::Run(sInputParams *pParams) { mfxStatus sts; int n_Thread = pParams->nSrcFiles; MSDKThread *pthread = NULL; sInputParams *pThreadParams = new sInputParams[pParams->nSrcFiles]; for (int i = 0; i < pParams->nSrcFiles; i++) { MSDK_MEMCPY_VAR(pThreadParams[i], pParams, sizeof(sInputParams)); pThreadParams[i].strSrcFile = pParams->pSrcFile[i]; pThreadParams[i].strDstFile = pParams->pDstFile[i]; if (pParams->hlsListNameArray) pThreadParams[i].hlsListName = pParams->hlsListNameArray[i]; if (pParams->hlsListPrefixArray) pThreadParams[i].hlsListPrefix = pParams->hlsListPrefixArray[i]; pThreadParams[i].nThreadID = i; pthread = new MSDKThread(sts, RunTranscoder, (void *) &pThreadParams[i]); m_HDLArray.push_back(pthread); } for (int i = 0; i < n_Thread; i++) { m_HDLArray[i]->Wait(); } msdk_fprintf(stderr, MSDK_STRING("\nAll Thread Finished.\n")); return sts; } void CTranscoder::Close() { while (m_HDLArray.size()) { delete m_HDLArray[m_HDLArray.size() - 1]; m_HDLArray.pop_back(); } } // void CTranscoder::Close() int main(int argc, char *argv[]) { mfxStatus sts = MFX_ERR_NONE; sInputParams Params; // input parameters from command line sts = ParseInputString(argv, (mfxU8) argc, &Params); MSDK_CHECK_PARSE_RESULT(sts, MFX_ERR_NONE, MFX_ERR_UNKNOWN); Params.CodecId = MFX_CODEC_AVC; av_register_all(); avformat_network_init(); if (Params.loglevel != 0) av_log_set_level(Params.loglevel); std::auto_ptr<CTranscoder> transcode; transcode.reset(new CTranscoder); sts = transcode->Init(&Params); MSDK_CHECK_PARSE_RESULT(sts, MFX_ERR_NONE, MFX_ERR_UNKNOWN); sts = transcode->Run(&Params); MSDK_CHECK_PARSE_RESULT(sts, MFX_ERR_NONE, MFX_ERR_UNKNOWN); return 0; }
#include "main.h" void creating_td_clicker(){ //grid click std::vector<SDL_Rect> grid_button = std::vector<SDL_Rect>(); grid_button.push_back({0,0,GRID_SIZE_X*SQUARE_SIZE, GRID_SIZE_Y*SQUARE_SIZE}); game->new_button("TD Grid", 0, 1, grid_button); game->set_button_active("TD Grid", true); //EVENT WHEN CLICKING THE GRID game->add_mouse_procedure(room_procedure(grid_click, true, false, 2, 1), 0, 1); //EVENT WHEN OVER THE GRID game->add_mouse_procedure(room_procedure(grid_over, true, false, 3, 1), 0, 1); } int build_button_clear_set(){ build_button_one_push_up(); build_button_two_push_up(); build_button_three_push_up(); build_button_four_push_up(); build_button_five_push_up(); build_button_six_push_up(); build_button_seven_push_up(); build_button_eight_push_up(); build_button_nine_push_up(); return 0; } int build_button_one_push_down(){ module->set_build_click(BUILD_BUTTON_ONE); build_button_clear_set(); game->set_spot("Build Icon One", {95,0,95,95}); return 0; } int build_button_one_push_up(){ if (module->get_state() != MODULE_BUILD || module->get_build_click() != BUILD_BUTTON_ONE) game->set_spot("Build Icon One", {0,0,95,95}); else if (module->get_build_click() == BUILD_BUTTON_ONE) game->set_spot("Build Icon One", {190,0,95,95}); return 0; } int build_button_two_push_down(){ module->set_build_click(BUILD_BUTTON_TWO); build_button_clear_set(); game->set_spot("Build Icon Two", {95,0,95,95}); return 0; } int build_button_two_push_up(){ if (module->get_state() != MODULE_BUILD || module->get_build_click() != BUILD_BUTTON_TWO) game->set_spot("Build Icon Two", {0,0,95,95}); else if (module->get_build_click() == BUILD_BUTTON_TWO) game->set_spot("Build Icon Two", {190,0,95,95}); return 0; } int build_button_three_push_down(){ module->set_build_click(BUILD_BUTTON_THREE); build_button_clear_set(); game->set_spot("Build Icon Three", {95,0,95,95}); return 0; } int build_button_three_push_up(){ if (module->get_state() != MODULE_BUILD || module->get_build_click() != BUILD_BUTTON_THREE) game->set_spot("Build Icon Three", {0,0,95,95}); else if (module->get_build_click() == BUILD_BUTTON_THREE) game->set_spot("Build Icon Three", {190,0,95,95}); return 0; } int build_button_four_push_down(){ module->set_build_click(BUILD_BUTTON_FOUR); build_button_clear_set(); game->set_spot("Build Icon Four", {95,0,95,95}); return 0; } int build_button_four_push_up(){ if (module->get_state() != MODULE_BUILD || module->get_build_click() != BUILD_BUTTON_FOUR) game->set_spot("Build Icon Four", {0,0,95,95}); else if (module->get_build_click() == BUILD_BUTTON_FOUR) game->set_spot("Build Icon Four", {190,0,95,95}); return 0; } int build_button_five_push_down(){ module->set_build_click(BUILD_BUTTON_FIVE); build_button_clear_set(); game->set_spot("Build Icon Five", {95,0,95,95}); return 0; } int build_button_five_push_up(){ if (module->get_state() != MODULE_BUILD || module->get_build_click() != BUILD_BUTTON_FIVE) game->set_spot("Build Icon Five", {0,0,95,95}); else if (module->get_build_click() == BUILD_BUTTON_FIVE) game->set_spot("Build Icon Five", {190,0,95,95}); return 0; } int build_button_six_push_down(){ module->set_build_click(BUILD_BUTTON_SIX); build_button_clear_set(); game->set_spot("Build Icon Six", {95,0,95,95}); return 0; } int build_button_six_push_up(){ if (module->get_state() != MODULE_BUILD || module->get_build_click() != BUILD_BUTTON_SIX) game->set_spot("Build Icon Six", {0,0,95,95}); else if (module->get_build_click() == BUILD_BUTTON_SIX) game->set_spot("Build Icon Six", {190,0,95,95}); return 0; } int build_button_seven_push_down(){ module->set_build_click(BUILD_BUTTON_SEVEN); build_button_clear_set(); game->set_spot("Build Icon Seven", {95,0,95,95}); return 0; } int build_button_seven_push_up(){ if (module->get_state() != MODULE_BUILD || module->get_build_click() != BUILD_BUTTON_SEVEN) game->set_spot("Build Icon Seven", {0,0,95,95}); else if (module->get_build_click() == BUILD_BUTTON_SEVEN) game->set_spot("Build Icon Seven", {190,0,95,95}); return 0; } int build_button_eight_push_down(){ module->set_build_click(BUILD_BUTTON_EIGHT); build_button_clear_set(); game->set_spot("Build Icon Eight", {95,0,95,95}); return 0; } int build_button_eight_push_up(){ if (module->get_state() != MODULE_BUILD || module->get_build_click() != BUILD_BUTTON_EIGHT) game->set_spot("Build Icon Eight", {0,0,95,95}); else if (module->get_build_click() == BUILD_BUTTON_EIGHT) game->set_spot("Build Icon Eight", {190,0,95,95}); return 0; } int build_button_nine_push_down(){ module->set_build_click(BUILD_BUTTON_NINE); build_button_clear_set(); game->set_spot("Build Icon Nine", {95,0,95,95}); return 0; } int build_button_nine_push_up(){ if (module->get_state() != MODULE_BUILD || module->get_build_click() != BUILD_BUTTON_NINE) game->set_spot("Build Icon Nine", {0,0,95,95}); else if (module->get_build_click() == BUILD_BUTTON_NINE) game->set_spot("Build Icon Nine", {190,0,95,95}); return 0; } int build_set_button_one_push_down(){ game->set_spot("Set Icon One", {50,0,50,46}); game->set_spot("Set Icon Two", {0,0,50,46}); module->set_to_race_one(); return 0; } int build_set_button_one_push_up(){ //game->set_spot("Set Icon One", {0,0,50,46}); return 0; } int build_set_button_two_push_down(){ game->set_spot("Set Icon One", {0,0,50,46}); game->set_spot("Set Icon Two", {50,0,50,46}); module->set_to_race_two(); return 0; } int build_set_button_two_push_up(){ //game->set_spot("Set Icon Two", {0,0,50,46}); return 0; } int start_button_push_down(){ game->set_spot("Start Button", {250,0,250,70}); module->start_level(); return 0; } int start_button_push_up(){ game->set_spot("Start Button", {0,0,250,70}); return 0; } int speed_button_push_down(){ int speed_state = module->toggling_speed(); game->set_spot("Speed Button", {66*speed_state,0,66,66}); return 0; } void creating_td_ui(){ //creating UI backgrounds game->new_image("Top UI Background", "images/top_ui.png", 0, 0); game->set_active("Top UI Background", true); game->add_point("Top UI Background", SCREEN_WIDTH/2, SCREEN_HEIGHT/10); //create buttons here //build buttons game->new_image("Build Icon One", "images/build_tower_icon.png", 0, 0, {0,0,95,95}); game->set_active("Build Icon One", true); game->add_point("Build Icon One", 70, 100); std::vector<SDL_Rect> build_button_1 = std::vector<SDL_Rect>(); build_button_1.push_back({70-95/2,100-95/2,95,95}); game->new_button("Build Button One", 0, 0, build_button_1); game->set_button_active("Build Button One", true); game->add_mouse_procedure(room_procedure(build_button_one_push_down, true, false, 2, 1), 0, 0); game->add_mouse_procedure(room_procedure(build_button_one_push_up, true, false, 1, 2), 0, 0); game->new_image("Build Icon Two", "images/build_tower_icon.png", 0, 0, {0,0,95,95}); game->set_active("Build Icon Two", true); game->add_point("Build Icon Two", 170, 100); std::vector<SDL_Rect> build_button_2 = std::vector<SDL_Rect>(); build_button_2.push_back({170-95/2,100-95/2,95,95}); game->new_button("Build Button Two", 0, 0, build_button_2); game->set_button_active("Build Button Two", true); game->add_mouse_procedure(room_procedure(build_button_two_push_down, true, false, 7, 3), 0, 0); game->add_mouse_procedure(room_procedure(build_button_two_push_up, true, false, 6, 4), 0, 0); game->new_image("Build Icon Three", "images/build_tower_icon.png", 0, 0, {0,0,95,95}); game->set_active("Build Icon Three", true); game->add_point("Build Icon Three", 270, 100); std::vector<SDL_Rect> build_button_3 = std::vector<SDL_Rect>(); build_button_3.push_back({270-95/2,100-95/2,95,95}); game->new_button("Build Button Three", 0, 0, build_button_3); game->set_button_active("Build Button Three", true); game->add_mouse_procedure(room_procedure(build_button_three_push_down, true, false, 12, 5), 0, 0); game->add_mouse_procedure(room_procedure(build_button_three_push_up, true, false, 11, 6), 0, 0); game->new_image("Build Icon Four", "images/build_tower_icon.png", 0, 0, {0,0,95,95}); game->set_active("Build Icon Four", true); game->add_point("Build Icon Four", 370, 100); std::vector<SDL_Rect> build_button_4 = std::vector<SDL_Rect>(); build_button_4.push_back({370-95/2,100-95/2,95,95}); game->new_button("Build Button Four", 0, 0, build_button_4); game->set_button_active("Build Button Four", true); game->add_mouse_procedure(room_procedure(build_button_four_push_down, true, false, 17, 7), 0, 0); game->add_mouse_procedure(room_procedure(build_button_four_push_up, true, false, 16, 8), 0, 0); game->new_image("Build Icon Five", "images/build_tower_icon.png", 0, 0, {0,0,95,95}); game->set_active("Build Icon Five", true); game->add_point("Build Icon Five", 470, 100); std::vector<SDL_Rect> build_button_5 = std::vector<SDL_Rect>(); build_button_5.push_back({470-95/2,100-95/2,95,95}); game->new_button("Build Button Five", 0, 0, build_button_5); game->set_button_active("Build Button Five", true); game->add_mouse_procedure(room_procedure(build_button_five_push_down, true, false, 22, 9), 0, 0); game->add_mouse_procedure(room_procedure(build_button_five_push_up, true, false, 21, 10), 0, 0); game->new_image("Build Icon Six", "images/build_tower_icon.png", 0, 0, {0,0,95,95}); game->set_active("Build Icon Six", true); game->add_point("Build Icon Six", 570, 100); std::vector<SDL_Rect> build_button_6 = std::vector<SDL_Rect>(); build_button_6.push_back({570-95/2,100-95/2,95,95}); game->new_button("Build Button Six", 0, 0, build_button_6); game->set_button_active("Build Button Six", true); game->add_mouse_procedure(room_procedure(build_button_six_push_down, true, false, 27, 11), 0, 0); game->add_mouse_procedure(room_procedure(build_button_six_push_up, true, false, 26, 12), 0, 0); game->new_image("Build Icon Seven", "images/build_tower_icon.png", 0, 0, {0,0,95,95}); game->set_active("Build Icon Seven", true); game->add_point("Build Icon Seven", 670, 100); std::vector<SDL_Rect> build_button_7 = std::vector<SDL_Rect>(); build_button_7.push_back({670-95/2,100-95/2,95,95}); game->new_button("Build Button Seven", 0, 0, build_button_7); game->set_button_active("Build Button Seven", true); game->add_mouse_procedure(room_procedure(build_button_seven_push_down, true, false, 32, 13), 0, 0); game->add_mouse_procedure(room_procedure(build_button_seven_push_up, true, false, 31, 14), 0, 0); game->new_image("Build Icon Eight", "images/build_tower_icon.png", 0, 0, {0,0,95,95}); game->set_active("Build Icon Eight", true); game->add_point("Build Icon Eight", 770, 100); std::vector<SDL_Rect> build_button_8 = std::vector<SDL_Rect>(); build_button_8.push_back({770-95/2,100-95/2,95,95}); game->new_button("Build Button Eight", 0, 0, build_button_8); game->set_button_active("Build Button Eight", true); game->add_mouse_procedure(room_procedure(build_button_eight_push_down, true, false, 37, 15), 0, 0); game->add_mouse_procedure(room_procedure(build_button_eight_push_up, true, false, 36, 16), 0, 0); game->new_image("Build Icon Nine", "images/build_tower_icon.png", 0, 0, {0,0,95,95}); game->set_active("Build Icon Nine", true); game->add_point("Build Icon Nine", 870, 100); std::vector<SDL_Rect> build_button_9 = std::vector<SDL_Rect>(); build_button_9.push_back({870-95/2,100-95/2,95,95}); game->new_button("Build Button Nine", 0, 0, build_button_9); game->set_button_active("Build Button Nine", true); game->add_mouse_procedure(room_procedure(build_button_nine_push_down, true, false, 42, 17), 0, 0); game->add_mouse_procedure(room_procedure(build_button_nine_push_up, true, false, 41, 18), 0, 0); game->add_mouse_procedure(room_procedure(build_button_clear_set, true, false, -1, 18), 0, 0); //build set buttons game->new_image("Set Icon One", "images/build_set_one.png", 0, 0, {0,0,50,46}); game->set_active("Set Icon One", true); game->add_point("Set Icon One", 950, 76); std::vector<SDL_Rect> build_set_button_1 = std::vector<SDL_Rect>(); build_set_button_1.push_back({950-50/2,76-46/2,50,46}); game->new_button("Build Set Button One", 0, 0, build_set_button_1); game->set_button_active("Build Set Button One", true); game->add_mouse_procedure(room_procedure(build_set_button_one_push_down, true, false, 47, 17), 0, 0); game->add_mouse_procedure(room_procedure(build_set_button_one_push_up, true, false, 46, 18), 0, 0); game->add_mouse_procedure(room_procedure(build_set_button_one_push_up, true, false, -1, 18), 0, 0); game->new_image("Set Icon Two", "images/build_set_two.png", 0, 0, {0,0,50,46}); game->set_active("Set Icon Two", true); game->add_point("Set Icon Two", 950, 125); std::vector<SDL_Rect> build_set_button_2 = std::vector<SDL_Rect>(); build_set_button_2.push_back({950-50/2,125-46/2,50,46}); game->new_button("Build Set Button Two", 0, 0, build_set_button_2); game->set_button_active("Build Set Button Two", true); game->add_mouse_procedure(room_procedure(build_set_button_two_push_down, true, false, 52, 17), 0, 0); game->add_mouse_procedure(room_procedure(build_set_button_two_push_up, true, false, 51, 18), 0, 0); game->add_mouse_procedure(room_procedure(build_set_button_two_push_up, true, false, -1, 18), 0, 0); //start button game->new_image("Start Button", "images/start_button.png", 0, 0, {0,0,250,70}); game->set_active("Start Button", true); game->add_point("Start Button", 1130, 115); std::vector<SDL_Rect> start_button = std::vector<SDL_Rect>(); start_button.push_back({1130-125,115-35,250,70}); game->new_button("Start Button", 0, 0, start_button); game->set_button_active("Start Button", true); game->add_mouse_procedure(room_procedure(start_button_push_down, true, false, 57, 3), 0, 0); game->add_mouse_procedure(room_procedure(start_button_push_up, true, false, 56, 4), 0, 0); game->add_mouse_procedure(room_procedure(start_button_push_up, true, false, -1, 4), 0, 0); //speed button game->new_image("Speed Button", "images/speed_button.png", 0, 0, {0,0,66,66}); game->set_active("Speed Button", true); game->add_point("Speed Button", 1025, 44); std::vector<SDL_Rect> speed_button = std::vector<SDL_Rect>(); speed_button.push_back({992,11,66,66}); game->new_button("Speed Button", 0, 0, speed_button); game->set_button_active("Speed Button", true); game->add_mouse_procedure(room_procedure(speed_button_push_down, true, false, 62, 20), 0, 0); } int upgrade_push_down(){ game->set_spot("Upgrade Button", {236,0,236,68}); module->upgrade_tower(); return 0; } int upgrade_push_up(){ game->set_spot("Upgrade Button", {0,0,236,68}); return 0; } int sell_push_down(){ game->set_spot("Sell Button", {236,0,236,68}); module->sell_tower(); return 0; } int sell_push_up(){ game->set_spot("Sell Button", {0,0,236,68}); return 0; } void creating_td_info_display(){ //TD INFO BACKGROUND game->new_image("Tower Info Background", "images/tower_stat_ui.png", 0, 2); game->add_point("Tower Info Background", SCREEN_WIDTH/10, SCREEN_HEIGHT*2/5); game->set_active("Tower Info Background", true); //COST DISPLAY AND UPGRADE BUTTON std::vector<SDL_Rect> upgrade_button = std::vector<SDL_Rect>(); upgrade_button.push_back({SCREEN_WIDTH/10 - 118,530-34,236,68}); game->new_image("Cost Display", "images/cost_display.png", 0, 2, {0,0,236,68}); game->add_point("Cost Display", SCREEN_WIDTH/10, 530); game->new_image("Upgrade Button", "images/upgrade_button.png", 0, 2, {0,0,236,68}); game->add_point("Upgrade Button", SCREEN_WIDTH/10, 530); game->new_image("Button Metal", "images/resource_icons/metal_icon_small.png", 0, 2, {0,0,15,15}); game->set_blend_mode("Button Metal", SDL_BLENDMODE_BLEND); game->add_point("Button Metal", SCREEN_WIDTH/10-106, 552); game->new_text("Metal Cost", "display font costs", 0, 2, "30", false, 0); game->add_point("Metal Cost", SCREEN_WIDTH/10-96+game->get_spot("Metal Cost").w/2, 552); game->new_image("Button Wood", "images/resource_icons/wood_icon_small.png", 0, 2, {0,0,15,15}); game->set_blend_mode("Button Wood", SDL_BLENDMODE_BLEND); game->add_point("Button Wood", SCREEN_WIDTH/10-29, 552); game->new_text("Wood Cost", "display font costs", 0, 2, "30", false, 0); game->add_point("Wood Cost", SCREEN_WIDTH/10-19+game->get_spot("Wood Cost").w/2, 552); //std::cout << SCREEN_WIDTH/10-19 << std::endl; //109 game->new_image("Button Crystal", "images/resource_icons/crystal_icon_small.png", 0, 2, {0,0,15,15}); game->set_blend_mode("Button Crystal", SDL_BLENDMODE_BLEND); game->add_point("Button Crystal", SCREEN_WIDTH/10+49, 552); //std::cout << SCREEN_WIDTH/10+49 << std::endl; //177 game->new_text("Crystal Cost", "display font costs", 0, 2, "30", false, 0); game->add_point("Crystal Cost", SCREEN_WIDTH/10+59+game->get_spot("Crystal Cost").w/2, 552); game->new_button("Upgrade Button", 0, 2, upgrade_button); game->add_mouse_procedure(room_procedure(upgrade_push_down, true, false, 2, 4), 0, 2); game->add_mouse_procedure(room_procedure(upgrade_push_up, true, false, 1, 5), 0, 2); game->add_mouse_procedure(room_procedure(upgrade_push_up, true, false, -1, 6), 0, 2); game->new_image("Blank Upgrade Button", "images/invalid_display.png", 0, 2); game->add_point("Blank Upgrade Button", SCREEN_WIDTH/10, 530); //SELL BUTTON std::vector<SDL_Rect> sell_button = std::vector<SDL_Rect>(); sell_button.push_back({SCREEN_WIDTH/10 - 118,600-34,236,68}); game->new_image("Sell Button", "images/sell_button.png", 0, 2, {0,0,236,68}); game->add_point("Sell Button", SCREEN_WIDTH/10, 600); game->copy_image("Blank Sell Button", "Blank Upgrade Button"); game->add_point("Blank Sell Button", SCREEN_WIDTH/10, 600); game->copy_image("Sell Button Metal", "Button Metal"); game->copy_image("Sell Button Wood", "Button Wood"); game->copy_image("Sell Button Crystal", "Button Crystal"); game->add_point("Sell Button Metal", SCREEN_WIDTH/10-106, 622); game->add_point("Sell Button Wood", SCREEN_WIDTH/10-29, 622); game->add_point("Sell Button Crystal", SCREEN_WIDTH/10+49, 622); game->new_text("Sell Metal Cost", "display font costs", 0, 2, "30", false, 0); game->add_point("Sell Metal Cost", SCREEN_WIDTH/10-96+game->get_spot("Sell Metal Cost").w/2, 622); game->new_text("Sell Wood Cost", "display font costs", 0, 2, "30", false, 0); game->add_point("Sell Wood Cost", SCREEN_WIDTH/10-19+game->get_spot("Sell Wood Cost").w/2, 622); game->new_text("Sell Crystal Cost", "display font costs", 0, 2, "30", false, 0); game->add_point("Sell Crystal Cost", SCREEN_WIDTH/10+49+game->get_spot("Sell Crystal Cost").w/2, 622); game->new_button("Sell Button", 0, 2, sell_button); game->add_mouse_procedure(room_procedure(sell_push_down, true, false, 7, 7), 0, 2); game->add_mouse_procedure(room_procedure(sell_push_up, true, false, 6, 8), 0, 2); game->add_mouse_procedure(room_procedure(sell_push_up, true, false, -1, 9), 0, 2); //game->set_button_active("Sell Button", true); game->new_text("Tower Name", "base font", 0, 2, "Tower", false, 0); game->add_point("Tower Name", SCREEN_WIDTH/10, 40); //game->set_active("Tower Name", true); game->new_text("Attack", "base font", 0, 2, "Attack: 10", false, 0); game->add_point("Attack", SCREEN_WIDTH/10, 90); //game->set_active("Attack", true); game->new_text("Range", "base font", 0, 2, "Range: 10", false, 0); game->add_point("Range", SCREEN_WIDTH/10, 130); //game->set_active("Range", true); game->new_text("Rate", "base font", 0, 2, "Rate: 10", false, 0); game->add_point("Rate", SCREEN_WIDTH/10, 170); //game->set_active("Rate", true); game->new_text("Tower Description", "base font", 0, 2, "Rate: 10", false, 0); game->add_point("Tower Description", SCREEN_WIDTH/10, 215); game->new_image("Select", "images/select_blank.png", 0, 2); game->add_point("Select", SCREEN_WIDTH/10, SCREEN_HEIGHT*2/5); game->set_active("Select", true); //board game->new_text("Metal", "base font", 0, 0, "Metal: 200", 0xFF, 0xFF, 0xFF, 0xFF, false, 0); game->add_point("Metal", 30+game->get_spot("Metal").w/2, 30); game->set_active("Metal", true); game->new_text("Wood", "base font", 0, 0, "Lumber: 100", 0xFF, 0xFF, 0xFF, 0xFF, false, 0); game->add_point("Wood", 200+game->get_spot("Wood").w/2, 30); game->set_active("Wood", true); game->new_text("Crystal", "base font", 0, 0, "Crystal: 10", 0xFF, 0xFF, 0xFF, 0xFF, false, 0); game->add_point("Crystal", 500+game->get_spot("Crystal").w/2, 30); game->set_active("Crystal", true); game->new_text("Level", "base font", 0, 0, "Level: 1", 0xFF, 0xFF, 0xFF, 0xFF, false, 0); game->add_point("Level", 750+game->get_spot("Level").w/2, 30); game->set_active("Level", true); game->new_text("Lives", "base font", 0, 0, "Lives: 15", 0xFF, 0xFF, 0xFF, 0xFF, false, 0); game->add_point("Lives", 900+game->get_spot("Lives").w/2, 30); game->set_active("Lives", true); } int mouse_follow(unsigned int ticks){ static int x, y; static Uint32 mouse_state; mouse_state = SDL_GetMouseState(&x, &y); ///Consider if the mouse is over the grid and the grid is currently building something if (module->get_state() == MODULE_BUILD){ if (x < SCREEN_WIDTH*4/5 && (y > SCREEN_HEIGHT/5 && y < SCREEN_HEIGHT) && game->get_active("Cursor")){ game->set_active("Cursor", false); } else if (!(x < SCREEN_WIDTH*4/5 && (y > SCREEN_HEIGHT/5 && y < SCREEN_HEIGHT)) && !game->get_active("Cursor")){ game->set_active("Cursor", true); game->clear_points("Tower Select"); } } else if (!game->get_active("Cursor")){ game->set_active("Cursor", true); } if (mouse_state == SDL_BUTTON_LEFT) game->set_spot("Cursor", {50, 0, 50, 50}); else game->set_spot("Cursor", {0, 0, 50, 50}); ///Mouse follow game->clear_points("Cursor"); game->add_point("Cursor", x+12, y+15); ///Check also if the mouse is over a tower or enemy return 0; } int press_camera_up(){ module->move_up(true); return 0; } int release_camera_up(){ module->move_up(false); return 0; } int press_camera_down(){ module->move_down(true); return 0; } int release_camera_down(){ module->move_down(false); return 0; } int press_camera_left(){ module->move_left(true); return 0; } int release_camera_left(){ module->move_left(false); return 0; } int press_camera_right(){ module->move_right(true); return 0; } int release_camera_right(){ module->move_right(false); return 0; } int grid_click(){ int x, y; x = game->get_button_over_x("TD Grid"); y = game->get_button_over_y("TD Grid"); module->click_on_grid(x, y); return 0; } int grid_over(){ int x, y; x = game->get_button_over_x("TD Grid"); y = game->get_button_over_y("TD Grid"); module->over_grid(x, y); return 0; } int grid_start(){ module->start_level(); return 0; } int update_module(unsigned int ticks){ module->update_td_module(ticks); return 0; } void load_module_room(){ //Cursor game->new_image("Cursor", "images/cursor.png", 0, {0,0,50,50}); game->set_blend_mode("Cursor", SDL_BLENDMODE_BLEND); game->set_active("Cursor", true); //TD grid, towers, and enemies //grid load_grid_tiles(); //destination points load_destination_points(); //effects load_debuffs(); //enemy load_enemies(); //tower load_towers(); load_tower_selection(); load_bullets(); //notification game->new_text("Notification", "notification font", 0, "blank", false, 0); game->set_color("Notification", {0xFF, 0xFF, 0x33, 0xFF}); game->add_point("Notification", SCREEN_WIDTH/2, SCREEN_HEIGHT/3); ///clicking grid & buttons creating_td_clicker(); creating_td_ui(); load_resource_icons(); creating_td_info_display(); ///LOADING MAP module->set_selected_map(SELECTED_LEVEL); module->load_map(); module->set_points(); module->draw_grid(); module->draw_points(); module->set_button_data_set(); game->add_pre_render_procedure(loop_procedure(update_module, true, true, true, 1)); ///LOADING RACES module->load_button_mapping(BUILD_RACE_ONE); build_set_button_one_push_down(); } int title_click(){ game->set_room(0); load_module_room(); return 0; } int set_map_to_default(){ SELECTED_LEVEL = "Default"; return 0; } int set_map_to_crossing(){ SELECTED_LEVEL = "Crossing"; return 0; } int set_map_to_traditional(){ SELECTED_LEVEL = "Traditional"; return 0; } void load_title_room(){ game->new_image("Title Image", "images/title_screen_bg_and_title.png", TITLE_ROOM, 0); game->add_point("Title Image", SCREEN_WIDTH/2, SCREEN_HEIGHT/2); game->set_active("Title Image", true); game->new_text("Title Text", "notification font", TITLE_ROOM, 0, "Press anywhere to go to the game", 0xFF, 0xFF, 0x00, 0xFF, false, 0); game->add_point("Title Text", SCREEN_WIDTH*2/3+20, SCREEN_HEIGHT*8/9 + 40); game->set_active("Title Text", true); game->new_text("Settings Text", "display font stats", TITLE_ROOM, 0, "Press 'i' for default map Press 'o' for crossing map Press 'p' for traditional map", 0xFF, 0xFF, 0x00, 0xFF, true, 350); game->add_point("Settings Text", SCREEN_WIDTH*1/4-80, SCREEN_HEIGHT*7/9+80); game->set_active("Settings Text", true); std::vector<SDL_Rect> title_rect = std::vector<SDL_Rect>(); title_rect.push_back({0,0,SCREEN_WIDTH, SCREEN_HEIGHT}); game->new_button("Title Button" , 1, 0, title_rect); game->add_mouse_procedure(room_procedure(title_click, true, false, 2, 0), TITLE_ROOM, 0); game->set_button_active("Title Button", true); game->add_key_procedure(key_procedure(set_map_to_default, true, true, SDL_SCANCODE_I, 0)); game->add_key_procedure(key_procedure(set_map_to_crossing, true, true, SDL_SCANCODE_O, 1)); game->add_key_procedure(key_procedure(set_map_to_traditional, true, true, SDL_SCANCODE_P, 2)); } int main(int args, char* argv[]){ game = NULL; module = NULL; game = new main_controller(SCREEN_WIDTH, SCREEN_HEIGHT, SCREEN_NAME, PRINTING); game->set_cursor(SDL_DISABLE); module = new td_module(180, 180, 15, 15); table = new td_level_loader(); //INITIALIZING THE MODULE if (!game->initialize()){ std::cout << "This framework has failed!" << std::endl; } else { std::cout << "This framework has loaded!" << std::endl; int ticks; game->add_font("base font", "fonts/Primitive.ttf", 28); game->add_font("notification font", "fonts/Primitive.ttf", 34); game->add_font("display font header", "fonts/Primitive.ttf", 26); game->add_font("display font stats", "fonts/Primitive.ttf", 22); game->add_font("display font description", "fonts/Primitive.ttf", 18); game->add_font("display font costs", "fonts/Primitive.ttf", 14); ///Adding the rooms & panels game->new_room(); game->new_panel(GAME_ROOM, 0, 0, SCREEN_WIDTH, SCREEN_HEIGHT/5); game->new_panel(GAME_ROOM, 0, SCREEN_HEIGHT/5, SCREEN_WIDTH*4/5, SCREEN_HEIGHT*4/5, SQUARE_SIZE*GRID_SIZE_X, SQUARE_SIZE*GRID_SIZE_Y); game->new_panel(GAME_ROOM, SCREEN_WIDTH*4/5, SCREEN_HEIGHT/5, SCREEN_WIDTH/5, SCREEN_HEIGHT*4/5); game->new_room(); game->new_panel(TITLE_ROOM, 0, 0, SCREEN_WIDTH, SCREEN_HEIGHT); game->set_room(TITLE_ROOM); ///====================================================================Loading assets ///-------------------------------TITLE ROOM load_title_room(); ///-------------------------------MODULE ROOM ///Adding procedures //cursor game->add_pre_render_procedure(loop_procedure(mouse_follow, false, true, true, 0)); //camera game->add_key_procedure(key_procedure(press_camera_up, true, true, SDL_SCANCODE_W, 0)); game->add_key_procedure(key_procedure(release_camera_up, true, true, -SDL_SCANCODE_W, 0)); game->add_key_procedure(key_procedure(press_camera_down, true, true, SDL_SCANCODE_S, 1)); game->add_key_procedure(key_procedure(release_camera_down, true, true, -SDL_SCANCODE_S, 1)); game->add_key_procedure(key_procedure(press_camera_left, true, true, SDL_SCANCODE_A, 2)); game->add_key_procedure(key_procedure(release_camera_left, true, true, -SDL_SCANCODE_A, 2)); game->add_key_procedure(key_procedure(press_camera_right, true, true, SDL_SCANCODE_D, 3)); game->add_key_procedure(key_procedure(release_camera_right, true, true, -SDL_SCANCODE_D, 3)); while ((ticks = game->loop_run()) != -1){ //std::cout << ticks << std::endl; } } delete table; table = NULL; delete module; module = NULL; game->close(); delete game; game = NULL; return 0; }
/* turbineex0.cpp */ #include "turbineex0.hpp" TurbineEx0::TurbineEx0(umComponent dictComp) { name = any_cast<const char *>(dictComp["name"]); ef = any_cast<double>(dictComp["ef"]); iPort = new Port(any_cast<mPort>(dictComp["iPort"])); oPort = new Port(any_cast<mPort>(dictComp["oPort"])); portdict = {{"iPort", iPort}, {"oPort", oPort}}; energy = WORKEXTRACTED; } TurbineEx0::~TurbineEx0() { delete iPort; delete oPort; } void TurbineEx0::state() { if (ef == 1.0) { oPort->s = iPort->s; // Isentropic compression (ideal cycle) oPort->ps_prop(); } else { double isoh = ps(oPort->p, iPort->s, 4); oPort->h = iPort->h - ef * (iPort->h - isoh); oPort->ph_prop(); } } int TurbineEx0::balance() { // mass and energy balance // mass balance if (!isnan(iPort->fdot)) { oPort->fdot = iPort->fdot; } else { if (!isnan(oPort->fdot)) iPort->fdot = oPort->fdot; } //energy workExtracted = iPort->fdot * (iPort->h - oPort->h); if (isnan(workExtracted)) { return 0; } else return 1; } void TurbineEx0::setportaddress() { if (iPort != portdict["iPort"]) iPort = portdict["iPort"]; if (oPort != portdict["oPort"]) oPort = portdict["oPort"]; } string TurbineEx0::resultstring() { string result; result = "\n" + name; result += "\n" + Port::title; result += "\n" + iPort->resultstring(); result += "\n" + oPort->resultstring(); result += "\nworkExtracted(kJ/kg): " + to_string_with_precision<double>(workExtracted, 3) + "\n"; return result; }
#include <iostream> #include <ros/ros.h> #include <geometry_msgs/QuaternionStamped.h> #include <nav_msgs/Odometry.h> #include <tf/transform_broadcaster.h> #include <fstream> // global variable #define PI 3.1415926 ros::Publisher g_odom_pub; boost::shared_ptr<tf::TransformBroadcaster> odom_broadcaster; double g_kl, g_kr, g_b; void odometryCallback(const geometry_msgs::QuaternionStamped::ConstPtr& encoder); int main(int argc, char **argv) { // init ros ros::init(argc, argv, "odometry"); ros::NodeHandle nh; /*TODO default parameters*/ //roslaunch debug: /*nh.getParam("/Odometry/robot/kl", g_kl); nh.getParam("/Odometry/robot/kr", g_kr); nh.getParam("/Odometry/robot/b", g_b);*/ //single node debug: nh.getParam("/robot/kl", g_kl); nh.getParam("/robot/kr", g_kr); nh.getParam("/robot/b", g_b); std::cout<<" g_kl=:"<< g_kl<<std::endl; std::cout<<" g_kr=:"<< g_kr<<std::endl; std::cout<<" g_b=:"<< g_b<<std::endl; odom_broadcaster.reset(new tf::TransformBroadcaster()); ros::Subscriber sub = nh.subscribe("/mbot/encoder", 1000, odometryCallback); g_odom_pub = nh.advertise<nav_msgs::Odometry>("/mbot/odometry", 1000); ros::spin(); return 1; } void odometryCallback(const geometry_msgs::QuaternionStamped::ConstPtr& encoder) { // TODO 参数需要更在标定后做更精细的修正 const double KL = g_kl; //m/tick const double KR = g_kr; //m/tick const double B = g_b; //width /*std::cout<<"KL"<<KL<<std::endl; std::cout<<"KR"<<KR<<std::endl; std::cout<<"B"<<B<<std::endl;*/ static double pre_time = 0.0; static double x = 0.0, y =0.0, theta = 0.0; // pose of robot static double pre_en_l1 = 0, pre_en_l2 = 0, pre_en_r1 = 0, pre_en_r2 = 0; //std::cout<<"delta_t="<<delta_t<<std::endl; /*std::cout<<"delta="<<g_kl<<std::endl; std::cout<<"x="<<g_kr<<std::endl; std::cout<<"y="<<g_b<<std::endl;*/ // 读取四个编码器的值,四个编码器的值是存储在一个四元数里的 double en_l1 = encoder->quaternion.x; double en_l2 = encoder->quaternion.y; double en_r1 = encoder->quaternion.z; double en_r2 = encoder->quaternion.w; //读取时间戳 double cur_time = encoder->header.stamp.toSec(); double delta_t = 0.0; //以秒为单位 if(pre_time == 0.0)//处理第一帧数据 { pre_time = cur_time; pre_en_l1 = en_l1; pre_en_l2 = en_l2; pre_en_r1 = en_r1; pre_en_r2 = en_r2; } else { // read deltas delta_t = cur_time - pre_time; pre_time = cur_time; double delta_en_l1 = en_l1 - pre_en_l1; double delta_en_l2 = en_l2 - pre_en_l2; double delta_en_r1 = en_r1 - pre_en_r1; double delta_en_r2 = en_r2 - pre_en_r2; double delta_en_l = (delta_en_l1 + delta_en_l2)* 0.5; double delta_en_r = (delta_en_r1 + delta_en_r2)* 0.5; pre_en_l1 = en_l1; pre_en_l2 = en_l2; pre_en_r1 = en_r1; pre_en_r2 = en_r2; //cal odometry double delta_theta = (KR*delta_en_r - KL*delta_en_l) / B; double delta_s = 0.5 *(KR*delta_en_r + KL*delta_en_l); double delta_x = delta_s * cos(theta + 0.5*delta_theta); double delta_y = delta_s * sin(theta + 0.5*delta_theta); x = x + delta_x; y = y + delta_y; theta = theta + delta_theta; // 修正角度 if(theta > PI) theta -= 2 * PI; else if(theta < -PI) theta += 2 * PI; double vx = delta_x / delta_t; double vy = delta_y / delta_t; double omega = delta_theta / delta_t; //since all odometry is 6DOF we'll need a quaternion created from yaw geometry_msgs::Quaternion odom_quat = tf::createQuaternionMsgFromYaw(theta); //first, we'll publish the transform over tf geometry_msgs::TransformStamped odom_trans; odom_trans.header.stamp = ros::Time::now(); odom_trans.header.frame_id = "odom"; odom_trans.child_frame_id = "base_link"; odom_trans.transform.translation.x = x; odom_trans.transform.translation.y = y; odom_trans.transform.translation.z = 0.0; odom_trans.transform.rotation = odom_quat; //send the transform odom_broadcaster->sendTransform(odom_trans); //publish odometry nav_msgs::Odometry odom; odom.header.stamp = ros::Time::now(); odom.header.frame_id = "odom"; odom.child_frame_id = "base_link"; odom.pose.pose.position.x = x; odom.pose.pose.position.y = y; odom.pose.pose.orientation = odom_quat; odom.twist.twist.angular.z = omega; odom.twist.twist.linear.x = vx; odom.twist.twist.linear.y = vy; /*std::cout<<"x="<<x; std::cout<<"y="<<x;*/ g_odom_pub.publish(odom); }// }//
#ifndef DWIZ_COMMON_STRING_UTILS_H #define DWIZ_COMMON_STRING_UTILS_H #include <common/dwiz_std.h> #include <string> #include <utility> namespace dwiz { /// Splits a string of the format "host:port" into host and port. /// Throws std::runtime_error if the string could not be parsed. std::pair<std::string, unsigned int> splitHostAndPort(std::string const& f_hostAndPort); } // namespace dwiz #endif
#pragma once #include"cocos2d.h" #include"HelloWorldScene.h" #include"time.h" #include"stdlib.h" #include"AStar.h" #include<fstream> #include"SimpleAudioEngine.h" #include"Result.h" USING_NS_CC; class MyResult; enum DIR { up=28,down=29,right=27,left=26 }; class SnakeNode :public cocos2d::Sprite{ public: static SnakeNode* create(const std::string &fileName) { SnakeNode * sprite = new SnakeNode(); if (sprite&& sprite->initWithFile(fileName)) { sprite->autorelease(); return sprite; } CC_SAFE_DELETE(sprite); return nullptr; } SnakeNode* pre; SnakeNode(SnakeNode *ptr = NULL) { this->pre = ptr; } }; class GameScene:public cocos2d::Scene { public: static cocos2d::Scene* createScene(); virtual bool init(); // a selector callback void menuCloseCallback(cocos2d::Ref* pSender); virtual void draw(cocos2d::Renderer *renderer, const cocos2d::Mat4& transform, uint32_t flags); virtual void myupdate(float dt); virtual void automatic(float dt); // implement the "static create()" method manually void CreatFood(); //键盘监听 virtual void onKeyPressed(cocos2d::EventKeyboard::KeyCode keyCode, cocos2d::Event*event); CREATE_FUNC(GameScene); void move(); void EatFood(); bool ReadWord(); void searchPath(); void ResetMap(); bool EatSelf();//检测吃到自己 bool IsOut();//检测是否出边框 static int sceneNum; protected: cocos2d::Size visibleSize; cocos2d::Vec2 origin; float contentScaleFactor; DIR dir;//蛇头的方向 SnakeNode *head; cocos2d::Sprite *food;//食物 cocos2d::Label *des;//单词释义 cocos2d::Label *ShowWord;//显示的单词 cocos2d::Label *Score;//分数 cocos2d::Label *Live;//生命 cocos2d::Label *SpeedLB;//速度显示 std::stack<Point*> Path; std::vector<SnakeNode*> SnakeBody; std::list<cocos2d::Sprite*> SnakeFood;//食物 std::ifstream fin;//文件流 std::string word;//当前单词 std::string description;//单词释义 std::string showstr;//显示的单词 std::string score_str; std::string live_str; int n;//蛇的长度 int current;//当前单词的第几个字母 int **map;//当前游戏的状态 0表示路,1表示起点,2表示障碍,3表示终点 int live;//生命数 int score;//分数 float speed;//速度 float autoSpeed;//自动寻路速度 bool isPlay;//音乐是否在播放 int SpeedLevel;//0慢,1中,2快 MyResult *p_Res;//修改游戏结束分数 };
/************************************************************* * > File Name : hdu3038.cpp * > Author : Tony * > Created Time : 2019/06/02 12:12:38 * > Algorithm : [DataStructure]UFSwithVal **************************************************************/ #include <bits/stdc++.h> using namespace std; const int maxn = 200010; int ans; struct UnionFindSet { int ufs[maxn], rank[maxn]; void init() { memset(rank, 0, sizeof(rank)); for (int i = 0; i < maxn - 10; ++i) { ufs[i] = i; } } int find(int x) { if (x == ufs[x]) return x; int fx = ufs[x]; ufs[x] = find(ufs[x]); rank[x] += rank[fx]; return ufs[x]; } void unionn(int a, int b, int s) { int x = find(a), y = find(b); if (x == y) { if (rank[a] + s != rank[b]) ans++; return; } else { ufs[y] = x; rank[y] = rank[a] + s - rank[b]; } } }ufs; int main() { int n, m; while (cin >> n >> m) { int a, b, s; ans = 0; ufs.init(); for (int i = 1; i <= m; ++i) { scanf("%d %d %d", &a, &b, &s); ufs.unionn(a, b + 1, s); } printf("%d\n", ans); } return 0; }
#include "arcpch.h" #include "DeferredLightingPass.h" #include <Arcane/Graphics/Window.h> #include <Arcane/Graphics/Shader.h> #include <Arcane/Graphics/Renderer/GLCache.h> #include <Arcane/Graphics/Camera/ICamera.h> #include <Arcane/Graphics/Renderer/Renderpass/Deferred/DeferredGeometryPass.h> #include <Arcane/Scene/Scene3D.h> #include <Arcane/Util/Loaders/ShaderLoader.h> namespace Arcane { DeferredLightingPass::DeferredLightingPass(Scene3D *scene) : RenderPass(scene), m_AllocatedFramebuffer(true) { m_LightingShader = ShaderLoader::LoadShader("deferred/PBR_LightingPass.glsl"); m_Framebuffer = new Framebuffer(Window::GetRenderResolutionWidth(), Window::GetRenderResolutionHeight(), false); m_Framebuffer->AddColorTexture(FloatingPoint16).AddDepthStencilTexture(NormalizedDepthStencil).CreateFramebuffer(); } DeferredLightingPass::DeferredLightingPass(Scene3D *scene, Framebuffer *customFramebuffer) : RenderPass(scene), m_AllocatedFramebuffer(false), m_Framebuffer(customFramebuffer) { m_LightingShader = ShaderLoader::LoadShader("deferred/PBR_LightingPass.glsl"); } DeferredLightingPass::~DeferredLightingPass() { if (m_AllocatedFramebuffer) { delete m_Framebuffer; } } LightingPassOutput DeferredLightingPass::executeLightingPass(ShadowmapPassOutput &shadowmapData, GeometryPassOutput &geometryData, PreLightingPassOutput &preLightingOutput, ICamera *camera, bool useIBL) { // Framebuffer setup glViewport(0, 0, m_Framebuffer->GetWidth(), m_Framebuffer->GetHeight()); glViewport(0, 0, m_Framebuffer->GetWidth(), m_Framebuffer->GetHeight()); m_Framebuffer->Bind(); m_Framebuffer->Clear(); m_GLCache->SetDepthTest(false); m_GLCache->SetMultisample(false); // Move the depth + stencil of the GBuffer to the our framebuffer // NOTE: Framebuffers have to have identical depth + stencil formats for this to work glBindFramebuffer(GL_READ_FRAMEBUFFER, geometryData.outputGBuffer->GetFramebuffer()); glBindFramebuffer(GL_DRAW_FRAMEBUFFER, m_Framebuffer->GetFramebuffer()); glBlitFramebuffer(0, 0, geometryData.outputGBuffer->GetWidth(), geometryData.outputGBuffer->GetHeight(), 0, 0, m_Framebuffer->GetWidth(), m_Framebuffer->GetHeight(), GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT, GL_NEAREST); // Setup initial stencil state m_GLCache->SetStencilTest(true); m_GLCache->SetStencilWriteMask(0x00); // Do not update stencil values DynamicLightManager *lightManager = m_ActiveScene->GetDynamicLightManager(); ProbeManager *probeManager = m_ActiveScene->GetProbeManager(); m_GLCache->SetShader(m_LightingShader); lightManager->BindLightingUniforms(m_LightingShader); m_LightingShader->SetUniform("viewPos", camera->GetPosition()); m_LightingShader->SetUniform("viewInverse", glm::inverse(camera->GetViewMatrix())); m_LightingShader->SetUniform("projectionInverse", glm::inverse(camera->GetProjectionMatrix())); // Bind GBuffer data geometryData.outputGBuffer->GetAlbedo()->Bind(4); m_LightingShader->SetUniform("albedoTexture", 4); geometryData.outputGBuffer->GetNormal()->Bind(5); m_LightingShader->SetUniform("normalTexture", 5); geometryData.outputGBuffer->GetMaterialInfo()->Bind(6); m_LightingShader->SetUniform("materialInfoTexture", 6); preLightingOutput.ssaoTexture->Bind(7); m_LightingShader->SetUniform("ssaoTexture", 7); geometryData.outputGBuffer->GetDepthStencilTexture()->Bind(8); m_LightingShader->SetUniform("depthTexture", 8); m_LightingShader->SetUniform("nearPlane", NEAR_PLANE); m_LightingShader->SetUniform("farPlane", FAR_PLANE); // Shadowmap code bindShadowmap(m_LightingShader, shadowmapData); // Finally perform the lighting using the GBuffer ModelRenderer *modelRenderer = m_ActiveScene->GetModelRenderer(); // IBL Binding probeManager->BindProbes(glm::vec3(0.0f, 0.0f, 0.0f), m_LightingShader); // Perform lighting on the terrain (turn IBL off) m_LightingShader->SetUniform("computeIBL", 0); m_GLCache->SetStencilFunc(GL_EQUAL, DeferredStencilValue::TerrainStencilValue, 0xFF); modelRenderer->NDC_Plane.Draw(); // Perform lighting on the models in the scene (turn IBL on) if (useIBL) { m_LightingShader->SetUniform("computeIBL", 1); } else { m_LightingShader->SetUniform("computeIBL", 0); } m_GLCache->SetStencilFunc(GL_EQUAL, DeferredStencilValue::ModelStencilValue, 0xFF); modelRenderer->NDC_Plane.Draw(); // Reset state m_GLCache->SetDepthTest(true); m_GLCache->SetStencilTest(false); // Render pass output LightingPassOutput passOutput; passOutput.outputFramebuffer = m_Framebuffer; return passOutput; } void DeferredLightingPass::bindShadowmap(Shader *shader, ShadowmapPassOutput &shadowmapData) { shadowmapData.shadowmapFramebuffer->GetDepthStencilTexture()->Bind(); shader->SetUniform("shadowmap", 0); shader->SetUniform("lightSpaceViewProjectionMatrix", shadowmapData.directionalLightViewProjMatrix); } }
// Copyright 2017 Global Phasing Ltd. #ifndef GEMMI_TO_CIF_HPP_ #define GEMMI_TO_CIF_HPP_ #include <fstream> #include "cifdoc.hpp" namespace gemmi { namespace cif { enum class Style { Simple, NoBlankLines, PreferPairs, // write single-row loops as pairs Pdbx, // PreferPairs + put '#' (empty comments) between categories Indent35, // start values in pairs from 35th column }; // CIF files are read in binary mode. It makes difference only for text fields. // If the text field with \r\n would be written as is in text mode on Windows // \r would get duplicated. As a workaround, here we convert \r\n to \n. // Hopefully \r that gets removed here is never meaningful. inline void write_text_field(std::ostream& os, const std::string& value) { for (size_t pos = 0, end = 0; end != std::string::npos; pos = end + 1) { end = value.find("\r\n", pos); size_t len = (end == std::string::npos ? value.size() : end) - pos; os.write(value.c_str() + pos, len); } } inline void write_out_pair(std::ostream& os, const std::string& name, const std::string& value, Style style) { os << name; if (is_text_field(value)) { os.put('\n'); write_text_field(os, value); } else { if (name.size() + value.size() > 120) os.put('\n'); else if (style == Style::Indent35 && name.size() < 34) os.write(" ", 34 - name.size()); else os.put(' '); os << value; } os.put('\n'); } inline void write_out_loop(std::ostream& os, const Loop& loop, Style style) { if (loop.values.empty()) return; if ((style == Style::PreferPairs || style == Style::Pdbx) && loop.length() == 1) { for (size_t i = 0; i != loop.tags.size(); ++i) write_out_pair(os, loop.tags[i], loop.values[i], style); return; } os << "loop_"; for (const std::string& tag : loop.tags) os << '\n' << tag; size_t ncol = loop.tags.size(); size_t col = 0; for (const std::string& val : loop.values) { bool text_field = is_text_field(val); os.put(col++ == 0 || text_field ? '\n' : ' '); if (text_field) write_text_field(os, val); else os << val; if (col == ncol) col = 0; } os.put('\n'); } inline void write_out_item(std::ostream& os, const Item& item, Style style) { switch (item.type) { case ItemType::Pair: write_out_pair(os, item.pair[0], item.pair[1], style); break; case ItemType::Loop: write_out_loop(os, item.loop, style); break; case ItemType::Frame: os << "save_" << item.frame.name << '\n'; for (const Item& inner_item : item.frame.items) write_out_item(os, inner_item, style); os << "save_\n"; break; case ItemType::Comment: os << item.pair[1] << '\n'; break; case ItemType::Erased: break; } } inline bool should_be_separted_(const Item& a, const Item& b) { if (a.type == ItemType::Comment || b.type == ItemType::Comment) return false; if (a.type != ItemType::Pair || b.type != ItemType::Pair) return true; // check if we have mmcif-like tags from different categories auto adot = a.pair[0].find('.'); if (adot == std::string::npos) return false; auto bdot = b.pair[0].find('.'); return adot != bdot || a.pair[0].compare(0, adot, b.pair[0], 0, adot) != 0; } inline void write_cif_to_stream(std::ostream& os, const Document& doc, Style s=Style::Simple) { bool first = true; for (const Block& block : doc.blocks) { if (!first) os.put('\n'); // extra blank line for readability os << "data_" << block.name << '\n'; if (s == Style::Pdbx) os << "#\n"; const Item* prev = nullptr; for (const Item& item : block.items) if (item.type != ItemType::Erased) { if (prev && s != Style::NoBlankLines && should_be_separted_(*prev, item)) os << (s == Style::Pdbx ? "#\n" : "\n"); write_out_item(os, item, s); prev = &item; } first = false; if (s == Style::Pdbx) os << "#\n"; } } inline void write_cif_to_file(const Document& doc, const std::string& filename, Style s=Style::Simple) { std::ofstream of(filename); if (!of) throw std::runtime_error("Failed to open " + filename); write_cif_to_stream(of, doc, s); of.close(); } } // namespace cif } // namespace gemmi #endif // vim:sw=2:ts=2:et
/* * Copyright (c) 2014, Julien Bernard * * Permission to use, copy, modify, and/or distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ #include <mm/erosion_score.h> #include <cmath> #include <mm/slope.h> namespace mm { double erosion_score::operator()(const heightmap& src) { typedef typename heightmap::size_type size_type; heightmap map = slope()(src); double total = 0.0; double total_sqr = 0.0; size_type n = 0; for (size_type x = 0; x < src.width(); ++x) { for (size_type y = 0; y < src.height(); ++y) { double value = map(x, y); total += value; total_sqr += value * value; n++; } } double avg = total / n; double avg_sqr = total_sqr / n; double std_dev = std::sqrt(avg_sqr - avg * avg); return std_dev / avg; } }
#include<bits/stdc++.h> using namespace std; bool solve(string str,set<string>& s) { string output=""; int n = str.length(); int i=0; while(i < n) { output+=str[i]; if(s.find(output)!=s.end()) { //word is present output=""; } i+=1; } if(output!="") { return false; } return true; } //recursion bool solve2(string str,set<string>& s) { if(str.size()==0) { return true; } if(str=="") { return true; } int n = str.size(); for(int i=1;i<=n;i++) { if(s.find(str.substr(0,i))!=s.end()) { // current prefix is present bool temp = solve2(str.substr(i),s); if(temp==true) { return true; } } } return false; } // iterative same as recursion using dp bool solve3(string str,set<string>& s) { int n = str.size(); bool* dp = new bool[n+1]();// word containing first i characters dp[0]=true; for(int i=1;i<=n;i++) { if(dp[i]==false && s.find(str.substr(0,i))!=s.end())// cur prefix is present in given dict { dp[i]=true; } if(dp[i]==true)// like in recursion we will check the remaining substring { if(i==n) { return true; } for(int j = i+1;j<=n;j++) { if(dp[j]==false && s.find(str.substr(i,j-i))!=s.end()) { // prefix from i is present dp[j]=true; } if(j==n && dp[j]==true) { // remainining is present return true; } } } } delete[] dp; return false; } int main() { int t; cin >> t; while(t--) { int n; cin >> n; set<string> s; for(int i=0;i<n;i++) { string input; cin >> input; s.insert(input); } string str; cin >> str; cout << solve3(str,s) << endl; } return 0; }
//----------------------------------------------- // // This file is part of the Siv3D Engine. // // Copyright (c) 2008-2018 Ryo Suzuki // Copyright (c) 2016-2018 OpenSiv3D Project // // Licensed under the MIT License. // //----------------------------------------------- # pragma once # include "IWebcam.hpp" # include <Siv3D/Webcam.hpp> # include <Siv3D/Image.hpp> # include <opencv2/videoio.hpp> namespace s3d { enum class WebcamState { None, Ready, Active, Pause, Stop, HasError, }; struct WebcamData { cv::VideoCapture m_capture; Size m_resolution = Size(0, 0); cv::Mat_<cv::Vec3b> m_frame; Image m_image; std::thread m_thread; std::atomic<WebcamState> m_state = WebcamState::None; std::mutex m_imageMutex; std::atomic<int32> m_newFrameCount = 0; static void OnRunning(WebcamData& webcam, const int32 index); ~WebcamData(); bool open(size_t index); void initResolution(); bool setResolution(const Size& resolution); bool retrieve(); void release(); const Size& getResolution() const; bool start(int32 index); void stop(); bool hasNewFrame() const; bool getFrame(Image& image); bool getFrame(DynamicTexture& texture); }; class Webcam::WebcamDetail { private: size_t m_index = 0; bool m_available = false; bool m_isActive = false; WebcamData m_webcam; public: WebcamDetail(size_t index); ~WebcamDetail(); bool isAvailable() const; bool start(); void stop(); bool isActive() const; size_t index() const; Size getResolution() const; bool setResolution(const Size& resolution); bool hasNewFrame() const; bool getFrame(Image& image); bool getFrame(DynamicTexture& texture); }; }
#ifndef TRUTHTABLE_H #define TRUTHTABLE_H typedef class truthtable { public: truthtable(int number, bool display = false); ~truthtable(); private: char* _toBinString(long long int); void _iterateTillZero(long long int); long long int _digits; bool _display; long long int _rows; } tt; #endif
#include"iostream" using namespace std; int main(){ int size; cout<<"enter the array size"; cin>>size; int arr[size]; cout<<"enter the array elements"; for(int i=0;i<size;i++){ cin>>arr[i]; } int lsum,rsum; for(int i=0;i<size;i++){ for(int j=i+1;j<size;j++){ lsum=0; rsum=0; for(int r=0;r<i;r++){ lsum=lsum+arr[r]; } for(int r=j;r<size;r++){ rsum=rsum+arr[r]; } if(lsum==rsum){ cout<<endl<<"there exist a element "<<arr[i]; cout<<endl<<lsum<<" "<<rsum; break; } } } return 0; }
#include <iostream> using namespace std; int FromBin (int n) { int increment; int Result; increment = 1; Result = 0; while(n != 0) { if (n % 10 == 1){ Result = Result+increment; n = n-1; } n = n/10; increment = increment*2; } cout<<Result; } void ToBin(int n) { if (n / 2 != 0) { ToBin(n / 2); } cout<<n % 2; } int main() { int choice; int n; cout<<"Choose a function: press 0 for decimals to binary, press 1 for binary to decimal\n"; cin>>choice; if (choice == 0){ cout<<"Enter a number: \n"; cin>>n; ToBin(n); } else if (choice == 1){ cout<<"Enter a number: \n"; cin>>n; FromBin(n); } else{ cout<<"Invalid input"; } }
#include "Primitive.h" #include "tinyxml2.h" #include "Base/ParseHelper.h" #include "Shape/Shape.h" #include <assert.h> #include "Material/Material.h" #include "Light/AreaLight.h" #include "Base/PCH.h" Primitive::Primitive() { mMaterialPtr = nullptr; mAreaLightPtr = nullptr; } Primitive::~Primitive() { // --------------------Shape------------------------ { auto it = mvShapeList.begin(); while ( it != mvShapeList.end() ) { it = mvShapeList.erase( it ); } } { auto it = mvShapeInformationList.begin(); while ( it != mvShapeInformationList.end() ) { SAFE_DELETE( *it ); it = mvShapeInformationList.erase( it ); } } // ------------------Material----------------------- SAFE_DELETE( mMaterialPtr ); } void Primitive::Deserialization( tinyxml2::XMLElement* RootElement ) { { const char* name = RootElement->Attribute( "name" ); mName.insert( mName.size() , name , strlen( name ) ); } if ( RootElement->Attribute( "uvscale" ) ) { ParseVector( RootElement->Attribute( "uvscale" ) , &mTexScale[0] ); } else { mTexScale = Vector2f( 1.0 , 1.0 ); } tinyxml2::XMLElement* ShapeRootElement = RootElement->FirstChildElement( "shape" ); while ( ShapeRootElement ) { DeserializationShape( ShapeRootElement ); ShapeRootElement = ShapeRootElement->NextSiblingElement( "shape" ); } tinyxml2::XMLElement* MaterialRootElement = RootElement->FirstChildElement( "material" ); DeserializationMaterial( MaterialRootElement ); tinyxml2::XMLElement* AreaLightRootElement = RootElement->FirstChildElement( "AreaLight" ); DeserializationAreaLight( AreaLightRootElement ); } void Primitive::DeserializationShape( tinyxml2::XMLElement* ShapeRootElement ) { const char* type = ShapeRootElement->Attribute( "type" ); Shape* shape = Shape::Create( type ); assert( shape != nullptr ); shape->Deserialization( ShapeRootElement ); // 记录反序列化信息 mvShapeInformationList.push_back( shape ); if ( shape->mbHasSubShape ) { for ( int i = 0; i < shape->GetSubShapeCount(); i++ ) { AddShape( shape->GetSubShape( i ) ); } } else { AddShape( shape ); } } void Primitive::DeserializationMaterial( tinyxml2::XMLElement* MaterialRootElement ) { const char* MaterialType = MaterialRootElement->Attribute( "type" ); mMaterialPtr = Material::Create( MaterialType ); assert( mMaterialPtr != nullptr ); mMaterialPtr->Deserialization( MaterialRootElement ); } void Primitive::DeserializationAreaLight( tinyxml2::XMLElement* AreaLightRootElement ) { if ( AreaLightRootElement ) { mAreaLightPtr = new AreaLight; mAreaLightPtr->Deserialization( AreaLightRootElement ); mAreaLightPtr->SetPrimitive( this ); } } void Primitive::Serialization( tinyxml2::XMLDocument& xmlDoc , tinyxml2::XMLElement* pRootElement ) { pRootElement->SetAttribute( "name" , mName.c_str() ); for ( auto& shape : mvShapeInformationList ) { tinyxml2::XMLElement* pElement = xmlDoc.NewElement( "shape" ); shape->Serialization( xmlDoc , pElement ); pRootElement->InsertEndChild( pElement ); } if ( mMaterialPtr != nullptr ) { tinyxml2::XMLElement* pElement = xmlDoc.NewElement( "material" ); mMaterialPtr->Serialization( xmlDoc , pElement ); pRootElement->InsertEndChild( pElement ); } if ( mAreaLightPtr != nullptr ) { tinyxml2::XMLElement* pElement = xmlDoc.NewElement( "AreaLight" ); mAreaLightPtr->Serialization( xmlDoc , pElement ); pRootElement->InsertEndChild( pElement ); } } void Primitive::AddShape( Shape* shape ) { shape->SetPrimitive( this ); mvShapeList.push_back( shape ); } AreaLight* Primitive::GetAreaLight() const { return mAreaLightPtr; } int Primitive::GetSubShapeCount() { return mvShapeInformationList.size(); } Shape* Primitive::GetSubShape( unsigned int index ) { return mvShapeInformationList[index]; } Material* Primitive::GetMaterial() { return mMaterialPtr; } std::string& Primitive::GetName() { return mName; }
// -*- C++ -*- // // Copyright (C) 1998, 1999, 2000, 2002 Los Alamos National Laboratory, // Copyright (C) 1998, 1999, 2000, 2002 CodeSourcery, LLC // // This file is part of FreePOOMA. // // FreePOOMA is free software; you can redistribute it and/or modify it // under the terms of the Expat license. // // This program 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 Expat // license for more details. // // You should have received a copy of the Expat license along with // FreePOOMA; see the file LICENSE. // #ifndef POOMA_CONNECT_PAWS_PAWS_CONNECTION_H #define POOMA_CONNECT_PAWS_PAWS_CONNECTION_H //----------------------------------------------------------------------------- // Classes: // Connection<Paws> //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- // Overview: // // Connection<Paws> is a ConnectionBase subclass that manages a connection // to a another program, using the Paws library for inter-app communication. // When a Connection<Paws> object is created, it will initialize the Paws // library and connect to the Paws controller. This is a specialization // of the Connection class, using the simple tag class "Paws" to specialize. // //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- // Include Files //----------------------------------------------------------------------------- #include "Connect/Connection.h" #include "Connect/Paws/PawsAppPointer.h" #include "Utilities/PAssert.h" //----------------------------------------------------------------------------- // Forward Declarations //----------------------------------------------------------------------------- class Paws; //----------------------------------------------------------------------------- // // Full Description: // // Connection<Paws> is a specialization of Connection<T> that maintains // a connection for this application to a Paws controller and other // Paws apps. It stores (via PawsAppPointer) a PawsApplication instance // used to establish and access this connection. // // When created, Connection<Paws> will create a PawsApplication instance // (or use an existing one if available), and register this app with the // provided string name with the Paws controller. Command-line parameters // must be provided that include special Paws flags to indicate the // location of the Paws controller and other settings. // // Once registered with the controller, connectors can be created that will // register individual data objects for sharing with other Paws apps. // // Connection<Paws> includes some extra methods not in the base class: // ready() indicates this application will wait for a "ready" signal // from the controller. ready() will not return until that signal // has been given (or if the application is not connected at all). // poll() gives Paws a chance to check for Paws-specific events and // process them. This is generally not something the user ever // has to call. // //----------------------------------------------------------------------------- /////////////////////////////////////////////////////////////////////////////// // namespace POOMA { template<> class Connection<Paws> : public ConnectionBase { public: //============================================================ // Public typedefs and enums //============================================================ typedef Paws ConnectionTag_t; typedef Connection<Paws> Connection_t; //============================================================ // Connection<Paws> Constructor //============================================================ // The constructor takes a string name; the type is "paws". It also // takes the argc, argv of the program, for use in initializing PAWS. Connection(const char *conname, int argc, char *argv[]) : ConnectionBase(conname, "paws"), paws_m(conname, argc, argv) { } //============================================================ // Connection<Paws> Destructor //============================================================ // Connection<Paws> destructor. Remove all connectors and close Paws link. virtual ~Connection() { close(); } //============================================================ // Connection<Paws> accessors //============================================================ // Return whether we are connected properly right now. virtual bool connected() const { return paws_m.connected(); } // Return the Paws connection object. inline PawsApplication &paws() const { return paws_m.paws(); } //============================================================ // Connection<Paws> operations //============================================================ // NOTE: The basic operations are all inherited from the base class. // The extra routines here are specific to a Connection<Paws>. // Perform a Paws poll. inline void poll() { paws_m.poll(); } // Wait for a ready signal from the Paws controller. inline void ready() { paws_m.ready(); } // Completely close the connection and remove all connectors. This is // the equivalent of running the destructor, using this routine you can // control when the connection is closed. This removes all connectors // and shuts down link to Paws controller. virtual void close() { disconnectConnectors(); paws_m.close(); } // Connect in an object of type T. This will create a new Connector // instance and add it in to our list of connected items. template<class T> ConnectorBase *connect(const char *cname, const T &obj, int mode) { ConnectorBase *cb = new Connector<T,Paws>(cname, obj, *this, mode); return ConnectionBase::connect(cb); } // Connect in an object of type T, by providing a non-const ref. The // connection will use this reference. This should be used for // types that cannot be specified with a const-ref, like regular // scalars. template<class T> ConnectorBase *connectScalar(const char *cname, T &obj, int mode) { ConnectorBase *cb = new Connector<T,Paws>(cname, obj, *this, mode); return ConnectionBase::connect(cb); } private: // The Paws connection object, managed by PawsAppPointer. PawsAppPointer paws_m; // The default and copy constructors are made private and undefined // since they should not be used Connection(); Connection(const Connection_t &); Connection_t &operator=(const Connection_t &); }; // } // namespace POOMA ////////////////////////////////////////////////////////////////////// #endif // POOMA_CONNECT_PAWS_PAWS_CONNECTION_H // ACL:rcsinfo // ---------------------------------------------------------------------- // $RCSfile: PawsConnection.h,v $ $Author: richard $ // $Revision: 1.5 $ $Date: 2004/11/01 18:16:19 $ // ---------------------------------------------------------------------- // ACL:rcsinfo
#include "Button.h" enum buttonStates { BTN_IDLE = 0, BTN_HOVER, BTN_ACTIVE }; Button::Button(float x, float y, float width, float height, std::string text, float size, sf::Font font, sf::Color idleColor, sf::Color hoverColor, sf::Color activeColor) { // Default button state this->buttonState = BTN_IDLE; // Button size and position this->shape.setPosition(sf::Vector2f(x, y)); this->shape.setSize(sf::Vector2f(width, height)); // Button color this->idleColor = idleColor; this->hoverColor = hoverColor; this->activeColor = activeColor; // Button text this->font = font; this->text.setFont(this->font); this->text.setString(text); this->text.setCharacterSize(size); this->text.setFillColor(sf::Color::White); this->text.setPosition( this->shape.getPosition().x + this->shape.getGlobalBounds().width / 2 - this->text.getGlobalBounds().width / 2, this->shape.getPosition().y + this->shape.getGlobalBounds().height / 3 - this->text.getGlobalBounds().height / 2 ); } void Button::checkClick(const sf::Vector2f mousePos) { this->buttonState = BTN_IDLE; if (this->shape.getGlobalBounds().contains(mousePos)) { this->buttonState = BTN_HOVER; if (sf::Mouse::isButtonPressed(sf::Mouse::Left)) this->buttonState = BTN_ACTIVE; } switch (this->buttonState) { case BTN_IDLE: this->shape.setFillColor(this->idleColor); break; case BTN_HOVER: this->shape.setFillColor(this->hoverColor); break; case BTN_ACTIVE: this->shape.setFillColor(this->activeColor); break; default: this->shape.setFillColor(this->idleColor); break; } } const bool Button::isPressed() const { if (this->buttonState == BTN_ACTIVE) return true; return false; } void Button::render(sf::RenderTarget* target) { target->draw(this->shape); target->draw(this->text); }
/* Copyright (c) 2005-2023, University of Oxford. All rights reserved. University of Oxford means the Chancellor, Masters and Scholars of the University of Oxford, having an administrative office at Wellington Square, Oxford OX1 2JD, UK. This file is part of Chaste. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the University of Oxford nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef TESTCABASEDDIVISIONRULE_HPP_ #define TESTCABASEDDIVISIONRULE_HPP_ #include <cxxtest/TestSuite.h> #include <boost/archive/text_oarchive.hpp> #include <boost/archive/text_iarchive.hpp> #include "ArchiveOpener.hpp" #include "CellsGenerator.hpp" #include "CaBasedCellPopulation.hpp" #include "FixedG1GenerationalCellCycleModel.hpp" #include "AbstractCellBasedTestSuite.hpp" #include "AbstractCaBasedDivisionRule.hpp" #include "ExclusionCaBasedDivisionRule.hpp" #include "ShovingCaBasedDivisionRule.hpp" #include "PottsMeshGenerator.hpp" #include "SmartPointers.hpp" //This test is always run sequentially (never in parallel) #include "FakePetscSetup.hpp" class TestCaBasedDivisionRules : public AbstractCellBasedTestSuite { public: void TestAddCellwithExclusionBasedDivisionRule() { /** * In this test we basically test that the AbstractCaBasedDivisionRule is implemented and joined with the population * correctly. We make a new ExclusionCaBasedDivisionRule, divide a cell with it and check that the new cells * are in the correct locations. */ // Make a simple Potts mesh PottsMeshGenerator<2> generator(3, 0, 0, 3, 0, 0); PottsMesh<2>* p_mesh = generator.GetMesh(); // Create 6 cells in the bottom 2 rows std::vector<unsigned> location_indices; for (unsigned index=0; index<6; index++) { location_indices.push_back(index); } std::vector<CellPtr> cells; CellsGenerator<FixedG1GenerationalCellCycleModel, 1> cells_generator; cells_generator.GenerateBasic(cells, location_indices.size()); // Create cell population CaBasedCellPopulation<2> cell_population(*p_mesh, cells, location_indices); CellPtr p_cell_0 = cell_population.GetCellUsingLocationIndex(0); MAKE_PTR(WildTypeCellMutationState, p_state); MAKE_PTR(StemCellProliferativeType, p_stem_type); FixedG1GenerationalCellCycleModel* p_model = new FixedG1GenerationalCellCycleModel(); CellPtr p_temp_cell(new Cell(p_state, p_model)); p_temp_cell->SetCellProliferativeType(p_stem_type); p_temp_cell->SetBirthTime(-1); // Set the division rule for our population to be the exclusion division rule (note that this is the default boost::shared_ptr<AbstractCaBasedDivisionRule<2> > p_division_rule_to_set(new ExclusionCaBasedDivisionRule<2>()); cell_population.SetCaBasedDivisionRule(p_division_rule_to_set); // Get the division rule back from the population and try to add new cell by dividing cell at site 0; boost::shared_ptr<AbstractCaBasedDivisionRule<2> > p_division_rule = cell_population.GetCaBasedDivisionRule(); CellPtr p_parent_cell = cell_population.GetCellUsingLocationIndex(0); TS_ASSERT(!(p_division_rule->IsRoomToDivide(p_parent_cell,cell_population))); // Test adding the new cell in the population (note this calls CalculateDaughterNodeIndex) TS_ASSERT_THROWS_THIS(cell_population.AddCell(p_cell_0, p_parent_cell), "Trying to divide when there is no room to divide, check your division rule"); // Test adding it in a free space p_parent_cell = cell_population.GetCellUsingLocationIndex(4); TS_ASSERT(p_division_rule->IsRoomToDivide(p_parent_cell,cell_population)); TS_ASSERT_EQUALS(p_division_rule->CalculateDaughterNodeIndex(p_cell_0,p_parent_cell,cell_population), 7u); // Test adding the new cell in the population (note this calls CalculateDaughterNodeIndex) cell_population.AddCell(p_cell_0, p_parent_cell); // Now check the cells are in the correct place TS_ASSERT_EQUALS(cell_population.GetNumRealCells(), 7u); } void TestArchivingExclusionCaBasedDivisionRule() { EXIT_IF_PARALLEL; // Beware of processes overwriting the identical archives of other processes OutputFileHandler handler("archive", false); std::string archive_filename = handler.GetOutputDirectoryFullPath() + "ExclusionCaBasedDivisionRule.arch"; { ExclusionCaBasedDivisionRule<2> division_rule; std::ofstream ofs(archive_filename.c_str()); boost::archive::text_oarchive output_arch(ofs); // Serialize via pointer to most abstract class possible AbstractCaBasedDivisionRule<2>* const p_division_rule = &division_rule; output_arch << p_division_rule; } { AbstractCaBasedDivisionRule<2>* p_division_rule; // Create an input archive std::ifstream ifs(archive_filename.c_str(), std::ios::binary); boost::archive::text_iarchive input_arch(ifs); // Restore from the archive input_arch >> p_division_rule; TS_ASSERT(p_division_rule != NULL); // Tidy up delete p_division_rule; } } void TestAddCellWithShovingBasedDivisionRule() { /** * In this test we create a new ShovingCaBasedDivisionRule, divide a cell with it * and check that the new cells are in the correct locations. First, we test where * there is space around the cells. This is the default setup. */ // Create a simple Potts mesh PottsMeshGenerator<2> generator(5, 0, 0, 5, 0, 0); PottsMesh<2>* p_mesh = generator.GetMesh(); // Create 9 cells in the central nodes std::vector<unsigned> location_indices; for (unsigned row=1; row<4; row++) { location_indices.push_back(1+row*5); location_indices.push_back(2+row*5); location_indices.push_back(3+row*5); } std::vector<CellPtr> cells; CellsGenerator<FixedG1GenerationalCellCycleModel, 1> cells_generator; cells_generator.GenerateBasic(cells, location_indices.size()); // Create cell population CaBasedCellPopulation<2> cell_population(*p_mesh, cells, location_indices); // Check the cell locations unsigned cell_locations[9] = {6, 7, 8, 11, 12, 13, 16, 17, 18}; unsigned index = 0; for (AbstractCellPopulation<2>::Iterator cell_iter = cell_population.Begin(); cell_iter != cell_population.End(); ++cell_iter) { TS_ASSERT_EQUALS(cell_population.GetLocationIndexUsingCell(*cell_iter),cell_locations[index]) ++index; } // Make a new cell to add MAKE_PTR(WildTypeCellMutationState, p_state); MAKE_PTR(StemCellProliferativeType, p_stem_type); FixedG1GenerationalCellCycleModel* p_model = new FixedG1GenerationalCellCycleModel(); CellPtr p_new_cell(new Cell(p_state, p_model)); p_new_cell->SetCellProliferativeType(p_stem_type); p_new_cell->SetBirthTime(-1); // Set the division rule for our population to be the shoving division rule boost::shared_ptr<AbstractCaBasedDivisionRule<2> > p_division_rule_to_set(new ShovingCaBasedDivisionRule<2>()); cell_population.SetCaBasedDivisionRule(p_division_rule_to_set); // Get the division rule back from the population and try to add new cell by dividing cell at site 0 boost::shared_ptr<AbstractCaBasedDivisionRule<2> > p_division_rule = cell_population.GetCaBasedDivisionRule(); // Select central cell CellPtr p_cell_12 = cell_population.GetCellUsingLocationIndex(12); // The ShovingCaBasedDivisionRule method IsRoomToDivide() always returns true TS_ASSERT_EQUALS((p_division_rule->IsRoomToDivide(p_cell_12, cell_population)), true); /* * Test adding the new cell to the population; this calls CalculateDaughterNodeIndex(). * The new cell moves into node 13. */ cell_population.AddCell(p_new_cell, p_cell_12); // Now check the cells are in the correct place TS_ASSERT_EQUALS(cell_population.GetNumRealCells(), 10u); // Note the cell originally on node 13 has been shoved to node 14 and the new cell is on node 13 unsigned new_cell_locations[10] = {6, 7, 8, 11, 12, 14, 16, 17, 18, 13}; index = 0; for (AbstractCellPopulation<2>::Iterator cell_iter = cell_population.Begin(); cell_iter != cell_population.End(); ++cell_iter) { TS_ASSERT_EQUALS(cell_population.GetLocationIndexUsingCell(*cell_iter), new_cell_locations[index]) ++index; } } void TestAddCellWithShovingBasedDivisionRuleAndShovingRequired() { /** * In this test of ShovingCaBasedDivisionRule we check the case where there is * no room to divide without the cells being shoved to the edge of the mesh. */ // Create a simple Potts mesh PottsMeshGenerator<2> generator(5, 0, 0, 5, 0, 0); PottsMesh<2>* p_mesh = generator.GetMesh(); // Create 25 cells, one for each node std::vector<unsigned> location_indices; for (unsigned index=0; index<25; index++) { location_indices.push_back(index); } std::vector<CellPtr> cells; CellsGenerator<FixedG1GenerationalCellCycleModel, 1> cells_generator; cells_generator.GenerateBasic(cells, location_indices.size()); // Create cell population CaBasedCellPopulation<2> cell_population(*p_mesh, cells, location_indices); // Make a new cell to add MAKE_PTR(WildTypeCellMutationState, p_state); MAKE_PTR(StemCellProliferativeType, p_stem_type); FixedG1GenerationalCellCycleModel* p_model = new FixedG1GenerationalCellCycleModel(); CellPtr p_new_cell(new Cell(p_state, p_model)); p_new_cell->SetCellProliferativeType(p_stem_type); p_new_cell->SetBirthTime(-1); // Set the division rule for our population to be the shoving division rule boost::shared_ptr<AbstractCaBasedDivisionRule<2> > p_division_rule_to_set(new ShovingCaBasedDivisionRule<2>()); cell_population.SetCaBasedDivisionRule(p_division_rule_to_set); // Get the division rule back from the population and try to add new cell by dividing cell at site 0; boost::shared_ptr<AbstractCaBasedDivisionRule<2> > p_division_rule = cell_population.GetCaBasedDivisionRule(); // Select central cell CellPtr p_cell_12 = cell_population.GetCellUsingLocationIndex(12); // Try to divide but cant as hit boundary TS_ASSERT_THROWS_THIS(p_division_rule->CalculateDaughterNodeIndex(p_new_cell, p_cell_12, cell_population), "Cells reaching the boundary of the domain. Make the Potts mesh larger."); } void TestArchivingShovingCaBasedDivisionRule() { EXIT_IF_PARALLEL; // Beware of processes overwriting the identical archives of other processes OutputFileHandler handler("archive", false); std::string archive_filename = handler.GetOutputDirectoryFullPath() + "ShovingCaBasedDivisionRule.arch"; { ShovingCaBasedDivisionRule<2> division_rule; std::ofstream ofs(archive_filename.c_str()); boost::archive::text_oarchive output_arch(ofs); // Serialize via pointer to most abstract class possible AbstractCaBasedDivisionRule<2>* const p_division_rule = &division_rule; output_arch << p_division_rule; } { AbstractCaBasedDivisionRule<2>* p_division_rule; // Create an input archive std::ifstream ifs(archive_filename.c_str(), std::ios::binary); boost::archive::text_iarchive input_arch(ifs); // Restore from the archive input_arch >> p_division_rule; TS_ASSERT(p_division_rule != NULL); // Tidy up delete p_division_rule; } } }; #endif /*TESTCABASEDDIVISIONRULE_HPP_*/
#ifndef ROSE_X86INSTRUCTIONSEMANTICS_H #define ROSE_X86INSTRUCTIONSEMANTICS_H /* See tests/roseTests/binaryTests/SemanticVerification for ideas about how to test your work here. Note that the test is not * run automatically because it depends on setting up a slave machine who's architecture is what is being simulated by the * instruction semantics (not necessarily the same architecture that's running ROSE). */ #include "semanticsModule.h" #include <cassert> #include <cstdio> #include <iostream> #include "integerOps.h" #include "AsmUnparser_compat.h" /* for unparseInstructionWithAddress() */ /* Returns the segment register corresponding to the specified register reference address expression. */ static inline X86SegmentRegister getSegregFromMemoryReference(SgAsmMemoryReferenceExpression* mr) { X86SegmentRegister segreg = x86_segreg_none; SgAsmx86RegisterReferenceExpression* seg = isSgAsmx86RegisterReferenceExpression(mr->get_segment()); if (seg) { ROSE_ASSERT(seg->get_descriptor().get_major() == x86_regclass_segment); segreg = (X86SegmentRegister)(seg->get_descriptor().get_minor()); } else { ROSE_ASSERT(!"Bad segment expr"); } if (segreg == x86_segreg_none) segreg = x86_segreg_ds; return segreg; } namespace BinaryAnalysis { namespace InstructionSemantics { /** Translation class. Translates x86 instructions to RISC-like operations and invokes those operations in the supplied * semantic policy (a template argument). See the BinaryAnalysis::InstructionSemantics name space for details. Apologies for * the lack of documentation for this class. You can at least find some examples in the semantics.C file of the * tests/roseTests/binaryTests directory, among others. */ template <typename Policy, template <size_t> class WordType> struct X86InstructionSemantics { # ifdef Word # error "Having a macro called \"Word\" conflicts with x86InstructionSemantics.h" # else # define Word(Len) WordType<(Len)> # endif struct Exception { Exception(const std::string &mesg, SgAsmInstruction *insn): mesg(mesg), insn(insn) {} friend std::ostream& operator<<(std::ostream &o, const Exception &e) { o <<"instruction semantics: " <<e.mesg; if (e.insn) o <<" [" <<unparseInstructionWithAddress(e.insn) <<"]"; return o; } std::string mesg; SgAsmInstruction *insn; }; Policy& policy; SgAsmInstruction *current_instruction; Word(32) orig_eip; // set at the top of translate() /* Registers used explicitly by this class. */ RegisterDescriptor REG_EAX, REG_EBX, REG_ECX, REG_EDX, REG_EDI, REG_EIP, REG_ESI, REG_ESP, REG_EBP; RegisterDescriptor REG_AX, REG_CX, REG_DX, REG_AL, REG_AH; RegisterDescriptor REG_EFLAGS, REG_AF, REG_CF, REG_DF, REG_OF, REG_PF, REG_SF, REG_ZF; X86InstructionSemantics(Policy& policy) : policy(policy), current_instruction(NULL), orig_eip(policy.readRegister<32>(policy.findRegister("eip"))) { REG_EAX = policy.findRegister("eax", 32); REG_EBX = policy.findRegister("ebx", 32); REG_ECX = policy.findRegister("ecx", 32); REG_EDX = policy.findRegister("edx", 32); REG_EDI = policy.findRegister("edi", 32); REG_EIP = policy.findRegister("eip", 32); REG_ESI = policy.findRegister("esi", 32); REG_ESP = policy.findRegister("esp", 32); REG_EBP = policy.findRegister("ebp", 32); REG_AX = policy.findRegister("ax", 16); REG_CX = policy.findRegister("cx", 16); REG_DX = policy.findRegister("dx", 16); REG_AL = policy.findRegister("al", 8); REG_AH = policy.findRegister("ah", 8); REG_EFLAGS=policy.findRegister("eflags", 32); REG_AF = policy.findRegister("af", 1); REG_CF = policy.findRegister("cf", 1); REG_DF = policy.findRegister("df", 1); REG_OF = policy.findRegister("of", 1); REG_PF = policy.findRegister("pf", 1); REG_SF = policy.findRegister("sf", 1); REG_ZF = policy.findRegister("zf", 1); } virtual ~X86InstructionSemantics() {} /** Beginning of a 'rep', 'repe', or 'repne' loop. The return value is the condition status, and is true if the loop body * should execute, false otherwise. */ WordType<1> rep_enter() { return policy.invert(policy.equalToZero(readRegister<32>(REG_ECX))); } /** Decrement the counter for a 'rep', 'repe', or 'repne' loop and adjust the instruction pointer. The instruction pointer * is reset to the beginning of the instruction if the loop counter, cx register, is non-zero after decrementing and @p * repeat is true. Otherwise the instruction pointer is not adjusted and the loop effectively exits. If @p cond is false * then this function has no effect on the state. */ void rep_repeat(SgAsmx86Instruction *insn, WordType<1> repeat, WordType<1> cond) { WordType<32> new_cx = policy.add(readRegister<32>(REG_ECX), policy.ite(cond, number<32>(-1), number<32>(0))); writeRegister(REG_ECX, new_cx); repeat = policy.and_(repeat, policy.invert(policy.equalToZero(new_cx))); writeRegister(REG_EIP, policy.ite(policy.and_(cond, repeat), orig_eip, /* repeat */ readRegister<32>(REG_EIP))); /* exit */ } /** Return the value of the memory pointed to by the SI register. */ template<size_t N> WordType<8*N> stringop_load_si(SgAsmx86Instruction *insn, WordType<1> cond) { return readMemory<8*N>((insn->get_segmentOverride() == x86_segreg_none ? x86_segreg_ds : insn->get_segmentOverride()), readRegister<32>(REG_ESI), cond); } /** Return the value of memory pointed to by the DI register. */ template<size_t N> WordType<8*N> stringop_load_di(WordType<1> cond) { return readMemory<8*N>(x86_segreg_es, readRegister<32>(REG_EDI), cond); } /** Instruction semantics for stosN where N is 1 (b), 2 (w), or 4 (d). If @p cond is false then this instruction does not * change any state. */ template<size_t N> void stos_semantics(SgAsmx86Instruction *insn, WordType<1> cond) { const SgAsmExpressionPtrList& operands = insn->get_operandList()->get_operands(); if (operands.size()!=0) throw Exception("instruction must have no operands", insn); if (insn->get_addressSize()!=x86_insnsize_32) throw Exception("address size must be 32 bits", insn); /* Fill memory pointed to by ES:[DI] with contents of AX. */ policy.writeMemory(x86_segreg_es, readRegister<32>(REG_EDI), extract<0, 8*N>(readRegister<32>(REG_EAX)), cond); /* Update DI */ writeRegister(REG_EDI, policy.ite(cond, policy.add(readRegister<32>(REG_EDI), policy.ite(readRegister<1>(REG_DF), number<32>(-N), number<32>(N))), readRegister<32>(REG_EDI))); } /** Instruction semantics for rep_stosN where N is 1 (b), 2 (w), or 4 (d). This method handles semantics for one iteration * of stosN. See https://siyobik.info/index.php?module=x86&id=279 */ template<size_t N> void rep_stos_semantics(SgAsmx86Instruction *insn) { WordType<1> in_loop = rep_enter(); stos_semantics<N>(insn, in_loop); rep_repeat(insn, policy.true_(), in_loop); } /** Instruction semantics for movsN where N is 1 (b), 2 (w), or 4 (d). If @p cond is false then this instruction does not * change any state. */ template<size_t N> void movs_semantics(SgAsmx86Instruction *insn, WordType<1> cond) { const SgAsmExpressionPtrList &operands = insn->get_operandList()->get_operands(); if (operands.size()!=0) throw Exception("instruction must have no operands", insn); if (insn->get_addressSize() != x86_insnsize_32) throw Exception("size not implemented", insn); policy.writeMemory(x86_segreg_es, readRegister<32>(REG_EDI), stringop_load_si<N>(insn, cond), cond); writeRegister(REG_ESI, policy.add(readRegister<32>(REG_ESI), policy.ite(cond, policy.ite(readRegister<1>(REG_DF), number<32>(-(N)), number<32>(N)), number<32>(0)))); writeRegister(REG_EDI, policy.add(readRegister<32>(REG_EDI), policy.ite(cond, policy.ite(readRegister<1>(REG_DF), number<32>(-(N)), number<32>(N)), number<32>(0)))); } /** Instruction semantics for rep_movsN where N is 1 (b), 2 (w), or 4 (d). This method handles semantics for one iteration * of the instruction. */ template<size_t N> void rep_movs_semantics(SgAsmx86Instruction *insn) { WordType<1> in_loop = rep_enter(); movs_semantics<N>(insn, in_loop); rep_repeat(insn, policy.true_(), in_loop); } /** Instruction semantics for cmpsN where N is 1 (b), 2 (w), or 4 (d). If @p cond is false then this instruction does not * change any state. See Intel Instruction Set Reference 3-154 Vol 2a, March 2009 for opcodes 0xa6 and 0xa7 with no prefix. */ template<size_t N> void cmps_semantics(SgAsmx86Instruction *insn, WordType<1> cond) { const SgAsmExpressionPtrList &operands = insn->get_operandList()->get_operands(); if (operands.size()!=0) throw Exception("instruction must have no operands", insn); if (insn->get_addressSize() != x86_insnsize_32) throw Exception("size not implemented", insn); doAddOperation<8*N>(stringop_load_si<N>(insn, cond), policy.invert(stringop_load_di<N>(cond)), true, policy.false_(), cond); writeRegister(REG_ESI, policy.ite(cond, policy.add(readRegister<32>(REG_ESI), policy.ite(readRegister<1>(REG_DF), number<32>(-N), number<32>(N))), readRegister<32>(REG_ESI))); writeRegister(REG_EDI, policy.ite(cond, policy.add(readRegister<32>(REG_EDI), policy.ite(readRegister<1>(REG_DF), number<32>(-N), number<32>(N))), readRegister<32>(REG_EDI))); } /** Instruction semantics for one iteration of the repe_cmpsN instruction, where N is 1 (b), 2 (w), or 4 (d). */ template<size_t N> void repe_cmps_semantics(SgAsmx86Instruction *insn) { WordType<1> in_loop = rep_enter(); cmps_semantics<N>(insn, in_loop); WordType<1> repeat = readRegister<1>(REG_ZF); rep_repeat(insn, repeat, in_loop); } /** Instruction semantics for one iteration of the repne_cmpsN instruction, where N is 1 (b), 2 (w), or 4 (d). */ template<size_t N> void repne_cmps_semantics(SgAsmx86Instruction *insn) { WordType<1> in_loop = rep_enter(); cmps_semantics<N>(insn, in_loop); WordType<1> repeat = policy.invert(readRegister<1>(REG_ZF)); rep_repeat(insn, repeat, in_loop); } /** Instruction semantics for scasN where N is 1 (b), 2 (w), or 4 (d). If @p cond is false then this instruction does not * change any state. */ template<size_t N> void scas_semantics(SgAsmx86Instruction *insn, WordType<1> cond) { const SgAsmExpressionPtrList &operands = insn->get_operandList()->get_operands(); if (operands.size()!=0) throw Exception("instruction must have no operands", insn); if (insn->get_addressSize() != x86_insnsize_32) throw Exception("size not implemented", insn); doAddOperation<8*N>(extract<0, 8*N>(readRegister<32>(REG_EAX)), policy.invert(stringop_load_di<N>(cond)), true, policy.false_(), cond); writeRegister(REG_EDI, policy.ite(cond, policy.add(readRegister<32>(REG_EDI), policy.ite(readRegister<1>(REG_DF), number<32>(-N), number<32>(N))), readRegister<32>(REG_EDI))); } /** Instruction semantics for one iteration of repe_scasN where N is 1 (b), 2 (w), or 4 (d). */ template<size_t N> void repe_scas_semantics(SgAsmx86Instruction *insn) { WordType<1> in_loop = rep_enter(); scas_semantics<N>(insn, in_loop); WordType<1> repeat = readRegister<1>(REG_ZF); rep_repeat(insn, repeat, in_loop); } /** Instruction semantics for one iterator of repne_scasN where N is 1 (b), 2 (w), or 4 (d). */ template<size_t N> void repne_scas_semantics(SgAsmx86Instruction *insn) { WordType<1> in_loop = rep_enter(); scas_semantics<N>(insn, in_loop); WordType<1> repeat = policy.invert(readRegister<1>(REG_ZF)); rep_repeat(insn, repeat, in_loop); } /** Helper for lods_semantics() to load one byte into the AL register. */ void lods_semantics_regupdate(WordType<8> v) { writeRegister(REG_AL, v); } /** Helper for lods_semantics() to load one word into the AX register. */ void lods_semantics_regupdate(WordType<16> v) { writeRegister(REG_AX, v); } /** Helper for lods_semantics() to load one doubleword into the EAX register. */ void lods_semantics_regupdate(WordType<32> v) { writeRegister(REG_EAX, v); } /** Instruction semantics for lodsN where N is 1 (b), 2 (w), or 4 (d). */ template<size_t N> void lods_semantics(SgAsmx86Instruction *insn) { const SgAsmExpressionPtrList &operands = insn->get_operandList()->get_operands(); if (operands.size()!=0) throw Exception("instruction must have no operands", insn); if (insn->get_addressSize() != x86_insnsize_32) throw Exception("size not implemented", insn); lods_semantics_regupdate(stringop_load_si<N>(insn, policy.true_())); writeRegister(REG_ESI, policy.add(readRegister<32>(REG_ESI), policy.ite(readRegister<1>(REG_DF), number<32>(-N), number<32>(N)))); } /** Implements the SHR, SAR, SHL, and SAL instructions for various operand sizes. The shift amount is always 8 bits wide * in the instruction, but the semantics mask off all but the low-order bits, keeping 5 bits in 32-bit mode and 7 bits in * 64-bit mode (indicated by the shiftSignificantBits template argument). The semantics of SHL and SAL are identical (in * fact, ROSE doesn't even define x86_sal). */ template<size_t operandBits, size_t shiftSignificantBits> WordType<operandBits> shift_semantics(X86InstructionKind kind, const WordType<operandBits> &operand, const WordType<8> &total_shift) { assert(x86_shr==kind || x86_sar==kind || x86_shl==kind); // The 8086 does not mask the shift count; processors starting with the 80286 (including virtual-8086 mode) do // mask. The effect (other than timing) is the same either way. WordType<shiftSignificantBits> maskedShiftCount = extract<0, shiftSignificantBits>(total_shift); WordType<1> isZeroShiftCount = policy.equalToZero(maskedShiftCount); // Do the actual shift, according to instruction kind. WordType<operandBits> retval; switch (kind) { case x86_shr: retval = policy.shiftRight(operand, maskedShiftCount); break; case x86_sar: retval = policy.shiftRightArithmetic(operand, maskedShiftCount); break; case x86_shl: retval = policy.shiftLeft(operand, maskedShiftCount); break; default: abort(); } // AF is undefined if the shift count is non-zero, otherwise unchanged. The Intel manual is not clear // whether the determination is by original count or masked count. We assume the latter. writeRegister(REG_AF, policy.ite(isZeroShiftCount, readRegister<1>(REG_AF), policy.undefined_())); // What is the last bit shifted off the operand? If we're right shifting by N bits, then the original operand N-1 bit // is what should make it into the final CF; if we're left shifting by N bits then we need bit operandBits-N. uintmax_t m = ((uintmax_t)1 << shiftSignificantBits) - 1; WordType<shiftSignificantBits> mask = number<shiftSignificantBits>(m); // -1 in modulo arithmetic WordType<shiftSignificantBits> bitPosition; if (x86_shr==kind || x86_sar==kind) { bitPosition = policy.add(maskedShiftCount, mask); } else { bitPosition = policy.add(number<shiftSignificantBits>(operandBits & m), // probably zero in modulo arithmetic policy.add(policy.invert(maskedShiftCount), number<shiftSignificantBits>(1))); } WordType<1> shifted_off = extract<0, 1>(policy.shiftRight(operand, bitPosition)); // isLargeShift is true if the (unmasked) amount by which to shift is greater than or equal to the size in // bits of the destination operand. assert(shiftSignificantBits<8); WordType<1> isLargeShift = policy.invert(policy.equalToZero(extract<shiftSignificantBits, 8>(total_shift))); // isOneBitShift is true if the (masked) amount by which to shift is equal to one. WordType<1> isOneBitShift = policy.equalToZero(policy.add(maskedShiftCount, mask)); // New carry flag value. From the Intel manual, the CF flag is "undefined for SHL and SHR [and SAL] instructions where // the count is greater than or equal to the size (in bits) of the destination operand", and "if the count is 0, the // flags are not affected." The manual is silent about the value of CF for large SAR shifts, so we use the original // sign bit, matching the pseudo-code in the manual. WordType<1> newCF = policy.ite(isZeroShiftCount, readRegister<1>(REG_CF), // preserve current value policy.ite(isLargeShift, (x86_sar==kind ? extract<operandBits-1, operandBits>(operand) : // original sign bit policy.undefined_()), shifted_off)); writeRegister(REG_CF, newCF); // Ajust the overflow flag. From the Intel manual, "The OF flag is affected only on 1-bit shifts. For left shifts, // the OF flag is set to 0 if the most-significant bit of the result is the same as the CF flag (that is, the top two // bits of the original operand were the same); otherwise, it is set to 1. For the SAR instruction, the OF flag is // cleared for all 1-bit shifts. For the SHR instruction, the OF flag is set to the most-significant bit of the // original operand. WordType<1> newOF; switch (kind) { case x86_shr: newOF = policy.ite(isOneBitShift, extract<operandBits-1, operandBits>(operand), readRegister<1>(REG_OF)); break; case x86_sar: newOF = policy.ite(isOneBitShift, policy.false_(), readRegister<1>(REG_OF)); break; case x86_shl: newOF = policy.ite(isOneBitShift, policy.xor_(newCF, extract<operandBits-1, operandBits>(retval)), readRegister<1>(REG_OF)); break; default: // to shut up compiler warnings even though we would have aborted by now. abort(); } writeRegister(REG_OF, newOF); // Result flags SF, ZF, and PF are set according to the result, but are unchanged if the shift count is zero. setFlagsForResult<operandBits>(retval, policy.invert(isZeroShiftCount)); return retval; } template <size_t Len> Word(Len) invertMaybe(const Word(Len)& w, bool inv) { if (inv) { return policy.invert(w); } else { return w; } } template <size_t Len> Word(Len) number(uintmax_t v) { return policy.template number<Len>(v); } template <size_t From, size_t To, size_t Len> Word(To - From) extract(Word(Len) w) { return policy.template extract<From, To>(w); } template <size_t From, size_t To> Word(To) signExtend(Word(From) w) { return policy.template signExtend<From, To>(w); } /** Reads from a named register. Delegated to policy. */ template<size_t Len> Word(Len) readRegister(const RegisterDescriptor &reg) { return policy.template readRegister<Len>(reg); } /** Writes to a named register. Delegated to policy. */ template<size_t Len> void writeRegister(const RegisterDescriptor &reg, const Word(Len) &value) { policy.template writeRegister<Len>(reg, value); } template <size_t Len> Word(1) greaterOrEqualToTen(Word(Len) w) { Word(Len) carries = number<Len>(0); policy.addWithCarries(w, number<Len>(6), policy.false_(), carries); return extract<Len - 1, Len>(carries); } template <size_t Len/*bits*/> Word(Len) readMemory(X86SegmentRegister segreg, const Word(32)& addr, Word(1) cond) { return policy.template readMemory<Len>(segreg, addr, cond); } Word(32) readEffectiveAddress(SgAsmExpression* expr) { assert (isSgAsmMemoryReferenceExpression(expr)); return read32(isSgAsmMemoryReferenceExpression(expr)->get_address()); } /* Returns an eight-bit value desribed by an instruction operand. */ Word(8) read8(SgAsmExpression* e) { switch (e->variantT()) { case V_SgAsmx86RegisterReferenceExpression: { SgAsmx86RegisterReferenceExpression* rre = isSgAsmx86RegisterReferenceExpression(e); return policy.readRegister<8>(rre->get_descriptor()); } case V_SgAsmBinaryAdd: { return policy.add(read8(isSgAsmBinaryAdd(e)->get_lhs()), read8(isSgAsmBinaryAdd(e)->get_rhs())); } case V_SgAsmBinaryMultiply: { SgAsmByteValueExpression* rhs = isSgAsmByteValueExpression(isSgAsmBinaryMultiply(e)->get_rhs()); if (!rhs) throw Exception("byte value expression expected", current_instruction); SgAsmExpression* lhs = isSgAsmBinaryMultiply(e)->get_lhs(); return extract<0, 8>(policy.unsignedMultiply(read8(lhs), read8(rhs))); } case V_SgAsmMemoryReferenceExpression: { return readMemory<8>(getSegregFromMemoryReference(isSgAsmMemoryReferenceExpression(e)), readEffectiveAddress(e), policy.true_()); } case V_SgAsmByteValueExpression: case V_SgAsmWordValueExpression: case V_SgAsmDoubleWordValueExpression: case V_SgAsmQuadWordValueExpression: { uint64_t val = SageInterface::getAsmSignedConstant(isSgAsmValueExpression(e)); return number<8>(val & 0xFFU); } default: { fprintf(stderr, "Bad variant %s in read8\n", e->class_name().c_str()); abort(); } } } /* Returns a 16-bit value described by an instruction operand. */ Word(16) read16(SgAsmExpression* e) { switch (e->variantT()) { case V_SgAsmx86RegisterReferenceExpression: { SgAsmx86RegisterReferenceExpression* rre = isSgAsmx86RegisterReferenceExpression(e); return policy.readRegister<16>(rre->get_descriptor()); } case V_SgAsmBinaryAdd: { return policy.add(read16(isSgAsmBinaryAdd(e)->get_lhs()), read16(isSgAsmBinaryAdd(e)->get_rhs())); } case V_SgAsmBinaryMultiply: { SgAsmByteValueExpression* rhs = isSgAsmByteValueExpression(isSgAsmBinaryMultiply(e)->get_rhs()); if (!rhs) throw Exception("byte value expression expected", current_instruction); SgAsmExpression* lhs = isSgAsmBinaryMultiply(e)->get_lhs(); return extract<0, 16>(policy.unsignedMultiply(read16(lhs), read8(rhs))); } case V_SgAsmMemoryReferenceExpression: { return readMemory<16>(getSegregFromMemoryReference(isSgAsmMemoryReferenceExpression(e)), readEffectiveAddress(e), policy.true_()); } case V_SgAsmByteValueExpression: case V_SgAsmWordValueExpression: case V_SgAsmDoubleWordValueExpression: case V_SgAsmQuadWordValueExpression: { uint64_t val = SageInterface::getAsmSignedConstant(isSgAsmValueExpression(e)); return number<16>(val & 0xFFFFU); } default: { fprintf(stderr, "Bad variant %s in read16\n", e->class_name().c_str()); abort(); } } } /* Returns a 32-bit value described by an instruction operand. */ Word(32) read32(SgAsmExpression* e) { switch (e->variantT()) { case V_SgAsmx86RegisterReferenceExpression: { SgAsmx86RegisterReferenceExpression* rre = isSgAsmx86RegisterReferenceExpression(e); return policy.readRegister<32>(rre->get_descriptor()); } case V_SgAsmBinaryAdd: { return policy.add(read32(isSgAsmBinaryAdd(e)->get_lhs()), read32(isSgAsmBinaryAdd(e)->get_rhs())); } case V_SgAsmBinaryMultiply: { SgAsmByteValueExpression* rhs = isSgAsmByteValueExpression(isSgAsmBinaryMultiply(e)->get_rhs()); if (!rhs) throw Exception("byte value expression expected", current_instruction); SgAsmExpression* lhs = isSgAsmBinaryMultiply(e)->get_lhs(); return extract<0, 32>(policy.unsignedMultiply(read32(lhs), read8(rhs))); } case V_SgAsmMemoryReferenceExpression: { return readMemory<32>(getSegregFromMemoryReference(isSgAsmMemoryReferenceExpression(e)), readEffectiveAddress(e), policy.true_()); } case V_SgAsmByteValueExpression: case V_SgAsmWordValueExpression: case V_SgAsmDoubleWordValueExpression: case V_SgAsmQuadWordValueExpression: { uint64_t val = SageInterface::getAsmSignedConstant(isSgAsmValueExpression(e)); return number<32>(val & 0xFFFFFFFFU); } default: { fprintf(stderr, "Bad variant %s in read32\n", e->class_name().c_str()); abort(); } } } /* Writes the specified eight-bit value to the location specified by an instruction operand. */ void write8(SgAsmExpression* e, const Word(8)& value) { switch (e->variantT()) { case V_SgAsmx86RegisterReferenceExpression: { SgAsmx86RegisterReferenceExpression* rre = isSgAsmx86RegisterReferenceExpression(e); policy.writeRegister(rre->get_descriptor(), value); break; } case V_SgAsmMemoryReferenceExpression: { policy.writeMemory(getSegregFromMemoryReference(isSgAsmMemoryReferenceExpression(e)), readEffectiveAddress(e), value, policy.true_()); break; } default: { fprintf(stderr, "Bad variant %s in write8\n", e->class_name().c_str()); abort(); } } } /* Writes the specified 16-bit value to the location specified by an instruction operand. */ void write16(SgAsmExpression* e, const Word(16)& value) { switch (e->variantT()) { case V_SgAsmx86RegisterReferenceExpression: { SgAsmx86RegisterReferenceExpression* rre = isSgAsmx86RegisterReferenceExpression(e); policy.writeRegister(rre->get_descriptor(), value); break; } case V_SgAsmMemoryReferenceExpression: { policy.writeMemory(getSegregFromMemoryReference(isSgAsmMemoryReferenceExpression(e)), readEffectiveAddress(e), value, policy.true_()); break; } default: { fprintf(stderr, "Bad variant %s in write16\n", e->class_name().c_str()); abort(); } } } /* Writes the specified 32-bit value to the location specified by an instruction operand. */ void write32(SgAsmExpression* e, const Word(32)& value) { switch (e->variantT()) { case V_SgAsmx86RegisterReferenceExpression: { SgAsmx86RegisterReferenceExpression* rre = isSgAsmx86RegisterReferenceExpression(e); policy.writeRegister(rre->get_descriptor(), value); break; } case V_SgAsmMemoryReferenceExpression: { policy.writeMemory(getSegregFromMemoryReference(isSgAsmMemoryReferenceExpression(e)), readEffectiveAddress(e), value, policy.true_()); break; } default: { fprintf(stderr, "Bad variant %s in write32\n", e->class_name().c_str()); abort(); } } } /* Returns true if W has an even number of bits set; false for an odd number */ Word(1) parity(Word(8) w) { Word(1) p01 = policy.xor_(extract<0, 1>(w), extract<1, 2>(w)); Word(1) p23 = policy.xor_(extract<2, 3>(w), extract<3, 4>(w)); Word(1) p45 = policy.xor_(extract<4, 5>(w), extract<5, 6>(w)); Word(1) p67 = policy.xor_(extract<6, 7>(w), extract<7, 8>(w)); Word(1) p0123 = policy.xor_(p01, p23); Word(1) p4567 = policy.xor_(p45, p67); return policy.invert(policy.xor_(p0123, p4567)); } /* Sets flags: parity, sign, and zero */ template <size_t Len> void setFlagsForResult(const Word(Len)& result) { writeRegister(REG_PF, parity(extract<0, 8>(result))); writeRegister(REG_SF, extract<Len - 1, Len>(result)); writeRegister(REG_ZF, policy.equalToZero(result)); } /* Sets flags conditionally. Sets parity, sign, and zero flags if COND is true. */ template <size_t Len> void setFlagsForResult(const Word(Len)& result, Word(1) cond) { writeRegister(REG_PF, policy.ite(cond, parity(extract<0, 8>(result)), readRegister<1>(REG_PF))); writeRegister(REG_SF, policy.ite(cond, extract<Len - 1, Len>(result), readRegister<1>(REG_SF))); writeRegister(REG_ZF, policy.ite(cond, policy.equalToZero(result), readRegister<1>(REG_ZF))); } /* Adds A and B and adjusts condition flags. Can be used for subtraction if B is two's complement and invertCarries is set. */ template <size_t Len> Word(Len) doAddOperation(const Word(Len)& a, const Word(Len)& b, bool invertCarries, Word(1) carryIn) { Word(Len) carries = number<Len>(0); Word(Len) result = policy.addWithCarries(a, b, invertMaybe(carryIn, invertCarries), carries/*out*/); setFlagsForResult<Len>(result); writeRegister(REG_AF, invertMaybe(extract<3, 4>(carries), invertCarries)); writeRegister(REG_CF, invertMaybe(extract<Len - 1, Len>(carries), invertCarries)); writeRegister(REG_OF, policy.xor_(extract<Len - 1, Len>(carries), extract<Len - 2, Len - 1>(carries))); return result; } /* Conditionally adds A and B and adjusts condition flags. Can be used for subtraction if B is two's complement and * invertCarries is set. Does nothing if COND is false. */ template <size_t Len> Word(Len) doAddOperation(const Word(Len)& a, const Word(Len)& b, bool invertCarries, Word(1) carryIn, Word(1) cond) { Word(Len) carries = number<Len>(0); Word(Len) result = policy.addWithCarries(a, b, invertMaybe(carryIn, invertCarries), carries/*out*/); setFlagsForResult<Len>(result, cond); writeRegister(REG_AF, policy.ite(cond, invertMaybe(extract<3, 4>(carries), invertCarries), readRegister<1>(REG_AF))); writeRegister(REG_CF, policy.ite(cond, invertMaybe(extract<Len - 1, Len>(carries), invertCarries), readRegister<1>(REG_CF))); writeRegister(REG_OF, policy.ite(cond, policy.xor_(extract<Len - 1, Len>(carries), extract<Len - 2, Len - 1>(carries)), readRegister<1>(REG_OF))); return result; } /* Does increment (decrement with DEC set), and adjusts condition flags. */ template <size_t Len> Word(Len) doIncOperation(const Word(Len)& a, bool dec, bool setCarry) { Word(Len) carries = number<Len>(0); Word(Len) result = policy.addWithCarries(a, number<Len>(dec ? -1 : 1), policy.false_(), carries/*out*/); setFlagsForResult<Len>(result); writeRegister(REG_AF, invertMaybe(extract<3, 4>(carries), dec)); writeRegister(REG_OF, policy.xor_(extract<Len - 1, Len>(carries), extract<Len - 2, Len - 1>(carries))); if (setCarry) writeRegister(REG_CF, invertMaybe(extract<Len - 1, Len>(carries), dec)); return result; } /* Virtual so that we can subclass X86InstructionSemantics and have an opportunity to override the translation of any * instruction. */ #if _MSC_VER // tps (02/01/2010) : fixme : Commented this out for Windows - there is a problem with the try: // error C2590: 'translate' : only a constructor can have a base/member initializer list virtual void translate(SgAsmx86Instruction* insn) { } #else virtual void translate(SgAsmx86Instruction* insn) try { orig_eip = readRegister<32>(REG_EIP); writeRegister(REG_EIP, policy.add(orig_eip, policy.number<32>(insn->get_size()))); X86InstructionKind kind = insn->get_kind(); const SgAsmExpressionPtrList& operands = insn->get_operandList()->get_operands(); switch (kind) { case x86_mov: { if (operands.size()!=2) throw Exception("instruction must have two operands", insn); switch (numBytesInAsmType(operands[0]->get_type())) { case 1: write8(operands[0], read8(operands[1])); break; case 2: write16(operands[0], read16(operands[1])); break; case 4: write32(operands[0], read32(operands[1])); break; default: throw Exception("size not implemented", insn); break; } break; } case x86_xchg: { if (operands.size()!=2) throw Exception("instruction must have two operands", insn); switch (numBytesInAsmType(operands[0]->get_type())) { case 1: { Word(8) temp = read8(operands[1]); write8(operands[1], read8(operands[0])); write8(operands[0], temp); break; } case 2: { Word(16) temp = read16(operands[1]); write16(operands[1], read16(operands[0])); write16(operands[0], temp); break; } case 4: { Word(32) temp = read32(operands[1]); write32(operands[1], read32(operands[0])); write32(operands[0], temp); break; } default: throw Exception("size not implemented", insn); break; } break; } case x86_movzx: { if (operands.size()!=2) throw Exception("instruction must have two operands", insn); switch (numBytesInAsmType(operands[0]->get_type())) { case 2: { write16(operands[0], policy.concat(read8(operands[1]), number<8>(0))); break; } case 4: { switch (numBytesInAsmType(operands[1]->get_type())) { case 1: write32(operands[0], policy.concat(read8(operands[1]), number<24>(0))); break; case 2: write32(operands[0], policy.concat(read16(operands[1]), number<16>(0))); break; default: throw Exception("size not implemented", insn); } break; } default: throw Exception("size not implemented", insn); break; } break; } case x86_movsx: { if (operands.size()!=2) throw Exception("instruction must have two operands", insn); switch (numBytesInAsmType(operands[0]->get_type())) { case 2: { Word(8) op1 = read8(operands[1]); Word(16) result = signExtend<8, 16>(op1); write16(operands[0], result); break; } case 4: { switch (numBytesInAsmType(operands[1]->get_type())) { case 1: { Word(8) op1 = read8(operands[1]); Word(32) result = signExtend<8, 32>(op1); write32(operands[0], result); break; } case 2: { Word(16) op1 = read16(operands[1]); Word(32) result = signExtend<16, 32>(op1); write32(operands[0], result); break; } default: throw Exception("size not implemented", insn); } break; } default: throw Exception("size not implemented", insn); break; } break; } case x86_cbw: { if (operands.size()!=0) throw Exception("instruction must have no operands", insn); writeRegister(REG_AX, signExtend<8, 16>(readRegister<8>(REG_AL))); break; } case x86_cwde: { if (operands.size()!=0) throw Exception("instruction must have no operands", insn); writeRegister(REG_EAX, signExtend<16, 32>(readRegister<16>(REG_AX))); break; } case x86_cwd: { if (operands.size()!=0) throw Exception("instruction must have no operands", insn); writeRegister(REG_DX, extract<16, 32>(signExtend<16, 32>(readRegister<16>(REG_AX)))); break; } case x86_cdq: { if (operands.size()!=0) throw Exception("instruction must have no operands", insn); writeRegister(REG_EDX, extract<32, 64>(signExtend<32, 64>(readRegister<32>(REG_AX)))); break; } case x86_lea: { if (operands.size()!=2) throw Exception("instruction must have two operands", insn); write32(operands[0], readEffectiveAddress(operands[1])); break; } case x86_and: { if (operands.size()!=2) throw Exception("instruction must have two operands", insn); switch (numBytesInAsmType(operands[0]->get_type())) { case 1: { Word(8) result = policy.and_(read8(operands[0]), read8(operands[1])); setFlagsForResult<8>(result); write8(operands[0], result); break; } case 2: { Word(16) result = policy.and_(read16(operands[0]), read16(operands[1])); setFlagsForResult<16>(result); write16(operands[0], result); break; } case 4: { Word(32) result = policy.and_(read32(operands[0]), read32(operands[1])); setFlagsForResult<32>(result); write32(operands[0], result); break; } default: throw Exception("size not implemented", insn); break; } writeRegister(REG_OF, policy.false_()); writeRegister(REG_AF, policy.undefined_()); writeRegister(REG_CF, policy.false_()); break; } case x86_or: { if (operands.size()!=2) throw Exception("instruction must have two operands", insn); switch (numBytesInAsmType(operands[0]->get_type())) { case 1: { Word(8) result = policy.or_(read8(operands[0]), read8(operands[1])); setFlagsForResult<8>(result); write8(operands[0], result); break; } case 2: { Word(16) result = policy.or_(read16(operands[0]), read16(operands[1])); setFlagsForResult<16>(result); write16(operands[0], result); break; } case 4: { Word(32) result = policy.or_(read32(operands[0]), read32(operands[1])); setFlagsForResult<32>(result); write32(operands[0], result); break; } default: throw Exception("size not implemented", insn); break; } writeRegister(REG_OF, policy.false_()); writeRegister(REG_AF, policy.undefined_()); writeRegister(REG_CF, policy.false_()); break; } case x86_test: { if (operands.size()!=2) throw Exception("instruction must have two operands", insn); switch (numBytesInAsmType(operands[0]->get_type())) { case 1: { Word(8) result = policy.and_(read8(operands[0]), read8(operands[1])); setFlagsForResult<8>(result); break; } case 2: { Word(16) result = policy.and_(read16(operands[0]), read16(operands[1])); setFlagsForResult<16>(result); break; } case 4: { Word(32) result = policy.and_(read32(operands[0]), read32(operands[1])); setFlagsForResult<32>(result); break; } default: throw Exception("size not implemented", insn); break; } writeRegister(REG_OF, policy.false_()); writeRegister(REG_AF, policy.undefined_()); writeRegister(REG_CF, policy.false_()); break; } case x86_xor: { if (operands.size()!=2) throw Exception("instruction must have two operands", insn); switch (numBytesInAsmType(operands[0]->get_type())) { case 1: { Word(8) result = policy.xor_(read8(operands[0]), read8(operands[1])); setFlagsForResult<8>(result); write8(operands[0], result); break; } case 2: { Word(16) result = policy.xor_(read16(operands[0]), read16(operands[1])); setFlagsForResult<16>(result); write16(operands[0], result); break; } case 4: { Word(32) result = policy.xor_(read32(operands[0]), read32(operands[1])); setFlagsForResult<32>(result); write32(operands[0], result); break; } default: throw Exception("size not implemented", insn); break; } writeRegister(REG_OF, policy.false_()); writeRegister(REG_AF, policy.undefined_()); writeRegister(REG_CF, policy.false_()); break; } case x86_not: { if (operands.size()!=1) throw Exception("instruction must have one operand", insn); switch (numBytesInAsmType(operands[0]->get_type())) { case 1: { Word(8) result = policy.invert(read8(operands[0])); write8(operands[0], result); break; } case 2: { Word(16) result = policy.invert(read16(operands[0])); write16(operands[0], result); break; } case 4: { Word(32) result = policy.invert(read32(operands[0])); write32(operands[0], result); break; } default: throw Exception("size not implemented", insn); break; } break; } case x86_xadd: { if (operands.size()!=2) throw Exception("instruction must have two operands", insn); switch (numBytesInAsmType(operands[0]->get_type())) { case 1: { Word(8) result = doAddOperation<8>(read8(operands[0]), read8(operands[1]), false, policy.false_()); write8(operands[1], read8(operands[0])); write8(operands[0], result); break; } case 2: { Word(16) result = doAddOperation<16>(read16(operands[0]), read16(operands[1]), false, policy.false_()); write16(operands[1], read16(operands[0])); write16(operands[0], result); break; } case 4: { Word(32) result = doAddOperation<32>(read32(operands[0]), read32(operands[1]), false, policy.false_()); write32(operands[1], read32(operands[0])); write32(operands[0], result); break; } default: throw Exception("size not implemented", insn); break; } break; } case x86_add: { if (operands.size()!=2) throw Exception("instruction must have two operands", insn); switch (numBytesInAsmType(operands[0]->get_type())) { case 1: { Word(8) result = doAddOperation<8>(read8(operands[0]), read8(operands[1]), false, policy.false_()); write8(operands[0], result); break; } case 2: { Word(16) result = doAddOperation<16>(read16(operands[0]), read16(operands[1]), false, policy.false_()); write16(operands[0], result); break; } case 4: { Word(32) result = doAddOperation<32>(read32(operands[0]), read32(operands[1]), false, policy.false_()); write32(operands[0], result); break; } default: throw Exception("size not implemented", insn); break; } break; } case x86_adc: { if (operands.size()!=2) throw Exception("instruction must have two operands", insn); switch (numBytesInAsmType(operands[0]->get_type())) { case 1: { Word(8) result = doAddOperation<8>(read8(operands[0]), read8(operands[1]), false, readRegister<1>(REG_CF)); write8(operands[0], result); break; } case 2: { Word(16) result = doAddOperation<16>(read16(operands[0]), read16(operands[1]), false, readRegister<1>(REG_CF)); write16(operands[0], result); break; } case 4: { Word(32) result = doAddOperation<32>(read32(operands[0]), read32(operands[1]), false, readRegister<1>(REG_CF)); write32(operands[0], result); break; } default: throw Exception("size not implemented", insn); break; } break; } case x86_sub: { if (operands.size()!=2) throw Exception("instruction must have two operands", insn); switch (numBytesInAsmType(operands[0]->get_type())) { case 1: { Word(8) result = doAddOperation<8>(read8(operands[0]), policy.invert(read8(operands[1])), true, policy.false_()); write8(operands[0], result); break; } case 2: { Word(16) result = doAddOperation<16>(read16(operands[0]), policy.invert(read16(operands[1])), true, policy.false_()); write16(operands[0], result); break; } case 4: { Word(32) result = doAddOperation<32>(read32(operands[0]), policy.invert(read32(operands[1])), true, policy.false_()); write32(operands[0], result); break; } default: throw Exception("size not implemented", insn); break; } break; } case x86_sbb: { if (operands.size()!=2) throw Exception("instruction must have two operands", insn); switch (numBytesInAsmType(operands[0]->get_type())) { case 1: { Word(8) result = doAddOperation<8>(read8(operands[0]), policy.invert(read8(operands[1])), true, readRegister<1>(REG_CF)); write8(operands[0], result); break; } case 2: { Word(16) result = doAddOperation<16>(read16(operands[0]), policy.invert(read16(operands[1])), true, readRegister<1>(REG_CF)); write16(operands[0], result); break; } case 4: { Word(32) result = doAddOperation<32>(read32(operands[0]), policy.invert(read32(operands[1])), true, readRegister<1>(REG_CF)); write32(operands[0], result); break; } default: throw Exception("size not implemented", insn); break; } break; } case x86_cmp: { if (operands.size()!=2) throw Exception("instruction must have two operands", insn); switch (numBytesInAsmType(operands[0]->get_type())) { case 1: { doAddOperation<8>(read8(operands[0]), policy.invert(read8(operands[1])), true, policy.false_()); break; } case 2: { doAddOperation<16>(read16(operands[0]), policy.invert(read16(operands[1])), true, policy.false_()); break; } case 4: { doAddOperation<32>(read32(operands[0]), policy.invert(read32(operands[1])), true, policy.false_()); break; } default: throw Exception("size not implemented", insn); break; } break; } case x86_neg: { if (operands.size()!=1) throw Exception("instruction must have one operand", insn); switch (numBytesInAsmType(operands[0]->get_type())) { case 1: { Word(8) result = doAddOperation<8>(number<8>(0), policy.invert(read8(operands[0])), true, policy.false_()); write8(operands[0], result); break; } case 2: { Word(16) result = doAddOperation<16>(number<16>(0), policy.invert(read16(operands[0])), true, policy.false_()); write16(operands[0], result); break; } case 4: { Word(32) result = doAddOperation<32>(number<32>(0), policy.invert(read32(operands[0])), true, policy.false_()); write32(operands[0], result); break; } default: throw Exception("size not implemented", insn); break; } break; } case x86_inc: { if (operands.size()!=1) throw Exception("instruction must have one operand", insn); switch (numBytesInAsmType(operands[0]->get_type())) { case 1: { Word(8) result = doIncOperation<8>(read8(operands[0]), false, false); write8(operands[0], result); break; } case 2: { Word(16) result = doIncOperation<16>(read16(operands[0]), false, false); write16(operands[0], result); break; } case 4: { Word(32) result = doIncOperation<32>(read32(operands[0]), false, false); write32(operands[0], result); break; } default: throw Exception("size not implemented", insn); break; } break; } case x86_dec: { if (operands.size()!=1) throw Exception("instruction must have one operand", insn); switch (numBytesInAsmType(operands[0]->get_type())) { case 1: { Word(8) result = doIncOperation<8>(read8(operands[0]), true, false); write8(operands[0], result); break; } case 2: { Word(16) result = doIncOperation<16>(read16(operands[0]), true, false); write16(operands[0], result); break; } case 4: { Word(32) result = doIncOperation<32>(read32(operands[0]), true, false); write32(operands[0], result); break; } default: throw Exception("size not implemented", insn); break; } break; } case x86_cmpxchg: { if (operands.size()!=2) throw Exception("instruction must have two operands", insn); switch (numBytesInAsmType(operands[0]->get_type())) { case 1: { Word(8) op0 = read8(operands[0]); Word(8) oldAx = readRegister<8>(REG_AL); doAddOperation<8>(oldAx, policy.invert(op0), true, policy.false_()); write8(operands[0], policy.ite(readRegister<1>(REG_ZF), read8(operands[1]), op0)); writeRegister(REG_AL, policy.ite(readRegister<1>(REG_ZF), oldAx, op0)); break; } case 2: { Word(16) op0 = read16(operands[0]); Word(16) oldAx = readRegister<16>(REG_AX); doAddOperation<16>(oldAx, policy.invert(op0), true, policy.false_()); write16(operands[0], policy.ite(readRegister<1>(REG_ZF), read16(operands[1]), op0)); writeRegister(REG_AX, policy.ite(readRegister<1>(REG_ZF), oldAx, op0)); break; } case 4: { Word(32) op0 = read32(operands[0]); Word(32) oldAx = readRegister<32>(REG_EAX); doAddOperation<32>(oldAx, policy.invert(op0), true, policy.false_()); write32(operands[0], policy.ite(readRegister<1>(REG_ZF), read32(operands[1]), op0)); writeRegister(REG_EAX, policy.ite(readRegister<1>(REG_ZF), oldAx, op0)); break; } default: throw Exception("size not implemented", insn); break; } break; } case x86_shl: // fall through case x86_sar: // fall through case x86_shr: { switch (numBytesInAsmType(operands[0]->get_type())) { case 1: { WordType<8> output = shift_semantics<8, 5>(kind, read8(operands[0]), read8(operands[1])); write8(operands[0], output); break; } case 2: { WordType<16> output = shift_semantics<16, 5>(kind, read16(operands[0]), read8(operands[1])); write16(operands[0], output); break; } case 4: { WordType<32> output = shift_semantics<32, 5>(kind, read32(operands[0]), read8(operands[1])); write32(operands[0], output); break; } default: throw Exception("size not implemented", insn); } break; } case x86_rol: { switch (numBytesInAsmType(operands[0]->get_type())) { case 1: { Word(8) op = read8(operands[0]); Word(5) shiftCount = extract<0, 5>(read8(operands[1])); Word(8) output = policy.rotateLeft(op, shiftCount); writeRegister(REG_CF, policy.ite(policy.equalToZero(shiftCount), readRegister<1>(REG_CF), extract<0, 1>(output))); writeRegister(REG_OF, policy.ite(policy.equalToZero(shiftCount), readRegister<1>(REG_OF), policy.xor_(extract<0, 1>(output), extract<7, 8>(output)))); write8(operands[0], output); break; } case 2: { Word(16) op = read16(operands[0]); Word(5) shiftCount = extract<0, 5>(read8(operands[1])); Word(16) output = policy.rotateLeft(op, shiftCount); writeRegister(REG_CF, policy.ite(policy.equalToZero(shiftCount), readRegister<1>(REG_CF), extract<0, 1>(output))); writeRegister(REG_OF, policy.ite(policy.equalToZero(shiftCount), readRegister<1>(REG_OF), policy.xor_(extract<0, 1>(output), extract<15, 16>(output)))); write16(operands[0], output); break; } case 4: { Word(32) op = read32(operands[0]); Word(5) shiftCount = extract<0, 5>(read8(operands[1])); Word(32) output = policy.rotateLeft(op, shiftCount); writeRegister(REG_CF, policy.ite(policy.equalToZero(shiftCount), readRegister<1>(REG_CF), extract<0, 1>(output))); writeRegister(REG_OF, policy.ite(policy.equalToZero(shiftCount), readRegister<1>(REG_OF), policy.xor_(extract<0, 1>(output), extract<31, 32>(output)))); write32(operands[0], output); break; } default: throw Exception("size not implemented", insn); } break; } case x86_ror: { switch (numBytesInAsmType(operands[0]->get_type())) { case 1: { Word(8) op = read8(operands[0]); Word(5) shiftCount = extract<0, 5>(read8(operands[1])); Word(8) output = policy.rotateRight(op, shiftCount); writeRegister(REG_CF, policy.ite(policy.equalToZero(shiftCount), readRegister<1>(REG_CF), extract<7, 8>(output))); writeRegister(REG_OF, policy.ite(policy.equalToZero(shiftCount), readRegister<1>(REG_OF), policy.xor_(extract<6, 7>(output), extract<7, 8>(output)))); write8(operands[0], output); break; } case 2: { Word(16) op = read16(operands[0]); Word(5) shiftCount = extract<0, 5>(read8(operands[1])); Word(16) output = policy.rotateRight(op, shiftCount); writeRegister(REG_CF, policy.ite(policy.equalToZero(shiftCount), readRegister<1>(REG_CF), extract<15, 16>(output))); writeRegister(REG_OF, policy.ite(policy.equalToZero(shiftCount), readRegister<1>(REG_OF), policy.xor_(extract<14, 15>(output), extract<15, 16>(output)))); write16(operands[0], output); break; } case 4: { Word(32) op = read32(operands[0]); Word(5) shiftCount = extract<0, 5>(read8(operands[1])); Word(32) output = policy.rotateRight(op, shiftCount); writeRegister(REG_CF, policy.ite(policy.equalToZero(shiftCount), readRegister<1>(REG_CF), extract<31, 32>(output))); writeRegister(REG_OF, policy.ite(policy.equalToZero(shiftCount), readRegister<1>(REG_OF), policy.xor_(extract<30, 31>(output), extract<31, 32>(output)))); write32(operands[0], output); break; } default: throw Exception("size not implemented", insn); } break; } case x86_shld: { Word(5) shiftCount = extract<0, 5>(read8(operands[2])); switch (numBytesInAsmType(operands[0]->get_type())) { case 2: { Word(16) op1 = read16(operands[0]); Word(16) op2 = read16(operands[1]); Word(16) output1 = policy.shiftLeft(op1, shiftCount); Word(16) output2 = policy.ite(policy.equalToZero(shiftCount), number<16>(0), policy.shiftRight(op2, policy.negate(shiftCount))); Word(16) output = policy.or_(output1, output2); Word(1) newCf = policy.ite(policy.equalToZero(shiftCount), readRegister<1>(REG_CF), extract<15, 16>(policy.shiftLeft(op1, policy.add(shiftCount, number<5>(15))))); writeRegister(REG_CF, newCf); Word(1) newOf = policy.ite(policy.equalToZero(shiftCount), readRegister<1>(REG_OF), policy.xor_(extract<15, 16>(output), newCf)); writeRegister(REG_OF, newOf); write16(operands[0], output); setFlagsForResult<16>(output); writeRegister(REG_AF, policy.ite(policy.equalToZero(shiftCount), readRegister<1>(REG_AF), policy.undefined_())); break; } case 4: { Word(32) op1 = read32(operands[0]); Word(32) op2 = read32(operands[1]); Word(5) shiftCount = extract<0, 5>(read8(operands[2])); Word(32) output1 = policy.shiftLeft(op1, shiftCount); Word(32) output2 = policy.ite(policy.equalToZero(shiftCount), number<32>(0), policy.shiftRight(op2, policy.negate(shiftCount))); Word(32) output = policy.or_(output1, output2); Word(1) newCf = policy.ite(policy.equalToZero(shiftCount), readRegister<1>(REG_CF), extract<31, 32>(policy.shiftLeft(op1, policy.add(shiftCount, number<5>(31))))); writeRegister(REG_CF, newCf); Word(1) newOf = policy.ite(policy.equalToZero(shiftCount), readRegister<1>(REG_OF), policy.xor_(extract<31, 32>(output), newCf)); writeRegister(REG_OF, newOf); write32(operands[0], output); setFlagsForResult<32>(output); writeRegister(REG_AF, policy.ite(policy.equalToZero(shiftCount), readRegister<1>(REG_AF), policy.undefined_())); break; } default: throw Exception("size not implemented", insn); } break; } case x86_shrd: { Word(5) shiftCount = extract<0, 5>(read8(operands[2])); switch (numBytesInAsmType(operands[0]->get_type())) { case 2: { Word(16) op1 = read16(operands[0]); Word(16) op2 = read16(operands[1]); Word(16) output1 = policy.shiftRight(op1, shiftCount); Word(16) output2 = policy.ite(policy.equalToZero(shiftCount), number<16>(0), policy.shiftLeft(op2, policy.negate(shiftCount))); Word(16) output = policy.or_(output1, output2); Word(1) newCf = policy.ite(policy.equalToZero(shiftCount), readRegister<1>(REG_CF), extract<0, 1>(policy.shiftRight(op1, policy.add(shiftCount, number<5>(15))))); writeRegister(REG_CF, newCf); Word(1) newOf = policy.ite(policy.equalToZero(shiftCount), readRegister<1>(REG_OF), policy.xor_(extract<15, 16>(output), extract<15, 16>(op1))); writeRegister(REG_OF, newOf); write16(operands[0], output); setFlagsForResult<16>(output); writeRegister(REG_AF, policy.ite(policy.equalToZero(shiftCount), readRegister<1>(REG_AF), policy.undefined_())); break; } case 4: { Word(32) op1 = read32(operands[0]); Word(32) op2 = read32(operands[1]); Word(32) output1 = policy.shiftRight(op1, shiftCount); Word(32) output2 = policy.ite(policy.equalToZero(shiftCount), number<32>(0), policy.shiftLeft(op2, policy.negate(shiftCount))); Word(32) output = policy.or_(output1, output2); Word(1) newCf = policy.ite(policy.equalToZero(shiftCount), readRegister<1>(REG_CF), extract<0, 1>(policy.shiftRight(op1, policy.add(shiftCount, number<5>(31))))); writeRegister(REG_CF, newCf); Word(1) newOf = policy.ite(policy.equalToZero(shiftCount), readRegister<1>(REG_OF), policy.xor_(extract<31, 32>(output), extract<31, 32>(op1))); writeRegister(REG_OF, newOf); write32(operands[0], output); setFlagsForResult<32>(output); writeRegister(REG_AF, policy.ite(policy.equalToZero(shiftCount), readRegister<1>(REG_AF), policy.undefined_())); break; } default: throw Exception("size not implemented", insn); } break; } case x86_bsf: { writeRegister(REG_OF, policy.undefined_()); writeRegister(REG_SF, policy.undefined_()); writeRegister(REG_AF, policy.undefined_()); writeRegister(REG_PF, policy.undefined_()); writeRegister(REG_CF, policy.undefined_()); switch (numBytesInAsmType(operands[0]->get_type())) { case 2: { Word(16) op = read16(operands[1]); writeRegister(REG_ZF, policy.equalToZero(op)); Word(16) result = policy.ite(readRegister<1>(REG_ZF), read16(operands[0]), policy.leastSignificantSetBit(op)); write16(operands[0], result); break; } case 4: { Word(32) op = read32(operands[1]); writeRegister(REG_ZF, policy.equalToZero(op)); Word(32) result = policy.ite(readRegister<1>(REG_ZF), read32(operands[0]), policy.leastSignificantSetBit(op)); write32(operands[0], result); break; } default: throw Exception("size not implemented", insn); } break; } case x86_bsr: { writeRegister(REG_OF, policy.undefined_()); writeRegister(REG_SF, policy.undefined_()); writeRegister(REG_AF, policy.undefined_()); writeRegister(REG_PF, policy.undefined_()); writeRegister(REG_CF, policy.undefined_()); switch (numBytesInAsmType(operands[0]->get_type())) { case 2: { Word(16) op = read16(operands[1]); writeRegister(REG_ZF, policy.equalToZero(op)); Word(16) result = policy.ite(readRegister<1>(REG_ZF), read16(operands[0]), policy.mostSignificantSetBit(op)); write16(operands[0], result); break; } case 4: { Word(32) op = read32(operands[1]); writeRegister(REG_ZF, policy.equalToZero(op)); Word(32) result = policy.ite(readRegister<1>(REG_ZF), read32(operands[0]), policy.mostSignificantSetBit(op)); write32(operands[0], result); break; } default: throw Exception("size not implemented", insn); } break; } case x86_bt: { /* Bit test */ if (operands.size()!=2) throw Exception("instruction must have two operands", insn); /* All flags except CF are undefined */ writeRegister(REG_OF, policy.undefined_()); writeRegister(REG_SF, policy.undefined_()); writeRegister(REG_ZF, policy.undefined_()); writeRegister(REG_AF, policy.undefined_()); writeRegister(REG_PF, policy.undefined_()); if (isSgAsmMemoryReferenceExpression(operands[0]) && isSgAsmx86RegisterReferenceExpression(operands[1])) { /* Special case allowing multi-word offsets into memory */ Word(32) addr = readEffectiveAddress(operands[0]); int numBytes = numBytesInAsmType(operands[1]->get_type()); Word(32) bitnum = numBytes == 2 ? signExtend<16, 32>(read16(operands[1])) : read32(operands[1]); Word(32) adjustedAddr = policy.add(addr, signExtend<29, 32>(extract<3, 32>(bitnum))); Word(8) val = readMemory<8>(getSegregFromMemoryReference(isSgAsmMemoryReferenceExpression(operands[0])), adjustedAddr, policy.true_()); Word(1) bitval = extract<0, 1>(policy.rotateRight(val, extract<0, 3>(bitnum))); writeRegister(REG_CF, bitval); } else { /* Simple case */ switch (numBytesInAsmType(operands[0]->get_type())) { case 2: { Word(16) op0 = read16(operands[0]); Word(4) bitnum = extract<0, 4>(read16(operands[1])); Word(1) bitval = extract<0, 1>(policy.rotateRight(op0, bitnum)); writeRegister(REG_CF, bitval); break; } case 4: { Word(32) op0 = read32(operands[0]); Word(5) bitnum = extract<0, 5>(read32(operands[1])); Word(1) bitval = extract<0, 1>(policy.rotateRight(op0, bitnum)); writeRegister(REG_CF, bitval); break; } default: throw Exception("size not implemented", insn); } } break; } case x86_btr: { /* Bit test and reset */ if (operands.size()!=2) throw Exception("instruction must have two operands", insn); /* All flags except CF are undefined */ writeRegister(REG_OF, policy.undefined_()); writeRegister(REG_SF, policy.undefined_()); writeRegister(REG_ZF, policy.undefined_()); writeRegister(REG_AF, policy.undefined_()); writeRegister(REG_PF, policy.undefined_()); if (isSgAsmMemoryReferenceExpression(operands[0]) && isSgAsmx86RegisterReferenceExpression(operands[1])) { /* Special case allowing multi-word offsets into memory */ Word(32) addr = readEffectiveAddress(operands[0]); int numBytes = numBytesInAsmType(operands[1]->get_type()); Word(32) bitnum = numBytes == 2 ? signExtend<16, 32>(read16(operands[1])) : read32(operands[1]); Word(32) adjustedAddr = policy.add(addr, signExtend<29, 32>(extract<3, 32>(bitnum))); Word(8) val = readMemory<8>(getSegregFromMemoryReference(isSgAsmMemoryReferenceExpression(operands[0])), adjustedAddr, policy.true_()); Word(1) bitval = extract<0, 1>(policy.rotateRight(val, extract<0, 3>(bitnum))); Word(8) result = policy.and_(val, policy.invert(policy.rotateLeft(number<8>(1), extract<0, 3>(bitnum)))); writeRegister(REG_CF, bitval); policy.writeMemory(getSegregFromMemoryReference(isSgAsmMemoryReferenceExpression(operands[0])), adjustedAddr, result, policy.true_()); } else { /* Simple case */ switch (numBytesInAsmType(operands[0]->get_type())) { case 2: { Word(16) op0 = read16(operands[0]); Word(4) bitnum = extract<0, 4>(read16(operands[1])); Word(1) bitval = extract<0, 1>(policy.rotateRight(op0, bitnum)); Word(16) result = policy.and_(op0, policy.invert(policy.rotateLeft(number<16>(1), bitnum))); writeRegister(REG_CF, bitval); write16(operands[0], result); break; } case 4: { Word(32) op0 = read32(operands[0]); Word(5) bitnum = extract<0, 5>(read32(operands[1])); Word(1) bitval = extract<0, 1>(policy.rotateRight(op0, bitnum)); Word(32) result = policy.and_(op0, policy.invert(policy.rotateLeft(number<32>(1), bitnum))); writeRegister(REG_CF, bitval); write32(operands[0], result); break; } default: throw Exception("size not implemented", insn); } } break; } case x86_bts: { /* bit test and set */ if (operands.size()!=2) throw Exception("instruction must have two operands", insn); /* All flags except CF are undefined */ writeRegister(REG_OF, policy.undefined_()); writeRegister(REG_SF, policy.undefined_()); writeRegister(REG_ZF, policy.undefined_()); writeRegister(REG_AF, policy.undefined_()); writeRegister(REG_PF, policy.undefined_()); if (isSgAsmMemoryReferenceExpression(operands[0]) && isSgAsmx86RegisterReferenceExpression(operands[1])) { /* Special case allowing multi-word offsets into memory */ Word(32) addr = readEffectiveAddress(operands[0]); int numBytes = numBytesInAsmType(operands[1]->get_type()); Word(32) bitnum = numBytes == 2 ? signExtend<16, 32>(read16(operands[1])) : read32(operands[1]); Word(32) adjustedAddr = policy.add(addr, signExtend<29, 32>(extract<3, 32>(bitnum))); Word(8) val = readMemory<8>(getSegregFromMemoryReference(isSgAsmMemoryReferenceExpression(operands[0])), adjustedAddr, policy.true_()); Word(1) bitval = extract<0, 1>(policy.rotateRight(val, extract<0, 3>(bitnum))); Word(8) result = policy.or_(val, policy.rotateLeft(number<8>(1), extract<0, 3>(bitnum))); writeRegister(REG_CF, bitval); policy.writeMemory(getSegregFromMemoryReference(isSgAsmMemoryReferenceExpression(operands[0])), adjustedAddr, result, policy.true_()); } else { /* Simple case */ switch (numBytesInAsmType(operands[0]->get_type())) { case 2: { Word(16) op0 = read16(operands[0]); Word(4) bitnum = extract<0, 4>(read16(operands[1])); Word(1) bitval = extract<0, 1>(policy.rotateRight(op0, bitnum)); Word(16) result = policy.or_(op0, policy.rotateLeft(number<16>(1), bitnum)); writeRegister(REG_CF, bitval); write16(operands[0], result); break; } case 4: { Word(32) op0 = read32(operands[0]); Word(5) bitnum = extract<0, 5>(read32(operands[1])); Word(1) bitval = extract<0, 1>(policy.rotateRight(op0, bitnum)); Word(32) result = policy.or_(op0, policy.rotateLeft(number<32>(1), bitnum)); writeRegister(REG_CF, bitval); write32(operands[0], result); break; } default: throw Exception("size not implemented", insn); } } break; } case x86_imul: { switch (numBytesInAsmType(operands[0]->get_type())) { case 1: { Word(8) op0 = readRegister<8>(REG_AL); Word(8) op1 = read8(operands[0]); Word(16) mulResult = policy.signedMultiply(op0, op1); writeRegister(REG_AX, mulResult); Word(1) carry = policy.invert(policy.or_(policy.equalToZero(policy.invert(extract<7, 16>(mulResult))), policy.equalToZero(extract<7, 16>(mulResult)))); writeRegister(REG_CF, carry); writeRegister(REG_OF, carry); break; } case 2: { Word(16) op0 = operands.size() == 1 ? readRegister<16>(REG_AX) : read16(operands[operands.size() - 2]); Word(16) op1 = read16(operands[operands.size() - 1]); Word(32) mulResult = policy.signedMultiply(op0, op1); if (operands.size() == 1) { writeRegister(REG_AX, extract<0, 16>(mulResult)); writeRegister(REG_DX, extract<16, 32>(mulResult)); } else { write16(operands[0], extract<0, 16>(mulResult)); } Word(1) carry = policy.invert(policy.or_(policy.equalToZero(policy.invert(extract<7, 32>(mulResult))), policy.equalToZero(extract<7, 32>(mulResult)))); writeRegister(REG_CF, carry); writeRegister(REG_OF, carry); break; } case 4: { Word(32) op0 = operands.size() == 1 ? readRegister<32>(REG_EAX) : read32(operands[operands.size() - 2]); Word(32) op1 = read32(operands[operands.size() - 1]); Word(64) mulResult = policy.signedMultiply(op0, op1); if (operands.size() == 1) { writeRegister(REG_EAX, extract<0, 32>(mulResult)); writeRegister(REG_EDX, extract<32, 64>(mulResult)); } else { write32(operands[0], extract<0, 32>(mulResult)); } Word(1) carry = policy.invert(policy.or_(policy.equalToZero(policy.invert(extract<7, 64>(mulResult))), policy.equalToZero(extract<7, 64>(mulResult)))); writeRegister(REG_CF, carry); writeRegister(REG_OF, carry); break; } default: throw Exception("size not implemented", insn); } writeRegister(REG_SF, policy.undefined_()); writeRegister(REG_ZF, policy.undefined_()); writeRegister(REG_AF, policy.undefined_()); writeRegister(REG_PF, policy.undefined_()); break; } case x86_mul: { switch (numBytesInAsmType(operands[0]->get_type())) { case 1: { Word(8) op0 = readRegister<8>(REG_AL); Word(8) op1 = read8(operands[0]); Word(16) mulResult = policy.unsignedMultiply(op0, op1); writeRegister(REG_AX, mulResult); Word(1) carry = policy.invert(policy.equalToZero(extract<8, 16>(mulResult))); writeRegister(REG_CF, carry); writeRegister(REG_OF, carry); break; } case 2: { Word(16) op0 = readRegister<16>(REG_AX); Word(16) op1 = read16(operands[0]); Word(32) mulResult = policy.unsignedMultiply(op0, op1); writeRegister(REG_AX, extract<0, 16>(mulResult)); writeRegister(REG_DX, extract<16, 32>(mulResult)); Word(1) carry = policy.invert(policy.equalToZero(extract<16, 32>(mulResult))); writeRegister(REG_CF, carry); writeRegister(REG_OF, carry); break; } case 4: { Word(32) op0 = readRegister<32>(REG_EAX); Word(32) op1 = read32(operands[0]); Word(64) mulResult = policy.unsignedMultiply(op0, op1); writeRegister(REG_EAX, extract<0, 32>(mulResult)); writeRegister(REG_EDX, extract<32, 64>(mulResult)); Word(1) carry = policy.invert(policy.equalToZero(extract<32, 64>(mulResult))); writeRegister(REG_CF, carry); writeRegister(REG_OF, carry); break; } default: throw Exception("size not implemented", insn); } writeRegister(REG_SF, policy.undefined_()); writeRegister(REG_ZF, policy.undefined_()); writeRegister(REG_AF, policy.undefined_()); writeRegister(REG_PF, policy.undefined_()); break; } case x86_idiv: { switch (numBytesInAsmType(operands[0]->get_type())) { case 1: { Word(16) op0 = readRegister<16>(REG_AX); Word(8) op1 = read8(operands[0]); /* if op1 == 0, we should trap */ Word(16) divResult = policy.signedDivide(op0, op1); Word(8) modResult = policy.signedModulo(op0, op1); /* if result overflows, we should trap */ writeRegister(REG_AX, policy.concat(extract<0, 8>(divResult), modResult)); break; } case 2: { Word(32) op0 = policy.concat(readRegister<16>(REG_AX), readRegister<16>(REG_DX)); Word(16) op1 = read16(operands[0]); /* if op1 == 0, we should trap */ Word(32) divResult = policy.signedDivide(op0, op1); Word(16) modResult = policy.signedModulo(op0, op1); /* if result overflows, we should trap */ writeRegister(REG_AX, extract<0, 16>(divResult)); writeRegister(REG_DX, modResult); break; } case 4: { Word(64) op0 = policy.concat(readRegister<32>(REG_EAX), readRegister<32>(REG_EDX)); Word(32) op1 = read32(operands[0]); /* if op1 == 0, we should trap */ Word(64) divResult = policy.signedDivide(op0, op1); Word(32) modResult = policy.signedModulo(op0, op1); /* if result overflows, we should trap */ writeRegister(REG_EAX, extract<0, 32>(divResult)); writeRegister(REG_EDX, modResult); break; } default: throw Exception("size not implemented", insn); } writeRegister(REG_SF, policy.undefined_()); writeRegister(REG_ZF, policy.undefined_()); writeRegister(REG_AF, policy.undefined_()); writeRegister(REG_PF, policy.undefined_()); writeRegister(REG_CF, policy.undefined_()); writeRegister(REG_OF, policy.undefined_()); break; } case x86_div: { switch (numBytesInAsmType(operands[0]->get_type())) { case 1: { Word(16) op0 = readRegister<16>(REG_AX); Word(8) op1 = read8(operands[0]); /* if op1 == 0, we should trap */ Word(16) divResult = policy.unsignedDivide(op0, op1); Word(8) modResult = policy.unsignedModulo(op0, op1); /* if extract<8, 16> of divResult is non-zero (overflow), we should trap */ writeRegister(REG_AX, policy.concat(extract<0, 8>(divResult), modResult)); break; } case 2: { Word(32) op0 = policy.concat(readRegister<16>(REG_AX), readRegister<16>(REG_DX)); Word(16) op1 = read16(operands[0]); /* if op1 == 0, we should trap */ Word(32) divResult = policy.unsignedDivide(op0, op1); Word(16) modResult = policy.unsignedModulo(op0, op1); /* if extract<16, 32> of divResult is non-zero (overflow), we should trap */ writeRegister(REG_AX, extract<0, 16>(divResult)); writeRegister(REG_DX, modResult); break; } case 4: { Word(64) op0 = policy.concat(readRegister<32>(REG_EAX), readRegister<32>(REG_EDX)); Word(32) op1 = read32(operands[0]); /* if op1 == 0, we should trap */ Word(64) divResult = policy.unsignedDivide(op0, op1); Word(32) modResult = policy.unsignedModulo(op0, op1); /* if extract<32, 64> of divResult is non-zero (overflow), we should trap */ writeRegister(REG_EAX, extract<0, 32>(divResult)); writeRegister(REG_EDX, modResult); break; } default: throw Exception("size not implemented", insn); } writeRegister(REG_SF, policy.undefined_()); writeRegister(REG_ZF, policy.undefined_()); writeRegister(REG_AF, policy.undefined_()); writeRegister(REG_PF, policy.undefined_()); writeRegister(REG_CF, policy.undefined_()); writeRegister(REG_OF, policy.undefined_()); break; } case x86_aaa: { if (operands.size()!=0) throw Exception("instruction must have no operands", insn); Word(1) incAh = policy.or_(readRegister<1>(REG_AF), greaterOrEqualToTen(extract<0, 4>(readRegister<8>(REG_AL)))); writeRegister(REG_AX, policy.concat(policy.add(policy.ite(incAh, number<4>(6), number<4>(0)), extract<0, 4>(readRegister<8>(REG_AL))), policy.concat(number<4>(0), policy.add(policy.ite(incAh, number<8>(1), number<8>(0)), readRegister<8>(REG_AH))))); writeRegister(REG_OF, policy.undefined_()); writeRegister(REG_SF, policy.undefined_()); writeRegister(REG_ZF, policy.undefined_()); writeRegister(REG_PF, policy.undefined_()); writeRegister(REG_AF, incAh); writeRegister(REG_CF, incAh); break; } case x86_aas: { if (operands.size()!=0) throw Exception("instruction must have no operands", insn); Word(1) decAh = policy.or_(readRegister<1>(REG_AF), greaterOrEqualToTen(extract<0, 4>(readRegister<8>(REG_AL)))); writeRegister(REG_AX, policy.concat(policy.add(policy.ite(decAh, number<4>(-6), number<4>(0)), extract<0, 4>(readRegister<8>(REG_AL))), policy.concat(number<4>(0), policy.add(policy.ite(decAh, number<8>(-1), number<8>(0)), readRegister<8>(REG_AH))))); writeRegister(REG_OF, policy.undefined_()); writeRegister(REG_SF, policy.undefined_()); writeRegister(REG_ZF, policy.undefined_()); writeRegister(REG_PF, policy.undefined_()); writeRegister(REG_AF, decAh); writeRegister(REG_CF, decAh); break; } case x86_aam: { if (operands.size()!=1) throw Exception("instruction must have one operand", insn); Word(8) al = readRegister<8>(REG_AL); Word(8) divisor = read8(operands[0]); Word(8) newAh = policy.unsignedDivide(al, divisor); Word(8) newAl = policy.unsignedModulo(al, divisor); writeRegister(REG_AX, policy.concat(newAl, newAh)); writeRegister(REG_OF, policy.undefined_()); writeRegister(REG_AF, policy.undefined_()); writeRegister(REG_CF, policy.undefined_()); setFlagsForResult<8>(newAl); break; } case x86_aad: { if (operands.size()!=1) throw Exception("instruction must have one operand", insn); Word(8) al = readRegister<8>(REG_AL); Word(8) ah = readRegister<8>(REG_AH); Word(8) divisor = read8(operands[0]); Word(8) newAl = policy.add(al, extract<0, 8>(policy.unsignedMultiply(ah, divisor))); writeRegister(REG_AX, policy.concat(newAl, number<8>(0))); writeRegister(REG_OF, policy.undefined_()); writeRegister(REG_AF, policy.undefined_()); writeRegister(REG_CF, policy.undefined_()); setFlagsForResult<8>(newAl); break; } case x86_bswap: { if (operands.size()!=1) throw Exception("instruction must have one operand", insn); Word(32) oldVal = read32(operands[0]); Word(32) newVal = policy.concat(extract<24, 32>(oldVal), policy.concat(extract<16, 24>(oldVal), policy.concat(extract<8, 16>(oldVal), extract<0, 8>(oldVal)))); write32(operands[0], newVal); break; } case x86_push: { if (operands.size()!=1) throw Exception("instruction must have one operand", insn); if (insn->get_addressSize() != x86_insnsize_32 || insn->get_operandSize() != x86_insnsize_32) throw Exception("size not implemented", insn); Word(32) oldSp = readRegister<32>(REG_ESP); Word(32) newSp = policy.add(oldSp, number<32>(-4)); policy.writeMemory(x86_segreg_ss, newSp, read32(operands[0]), policy.true_()); writeRegister(REG_ESP, newSp); break; } case x86_pushad: { if (operands.size()!=0) throw Exception("instruction must have no operands", insn); if (insn->get_addressSize() != x86_insnsize_32) throw Exception("size not implemented", insn); Word(32) oldSp = readRegister<32>(REG_ESP); Word(32) newSp = policy.add(oldSp, number<32>(-32)); policy.writeMemory(x86_segreg_ss, newSp, readRegister<32>(REG_EDI), policy.true_()); policy.writeMemory(x86_segreg_ss, policy.add(newSp, number<32>(4)), readRegister<32>(REG_ESI), policy.true_()); policy.writeMemory(x86_segreg_ss, policy.add(newSp, number<32>(8)), readRegister<32>(REG_EBP), policy.true_()); policy.writeMemory(x86_segreg_ss, policy.add(newSp, number<32>(12)), oldSp, policy.true_()); policy.writeMemory(x86_segreg_ss, policy.add(newSp, number<32>(16)), readRegister<32>(REG_EBX), policy.true_()); policy.writeMemory(x86_segreg_ss, policy.add(newSp, number<32>(20)), readRegister<32>(REG_EDX), policy.true_()); policy.writeMemory(x86_segreg_ss, policy.add(newSp, number<32>(24)), readRegister<32>(REG_ECX), policy.true_()); policy.writeMemory(x86_segreg_ss, policy.add(newSp, number<32>(28)), readRegister<32>(REG_EAX), policy.true_()); writeRegister(REG_ESP, newSp); break; } case x86_pushfd: { if (operands.size()!=0) throw Exception("instruction must have no operands", insn); if (insn->get_addressSize() != x86_insnsize_32) throw Exception("size not implemented", insn); Word(32) oldSp = readRegister<32>(REG_ESP); Word(32) newSp = policy.add(oldSp, number<32>(-4)); policy.writeMemory(x86_segreg_ss, newSp, readRegister<32>(REG_EFLAGS), policy.true_()); writeRegister(REG_ESP, newSp); break; } case x86_pop: { if (operands.size()!=1) throw Exception("instruction must have one operand", insn); if (insn->get_addressSize() != x86_insnsize_32 || insn->get_operandSize() != x86_insnsize_32) throw Exception("size not implemented", insn); Word(32) oldSp = readRegister<32>(REG_ESP); Word(32) newSp = policy.add(oldSp, number<32>(4)); writeRegister(REG_ESP, newSp); write32(operands[0], readMemory<32>(x86_segreg_ss, oldSp, policy.true_())); break; } case x86_popad: { if (operands.size()!=0) throw Exception("instruction must have no operands", insn); if (insn->get_addressSize() != x86_insnsize_32) throw Exception("size not implemented", insn); Word(32) oldSp = readRegister<32>(REG_ESP); Word(32) newSp = policy.add(oldSp, number<32>(32)); writeRegister(REG_EDI, readMemory<32>(x86_segreg_ss, oldSp, policy.true_())); writeRegister(REG_ESI, readMemory<32>(x86_segreg_ss, policy.add(oldSp, number<32>(4)), policy.true_())); writeRegister(REG_EBP, readMemory<32>(x86_segreg_ss, policy.add(oldSp, number<32>(8)), policy.true_())); writeRegister(REG_EBX, readMemory<32>(x86_segreg_ss, policy.add(oldSp, number<32>(16)), policy.true_())); writeRegister(REG_EDX, readMemory<32>(x86_segreg_ss, policy.add(oldSp, number<32>(20)), policy.true_())); writeRegister(REG_ECX, readMemory<32>(x86_segreg_ss, policy.add(oldSp, number<32>(24)), policy.true_())); writeRegister(REG_EAX, readMemory<32>(x86_segreg_ss, policy.add(oldSp, number<32>(28)), policy.true_())); readMemory<32>(x86_segreg_ss, policy.add(oldSp, number<32>(12)), policy.true_()); writeRegister(REG_ESP, newSp); break; } case x86_leave: { if (operands.size()!=0) throw Exception("instruction must have no operands", insn); writeRegister(REG_ESP, readRegister<32>(REG_EBP)); if (insn->get_addressSize() != x86_insnsize_32 || insn->get_operandSize() != x86_insnsize_32) throw Exception("size not implemented", insn); Word(32) oldSp = readRegister<32>(REG_ESP); Word(32) newSp = policy.add(oldSp, number<32>(4)); writeRegister(REG_EBP, readMemory<32>(x86_segreg_ss, oldSp, policy.true_())); writeRegister(REG_ESP, newSp); break; } case x86_call: { if (operands.size()!=1) throw Exception("instruction must have one operand", insn); if (insn->get_addressSize() != x86_insnsize_32 || insn->get_operandSize() != x86_insnsize_32) throw Exception("size not implemented", insn); Word(32) oldSp = readRegister<32>(REG_ESP); Word(32) newSp = policy.add(oldSp, number<32>(-4)); policy.writeMemory(x86_segreg_ss, newSp, readRegister<32>(REG_EIP), policy.true_()); writeRegister(REG_EIP, policy.filterCallTarget(read32(operands[0]))); writeRegister(REG_ESP, newSp); break; } case x86_ret: { if (operands.size()>1) throw Exception("instruction must have zero or one operand", insn); if (insn->get_addressSize() != x86_insnsize_32 || insn->get_operandSize() != x86_insnsize_32) throw Exception("size not implemented", insn); Word(32) extraBytes = (operands.size() == 1 ? read32(operands[0]) : number<32>(0)); Word(32) oldSp = readRegister<32>(REG_ESP); Word(32) newSp = policy.add(oldSp, policy.add(number<32>(4), extraBytes)); writeRegister(REG_EIP, policy.filterReturnTarget(readMemory<32>(x86_segreg_ss, oldSp, policy.true_()))); writeRegister(REG_ESP, newSp); break; } case x86_loop: { if (operands.size()!=1) throw Exception("instruction must have one operand", insn); if (insn->get_addressSize() != x86_insnsize_32 || insn->get_operandSize() != x86_insnsize_32) throw Exception("size not implemented", insn); Word(32) oldCx = readRegister<32>(REG_ECX); Word(32) newCx = policy.add(number<32>(-1), oldCx); writeRegister(REG_ECX, newCx); Word(1) doLoop = policy.invert(policy.equalToZero(newCx)); writeRegister(REG_EIP, policy.ite(doLoop, read32(operands[0]), readRegister<32>(REG_EIP))); break; } case x86_loopz: { if (operands.size()!=1) throw Exception("instruction must have one operand", insn); if (insn->get_addressSize() != x86_insnsize_32 || insn->get_operandSize() != x86_insnsize_32) throw Exception("size not implemented", insn); Word(32) oldCx = readRegister<32>(REG_ECX); Word(32) newCx = policy.add(number<32>(-1), oldCx); writeRegister(REG_ECX, newCx); Word(1) doLoop = policy.and_(policy.invert(policy.equalToZero(newCx)), readRegister<1>(REG_ZF)); writeRegister(REG_EIP, policy.ite(doLoop, read32(operands[0]), readRegister<32>(REG_EIP))); break; } case x86_loopnz: { if (operands.size()!=1) throw Exception("instruction must have one operand", insn); if (insn->get_addressSize() != x86_insnsize_32 || insn->get_operandSize() != x86_insnsize_32) throw Exception("size not implemented", insn); Word(32) oldCx = readRegister<32>(REG_ECX); Word(32) newCx = policy.add(number<32>(-1), oldCx); writeRegister(REG_ECX, newCx); Word(1) doLoop = policy.and_(policy.invert(policy.equalToZero(newCx)), policy.invert(readRegister<1>(REG_ZF))); writeRegister(REG_EIP, policy.ite(doLoop, read32(operands[0]), readRegister<32>(REG_EIP))); break; } case x86_jmp: { if (operands.size()!=1) throw Exception("instruction must have one operand", insn); writeRegister(REG_EIP, policy.filterIndirectJumpTarget(read32(operands[0]))); break; } /* Flag expressions that must be true for a conditional jump to occur. */ # define FLAGCOMBO_ne policy.invert(readRegister<1>(REG_ZF)) # define FLAGCOMBO_e readRegister<1>(REG_ZF) # define FLAGCOMBO_no policy.invert(readRegister<1>(REG_OF)) # define FLAGCOMBO_o readRegister<1>(REG_OF) # define FLAGCOMBO_ns policy.invert(readRegister<1>(REG_SF)) # define FLAGCOMBO_s readRegister<1>(REG_SF) # define FLAGCOMBO_po policy.invert(readRegister<1>(REG_PF)) # define FLAGCOMBO_pe readRegister<1>(REG_PF) # define FLAGCOMBO_ae policy.invert(readRegister<1>(REG_CF)) # define FLAGCOMBO_b readRegister<1>(REG_CF) # define FLAGCOMBO_be policy.or_(FLAGCOMBO_b, FLAGCOMBO_e) # define FLAGCOMBO_a policy.and_(FLAGCOMBO_ae, FLAGCOMBO_ne) # define FLAGCOMBO_l policy.xor_(readRegister<1>(REG_SF), readRegister<1>(REG_OF)) # define FLAGCOMBO_ge policy.invert(policy.xor_(readRegister<1>(REG_SF), readRegister<1>(REG_OF))) # define FLAGCOMBO_le policy.or_(FLAGCOMBO_e, FLAGCOMBO_l) # define FLAGCOMBO_g policy.and_(FLAGCOMBO_ge, FLAGCOMBO_ne) # define FLAGCOMBO_cxz policy.equalToZero(readRegister<16>(REG_CX)) # define FLAGCOMBO_ecxz policy.equalToZero(readRegister<32>(REG_ECX)) # define JUMP(tag) { \ if (operands.size()!=1) \ throw Exception("instruction must have one operand", insn); \ writeRegister(REG_EIP, policy.ite(FLAGCOMBO_##tag, \ read32(operands[0]), \ readRegister<32>(REG_EIP))); \ } case x86_jne: JUMP(ne); break; case x86_je: JUMP(e); break; case x86_jno: JUMP(no); break; case x86_jo: JUMP(o); break; case x86_jpo: JUMP(po); break; case x86_jpe: JUMP(pe); break; case x86_jns: JUMP(ns); break; case x86_js: JUMP(s); break; case x86_jae: JUMP(ae); break; case x86_jb: JUMP(b); break; case x86_jbe: JUMP(be); break; case x86_ja: JUMP(a); break; case x86_jle: JUMP(le); break; case x86_jg: JUMP(g); break; case x86_jge: JUMP(ge); break; case x86_jl: JUMP(l); break; case x86_jcxz: JUMP(cxz); break; case x86_jecxz: JUMP(ecxz); break; # undef JUMP # define SET(tag) { \ if (operands.size()!=1) \ throw Exception("instruction must have one operand", insn); \ write8(operands[0], policy.concat(FLAGCOMBO_##tag, number<7>(0))); \ } case x86_setne: SET(ne); break; case x86_sete: SET(e); break; case x86_setno: SET(no); break; case x86_seto: SET(o); break; case x86_setpo: SET(po); break; case x86_setpe: SET(pe); break; case x86_setns: SET(ns); break; case x86_sets: SET(s); break; case x86_setae: SET(ae); break; case x86_setb: SET(b); break; case x86_setbe: SET(be); break; case x86_seta: SET(a); break; case x86_setle: SET(le); break; case x86_setg: SET(g); break; case x86_setge: SET(ge); break; case x86_setl: SET(l); break; # undef SET # define CMOV(tag) { \ if (operands.size()!=2) \ throw Exception("instruction must have two operands", insn); \ switch (numBytesInAsmType(operands[0]->get_type())) { \ case 2: write16(operands[0], policy.ite(FLAGCOMBO_##tag, read16(operands[1]), read16(operands[0]))); break; \ case 4: write32(operands[0], policy.ite(FLAGCOMBO_##tag, read32(operands[1]), read32(operands[0]))); break; \ default: throw Exception("size not implemented", insn); \ \ } \ } case x86_cmovne: CMOV(ne); break; case x86_cmove: CMOV(e); break; case x86_cmovno: CMOV(no); break; case x86_cmovo: CMOV(o); break; case x86_cmovpo: CMOV(po); break; case x86_cmovpe: CMOV(pe); break; case x86_cmovns: CMOV(ns); break; case x86_cmovs: CMOV(s); break; case x86_cmovae: CMOV(ae); break; case x86_cmovb: CMOV(b); break; case x86_cmovbe: CMOV(be); break; case x86_cmova: CMOV(a); break; case x86_cmovle: CMOV(le); break; case x86_cmovg: CMOV(g); break; case x86_cmovge: CMOV(ge); break; case x86_cmovl: CMOV(l); break; # undef CMOV /* The flag expressions are no longer needed */ # undef FLAGCOMBO_ne # undef FLAGCOMBO_e # undef FLAGCOMBO_ns # undef FLAGCOMBO_s # undef FLAGCOMBO_ae # undef FLAGCOMBO_b # undef FLAGCOMBO_be # undef FLAGCOMBO_a # undef FLAGCOMBO_l # undef FLAGCOMBO_ge # undef FLAGCOMBO_le # undef FLAGCOMBO_g # undef FLAGCOMBO_cxz # undef FLAGCOMBO_ecxz case x86_cld: { if (operands.size()!=0) throw Exception("instruction must have no operands", insn); writeRegister(REG_DF, policy.false_()); break; } case x86_std: { if (operands.size()!=0) throw Exception("instruction must have no operands", insn); writeRegister(REG_DF, policy.true_()); break; } case x86_clc: { if (operands.size()!=0) throw Exception("instruction must have no operands", insn); writeRegister(REG_CF, policy.false_()); break; } case x86_stc: { if (operands.size()!=0) throw Exception("instruction must have no operands", insn); writeRegister(REG_CF, policy.true_()); break; } case x86_cmc: { if (operands.size()!=0) throw Exception("instruction must have no operands", insn); writeRegister(REG_CF, policy.invert(readRegister<1>(REG_CF))); break; } case x86_nop: break; case x86_repne_scasb: repne_scas_semantics<1>(insn); break; case x86_repne_scasw: repne_scas_semantics<2>(insn); break; case x86_repne_scasd: repne_scas_semantics<4>(insn); break; case x86_repe_scasb: repe_scas_semantics<1>(insn); break; case x86_repe_scasw: repe_scas_semantics<2>(insn); break; case x86_repe_scasd: repe_scas_semantics<4>(insn); break; case x86_scasb: scas_semantics<1>(insn, policy.true_()); break; case x86_scasw: scas_semantics<2>(insn, policy.true_()); break; case x86_scasd: scas_semantics<4>(insn, policy.true_()); break; case x86_repne_cmpsb: repne_cmps_semantics<1>(insn); break; case x86_repne_cmpsw: repne_cmps_semantics<2>(insn); break; case x86_repne_cmpsd: repne_cmps_semantics<4>(insn); break; case x86_repe_cmpsb: repe_cmps_semantics<1>(insn); break; case x86_repe_cmpsw: repe_cmps_semantics<2>(insn); break; case x86_repe_cmpsd: repe_cmps_semantics<4>(insn); break; case x86_cmpsb: cmps_semantics<1>(insn, policy.true_()); break; case x86_cmpsw: cmps_semantics<2>(insn, policy.true_()); break; case x86_cmpsd: /* This mnemonic, CMPSD, refers to two instructions: opcode A7 compares registers SI and DI (16-, 32-, or * 64-bits) and sets the status flags. Opcode "F2 0F C2 /r ib" takes three arguments (an MMX register, an MMX * or 64-bit register, and an 8-bit immediate) and compares floating point values. The instruction semantics * layer doesn't handle floating point instructions yet and reports them as "Bad instruction". */ if (0==operands.size()) { cmps_semantics<4>(insn, policy.true_()); break; } else { /* Floating point instructions are not handled yet. */ throw Exception("instruction not implemented", insn); } break; case x86_movsb: movs_semantics<1>(insn, policy.true_()); break; case x86_movsw: movs_semantics<2>(insn, policy.true_()); break; case x86_movsd: movs_semantics<4>(insn, policy.true_()); break; case x86_rep_movsb: rep_movs_semantics<1>(insn); break; case x86_rep_movsw: rep_movs_semantics<2>(insn); break; case x86_rep_movsd: rep_movs_semantics<4>(insn); break; case x86_stosb: stos_semantics<1>(insn, policy.true_()); break; case x86_stosw: stos_semantics<2>(insn, policy.true_()); break; case x86_stosd: stos_semantics<4>(insn, policy.true_()); break; case x86_rep_stosb: rep_stos_semantics<1>(insn); break; case x86_rep_stosw: rep_stos_semantics<2>(insn); break; case x86_rep_stosd: rep_stos_semantics<4>(insn); break; case x86_lodsb: lods_semantics<1>(insn); break; case x86_lodsw: lods_semantics<2>(insn); break; case x86_lodsd: lods_semantics<4>(insn); break; case x86_hlt: { if (operands.size()!=0) throw Exception("instruction must have no operands", insn); policy.hlt(); writeRegister(REG_EIP, orig_eip); break; } case x86_cpuid: { if (operands.size()!=0) throw Exception("instruction must have no operands", insn); policy.cpuid(); break; } case x86_rdtsc: { if (operands.size()!=0) throw Exception("instruction must have no operands", insn); Word(64) tsc = policy.rdtsc(); writeRegister(REG_EAX, extract<0, 32>(tsc)); writeRegister(REG_EDX, extract<32, 64>(tsc)); break; } case x86_int: { if (operands.size()!=1) throw Exception("instruction must have one operand", insn); SgAsmByteValueExpression* bv = isSgAsmByteValueExpression(operands[0]); if (!bv) throw Exception("operand must be a byte value expression", insn); policy.interrupt(bv->get_value()); break; } /* This is a dummy version that should be replaced later FIXME */ case x86_fnstcw: { if (operands.size()!=1) throw Exception("instruction must have one operand", insn); write16(operands[0], number<16>(0x37f)); break; } case x86_fldcw: { if (operands.size()!=1) throw Exception("instruction must have one operand", insn); read16(operands[0]); /* To catch access control violations */ break; } case x86_sysenter: { if (operands.size()!=0) throw Exception("instruction must have no operands", insn); policy.sysenter(); break; } default: { throw Exception("instruction not implemented", insn); break; } } } catch(Exception e) { if (!e.insn) e.insn = insn; throw e; } #endif void processInstruction(SgAsmx86Instruction* insn) { ROSE_ASSERT(insn); current_instruction = insn; policy.startInstruction(insn); translate(insn); policy.finishInstruction(insn); } void processBlock(const SgAsmStatementPtrList& stmts, size_t begin, size_t end) { if (begin == end) return; policy.startBlock(stmts[begin]->get_address()); for (size_t i = begin; i < end; ++i) { processInstruction(isSgAsmx86Instruction(stmts[i])); } policy.finishBlock(stmts[begin]->get_address()); } static bool isRepeatedStringOp(SgAsmStatement* s) { SgAsmx86Instruction* insn = isSgAsmx86Instruction(s); if (!insn) return false; switch (insn->get_kind()) { case x86_repe_cmpsb: return true; case x86_repe_cmpsd: return true; case x86_repe_cmpsq: return true; case x86_repe_cmpsw: return true; case x86_repe_scasb: return true; case x86_repe_scasd: return true; case x86_repe_scasq: return true; case x86_repe_scasw: return true; case x86_rep_insb: return true; case x86_rep_insd: return true; case x86_rep_insw: return true; case x86_rep_lodsb: return true; case x86_rep_lodsd: return true; case x86_rep_lodsq: return true; case x86_rep_lodsw: return true; case x86_rep_movsb: return true; case x86_rep_movsd: return true; case x86_rep_movsq: return true; case x86_rep_movsw: return true; case x86_repne_cmpsb: return true; case x86_repne_cmpsd: return true; case x86_repne_cmpsq: return true; case x86_repne_cmpsw: return true; case x86_repne_scasb: return true; case x86_repne_scasd: return true; case x86_repne_scasq: return true; case x86_repne_scasw: return true; case x86_rep_outsb: return true; case x86_rep_outsd: return true; case x86_rep_outsw: return true; case x86_rep_stosb: return true; case x86_rep_stosd: return true; case x86_rep_stosq: return true; case x86_rep_stosw: return true; default: return false; } } static bool isHltOrInt(SgAsmStatement* s) { SgAsmx86Instruction* insn = isSgAsmx86Instruction(s); if (!insn) return false; switch (insn->get_kind()) { case x86_hlt: return true; case x86_int: return true; default: return false; } } void processBlock(SgAsmBlock* b) { const SgAsmStatementPtrList& stmts = b->get_statementList(); if (stmts.empty()) return; if (!isSgAsmInstruction(stmts[0])) return; /* A block containing functions or something */ size_t i = 0; while (i < stmts.size()) { size_t oldI = i; /* Advance until either i points to a repeated string op or it is just after a hlt or int */ while (i < stmts.size() && !isRepeatedStringOp(stmts[i]) && (i == oldI || !isHltOrInt(stmts[i - 1]))) ++i; processBlock(stmts, oldI, i); if (i >= stmts.size()) break; if (isRepeatedStringOp(stmts[i])) { processBlock(stmts, i, i + 1); ++i; } ROSE_ASSERT(i != oldI); } } }; #undef Word } /*namespace*/ } /*namespace*/ #endif /* ROSE_X86INSTRUCTIONSEMANTICS_H */
#include "i2c_device.h" bool device_triggered[256] = {false}; static void i2c_device_hook(struct avr_irq_t * irq, uint32_t value, void* adevice){ i2c_device* p = (i2c_device*)adevice; avr_twi_msg_irq_t v; v.u.v = value; /* * If we receive a STOP, check it was meant to us, and reset the transaction */ if (v.u.twi.msg & TWI_COND_STOP) { p->selected = 0; } /* uint8_t addr = v.u.twi.addr; if(device_triggered[addr] == false){ device_triggered[addr] = true; printf("%d\r\n",addr); }*/ /* * if we receive a start, reset status, check if the slave address is * meant to be us, and if so reply with an ACK bit */ if (v.u.twi.msg & TWI_COND_START) { p->selected = 0; if (p->address == v.u.twi.addr || p->address == v.u.twi.addr-1){ // it's us ! p->selected = v.u.twi.addr; avr_raise_irq(p->irq_list + TWI_IRQ_INPUT, avr_twi_irq_msg(TWI_COND_ACK, p->selected, 1)); } } /* * If it's a data transaction, first check it is meant to be us (we * received the correct address and are selected) */ if (p->selected) { /* * This is a write transaction */ if (v.u.twi.msg & TWI_COND_WRITE) { avr_raise_irq(p->irq_list + TWI_IRQ_INPUT, avr_twi_irq_msg(TWI_COND_ACK, p->selected, 1)); p->write(v.u.twi.data); } /* * It's a read transaction */ if (v.u.twi.msg & TWI_COND_READ) { uint8_t data = p->read(); avr_raise_irq(p->irq_list + TWI_IRQ_INPUT, avr_twi_irq_msg(TWI_COND_READ, p->selected, data)); } } } i2c_device::i2c_device(uint8_t aaddress, const char* name) : device(){ address = aaddress; selected = 0; c_names[0] = (std::string(name) + "_in").c_str(); c_names[1] = (std::string(name) + "_out").c_str(); } void i2c_device::attach(struct avr_t * avr){ irq_list = avr_alloc_irq(&avr->irq_pool, 0, 2, c_names); avr_irq_register_notify(irq_list + TWI_IRQ_OUTPUT, i2c_device_hook, (void*)this); // "connect" the IRQs of the device to the TWI/i2c master of the AVR avr_connect_irq(irq_list + TWI_IRQ_INPUT, avr_io_getirq(avr, AVR_IOCTL_TWI_GETIRQ(0), TWI_IRQ_INPUT)); avr_connect_irq(avr_io_getirq(avr, AVR_IOCTL_TWI_GETIRQ(0), TWI_IRQ_OUTPUT), irq_list + TWI_IRQ_OUTPUT ); } i2c_device::~i2c_device(){ //TODO detatch irq }
#pragma once class Food { private: POSITION foodPos; ege::PIMAGE foodImg; public: Food(); ~Food(); void reDraw(); POSITION getFoodPostion(); };
/*********************************************************************** created: Thu Feb 16 2012 author: Paul D Turner <paul@cegui.org.uk> *************************************************************************/ /*************************************************************************** * Copyright (C) 2004 - 2012 Paul D Turner & The CEGUI Development Team * * 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 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 _CEGUIInjectedInputReceiver_h_ #define _CEGUIInjectedInputReceiver_h_ #include "CEGUI/InputEvent.h" namespace CEGUI { //! Input injection interface to be implemented by classes that take raw inputs class CEGUIEXPORT InjectedInputReceiver { public: virtual ~InjectedInputReceiver() = default; /*! \brief Function that injects a mouse movement event into the receiver. \param delta_x amount the mouse moved on the x axis. \param delta_y amount the mouse moved on the y axis. \return - true if the input was processed by the input receiver. - false if the input was not processed by the input receiver. */ virtual bool injectMouseMove(float delta_x, float delta_y) = 0; /*! \brief Function that notifies that the mouse has left the host area that the receiver receives input for. \return - true if the event was handled. - false if the event was not handled. */ virtual bool injectMouseLeaves() = 0; /*! \brief Function that injects a mouse button down event into the receiver. \param button One of the MouseButton values indicating which button was pressed. \return - true if the input was processed by the receiver. - false if the input was not processed by the receiver. */ virtual bool injectMouseButtonDown(MouseButton button) = 0; /*! \brief Function that injects a mouse button up event into the receiver. \param button One of the MouseButton values indicating which button was released. \return - true if the input was processed by the receiver. - false if the input was not processed by the receiver. */ virtual bool injectMouseButtonUp(MouseButton button) = 0; /*! \brief Function that injects a key down event into the receiver. \param key_code Key::Scan value indicating which key was pressed. \return - true if the input was processed by the receiver. - false if the input was not processed by the receiver. */ virtual bool injectKeyDown(Key::Scan scan_code) = 0; /*! \brief Function that injects a key up event into the receiver. \param key_code Key::Scan value indicating which key was released. \return - true if the input was processed by the receiver. - false if the input was not processed by the receiver. */ virtual bool injectKeyUp(Key::Scan scan_code) = 0; /*! \brief Function that injects a typed character event into the receiver. \param code_point Unicode or ASCII (depends on used String class) code point of the character that was typed. \return - true if the input was processed by the receiver. - false if the input was not processed by the receiver. */ virtual bool injectChar(char32_t code_point) = 0; /*! \brief Function that injects a mouse-wheel / scroll-wheel event into the receiver. \param delta float value representing the amount the wheel moved. \return - true if the input was processed by the receiver. - false if the input was not processed by the receiver. */ virtual bool injectMouseWheelChange(float delta) = 0; /*! \brief Function that injects a new position for the mouse cursor. \param x_pos New absolute pixel position of the mouse cursor on the x axis. \param y_pos New absolute pixel position of the mouse cursoe in the y axis. \return - true if the generated mouse move event was handled. - false if the generated mouse move event was not handled. */ virtual bool injectMousePosition(float x_pos, float y_pos) = 0; /*! \brief Function to directly inject a mouse button click event. Here 'click' means a mouse button down event followed by a mouse button up event. \note Under normal, default settings, this event is automatically generated by the system from the regular up and down events you inject. You may use this function directly, though you'll probably want to disable the automatic click event generation first by using the setMouseClickEventGenerationEnabled function - this setting controls the auto-generation of events and also determines the default 'handled' state of the injected click events according to the rules used for mouse up/down events. \param button One of the MouseButton enumerated values. \return - true if some window or handler reported that it handled the event. - false if nobody handled the event. */ virtual bool injectMouseButtonClick(const MouseButton button) = 0; /*! \brief Function to directly inject a mouse button double-click event. Here 'double-click' means a single mouse button had the sequence down, up, down within a predefined period of time. \note Under normal, default settings, this event is automatically generated by the system from the regular up and down events you inject. You may use this function directly, though you'll probably want to disable the automatic click event generation first by using the setMouseClickEventGenerationEnabled function - this setting controls the auto-generation of events and also determines the default 'handled' state of the injected click events according to the rules used for mouse up/down events. \param button One of the MouseButton enumerated values. \return - true if some window or handler reported that it handled the event. - false if nobody handled the event. */ virtual bool injectMouseButtonDoubleClick(const MouseButton button) = 0; /*! \brief Function to directly inject a mouse button triple-click event. Here 'triple-click' means a single mouse button had the sequence down, up, down, up, down within a predefined period of time. \note Under normal, default settings, this event is automatically generated by the system from the regular up and down events you inject. You may use this function directly, though you'll probably want to disable the automatic click event generation first by using the setMouseClickEventGenerationEnabled function - this setting controls the auto-generation of events and also determines the default 'handled' state of the injected click events according to the rules used for mouse up/down events. \param button One of the MouseButton enumerated values. \return - true if some window or handler reported that it handled the event. - false if nobody handled the event. */ virtual bool injectMouseButtonTripleClick(const MouseButton button) = 0; }; } #endif
// RPC stubs for clients to talk to lock_server, and cache the locks // see lock_client.cache.h for protocol details. #include "lock_client_cache.h" #include "rpc.h" #include <sstream> #include <iostream> #include <stdio.h> #include "tprintf.h" #include <time.h> #include <vector> #include <unistd.h> using namespace std; int lock_client_cache::last_port = 0; lock_client_cache::lock_client_cache(std::string xdst, i_lock_release_user *_lu) : lock_client(xdst), lu(_lu) { srand(time(NULL)^last_port); rlock_port = ((rand()%32000) | (0x1 << 10)); const char *hname; // VERIFY(gethostname(hname, 100) == 0); hname = "127.0.0.1"; std::ostringstream host; host << hname << ":" << rlock_port; id = host.str(); last_port = rlock_port; rpcs *rlsrpc = new rpcs(rlock_port); rlsrpc->reg(rlock_protocol::revoke, this, &lock_client_cache::revoke_handler); rlsrpc->reg(rlock_protocol::retry, this, &lock_client_cache::retry_handler); pthread_mutex_init(&lc_mutex, 0); pthread_create(&tid, 0, &lock_client_cache::thread_func, this); } lock_client_cache::~lock_client_cache() { pthread_cancel(tid); pthread_join(tid, 0); } lock_protocol::status lock_client_cache::acquire(lock_protocol::lockid_t lid) { /* *0. accuqire global lock *1. if not in map, create and mark UNALLOC *2. get and judge status *3. if UNALLOC, mark WAIT and ask server for it * 3.1 if server return OK, mark it OCCUPY and mark nd_return, * relese global lock and exit function * 3.2 if not, release global lock and return step 0 *4. if AVAIL, mark OCCUPY, release global lock and exit function *5. else release global lock and return step 0 */ int ret = lock_protocol::RETRY; do { pthread_mutex_lock(&lc_mutex); lock_info info = lc_map[lid]; if(info.status == UNALLOC) { info.status = WAIT; int r; ret = cl->call(lock_protocol::acquire, lid, id, r); if(ret == lock_protocol::OK) { //printf("[%s] request lock:%u res:%u nd_return:%u\n", // id.c_str(), int(lid), int(ret), r); info.status = OCCUPY; info.nd_return = (r == 1); } lc_map[lid] = info; } else if(info.status == AVAIL) { //printf("[%s] acquire lock:%u\n", id.c_str(), int(lid)); info.status = OCCUPY; lc_map[lid] = info; ret = lock_protocol::OK; } //WAIT & OCCUPY do nothing pthread_mutex_unlock(&lc_mutex); } while(ret == lock_protocol::RETRY); return ret; } lock_protocol::status lock_client_cache::release(lock_protocol::lockid_t lid) { pthread_mutex_lock(&lc_mutex); lock_info info = lc_map[lid]; info.status = AVAIL; info.last_release = time(0); lc_map[lid] = info; pthread_mutex_unlock(&lc_mutex); //printf("[%s] release lock:%u\n", id.c_str(), int(lid)); return lock_protocol::OK; } rlock_protocol::status lock_client_cache::revoke_handler(lock_protocol::lockid_t lid, int &r) { //no use int ret = rlock_protocol::OK; return ret; } rlock_protocol::status lock_client_cache::retry_handler(lock_protocol::lockid_t lid, int nd_return, int &r) { //svr inform client when 1.someone need the lock 2.when lock is OK pthread_mutex_lock(&lc_mutex); lock_info info = lc_map[lid]; if(info.status == UNALLOC || info.status == WAIT) info.status = AVAIL; info.nd_return = (nd_return == 1); lc_map[lid] = info; pthread_mutex_unlock(&lc_mutex); //printf("[%s] retry lock:%u nd_return:%u\n", id.c_str(), int(lid), nd_return); return rlock_protocol::OK; } void *lock_client_cache::thread_func(void *data) { lock_client_cache *p = (lock_client_cache *)data; while(true) { sleep(1); pthread_mutex_lock(&(p->lc_mutex)); vector<lock_protocol::lockid_t> nd_release; for(map<lock_protocol::lockid_t, lock_info>::iterator it = p->lc_map.begin(); it != p->lc_map.end(); ++it) { if(it->second.nd_return && it->second.status == AVAIL /*&& it->second.last_release < time(0)*/) { it->second.status = OCCUPY; nd_release.push_back(it->first); //printf("[%s] recycle lock:%u\n", // p->id.c_str(), int(it->first)); } } pthread_mutex_unlock(&(p->lc_mutex)); for(vector<lock_protocol::lockid_t>::iterator it = nd_release.begin(); it != nd_release.end(); ++it) { int r; p->call_do_release(*it); p->cl->call(lock_protocol::release, *it, p->id, r); //printf("[%s] do release:%u\n", p->id.c_str(), int(*it)); pthread_mutex_lock(&(p->lc_mutex)); p->lc_map[*it].status = UNALLOC; p->lc_map[*it].nd_return = 0; pthread_mutex_unlock(&(p->lc_mutex)); } } return 0; }
#ifndef SEVENSEGMENT_H_ #define SEVENSEGMENT_H_ #include <ostream> void printLargeDigit(int i, std::ostream &out); void printLargeNumber(int i, std::ostream &out); void printLargeError(std::ostream &out); #endif /* SEVENSEGMENT_H_ */
// Copyright 2021 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "ash/components/fwupd/firmware_update_manager.h" #include "base/check_op.h" namespace ash { namespace { FirmwareUpdateManager* g_instance = nullptr; } // namespace FirmwareUpdateManager::FirmwareUpdateManager() { DCHECK_EQ(nullptr, g_instance); g_instance = this; } FirmwareUpdateManager::~FirmwareUpdateManager() { DCHECK_EQ(this, g_instance); g_instance = nullptr; } // static FirmwareUpdateManager* FirmwareUpdateManager::Get() { DCHECK(g_instance); return g_instance; } } // namespace ash
#include "VulkanException.h" VulkanException::VulkanException(char const* const message, int line, char const* file) throw() : std::runtime_error(message), message(message), line(line), file(file) {} char const * VulkanException::what() const throw() { return message; }
#include<stdio.h> int main() { int i,j,k,count=0,arr[100],temp,np,n; scanf("%d",&np); for(k=0; k<np; k++) { scanf("%d",&n); for(i=0;i<n;i++) scanf("%d",&arr[i]); count=0; for (i = 1; i < n; i++) { for (j = 0; j<n - i; j++) { if (arr[j]>arr[j + 1]) { temp = arr[j]; arr[j] = arr[j + 1]; arr[j + 1] = temp; count++; } } } printf("Optimal train swapping takes %d swaps.\n",count); } return 0; }
#include <bits/stdc++.h> using namespace std; int main() { string a; cin>>a; bool vis[1000]; for(int i=0; i<1000; i++) vis[i] = 0; int n = 0; for(int i=0; i<a.length(); i++) { if(!vis[a[i]]) { n++; vis[a[i]] = 1; } } if(n%2==0) cout<<"CHAT WITH HER!"<<endl; else cout<<"IGNORE HIM!"<<endl; }
#ifndef __COMMONHEADER_H_ #define __COMMONHEADER_H_ #include <stdio.h> #include <iostream> #include <algorithm> #include <WS2tcpip.h> #include <WinSock2.h> #include <fstream> #include <process.h> #include <sqlext.h> #include <vector> #include <queue> #include <list> #include <map> #include <unordered_map> #include <algorithm> #include "CommonType.h" #include "CLog.h" #include "CRandom.h" #include "CSingleton.h" #include "command.h" #include "packet.h" #include "ipEndPoint.h" #include "CSendBuffer.h" #include "CLocker.h" #include "CCircleQueue.h" #include "CThreadSafeQueue.h" using namespace std; #define SAFE_DELETE(p) if (p) { delete (p); (p) = NULL; } #define SAFE_DELETE_ARRAY(p) if (p) { delete[] (p); (p) = NULL;} #define CLOSE_SOCKET(s) if (s) {closesocket(s); (s) = 0; } #endif