├── .gitignore ├── LICENSE ├── README.md ├── algorithm ├── ex5 │ ├── clist.c │ ├── clist.h │ ├── dlist.c │ ├── dlist.h │ ├── frames.c │ ├── list.c │ ├── list.h │ ├── page.c │ └── page.h ├── ex6 │ ├── events.c │ ├── list.h │ ├── queue.c │ ├── queue.h │ ├── stack.c │ └── stack.h ├── ex7 │ ├── cover.c │ ├── cover.h │ ├── list.h │ ├── set.c │ └── set.h └── ex8 │ ├── chtbl.c │ ├── chtbl.h │ ├── hashpjw.c │ └── list.h ├── anagram ├── README ├── change.c ├── sign.c └── squash.c ├── cppdemo ├── Blob.h ├── Sales_data_class.h ├── String.cpp ├── String.h ├── book_sales ├── data ├── test_13_16.cpp ├── test_13_27.cpp ├── test_13_30.cpp ├── test_13_34_36.cpp ├── test_13_39.cpp ├── test_13_39.h ├── test_13_40.cpp ├── test_13_40.h ├── test_13_43.cpp ├── test_13_43.h ├── test_13_44.cpp ├── test_HadPtr.cpp ├── test_blob.cpp └── test_sales_data.cpp ├── hanoi_game ├── README ├── hanoi.cpp ├── hanoi_2013.scm ├── hanoi_alg.scm ├── hanoi_auto.c ├── hanoi_new.c ├── hanoi_tower.c ├── hanoi_tower_win.c ├── makefile └── test-hanoi.sh ├── idea-365 ├── D001_RandomFilesName │ └── RandomFilesName.java ├── D002_myForthEval │ └── myForthEval.js ├── D003_JavaCompiler │ ├── MyBook.java │ └── TestCompiler.java ├── D004_GameOfLife │ └── LifeGame.java ├── D005_DispatcherTools │ ├── BeanOperate.java │ ├── Company.java │ ├── Dept.java │ ├── Emp.java │ ├── StringUtils.java │ └── TestDemo.java ├── D006_ComplexLambda │ ├── Apple.java │ └── ComplexLambda.java ├── D007_StreamTest │ ├── Dish.java │ └── StreamTest.java ├── D008_CollectorsTest │ ├── CollectorsTest.java │ └── ToListCollector.java ├── D009_ParallelStreamsTest │ └── ParallelStreamsTest.java ├── D010_StackVm │ ├── DictUtil.java │ ├── TestNewDict.java │ ├── Vm.java │ └── WordUtil.java ├── D011BatchRname │ └── rename.py ├── D012_TraverseFiles │ └── TraverseFiles.cpp ├── D013_KnapsackProblem │ └── KnapsackProblem.cpp ├── D014_EditDistance │ └── EditDistance.cpp ├── D015_GoogleFunction │ └── GoogleFunction.cpp ├── D016_LongestCommonSubsequence │ ├── 最长公共子序列_动态规划.cpp │ ├── 最长公共子序列_动态规划_带回溯.cpp │ ├── 最长公共子序列_动态规划_最小空间.cpp │ ├── 最长公共子序列_备忘表.cpp │ └── 最长公共子序列_朴素算法.cpp ├── D017_RleEncode │ └── RLE压缩算法.cpp ├── D018_BinarySearchTree │ ├── BinarySearchTree.cpp │ └── BinarySearchTree.h ├── D019_RedBlackTree │ ├── RBTree.cpp │ └── RBTree.h ├── D020_CFCrypto │ ├── CFCrypto.py │ ├── CFCryptoMultiprocessing.py │ ├── CFX.py │ ├── test_cfx.py │ └── test_crypto.py ├── D021_CFSearch │ └── CFSearch.py ├── D022_CFFile │ └── CFFile.py ├── D023_FileSplit │ └── FileSplit.py ├── D024_CFPassword │ └── CFPassword.py ├── D025_SqliteDataModel │ ├── DataModel.py │ └── test_DataModel.py ├── D026_CFORM │ ├── CFORM │ │ ├── Model.py │ │ ├── __init__.py │ │ └── db.py │ └── tests │ │ └── test_Model.py ├── D027_CFImage │ └── CFImage.py ├── D028_XML2GUI │ ├── MainWindow.py │ ├── my_window.xml │ └── xml2gui.py ├── D029_JSON2GUI │ ├── Calculator.py │ ├── UI.json │ └── json2gui.py ├── D030_StockQuotation │ ├── StockQutation.py │ └── UI.json ├── D031_MP3Player │ ├── MP3Player.py │ └── UI.json ├── D032_ImgLook │ ├── ImgLook.py │ └── UI.json ├── D033_JSON2PY │ ├── GifHandle.py │ ├── ImgLook.py │ ├── UI.json │ ├── UI.py │ └── json2py.py ├── D034_CFCanvas │ └── CFCanvas.py ├── D035_FFmpegTool │ ├── FFmpegTool.py │ └── FFmpegToolUI.json ├── D036_ProgressBar │ └── ProgressBar.py ├── D037_CFFormatFile │ └── CFFormatFile.py ├── D038_CryptoTools │ ├── FileSplit.py │ ├── FileSplitUI.json │ ├── MD5Generate.py │ ├── MD5GenerateUI.json │ ├── RandomPassword.py │ ├── RandomPasswordUI.json │ └── libs │ │ ├── CFFile.py │ │ ├── Util.py │ │ └── json2gui.py ├── D039_SocketTest │ └── ChatClient.py ├── D040_WeiboHotSpider │ ├── DailyDownload.py │ ├── DataClean.py │ ├── DataExtract.py │ └── libs │ │ ├── CFCryptoX.py │ │ ├── Key.py │ │ └── ORM.py ├── D041_MusicJsonToSqlite │ └── transform.py └── README.md ├── javademo ├── CopyDemo.java ├── DAOProject │ ├── .classpath │ ├── .project │ ├── .settings │ │ └── org.eclipse.jdt.core.prefs │ └── src │ │ ├── README.md │ │ └── com │ │ └── cfxyz │ │ ├── dao │ │ ├── IDAO.java │ │ ├── IDeptDAO.java │ │ ├── IEmpDAO.java │ │ └── impl │ │ │ ├── DeptDAOImpl.java │ │ │ └── EmpDAOImpl.java │ │ ├── dbc │ │ └── DatabaseConnection.java │ │ ├── factory │ │ ├── DAOFactory.java │ │ └── ServiceFactory.java │ │ ├── service │ │ ├── IDeptService.java │ │ ├── IEmpService.java │ │ └── impl │ │ │ ├── DeptServiceImpl.java │ │ │ └── EmpServiceImpl.java │ │ ├── test │ │ ├── TestEmpInsert.java │ │ ├── TestEmpSplit.java │ │ └── junit │ │ │ ├── IDeptServiceTest.java │ │ │ └── IEmpServiceTest.java │ │ └── vo │ │ ├── Dept.java │ │ └── Emp.java ├── EchoClient.java ├── EchoServer.java ├── HelloClient.java ├── HelloServer.java ├── LinkDemo.java ├── MyProject │ ├── .classpath │ ├── .project │ ├── .settings │ │ └── org.eclipse.jdt.core.prefs │ └── src │ │ └── com │ │ └── cfxyz │ │ ├── demo │ │ ├── CopyDemo.java │ │ ├── EchoClient.java │ │ ├── EchoServer.java │ │ ├── Hello.java │ │ ├── HelloClient.java │ │ ├── HelloServer.java │ │ ├── TestArrayList.java │ │ ├── TestArrays.java │ │ ├── TestBatch.java │ │ ├── TestBinaryTree.java │ │ ├── TestClass.java │ │ ├── TestClone.java │ │ ├── TestCollections.java │ │ ├── TestDate.java │ │ ├── TestDemo.java │ │ ├── TestFactory.java │ │ ├── TestFile.java │ │ ├── TestFileOld.java │ │ ├── TestJDBC.java │ │ ├── TestMap.java │ │ ├── TestMapReduce.java │ │ ├── TestMath.java │ │ ├── TestMemoryStream.java │ │ ├── TestPrint.java │ │ ├── TestPrintStream.java │ │ ├── TestProperties.java │ │ ├── TestRegex.java │ │ ├── TestResource.java │ │ ├── TestRuntime.java │ │ ├── TestScanner.java │ │ ├── TestSerializable.java │ │ ├── TestSet.java │ │ ├── TestSimpleDateFormat.java │ │ ├── TestStream.java │ │ ├── TestStringBuffer.java │ │ ├── TestSystem.java │ │ ├── TestSystemin.java │ │ ├── TestSystemout.java │ │ ├── TestThread.java │ │ ├── TestThread2.java │ │ └── testPreparedStatement.java │ │ ├── test │ │ └── MyMathTest.java │ │ └── util │ │ └── MyMath.java ├── README.md ├── TestBatch.java ├── TestBinaryTree.java ├── TestFactory.java ├── TestFile.java ├── TestJDBC.java ├── TestMapReduce.java ├── TestPreparedStatement.java ├── TestSet.java ├── TestSimpleDateFormat.java └── TestThread.java ├── jsdemo ├── README.md ├── checkbox.html ├── css │ ├── cfxyz.css │ └── my.css ├── emp_insert.htm ├── form.html ├── js │ ├── cfxyz.js │ ├── demo.js │ └── emp.js ├── radio.html ├── select.html ├── show.html ├── textarea.html └── validatePwd.html ├── jspdemo ├── LoginProject │ ├── .classpath │ ├── .project │ ├── .settings │ │ ├── .jsdtscope │ │ ├── org.eclipse.jdt.core.prefs │ │ ├── org.eclipse.wst.common.component │ │ ├── org.eclipse.wst.common.project.facet.core.xml │ │ ├── org.eclipse.wst.jsdt.ui.superType.container │ │ └── org.eclipse.wst.jsdt.ui.superType.name │ ├── .tern-project │ ├── WebRoot │ │ ├── META-INF │ │ │ └── MANIFEST.MF │ │ ├── WEB-INF │ │ │ ├── classes │ │ │ │ └── 数据库脚本.sql │ │ │ └── web.xml │ │ ├── check.jsp │ │ ├── css │ │ │ └── cfxyz.css │ │ ├── js │ │ │ ├── cfxyz.js │ │ │ └── login.js │ │ ├── login.jsp │ │ └── welcome.jsp │ └── src │ │ └── 数据库脚本.sql └── README.md ├── lottery ├── LotterySortThree.java ├── README ├── gua_gua_le.c ├── makefile └── sort3.c ├── morse_code ├── README ├── char2morse.c └── makefile ├── puzzle_game ├── 15_puzzle.c ├── 24_puzzle.c ├── 8_puzzle.c ├── 8_puzzle_auto.c ├── README ├── makefile └── squared-up.scm ├── random_game ├── README ├── color_4.c ├── life_evolution.c ├── life_game.c ├── makefile ├── random_motion.c ├── random_walk.c └── snake.c └── testsql ├── form.sql ├── mysqltest.sql ├── practice.sql └── test.sql /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2018 No.18 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | CodeFarm--代码牧场,代码们的成长地。 2 | ===================== 3 | 4 | ###### 作者:No.18 5 | ###### E-mail:cforth@cfxyz.com 6 | --------------------- 7 | 8 | ## [algorithm](https://github.com/cforth/codefarm/tree/master/algorithm) 9 | 10 | 《算法精解:C语言表述》中的练习。 11 | 12 | ## [anagram](https://github.com/cforth/codefarm/tree/master/anagram) 13 | 14 | 字谜游戏,找出一本字典里所有的变位词。 15 | 16 | ## [hanoi_game](https://github.com/cforth/codefarm/tree/master/hanoi_game) 17 | 18 | 汉诺塔游戏,包含了linux和windows平台版本。 19 | 20 | ## [lottery](https://github.com/cforth/codefarm/tree/master/lottery) 21 | 22 | 彩票游戏,目前有刮刮乐和排列三彩票游戏。 23 | 24 | ## [puzzle_game](https://github.com/cforth/codefarm/tree/master/puzzle_game) 25 | 26 | 重排九宫系列游戏。 27 | 28 | ## [random_game](https://github.com/cforth/codefarm/tree/master/random_game) 29 | 30 | 随机游走系列游戏。 31 | 32 | ## [morse_code](https://github.com/cforth/codefarm/tree/master/morse_code) 33 | 34 | 莫尔斯电码转换。 35 | 36 | ## [javademo](https://github.com/cforth/codefarm/tree/master/javademo) 37 | 38 | 学习Java时的一些代码模型。 39 | 40 | ## [testsql](https://github.com/cforth/codefarm/tree/master/testsql) 41 | 42 | 学习Oracle数据库时的SQL语句。 43 | 44 | ## [jsdemo](https://github.com/cforth/codefarm/tree/master/jsdemo) 45 | 46 | 学习JavaScript时的一些代码模型。 47 | 48 | ## [jspdemo](https://github.com/cforth/codefarm/tree/master/jspdemo) 49 | 50 | 学习JSP时的练习项目。 51 | 52 | ## [idea-365](https://github.com/cforth/codefarm/tree/master/idea-365) 53 | 54 | 每天的记录、代码练习、小工具、思考碎片等。 55 | 56 | ## [cppdemo](https://github.com/cforth/codefarm/tree/master/cppdemo) 57 | 58 | 学习C++ Primer 59 | -------------------------------------------------------------------------------- /algorithm/ex5/clist.h: -------------------------------------------------------------------------------- 1 | #ifndef CLIST_H 2 | #define CLIST_H 3 | 4 | #include 5 | 6 | /* Define a structure for circular list elements. */ 7 | typedef struct CListElmt_ 8 | { 9 | void *data; 10 | struct CListElmt_ *next; 11 | }CListElmt; 12 | 13 | /* Define a structure for circular lists. */ 14 | typedef struct CList_ 15 | { 16 | int size; 17 | int (*match)(const void *key1, const void *key2); 18 | void (*destroy)(void *data); 19 | CListElmt *head; 20 | }CList; 21 | 22 | /* Public Interface */ 23 | void clist_init(CList *list, void (*destroy)(void *data)); 24 | void clist_destroy(CList *list); 25 | int clist_ins_next(CList *list, CListElmt *element, const void *data); 26 | int clist_rem_next(CList *list, CListElmt *element, void **data); 27 | #define clist_size(list) ((list)->size) 28 | #define clist_head(list) ((list)->head) 29 | #define clist_data(element) ((element)->data) 30 | #define clist_next(element) ((element)->next) 31 | 32 | #endif -------------------------------------------------------------------------------- /algorithm/ex5/dlist.h: -------------------------------------------------------------------------------- 1 | #ifndef DLIST_H 2 | #define DLIST_H 3 | 4 | #include 5 | 6 | /* Define a structure for doubly-linked list elements. */ 7 | typedef struct DListElmt_ 8 | { 9 | void *data; 10 | struct DListElmt_ *prev; 11 | struct DListElmt_ *next; 12 | }DListElmt; 13 | 14 | /* Define a structure for doubly-linked lists. */ 15 | typedef struct DList_ 16 | { 17 | int size; 18 | int (*match)(const void *key1, const void *key2); 19 | void (*destroy)(void *data); 20 | DListElmt *head; 21 | DListElmt *tail; 22 | }DList; 23 | 24 | /* Public Interface */ 25 | void dlist_init(DList *list, void (*destroy)(void *data)); 26 | void dlist_destroy(DList *list); 27 | int dlist_ins_next(DList *list, DListElmt *element, const void *data); 28 | int dlist_ins_prev(DList *list, DListElmt *element, const void *data); 29 | int dlist_remove(DList *list, DListElmt *element, void **data); 30 | #define dlist_size(list) ((list)->size) 31 | #define dlist_head(list) ((list)->head) 32 | #define dlist_tail(list) ((list)->tail) 33 | #define dlist_is_head(element) ((element)->prev == NULL ? 1 : 0) 34 | #define dlist_is_tail(element) ((element)->next == NULL ? 1 : 0) 35 | #define dlist_data(element) ((element)->data) 36 | #define dlist_next(element) ((element)->next) 37 | #define dlist_prev(element) ((element)->prev) 38 | 39 | #endif -------------------------------------------------------------------------------- /algorithm/ex5/frames.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | #include "frames.h" 4 | #include "list.h" 5 | 6 | /* alloc_frame */ 7 | int alloc_frame(List *frames) 8 | { 9 | int frame_number, *data; 10 | 11 | if (list_size(frames) == 0) 12 | /* Return that there are no frames available. */ 13 | return -1; 14 | else { 15 | if (list_rem_next(frames, NULL, (void **)&data) != 0) 16 | /* Return that a frame could not be retrieved. */ 17 | return -1; 18 | else { 19 | /* Store the number of the available frame. */ 20 | frame_number = *data; 21 | free(data); 22 | } 23 | } 24 | 25 | return frame_number; 26 | } 27 | 28 | /* free_frame */ 29 | int free_frame(List *frames, int frame_number) 30 | { 31 | int *data; 32 | 33 | /* Allocate storage for the frame number. */ 34 | if ((data = (int *)malloc(sizeof(int))) == NULL) 35 | return -1; 36 | 37 | /* Put the frame back in the list of available frames. */ 38 | *data = frame_number; 39 | 40 | if (list_ins_next(frames, NULL, data) != 0) 41 | return -1; 42 | 43 | return 0; 44 | } 45 | -------------------------------------------------------------------------------- /algorithm/ex5/list.h: -------------------------------------------------------------------------------- 1 | #ifndef LIST_H 2 | #define LIST_H 3 | 4 | #include 5 | 6 | /* Define a structure for linked list elements. */ 7 | typedef struct ListElmt_ 8 | { 9 | void *data; 10 | struct ListElmt_ *next; 11 | } ListElmt; 12 | 13 | /* Define a structure for linked lists. */ 14 | typedef struct List_ 15 | { 16 | int size; 17 | int (*match)(const void *key1, const void *key2); 18 | void (*destroy)(void *data); 19 | ListElmt *head; 20 | ListElmt *tail; 21 | } List; 22 | 23 | /* Public Interface */ 24 | void list_init(List *list, void (*destroy)(void *data)); 25 | void list_destroy(List *list); 26 | int list_ins_next(List *list, ListElmt *element, const void *data); 27 | int list_rem_next(List *list, ListElmt *element, void **data); 28 | 29 | #define list_size(list) ((list)->size) 30 | 31 | #define list_head(list) ((list)->head) 32 | #define list_tail(list) ((list)->tail) 33 | #define list_is_head(list, element) ((element) == (list)->head ? 1 : 0) 34 | #define list_is_tail(element) ((element)->next == NULL ? 1 : 0) 35 | #define list_data(element) ((element)->data) 36 | #define list_next(element) ((element)->next) 37 | 38 | #endif 39 | -------------------------------------------------------------------------------- /algorithm/ex5/page.c: -------------------------------------------------------------------------------- 1 | #include "clist.h" 2 | #include "page.h" 3 | 4 | /* replace_pages */ 5 | int replace_page(CListElmt **current) 6 | { 7 | /* Circle through the list of pages until one is found to replace. */ 8 | while (((Page *)(*current)->data)->reference != 0) 9 | { 10 | ((Page *)(*current)->data)->reference = 0; 11 | *current = clist_next(*current); 12 | } 13 | 14 | return ((Page *)(*current)->data)->number; 15 | } 16 | -------------------------------------------------------------------------------- /algorithm/ex5/page.h: -------------------------------------------------------------------------------- 1 | #ifndef PAGE_H 2 | #define PAGE_H 3 | #include "clist.h" 4 | 5 | /* Define s structure for information about pages. */ 6 | typedef struct Page_ 7 | { 8 | int number; 9 | int reference; 10 | }Page; 11 | 12 | /* Public Interface */ 13 | int replace_page(CListElmt **current); 14 | 15 | #endif -------------------------------------------------------------------------------- /algorithm/ex6/events.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include "event.h" 4 | #include "events.h" 5 | #include "queue.h" 6 | 7 | /* receive_event */ 8 | int receive_event(Queue *events, const Event *event) 9 | { 10 | Event *new_event; 11 | 12 | /* Allocate space for the event. */ 13 | if ((new_event = (Event *)malloc(sizeof(Event))) == NULL) 14 | return -1; 15 | 16 | /* Make a copy of the event and enqueue it. */ 17 | memcpy(new_event, event, sizeof(Event)); 18 | 19 | if (queue_enqueue(events, new_event) != 0) 20 | return -1; 21 | 22 | return 0; 23 | } 24 | 25 | 26 | /* process_event */ 27 | int process_event(Queue *events, int (*dispatch)(Event *event)) 28 | { 29 | Event *event; 30 | 31 | if (queue_size(events) == 0) 32 | /* Return that there sre no events to dispatch. */ 33 | return -1; 34 | else 35 | { 36 | if (queue_dequeue(events, (void **)&event) != 0) 37 | /* Return that an event could not be retrieved. */ 38 | return -1; 39 | else 40 | { 41 | /* Call a user-defined function to dispatch the event. */ 42 | dispatch(event); 43 | free(event); 44 | } 45 | } 46 | return 0; 47 | } 48 | -------------------------------------------------------------------------------- /algorithm/ex6/list.h: -------------------------------------------------------------------------------- 1 | #ifndef LIST_H 2 | #define LIST_H 3 | 4 | #include 5 | 6 | /* Define a structure for linked list elements. */ 7 | typedef struct ListElmt_ 8 | { 9 | void *data; 10 | struct ListElmt_ *next; 11 | } ListElmt; 12 | 13 | /* Define a structure for linked lists. */ 14 | typedef struct List_ 15 | { 16 | int size; 17 | int (*match)(const void *key1, const void *key2); 18 | void (*destroy)(void *data); 19 | ListElmt *head; 20 | ListElmt *tail; 21 | } List; 22 | 23 | /* Public Interface */ 24 | void list_init(List *list, void (*destroy)(void *data)); 25 | void list_destroy(List *list); 26 | int list_ins_next(List *list, ListElmt *element, const void *data); 27 | int list_rem_next(List *list, ListElmt *element, void **data); 28 | 29 | #define list_size(list) ((list)->size) 30 | 31 | #define list_head(list) ((list)->head) 32 | #define list_tail(list) ((list)->tail) 33 | #define list_is_head(list, element) ((element) == (list)->head ? 1 : 0) 34 | #define list_is_tail(element) ((element)->next == NULL ? 1 : 0) 35 | #define list_data(element) ((element)->data) 36 | #define list_next(element) ((element)->next) 37 | 38 | #endif 39 | -------------------------------------------------------------------------------- /algorithm/ex6/queue.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | #include "list.h" 4 | #include "queue.h" 5 | 6 | /* queue_enqueue */ 7 | int queue_enqueue(Queue *queue, const void *data) 8 | { 9 | /*Enqueue the data */ 10 | return list_ins_next(queue, list_tail(queue), data); 11 | } 12 | 13 | /* queue_dequeue */ 14 | int queue_dequeue(Queue *queue, void **data) 15 | { 16 | /* Dequeue the data */ 17 | return list_rem_next(queue, NULL, data); 18 | } 19 | -------------------------------------------------------------------------------- /algorithm/ex6/queue.h: -------------------------------------------------------------------------------- 1 | #ifndef QUEUE_H 2 | #define QUEUE_H 3 | 4 | #include 5 | 6 | #include "list.h" 7 | 8 | /* Implement queues as linked lists. */ 9 | typedef List Queue; 10 | 11 | /* Public Interface */ 12 | #define queue_init list_init 13 | #define queue_destroy list_destroy 14 | 15 | int queue_enqueue(Queue *queue, const void *data); 16 | 17 | int queue_dequeue(Queue *queue, void **data); 18 | 19 | #define queue_peek(queue) ((queue)->head == NULL ? NULL : (queue)->head->data) 20 | 21 | #define queue_size list_size 22 | 23 | #endif 24 | -------------------------------------------------------------------------------- /algorithm/ex6/stack.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | #include "list.h" 4 | #include "stack.h" 5 | 6 | /* stack_push */ 7 | int stack_push(Stack *stack, const void *data) 8 | { 9 | /*Push the data onto the stack. */ 10 | return list_ins_next(stack, NULL, data); 11 | } 12 | 13 | /* stack_pop */ 14 | int stack_pop(Stack *stack, void **data) 15 | { 16 | /* Pop the data off the stack. */ 17 | return list_rem_next(stack, NULL, data); 18 | } 19 | -------------------------------------------------------------------------------- /algorithm/ex6/stack.h: -------------------------------------------------------------------------------- 1 | #ifndef STACK_H 2 | #define STACK_H 3 | 4 | #include 5 | #include "list.h" 6 | 7 | /* Implement stacks as linked lists. */ 8 | typedef List Stack; 9 | 10 | /* Public Interface */ 11 | #define stack_init list_init 12 | 13 | #define stack_destroy list_destroy 14 | 15 | int stack_push(Stack *stack, const void *data); 16 | 17 | int stack_pop(Stack *stack, void **data); 18 | 19 | #define stack_peek(stack) ((stack)->head == NULL ? NULL : (stack)->head->data) 20 | 21 | #define stack_size list_size 22 | 23 | #endif 24 | -------------------------------------------------------------------------------- /algorithm/ex7/cover.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include "cover.h" 3 | #include "list.h" 4 | #include "set.h" 5 | 6 | /* cover */ 7 | int cover(Set *members, Set *subsets, Set *covering) 8 | { 9 | Set intersection; 10 | KSet *subset; 11 | ListElmt *member, *max_member; 12 | void *data; 13 | int max_size; 14 | 15 | /* Initialize the covering. */ 16 | set_init(covering, subsets->match, NULL); 17 | 18 | /* Continue while there are noncovered members and candidate subsets. */ 19 | while (set_size(members) > 0 && set_size(subsets) > 0) 20 | { 21 | /* Find the subset that covers the most members. */ 22 | max_size = 0; 23 | for (member = list_head(subsets); member != NULL; member = list_next(member)) 24 | { 25 | if (set_intersection(&intersection, &((KSet *)list_data(member))->set, members) != 0) 26 | { 27 | return -1; 28 | } 29 | if (set_size(&intersection) > max_size) 30 | { 31 | max_member = member; 32 | max_size = set_size(&intersection); 33 | } 34 | 35 | set_destroy(&intersection); 36 | } 37 | 38 | /* A covering is not possible if there was no intersection. */ 39 | if (max_size == 0) 40 | return 1; 41 | 42 | /* Insert the selected subset into the covering. */ 43 | subset = (KSet *)list_data(max_member); 44 | 45 | if (set_insert(covering, subset) != 0) 46 | return -1; 47 | 48 | /* Remove each covered member from the set of noncovered members. */ 49 | for (member = list_head(&((KSet *)list_data(max_member))->set); member != NULL; member = list_next(member)) 50 | { 51 | data = list_data(member); 52 | if (set_remove(members, (void**)&data) == 0 && members->destroy != NULL) 53 | members->destroy(data); 54 | } 55 | 56 | /* Remove the subset from the set of candidate subsets. */ 57 | if (set_remove(subsets, (void **)&subset) != 0) 58 | return -1; 59 | } 60 | 61 | /* No covering is possible if there are still noncovered members. */ 62 | if (set_size(members) > 0) 63 | return -1; 64 | 65 | return 0; 66 | } 67 | -------------------------------------------------------------------------------- /algorithm/ex7/cover.h: -------------------------------------------------------------------------------- 1 | #ifndef COVER_H 2 | #define COVER_H 3 | #include "set.h" 4 | 5 | /* Define a structure for subsets identified by a key. */ 6 | typedef struct KSet_ 7 | { 8 | void *key; 9 | Set set; 10 | }KSet; 11 | 12 | 13 | /* Public Interface */ 14 | int cover(Set *members, Set *subsets, Set *covering); 15 | 16 | #endif 17 | -------------------------------------------------------------------------------- /algorithm/ex7/list.h: -------------------------------------------------------------------------------- 1 | #ifndef LIST_H 2 | #define LIST_H 3 | 4 | #include 5 | 6 | /* Define a structure for linked list elements. */ 7 | typedef struct ListElmt_ 8 | { 9 | void *data; 10 | struct ListElmt_ *next; 11 | } ListElmt; 12 | 13 | /* Define a structure for linked lists. */ 14 | typedef struct List_ 15 | { 16 | int size; 17 | int (*match)(const void *key1, const void *key2); 18 | void (*destroy)(void *data); 19 | ListElmt *head; 20 | ListElmt *tail; 21 | } List; 22 | 23 | /* Public Interface */ 24 | void list_init(List *list, void (*destroy)(void *data)); 25 | void list_destroy(List *list); 26 | int list_ins_next(List *list, ListElmt *element, const void *data); 27 | int list_rem_next(List *list, ListElmt *element, void **data); 28 | 29 | #define list_size(list) ((list)->size) 30 | 31 | #define list_head(list) ((list)->head) 32 | #define list_tail(list) ((list)->tail) 33 | #define list_is_head(list, element) ((element) == (list)->head ? 1 : 0) 34 | #define list_is_tail(element) ((element)->next == NULL ? 1 : 0) 35 | #define list_data(element) ((element)->data) 36 | #define list_next(element) ((element)->next) 37 | 38 | #endif 39 | -------------------------------------------------------------------------------- /algorithm/ex7/set.h: -------------------------------------------------------------------------------- 1 | #ifndef SET_H 2 | #define SET_H 3 | 4 | #include 5 | #include "list.h" 6 | 7 | /* Implement sets as linked llists. */ 8 | 9 | typedef List Set; 10 | 11 | /* Public Interface */ 12 | 13 | void set_init(Set *set, int (*match)(const void *key1, const void *key2), void (*destroy)(void *data)); 14 | #define set_destroy list_destroy 15 | int set_insert(Set *set, const void *data); 16 | int set_remove(Set *set, void **data); 17 | int set_union(Set *setu, const Set *set1, const Set *set2); 18 | int set_intersection(Set *seti, const Set *set1, const Set *set2); 19 | int set_difference(Set *setd, const Set *set1, const Set *set2); 20 | int set_is_member(const Set *set, const void *data); 21 | int set_is_subset(const Set *set1, const Set *set2); 22 | int set_is_equal(const Set *set1, const Set *set2); 23 | #define set_size(set) ((set)->size) 24 | 25 | #endif -------------------------------------------------------------------------------- /algorithm/ex8/chtbl.h: -------------------------------------------------------------------------------- 1 | #ifndef CHTBL_H 2 | #define CHTBL_H 3 | 4 | #include 5 | 6 | #include "list.h" 7 | 8 | /* Define a structure for chained hash tables. */ 9 | typedef struct CHTbl_ 10 | { 11 | int buckets; 12 | int (*h)(const void *key); 13 | int (*match)(const void *key1, const void *key2); 14 | void (*destroy)(void *data); 15 | int size; 16 | List *table; 17 | } CHTbl; 18 | 19 | /* Public Interface */ 20 | int chtbl_init(CHTbl *htbl, int buckets, int(*h)(const void *key), int (*match)(const void *key1, const void *key2), void (*destroy)(void *data)); 21 | 22 | void chtbl_destroy(CHTbl *htbl); 23 | 24 | int chtbl_insert(CHTbl *htbl, const void *data); 25 | 26 | int chtbl_remove(CHTbl *htbl, void **data); 27 | 28 | int chtbl_lookup(const CHTbl *htbl, void **data); 29 | 30 | #define chtbl_size(htbl) ((htbl)->size) 31 | 32 | #endif -------------------------------------------------------------------------------- /algorithm/ex8/hashpjw.c: -------------------------------------------------------------------------------- 1 | #include "hashpjw.h" 2 | 3 | usigned int hashpjw(const void *key) 4 | { 5 | const char *ptr; 6 | unsigned int val; 7 | 8 | /* Hash the key by performing a number of bit operations on it. */ 9 | val = 0; 10 | ptr = key; 11 | 12 | while (*ptr != '\0') 13 | { 14 | unsigned int tmp; 15 | val = (val << 4) + (*ptr); 16 | 17 | if (tmp = (val & 0xf0000000)) 18 | { 19 | val = val ^ (tmp >> 24); 20 | val = val ^ tmp; 21 | } 22 | 23 | ptr++; 24 | } 25 | 26 | /* In practice, replace PRIME_TBLSIZ with the actual table size. */ 27 | return val % PRIME_TBLSIZ; 28 | } -------------------------------------------------------------------------------- /algorithm/ex8/list.h: -------------------------------------------------------------------------------- 1 | #ifndef LIST_H 2 | #define LIST_H 3 | 4 | #include 5 | 6 | /* Define a structure for linked list elements. */ 7 | typedef struct ListElmt_ 8 | { 9 | void *data; 10 | struct ListElmt_ *next; 11 | } ListElmt; 12 | 13 | /* Define a structure for linked lists. */ 14 | typedef struct List_ 15 | { 16 | int size; 17 | int (*match)(const void *key1, const void *key2); 18 | void (*destroy)(void *data); 19 | ListElmt *head; 20 | ListElmt *tail; 21 | } List; 22 | 23 | /* Public Interface */ 24 | void list_init(List *list, void (*destroy)(void *data)); 25 | void list_destroy(List *list); 26 | int list_ins_next(List *list, ListElmt *element, const void *data); 27 | int list_rem_next(List *list, ListElmt *element, void **data); 28 | 29 | #define list_size(list) ((list)->size) 30 | 31 | #define list_head(list) ((list)->head) 32 | #define list_tail(list) ((list)->tail) 33 | #define list_is_head(list, element) ((element) == (list)->head ? 1 : 0) 34 | #define list_is_tail(element) ((element)->next == NULL ? 1 : 0) 35 | #define list_data(element) ((element)->data) 36 | #define list_next(element) ((element)->next) 37 | 38 | #endif 39 | -------------------------------------------------------------------------------- /anagram/README: -------------------------------------------------------------------------------- 1 | 2012-08-07 2 | 转移至anagram文件夹。 3 | 4 | 2012-06-02 5 | 上传了变位词迷游戏,找出一本字典里所有的变位词。 6 | 7 | -------------------------------------------------------------------------------- /anagram/change.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | int main() 4 | { 5 | int c; 6 | while((c = getchar()) != EOF) { 7 | if(c >= 'A' && c <= 'Z') 8 | c += 32; 9 | printf("%c", c); 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /anagram/sign.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #define WORDMAX 50 4 | 5 | int charcomp(char *x, char *y) 6 | { 7 | return *x - *y; 8 | } 9 | 10 | int main() 11 | { 12 | char word[WORDMAX], sign[WORDMAX]; 13 | while (scanf("%s", word) != EOF) { 14 | strcpy(sign, word); 15 | qsort(sign, strlen(sign), sizeof(char), charcomp); 16 | printf("%s %s\n", sign, word); 17 | } 18 | return 0; 19 | } 20 | -------------------------------------------------------------------------------- /anagram/squash.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #define WORDMAX 50 4 | 5 | int main() 6 | { 7 | char word[WORDMAX], sig[WORDMAX], oldsig[WORDMAX]; 8 | int linenum = 0; 9 | strcpy(oldsig, ""); 10 | while (scanf("%s %s", sig, word) != EOF) { 11 | if(strcmp(oldsig, sig) != 0 && linenum > 0) 12 | printf("\n"); 13 | strcpy(oldsig, sig); 14 | linenum++; 15 | printf("%s\t\t", word); 16 | } 17 | printf("\n"); 18 | return 0; 19 | } 20 | -------------------------------------------------------------------------------- /cppdemo/Blob.h: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/cforth/codefarm/cabd0ec1e9fb2a2aa582682b1a4016378e8515dc/cppdemo/Blob.h -------------------------------------------------------------------------------- /cppdemo/Sales_data_class.h: -------------------------------------------------------------------------------- 1 | #ifndef SALES_DATA_H 2 | #define SALES_DATA_H 3 | /* 4 | * 书籍销售信息类 5 | */ 6 | class Sales_data { 7 | //友元声明 8 | friend std::istream &read(std::istream &, Sales_data &); 9 | friend std::ostream &print(std::ostream &os, const Sales_data &); 10 | friend Sales_data add(const Sales_data &, const Sales_data &); 11 | friend bool compareIsbn(const Sales_data &lhs, const Sales_data &rhs); 12 | 13 | public: 14 | Sales_data() = default; //默认构造函数 15 | Sales_data(const std::string &s, unsigned n, double p) : bookNo(s), units_sold(n), revenue(p*n) { //初始化成员,成员函数为空 16 | } 17 | Sales_data(const std::string &s) : bookNo(s) { 18 | } 19 | Sales_data(std::istream &); // 构造函数声明,从输入流初始化成员 20 | Sales_data(const Sales_data&); //拷贝构造函数 21 | 22 | std::string isbn() const { return bookNo; } 23 | Sales_data &combine(const Sales_data &); 24 | double avg_price() const { //隐式内联函数 25 | return units_sold ? revenue/units_sold : 0; 26 | } 27 | 28 | private: 29 | std::string bookNo; //书籍的编号 30 | unsigned units_sold = 0; //书籍销售数量 31 | double revenue = 0.0; //书籍销售总价格 32 | }; 33 | 34 | /* 35 | * Sales_data的拷贝构造函数 36 | */ 37 | Sales_data::Sales_data(const Sales_data &orig): 38 | bookNo(orig.bookNo), 39 | units_sold(orig.units_sold), 40 | revenue(orig.revenue) 41 | { std::cout << "I'm copying! BookNo: " << orig.bookNo << std::endl;} 42 | 43 | /* 44 | * Sales_data类的成员函数实现 45 | */ 46 | Sales_data &Sales_data::combine(const Sales_data &rhs) { 47 | units_sold += rhs.units_sold; 48 | revenue += rhs.revenue; 49 | return *this; 50 | } 51 | 52 | /* 53 | * Sales_data类的接口函数声明,非成员函数,在类中声明为友元 54 | */ 55 | std::istream &read(std::istream &, Sales_data &); 56 | std::ostream &print(std::ostream &os, const Sales_data &); 57 | Sales_data add(const Sales_data &, const Sales_data &); 58 | bool compareIsbn(const Sales_data &lhs, const Sales_data &rhs); 59 | 60 | /* 61 | * Sales_data类的接口函数实现 62 | */ 63 | std::istream &read(std::istream &is, Sales_data &item) { 64 | double price = 0; 65 | is >> item.bookNo >> item.units_sold >> price; 66 | item.revenue = price * item.units_sold; 67 | return is; 68 | } 69 | 70 | std::ostream &print(std::ostream &os, const Sales_data &item) { 71 | os << item.isbn() << " " 72 | << item.units_sold << " " 73 | << item.revenue << " " 74 | << item.avg_price(); 75 | return os; 76 | } 77 | 78 | Sales_data add(const Sales_data &lhs, const Sales_data &rhs) { 79 | Sales_data sum = lhs; 80 | sum.combine(rhs); 81 | return sum; 82 | } 83 | 84 | /* 85 | * 提供此类作为关联容器关键字类型时所需要的小于号比较符 86 | */ 87 | bool compareIsbn(const Sales_data &lhs, const Sales_data &rhs) { 88 | return lhs.isbn() < rhs.isbn(); 89 | } 90 | #endif 91 | -------------------------------------------------------------------------------- /cppdemo/String.h: -------------------------------------------------------------------------------- 1 | #ifndef STRING_H 2 | #define STRING_H 3 | #include 4 | #include 5 | #include 6 | #include 7 | #include 8 | #include 9 | 10 | class String { 11 | friend String operator+(const String&, const String&); 12 | friend String add(const String&, const String&); 13 | friend std::ostream &operator<<(std::ostream&, const String&); 14 | friend std::ostream &print(std::ostream&, const String&); 15 | 16 | public: 17 | String() = default; 18 | String(const char *cp) : 19 | sz(std::strlen(cp)), p(a.allocate(sz)) 20 | { std::uninitialized_copy(cp, cp + sz, p); } 21 | String(const String &s) : 22 | sz(s.sz), p(a.allocate(s.sz)) 23 | { std::uninitialized_copy(s.p, s.p + sz, p); } 24 | String(String &&s) noexcept : 25 | sz(s.size()), p(s.p) 26 | { s.p = 0; s.sz = 0; } 27 | String(size_t n, char c) : 28 | sz(n), p(a.allocate(n)) 29 | { std::uninitialized_fill_n(p, sz, c); } 30 | String &operator=(const String &); 31 | String &operator=(String &&) noexcept; 32 | 33 | ~String() noexcept { if (p) a.deallocate(p, sz); } 34 | 35 | String &operator=(const char*); 36 | String &operator=(char); 37 | String &operator=(std::initializer_list); 38 | 39 | const char *begin() { return p; } 40 | const char *begin() const { return p; } 41 | const char *end() { return p + sz; } 42 | const char *end() const { return p + sz; } 43 | 44 | size_t size() const { return sz; } 45 | void swap(String &s) { 46 | auto tmp = p; 47 | p = s.p; 48 | s.p = tmp; 49 | auto cnt = sz; 50 | sz = s.sz; 51 | s.sz = cnt; 52 | } 53 | 54 | private: 55 | std::size_t sz = 0; 56 | char *p = nullptr; 57 | static std::allocator a; 58 | }; 59 | 60 | String make_plural(size_t ctr, const String &, const String &); 61 | 62 | inline void swap(String &s1, String &s2) { 63 | s1.swap(s2); 64 | } 65 | 66 | #endif 67 | -------------------------------------------------------------------------------- /cppdemo/book_sales: -------------------------------------------------------------------------------- 1 | 0-201-70353-X 4 24.99 2 | 0-201-82470-1 4 45.39 3 | 0-201-88954-4 2 15.00 4 | 0-201-88954-4 5 12.00 5 | 0-201-88954-4 7 12.00 6 | 0-201-88954-4 2 12.00 7 | 0-399-82477-1 2 45.39 8 | 0-399-82477-1 3 45.39 9 | 0-201-78345-X 3 20.00 10 | 0-201-78345-X 2 25.00 11 | -------------------------------------------------------------------------------- /cppdemo/data: -------------------------------------------------------------------------------- 1 | 0-201-70353-X 4 99.96 24.99 2 | 0-201-82470-1 4 181.56 45.39 3 | 0-201-88954-4 16 198 12.375 4 | 0-399-82477-1 5 226.95 45.39 5 | 0-201-78345-X 5 110 22 6 | -------------------------------------------------------------------------------- /cppdemo/test_13_16.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | 5 | class Employee { 6 | public: 7 | Employee(const string &s = string()): 8 | name(new string(s)), 9 | id(++num) { } 10 | 11 | Employee(const Employee& e) : 12 | name(new string(*e.name)), 13 | id(e.id) { 14 | } 15 | 16 | ~Employee() { 17 | delete name; 18 | } 19 | static int num; 20 | string *name; 21 | int id; 22 | 23 | }; 24 | 25 | int Employee::num = 0; 26 | 27 | int main() { 28 | Employee emp1, emp2; 29 | cout << *emp1.name << " " << emp1.id << endl; 30 | cout << *emp2.name << " " << emp2.id << endl; 31 | 32 | Employee emp3("cf"), emp4("hk"); 33 | cout << *emp3.name << " " << emp3.id << endl; 34 | cout << *emp4.name << " " << emp4.id << endl; 35 | 36 | Employee emp5(emp3); 37 | cout << *emp5.name << " " << emp5.id << endl; 38 | *emp3.name = string("xxx"); 39 | cout << *emp5.name << " " << emp5.id << endl; 40 | cout << *emp3.name << " " << emp3.id << endl; 41 | return 0; 42 | } 43 | -------------------------------------------------------------------------------- /cppdemo/test_13_27.cpp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/cforth/codefarm/cabd0ec1e9fb2a2aa582682b1a4016378e8515dc/cppdemo/test_13_27.cpp -------------------------------------------------------------------------------- /cppdemo/test_13_30.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using std::cout; 4 | using std::endl; 5 | 6 | class HasPtr { 7 | friend void swap(HasPtr&, HasPtr&); 8 | public: 9 | //默认构造函数 10 | HasPtr(const std::string &s = std::string()) : 11 | ps(new std::string(s)), i(0) { } 12 | 13 | //拷贝构造函数 14 | HasPtr(const HasPtr &orig) : 15 | ps(new std::string(*orig.ps)), 16 | i(orig.i) { 17 | cout << "copy: "; 18 | print(cout) << endl; 19 | } 20 | 21 | //赋值运算符 22 | HasPtr& operator=(HasPtr rhs) { 23 | swap(*this, rhs); 24 | return *this; 25 | } 26 | 27 | 28 | 29 | //析构函数 30 | ~HasPtr() { 31 | cout << "delete: "; 32 | print(cout) << endl; 33 | delete ps; 34 | } 35 | 36 | //print obj status 37 | std::ostream& print(std::ostream &out) { 38 | out << "ps: " << *ps 39 | << " i: " << i; 40 | return out; 41 | } 42 | 43 | private: 44 | std::string *ps; 45 | int i; 46 | }; 47 | 48 | //swap函数 49 | inline 50 | void swap(HasPtr &lhs, HasPtr &rhs) { 51 | using std::swap; 52 | cout << "swap!!!" << endl; 53 | swap(lhs.ps, rhs.ps); 54 | swap(lhs.i, rhs.i); 55 | } 56 | 57 | int main() { 58 | HasPtr p1("111"); 59 | HasPtr p2("222"); 60 | cout << "===========" < 3 | #include 4 | #include 5 | using std::string; 6 | using std::allocator; 7 | using std::cout; 8 | using std::endl; 9 | 10 | allocator StrVec::alloc; 11 | 12 | int main() { 13 | StrVec sv; 14 | sv.push_back("1235"); 15 | sv.push_back("sdfasdf0"); 16 | for(auto p = sv.begin(); p != sv.end(); ++p) { 17 | cout << *p << endl; 18 | } 19 | 20 | StrVec sv2(sv); 21 | for(auto p = sv2.begin(); p != sv2.end(); ++p) { 22 | cout << *p << endl; 23 | } 24 | 25 | return 0; 26 | } 27 | 28 | -------------------------------------------------------------------------------- /cppdemo/test_13_39.h: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/cforth/codefarm/cabd0ec1e9fb2a2aa582682b1a4016378e8515dc/cppdemo/test_13_39.h -------------------------------------------------------------------------------- /cppdemo/test_13_40.cpp: -------------------------------------------------------------------------------- 1 | #include "test_13_40.h" 2 | #include 3 | #include 4 | #include 5 | using std::string; 6 | using std::allocator; 7 | using std::cout; 8 | using std::endl; 9 | 10 | allocator StrVec::alloc; 11 | 12 | int main() { 13 | StrVec sv({"sadf","sdfsadfasf","sadfsadf"}); 14 | for(auto p = sv.begin(); p != sv.end(); ++p) { 15 | cout << *p << endl; 16 | } 17 | 18 | StrVec sv2(sv); 19 | for(auto p = sv2.begin(); p != sv2.end(); ++p) { 20 | cout << *p << endl; 21 | } 22 | 23 | return 0; 24 | } 25 | 26 | -------------------------------------------------------------------------------- /cppdemo/test_13_40.h: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/cforth/codefarm/cabd0ec1e9fb2a2aa582682b1a4016378e8515dc/cppdemo/test_13_40.h -------------------------------------------------------------------------------- /cppdemo/test_13_43.cpp: -------------------------------------------------------------------------------- 1 | #include "test_13_43.h" 2 | #include 3 | #include 4 | #include 5 | using std::string; 6 | using std::allocator; 7 | using std::cout; 8 | using std::endl; 9 | 10 | allocator StrVec::alloc; 11 | 12 | int main() { 13 | StrVec sv({"sadf","sdfsadfasf","sadfsadf"}); 14 | for(auto p = sv.begin(); p != sv.end(); ++p) { 15 | cout << *p << endl; 16 | } 17 | 18 | StrVec sv2(sv); 19 | for(auto p = sv2.begin(); p != sv2.end(); ++p) { 20 | cout << *p << endl; 21 | } 22 | 23 | return 0; 24 | } 25 | 26 | -------------------------------------------------------------------------------- /cppdemo/test_13_43.h: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/cforth/codefarm/cabd0ec1e9fb2a2aa582682b1a4016378e8515dc/cppdemo/test_13_43.h -------------------------------------------------------------------------------- /cppdemo/test_13_44.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include "String.h" 3 | using std::cout; 4 | using std::cin; 5 | using std::endl; 6 | 7 | int main() { 8 | String xxx = "11111"; 9 | cout << xxx << endl; 10 | return 0; 11 | } 12 | -------------------------------------------------------------------------------- /cppdemo/test_HadPtr.cpp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/cforth/codefarm/cabd0ec1e9fb2a2aa582682b1a4016378e8515dc/cppdemo/test_HadPtr.cpp -------------------------------------------------------------------------------- /cppdemo/test_blob.cpp: -------------------------------------------------------------------------------- 1 | #include "Blob.h" 2 | #include 3 | #include 4 | using std::cout; 5 | using std::endl; 6 | using std::string; 7 | 8 | int main() { 9 | Blob ia; 10 | Blob ia2 = {0,1,2,3,4,5}; 11 | for(int x = 0; x < ia2.size(); ++x) 12 | cout << ia2[x] << " "; 13 | cout << endl; 14 | 15 | Blob ia3 = {"Hello", "World", "!!"}; 16 | for(int x = 0; x < ia3.size(); ++x) 17 | cout << ia3[x] << " "; 18 | cout << endl; 19 | } 20 | -------------------------------------------------------------------------------- /cppdemo/test_sales_data.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include "Sales_data_class.h" 5 | using namespace std; 6 | int main(int argc, char* argv[]) { 7 | ifstream input(argv[1]); 8 | ofstream output(argv[2], ofstream::out | ofstream::app); 9 | Sales_data total; 10 | if(read(input, total)) { 11 | Sales_data trans; 12 | while (read(input, trans)) { 13 | if(total.isbn() == trans.isbn()) 14 | total = add(total, trans); 15 | else { 16 | print(output, total) << endl; 17 | total = trans; 18 | } 19 | } 20 | Sales_data xxx = total; //测试拷贝初始化 21 | print(output, xxx) << endl; 22 | } else { 23 | cerr << "No data?!" << endl; 24 | return -1; 25 | } 26 | return 0; 27 | } 28 | -------------------------------------------------------------------------------- /hanoi_game/README: -------------------------------------------------------------------------------- 1 | 2016-10-09 2 | hanoi.cpp是用C++写的汉诺塔游戏,符合C++11标准。 3 | 4 | 2013-03-07 5 | 为hanoi_2013.scm增加了算法模块,自动运行汉诺塔游戏 6 | 上传了test_hanoi.sh脚本,用于测试汉诺塔游戏hanoi_2013.scm 7 | 8 | 2013-03-06 9 | 上传了scheme版的汉诺塔游戏hanoi_2013.scm 10 | 目前只实现了汉诺塔游戏的核心部分,只是个雏形。 11 | 12 | 2013-02-26 13 | 修复了hanoi_new层数9时无法移动的BUG。 14 | 15 | 上传了hanoi_auto.c: 16 | 编译执行,首先接受汉诺塔游戏的层数,再接受移塔步骤,操作方法见hanoi_new说明。 17 | 18 | 上传了hanoi_alg.scm: 19 | 使用scheme编写,主要是接受汉诺塔游戏的层数,输出移塔步骤,通过管道给hanoi_auto.exe。 20 | 21 | hanoi_auto与hanoi_alg配合使用,可自动完成汉诺塔游戏。 22 | 操作步骤如下: 23 | ./hanoi_alg.scm | ./hanoi_auto.exe 24 | 5 //输入要完成的hanoi层数 25 | 试一下吧! 26 | 27 | 2012-09-05 28 | 新版汉诺塔游戏hanoi_new已完成。 29 | 新增加的功能有: 30 | 完成一个级别后自动晋级至下一级别,选关模式,还有记录步数的功能。 31 | 操作方法: 32 | ‘a’ 左移 33 | ‘d’ 右移 34 | ‘s’ 拿起/放下 35 | ‘>’ 跳至下一关,直至第九关退出。 36 | 37 | 2012-09-03 38 | 上传了新版的汉诺塔游戏hanoi_new 39 | 正在编写代码中。 40 | 41 | 2012-08-07 42 | 转移至hanoi_game文件夹。 43 | 44 | 2012-07-25 45 | 增加了hanoi_tower的完成度检测。 46 | 完成游戏后自动提示并退出。 47 | 48 | 2012-07-21 49 | 更新了汉诺塔游戏代码,使之能在linux平台上被GCC成功编译。 50 | 51 | 2012-05-10 52 | 上传了汉诺塔游戏,A是左移,D是右移,S是拿起或放下。只能在windows系统上运行。 53 | -------------------------------------------------------------------------------- /hanoi_game/hanoi.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | using namespace std; 6 | 7 | ostream& print(ostream &out, map> &hanoi, int depth) { 8 | for(int i = depth - 1; i >= 0; --i) { 9 | for(auto h : hanoi) { 10 | if((int)(h.second.size()) > i) { 11 | out << h.second[i] ; 12 | } else { 13 | out << " "; 14 | } 15 | out << "\t"; 16 | } 17 | out << endl; 18 | } 19 | 20 | for(auto h : hanoi) { 21 | out << h.first << "\t"; 22 | } 23 | out << endl; 24 | 25 | return out; 26 | } 27 | 28 | istream& read_cmd(istream &in, string &from, string &to) { 29 | cout << "Your move:"; 30 | in >> from >> to ; 31 | return in; 32 | } 33 | 34 | void move(vector &a, vector &b) { 35 | if(!a.empty()) { 36 | if(b.empty() || a.back() < b.back()) { 37 | b.push_back(a.back()); 38 | a.pop_back(); 39 | } 40 | } 41 | } 42 | 43 | bool check(vector &c, int num) { 44 | if(!c.empty() && c.size() == num) { 45 | cout << "You Win!!!" << endl; 46 | return true; 47 | } 48 | return false; 49 | } 50 | 51 | int main() { 52 | map> hanoi = {{"a", {3,2,1}}, {"b", {}}, {"c", {}}}; 53 | int depth = 3; 54 | print(cout, hanoi, depth) << endl; 55 | 56 | int win_num = hanoi["a"][0]; 57 | string from, to; 58 | while(read_cmd(cin, from, to)) { 59 | if(hanoi.count(from) != 0 && hanoi.count(to) != 0) { 60 | move(hanoi[from], hanoi[to]); 61 | print(cout, hanoi, depth) << endl; 62 | if (check(hanoi["c"], win_num)) return 0; 63 | } else { 64 | cout << "Wrong move!!!" << endl; 65 | } 66 | cin.clear(); 67 | } 68 | return 0; 69 | } 70 | -------------------------------------------------------------------------------- /hanoi_game/hanoi_alg.scm: -------------------------------------------------------------------------------- 1 | #!/bin/guile -s 2 | !# 3 | 4 | ;递归版的hanoi塔算法 5 | (define (dohanoi n to from using) 6 | (if (> n 0) 7 | (begin 8 | (dohanoi (- n 1) using from to) 9 | (display "move ") 10 | (display from) 11 | (display " --> ") 12 | (display to) 13 | (newline) 14 | (dohanoi (- n 1) to using from) 15 | #t) 16 | #f)) 17 | 18 | (define (hanoi n) 19 | (dohanoi n 3 1 2)) 20 | 21 | 22 | ;运行hanoi_alg.scm,输入要求解的汉诺塔层数,摁回车执行。 23 | ;hanoi_alg.scm将输出汉诺塔游戏移塔步骤,并将层数与移塔步骤通过管道输给hanoi_auto程序。 24 | ;hanoi_auto打印出步骤到屏幕。 25 | ;将hanoi算法的结果以序列形式返回,以序列中每两个组成一个操作对,中间步骤,用于后面生成汉诺塔游戏自动移塔动作。 26 | (define (hanoi-list n) 27 | (let ((lst '())) 28 | (define (dohanoi-l n to from using) 29 | (if (> n 0) 30 | (begin 31 | (dohanoi-l (- n 1) using from to) 32 | (if (null? lst) 33 | (set! lst (list from to)) 34 | (set! lst (append lst (list from to)))) 35 | (dohanoi-l (- n 1) to using from) 36 | #t) 37 | #f)) 38 | (begin 39 | (dohanoi-l n 3 1 2) 40 | lst))) 41 | 42 | ;自动运行操作步骤,运行结果通过管道作为hanoi_auto程序的输入,hanoi_auto程序打印出移塔的过程。 43 | (define (auto-move n) 44 | (let ((lst (hanoi-list n))) 45 | (define (change-move lst) 46 | (if (null? (cdr lst)) 47 | '() 48 | (begin 49 | (display "s") 50 | (newline) 51 | (cond ((or (and (= (car lst) 1) (= (cadr lst) 2)) 52 | (and (= (car lst) 2) (= (cadr lst) 3)) 53 | (and (= (car lst) 3) (= (cadr lst) 1))) 54 | (display "d")) 55 | ((or (and (= (car lst) 1) (= (cadr lst) 3)) 56 | (and (= (car lst) 2) (= (cadr lst) 1)) 57 | (and (= (car lst) 3) (= (cadr lst) 2))) 58 | (display "a"))) 59 | (newline) 60 | (change-move (cdr lst))))) 61 | (change-move lst))) 62 | 63 | 64 | 65 | 66 | ;从键盘接收hanoi塔层数level 67 | (define level (read)) 68 | (display level) 69 | (newline) 70 | (auto-move level) 71 | -------------------------------------------------------------------------------- /hanoi_game/makefile: -------------------------------------------------------------------------------- 1 | #运行 make 源代码名字(不带".c"后缀) 2 | #例如 make 8_puzzle 3 | #可以自动编译生成 8_puzzle可执行文件 4 | CC := gcc 5 | CFLAGS := -Wall 6 | clean: 7 | @echo "cleanning project" 8 | -rm -f *.exe 9 | @echo "clean completed" 10 | -------------------------------------------------------------------------------- /hanoi_game/test-hanoi.sh: -------------------------------------------------------------------------------- 1 | #! /bin/bash -f 2 | echo 汉诺塔游戏测试 3 | echo 4 | echo 开始时间: 5 | date 6 | ./hanoi_2013.scm 7 | echo 结束时间: 8 | date 9 | echo 10 | -------------------------------------------------------------------------------- /idea-365/D001_RandomFilesName/RandomFilesName.java: -------------------------------------------------------------------------------- 1 | import java.io.File; 2 | import java.util.ArrayList; 3 | import java.util.List; 4 | import java.util.Random; 5 | 6 | /** 7 | * 从磁盘的指定目录中,获取一个随机的文件名称。 8 | * 例如:在"F:\\temp\\RandomFile"路径下存放了许多图片素材,每次执行获得一个随机的图片的名称路径 9 | */ 10 | public class RandomFilesName { 11 | 12 | public static void main(String[] args) throws Exception{ 13 | String dirPath = "F:\\temp\\RandomFile\\" ; 14 | List list = getFilesName(dirPath); 15 | System.out.println(dirPath + list.get(randomNumber(0, list.size() - 1))); 16 | } 17 | 18 | /** 19 | * 读取文件夹下所有文件名称到一个列表中 20 | * @param dirPath 文件夹路径 21 | * @return list 字符串列表 22 | * @throws Exception 23 | */ 24 | public static List getFilesName(String dirPath) throws Exception { 25 | List list = new ArrayList(); 26 | File[] files = new File(dirPath).listFiles(); 27 | for(File f : files) { 28 | if(!f.isDirectory()) { 29 | list.add(f.getName()); 30 | } 31 | } 32 | return list ; 33 | } 34 | 35 | /** 36 | * 随机数发生器 37 | * @param min 最小的数 38 | * @param max 最大的数 39 | * @return 40 | */ 41 | public static int randomNumber(int min, int max) { 42 | return new Random().nextInt(max)%(max-min+1) + min; 43 | } 44 | } 45 | -------------------------------------------------------------------------------- /idea-365/D002_myForthEval/myForthEval.js: -------------------------------------------------------------------------------- 1 | /** 2 | ** 类似Forth语法的虚拟机函数 3 | ** myForthEval(':XHHWW') 表示定义一个扩展词'X',内容为'HHWW' 4 | ** myForthEval('X') 表示执行这个扩展词'X' 5 | */ 6 | function myForthEval(str){ 7 | i=0; 8 | if(str[i]==':'){ 9 | i++; 10 | eval(str[i] + " = function(){myForthEval('" + str.substring(i+1,str.length) + "');}"); 11 | }else{ 12 | while(i c = new URLClassLoader(urls).loadClass("MyBook"); 20 | System.out.println(c.getName()); 21 | System.out.println(c.newInstance()); 22 | 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /idea-365/D005_DispatcherTools/Company.java: -------------------------------------------------------------------------------- 1 | package com.cfxyz.vo; 2 | 3 | import java.io.Serializable; 4 | 5 | @SuppressWarnings("serial") 6 | public class Company implements Serializable { 7 | private String title; 8 | 9 | public String getTitle() { 10 | return title; 11 | } 12 | 13 | public void setTitle(String title) { 14 | this.title = title; 15 | } 16 | } 17 | 18 | -------------------------------------------------------------------------------- /idea-365/D005_DispatcherTools/Dept.java: -------------------------------------------------------------------------------- 1 | package com.cfxyz.vo; 2 | 3 | import java.io.Serializable; 4 | 5 | @SuppressWarnings("serial") 6 | public class Dept implements Serializable { 7 | private String dname; 8 | private int deptno; 9 | private double sal; 10 | private String[] loc; 11 | private Double[] ids; 12 | public void setIds(Double[] ids) { 13 | this.ids = ids; 14 | } 15 | public Double[] getIds() { 16 | return ids; 17 | } 18 | public void setLoc(String[] loc) { 19 | this.loc = loc; 20 | } 21 | public String[] getLoc() { 22 | return loc; 23 | } 24 | public int getDeptno() { 25 | return deptno; 26 | } 27 | public void setDeptno(int deptno) { 28 | this.deptno = deptno; 29 | } 30 | public double getSal() { 31 | return sal; 32 | } 33 | public void setSal(double sal) { 34 | this.sal = sal; 35 | } 36 | private Company company = new Company(); //必须实例化 37 | public Company getCompany() { 38 | return company; 39 | } 40 | public void setCompany(Company company) { 41 | this.company = company; 42 | } 43 | public void setDname(String dname) { 44 | this.dname = dname; 45 | } 46 | public String getDname() { 47 | return dname; 48 | } 49 | } 50 | 51 | -------------------------------------------------------------------------------- /idea-365/D005_DispatcherTools/Emp.java: -------------------------------------------------------------------------------- 1 | package com.cfxyz.vo; 2 | 3 | import java.io.Serializable; 4 | 5 | @SuppressWarnings("serial") 6 | public class Emp implements Serializable{ 7 | private String ename; 8 | private Double sal; 9 | private Dept dept = new Dept(); 10 | public Dept getDept() { 11 | return dept; 12 | } 13 | public void setDept(Dept dept) { 14 | this.dept = dept; 15 | } 16 | public String getEname() { 17 | return ename; 18 | } 19 | public void setEname(String ename) { 20 | this.ename = ename; 21 | } 22 | public Double getSal() { 23 | return sal; 24 | } 25 | public void setSal(Double sal) { 26 | this.sal = sal; 27 | } 28 | 29 | } 30 | 31 | -------------------------------------------------------------------------------- /idea-365/D005_DispatcherTools/StringUtils.java: -------------------------------------------------------------------------------- 1 | package com.cfxyz.util; 2 | 3 | public class StringUtils { 4 | public static String initcap(String str) { 5 | if(str == null || "".equals(str)) { 6 | return str; 7 | } 8 | if(str.length() == 1) { 9 | return str.toUpperCase(); 10 | }else{ 11 | return str.substring(0,1).toUpperCase() + str.substring(1); 12 | } 13 | } 14 | } 15 | 16 | -------------------------------------------------------------------------------- /idea-365/D005_DispatcherTools/TestDemo.java: -------------------------------------------------------------------------------- 1 | package com.cfxyz.test; 2 | 3 | import java.util.Arrays; 4 | 5 | import com.cfxyz.util.BeanOperate; 6 | import com.cfxyz.vo.Dept; 7 | import com.cfxyz.vo.Emp; 8 | 9 | public class TestDemo { 10 | private Emp emp = new Emp(); 11 | public Emp getEmp() { 12 | return emp; 13 | } 14 | private Dept dept = new Dept(); 15 | public Dept getDept() { 16 | return dept; 17 | } 18 | 19 | public static void main(String[] args) { 20 | { 21 | String attribute = "dept.sal"; //表示的属性,单级属性 22 | String value = "8000.55"; 23 | TestDemo td = new TestDemo(); 24 | //此时就表示设置内容 25 | BeanOperate bo = new BeanOperate(td, attribute, value); 26 | System.out.println("单级属性设置:" + td.getDept().getSal()); 27 | } 28 | System.out.println("================================"); 29 | { 30 | String attribute = "emp.dept.company.title"; //表示的属性,多级属性 31 | String value = "HELLO公司"; 32 | TestDemo td = new TestDemo(); 33 | //此时就表示设置内容 34 | BeanOperate bo = new BeanOperate(td, attribute, value); 35 | System.out.println("多级属性设置:" + td.getEmp().getDept().getCompany().getTitle()); 36 | } 37 | System.out.println("================================"); 38 | { 39 | String attribute = "dept.loc"; //数组设置 40 | String [] value = {"上海","北京","重庆"}; 41 | TestDemo td = new TestDemo(); 42 | //此时就表示设置内容 43 | BeanOperate bo = new BeanOperate(td, attribute, value); 44 | System.out.println("数组属性设置:" + Arrays.toString(td.getDept().getLoc())); 45 | } 46 | System.out.println("================================"); 47 | { 48 | String attribute = "dept.ids"; //数组设置 49 | String [] value = {"1","2.8","3"}; 50 | TestDemo td = new TestDemo(); 51 | //此时就表示设置内容 52 | BeanOperate bo = new BeanOperate(td, attribute, value); 53 | System.out.println("数组属性设置:" + Arrays.toString(td.getDept().getIds())); 54 | } 55 | } 56 | } 57 | 58 | -------------------------------------------------------------------------------- /idea-365/D006_ComplexLambda/Apple.java: -------------------------------------------------------------------------------- 1 | package com.cfxyz.vo; 2 | 3 | public class Apple { 4 | private String color ; 5 | private Integer weight ; 6 | private String country ; 7 | public Apple(Integer weight, String color, String country) { 8 | this.weight = weight ; 9 | this.color = color ; 10 | this.country = country ; 11 | } 12 | public Integer getWeight() { 13 | return weight; 14 | } 15 | public void setWeight(Integer weight) { 16 | this.weight = weight; 17 | } 18 | public String getColor() { 19 | return color; 20 | } 21 | public void setColor(String color) { 22 | this.color = color; 23 | } 24 | public String getCountry() { 25 | return country; 26 | } 27 | public void setCountry(String country) { 28 | this.country = country; 29 | } 30 | @Override 31 | public String toString() { 32 | return "Apple [color=" + color + ", weight=" + weight + ", country=" + country + "]"; 33 | } 34 | 35 | } 36 | 37 | -------------------------------------------------------------------------------- /idea-365/D007_StreamTest/Dish.java: -------------------------------------------------------------------------------- 1 | package com.cfxyz.vo; 2 | 3 | public class Dish { 4 | private final String name; 5 | private final boolean vegetarian; 6 | private final int calories; 7 | private final Type type; 8 | 9 | public Dish(String name, boolean vegetarian, int calories, Type type) { 10 | this.name = name; 11 | this.vegetarian = vegetarian; 12 | this.calories = calories; 13 | this.type = type; 14 | } 15 | 16 | public String getName() { 17 | return name; 18 | } 19 | 20 | public boolean isVegetarian() { 21 | return vegetarian; 22 | } 23 | 24 | public int getCalories() { 25 | return calories; 26 | } 27 | 28 | public Type getType() { 29 | return type; 30 | } 31 | 32 | @Override 33 | public String toString() { 34 | return name; 35 | } 36 | 37 | public enum Type { MEAT, FISH, OTHER } 38 | } 39 | 40 | -------------------------------------------------------------------------------- /idea-365/D008_CollectorsTest/ToListCollector.java: -------------------------------------------------------------------------------- 1 | package com.cfxyz.util; 2 | 3 | import java.util.* ; 4 | import java.util.function.* ; 5 | import java.util.stream.Collector; 6 | import static java.util.stream.Collector.Characteristics.* ; 7 | 8 | public class ToListCollector implements Collector, List> { 9 | 10 | @Override 11 | public Supplier> supplier() { 12 | return ArrayList::new ; // 创建集合操作的起始点 13 | } 14 | 15 | @Override 16 | public BiConsumer, T> accumulator() { 17 | return List::add ; //累积遍历过的项目,原位修改累加器 18 | } 19 | 20 | @Override 21 | public BinaryOperator> combiner() { 22 | return (list1, list2) -> { 23 | list1.addAll(list2) ; //修改第一个累加器,将其与第二个累加器的内容合并 24 | return list1 ; //返回修改后的第一个累加器 25 | } ; 26 | } 27 | 28 | @Override 29 | public Function, List> finisher() { 30 | return Function.identity(); //恒等函数 31 | } 32 | 33 | @Override 34 | public Set characteristics() { 35 | return Collections.unmodifiableSet(EnumSet.of( 36 | IDENTITY_FINISH, CONCURRENT)); //为收集器添加IDENTITY_FINISH和CONCURRENT标志 37 | } 38 | } 39 | 40 | -------------------------------------------------------------------------------- /idea-365/D009_ParallelStreamsTest/ParallelStreamsTest.java: -------------------------------------------------------------------------------- 1 | package com.cfxyz.demo; 2 | 3 | import java.util.function.Function; 4 | import java.util.stream.LongStream; 5 | import java.util.stream.Stream; 6 | 7 | public class ParallelStreamsTest { 8 | public static void main(String[] args) { 9 | System.setProperty("java.util.concurrent.ForkJoinPool.common.parallelism","4"); //对应处理器的核心数 10 | System.out.println("Iterative sum done in:" + 11 | measureSumPerf(ParallelStreamsTest::iterativeSum, 10_000_000) + " msecs"); 12 | System.out.println("Sequential sum done in:" + 13 | measureSumPerf(ParallelStreamsTest::sequentialSum, 10_000_000) + " msecs"); 14 | // System.out.println("parallel sum done in:" + 15 | // measureSumPerf(ParallelStreamsTest::parallelSum, 10_000_000) + " msecs"); 16 | System.out.println("rangedSum sum done in:" + 17 | measureSumPerf(ParallelStreamsTest::rangedSum, 10_000_000) + " msecs"); 18 | } 19 | 20 | /** 21 | * 使用传统的for循环累加 22 | * @param n 23 | * @return 24 | */ 25 | public static long iterativeSum(long n) { 26 | long result = 0; 27 | for (long i = 1L; i <= n; i++) { 28 | result += i; 29 | } 30 | return result; 31 | } 32 | 33 | /** 34 | * 使用普通流 35 | * @param n 36 | * @return 37 | */ 38 | public static long sequentialSum(long n) { 39 | return Stream.iterate(1L, i -> i + 1) //生成自然数无限流 40 | .limit(n) //限制到前n个数 41 | .reduce(0L, Long::sum); //对所有数字求和来归纳流 42 | } 43 | 44 | /** 45 | * 使用并行流,iterate方法本质是顺序的,所以无法发挥并行优势 46 | * @param n 47 | * @return 48 | */ 49 | public static long parallelSum(long n) { 50 | return Stream.iterate(1L, i -> i + 1) 51 | .limit(n) 52 | .parallel() //将流转换为并行流 53 | .reduce(0L, Long::sum) ; 54 | } 55 | 56 | /** 57 | * 使用并行流,使用rangeClosed方法省掉装拆箱的时间 58 | * @param n 59 | * @return 60 | */ 61 | public static long rangedSum(long n) { 62 | return LongStream.rangeClosed(1, n) 63 | .reduce(0L, Long::sum) ; 64 | } 65 | 66 | /** 67 | * 测试方法 68 | * @param adder 69 | * @param n 70 | * @return 71 | */ 72 | public static long measureSumPerf(Function adder, long n) { 73 | long fastest = Long.MAX_VALUE; 74 | for (int i = 0; i < 10; i++) { 75 | long start = System.nanoTime(); 76 | long sum = adder.apply(n); 77 | long duration = (System.nanoTime() - start) / 1_000_000; 78 | System.out.println("Result: " + sum); 79 | if (duration < fastest) fastest = duration; 80 | } 81 | return fastest; 82 | } 83 | } 84 | 85 | -------------------------------------------------------------------------------- /idea-365/D010_StackVm/TestNewDict.java: -------------------------------------------------------------------------------- 1 | package com.cfxyz.newvm.test; 2 | 3 | import com.cfxyz.newvm.Vm; 4 | import com.cfxyz.newvm.util.DictUtil; 5 | import com.cfxyz.newvm.util.WordUtil; 6 | 7 | public class TestNewDict { 8 | 9 | public static void main(String[] args) { 10 | //给虚拟机分配好内存空间 11 | Vm vm = new Vm() ; 12 | 13 | //在词典中写入 14 | DictUtil.addWord(-1, "NORMAL", "REVEAL", "END", "CORE", new int[]{DictUtil.END}, vm); 15 | DictUtil.addWord(vm.last, "NORMAL", "REVEAL", "ADD", "CORE", new int[]{DictUtil.ADD}, vm); 16 | DictUtil.addWord(vm.last, "NORMAL", "REVEAL", "ADD2", "COLON", new int[]{DictUtil.ADD,DictUtil.ADD,DictUtil.END}, vm); 17 | 18 | //在算术栈中写入 19 | vm.paramStack.push(1); 20 | vm.paramStack.push(2); 21 | vm.paramStack.push(3); 22 | vm.paramStack.push(4); 23 | vm.paramStack.push(5); 24 | vm.paramStack.push(6); 25 | 26 | //在静态代码区中写入词的LFA地址 27 | vm.memory[vm.soureP++] = DictUtil.ADD; 28 | vm.memory[vm.soureP++] = 1018; //ADD2的LFA地址 29 | vm.memory[vm.soureP++] = 1018; //ADD2的LFA地址 30 | 31 | //打印出虚拟机的快照 32 | System.out.println(vm); 33 | DictUtil.listWord(vm); 34 | 35 | //执行静态代码 36 | while(vm.ip != vm.soureP){ 37 | int lfaAddr = vm.memory[vm.ip]; 38 | int nameLenAddr = lfaAddr + 3; 39 | int nameLength = vm.memory[nameLenAddr]; 40 | int cfaAddr = nameLenAddr + nameLength + 1; 41 | WordUtil.wordHandle(cfaAddr, vm); 42 | vm.ip ++ ; 43 | } 44 | System.out.println(); 45 | System.out.println(vm); 46 | } 47 | 48 | } 49 | -------------------------------------------------------------------------------- /idea-365/D010_StackVm/Vm.java: -------------------------------------------------------------------------------- 1 | package com.cfxyz.newvm; 2 | 3 | import java.util.Arrays; 4 | import java.util.Stack; 5 | 6 | public class Vm { 7 | public int here; //词典中空白位的开始地址 8 | public int last; //词典中最新一个词的词头地址 9 | public int ip; //IP指针,指向正在执行的词的地址 10 | public int soureP; //静态代码指针,指向静态代码的空白位的开始地址 11 | public int[] memory; //静态代码域+词典域 12 | public int sourceSize = 1000; //静态代码域长度 13 | public int dictSize = 1000 ; //词典长度 14 | 15 | public Stack returnStack; //返回栈 16 | public Stack paramStack; //算术栈 17 | 18 | public Vm() { 19 | this.soureP = 0 ; //静态代码指针初始化 20 | this.here = sourceSize ; //词典指针初始化 21 | this.last = this.here ; //词典空白位开始地址指向空白词典头部 22 | this.ip = 0 ; //IP指针指向静态代码域 23 | this.memory = new int[sourceSize + dictSize]; 24 | this.returnStack = new Stack(); 25 | this.paramStack = new Stack(); 26 | } 27 | 28 | public void setValue(int value) { 29 | this.memory[this.here] = value ; 30 | } 31 | 32 | @Override 33 | public String toString() { 34 | int[] source = new int[this.sourceSize]; 35 | for(int x = 0 ; x < this.sourceSize; x ++) { 36 | source[x] = this.memory[x] ; 37 | } 38 | int[] dict = new int[this.dictSize]; 39 | for(int x = 0; x 2 | #include 3 | #include 4 | using namespace std; 5 | 6 | //遍历当前目录下的文件夹和文件,默认是按字母顺序遍历 7 | bool TraverseFiles(string path,int &file_num) 8 | { 9 | _finddata_t file_info; 10 | string current_path=path+"/*.*"; //可以定义后面的后缀为*.exe,*.txt等来查找特定后缀的文件,*.*是通配符,匹配所有类型,路径连接符最好是左斜杠/,可跨平台 11 | //打开文件查找句柄 12 | int handle=_findfirst(current_path.c_str(),&file_info); 13 | //返回值为-1则查找失败 14 | if(-1==handle) 15 | return false; 16 | do 17 | { 18 | //判断是否子目录 19 | string attribute; 20 | if(file_info.attrib==_A_SUBDIR) //是目录 21 | attribute="dir"; 22 | else 23 | attribute="file"; 24 | //输出文件信息并计数,文件名(带后缀)、文件最后修改时间、文件字节数(文件夹显示0)、文件是否目录 25 | cout< 2 | #include 3 | using std::cout; 4 | using std::cin; 5 | using std::endl; 6 | using std::min; 7 | 8 | #define MAX_STRING_LEN 10 9 | 10 | int EditDistance(char *src, char *dest) 11 | { 12 | int i,j; 13 | int d[MAX_STRING_LEN][MAX_STRING_LEN] = { 0xFFFF }; 14 | 15 | for(i = 0; i <= strlen(src); i++) 16 | d[i][0] = i; 17 | for(j = 0; j <= strlen(dest); j++) 18 | d[0][j] = j; 19 | 20 | for(i = 1; i <= strlen(src); i++) 21 | { 22 | for(j = 1; j <= strlen(dest); j++) 23 | { 24 | if((src[i - 1] == dest[j - 1])) 25 | { 26 | d[i][j] = d[i - 1][j - 1]; //不需要编辑操作 27 | } 28 | else 29 | { 30 | int edIns = d[i][j - 1] + 1; //source 插入字符 31 | int edDel = d[i - 1][j] + 1; //source 删除字符 32 | int edRep = d[i - 1][j - 1] + 1; //source 替换字符 33 | 34 | d[i][j] = min(min(edIns, edDel), edRep); 35 | } 36 | } 37 | } 38 | 39 | return d[strlen(src)][strlen(dest)]; 40 | } 41 | 42 | int main() { 43 | char s[] = "SNOWY"; 44 | char d[] = "SUNNY"; 45 | 46 | cout << EditDistance(s,d) << endl; 47 | } 48 | -------------------------------------------------------------------------------- /idea-365/D016_LongestCommonSubsequence/最长公共子序列_动态规划.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using std::cout; 3 | using std::endl; 4 | using std::max; 5 | #define MAX_LENGTH 10 6 | 7 | //最长公共子序列(动态规划) 8 | int LCS(char *src, char *dest, int i, int j) { 9 | //初始化一个二维数组作为备忘表 10 | int table[MAX_LENGTH+1][MAX_LENGTH+1]; 11 | for(int x = 0; x <= i; ++x) 12 | table[x][0] = 0; 13 | for(int y = 0; y <= j; ++y) 14 | table[0][y] = 0; 15 | //通过递归公式,从底向上在二维数组中填充,最后table[i][j]就是最长子序列的长度 16 | for(int x = 1; x <= i; ++x) 17 | for(int y = 1; y <= j; ++y) { 18 | if(src[x-1] == dest[y-1]) 19 | table[x][y] = table[x-1][y-1] + 1; 20 | else 21 | table[x][y] = max(table[x][y-1], table[x-1][y]); 22 | } 23 | return table[i][j]; 24 | } 25 | 26 | int main() { 27 | int len_x = 7; 28 | int len_y = 6; 29 | char x[] = {'A','B','C','B','D','A','B'}; 30 | char y[] = {'B','D','C','A','B','A'}; 31 | 32 | cout << LCS(x,y,len_x,len_y) << endl; 33 | } 34 | -------------------------------------------------------------------------------- /idea-365/D016_LongestCommonSubsequence/最长公共子序列_动态规划_带回溯.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using std::cout; 4 | using std::endl; 5 | using std::max; 6 | using std::deque; 7 | #define MAX_LENGTH 10 8 | 9 | //带状态的备忘表元素 10 | struct StNum { 11 | int num; 12 | bool state; //如果src[i]等于dest[j],标记为true 13 | }; 14 | 15 | //最长公共子序列(动态规划-回溯分析) 16 | int LCS(char *src, char *dest, int i, int j) { 17 | //初始化一个二维数组作为备忘表 18 | StNum table[MAX_LENGTH+1][MAX_LENGTH+1]; 19 | for(int x = 0; x <= i; ++x) { 20 | table[x][0].num = 0; 21 | table[x][0].state = false; 22 | } 23 | for(int y = 0; y <= j; ++y) { 24 | table[0][y].num = 0; 25 | table[0][y].state = false; 26 | } 27 | 28 | //通过递归公式,从底向上在二维数组中填充,最后table[i][j].num就是最长子序列的长度 29 | for(int x = 1; x <= i; ++x) 30 | for(int y = 1; y <= j; ++y) { 31 | if(src[x-1] == dest[y-1]) { 32 | table[x][y].num = table[x-1][y-1].num + 1; 33 | table[x][y].state = true; 34 | } 35 | else { 36 | table[x][y].num = max(table[x][y-1].num, table[x-1][y].num); 37 | table[x][y].state = false; 38 | } 39 | } 40 | 41 | //根据 table[i][j].state的状态在二维数组中向斜上方回溯 42 | deque res; 43 | for(int x = i, y = j; x > 0 && y > 0;) { 44 | if(table[x][y].state) { 45 | res.push_front(src[x-1]); 46 | x--; 47 | y--; 48 | } 49 | else { 50 | y--; 51 | } 52 | } 53 | 54 | //打印出最长子序列 55 | for(auto c : res) 56 | cout << c << " "; 57 | cout << endl; 58 | 59 | return table[i][j].num; 60 | } 61 | 62 | int main() { 63 | int len_x = 7; 64 | int len_y = 6; 65 | char x[] = {'A','B','C','B','D','A','B'}; 66 | char y[] = {'B','D','C','A','B','A'}; 67 | 68 | cout << LCS(x,y,len_x,len_y) << endl; 69 | } 70 | -------------------------------------------------------------------------------- /idea-365/D016_LongestCommonSubsequence/最长公共子序列_动态规划_最小空间.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using std::cout; 3 | using std::endl; 4 | using std::max; 5 | #define MAX_LENGTH 10 6 | 7 | //最长公共子序列(动态规划-最小空间复杂度O(min(m,n)*2),无法回溯) 8 | int LCS(char *src, char *dest, int i, int j) { 9 | //因为只需要利用前一行的数据推算,可以用行数为2的二维数组最为备忘表。 10 | int table[2][j+1]; //gcc支持变长数组 11 | for(int x = 0; x < 2; ++x) 12 | table[x][0] = 0; 13 | for(int y = 0; y <= j; ++y) 14 | table[0][y] = 0; 15 | //通过递归公式,向二维数组内填充,反复利用两行。 16 | for(int x = 1; x <= i; ++x) 17 | for(int y = 1; y <= j; ++y) { 18 | if(src[x-1] == dest[y-1]) 19 | table[x%2][y] = table[(x-1)%2][y-1] + 1; 20 | else 21 | table[x%2][y] = max(table[x%2][y-1], table[(x-1)%2][y]); 22 | } 23 | return table[i%2][j]; 24 | } 25 | 26 | int main() { 27 | int len_x = 7; 28 | int len_y = 8; 29 | char x[] = {'A','B','C','B','D','A','B'}; 30 | char y[] = {'B','D','C','A','B','A','B','C'}; 31 | int res; 32 | //确保利用最小空间保存备忘表table 33 | if(len_x > len_y) 34 | res = LCS(x,y,len_x,len_y); 35 | else 36 | res = LCS(y,x,len_y,len_x); 37 | 38 | cout << res << endl; 39 | } 40 | -------------------------------------------------------------------------------- /idea-365/D016_LongestCommonSubsequence/最长公共子序列_备忘表.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using std::cout; 3 | using std::endl; 4 | using std::max; 5 | 6 | //最长公共子序列(备忘表) 7 | //使用一个二维数组C[m][n]来记录计算结果,对于已经计算过的C[i,j]直接查表得出。 8 | int LCS(char *src, char *dest, int i, int j, int **table) { 9 | if(i < 0 || j < 0) 10 | return 0; 11 | 12 | if(table[i][j] == 0) { 13 | if(src[i] == dest[j]) 14 | table[i][j] = LCS(src, dest, i-1, j-1, table) + 1; 15 | else 16 | table[i][j] = max(LCS(src, dest, i-1, j, table), LCS(src, dest, i, j-1, table)); 17 | } 18 | return table[i][j]; 19 | } 20 | 21 | int main() { 22 | int len_x = 7; 23 | int len_y = 6; 24 | char x[] = {'A','B','C','B','D','A','B'}; 25 | char y[] = {'B','D','C','A','B','A'}; 26 | 27 | //初始化一个二维数组作为备忘表,用0填充,代表没有记录的标志 28 | int max_len = 10; 29 | int **table = new int*[max_len]; 30 | for(int x = 0; x < max_len; ++x) { 31 | table[x] = new int[max_len]; 32 | } 33 | for(int x = 0; x < max_len; ++x) { 34 | for(int y = 0; y < max_len; ++y) 35 | table[x][y] = 0; 36 | } 37 | 38 | cout << LCS(x,y,len_x-1,len_y-1, table) << endl; 39 | 40 | //打印出二维数组 41 | for(int x = 0; x < max_len; ++x) { 42 | for(int y = 0; y < max_len; ++y) 43 | cout << table[x][y] << " "; 44 | cout << endl; 45 | } 46 | } 47 | -------------------------------------------------------------------------------- /idea-365/D016_LongestCommonSubsequence/最长公共子序列_朴素算法.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | int max(int a, int b) { 5 | return a > b ? a : b; 6 | } 7 | 8 | //最长公共子序列(朴素算法),速度非常慢 9 | int LCS(char *src, char *dest, int i, int j) { 10 | if(i < 0 || j < 0) 11 | return 0; 12 | if(src[i] == dest[j]) 13 | return LCS(src, dest, i-1, j-1) + 1; 14 | else 15 | return max(LCS(src, dest, i-1, j), LCS(src, dest, i, j-1)); 16 | } 17 | 18 | int main() { 19 | int len_x = 7; 20 | int len_y = 6; 21 | char x[] = {'A','B','C','B','D','A','B'}; 22 | char y[] = {'B','D','C','A','B','A'}; 23 | 24 | printf("%d\n", LCS(x,y,len_x-1,len_y-1)); 25 | 26 | char *s1 = "helloworld"; 27 | char *s2 = "howareyou"; 28 | printf("%d\n", LCS(s1,s2,strlen(s1)-1,strlen(s2)-1)); 29 | } 30 | -------------------------------------------------------------------------------- /idea-365/D018_BinarySearchTree/BinarySearchTree.cpp: -------------------------------------------------------------------------------- 1 | #include "BinarySearchTree.h" 2 | #include 3 | #include 4 | using std::cout; 5 | using std::cin; 6 | using std::endl; 7 | using std::string; 8 | 9 | int main() { 10 | BinaryTree int_tree; 11 | int num[7] = {3,1,8,2,6,7,5}; 12 | for(int x = 0; x < 7; ++x) { 13 | int_tree.insert(num[x]); 14 | } 15 | int_tree.inorderWalk([](int x){cout << x << " ";}); 16 | cout << endl; 17 | int_tree.remove(6); 18 | int_tree.remove(3); 19 | int_tree.inorderWalk([](int x){cout << x << " ";}); 20 | cout << endl; 21 | 22 | BinaryTree float_tree; 23 | float num2[7] = {3.1,1.2,8.3,2.4,6.5,7.6,5.7}; 24 | for(int x = 0; x < 7; ++x) { 25 | float_tree.insert(num2[x]); 26 | } 27 | float_tree.inorderWalk([](double x){cout << x << " | ";}); 28 | cout << endl; 29 | 30 | BinaryTree str_tree; 31 | string num3[5] = {"abc","cba","bca","bac","cab"}; 32 | for(int x = 0; x < 5; ++x) { 33 | str_tree.insert(num3[x]); 34 | } 35 | str_tree.inorderWalk([](string x){cout << x << " ";}); 36 | cout << endl; 37 | 38 | string s = "bca"; 39 | auto res = str_tree.search(s); 40 | if(res) 41 | cout << res->key << endl; 42 | else 43 | cout << "no key!!" << endl; 44 | } -------------------------------------------------------------------------------- /idea-365/D019_RedBlackTree/RBTree.cpp: -------------------------------------------------------------------------------- 1 | #include "RBTree.h" 2 | #include 3 | using std::cout; 4 | using std::cin; 5 | using std::endl; 6 | 7 | int main() { 8 | Node *nil = new Node{BLACK,INT_MIN,NULL,NULL,NULL}; 9 | Node *root = nil; 10 | RBTree rbtree = {root, nil}; 11 | RBTree *rbt = &rbtree; 12 | 13 | int num[9] = {9,7,8,5,4,3,6,2,1}; 14 | for(int x = 0; x < 9; ++x) { 15 | Node *z = new Node{RED,num[x],rbt->nil,rbt->nil,rbt->nil}; 16 | rb_insert(rbt, z); 17 | } 18 | cout << "root->key: " << rbt->root->key << endl; 19 | inorder_traverse(rbt, rbt->root); 20 | 21 | cout << "delete test:" << endl; 22 | for(int x = 1; x <= 9; ++x) { 23 | cout << "delete: " << x << endl; 24 | Node *n = rb_search(rbt, x); 25 | if(n != rbt->nil) { 26 | rb_delete(rbt, n); 27 | cout << "root->key: " << rbt->root->key << endl; 28 | inorder_traverse(rbt, rbt->root); 29 | } 30 | cout << endl; 31 | } 32 | 33 | return 0; 34 | } -------------------------------------------------------------------------------- /idea-365/D021_CFSearch/CFSearch.py: -------------------------------------------------------------------------------- 1 | import os 2 | 3 | 4 | class FileSearch(object): 5 | MOVIE = ['mp4', 'avi', 'wmv', 'rmvb', 'mov', 'mkv'] 6 | PIC = ['bmp', 'gif', 'jpeg', 'jpg', 'png'] 7 | DATA = ['zip', 'rar', '7z'] 8 | DOC = ['doc', 'xls', 'ppt', 'pdf', 'txt'] 9 | 10 | # 初始化时设置好过滤器 11 | def __init__(self, the_filter): 12 | capital_filter = [x.upper() for x in the_filter] 13 | self.the_filter = the_filter + capital_filter 14 | print(self.the_filter) 15 | 16 | # 搜索过滤列表内的后缀名文件,返回一个生成器 17 | def search(self, dir_path): 18 | for path, subdir, files in os.walk(dir_path): 19 | for f in files: 20 | if '.' in f and f[f.rindex('.')+1:] in self.the_filter: 21 | file_path = os.path.abspath(path) 22 | yield os.path.join(file_path, f) 23 | -------------------------------------------------------------------------------- /idea-365/D022_CFFile/CFFile.py: -------------------------------------------------------------------------------- 1 | class File(object): 2 | def __init__(self, path, size): 3 | self.path = path 4 | self.tell_pos = 0 5 | self.size = size 6 | self.gen_file() 7 | 8 | def gen_file(self): 9 | with open(self.path, 'w') as f: 10 | f.seek(self.size-1) 11 | f.write('\x00') 12 | 13 | def write(self, data, mode='r+'): 14 | if len(data) + self.tell_pos > self.size: 15 | print('error') 16 | return 17 | with open(self.path, mode) as f: 18 | f.seek(self.tell_pos) 19 | f.write(data) 20 | self.tell_pos = f.tell() 21 | -------------------------------------------------------------------------------- /idea-365/D023_FileSplit/FileSplit.py: -------------------------------------------------------------------------------- 1 | import os 2 | 3 | def file_split(file_path, output_file_path, size): 4 | if not os.path.exists(file_path): 5 | raise ValueError('Input file path not exists: %s ', file_path) 6 | 7 | all_len = os.path.getsize(file_path) 8 | num = all_len // size if all_len % size == 0 else (all_len // size) + 1 9 | index = 0 10 | with open(file_path, 'rb') as f: 11 | for i in range(0, num): 12 | index += 1 13 | data = f.read(size) 14 | if not data: 15 | break 16 | with open(output_file_path + '.' + str(index), 'ab') as out: 17 | out.write(data) 18 | 19 | 20 | def file_merge(file_path, output_file_path, num): 21 | if os.path.exists(output_file_path): 22 | raise ValueError('Output file path exists: %s ', output_file_path) 23 | 24 | with open(output_file_path, 'ab') as out: 25 | for i in range(1, num+1): 26 | with open(file_path + '.' + str(i), 'rb') as f: 27 | data = f.read() 28 | if not data: 29 | break 30 | out.write(data) 31 | 32 | file_split('E:/tt.zip', 'E:/xxx', 100*1024*1024) 33 | file_merge('E:/xxx', 'E:/ttt.zip', 5) 34 | -------------------------------------------------------------------------------- /idea-365/D024_CFPassword/CFPassword.py: -------------------------------------------------------------------------------- 1 | import random 2 | 3 | 4 | LOW_LEVEL = ['1', '2', '3', '4', '5', '6', '7', '8', '9', '0'] 5 | 6 | MEDIUM_LEVEL = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 7 | 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 8 | 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 9 | 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 10 | '1', '2', '3', '4', '5', '6', '7', '8', '9', '0'] 11 | 12 | HIGH_LEVEL = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 13 | 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 14 | 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 15 | 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 16 | '!', '@', '#', '$', '%', '^', '&', '*', '-', '_', '=', 17 | '+', '1', '2', '3', '4', '5', '6', '7', '8', '9', '0', ' '] 18 | 19 | 20 | def generate_password(length, level=LOW_LEVEL): 21 | return ''.join([random.choice(level) for i in range(0, length)]) 22 | 23 | 24 | if __name__ == '__main__': 25 | print(generate_password(8)) 26 | print(generate_password(16, MEDIUM_LEVEL)) 27 | print(generate_password(64, HIGH_LEVEL)) 28 | -------------------------------------------------------------------------------- /idea-365/D026_CFORM/CFORM/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/cforth/codefarm/cabd0ec1e9fb2a2aa582682b1a4016378e8515dc/idea-365/D026_CFORM/CFORM/__init__.py -------------------------------------------------------------------------------- /idea-365/D026_CFORM/CFORM/db.py: -------------------------------------------------------------------------------- 1 | import sqlite3 2 | 3 | 4 | # 数据库操作,负责连接、提交事务、断开数据库,返回操作的行数与结果列表 5 | def operate(db_name, execute_str, execute_args=None): 6 | result = None 7 | conn = sqlite3.connect(db_name + ".db") 8 | row_size = 0 9 | try: 10 | cursor = conn.cursor() 11 | if execute_args: 12 | cursor.execute(execute_str, execute_args) 13 | else: 14 | cursor.execute(execute_str) 15 | result = cursor.fetchall() 16 | row_size = cursor.rowcount 17 | cursor.close() 18 | conn.commit() 19 | except Exception as e: 20 | print(e) 21 | finally: 22 | conn.close() 23 | return row_size, result -------------------------------------------------------------------------------- /idea-365/D026_CFORM/tests/test_Model.py: -------------------------------------------------------------------------------- 1 | from CFORM.Model import * 2 | 3 | 4 | class User(Model): 5 | # 定义类的属性到列的映射: 6 | id = IntegerField('id', primary_key=True) 7 | username = StringField('username') 8 | email = StringField('email') 9 | password = StringField('password') 10 | 11 | 12 | # 新建数据库和数据表 13 | if not User.has_table(): 14 | User.new_table() 15 | 16 | # 将数据存入数据表中 17 | u = User(id=1, username='cf', email='cforth@cfxyzom', password='hello') 18 | if not User.find("username", u.username): 19 | u.save() 20 | 21 | u = User(id=2, username='xxx', email='xxx@cfxyzom', password='world') 22 | if not User.find("username", u.username): 23 | u.save() 24 | 25 | u = User(id=3, username='yyy', email='yyy@cfxyzom', password='sdgfdg') 26 | if not User.find("username", u.username): 27 | u.save() 28 | 29 | # 删除数据 30 | User.remove('id', 2) 31 | -------------------------------------------------------------------------------- /idea-365/D028_XML2GUI/MainWindow.py: -------------------------------------------------------------------------------- 1 | from xml2gui import * 2 | import tkinter as tk 3 | import tkinter.filedialog as filedialog 4 | import tkinter.ttk as ttk 5 | 6 | 7 | class Window(ttk.Frame): 8 | def __init__(self, master=None): 9 | super().__init__(master, padding=2) 10 | # 从xml文件自动设置UI控件 11 | create_ui(self, "my_window.xml") 12 | # 为控件绑定指令 13 | create_command(self, "passwordShowButton", self.password_show_button_callback) 14 | create_command(self, "fileFromButton", self.file_from_button_callback) 15 | create_command(self, "fileToButton", self.file_to_button_callback) 16 | create_command(self, "doButton", self.do_button_callback) 17 | self.grid(row=0, column=0) 18 | 19 | def password_show_button_callback(self, event=None): 20 | self.__dict__["passwordEntry"]["show"] = "" if self.__dict__["passwordEntry"]["show"] == "*" else "*" 21 | 22 | def file_from_button_callback(self, event=None): 23 | self.__dict__["fileFrom"].set(filedialog.askopenfilename()) 24 | 25 | def file_to_button_callback(self, event=None): 26 | self.__dict__["fileTo"].set(filedialog.askdirectory()) 27 | 28 | def do_button_callback(self, event=None): 29 | self.__dict__["info"].set("密码:%s\n输入路径:%s\n输出路径:%s" % 30 | (self.__dict__["password"].get(), 31 | self.__dict__["fileFrom"].get(), 32 | self.__dict__["fileTo"].get())) 33 | 34 | 35 | app = Window() 36 | # 设置窗口标题: 37 | app.master.title('测试') 38 | # 主消息循环: 39 | app.mainloop() 40 | -------------------------------------------------------------------------------- /idea-365/D028_XML2GUI/my_window.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | 45 | 46 | 47 | 48 | 49 | 50 | 51 | 52 | -------------------------------------------------------------------------------- /idea-365/D028_XML2GUI/xml2gui.py: -------------------------------------------------------------------------------- 1 | from xml.parsers.expat import ParserCreate 2 | import tkinter as tk 3 | import tkinter.ttk as ttk 4 | import logging 5 | 6 | logging.basicConfig(level=logging.INFO) 7 | 8 | 9 | # xml解析类 10 | class MySaxHandler(object): 11 | def __init__(self): 12 | self.window = None 13 | self.stack = [] 14 | 15 | def start_element(self, name, attrs): 16 | if name == 'Root': 17 | self.window = {} 18 | else: 19 | if not self.stack: 20 | self.window[name] = {} 21 | self.stack.append(name) 22 | else: 23 | self.window[self.stack[-1]][name] = attrs 24 | 25 | def end_element(self, name): 26 | if self.stack and self.stack[-1] == name: 27 | self.stack.pop() 28 | elif name == 'Root': 29 | logging.info(str(self.window)) 30 | 31 | def char_data(self, text): 32 | pass 33 | 34 | 35 | # 从xml文件自动设置UI控件 36 | def create_ui(self, xml_file): 37 | try: 38 | with open(xml_file, 'r', encoding='utf-8') as f: 39 | xml = f.read() 40 | if xml: 41 | handler = MySaxHandler() 42 | parser = ParserCreate() 43 | parser.StartElementHandler = handler.start_element 44 | parser.EndElementHandler = handler.end_element 45 | parser.CharacterDataHandler = handler.char_data 46 | parser.Parse(xml) 47 | widget = handler.window 48 | else: 49 | widget = {} 50 | except Exception as err: 51 | widget = {} 52 | logging.error('Err: %s' % err) 53 | 54 | if widget: 55 | for k in widget: 56 | widget_class = widget[k]["type"]["name"] 57 | widget_str_parm = widget[k]["strParm"] if widget[k].get("strParm") else {} 58 | widget_int_parm = widget[k]["intParm"] if widget[k].get("intParm") else {} 59 | widget_var = widget[k]["var"] if widget[k].get("var") else None 60 | 61 | # 动态生成控件,并添加字符串类型的参数(若有) 62 | self.__dict__[k] = ttk.__dict__[widget_class](self, **widget_str_parm) 63 | # 为每个控件添加数值类型的参数(若有) 64 | for pk in widget_int_parm: 65 | self.__dict__[k][pk] = int(widget_int_parm[pk]) 66 | # 为每个控件绑定变量(若有) 67 | if widget_var: 68 | self.__dict__[widget_var["name"]] = tk.StringVar() 69 | self.__dict__[k]["textvariable"] = self.__dict__[widget_var["name"]] 70 | self.__dict__[k].grid(**widget[k]["grid"]) 71 | 72 | 73 | # 绑定控件的指令 74 | def create_command(self, widget, command): 75 | self.__dict__[widget]["command"] = command 76 | -------------------------------------------------------------------------------- /idea-365/D029_JSON2GUI/Calculator.py: -------------------------------------------------------------------------------- 1 | from CFTookit.json2gui import * 2 | import tkinter as tk 3 | 4 | 5 | class Window(tk.Frame): 6 | def __init__(self, ui_json, master=None): 7 | super().__init__(master) 8 | # 从json自动设置UI控件 9 | create_ui(self, ui_json) 10 | # 从json自动绑定事件 11 | create_all_binds(self, ui_json) 12 | self.cache = "" 13 | self.grid(row=0, column=0) 14 | 15 | def callback(self, event): 16 | # 取出事件发生的按钮对应的符号或数字 17 | symbol = event.widget["text"] 18 | # 控制和计算 19 | if symbol == "<-": 20 | if self.cache: 21 | self.cache = self.cache[:-1] 22 | elif symbol == "AC": 23 | self.cache = "" 24 | elif symbol == "=": 25 | # 直接使用eval函数计算 26 | self.cache = str(eval(self.cache)) 27 | else: 28 | self.cache += symbol 29 | # 显示出来 30 | getattr(self, "output").set(self.cache) 31 | 32 | 33 | app = Window("UI.json") 34 | # 设置窗口标题: 35 | app.master.title("计算器") 36 | # 主消息循环: 37 | app.mainloop() 38 | -------------------------------------------------------------------------------- /idea-365/D030_StockQuotation/StockQutation.py: -------------------------------------------------------------------------------- 1 | from CFTookit.json2gui import * 2 | import tkinter as tk 3 | import requests 4 | import json 5 | import re 6 | import logging 7 | 8 | logging.basicConfig(level=logging.INFO) 9 | 10 | 11 | class Window(tk.Frame): 12 | def __init__(self, ui_json, master=None): 13 | super().__init__(master) 14 | # 从json自动设置UI控件 15 | create_ui(self, ui_json) 16 | # 从json自动绑定事件 17 | create_all_binds(self, ui_json) 18 | self.grid(row=0, column=0) 19 | 20 | def get_quotation(self, event): 21 | stock_code = self.__dict__["stockCode"].get() 22 | if not re.match(r"^\d{6}$", stock_code): 23 | getattr(self, "output").set("") 24 | raise ValueError("Stock Code Error") 25 | 26 | # 添加0或1在股票代码之前,满足获取行情的API需要 27 | if stock_code[0] == "0" or stock_code[0] == "3": 28 | stock_code = "1" + stock_code 29 | else: 30 | stock_code = "0" + stock_code 31 | 32 | url = "http://api.money.126.net/data/feed/" + stock_code + ",money.api" 33 | result = requests.get(url).content.decode() 34 | json_str = result[result.index("(") + 1:result.rindex(")")] 35 | data_dict = json.loads(json_str) 36 | if data_dict: 37 | now_time = data_dict[stock_code]["time"] 38 | stock_symbol = data_dict[stock_code]["symbol"] 39 | stock_name = data_dict[stock_code]["name"] 40 | now_price = data_dict[stock_code]["price"] 41 | percent = data_dict[stock_code]["percent"] * 100.0 42 | updown = data_dict[stock_code]["updown"] 43 | logging.info(str(data_dict)) 44 | quotation = "名称:%s\n代码:%s\n价格:%.2f\n涨跌幅:%.2f%%\n涨跌价:%.2f\n时间:%s" % \ 45 | (stock_name, stock_symbol, now_price, percent, updown, now_time) 46 | getattr(self, "output").set(quotation) 47 | else: 48 | getattr(self, "output").set("") 49 | 50 | 51 | app = Window("UI.json") 52 | # 设置窗口标题: 53 | app.master.title("股票行情") 54 | # 主消息循环: 55 | app.mainloop() 56 | -------------------------------------------------------------------------------- /idea-365/D030_StockQuotation/UI.json: -------------------------------------------------------------------------------- 1 | { 2 | "stockCodeEntry": { 3 | "class": "Entry", 4 | "var": "stockCode", 5 | "int": {"width": 50}, 6 | "grid": {"row":0, "column":0, "sticky":["W", "E"]} 7 | }, 8 | "displayButton": { 9 | "class": "Button", 10 | "bind": {"": "get_quotation"}, 11 | "int": {"width": 10}, 12 | "string": {"text": "显示行情"}, 13 | "grid": {"row":0, "column":1} 14 | }, 15 | "outputLabel": { 16 | "class": "Label", 17 | "var": "output", 18 | "int": {"height": 10}, 19 | "string": {"font": "Arial, 12"}, 20 | "grid": {"row":1, "column":0, "columnspan": 2, "sticky":["W", "E", "N", "S"]} 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /idea-365/D032_ImgLook/UI.json: -------------------------------------------------------------------------------- 1 | { 2 | "passwordShowButton": { 3 | "class": "Button", 4 | "int": {"width": 10}, 5 | "string": {"text": "显隐密码"}, 6 | "command": "password_show_button_callback", 7 | "grid": {"row":0, "column":0, "sticky":["W", "E"]} 8 | }, 9 | "passwordEntry": { 10 | "class": "Entry", 11 | "var": "password", 12 | "int": {"width": 80}, 13 | "string": {"show": "*"}, 14 | "grid": {"row":0, "column":1, "sticky":["W", "E"]} 15 | }, 16 | "cryptoOptionCombobox": { 17 | "class": "Combobox", 18 | "var": "cryptoOption", 19 | "int": {"width": 10}, 20 | "string": {"state": ["readonly"], "values": ["解密文件", "不需解密", "解密保名"]}, 21 | "grid": {"row":0, "column":2, "sticky":["W", "E"]} 22 | }, 23 | "fileFromButton": { 24 | "class": "Button", 25 | "int": {"width": 10}, 26 | "string": {"text": "选择文件"}, 27 | "command": "file_from_button_callback", 28 | "grid": {"row":1, "column":0, "sticky":["W", "E"]} 29 | }, 30 | "imgPathEntry": { 31 | "class": "Entry", 32 | "var": "imgPath", 33 | "int": {"width": 80}, 34 | "string": {"state": "disable"}, 35 | "grid": {"row":1, "column":1, "sticky":["W", "E"]} 36 | }, 37 | "showButton": { 38 | "class": "Button", 39 | "bind": {"": "img_show"}, 40 | "int": {"width": 10}, 41 | "string": {"text": "显示"}, 42 | "grid": {"row":1, "column":2, "sticky":["W", "E"]} 43 | }, 44 | "imgSizeNameLabel": { 45 | "class": "Label", 46 | "int": {"width": 10}, 47 | "string": {"text": "调整大小"}, 48 | "grid": {"row":2, "column":0, "sticky":["W", "E"]} 49 | }, 50 | "imgSizeScale": { 51 | "class": "Scale", 52 | "string": {"orient": "horizontal"}, 53 | "int": {"from_": 1, "to": 100}, 54 | "bind": {"": "set_img_width", "": "set_img_size_info"}, 55 | "grid": {"row":2, "column":1, "sticky":["W", "E"]} 56 | }, 57 | "imgSizeInfoLabel": { 58 | "class": "Label", 59 | "int": {"width": 10}, 60 | "var": "imgSizeInfo", 61 | "grid": {"row":2, "column":2, "sticky":["W", "E"]} 62 | }, 63 | "prevImgButton": { 64 | "class": "Button", 65 | "string": {"text": "<"}, 66 | "command": "prev_img_button_callback", 67 | "grid": {"row":3, "column":0, "sticky":["N", "S"]} 68 | }, 69 | "imgLabel": { 70 | "class": "Label", 71 | "grid": {"row":3, "column":1, "sticky":["W", "E", "N", "S"]} 72 | }, 73 | "nextImgButton": { 74 | "class": "Button", 75 | "string": {"text": ">"}, 76 | "command": "next_img_button_callback", 77 | "grid": {"row":3, "column":2, "sticky":["N", "S"]} 78 | } 79 | } -------------------------------------------------------------------------------- /idea-365/D033_JSON2PY/GifHandle.py: -------------------------------------------------------------------------------- 1 | from PIL import Image, ImageTk 2 | 3 | 4 | # GIF动图处理类 5 | class GifHandle(object): 6 | def __init__(self, master_widget, img_path): 7 | # 保存显示图片的控件引用 8 | self.master_widget = master_widget 9 | # 保存图片路径 10 | self.img_path = img_path 11 | # 保存gif格式图片当前显示的帧的数据 12 | self._frame = None 13 | # 保存gif格式图片每一帧 14 | self._gif_frames = [] 15 | # 保存gif格式图片帧的数量 16 | self._frame_count = 0 17 | # 保存gif格式图片每一帧的延时 18 | self.delay = 50 19 | # 保存gif格式图片当前显示的帧的位置 20 | self._ind = 0 21 | # 设置gif图片默认运行状态为关闭 22 | self._gif_running = False 23 | # 初始化gif动图 24 | self._init_gif() 25 | 26 | # 初始化GIF动图,将GIF动图每一帧保存起来准备显示 27 | def _init_gif(self): 28 | im = Image.open(self.img_path) 29 | seq = [] 30 | try: 31 | while True: 32 | seq.append(im.copy()) 33 | im.seek(len(seq)) # skip to next frame 34 | except EOFError: 35 | pass # we're done 36 | try: 37 | self.delay = im.info['duration'] 38 | # 将默认延时设置为50ms 39 | if self.delay < 50: 40 | self.delay = 50 41 | except KeyError: 42 | self.delay = 50 43 | first = seq[0].convert('RGBA') 44 | self._gif_frames = [ImageTk.PhotoImage(first)] 45 | temp = seq[0] 46 | for image in seq[1:]: 47 | temp.paste(image) 48 | frame = temp.convert('RGBA') 49 | self._gif_frames.append(ImageTk.PhotoImage(frame)) 50 | self._frame_count += 1 51 | 52 | # 更新GIF动图的下一帧 53 | def _update_gif(self): 54 | self._frame = self._gif_frames[self._ind] 55 | self._ind += 1 56 | if self._ind >= self._frame_count: 57 | self._ind = 0 58 | # 将gif当前帧显示在widget容器中 59 | self.master_widget.configure(image=self._frame) 60 | # 设置定时器,更新widget容器显示的gif帧 61 | self.master_widget.gif_timer = self.master_widget.after(self.delay, self._update_gif) 62 | 63 | # 启动GIF动图 64 | def start_gif(self): 65 | # 设置gif图片运行标志 66 | self._gif_running = True 67 | # 在widget容器中设置定时器 68 | self.master_widget.gif_timer = self.master_widget.after(0, self._update_gif) 69 | 70 | # 停止当前的GIF动图 71 | def stop_gif(self): 72 | if self._gif_running: 73 | # 停止定时器 74 | self.master_widget.after_cancel(self.master_widget.gif_timer) 75 | self._gif_running = False 76 | -------------------------------------------------------------------------------- /idea-365/D033_JSON2PY/UI.json: -------------------------------------------------------------------------------- 1 | { 2 | "passwordShowButton": { 3 | "class": "Button", 4 | "int": {"width": 10}, 5 | "string": {"text": "显隐密码"}, 6 | "command": "password_show_button_callback", 7 | "grid": {"row":0, "column":0, "sticky":["W", "E"]} 8 | }, 9 | "passwordEntry": { 10 | "class": "Entry", 11 | "var": "password", 12 | "int": {"width": 80}, 13 | "string": {"show": "*"}, 14 | "grid": {"row":0, "column":1, "sticky":["W", "E"]} 15 | }, 16 | "cryptoOptionCombobox": { 17 | "class": "Combobox", 18 | "var": "cryptoOption", 19 | "int": {"width": 10}, 20 | "string": {"state": ["readonly"], "values": ["解密文件", "不需解密", "解密保名"]}, 21 | "grid": {"row":0, "column":2, "sticky":["W", "E"]} 22 | }, 23 | "fileFromButton": { 24 | "class": "Button", 25 | "int": {"width": 10}, 26 | "string": {"text": "选择文件"}, 27 | "command": "file_from_button_callback", 28 | "grid": {"row":1, "column":0, "sticky":["W", "E"]} 29 | }, 30 | "imgPathEntry": { 31 | "class": "Entry", 32 | "var": "imgPath", 33 | "int": {"width": 80}, 34 | "string": {"state": "disable"}, 35 | "grid": {"row":1, "column":1, "sticky":["W", "E"]} 36 | }, 37 | "showButton": { 38 | "class": "Button", 39 | "bind": {"": "img_show"}, 40 | "int": {"width": 10}, 41 | "string": {"text": "显示"}, 42 | "grid": {"row":1, "column":2, "sticky":["W", "E"]} 43 | }, 44 | "imgSizeNameLabel": { 45 | "class": "Label", 46 | "int": {"width": 10}, 47 | "string": {"text": "调整大小"}, 48 | "grid": {"row":2, "column":0, "sticky":["W", "E"]} 49 | }, 50 | "imgSizeScale": { 51 | "class": "Scale", 52 | "string": {"orient": "horizontal"}, 53 | "int": {"from_": 1, "to": 100}, 54 | "bind": {"": "set_img_width", "": "set_img_size_info"}, 55 | "grid": {"row":2, "column":1, "sticky":["W", "E"]} 56 | }, 57 | "imgSizeInfoLabel": { 58 | "class": "Label", 59 | "int": {"width": 10}, 60 | "var": "imgSizeInfo", 61 | "grid": {"row":2, "column":2, "sticky":["W", "E"]} 62 | }, 63 | "prevImgButton": { 64 | "class": "Button", 65 | "string": {"text": "<"}, 66 | "command": "prev_img_button_callback", 67 | "grid": {"row":3, "column":0, "sticky":["N", "S"]} 68 | }, 69 | "imgLabel": { 70 | "class": "Label", 71 | "grid": {"row":3, "column":1, "sticky":["W", "E", "N", "S"]} 72 | }, 73 | "nextImgButton": { 74 | "class": "Button", 75 | "string": {"text": ">"}, 76 | "command": "next_img_button_callback", 77 | "grid": {"row":3, "column":2, "sticky":["N", "S"]} 78 | } 79 | } -------------------------------------------------------------------------------- /idea-365/D036_ProgressBar/ProgressBar.py: -------------------------------------------------------------------------------- 1 | import tkinter as tk 2 | import tkinter.ttk as ttk 3 | import time 4 | from threading import Thread 5 | 6 | 7 | class ProgressBar(ttk.Frame): 8 | def __init__(self, progress_current, progress_total, progress_var, master=None): 9 | super().__init__(master, padding=2) 10 | self.progress_var = tk.DoubleVar() 11 | self.progress_current_label_var = tk.StringVar() 12 | self.progress_total_label_var = tk.StringVar() 13 | self.progress_var.set(progress_var) 14 | self.progress_current_label_var.set(progress_current) 15 | self.progress_total_label_var.set(progress_total) 16 | self.progressCurrentLabel = ttk.Label(self, textvariable=self.progress_current_label_var) 17 | self.progressBar = ttk.Progressbar(self, orient='horizontal', mode='determinate', value=0) 18 | self.progressBar['variable'] = self.progress_var 19 | self.progressTotalLabel = ttk.Label(self, textvariable=self.progress_total_label_var) 20 | pad_w_e = dict(sticky=(tk.W, tk.E), padx="0.5m", pady="0.5m") 21 | self.progressCurrentLabel.grid(row=0, column=0, **pad_w_e) 22 | self.progressBar.grid(row=0, column=1, **pad_w_e) 23 | self.progressTotalLabel.grid(row=0, column=2, **pad_w_e) 24 | self.grid(row=0, column=0, sticky=(tk.N, tk.S, tk.E, tk.W)) 25 | 26 | def set_status(self, progress_current, progress_total, progress_var): 27 | self.progress_var.set(progress_var) 28 | self.progress_current_label_var.set(progress_current) 29 | self.progress_total_label_var.set(progress_total) 30 | 31 | 32 | class Window(ttk.Frame): 33 | def __init__(self, master=None): 34 | super().__init__(master, padding=2) 35 | self.bar = ProgressBar("0%", "100%", 0.0, master=self) 36 | self.button = ttk.Button(self, text="开始", command=self.do) 37 | self.bar.pack() 38 | self.button.pack() 39 | self.pack() 40 | 41 | def update_bar(self): 42 | for x in range(100): 43 | self.bar.set_status(str(x) + "%", "100%", x) 44 | time.sleep(1) 45 | 46 | def do(self): 47 | xxx = Thread(target=self.update_bar, args=()) 48 | xxx.start() 49 | 50 | 51 | if __name__ == '__main__': 52 | app = Window() 53 | # 设置窗口标题: 54 | app.master.title("进度条") 55 | # 主消息循环: 56 | app.mainloop() 57 | -------------------------------------------------------------------------------- /idea-365/D037_CFFormatFile/CFFormatFile.py: -------------------------------------------------------------------------------- 1 | import os 2 | import hashlib 3 | 4 | 5 | def generate_cf_format_file(file_path, output_dir, file_name=None): 6 | if not os.path.exists(file_path): 7 | raise ValueError('Input file path not exists: %s ', file_path) 8 | 9 | if not os.path.exists(output_dir): 10 | raise ValueError('Output file path not exists: %s ', output_dir) 11 | 12 | if not os.path.isfile(file_path): 13 | raise ValueError('Input file path not file: %s ', file_path) 14 | 15 | if not file_name: 16 | file_name = os.path.basename(file_path) 17 | 18 | file_name_bytes = file_name.encode('utf-8') 19 | 20 | md5 = hashlib.md5() 21 | md5.update(file_name_bytes) 22 | file_name_md5 = md5.hexdigest() 23 | 24 | with open(os.path.join(output_dir, file_name_md5), 'wb') as out_f: 25 | out_f.write(b'cf') 26 | file_name_length = len(file_name_bytes) 27 | name_length_str = '' 28 | for i in range(0, 4 - len(str(file_name_length))): 29 | name_length_str += '0' 30 | name_length_str += str(file_name_length) 31 | out_f.write(name_length_str.encode('utf-8')) 32 | out_f.write(file_name_bytes) 33 | 34 | with open(file_path, 'rb') as in_f: 35 | data = in_f.read() 36 | out_f.write(data) 37 | 38 | 39 | def parse_cf_format_file(file_path): 40 | with open(file_path, 'rb') as f: 41 | file_format = f.read(2) 42 | if file_format == b'cf': 43 | print("CF Format File") 44 | name_length = int(f.read(4).decode('utf-8')) 45 | print(name_length) 46 | name = f.read(name_length).decode('utf-8') 47 | print(name) 48 | 49 | 50 | def extract_cf_format_file(file_path, output_dir): 51 | with open(file_path, 'rb') as f: 52 | file_format = f.read(2) 53 | if file_format == b'cf': 54 | print("CF Format File") 55 | name_length = int(f.read(4).decode('utf-8')) 56 | print(name_length) 57 | name = f.read(name_length).decode('utf-8') 58 | print(name) 59 | data = f.read() 60 | with open(os.path.join(output_dir, name), 'wb') as out_f: 61 | out_f.write(data) 62 | -------------------------------------------------------------------------------- /idea-365/D038_CryptoTools/FileSplitUI.json: -------------------------------------------------------------------------------- 1 | { 2 | "fileFromButton": { 3 | "class": "Button", 4 | "int": {"width": 10}, 5 | "string": {"text": "来源"}, 6 | "command": "file_from_button_callback", 7 | "grid": {"row":0, "column":0, "sticky":["W", "E"]} 8 | }, 9 | "fileFromEntry": { 10 | "class": "Entry", 11 | "var": "file_from", 12 | "int": {"width": 60}, 13 | "grid": {"row":0, "column":1, "sticky":["W", "E"]} 14 | }, 15 | "fileToButton": { 16 | "class": "Button", 17 | "int": {"width": 10}, 18 | "string": {"text": "目标"}, 19 | "command": "file_to_button_callback", 20 | "grid": {"row":1, "column":0, "sticky":["W", "E"]} 21 | }, 22 | "fileToEntry": { 23 | "class": "Entry", 24 | "var": "file_to", 25 | "int": {"width": 60}, 26 | "grid": {"row":1, "column":1, "sticky":["W", "E"]} 27 | }, 28 | "splitCounterLabel": { 29 | "class": "Label", 30 | "int": {"width": 10}, 31 | "string": {"text": "个数: "}, 32 | "grid": {"row":2, "column":0} 33 | }, 34 | "splitCounterEntry": { 35 | "class": "Entry", 36 | "var": "split_counter", 37 | "int": {"width": 60}, 38 | "grid": {"row":2, "column":1, "sticky":["W", "E"]} 39 | }, 40 | "splitOptionCombobox": { 41 | "class": "Combobox", 42 | "var": "split_option", 43 | "int": {"width": 10}, 44 | "string": {"state": ["readonly"], "values": ["分割", "合并"]}, 45 | "grid": {"row":3, "column":0, "sticky":["W", "E"]} 46 | }, 47 | "splitButton": { 48 | "class": "Button", 49 | "int": {"width": 10}, 50 | "string": {"text": "执行"}, 51 | "command": "split_button_callback", 52 | "grid": {"row":3, "column":1, "sticky":["E"]} 53 | }, 54 | "resultText": { 55 | "class": "Text", 56 | "int": {"width": 60, "height": 20}, 57 | "string": {"wrap": "none"}, 58 | "grid": {"row":4, "column":0, "columnspan":2, "sticky":["W", "E", "N", "S"]} 59 | }, 60 | "TextScrollbarY": { 61 | "class": "Scrollbar", 62 | "string": {"orient": "vertical"}, 63 | "grid": {"row":4, "column":2, "sticky":["N", "S"]} 64 | }, 65 | "TextScrollbarX": { 66 | "class": "Scrollbar", 67 | "string": {"orient": "horizontal"}, 68 | "grid": {"row":5, "column":0, "columnspan":2, "sticky":["W", "E"]} 69 | } 70 | } -------------------------------------------------------------------------------- /idea-365/D038_CryptoTools/MD5GenerateUI.json: -------------------------------------------------------------------------------- 1 | { 2 | "fileFromOptionCombobox": { 3 | "class": "Combobox", 4 | "var": "fileFromOption", 5 | "int": {"width": 10}, 6 | "string": {"state": ["readonly"], "values": ["文件", "文件夹", "字符串"]}, 7 | "grid": {"row":0, "column":0, "sticky":["W", "E"]} 8 | }, 9 | "fileFromButton": { 10 | "class": "Button", 11 | "int": {"width": 10}, 12 | "string": {"text": "选择文件"}, 13 | "command": "file_from_button_callback", 14 | "grid": {"row":0, "column":1, "sticky":["W", "E"]} 15 | }, 16 | "fileFromPathEntry": { 17 | "class": "Entry", 18 | "var": "file_from_path", 19 | "int": {"width": 40}, 20 | "grid": {"row":0, "column":2, "sticky":["W", "E"]} 21 | }, 22 | "MD5GenerateButton": { 23 | "class": "Button", 24 | "int": {"width": 10}, 25 | "string": {"text": "MD5生成"}, 26 | "command": "md5_generate_button_callback", 27 | "grid": {"row":0, "column":3, "sticky":["W", "E"]} 28 | }, 29 | "MD5ResultText": { 30 | "class": "Text", 31 | "int": {"width": 60, "height": 20}, 32 | "string": {"wrap": "none"}, 33 | "grid": {"row":1, "column":0, "columnspan":4, "sticky":["W", "E", "N", "S"]} 34 | }, 35 | "TextScrollbarY": { 36 | "class": "Scrollbar", 37 | "string": {"orient": "vertical"}, 38 | "grid": {"row":1, "column":4, "sticky":["N", "S"]} 39 | }, 40 | "TextScrollbarX": { 41 | "class": "Scrollbar", 42 | "string": {"orient": "horizontal"}, 43 | "grid": {"row":2, "column":0, "columnspan":5, "sticky":["W", "E"]} 44 | } 45 | } -------------------------------------------------------------------------------- /idea-365/D038_CryptoTools/RandomPasswordUI.json: -------------------------------------------------------------------------------- 1 | { 2 | "passLengthLabel": { 3 | "class": "Label", 4 | "int": {"width": 10}, 5 | "string": {"text": "密码长度: "}, 6 | "grid": {"row":0, "column":0} 7 | }, 8 | "passLengthEntry": { 9 | "class": "Entry", 10 | "var": "pass_length", 11 | "int": {"width": 10}, 12 | "grid": {"row":0, "column":1, "sticky":["W", "E"]} 13 | }, 14 | "passNumberLabel": { 15 | "class": "Label", 16 | "int": {"width": 10}, 17 | "string": {"text": "密码个数: "}, 18 | "grid": {"row":0, "column":2} 19 | }, 20 | "passNumberEntry": { 21 | "class": "Entry", 22 | "var": "pass_number", 23 | "int": {"width": 10}, 24 | "grid": {"row":0, "column":3, "sticky":["W", "E"]} 25 | }, 26 | "passLevelLabel": { 27 | "class": "Label", 28 | "int": {"width": 10}, 29 | "string": {"text": "密码强度: "}, 30 | "grid": {"row":0, "column":4} 31 | }, 32 | "passLevelCombobox": { 33 | "class": "Combobox", 34 | "var": "pass_level", 35 | "int": {"width": 10}, 36 | "string": {"state": ["readonly"], "values": ["简单", "中等", "复杂"]}, 37 | "grid": {"row":0, "column":5, "sticky":["W", "E"]} 38 | }, 39 | "generatePasswordButton": { 40 | "class": "Button", 41 | "int": {"width": 5}, 42 | "string": {"text": "生成"}, 43 | "command": "generate_password_button_callback", 44 | "grid": {"row":0, "column":6, "sticky":["W", "E"]} 45 | }, 46 | "resultText": { 47 | "class": "Text", 48 | "int": {"width": 60, "height": 20}, 49 | "string": {"wrap": "none"}, 50 | "grid": {"row":1, "column":0, "columnspan":7, "sticky":["W", "E", "N", "S"]} 51 | }, 52 | "TextScrollbarY": { 53 | "class": "Scrollbar", 54 | "string": {"orient": "vertical"}, 55 | "grid": {"row":1, "column":7, "sticky":["N", "S"]} 56 | }, 57 | "TextScrollbarX": { 58 | "class": "Scrollbar", 59 | "string": {"orient": "horizontal"}, 60 | "grid": {"row":2, "column":0, "columnspan":7, "sticky":["W", "E"]} 61 | } 62 | } -------------------------------------------------------------------------------- /idea-365/D038_CryptoTools/libs/Util.py: -------------------------------------------------------------------------------- 1 | import os 2 | import tkinter as tk 3 | 4 | 5 | # 计算文件夹内的文件个数 6 | def count_files(dir_path): 7 | count = 0 8 | for path, subdir, files in os.walk(dir_path): 9 | for f in files: 10 | count += 1 11 | return count 12 | 13 | 14 | def set_combobox_item(combobox, text, fuzzy=False): 15 | for index, value in enumerate(combobox.cget("values")): 16 | if (fuzzy and text in value) or (value == text): 17 | combobox.current(index) 18 | return 19 | combobox.current(0 if len(combobox.cget("values")) else -1) 20 | 21 | 22 | def is_sub_path(output_path, input_path): 23 | input_dir = os.path.abspath(input_path).replace('\\', '/') 24 | output_dir = os.path.abspath(output_path).replace('\\', '/') 25 | if input_dir in output_dir: 26 | return True 27 | else: 28 | return False 29 | 30 | 31 | # 文本选中时的处理 32 | class TextSection(object): 33 | def __init__(self, master_widget, text_area): 34 | self.master_widget = master_widget 35 | self.text_area = text_area 36 | 37 | def on_paste(self): 38 | try: 39 | self.text = self.master_widget.clipboard_get() 40 | except tk.TclError: 41 | pass 42 | try: 43 | self.text_area.delete('sel.first', 'sel.last') 44 | except tk.TclError: 45 | pass 46 | self.text_area.insert(tk.INSERT, self.text) 47 | 48 | def on_copy(self): 49 | self.text = self.text_area.get('sel.first', 'sel.last') 50 | self.master_widget.clipboard_clear() 51 | self.master_widget.clipboard_append(self.text) 52 | 53 | def on_cut(self): 54 | self.on_copy() 55 | try: 56 | self.text_area.delete('sel.first', 'sel.last') 57 | except tk.TclError: 58 | pass 59 | -------------------------------------------------------------------------------- /idea-365/D040_WeiboHotSpider/DailyDownload.py: -------------------------------------------------------------------------------- 1 | import time 2 | import re 3 | import random 4 | from selenium import webdriver 5 | 6 | # 打开浏览器,关闭弹出通知 7 | options = webdriver.ChromeOptions() 8 | prefs = { 9 | 'profile.default_content_setting_values': 10 | { 11 | 'notifications': 2 12 | } 13 | } 14 | options.add_experimental_option('prefs', prefs) 15 | # executable_path中放入所需要的chromedriver,网上下载 16 | wb = webdriver.Chrome(executable_path="./driver/chromedriver.exe", chrome_options=options) 17 | 18 | # 设置浏览器反应时间 19 | wb.implicitly_wait(10) 20 | 21 | # 设置窗口最大化 22 | wb.maximize_window() 23 | 24 | # 设置访问的网站,微博需要先打开首页,再打开实时热点,不然无法获取到实时热点 25 | url = 'https://weibo.com/' 26 | wb.get(url) 27 | 28 | # wb.find_element_by_id('pl_unlogin_home_hots').find_elements_by_class_name("UG_box_foot")[1].click() 29 | 30 | time.sleep(10) 31 | wb.get("https://weibo.com/a/hot/realtime") 32 | 33 | now_year = time.strftime("%Y{y}", time.localtime()).format(y='年',) 34 | now_date = time.strftime("%m{m}%d{d}", time.localtime()).format(m='月', d='日') 35 | print(now_date) 36 | # 将实时热点主网页存入文件中, 自建日期文件夹,防止误操作,格式为 10月18日 37 | with open("./data/" + now_year + "/" + now_date + "/main.html", 'wb') as f: 38 | f.write(wb.page_source.encode("utf-8", "ignore")) # 忽略非法字符 39 | print('写入成功') 40 | 41 | # 获取所有热点的子网页链接 42 | with open("./data/" + now_year + "/" + now_date + "/main.html", 'r', encoding="utf-8") as f: 43 | redian_text = f.read() 44 | 45 | pattern = re.compile(r'

(.*)

') 46 | href_pattern = re.compile(r'href="(.*)\?type=grab"') 47 | href_list = pattern.findall(redian_text) 48 | 49 | index = 0 50 | for zi_href in href_list: 51 | index += 1 52 | r_href = "https://weibo.com/a/hot/" + href_pattern.findall(zi_href)[0] 53 | wb.get(r_href) 54 | time.sleep(random.randint(5, 10)) 55 | # 将当日实时热点的子网页存入文件中 56 | with open("./data/" + now_year + "/" + now_date + "/" + str(index) + ".html", 'wb') as f: 57 | f.write(wb.page_source.encode("utf-8", "ignore")) # 忽略非法字符 58 | print('写入成功' + str(index)) 59 | -------------------------------------------------------------------------------- /idea-365/D040_WeiboHotSpider/DataClean.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | import os 4 | import time 5 | import shutil 6 | import zipfile 7 | 8 | 9 | def get_zip_file(input_path, result): 10 | files = os.listdir(input_path) 11 | for file in files: 12 | if os.path.isdir(input_path + '/' + file): 13 | get_zip_file(input_path + '/' + file, result) 14 | else: 15 | result.append(input_path + '/' + file) 16 | 17 | 18 | def zip_file_path(input_path, output_path, output_name): 19 | f = zipfile.ZipFile(output_path + '/' + output_name, 'w', zipfile.ZIP_DEFLATED) 20 | file_lists = [] 21 | get_zip_file(input_path, file_lists) 22 | for file in file_lists: 23 | f.write(file) 24 | f.close() 25 | return output_path + r"/" + output_name 26 | 27 | 28 | if __name__ == '__main__': 29 | now_year = time.strftime("%Y{y}", time.localtime()).format(y='年', ) 30 | now_date = time.strftime("%m{m}%d{d}", time.localtime()).format(m='月', d='日') 31 | zip_file_path(r"./data/"+now_year+"/"+now_date, './data/back/', now_date+".zip") 32 | # shutil.rmtree(r"./data/2020年/10月20日") 33 | -------------------------------------------------------------------------------- /idea-365/D040_WeiboHotSpider/DataExtract.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | import re 4 | import os 5 | from libs.ORM import * 6 | 7 | 8 | class DailyHotNews(Model): 9 | # 定义类的属性到列的映射: 10 | title = StringField('title') 11 | content = StringField('content') 12 | author = StringField('author') 13 | date = StringField('date') 14 | 15 | 16 | # 处理文件夹 17 | def dir_handle(data_dir): 18 | data_dir_path = os.path.abspath(data_dir) 19 | print(data_dir_path) 20 | 21 | for path, subdir, files in os.walk(data_dir_path): 22 | for f in files: 23 | hot_html = os.path.join(path, f) 24 | if hot_html.find("main") == -1: 25 | save_in_sqlite(*extract(hot_html)) 26 | 27 | 28 | # 处理数据,网页保存的路径格式为 data/2020年/10月18日/***.html 29 | def extract(hot_news_html_path): 30 | # 匹配热点标题 31 | title_pattern = re.compile(r'

(.*?)

', re.DOTALL) 32 | # 匹配热点内容 33 | content_pattern = re.compile(r'
(.*?)
', re.DOTALL) 34 | # 匹配热点的作者和日期时间 35 | author_date_time_pattern = re.compile(r'(.*?)', re.DOTALL) 36 | 37 | with open(hot_news_html_path, 'r', encoding="utf-8") as hf: 38 | dir_date = os.path.basename(os.path.dirname(hot_news_html_path)) 39 | hot_news_text = hf.read() 40 | # 获取热点的标题 41 | title = title_pattern.findall(hot_news_text) 42 | title = title[0].strip() if title else "No Title" 43 | print("Title: " + title) 44 | # 获取热点内容 45 | content = content_pattern.findall(hot_news_text) 46 | content = content[0].strip() if title else "No Content" 47 | print("Content: " + content) 48 | # 获取热点作者 49 | author_date_time = author_date_time_pattern.findall(hot_news_text) 50 | author = author_date_time[0].strip() if author_date_time else "No author" 51 | print("Author: " + author) 52 | # 获取日期和时间 53 | date_time = author_date_time[1].strip() if author_date_time else "No date and time" 54 | date_time = date_time if date_time.find("今天") == -1 else date_time.replace("今天", dir_date) 55 | print("Date Time: " + date_time) 56 | print("\n\n") 57 | return title, content, author, date_time 58 | 59 | 60 | # 存入数据库文件 61 | def save_in_sqlite(title, content, author, date_time): 62 | # 新建数据库和数据表 63 | if not DailyHotNews.has_table(): 64 | DailyHotNews.new_table() 65 | news = DailyHotNews(title=title, content=content, author=author, date=date_time) 66 | news.save() 67 | 68 | 69 | dir_handle("./data/2020年") 70 | -------------------------------------------------------------------------------- /idea-365/D040_WeiboHotSpider/libs/Key.py: -------------------------------------------------------------------------------- 1 | import hashlib 2 | import random 3 | 4 | LOW_LEVEL = ['1', '2', '3', '4', '5', '6', '7', '8', '9', '0'] 5 | 6 | MEDIUM_LEVEL = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 7 | 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 8 | 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 9 | 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 10 | '1', '2', '3', '4', '5', '6', '7', '8', '9', '0'] 11 | 12 | HIGH_LEVEL = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 13 | 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 14 | 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 15 | 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 16 | '!', '@', '#', '$', '%', '^', '&', '*', '-', '_', '=', 17 | '+', '1', '2', '3', '4', '5', '6', '7', '8', '9', '0'] 18 | 19 | 20 | # 根据密码长度与复杂度,生成随机密码 21 | def generate_password(length, level): 22 | return ''.join([random.choice(level) for i in range(0, length)]) 23 | 24 | 25 | # b'\0'填充密码 26 | def null_pad(data_to_pad): 27 | data_len = len(data_to_pad) 28 | # 不超过128位的密码填充长度(字节单位) 29 | if data_len <= 16: 30 | key_len = 16 31 | # 128位以上,不超过192位的密码填充长度(字节单位) 32 | elif 16 < data_len <= 24: 33 | key_len = 24 34 | # 192位以上,不超过256位的密码填充长度(字节单位) 35 | elif 24 < data_len <= 32: 36 | key_len = 32 37 | # 超过256位的密码直接截断到256位长度 38 | else: 39 | return data_to_pad[:32] 40 | # 进行'\0'填充 41 | padding_len = key_len - len(data_to_pad) 42 | padding = b'\0' * padding_len 43 | return data_to_pad + padding 44 | 45 | 46 | # 生成密钥 47 | def gen_aes_key(password, salt, use_md5): 48 | # 将密码加盐,防止泄露原始密码 49 | password = password + salt if salt else password 50 | # use_md5为True值时,将密码转为md5值作为密钥,否则使用b'\0'填充密码 51 | if use_md5: 52 | md5 = hashlib.md5() 53 | md5.update(password.encode('utf-8')) 54 | key = md5.digest() 55 | else: 56 | key = null_pad(password.encode('utf-8')) 57 | 58 | return key -------------------------------------------------------------------------------- /idea-365/D041_MusicJsonToSqlite/transform.py: -------------------------------------------------------------------------------- 1 | import json 2 | from CryptoFactory.ORM import * 3 | 4 | 5 | class MusicInfo(Model): 6 | # 定义类的属性到列的映射: 7 | id = IntegerField('id', primary_key=True) 8 | music_name = StringField('music_name') 9 | music_star = StringField('music_star') 10 | play_count = IntegerField('play_count') 11 | tag = StringField('tag') 12 | 13 | 14 | def read_from_json(json_path): 15 | music_play_times_dict = {} 16 | star_index_path_list = [] 17 | if os.path.exists(json_path): 18 | with open(json_path, "r") as f: 19 | music_info = json.load(f) 20 | if music_info.get("music_play_times_dict"): 21 | music_play_times_dict = music_info.get("music_play_times_dict") 22 | if music_info.get("star_index_path_list"): 23 | star_index_path_list = music_info.get("star_index_path_list") 24 | 25 | # 新建数据库和数据表 26 | if not MusicInfo.has_table(): 27 | MusicInfo.new_table() 28 | 29 | for k, v in music_play_times_dict.items(): 30 | if k in star_index_path_list: 31 | music_star = "true" 32 | else: 33 | music_star = "false" 34 | m = MusicInfo(music_name=k, music_star=music_star, play_count=v, tag="") 35 | m.save() 36 | 37 | 38 | read_from_json("2cc99dd79dac4bba674e11560d4612d4.json") 39 | -------------------------------------------------------------------------------- /idea-365/README.md: -------------------------------------------------------------------------------- 1 | # idea-365 2 | 每天的记录、代码练习、小工具、思考碎片等。 3 | -------------------------------------------------------------------------------- /javademo/CopyDemo.java: -------------------------------------------------------------------------------- 1 | import java.io.File; 2 | import java.io.FileInputStream; 3 | import java.io.FileOutputStream; 4 | import java.io.InputStream; 5 | import java.io.OutputStream; 6 | 7 | /** 模拟DOS系统中的COPY程序 8 | * 命令行参数 ( 源文件 目标文件) 9 | */ 10 | public class CopyDemo { 11 | 12 | public static void main(String[] args) throws Exception{ 13 | long start = System.currentTimeMillis(); 14 | if(args.length != 2) { //初始化参数不足两位 15 | System.out.println("命令执行错误!"); 16 | System.exit(1); //程序退出执行 17 | } 18 | // 如果输入参数正确了,那么应该进行文件的验证 19 | File inFile = new File(args[0]); //第一个为源文件路径 20 | if (!inFile.exists()) { //源文件不存在 21 | System.out.println("源文件不存在,请确认执行路径。"); 22 | System.exit(1); //程序退出 23 | } 24 | // 如果此时源文件正确,那么就需要定义输出文件,同时考虑到输出文件有目录 25 | File outFile = new File(args[1]); 26 | if (!outFile.getParentFile().exists()) { 27 | outFile.getParentFile().mkdirs(); //创建目录 28 | } 29 | // 实现文件内容的拷贝 30 | InputStream input = new FileInputStream(inFile); 31 | OutputStream output = new FileOutputStream(outFile); 32 | // 实现文件拷贝 33 | int temp = 0; //保存每次读取的个数 34 | byte data[] = new byte [2048]; // 每次读取2048个字节 35 | // 将每次读取的数据保存在字节数组里面,并且返回读取的个数 36 | while((temp = input.read(data)) != -1) { 37 | output.write(data, 0, temp); //输出数组 38 | } 39 | input.close(); 40 | output.close(); 41 | long end = System.currentTimeMillis(); 42 | System.out.println("拷贝完成!\n花费的时间:" + (end - start) + "毫秒"); 43 | } 44 | 45 | } 46 | -------------------------------------------------------------------------------- /javademo/DAOProject/.classpath: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | -------------------------------------------------------------------------------- /javademo/DAOProject/.project: -------------------------------------------------------------------------------- 1 | 2 | 3 | DAOProject 4 | 5 | 6 | 7 | 8 | 9 | org.eclipse.jdt.core.javabuilder 10 | 11 | 12 | 13 | 14 | 15 | org.eclipse.jdt.core.javanature 16 | 17 | 18 | -------------------------------------------------------------------------------- /javademo/DAOProject/.settings/org.eclipse.jdt.core.prefs: -------------------------------------------------------------------------------- 1 | eclipse.preferences.version=1 2 | org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=enabled 3 | org.eclipse.jdt.core.compiler.codegen.methodParameters=do not generate 4 | org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.8 5 | org.eclipse.jdt.core.compiler.codegen.unusedLocal=preserve 6 | org.eclipse.jdt.core.compiler.compliance=1.8 7 | org.eclipse.jdt.core.compiler.debug.lineNumber=generate 8 | org.eclipse.jdt.core.compiler.debug.localVariable=generate 9 | org.eclipse.jdt.core.compiler.debug.sourceFile=generate 10 | org.eclipse.jdt.core.compiler.problem.assertIdentifier=error 11 | org.eclipse.jdt.core.compiler.problem.enumIdentifier=error 12 | org.eclipse.jdt.core.compiler.source=1.8 13 | -------------------------------------------------------------------------------- /javademo/DAOProject/src/README.md: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/cforth/codefarm/cabd0ec1e9fb2a2aa582682b1a4016378e8515dc/javademo/DAOProject/src/README.md -------------------------------------------------------------------------------- /javademo/DAOProject/src/com/cfxyz/dao/IDAO.java: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/cforth/codefarm/cabd0ec1e9fb2a2aa582682b1a4016378e8515dc/javademo/DAOProject/src/com/cfxyz/dao/IDAO.java -------------------------------------------------------------------------------- /javademo/DAOProject/src/com/cfxyz/dao/IDeptDAO.java: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/cforth/codefarm/cabd0ec1e9fb2a2aa582682b1a4016378e8515dc/javademo/DAOProject/src/com/cfxyz/dao/IDeptDAO.java -------------------------------------------------------------------------------- /javademo/DAOProject/src/com/cfxyz/dao/IEmpDAO.java: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/cforth/codefarm/cabd0ec1e9fb2a2aa582682b1a4016378e8515dc/javademo/DAOProject/src/com/cfxyz/dao/IEmpDAO.java -------------------------------------------------------------------------------- /javademo/DAOProject/src/com/cfxyz/dao/impl/DeptDAOImpl.java: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/cforth/codefarm/cabd0ec1e9fb2a2aa582682b1a4016378e8515dc/javademo/DAOProject/src/com/cfxyz/dao/impl/DeptDAOImpl.java -------------------------------------------------------------------------------- /javademo/DAOProject/src/com/cfxyz/dao/impl/EmpDAOImpl.java: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/cforth/codefarm/cabd0ec1e9fb2a2aa582682b1a4016378e8515dc/javademo/DAOProject/src/com/cfxyz/dao/impl/EmpDAOImpl.java -------------------------------------------------------------------------------- /javademo/DAOProject/src/com/cfxyz/dbc/DatabaseConnection.java: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/cforth/codefarm/cabd0ec1e9fb2a2aa582682b1a4016378e8515dc/javademo/DAOProject/src/com/cfxyz/dbc/DatabaseConnection.java -------------------------------------------------------------------------------- /javademo/DAOProject/src/com/cfxyz/factory/DAOFactory.java: -------------------------------------------------------------------------------- 1 | package com.cfxyz.factory; 2 | 3 | import java.sql.Connection; 4 | 5 | import com.cfxyz.dao.IDeptDAO; 6 | import com.cfxyz.dao.IEmpDAO; 7 | import com.cfxyz.dao.impl.DeptDAOImpl; 8 | import com.cfxyz.dao.impl.EmpDAOImpl; 9 | 10 | public class DAOFactory { 11 | public static IEmpDAO getIEmpDAOInstance(Connection conn) { 12 | return new EmpDAOImpl(conn); 13 | } 14 | public static IDeptDAO getIDeptDAOInstance(Connection conn) { 15 | return new DeptDAOImpl(conn); 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /javademo/DAOProject/src/com/cfxyz/factory/ServiceFactory.java: -------------------------------------------------------------------------------- 1 | package com.cfxyz.factory; 2 | 3 | import com.cfxyz.service.IDeptService; 4 | import com.cfxyz.service.IEmpService; 5 | import com.cfxyz.service.impl.DeptServiceImpl; 6 | import com.cfxyz.service.impl.EmpServiceImpl; 7 | 8 | public class ServiceFactory { 9 | public static IEmpService getIEmpServiceInstance() { 10 | return new EmpServiceImpl(); 11 | } 12 | public static IDeptService getIDeptServiceInstance() { 13 | return new DeptServiceImpl(); 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /javademo/DAOProject/src/com/cfxyz/service/IDeptService.java: -------------------------------------------------------------------------------- 1 | package com.cfxyz.service; 2 | 3 | import java.util.List; 4 | import java.util.Set; 5 | 6 | import com.cfxyz.vo.Dept; 7 | 8 | public interface IDeptService { 9 | 10 | public boolean insert(Dept vo) throws Exception ; 11 | public boolean update(Dept vo) throws Exception ; 12 | public boolean delete(Set ids) throws Exception ; 13 | public Dept get(int id) throws Exception ; 14 | public List list() throws Exception ; 15 | } 16 | -------------------------------------------------------------------------------- /javademo/DAOProject/src/com/cfxyz/service/IEmpService.java: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/cforth/codefarm/cabd0ec1e9fb2a2aa582682b1a4016378e8515dc/javademo/DAOProject/src/com/cfxyz/service/IEmpService.java -------------------------------------------------------------------------------- /javademo/DAOProject/src/com/cfxyz/service/impl/DeptServiceImpl.java: -------------------------------------------------------------------------------- 1 | package com.cfxyz.service.impl; 2 | 3 | import java.util.List; 4 | import java.util.Set; 5 | 6 | import com.cfxyz.dbc.DatabaseConnection; 7 | import com.cfxyz.factory.DAOFactory; 8 | import com.cfxyz.service.IDeptService; 9 | import com.cfxyz.vo.Dept; 10 | 11 | public class DeptServiceImpl implements IDeptService { 12 | private DatabaseConnection dbc = new DatabaseConnection(); 13 | 14 | @Override 15 | public boolean insert(Dept vo) throws Exception { 16 | try { 17 | if(DAOFactory.getIDeptDAOInstance(this.dbc.getConnection()).findById(vo.getDeptno()) == null) { 18 | return DAOFactory.getIDeptDAOInstance(this.dbc.getConnection()).doCreate(vo); 19 | } 20 | return false; 21 | } catch (Exception e) { 22 | throw e; 23 | } finally { 24 | this.dbc.close(); 25 | } 26 | } 27 | 28 | @Override 29 | public boolean update(Dept vo) throws Exception { 30 | try { 31 | return DAOFactory.getIDeptDAOInstance(this.dbc.getConnection()).doUpdate(vo); 32 | } catch (Exception e) { 33 | throw e; 34 | } finally { 35 | this.dbc.close(); 36 | } 37 | } 38 | 39 | @Override 40 | public boolean delete(Set ids) throws Exception { 41 | try { 42 | return DAOFactory.getIDeptDAOInstance(this.dbc.getConnection()).doRemoveBatch(ids); 43 | } catch (Exception e) { 44 | throw e; 45 | } finally { 46 | this.dbc.close(); 47 | } 48 | } 49 | 50 | @Override 51 | public Dept get(int id) throws Exception { 52 | try { 53 | return DAOFactory.getIDeptDAOInstance(this.dbc.getConnection()).findById(id) ; 54 | } catch (Exception e) { 55 | throw e; 56 | } finally { 57 | this.dbc.close(); 58 | } 59 | } 60 | 61 | @Override 62 | public List list() throws Exception { 63 | try { 64 | return DAOFactory.getIDeptDAOInstance(this.dbc.getConnection()).findAll(); 65 | } catch (Exception e) { 66 | throw e; 67 | } finally { 68 | this.dbc.close(); 69 | } 70 | } 71 | 72 | } 73 | -------------------------------------------------------------------------------- /javademo/DAOProject/src/com/cfxyz/service/impl/EmpServiceImpl.java: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/cforth/codefarm/cabd0ec1e9fb2a2aa582682b1a4016378e8515dc/javademo/DAOProject/src/com/cfxyz/service/impl/EmpServiceImpl.java -------------------------------------------------------------------------------- /javademo/DAOProject/src/com/cfxyz/test/TestEmpInsert.java: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/cforth/codefarm/cabd0ec1e9fb2a2aa582682b1a4016378e8515dc/javademo/DAOProject/src/com/cfxyz/test/TestEmpInsert.java -------------------------------------------------------------------------------- /javademo/DAOProject/src/com/cfxyz/test/TestEmpSplit.java: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/cforth/codefarm/cabd0ec1e9fb2a2aa582682b1a4016378e8515dc/javademo/DAOProject/src/com/cfxyz/test/TestEmpSplit.java -------------------------------------------------------------------------------- /javademo/DAOProject/src/com/cfxyz/test/junit/IDeptServiceTest.java: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/cforth/codefarm/cabd0ec1e9fb2a2aa582682b1a4016378e8515dc/javademo/DAOProject/src/com/cfxyz/test/junit/IDeptServiceTest.java -------------------------------------------------------------------------------- /javademo/DAOProject/src/com/cfxyz/test/junit/IEmpServiceTest.java: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/cforth/codefarm/cabd0ec1e9fb2a2aa582682b1a4016378e8515dc/javademo/DAOProject/src/com/cfxyz/test/junit/IEmpServiceTest.java -------------------------------------------------------------------------------- /javademo/DAOProject/src/com/cfxyz/vo/Dept.java: -------------------------------------------------------------------------------- 1 | package com.cfxyz.vo; 2 | 3 | import java.io.Serializable; 4 | 5 | @SuppressWarnings("serial") 6 | public class Dept implements Serializable { 7 | private Integer deptno; 8 | private String dname ; 9 | private String loc ; 10 | public Integer getDeptno() { 11 | return deptno; 12 | } 13 | public void setDeptno(Integer deptno) { 14 | this.deptno = deptno; 15 | } 16 | public String getDname() { 17 | return dname; 18 | } 19 | public void setDname(String dname) { 20 | this.dname = dname; 21 | } 22 | public String getLoc() { 23 | return loc; 24 | } 25 | public void setLoc(String loc) { 26 | this.loc = loc; 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /javademo/DAOProject/src/com/cfxyz/vo/Emp.java: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/cforth/codefarm/cabd0ec1e9fb2a2aa582682b1a4016378e8515dc/javademo/DAOProject/src/com/cfxyz/vo/Emp.java -------------------------------------------------------------------------------- /javademo/EchoClient.java: -------------------------------------------------------------------------------- 1 | import java.io.PrintStream; 2 | import java.net.Socket; 3 | import java.util.Scanner; 4 | 5 | public class EchoClient { 6 | 7 | public static void main(String[] args) throws Exception { 8 | Socket client = new Socket("localhost", 9999); //连接服务端 9 | Scanner input = new Scanner(System.in); 10 | Scanner scan = new Scanner(client.getInputStream()); 11 | input.useDelimiter("\n"); 12 | scan.useDelimiter("\n"); 13 | PrintStream out = new PrintStream(client.getOutputStream()); 14 | boolean flag = true; 15 | while(flag) { 16 | System.out.print("请输入要发送的数据:"); 17 | if(input.hasNext()) { 18 | String str = input.next().trim(); 19 | out.println(str); //发送服务器端数据 20 | if(str.equalsIgnoreCase("byebye")) { 21 | flag = false; //结束循环 22 | } 23 | if(scan.hasNext()) { 24 | System.out.println(scan.next()); 25 | } 26 | } 27 | } 28 | input.close(); 29 | scan.close(); 30 | out.close(); 31 | client.close(); 32 | } 33 | 34 | } 35 | -------------------------------------------------------------------------------- /javademo/EchoServer.java: -------------------------------------------------------------------------------- 1 | import java.io.PrintStream; 2 | import java.net.ServerSocket; 3 | import java.net.Socket; 4 | import java.util.Scanner; 5 | 6 | class EchoThread implements Runnable { 7 | private Socket client; 8 | public EchoThread(Socket client) { 9 | this.client = client; 10 | } 11 | 12 | @Override 13 | public void run() { 14 | try { 15 | // 得到客户端输入数据以及向客户端输出数据的对象 16 | Scanner scan = new Scanner(client.getInputStream()); 17 | PrintStream out = new PrintStream(client.getOutputStream()); 18 | boolean flag = true; 19 | while(flag) { 20 | if(scan.hasNext()) { 21 | String str = scan.next().trim(); //得到客户端发送的内容 22 | if(str.equalsIgnoreCase("byebye")) { 23 | out.println("拜拜,下次再会!"); //程序要结束 24 | flag = false; 25 | } else { //回应输入信息 26 | out.println("ECHO : " + str); 27 | } 28 | } 29 | } 30 | System.out.println("客户端关闭连接....."); 31 | scan.close(); 32 | out.close(); 33 | client.close(); 34 | }catch(Exception e){ 35 | e.printStackTrace(); 36 | } 37 | } 38 | } 39 | 40 | public class EchoServer { 41 | 42 | public static void main(String[] args) throws Exception { 43 | ServerSocket server = new ServerSocket(9999); 44 | System.out.println("等待连接....."); 45 | boolean flag = true; 46 | while(flag) { 47 | Socket client = server.accept(); //连接客户端 48 | new Thread(new EchoThread(client)).start(); 49 | System.out.println("客户端已经连接....."); 50 | } 51 | server.close(); 52 | } 53 | 54 | } 55 | -------------------------------------------------------------------------------- /javademo/HelloClient.java: -------------------------------------------------------------------------------- 1 | import java.net.Socket; 2 | import java.util.Scanner; 3 | 4 | public class HelloClient { 5 | 6 | public static void main(String[] args) throws Exception { 7 | Socket client = new Socket("localhost", 9999); //连接服务器端 8 | //取得客户端的输入数据流对象,表示接收服务器端的输出信息 9 | Scanner scan = new Scanner(client.getInputStream()); 10 | scan.useDelimiter("\n"); 11 | if(scan.hasNext()) { 12 | System.out.println("【回应数据】" + scan.next()); 13 | } 14 | System.out.println("关闭客户端连接"); 15 | scan.close(); 16 | client.close(); 17 | } 18 | 19 | } -------------------------------------------------------------------------------- /javademo/HelloServer.java: -------------------------------------------------------------------------------- 1 | import java.io.PrintStream; 2 | import java.net.ServerSocket; 3 | import java.net.Socket; 4 | 5 | public class HelloServer { 6 | 7 | public static void main(String[] args) throws Exception { 8 | ServerSocket server = new ServerSocket(9999); 9 | System.out.println("等待客户端连接....."); 10 | Socket client = server.accept(); //等待客户端连接 11 | //利用打印流完成输出 12 | PrintStream out = new PrintStream(client.getOutputStream()); 13 | out.println("Hello World!"); 14 | System.out.println("关闭服务器端连接"); 15 | out.close(); 16 | client.close(); 17 | server.close(); 18 | } 19 | 20 | } -------------------------------------------------------------------------------- /javademo/MyProject/.classpath: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | -------------------------------------------------------------------------------- /javademo/MyProject/.project: -------------------------------------------------------------------------------- 1 | 2 | 3 | MyProject 4 | 5 | 6 | 7 | 8 | 9 | org.eclipse.jdt.core.javabuilder 10 | 11 | 12 | 13 | 14 | 15 | org.eclipse.jdt.core.javanature 16 | 17 | 18 | -------------------------------------------------------------------------------- /javademo/MyProject/.settings/org.eclipse.jdt.core.prefs: -------------------------------------------------------------------------------- 1 | eclipse.preferences.version=1 2 | org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=enabled 3 | org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.8 4 | org.eclipse.jdt.core.compiler.codegen.unusedLocal=preserve 5 | org.eclipse.jdt.core.compiler.compliance=1.8 6 | org.eclipse.jdt.core.compiler.debug.lineNumber=generate 7 | org.eclipse.jdt.core.compiler.debug.localVariable=generate 8 | org.eclipse.jdt.core.compiler.debug.sourceFile=generate 9 | org.eclipse.jdt.core.compiler.problem.assertIdentifier=error 10 | org.eclipse.jdt.core.compiler.problem.enumIdentifier=error 11 | org.eclipse.jdt.core.compiler.source=1.8 12 | -------------------------------------------------------------------------------- /javademo/MyProject/src/com/cfxyz/demo/CopyDemo.java: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/cforth/codefarm/cabd0ec1e9fb2a2aa582682b1a4016378e8515dc/javademo/MyProject/src/com/cfxyz/demo/CopyDemo.java -------------------------------------------------------------------------------- /javademo/MyProject/src/com/cfxyz/demo/EchoClient.java: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/cforth/codefarm/cabd0ec1e9fb2a2aa582682b1a4016378e8515dc/javademo/MyProject/src/com/cfxyz/demo/EchoClient.java -------------------------------------------------------------------------------- /javademo/MyProject/src/com/cfxyz/demo/EchoServer.java: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/cforth/codefarm/cabd0ec1e9fb2a2aa582682b1a4016378e8515dc/javademo/MyProject/src/com/cfxyz/demo/EchoServer.java -------------------------------------------------------------------------------- /javademo/MyProject/src/com/cfxyz/demo/Hello.java: -------------------------------------------------------------------------------- 1 | package com.cfxyz.demo; 2 | 3 | class Foo { 4 | public Foo(Object x) { 5 | System.out.println(x); 6 | } 7 | } 8 | 9 | public class Hello { 10 | 11 | public static void main(String[] args) { 12 | int x = 0 ; 13 | Object y = null; 14 | Integer xxx = new Integer(x); 15 | Foo fx = new Foo(xxx); 16 | Foo fy = new Foo(y); 17 | 18 | } 19 | 20 | } 21 | -------------------------------------------------------------------------------- /javademo/MyProject/src/com/cfxyz/demo/HelloClient.java: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/cforth/codefarm/cabd0ec1e9fb2a2aa582682b1a4016378e8515dc/javademo/MyProject/src/com/cfxyz/demo/HelloClient.java -------------------------------------------------------------------------------- /javademo/MyProject/src/com/cfxyz/demo/HelloServer.java: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/cforth/codefarm/cabd0ec1e9fb2a2aa582682b1a4016378e8515dc/javademo/MyProject/src/com/cfxyz/demo/HelloServer.java -------------------------------------------------------------------------------- /javademo/MyProject/src/com/cfxyz/demo/TestArrayList.java: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/cforth/codefarm/cabd0ec1e9fb2a2aa582682b1a4016378e8515dc/javademo/MyProject/src/com/cfxyz/demo/TestArrayList.java -------------------------------------------------------------------------------- /javademo/MyProject/src/com/cfxyz/demo/TestArrays.java: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/cforth/codefarm/cabd0ec1e9fb2a2aa582682b1a4016378e8515dc/javademo/MyProject/src/com/cfxyz/demo/TestArrays.java -------------------------------------------------------------------------------- /javademo/MyProject/src/com/cfxyz/demo/TestBatch.java: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/cforth/codefarm/cabd0ec1e9fb2a2aa582682b1a4016378e8515dc/javademo/MyProject/src/com/cfxyz/demo/TestBatch.java -------------------------------------------------------------------------------- /javademo/MyProject/src/com/cfxyz/demo/TestBinaryTree.java: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/cforth/codefarm/cabd0ec1e9fb2a2aa582682b1a4016378e8515dc/javademo/MyProject/src/com/cfxyz/demo/TestBinaryTree.java -------------------------------------------------------------------------------- /javademo/MyProject/src/com/cfxyz/demo/TestClass.java: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/cforth/codefarm/cabd0ec1e9fb2a2aa582682b1a4016378e8515dc/javademo/MyProject/src/com/cfxyz/demo/TestClass.java -------------------------------------------------------------------------------- /javademo/MyProject/src/com/cfxyz/demo/TestClone.java: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/cforth/codefarm/cabd0ec1e9fb2a2aa582682b1a4016378e8515dc/javademo/MyProject/src/com/cfxyz/demo/TestClone.java -------------------------------------------------------------------------------- /javademo/MyProject/src/com/cfxyz/demo/TestCollections.java: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/cforth/codefarm/cabd0ec1e9fb2a2aa582682b1a4016378e8515dc/javademo/MyProject/src/com/cfxyz/demo/TestCollections.java -------------------------------------------------------------------------------- /javademo/MyProject/src/com/cfxyz/demo/TestDate.java: -------------------------------------------------------------------------------- 1 | package com.cfxyz.demo; 2 | 3 | import java.util.Date; 4 | 5 | public class TestDate { 6 | 7 | public static void main(String[] args) { 8 | long cur = System.currentTimeMillis(); 9 | Date date = new Date(cur); 10 | System.out.println(date); 11 | System.out.println(date.getTime()); 12 | } 13 | 14 | } 15 | -------------------------------------------------------------------------------- /javademo/MyProject/src/com/cfxyz/demo/TestDemo.java: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/cforth/codefarm/cabd0ec1e9fb2a2aa582682b1a4016378e8515dc/javademo/MyProject/src/com/cfxyz/demo/TestDemo.java -------------------------------------------------------------------------------- /javademo/MyProject/src/com/cfxyz/demo/TestFactory.java: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/cforth/codefarm/cabd0ec1e9fb2a2aa582682b1a4016378e8515dc/javademo/MyProject/src/com/cfxyz/demo/TestFactory.java -------------------------------------------------------------------------------- /javademo/MyProject/src/com/cfxyz/demo/TestFile.java: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/cforth/codefarm/cabd0ec1e9fb2a2aa582682b1a4016378e8515dc/javademo/MyProject/src/com/cfxyz/demo/TestFile.java -------------------------------------------------------------------------------- /javademo/MyProject/src/com/cfxyz/demo/TestFileOld.java: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/cforth/codefarm/cabd0ec1e9fb2a2aa582682b1a4016378e8515dc/javademo/MyProject/src/com/cfxyz/demo/TestFileOld.java -------------------------------------------------------------------------------- /javademo/MyProject/src/com/cfxyz/demo/TestJDBC.java: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/cforth/codefarm/cabd0ec1e9fb2a2aa582682b1a4016378e8515dc/javademo/MyProject/src/com/cfxyz/demo/TestJDBC.java -------------------------------------------------------------------------------- /javademo/MyProject/src/com/cfxyz/demo/TestMap.java: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/cforth/codefarm/cabd0ec1e9fb2a2aa582682b1a4016378e8515dc/javademo/MyProject/src/com/cfxyz/demo/TestMap.java -------------------------------------------------------------------------------- /javademo/MyProject/src/com/cfxyz/demo/TestMapReduce.java: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/cforth/codefarm/cabd0ec1e9fb2a2aa582682b1a4016378e8515dc/javademo/MyProject/src/com/cfxyz/demo/TestMapReduce.java -------------------------------------------------------------------------------- /javademo/MyProject/src/com/cfxyz/demo/TestMath.java: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/cforth/codefarm/cabd0ec1e9fb2a2aa582682b1a4016378e8515dc/javademo/MyProject/src/com/cfxyz/demo/TestMath.java -------------------------------------------------------------------------------- /javademo/MyProject/src/com/cfxyz/demo/TestMemoryStream.java: -------------------------------------------------------------------------------- 1 | package com.cfxyz.demo; 2 | 3 | import java.io.ByteArrayOutputStream; 4 | import java.io.File; 5 | import java.io.FileInputStream; 6 | import java.io.InputStream; 7 | 8 | public class TestMemoryStream { 9 | 10 | public static void main(String[] args) throws Exception { 11 | File fileA = new File("E:" + File.separator + "infoa.txt"); 12 | File fileB = new File("E:" + File.separator + "infob.txt"); 13 | InputStream inputA = new FileInputStream(fileA); 14 | InputStream inputB = new FileInputStream(fileB); 15 | ByteArrayOutputStream output = new ByteArrayOutputStream(); 16 | int temp = 0; 17 | while((temp = inputA.read()) != -1) { 18 | output.write(temp); 19 | } 20 | while((temp = inputB.read()) != -1) { 21 | output.write(temp); 22 | } 23 | byte data[] = output.toByteArray(); 24 | System.out.println(new String(data)); 25 | inputA.close(); 26 | inputB.close(); 27 | output.close(); 28 | } 29 | 30 | } 31 | -------------------------------------------------------------------------------- /javademo/MyProject/src/com/cfxyz/demo/TestPrint.java: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/cforth/codefarm/cabd0ec1e9fb2a2aa582682b1a4016378e8515dc/javademo/MyProject/src/com/cfxyz/demo/TestPrint.java -------------------------------------------------------------------------------- /javademo/MyProject/src/com/cfxyz/demo/TestPrintStream.java: -------------------------------------------------------------------------------- 1 | package com.cfxyz.demo; 2 | 3 | import java.io.File; 4 | import java.io.FileOutputStream; 5 | import java.io.PrintStream; 6 | 7 | public class TestPrintStream { 8 | 9 | public static void main(String[] args) throws Exception { 10 | PrintStream pu = new PrintStream(new FileOutputStream(new File("e:" + File.separator + "test.txt"))); 11 | pu.print("Hello "); 12 | pu.print("World "); 13 | pu.println(3 + 34); 14 | pu.println(23.3 + 33.4); 15 | pu.close(); 16 | } 17 | 18 | } 19 | -------------------------------------------------------------------------------- /javademo/MyProject/src/com/cfxyz/demo/TestProperties.java: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/cforth/codefarm/cabd0ec1e9fb2a2aa582682b1a4016378e8515dc/javademo/MyProject/src/com/cfxyz/demo/TestProperties.java -------------------------------------------------------------------------------- /javademo/MyProject/src/com/cfxyz/demo/TestRegex.java: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/cforth/codefarm/cabd0ec1e9fb2a2aa582682b1a4016378e8515dc/javademo/MyProject/src/com/cfxyz/demo/TestRegex.java -------------------------------------------------------------------------------- /javademo/MyProject/src/com/cfxyz/demo/TestResource.java: -------------------------------------------------------------------------------- 1 | package com.cfxyz.demo; 2 | 3 | import java.text.MessageFormat; 4 | import java.util.Locale; 5 | import java.util.ResourceBundle; 6 | 7 | public class TestResource { 8 | 9 | public static void main(String[] args) { 10 | @SuppressWarnings("unused") 11 | Locale locUS = new Locale("en", "US"); 12 | Locale locCN = new Locale("zh", "CN"); 13 | ResourceBundle rb = ResourceBundle.getBundle("Messages", locCN); 14 | String str = rb.getString("wel.msg"); 15 | System.out.println(MessageFormat.format(str, "CF")); 16 | } 17 | 18 | } 19 | -------------------------------------------------------------------------------- /javademo/MyProject/src/com/cfxyz/demo/TestRuntime.java: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/cforth/codefarm/cabd0ec1e9fb2a2aa582682b1a4016378e8515dc/javademo/MyProject/src/com/cfxyz/demo/TestRuntime.java -------------------------------------------------------------------------------- /javademo/MyProject/src/com/cfxyz/demo/TestScanner.java: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/cforth/codefarm/cabd0ec1e9fb2a2aa582682b1a4016378e8515dc/javademo/MyProject/src/com/cfxyz/demo/TestScanner.java -------------------------------------------------------------------------------- /javademo/MyProject/src/com/cfxyz/demo/TestSerializable.java: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/cforth/codefarm/cabd0ec1e9fb2a2aa582682b1a4016378e8515dc/javademo/MyProject/src/com/cfxyz/demo/TestSerializable.java -------------------------------------------------------------------------------- /javademo/MyProject/src/com/cfxyz/demo/TestSet.java: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/cforth/codefarm/cabd0ec1e9fb2a2aa582682b1a4016378e8515dc/javademo/MyProject/src/com/cfxyz/demo/TestSet.java -------------------------------------------------------------------------------- /javademo/MyProject/src/com/cfxyz/demo/TestSimpleDateFormat.java: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/cforth/codefarm/cabd0ec1e9fb2a2aa582682b1a4016378e8515dc/javademo/MyProject/src/com/cfxyz/demo/TestSimpleDateFormat.java -------------------------------------------------------------------------------- /javademo/MyProject/src/com/cfxyz/demo/TestStream.java: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/cforth/codefarm/cabd0ec1e9fb2a2aa582682b1a4016378e8515dc/javademo/MyProject/src/com/cfxyz/demo/TestStream.java -------------------------------------------------------------------------------- /javademo/MyProject/src/com/cfxyz/demo/TestStringBuffer.java: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/cforth/codefarm/cabd0ec1e9fb2a2aa582682b1a4016378e8515dc/javademo/MyProject/src/com/cfxyz/demo/TestStringBuffer.java -------------------------------------------------------------------------------- /javademo/MyProject/src/com/cfxyz/demo/TestSystem.java: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/cforth/codefarm/cabd0ec1e9fb2a2aa582682b1a4016378e8515dc/javademo/MyProject/src/com/cfxyz/demo/TestSystem.java -------------------------------------------------------------------------------- /javademo/MyProject/src/com/cfxyz/demo/TestSystemin.java: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/cforth/codefarm/cabd0ec1e9fb2a2aa582682b1a4016378e8515dc/javademo/MyProject/src/com/cfxyz/demo/TestSystemin.java -------------------------------------------------------------------------------- /javademo/MyProject/src/com/cfxyz/demo/TestSystemout.java: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/cforth/codefarm/cabd0ec1e9fb2a2aa582682b1a4016378e8515dc/javademo/MyProject/src/com/cfxyz/demo/TestSystemout.java -------------------------------------------------------------------------------- /javademo/MyProject/src/com/cfxyz/demo/TestThread.java: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/cforth/codefarm/cabd0ec1e9fb2a2aa582682b1a4016378e8515dc/javademo/MyProject/src/com/cfxyz/demo/TestThread.java -------------------------------------------------------------------------------- /javademo/MyProject/src/com/cfxyz/demo/TestThread2.java: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/cforth/codefarm/cabd0ec1e9fb2a2aa582682b1a4016378e8515dc/javademo/MyProject/src/com/cfxyz/demo/TestThread2.java -------------------------------------------------------------------------------- /javademo/MyProject/src/com/cfxyz/demo/testPreparedStatement.java: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/cforth/codefarm/cabd0ec1e9fb2a2aa582682b1a4016378e8515dc/javademo/MyProject/src/com/cfxyz/demo/testPreparedStatement.java -------------------------------------------------------------------------------- /javademo/MyProject/src/com/cfxyz/test/MyMathTest.java: -------------------------------------------------------------------------------- 1 | package com.cfxyz.test; 2 | 3 | import org.junit.Test; 4 | 5 | import com.cfxyz.util.MyMath; 6 | 7 | import junit.framework.TestCase; 8 | 9 | public class MyMathTest { 10 | 11 | @Test 12 | public void testDiv() { 13 | try { 14 | TestCase.assertEquals(MyMath.mydiv(10,2), 5); 15 | } catch (Exception e) { 16 | // TODO Auto-generated catch block 17 | e.printStackTrace(); 18 | } 19 | } 20 | 21 | } 22 | -------------------------------------------------------------------------------- /javademo/MyProject/src/com/cfxyz/util/MyMath.java: -------------------------------------------------------------------------------- 1 | package com.cfxyz.util; 2 | 3 | public class MyMath { 4 | public static int myadd(int x, int y) throws Exception{ 5 | return x + y; 6 | } 7 | 8 | public static int mydiv(int x, int y) throws Exception{ 9 | return x / y; 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /javademo/README.md: -------------------------------------------------------------------------------- 1 | Java代码练习 2 | ------------------ 3 | 4 | 1. [二叉树实现,节点为实现了Comparable接口的对象](https://github.com/cforth/codefarm/blob/master/javademo/TestBinaryTree.java) 5 | 6 | 2. [使用反射实现工厂类](https://github.com/cforth/codefarm/blob/master/javademo/TestFactory.java) 7 | 8 | 3. [简易资源管理器,并且输出到文件](https://github.com/cforth/codefarm/blob/master/javademo/TestFile.java) 9 | 10 | 4. [日期类操作](https://github.com/cforth/codefarm/blob/master/javademo/TestSimpleDateFormat.java) 11 | 12 | 5. [生产者消费者问题](https://github.com/cforth/codefarm/blob/master/javademo/TestThread.java) 13 | 14 | 6. [使用链表和接口实现宠物商店模型](https://github.com/cforth/codefarm/blob/master/javademo/LinkDemo.java) 15 | 16 | 7. [使用InputStream和OutputStream实现的文件拷贝程序](https://github.com/cforth/codefarm/blob/master/javademo/CopyDemo.java) 17 | 18 | 8. Scoket编程,[服务器端](https://github.com/cforth/codefarm/blob/master/javademo/HelloServer.java),[客户端](https://github.com/cforth/codefarm/blob/master/javademo/HelloClient.java) 19 | 20 | 9. 多线程版ECHO程序,[服务器端](https://github.com/cforth/codefarm/blob/master/javademo/EchoServer.java),[客户端](https://github.com/cforth/codefarm/blob/master/javademo/EchoClient.java) 21 | 22 | 10. [Set接口的子类](https://github.com/cforth/codefarm/blob/master/javademo/TestSet.java) 23 | 24 | 11. [JDK1.8中的MapReduce](https://github.com/cforth/codefarm/blob/master/javademo/TestMapReduce.java) 25 | 26 | 12. [数据库编程JDBC: Statement(不安全)、](https://github.com/cforth/codefarm/blob/master/javademo/TestJDBC.java)[PreparedStatement](https://github.com/cforth/codefarm/blob/master/javademo/TestPreparedStatement.java)、[批处理](https://github.com/cforth/codefarm/blob/master/javademo/TestBatch.java) 27 | 28 | 13. [DAO设计模式](https://github.com/cforth/codefarm/blob/master/javademo/DAOProject/src) 29 | 30 | 14. [在eclipse上的练习](https://github.com/cforth/codefarm/blob/master/javademo/MyProject) 31 | -------------------------------------------------------------------------------- /javademo/TestBatch.java: -------------------------------------------------------------------------------- 1 | import java.sql.Connection; 2 | import java.sql.DriverManager; 3 | import java.sql.Statement; 4 | import java.util.Arrays; 5 | 6 | /* 7 | * Oracle数据库脚本 8 | DROP TABLE member PURGE ; 9 | DROP SEQUENCE myseq ; 10 | CREATE SEQUENCE myseq ; 11 | CREATE TABLE member ( 12 | mid NUMBER, 13 | name VARCHAR2(20), 14 | birthday DATE DEFAULT SYSDATE , 15 | age NUMBER(3), 16 | note CLOB, 17 | CONSTRAINT pk_mid PRIMARY KEY(mid) 18 | ); 19 | */ 20 | 21 | public class TestBatch { 22 | private static final String DBDRIVER = "oracle.jdbc.driver.OracleDriver"; 23 | private static final String DBURL = "jdbc:oracle:thin:@localhost:1521:orcl"; 24 | private static final String USER = "scott"; 25 | private static final String PASSWORD = "tiger"; 26 | 27 | public static void main(String[] args) throws Exception { 28 | Class.forName(DBDRIVER); 29 | Connection conn = DriverManager.getConnection(DBURL, USER, PASSWORD); 30 | Statement stmt = conn.createStatement(); 31 | conn.setAutoCommit(false); //取消自动提交 32 | try { 33 | stmt.addBatch("INSERT INTO member(mid,name) VALUES (myseq.nextval, '测试A')"); 34 | stmt.addBatch("INSERT INTO member(mid,name) VALUES (myseq.nextval, '测试B')"); 35 | stmt.addBatch("INSERT INTO member(mid,name) VALUES (myseq.nextval, '测试C')"); 36 | stmt.addBatch("INSERT INTO member(mid,name) VALUES (myseq.nextval, '测试D')"); 37 | stmt.addBatch("INSERT INTO member(mid,name) VALUES (myseq.nextval, '测试E')"); 38 | int result [] = stmt.executeBatch(); //执行处理 39 | System.out.println(Arrays.toString(result)); 40 | conn.commit(); //如果没有错误,进行提交 41 | } catch(Exception e) { 42 | e.printStackTrace(); 43 | conn.rollback(); //如果出现异常则进行回滚 44 | } 45 | conn.close(); 46 | } 47 | 48 | } 49 | -------------------------------------------------------------------------------- /javademo/TestFactory.java: -------------------------------------------------------------------------------- 1 | interface Fruit { //接口定义 2 | public void eat(); 3 | } 4 | 5 | class Factory { //使用反射实现工厂类,从而不使用new关键字来获得解耦合 6 | public static Fruit getInstance(String className) { 7 | Fruit f = null; 8 | try { 9 | f = (Fruit) Class.forName(className).newInstance(); 10 | } catch (Exception e) { 11 | e.printStackTrace(); 12 | } 13 | return f; 14 | } 15 | } 16 | 17 | class Apple implements Fruit { 18 | @Override 19 | public void eat() { 20 | System.out.println("吃苹果!"); 21 | } 22 | } 23 | 24 | class Orange implements Fruit { 25 | @Override 26 | public void eat() { 27 | System.out.println("吃橘子!"); 28 | } 29 | } 30 | 31 | public class TestFactory { 32 | 33 | public static void main(String[] args) { 34 | Fruit apple = Factory.getInstance("Apple"); 35 | apple.eat(); 36 | Fruit orange = Factory.getInstance("Orange"); 37 | orange.eat(); 38 | } 39 | 40 | } 41 | -------------------------------------------------------------------------------- /javademo/TestFile.java: -------------------------------------------------------------------------------- 1 | import java.io.File; 2 | import java.io.FileOutputStream; 3 | import java.io.OutputStream; 4 | import java.math.BigDecimal; 5 | import java.text.SimpleDateFormat; 6 | import java.util.Date; 7 | 8 | public class TestFile { 9 | 10 | public static void main(String[] args) throws Exception{ 11 | //列出所有子目录中的文件 12 | getTime(); 13 | print(new File("d:" + File.separator), new File("F:" + File.separator + "demo" + File.separator + "test.txt"), 0); 14 | getTime(); 15 | } 16 | 17 | public static void print(File readfile, File writefile, int level) throws Exception { 18 | StringBuffer str = new StringBuffer(); 19 | for (int x = 0; x < level; x++) { 20 | str.append("|\t"); 21 | } 22 | str.append("|-"); 23 | writeFile(writefile, 24 | str + readfile.getName() + "\t\t" 25 | + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date(readfile.lastModified())) + "\t\t" 26 | + (readfile.isDirectory() ? "文件夹" : "文件") + "\t\t" 27 | + (readfile.isDirectory() ? "\r\n" : (new BigDecimal((double)readfile.length()/1024/1024).divide(new BigDecimal(1), 2, BigDecimal.ROUND_HALF_UP)) + "M\r\n")); 28 | 29 | if(readfile.isDirectory()) { 30 | level++; 31 | File result[] = readfile.listFiles(); 32 | if(result != null) { 33 | for(int x = 0; x < result.length; x ++) { 34 | print(result[x], writefile, level); 35 | } 36 | } 37 | } 38 | } 39 | 40 | public static void writeFile(File file, String str) throws Exception { 41 | // 1、目录不存在需要先创建目录 42 | if(!file.getParentFile().exists()) { //首先判断父目录是否存在 43 | file.getParentFile().mkdirs(); //不存在的话创建目录 44 | } 45 | // 2、使用OutputStream和其子类进行对象的实例化 46 | OutputStream output = new FileOutputStream(file, true); 47 | // 3、要进行文件内容的输出 48 | byte data[] = str.getBytes(); 49 | output.write(data);; 50 | // 4、资源操作一定要进行关闭 51 | output.close(); 52 | } 53 | 54 | public static void getTime() { 55 | Date date = new Date(); 56 | SimpleDateFormat start = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS"); 57 | System.out.println(start.format(date)); 58 | } 59 | 60 | } 61 | -------------------------------------------------------------------------------- /javademo/TestJDBC.java: -------------------------------------------------------------------------------- 1 | package com.cfxyz.demo; 2 | 3 | import java.sql.Connection; 4 | import java.sql.DriverManager; 5 | import java.sql.ResultSet; 6 | import java.sql.Statement; 7 | import java.util.Date; 8 | 9 | /* 10 | * Oracle数据库脚本 11 | DROP TABLE member PURGE ; 12 | DROP SEQUENCE myseq ; 13 | CREATE SEQUENCE myseq ; 14 | CREATE TABLE member ( 15 | mid NUMBER, 16 | name VARCHAR2(20), 17 | birthday DATE DEFAULT SYSDATE , 18 | age NUMBER(3), 19 | note CLOB, 20 | CONSTRAINT pk_mid PRIMARY KEY(mid) 21 | ); 22 | */ 23 | 24 | 25 | public class TestJDBC { 26 | private static final String DBDRIVER = "oracle.jdbc.driver.OracleDriver"; 27 | private static final String DBURL = "jdbc:oracle:thin:@localhost:1521:orcl"; 28 | private static final String USER = "scott"; 29 | private static final String PASSWORD = "tiger"; 30 | 31 | public static void main(String[] args) throws Exception { 32 | //第一步:加载数据库驱动程序,此时不需要实例化,因为会由容器自己负责管理 33 | Class.forName(DBDRIVER); 34 | 35 | //第二步:连接数据库 36 | Connection conn = DriverManager.getConnection(DBURL, USER, PASSWORD); 37 | System.out.println(conn); 38 | 39 | //第三步:操作数据库 40 | //数据更新: 41 | Statement stmt = conn.createStatement(); 42 | String sql =" INSERT INTO member (mid, name, birthday, age, note) VALUES " 43 | + " (myseq.nextval, '张三', TO_DATE('1998-10-10', 'yyyy-mm-dd'), 17, '是个人') " ; 44 | int len; 45 | for(int x = 0; x < 30; x++) { 46 | len = stmt.executeUpdate(sql) ; //执行更新 47 | System.out.println("影响的数据行:" + len); 48 | } 49 | 50 | //数据修改: 51 | sql ="UPDATE member SET name = '李四',birthday=SYSDATE, age=30 WHERE mid IN(3,5,7,9,11,13,15,17) " ; 52 | len = stmt.executeUpdate(sql) ; 53 | System.out.println("影响的数据行:" + len); 54 | 55 | //数据删除: 56 | sql ="DELETE FROM member WHERE mid IN(10, 20, 30)"; 57 | len = stmt.executeUpdate(sql) ; 58 | System.out.println("影响的数据行:" + len); 59 | 60 | //数据查询: 61 | sql = "SELECT mid, name, birthday, age, note FROM member"; 62 | ResultSet rs = stmt.executeQuery(sql) ; 63 | while(rs.next()) { //循环取出返回的每一行数据 64 | int mid = rs.getInt("mid"); 65 | String name = rs.getString("name"); 66 | int age = rs.getInt("age"); 67 | Date birthday = rs.getDate("birthday"); 68 | String note = rs.getString("note"); 69 | System.out.println(mid + ", " + name + ", " + age + ", " + birthday + ", " + note); 70 | } 71 | 72 | //第四步:关闭数据库 73 | rs.close(); //可选 74 | stmt.close(); //可选 75 | conn.close(); 76 | } 77 | 78 | } 79 | -------------------------------------------------------------------------------- /javademo/TestMapReduce.java: -------------------------------------------------------------------------------- 1 | import java.util.ArrayList; 2 | import java.util.DoubleSummaryStatistics; 3 | import java.util.List; 4 | 5 | class ShopCar { 6 | private String pname; 7 | private int amount; 8 | private double price; 9 | public ShopCar(String pname, double price, int amount) { 10 | this.pname = pname; 11 | this.amount = amount; 12 | this.price = price; 13 | } 14 | public String getPname() { 15 | return this.pname; 16 | } 17 | public int getAmount() { 18 | return this.amount; 19 | } 20 | public double getPrice() { 21 | return this.price; 22 | } 23 | } 24 | 25 | public class TestMapReduce { 26 | 27 | public static void main(String[] args) { 28 | List all = new ArrayList(); 29 | all.add(new ShopCar("Java开发", 34.5, 20)); 30 | all.add(new ShopCar("Jsp开发", 56.5, 50)); 31 | all.add(new ShopCar("Ocale开发", 99.5, 100)); 32 | double s = all.stream() 33 | .map((x)->x.getAmount() * x.getPrice()) 34 | .reduce((sum, m)-> sum+m).get(); 35 | System.out.println("总计花费:" + s); 36 | 37 | DoubleSummaryStatistics dss = all.stream() 38 | .mapToDouble((sc)->sc.getAmount() * sc.getPrice()) 39 | .summaryStatistics(); 40 | System.out.println("商品数量:" + dss.getCount()); 41 | System.out.println("平均花费:" + dss.getAverage()); 42 | System.out.println("最大花费:" + dss.getMax()); 43 | System.out.println("最下花费:" + dss.getMin()); 44 | } 45 | 46 | } 47 | -------------------------------------------------------------------------------- /javademo/TestPreparedStatement.java: -------------------------------------------------------------------------------- 1 | import java.sql.Connection; 2 | import java.sql.DriverManager; 3 | import java.sql.PreparedStatement; 4 | import java.sql.ResultSet; 5 | import java.util.Date; 6 | 7 | //测试数据先运行TestJDBC 8 | 9 | public class testPreparedStatement { 10 | private static final String DBDRIVER = "oracle.jdbc.driver.OracleDriver"; 11 | private static final String DBURL = "jdbc:oracle:thin:@localhost:1521:orcl"; 12 | private static final String USER = "scott"; 13 | private static final String PASSWORD = "tiger"; 14 | 15 | public static void main(String[] args) throws Exception { 16 | String name = "Mr'SMITH"; 17 | Date birthday = new Date(); 18 | int age = 18; 19 | String note = "是个外国人"; 20 | //第一步:加载数据库驱动程序,此时不需要实例化,因为会由容器自己负责管理 21 | Class.forName(DBDRIVER); 22 | 23 | //第二步:连接数据库 24 | Connection conn = DriverManager.getConnection(DBURL, USER, PASSWORD); 25 | 26 | //第三步:操作数据库 27 | //增加数据,SQL语句如果要换行,前后加空格 28 | String sql =" INSERT INTO member (mid, name, birthday, age, note) VALUES " 29 | + " (myseq.nextval, ?, ?, ?, ?) " ; 30 | PreparedStatement stmt = conn.prepareStatement(sql); 31 | stmt.setString(1, name); 32 | stmt.setDate(2, new java.sql.Date(birthday.getTime())); //Date必须进行转换 33 | stmt.setInt(3, age); 34 | stmt.setString(4, note); 35 | int len = stmt.executeUpdate() ; //执行更新 36 | System.out.println("影响的数据行:" + len); 37 | 38 | //查询数据 39 | sql ="SELECT mid, name, birthday, age, note FROM member ORDER BY mid" ; 40 | stmt = conn.prepareStatement(sql); 41 | ResultSet rs = stmt.executeQuery() ; //执行查询 42 | while(rs.next()) { //循环取出返回的每一行数据 43 | int mid = rs.getInt("mid"); 44 | name = rs.getString("name"); 45 | age = rs.getInt("age"); 46 | birthday = rs.getDate("birthday"); 47 | note = rs.getString("note"); 48 | System.out.println(mid + ", " + name + ", " + age + ", " + birthday + ", " + note); 49 | } 50 | 51 | //模糊查询 52 | String keyWord = "李"; 53 | sql ="SELECT mid, name, birthday, age, note FROM member WHERE name LIKE ?" ; 54 | stmt = conn.prepareStatement(sql); 55 | stmt.setString(1, "%"+keyWord+"%"); 56 | rs = stmt.executeQuery() ; //执行查询 57 | while(rs.next()) { //循环取出返回的每一行数据 58 | int mid = rs.getInt("mid"); 59 | name = rs.getString("name"); 60 | age = rs.getInt("age"); 61 | birthday = rs.getDate("birthday"); 62 | note = rs.getString("note"); 63 | System.out.println(mid + ", " + name + ", " + age + ", " + birthday + ", " + note); 64 | } 65 | 66 | //第四部:关闭连接 67 | rs.close(); //可选 68 | stmt.close(); //可选 69 | conn.close(); 70 | } 71 | 72 | } 73 | -------------------------------------------------------------------------------- /javademo/TestSimpleDateFormat.java: -------------------------------------------------------------------------------- 1 | package com.cfxyz.demo; 2 | 3 | import java.text.SimpleDateFormat; 4 | import java.util.Calendar; 5 | import java.util.Date; 6 | 7 | public class TestSimpleDateFormat { 8 | 9 | public static void main(String[] args) throws Exception { 10 | Date date = new Date(); 11 | SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS"); 12 | String str = sdf.format(date); //日期型数据变为字符串 13 | System.out.println(str); 14 | str = "2001-11-11 11:11:11.111"; 15 | date = sdf.parse(str); //字符串变为日期型数据 16 | System.out.println(date); 17 | 18 | Calendar cal = Calendar.getInstance(); 19 | StringBuffer buf = new StringBuffer(); 20 | buf.append(cal.get(Calendar.YEAR)).append("-"); 21 | buf.append(cal.get(Calendar.MONTH)+1).append("-"); 22 | buf.append(cal.get(Calendar.DAY_OF_MONTH)).append(" "); 23 | buf.append(cal.get(Calendar.HOUR_OF_DAY)).append(":"); 24 | buf.append(cal.get(Calendar.MINUTE)).append(":"); 25 | buf.append(cal.get(Calendar.SECOND)); 26 | System.out.println(buf); 27 | } 28 | 29 | } 30 | -------------------------------------------------------------------------------- /javademo/TestThread.java: -------------------------------------------------------------------------------- 1 | /** 2 | * 生产者 消费者模型 3 | * 每次生产一个,取出一个 4 | * 需要解决同步和重复问题。 5 | */ 6 | 7 | class Info { 8 | private String title; 9 | private String content; 10 | private boolean flag = true; 11 | // flag = true:表示可以生产,但不可以取走 12 | // flag = false:表示可以取走,但不可以生产 13 | public synchronized void set(String title, String content) { //解决同步问题 14 | //重复进入到set()方法里面,发现不能生产,所以要等待 15 | if(this.flag == false) { 16 | try { 17 | super.wait(); 18 | } catch (InterruptedException e) { 19 | e.printStackTrace(); 20 | } 21 | } 22 | this.title = title; 23 | try { 24 | Thread.sleep(200); 25 | } catch (InterruptedException e) { 26 | e.printStackTrace(); 27 | } 28 | this.content = content; 29 | this.flag = false; //修改生产标记 30 | super.notify();//唤醒其它等待线程 31 | } 32 | public synchronized void get() { //解决同步问题 33 | // 还没生产 34 | if(this.flag == true) { 35 | try { 36 | super.wait(); 37 | } catch (InterruptedException e) { 38 | e.printStackTrace(); 39 | } 40 | } 41 | try { 42 | Thread.sleep(100); 43 | } catch (InterruptedException e) { 44 | e.printStackTrace(); 45 | } 46 | System.out.println(this.title + "-" + this.content); 47 | this.flag = true; 48 | super.notify(); 49 | } 50 | } 51 | 52 | class Productor implements Runnable { 53 | private Info info; 54 | public Productor(Info info) { 55 | this.info = info; 56 | } 57 | @Override 58 | public void run() { 59 | for (int x = 0; x < 100; x++) { 60 | if(x % 2 == 0) { 61 | this.info.set("AAA", "111"); 62 | } else { 63 | this.info.set("BBB", "222"); 64 | } 65 | } 66 | 67 | } 68 | } 69 | 70 | class Customer implements Runnable { 71 | private Info info ; 72 | public Customer(Info info) { 73 | this.info = info; 74 | } 75 | @Override 76 | public void run() { 77 | for(int x = 0; x < 100 ; x++) { 78 | this.info.get(); 79 | } 80 | } 81 | } 82 | 83 | public class TestThread { 84 | 85 | public static void main(String[] args) { 86 | Info info = new Info(); 87 | new Thread(new Productor(info)).start(); 88 | new Thread(new Customer(info)).start(); 89 | } 90 | 91 | } 92 | -------------------------------------------------------------------------------- /jsdemo/README.md: -------------------------------------------------------------------------------- 1 | #JavaScript基础学习 2 | 3 | ##开发要求 4 | 5 | 要求定义一个雇员信息的增加页面,例如页面名称为:[emp_insert.htm](https://github.com/cforth/codefarm/tree/master/jsdemo/emp_insert.htm),而后在此页之中要提供输入表单,此表单定义要求如下: 6 | 7 | 1. 雇员编号:必须是4位数字; 8 | 9 | 2. 雇员姓名:不能为空; 10 | 11 | 3. 雇员职位:不能为空; 12 | 13 | 4. 雇用日期:按照“yyyy-mm-dd”的格式编写; 14 | 15 | 5. 基本工资:按照小数编写,小数最多为2位; 16 | 17 | 6. 佣金:按照小数编写,小数位最多为2位; 18 | 19 | -------------------------------------------------------------------------------- /jsdemo/checkbox.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | JavaScript 5 | 6 | 7 | 27 | 28 | 29 | 请选择:
30 | 知乎
31 | 果壳
32 | 伯乐在线
33 | 维基百科
34 | SegmentFault
35 | 21世纪网



36 | 全选 37 | 38 | 39 | 40 | -------------------------------------------------------------------------------- /jsdemo/css/cfxyz.css: -------------------------------------------------------------------------------- 1 | .init { 2 | background:#F5F5F5; 3 | font-weight:bold; 4 | color:#000000; 5 | } 6 | 7 | .wrong { 8 | background: #F5F5F5; 9 | font-weight: bold; 10 | border: 1px #FF0000 solid ; 11 | color:#000000; 12 | } 13 | 14 | .right { 15 | background: #F5F5F5; 16 | font-weight: bold; 17 | border: 1px #00FF00 solid ; 18 | color:#000000; 19 | } 20 | -------------------------------------------------------------------------------- /jsdemo/css/my.css: -------------------------------------------------------------------------------- 1 | .init { 2 | background: #F5F5F5; 3 | font-weight: bold; 4 | color:#000000; 5 | } 6 | 7 | .wrong { 8 | background: #F5F5F5; 9 | font-weight: bold; 10 | border: 1px #FF0000 solid ; 11 | color:#000000; 12 | } 13 | 14 | .right { 15 | background: #F5F5F5; 16 | font-weight: bold; 17 | border: 1px #00FF00 solid ; 18 | color:#000000; 19 | } 20 | -------------------------------------------------------------------------------- /jsdemo/emp_insert.htm: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 雇员管理操作 5 | 6 | 7 | 8 | 9 | 10 | 11 |
12 | 13 | 14 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | 45 | 46 |
雇员管理操作 15 |
雇员编号:
雇员姓名:
雇员职位:
雇员日期:
雇员工资:
佣金:
47 | 48 |
49 | 50 | -------------------------------------------------------------------------------- /jsdemo/form.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | JavaScript 5 | 6 | 7 | 27 | 28 | 29 |
30 | 请输入Email地址:
31 | 32 |
33 | 34 | 35 | -------------------------------------------------------------------------------- /jsdemo/js/cfxyz.js: -------------------------------------------------------------------------------- 1 | function validateEmpty(eleName) { 2 | var obj = document.getElementById(eleName); //取得对象 3 | var msg = document.getElementById(eleName + "Msg"); //提示信息 4 | if(obj.value != "") { //进行内容验证 5 | obj.className = "right"; 6 | msg.innerHTML = "内容输入正确!"; 7 | return true ; 8 | } else { 9 | obj.className = "wrong"; 10 | msg.innerHTML = "内容为空!"; 11 | return true ; 12 | } 13 | } 14 | 15 | function validateRegex(eleName, regex) { 16 | var obj = document.getElementById(eleName); //取得对象 17 | var msg = document.getElementById(eleName + "Msg"); //提示信息 18 | if(regex.test(obj.value)) { //进行内容验证 19 | obj.className = "right"; 20 | msg.innerHTML = "内容输入正确!"; 21 | return true ; 22 | } else { 23 | obj.className = "wrong"; 24 | msg.innerHTML = "内容输入错误!"; 25 | return false ; 26 | } 27 | } -------------------------------------------------------------------------------- /jsdemo/js/demo.js: -------------------------------------------------------------------------------- 1 | function validateEmpty(elementName) { 2 | var objElement = document.getElementById(elementName) ; 3 | var msgElement = document.getElementById(elementName + "Msg") ; 4 | if(objElement.value != ""){ //不为空 5 | objElement.className = "right"; 6 | msgElement.innerHTML = "输入内容正确!"; 7 | return true; 8 | } else { 9 | objElement.className = "wrong"; 10 | msgElement.innerHTML = "输入内容错误!"; 11 | return false; 12 | } 13 | } 14 | 15 | function validateRepeat(srcName, desName) { 16 | var srcElement = document.getElementById(srcName); 17 | var desElement = document.getElementById(desName); 18 | var msgElement = document.getElementById(desName + "Msg"); 19 | if(srcElement.value == desElement.value) { 20 | desElement.className = "right"; 21 | msgElement.innerHTML = "输入内容正确!"; 22 | return true; 23 | } else { 24 | desElement.className = "wrong"; 25 | msgElement.innerHTML = "两次输入内容不一致!"; 26 | return false; 27 | } 28 | } 29 | 30 | function validatePwd() { 31 | return validateEmpty("pwd"); 32 | } 33 | 34 | function validateConf() { 35 | if(validateEmpty("conf")) { 36 | return validateRepeat("pwd", "conf"); 37 | } 38 | return validateEmpty("conf"); 39 | } 40 | window.onload = function() { 41 | document.getElementById("pwd").addEventListener("blur", validatePwd, false) 42 | document.getElementById("conf").addEventListener("blur", validateConf, false) 43 | } 44 | -------------------------------------------------------------------------------- /jsdemo/js/emp.js: -------------------------------------------------------------------------------- 1 | function validateEmpno() { 2 | return validateRegex("empno", /^\d{4}$/); 3 | } 4 | 5 | function validateEname() { 6 | return validateEmpty("ename"); 7 | } 8 | 9 | function validateJob() { 10 | return validateEmpty("job"); 11 | } 12 | 13 | function validateHiredate() { 14 | return validateRegex("hiredate", /^\d{4}-\d{2}-\d{2}$/); 15 | } 16 | 17 | function validateSal() { 18 | return validateRegex("sal",/^\d+(\.\d{1,2})?$/); 19 | } 20 | 21 | function validateComm() { 22 | return validateRegex("comm",/^\d+(\.\d{1,2})?$/); 23 | } 24 | 25 | function validate() { 26 | return validateEmpno() && 27 | validateEname() && 28 | validateJob() && 29 | validateHiredate() && 30 | validateSal() && 31 | validateComm(); 32 | } -------------------------------------------------------------------------------- /jsdemo/radio.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | JavaScript 5 | 6 | 7 | 18 | 19 | 20 | 请选择性别: 21 | 男 22 |   23 | 女 24 |
25 | 26 | 27 | 28 | -------------------------------------------------------------------------------- /jsdemo/select.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | JavaScript 5 | 6 | 7 | 12 | 13 | 14 | 你的家乡:
20 | 21 | 22 | -------------------------------------------------------------------------------- /jsdemo/show.html: -------------------------------------------------------------------------------- 1 | 2 |

表单提交成功!

3 | -------------------------------------------------------------------------------- /jsdemo/textarea.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | JavaScript 5 | 6 | 7 | 22 | 23 | 24 |
25 | 描述:
26 |
27 | 28 |
29 | 30 | 31 | -------------------------------------------------------------------------------- /jsdemo/validatePwd.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | JavaScript 5 | 6 | 7 | 8 | 9 | 10 | 请输入面: 11 |
12 | 确认密码: 13 |
14 | 15 | 16 | -------------------------------------------------------------------------------- /jspdemo/LoginProject/.classpath: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | -------------------------------------------------------------------------------- /jspdemo/LoginProject/.project: -------------------------------------------------------------------------------- 1 | 2 | 3 | LoginProject 4 | 5 | 6 | 7 | 8 | 9 | org.eclipse.wst.jsdt.core.javascriptValidator 10 | 11 | 12 | 13 | 14 | org.eclipse.jdt.core.javabuilder 15 | 16 | 17 | 18 | 19 | org.eclipse.wst.common.project.facet.core.builder 20 | 21 | 22 | 23 | 24 | org.eclipse.wst.validation.validationbuilder 25 | 26 | 27 | 28 | 29 | com.genuitec.eclipse.j2eedt.core.DeploymentDescriptorValidator 30 | 31 | 32 | 33 | 34 | 35 | org.eclipse.jem.workbench.JavaEMFNature 36 | org.eclipse.wst.common.modulecore.ModuleCoreNature 37 | org.eclipse.wst.common.project.facet.core.nature 38 | org.eclipse.jdt.core.javanature 39 | org.eclipse.wst.jsdt.core.jsNature 40 | 41 | 42 | -------------------------------------------------------------------------------- /jspdemo/LoginProject/.settings/.jsdtscope: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | -------------------------------------------------------------------------------- /jspdemo/LoginProject/.settings/org.eclipse.jdt.core.prefs: -------------------------------------------------------------------------------- 1 | eclipse.preferences.version=1 2 | org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=enabled 3 | org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.7 4 | org.eclipse.jdt.core.compiler.compliance=1.7 5 | org.eclipse.jdt.core.compiler.problem.assertIdentifier=error 6 | org.eclipse.jdt.core.compiler.problem.enumIdentifier=error 7 | org.eclipse.jdt.core.compiler.source=1.7 8 | -------------------------------------------------------------------------------- /jspdemo/LoginProject/.settings/org.eclipse.wst.common.component: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | -------------------------------------------------------------------------------- /jspdemo/LoginProject/.settings/org.eclipse.wst.common.project.facet.core.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | -------------------------------------------------------------------------------- /jspdemo/LoginProject/.settings/org.eclipse.wst.jsdt.ui.superType.container: -------------------------------------------------------------------------------- 1 | org.eclipse.wst.jsdt.launching.baseBrowserLibrary -------------------------------------------------------------------------------- /jspdemo/LoginProject/.settings/org.eclipse.wst.jsdt.ui.superType.name: -------------------------------------------------------------------------------- 1 | Window -------------------------------------------------------------------------------- /jspdemo/LoginProject/.tern-project: -------------------------------------------------------------------------------- 1 | {"ide":{},"libs":["ecma5","browser"],"plugins":{"guess-types":{}}} -------------------------------------------------------------------------------- /jspdemo/LoginProject/WebRoot/META-INF/MANIFEST.MF: -------------------------------------------------------------------------------- 1 | Manifest-Version: 1.0 2 | Class-Path: 3 | 4 | -------------------------------------------------------------------------------- /jspdemo/LoginProject/WebRoot/WEB-INF/classes/数据库脚本.sql: -------------------------------------------------------------------------------- 1 | DROP TABLE member PURGE ; 2 | CREATE TABLE member( 3 | mid VARCHAR2(30) , 4 | password VARCHAR2(32) , 5 | CONSTRAINT pk_mid PRIMARY KEY(mid) 6 | ) ; 7 | INSERT INTO member(mid,password) VALUES ('admin','hello') ; 8 | INSERT INTO member(mid,password) VALUES ('cfxyz','java') ; 9 | COMMIT ; -------------------------------------------------------------------------------- /jspdemo/LoginProject/WebRoot/WEB-INF/web.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | LoginProject 4 | 5 | index.html 6 | index.htm 7 | index.jsp 8 | default.html 9 | default.htm 10 | default.jsp 11 | 12 | -------------------------------------------------------------------------------- /jspdemo/LoginProject/WebRoot/check.jsp: -------------------------------------------------------------------------------- 1 | <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> 2 | <%@ page import="java.sql.*" %> 3 | 4 | <%! //定义数据库相关连接信息 5 | public static final String DBDRIVER = "oracle.jdbc.driver.OracleDriver" ; 6 | public static final String DBURL = "jdbc:oracle:thin:@localhost:1521:orcl" ; 7 | public static final String USER = "scott" ; 8 | public static final String PASSWORD = "tiger" ; 9 | %> 10 | <% //接收请求参数 11 | String mid = request.getParameter("mid"); 12 | String password = request.getParameter("password"); 13 | if(mid == null || password == null) { 14 | %> 15 | 16 | 17 | 18 | <% 19 | } else { 20 | boolean flag = false ; //保存成功与否的标记 21 | %> 22 | <% // 编写程序语句 23 | Connection conn = null; 24 | PreparedStatement pstmt = null ; 25 | ResultSet rs = null ; 26 | String sql = "SELECT COUNT(mid) FROM member WHERE mid=? AND password=?" ; 27 | 28 | Class.forName(DBDRIVER); 29 | conn = DriverManager.getConnection(DBURL,USER,PASSWORD) ; 30 | pstmt = conn.prepareStatement(sql); 31 | pstmt.setString(1,mid); 32 | pstmt.setString(2,password); 33 | rs = pstmt.executeQuery(); 34 | if(rs.next()) { 35 | if(rs.getInt(1) == 1) { //登陆成功 36 | flag = true; //修改标记 37 | } 38 | } 39 | conn.close(); //数据库验证完毕后关闭连接 40 | %> 41 | <% 42 | if(flag) { //如果登陆成功,跳转到welcome.jsp 43 | %> 44 | 45 | <% 46 | } else { //表示失败 47 | %> 48 | 49 | 50 | 51 | <% 52 | } 53 | } 54 | %> 55 | 56 | 57 | 登陆程序 58 | 59 | 60 | This is my JSP page.
61 | 62 | 63 | -------------------------------------------------------------------------------- /jspdemo/LoginProject/WebRoot/css/cfxyz.css: -------------------------------------------------------------------------------- 1 | .init { 2 | background:#F5F5F5; 3 | font-weight:bold; 4 | color:#000000; 5 | } 6 | 7 | .wrong { 8 | background: #F5F5F5; 9 | font-weight: bold; 10 | border: 1px #FF0000 solid ; 11 | color:#000000; 12 | } 13 | 14 | .right { 15 | background: #F5F5F5; 16 | font-weight: bold; 17 | border: 1px #00FF00 solid ; 18 | color:#000000; 19 | } 20 | -------------------------------------------------------------------------------- /jspdemo/LoginProject/WebRoot/js/cfxyz.js: -------------------------------------------------------------------------------- 1 | function validateEmpty(eleName) { 2 | var obj = document.getElementById(eleName); //取得对象 3 | var msg = document.getElementById(eleName + "Msg"); //提示信息 4 | if(obj.value != "") { //进行内容验证 5 | obj.className = "right"; 6 | msg.innerHTML = "内容输入正确!"; 7 | return true ; 8 | } else { 9 | obj.className = "wrong"; 10 | msg.innerHTML = "内容为空!"; 11 | return false ; 12 | } 13 | } 14 | 15 | function validateRegex(eleName, regex) { 16 | var obj = document.getElementById(eleName); //取得对象 17 | var msg = document.getElementById(eleName + "Msg"); //提示信息 18 | if(regex.test(obj.value)) { //进行内容验证 19 | obj.className = "right"; 20 | msg.innerHTML = "内容输入正确!"; 21 | return true ; 22 | } else { 23 | obj.className = "wrong"; 24 | msg.innerHTML = "内容输入错误!"; 25 | return false ; 26 | } 27 | } 28 | 29 | function changeColor(obj, color) { 30 | obj.bgColor = color; 31 | } -------------------------------------------------------------------------------- /jspdemo/LoginProject/WebRoot/js/login.js: -------------------------------------------------------------------------------- 1 | function validateMid() { 2 | return validateEmpty("mid"); 3 | } 4 | 5 | function validatePassword() { 6 | return validateEmpty("password"); 7 | } 8 | 9 | function validate() { 10 | return validateMid() && validatePassword(); 11 | } 12 | -------------------------------------------------------------------------------- /jspdemo/LoginProject/WebRoot/login.jsp: -------------------------------------------------------------------------------- 1 | <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> 2 | 3 | 4 | 登陆程序 5 | 6 | 7 | 8 | 9 | 10 |

用户登陆

11 | <% 12 | //如果有check.jsp跳转回login.jsp,那么表示用户名或密码错误,属于错误提示信息 13 | String err = request.getParameter("err"); 14 | if("loginError".equals(err)) { 15 | %> 16 |

登陆失败,错误的用户名或密码!

17 | <% 18 | } else if("dataError".equals(err)) { 19 | %> 20 |

请输入正确的登陆信息!

21 | <% 22 | } 23 | %> 24 |
25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 41 | 42 |
用户名:
密  码:
38 | 39 | 40 |
43 |
44 | 45 | 46 | -------------------------------------------------------------------------------- /jspdemo/LoginProject/WebRoot/welcome.jsp: -------------------------------------------------------------------------------- 1 | <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> 2 | 3 | 4 | 登陆程序 5 | 6 | 7 |

登陆成功!欢迎光临!

8 | 9 | 10 | -------------------------------------------------------------------------------- /jspdemo/LoginProject/src/数据库脚本.sql: -------------------------------------------------------------------------------- 1 | DROP TABLE member PURGE ; 2 | CREATE TABLE member( 3 | mid VARCHAR2(30) , 4 | password VARCHAR2(32) , 5 | CONSTRAINT pk_mid PRIMARY KEY(mid) 6 | ) ; 7 | INSERT INTO member(mid,password) VALUES ('admin','hello') ; 8 | INSERT INTO member(mid,password) VALUES ('cfxyz','java') ; 9 | COMMIT ; -------------------------------------------------------------------------------- /jspdemo/README.md: -------------------------------------------------------------------------------- 1 | JSP项目练习 2 | ------------------ 3 | 4 | 1. [用户登录验证网页](https://github.com/cforth/codefarm/blob/master/jspdemo/LoginProject) 5 | 6 | -------------------------------------------------------------------------------- /lottery/README: -------------------------------------------------------------------------------- 1 | 2015-02-21 2 | LotterySortThree.java 3 | Java版的排列三游戏,需要运行 4 | javac -encoding utf8 LotterySortThree.java 5 | java LotterySortThree 6 | 7 | 2012-07-23 8 | 上传了排列3彩票游戏,自己选5个0~9之间的数字,中奖号码为3个。 9 | 10 | 2012-05-27 11 | 更新了刮刮乐游戏源代码,经GCC编译后可以在linux系统上运行。 12 | 13 | 2012-05-10 14 | 上传了刮刮乐游戏,投入钱币后,给出中奖号码。只能在windows系统上运行。 15 | -------------------------------------------------------------------------------- /lottery/gua_gua_le.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | // #include 5 | const int award[10] = {5,10,15,20,30,50,100,500,1000,10000}; 6 | static int prize_pool[10000]; 7 | 8 | int main() 9 | { 10 | int init_sum; 11 | int avail_sum; 12 | int coin_money; 13 | int sum_award_money; 14 | 15 | generate_prize_pool(); 16 | // look_prize_pool(); 17 | 18 | printf("Your initial capital : "); 19 | scanf("%d",&init_sum); 20 | printf("\n"); 21 | avail_sum = init_sum; 22 | 23 | while(avail_sum > 0) { 24 | printf("Start!Please coin: "); 25 | scanf("%d",&coin_money); 26 | printf("\n"); 27 | avail_sum -= coin_money; 28 | 29 | if(avail_sum < 0) { 30 | avail_sum += coin_money; 31 | printf("Your available funds too less! Try again!\n"); 32 | continue; 33 | } 34 | 35 | srand((unsigned)time(0)); 36 | sum_award_money = make_lottery(coin_money); 37 | avail_sum += sum_award_money; 38 | 39 | printf("You win %d yuan!!!\n",sum_award_money); 40 | printf("Your available funds : %d yuan\n",avail_sum); 41 | } 42 | 43 | printf("Sorry! You have no money!!\n"); 44 | system("pause"); 45 | return 0; 46 | } 47 | 48 | int make_lottery(int money) 49 | { 50 | int i; 51 | int win_num; 52 | int you_num; 53 | int award_money; 54 | int sum_award_money = 0; 55 | int max_num = 15; /*6.6% Probability of winning */ 56 | 57 | printf("WinNumber\tYouNumber\tAwardMoney\n"); 58 | for(i = 0; i < money; i++) { 59 | you_num = roll(max_num); 60 | win_num = roll(max_num); 61 | 62 | printf("%d\t\t%d\t\t", win_num, you_num); 63 | if(you_num == win_num) { 64 | award_money = prize_pool[roll(10000)]; 65 | sum_award_money += award_money; 66 | printf("%d\tWin!",award_money); 67 | } 68 | else { 69 | award_money = award[roll(10) - 1]; 70 | printf("%d\tLose!",award_money); 71 | } 72 | printf("\n"); 73 | // Sleep(1000); 74 | } 75 | return sum_award_money; 76 | } 77 | 78 | int roll(int max_num) 79 | { 80 | return 1+rand()%max_num; 81 | } 82 | 83 | int generate_prize_pool() 84 | { 85 | int i,j,k,temp; 86 | 87 | int award_num[10] = {7370,1000,666,500,333,200,100,20,10,1}; 88 | 89 | for(i=0; i<10000; i++) 90 | prize_pool[i] = 5; 91 | for(j=0; j<10; j++) 92 | for(k=0; k 2 | #include 3 | 4 | #define MAX 3 5 | #define YOUR 5 6 | int is_single( int num ); 7 | int roll ( int max_num ); 8 | int find_num( int* your_num, int* win_num ); 9 | 10 | int main( void ) 11 | { 12 | int num, i, c, win_num[MAX], your_num[YOUR]; 13 | srand((unsigned)time(0)); 14 | 15 | printf("Enter five numbers: "); 16 | for(i = 0; i < YOUR; i++) { 17 | scanf("%d", &num); 18 | if( !is_single(num) ) { 19 | printf("Please enter number between 0 and 9!\n"); 20 | return -1; 21 | } 22 | your_num[i] = num; 23 | } 24 | 25 | for(i = 0; i < MAX; i++) 26 | win_num[i] = roll(10); 27 | 28 | printf("\nYour numbers:\t"); 29 | for(i = 0; i < YOUR; i++) 30 | printf("%d ", your_num[i]); 31 | 32 | printf("\nWin numbers:\t"); 33 | for(i = 0; i < MAX; i++) 34 | printf("%d ", win_num[i]); 35 | 36 | printf("\nGet %d number!\n", find_num(your_num, win_num)); 37 | 38 | printf("Enter any key to quit!\n"); 39 | while((c = getchar()) != '\n' && c != EOF); 40 | getchar(); 41 | return 0; 42 | } 43 | 44 | int is_single( int num ) 45 | { 46 | return (num <= 9 && num >= 0); 47 | } 48 | 49 | int roll(int max_num) 50 | { 51 | return rand()%max_num; 52 | } 53 | 54 | int find_num( int* your_num, int* win_num ) 55 | { 56 | int i, j; 57 | int num = 0; 58 | for( i = 0; i < YOUR; i++ ) 59 | for( j = 0; j < MAX; j++) 60 | if(*(your_num + i) == *(win_num + j)) { 61 | *(win_num + j) = -1; 62 | num ++; 63 | break; 64 | } 65 | return num; 66 | } 67 | -------------------------------------------------------------------------------- /morse_code/README: -------------------------------------------------------------------------------- 1 | 2012-10-14 2 | 上传了char2morse.c 3 | 将键盘输入的英文字母组成的句子,翻译成摩斯电码。 4 | -------------------------------------------------------------------------------- /morse_code/char2morse.c: -------------------------------------------------------------------------------- 1 | #include 2 | #define MAX 1000 3 | 4 | static char dict[26][5] = 5 | { 6 | ".-", "-...", "-.-.", "-..", ".", 7 | "..-.", "--.", "....", "..", ".---", 8 | "-.-", ".-..", "--", "-.", "---", 9 | ".--.", "--.-", ".-.", "...", "-", 10 | "..-", "...-", ".--", "-..-", "-.--", 11 | "--.." 12 | }; 13 | 14 | 15 | int char2morse(int c) 16 | { 17 | if (c >= 'a' && c <= 'z') 18 | printf("%s", dict[c - 'a']); 19 | else if (c == ',') 20 | printf("--..--"); 21 | else if (c == '.') 22 | printf(".-.-.-"); 23 | else if (c == '?') 24 | printf("..--.."); 25 | else if (c == ' ') 26 | printf("\n"); 27 | else 28 | return -1; 29 | return 0; 30 | } 31 | 32 | 33 | int main() 34 | { 35 | int i, status, c; 36 | char buff[MAX]; 37 | 38 | fgets(buff, MAX, stdin); 39 | for(i = 0; (c = buff[i]) != '\n'; i++) { 40 | printf(" "); 41 | status = char2morse(c); 42 | if (status != 0) { 43 | fprintf(stderr, "\nError! Undefine word: '%c'\n", c); 44 | break; 45 | } 46 | } 47 | printf("\n"); 48 | return 0; 49 | } 50 | -------------------------------------------------------------------------------- /morse_code/makefile: -------------------------------------------------------------------------------- 1 | #运行 make 源代码名字(不带".c"后缀) 2 | #例如 make 8_puzzle 3 | #可以自动编译生成 8_puzzle可执行文件 4 | CC := gcc 5 | CFLAGS := -Wall 6 | clean: 7 | @echo "cleanning project" 8 | -rm -f *.exe 9 | @echo "clean completed" 10 | -------------------------------------------------------------------------------- /puzzle_game/README: -------------------------------------------------------------------------------- 1 | 2015-01-02 2 | 修改内容: 3 | 8_puzzle 4 | 14_puzzle 5 | 24_puzzle 6 | 修改字符'Q'为游戏退出键 7 | 每次移动后增加了清屏功能 8 | 9 | 2013-03-19 10 | squared-up.scm 11 | 本来是想用scheme实现重排九宫游戏,因水平不够,暂且搁置。 12 | 目前实现了构造和打印矩阵的功能。 13 | 14 | 2012-08-07 15 | 改写了8_puzzle 16 | 改写了8_puzzle_auto 17 | 改写了15_puzzle 18 | 改写了24_puzzle 19 | 使这几个游戏都不存在无解的情况。 20 | 取消了无用的init_point函数。 21 | 删除了squared_sort。 22 | 23 | 2012-08-04 24 | 上传了24_puzzle 25 | 重排二十四,数字推盘游戏,不存在无解的情况。 26 | 27 | 2012-08-02 28 | 将jigsaw改名为8_puzzle。 29 | 重构了squared_sort,运行速度大大提升。 30 | 上传了8_puzzle_auto,重排九宫的自动运行版本。 31 | 32 | 2012-08-01 33 | 上传了15_puzzle 34 | 重排15,数字推盘游戏。 35 | 重排九宫的升级版本。 36 | 37 | 2012-07-31 38 | 上传了jigsaw 39 | 矩阵拼图游戏,对矩阵中的数字进行移动。 40 | 使之成为从小到大排序,squared_sort手动版。 41 | 'a' 向左移动,'d'向右移动,'s'向下移动,'w'向上移动。 42 | 摁'>'键退出。 43 | -------------------------------------------------------------------------------- /puzzle_game/makefile: -------------------------------------------------------------------------------- 1 | #运行 make 源代码名字(不带".c"后缀) 2 | #例如 make 8_puzzle 3 | #可以自动编译生成 8_puzzle可执行文件 4 | CC := gcc 5 | CFLAGS := -Wall 6 | clean: 7 | @echo "cleanning project" 8 | -rm -f *.exe 9 | @echo "clean completed" 10 | -------------------------------------------------------------------------------- /puzzle_game/squared-up.scm: -------------------------------------------------------------------------------- 1 | #!/bin/guile -s 2 | !# 3 | 4 | ;用scheme写的重排九宫游戏 5 | ;构造顺序矩阵 6 | (define (make-matrix wide) 7 | (define (make-list start end) 8 | (define (make-list-iter start end result) 9 | (if (> start end) 10 | result 11 | (make-list-iter start (- end 1) (cons end result)))) 12 | (make-list-iter start end '())) 13 | (define (make-matrix-iter wide high result) 14 | (let ((start (+ (* (- high 1) wide) 1)) 15 | (end (* high wide))) 16 | (if (< high 1) 17 | result 18 | (make-matrix-iter wide (- high 1) (cons (make-list start end) result))))) 19 | (make-matrix-iter wide wide '())) 20 | 21 | ;打印顺序矩阵 22 | (define (print-matrix matrix) 23 | (define (print-list lst) 24 | (if (null? lst) 25 | #f 26 | (begin 27 | (display (car lst)) 28 | (display "\t") 29 | (print-list (cdr lst))))) 30 | (if (null? matrix) 31 | #f 32 | (begin 33 | (print-list (car matrix)) 34 | (newline) 35 | (print-matrix (cdr matrix))))) 36 | 37 | ;求顺序矩阵第X行,第Y列的数值,行列数以1为初始值 38 | (define (value-matrix matrix x y) 39 | (list-ref (list-ref matrix (- x 1)) (- y 1))) 40 | 41 | 42 | ;测试,因编码水平不够,暂且搁置 2013-3-19 43 | (display (list-ref (list-ref '((1 2) 2 3 4) 0) 0)) 44 | (newline) 45 | (define x (make-matrix 4)) 46 | (display x) 47 | (newline) 48 | (print-matrix x) 49 | (display (value-matrix x 3 2)) 50 | (newline) 51 | -------------------------------------------------------------------------------- /random_game/README: -------------------------------------------------------------------------------- 1 | 2012-08-07 2 | 转移至random_game文件夹。 3 | 4 | 2012-07-29 5 | 上传了random_motion 6 | life_evolution变种,每次每个字符随机游走一步。 7 | 摁'\n'单步执行,摁其他字符+'\n'退出。 8 | 打印出执行步数和每次发生的碰撞数。 9 | 10 | 2012-07-28 11 | 重构了life_game 12 | 重构了life_evolution 13 | 重构了snake,改为单步执行版本。 14 | 重构了random_walk,最后一步用'*'注明。 15 | 代码演化树: random_walk 7-23 16 | | 17 | snake 7-25 18 | | 19 | life_game 7-26 20 | | 21 | life_evolution 7-27 22 | | 23 | color_4 7-28 24 | 25 | 2012-07-28 26 | 更新了color_4 27 | 使用结构体数组重构了代码。 28 | 封装了检测矩阵是否满的模块和打印整个矩阵的模块。 29 | 留出了矩阵边长和填充字符种类数量的接口,允许自定义。 30 | 31 | 2012-07-27 32 | 上传了color_4 33 | 生命游戏的变种,用四原色随机填满整个空间。 34 | 要求是每种颜色块中间不能有分割。 35 | 最后打印出所用的步数。 36 | 37 | 2012-07-27 38 | 上传了life_evolution 39 | life_game的单步执行版本。 40 | 摁回车单步执行,摁任意键+回车退出游戏。 41 | 42 | 2012-07-27 43 | 更新了life_game 44 | 第一代为4个生命元母体随机出现, 45 | 每一代每个母体向外拓展一格空间。 46 | 遇到其他生命群落或者空间边框,则停止,等待下一代。 47 | 总共演化100代,有时会出现规则形状。 48 | 49 | 2012-07-26 50 | 上传了life_game 51 | 生命游戏,四条贪吃蛇随机出现。 52 | 每条蛇随机游走5000步。 53 | 54 | 2012-07-25 55 | 上传了snake游戏 56 | 贪吃蛇从'0'开始随机游动,行走62步后存活则游戏成功。 57 | 游动路线是 0->9,A->Z,a->z 58 | 59 | 2012-07-25 60 | 更新了random_walk。 61 | 使用图形显示醉汉10步的路线图。 62 | 起始位置为'0',终点位置为最大数字。 63 | 64 | 2012-07-23 65 | 上传了醉汉漫步游戏。 66 | 起始坐标为(0,0),给出100步醉汉的坐标位置。 67 | -------------------------------------------------------------------------------- /random_game/makefile: -------------------------------------------------------------------------------- 1 | #运行 make 源代码名字(不带".c"后缀) 2 | #例如 make 8_puzzle 3 | #可以自动编译生成 8_puzzle可执行文件 4 | CC := gcc 5 | CFLAGS := -Wall 6 | clean: 7 | @echo "cleanning project" 8 | -rm -f *.exe 9 | @echo "clean completed" 10 | -------------------------------------------------------------------------------- /random_game/random_walk.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | #define MAX 20 6 | #define MAX_STEP 100 7 | typedef struct { 8 | int x; 9 | int y; 10 | } point; 11 | 12 | int roll( int max_num ); 13 | point init_point(int x, int y); 14 | point make_point( point spore, int n ); 15 | int one_step( void ); 16 | void printf_space( char (*s)[MAX] ); 17 | 18 | int main( void ) 19 | { 20 | int step; 21 | char space[MAX][MAX]; 22 | char class = '0'; 23 | 24 | /*初始化随机数发生器、space数组、spoce结构体*/ 25 | srand((unsigned)time(0)); 26 | point spore = {MAX/2 - 1, MAX/2 - 1}; 27 | memset( space, ' ', sizeof(space) ); 28 | space[spore.x][spore.y]= class; 29 | class++; 30 | 31 | /*每个标号每一次随机扩展一格。 32 | *执行100步。 */ 33 | for(step = 0; step < MAX_STEP; step++) { 34 | 35 | spore = make_point( spore, one_step() ); 36 | 37 | space[spore.x][spore.y]= class; 38 | switch(class) { 39 | case '9': class = 'A'; break; 40 | case 'Z': class = 'a'; break; 41 | case 'z': class = '0'; break; 42 | default : class++; 43 | } 44 | } 45 | 46 | /*最后一步用'*'号标明*/ 47 | space[spore.x][spore.y]= '*'; 48 | /*打印整个space数组,显示到屏幕上*/ 49 | printf_space( &space[0] ); 50 | 51 | /*打印出总共执行的步数step*/ 52 | printf("Used %d steps.\n", step); 53 | return 0; 54 | } 55 | 56 | 57 | /* 58 | ** roll 59 | ** 返回 0到max_num-1之间的随机整数。 60 | */ 61 | int roll(int max_num) 62 | { 63 | return rand()%max_num; 64 | } 65 | 66 | 67 | /* 68 | ** init_point 69 | ** 初始化ponit,返回point类型结构体。 70 | */ 71 | point init_point(int x, int y) 72 | { 73 | point temp; 74 | temp.x = x; 75 | temp.y = y; 76 | return temp; 77 | } 78 | 79 | 80 | /* 81 | ** make_point 82 | ** 返回数值为下一个坐标位置的point类型结构体。 83 | */ 84 | point make_point( point spore, int n ) 85 | { 86 | int temp_x = spore.x; 87 | int temp_y = spore.y; 88 | 89 | if(roll(2)) 90 | spore.x += n; 91 | else 92 | spore.y += n; 93 | if((spore.x < 0 || spore.x >= MAX) || (spore.y < 0 || spore.y >= MAX)) { 94 | spore.x = temp_x; 95 | spore.y = temp_y; 96 | } 97 | 98 | return spore; 99 | } 100 | 101 | 102 | /* 103 | ** one_step 104 | ** 返回 -1到1之间随机整数。 105 | */ 106 | int one_step( void ) 107 | { 108 | return (roll(3) - 1); 109 | } 110 | 111 | 112 | /* 113 | ** printf_space 114 | ** 打印整个space数组,显示到屏幕上。 115 | */ 116 | void printf_space( char (*s)[MAX] ) 117 | { 118 | int i, j; 119 | for(i = 0; i < MAX*2 + 2; i++) 120 | printf("-"); 121 | printf("\n"); 122 | 123 | for(i = 0; i < MAX; i++, s++) { 124 | printf("|"); 125 | for(j = 0; j < MAX; j++) 126 | printf("%c ", (*s)[j]); 127 | printf("|\n"); 128 | } 129 | 130 | for(i = 0; i < MAX*2 + 2; i++) 131 | printf("-"); 132 | printf("\n"); 133 | return; 134 | } 135 | 136 | -------------------------------------------------------------------------------- /testsql/form.sql: -------------------------------------------------------------------------------- 1 | --第一设计范式(单表) 2 | --数据表中的每个字段都不可再分。例如: 3 | CREATE TABLE member ( 4 | mid NUMBER, 5 | name VARCHAR2(50), 6 | email VARCHAR2(50), 7 | tel VARCHAR2(50), 8 | mobile VARCHAR2(50), 9 | CONSTRAINT pk_mid PRIMARY KEY(mid) 10 | ); 11 | 12 | --第二范式(多对多关系映射) 13 | --数据表之中不存在非关键字段对任意一候选关键字段的部分函数依赖。 14 | --1、数据表中两列之间不存在函数关系 15 | --2、数据表中两列之间不存在依赖关系 16 | 17 | --根据第一范式设计学生选课表 18 | CREATE TABLE student_course( 19 | stuid NUMBER , 20 | sname VARCHAR2(50), 21 | ctitle VARCHAR2(50), 22 | credit NUMBER, 23 | score NUMBER, 24 | CONSTRAINT pk_stuid PRIMARY KEY(stuid) 25 | ) ; 26 | 27 | --以上代码有缺陷,根据第二范式改进如下 28 | CREATE TABLE student ( 29 | stuid NUMBER, 30 | sname VARCHAR2(50), 31 | CONSTRAINT pk_stuid PRIMARY KEY(stuid) 32 | ); 33 | 34 | CREATE TABLE course ( 35 | cid NUMBER, 36 | ctitle VARCHAR2(50), 37 | credit NUMBER, 38 | CONSTRAINT pk_cid PRIMARY KEY(cid) 39 | ); 40 | 41 | CREATE TABLE student_course ( 42 | stuid NUMBER REFERENCES student(stuid) ON DELETE CASCADE, 43 | cid NUMBER REFERENCES course(cid) ON DELETE CASCADE, 44 | score NUMBER 45 | ); 46 | 47 | INSERT INTO student VALUES (1, '张三'); 48 | INSERT INTO student VALUES (2, '李四'); 49 | INSERT INTO student VALUES (3, '王五'); 50 | INSERT INTO course VALUES (10, '马克思主义哲学'); 51 | INSERT INTO course VALUES (11, 'Java'); 52 | INSERT INTO course VALUES (12, 'Oracle'); 53 | INSERT INTO student_course VALUES (1,10,90) ; 54 | INSERT INTO student_course VALUES (2,11,89) ; 55 | INSERT INTO student_course VALUES (1,11,99) ; 56 | INSERT INTO student_course VALUES (3,11,98) ; 57 | 58 | --第三范式(一对多) 59 | --数据表之中不存在非关键字段对任意一候选关键字段的传递函数依赖。 60 | --要求设计一张表,可以描述一个学校有多个学生 61 | CREATE TABLE school ( 62 | schid NUMBER , 63 | name VARCHAR2(50) , 64 | address VARCHAR2(200) , 65 | tel VARCHAR2(50) , 66 | CONSTRAINT pk_schid PRIMARY KEY(schid) 67 | ); 68 | 69 | CREATE TABLE student ( 70 | sid NUMBER , 71 | sname VARCHAR2(50) , 72 | schid NUMBER REFERENCES school(schid) 73 | ); 74 | -------------------------------------------------------------------------------- /testsql/mysqltest.sql: -------------------------------------------------------------------------------- 1 | --1、登录MySQL 2 | mysql -uroot -pmysqladmin 3 | 4 | --2、创建数据库 5 | DROP DATABASE mldn ; 6 | CREATE DATABASE mldn CHARACTER SET UTF8 ; 7 | 8 | --3、创建表 9 | DROP TABLE IF EXISTS member; 10 | CREATE TABLE member ( 11 | mid INT AUTO_INCREMENT, 12 | age INT NOT NULL, 13 | brithday DATETIME, 14 | name VARCHAR(50) NOT NULL, 15 | note TEXT, 16 | CONSTRAINT pk_mid PRIMARY KEY(mid) 17 | ) type=innodb; 18 | 19 | --4、查看表结构 20 | DESC member; 21 | 22 | --5、增加一行 23 | INSERT INTO member(age,brithday,name,note) VALUES(20,'1996-10-10 11:11:11','aa','aaa'); 24 | 25 | --6、取得自动增长的值 26 | SELECT LAST_INSERT_ID(); 27 | 28 | --7、分页处理 29 | SELECT * FROM member LIMIT 5,5; 30 | --------------------------------------------------------------------------------