![]() |
干练的火锅 · Mysql联表update数据 - ...· 7 月前 · |
![]() |
很酷的手套 · Excel中将所有图片在单元格居中并固定大小 ...· 1 年前 · |
![]() |
年轻有为的茄子 · 【Fetch】笔记_Yomuki的博客-CS ...· 1 年前 · |
![]() |
寂寞的杯子 · npm install安装失败报错:The ...· 1 年前 · |
![]() |
有胆有识的海龟 · How to get height of ...· 1 年前 · |
1 控件准备创建winform窗体,并将其IsMdiContainer属性设置为true1.1 Mdi窗体空间及设置(1)RibbonControl控件Navigation & Layout下添加RibbonControl控件(2)按钮添加添加按钮barbtn_database,Caption = “数据库处理”;1.2 数据库处理子窗体添加名称为dataBase的窗体添加dataGridView控件,属性设置如下:添加panel控件,设置Anchor属性为Top, Bottom, Left, Right在panel控件上拖拽四个button控件,2 实现代码2.1 名称空间引用添加名称空间引用:using System.Data.OleDb; //连接Access数据库使用添加名称空间引用:using System.Threading; //导出到excel使用添加名称空间引用:using Excel = Microsoft.Office.Interop.Excel;2.2 全局变量定义数据库链接字符串全局变量: string connectStr= @"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=你的数据库mdb文件路径\Database1.mdb";存放数据的中介变量System.Data.DataTable dt = new System.Data.DataTable(); //注:此处与Excel的名称空间冲突,故使用全名2.3 在窗体Load事件中添加代码显示数据 //加载数据库 private void dataBase_Load(object sender, EventArgs e) OleDbConnection connection = new OleDbConnection(connectStr); connection.Open(); OleDbCommand cmd = connection.CreateCommand(); cmd.CommandText = "select * from fruit"; OleDbDataAdapter adapter = new OleDbDataAdapter(cmd); DataSet ds = new DataSet(); adapter.Fill(ds); dt = ds.Tables[0]; dataGridView1.DataSource = dt; connection.Close(); cmd.Dispose(); connection.Dispose(); }2.4 数据库更新代码//更新数据到数据库中 private void btn_updataToDatabase_Click(object sender, EventArgs e) OleDbConnection connection = new OleDbConnection(connectStr); connection.Open(); OleDbCommand cmd = connection.CreateCommand(); cmd.CommandText = "select * from fruit"; OleDbDataAdapter adapter = new OleDbDataAdapter(cmd); OleDbCommandBuilder cmdBulid = new OleDbCommandBuilder(adapter); adapter.DeleteCommand = cmdBulid.GetDeleteCommand(); adapter.InsertCommand = cmdBulid.GetInsertCommand(); adapter.UpdateCommand = cmdBulid.GetUpdateCommand(); adapter.Update((System.Data.DataTable)dataGridView1.DataSource); adapter.Dispose(); cmdBulid.Dispose(); cmd.Dispose(); connection.Dispose(); }2.5 删除DataGridView数据记录代码 //删除dataGridView中的记录 private void btn_deleteDataItem_Click(object sender, EventArgs e) int cnt = dataGridView1.SelectedRows.Count; for (int i = 0; i < cnt; i++) DataRowView drv = dataGridView1.SelectedRows[i].DataBoundItem as DataRowView; drv.Delete(); }2.6 更新数据库代码 //更新数据到数据库中 private void btn_updataToDatabase_Click(object sender, EventArgs e) OleDbConnection connection = new OleDbConnection(connectStr); connection.Open(); OleDbCommand cmd = connection.CreateCommand(); cmd.CommandText = "select * from fruit"; OleDbDataAdapter adapter = new OleDbDataAdapter(cmd); OleDbCommandBuilder cmdBulid = new OleDbCommandBuilder(adapter); adapter.DeleteCommand = cmdBulid.GetDeleteCommand(); adapter.InsertCommand = cmdBulid.GetInsertCommand(); adapter.UpdateCommand = cmdBulid.GetUpdateCommand(); adapter.Update((System.Data.DataTable)dataGridView1.DataSource); adapter.Dispose(); cmdBulid.Dispose(); cmd.Dispose(); connection.Dispose(); }2.7 输出到Excel代码//导出数据到Excel表格中 private void btn_ouputToExcel_Click(object sender, EventArgs e) SaveFileDialog saveDlg = new SaveFileDialog(); saveDlg.Filter = "*.xls|*.xls"; string outputStr; if (saveDlg.ShowDialog() == System.Windows.Forms.DialogResult.OK) Excel._Application myExcel; ThreadPool.QueueUserWorkItem( (pp) => { myExcel = new Microsoft.Office.Interop.Excel.Application(); Excel.Workbook p_wk = myExcel.Workbooks.Add(); Excel.Worksheet p_ws = (Excel.Worksheet)p_wk.Worksheets.Add(); for (int i = 0; i < dataGridView1.Rows.Count - 1; i++) p_ws.Cells[i + 1, 1] = dataGridView1.Rows[i].Cells[0].Value.ToString(); p_ws.Cells[i + 1, 2] = dataGridView1.Rows[i].Cells[1].Value.ToString(); p_ws.Cells[i + 1, 3] = dataGridView1.Rows[i].Cells[2].Value.ToString(); p_wk.SaveAs(saveDlg.FileName); ((Excel._Application)myExcel.Application).Quit(); this.Invoke((MethodInvoker)(() => { MessageBox.Show("导出到Excel成功", "提示信息"); })); outputStr = saveDlg.FileName; saveDlg.Dispose(); }3 界面展示3.1 原始数据库及数据载入3.2 删除和增加记录3.3 数据库更新3.4 导出到Excel4 总结及疑问4.1 成果总结:系统练习了使用C#进行数据库更新、删除和修改操作,并将dataGridView中的数据导出到Excel表格中;4.2 仍存在的问题:(1)数据库采用自动编号,我手动输入的ID与更新后的数据库ID不一致,有待深入研究改善;(2)刷新ID仅仅是在DataGridView控件中进行的,并未实际更新到数据库中
需求说明:删除数据库中的表格所有数据,但是保留表的原始结构使用到的sql语句:delete * form tableName1 准备工作2 C#操作代码2.1 自定义函数链接数据库并处理 /// <summary> /// 对连接的数据库执行响应的处理指令 /// </summary> /// <param name="connectStr"> 定义的数据库连接字符串 </param> /// <param name="sqlStr"> 要执行的SQL指令 </param> private void sqlCmd(string connectStr, string sqlStr) OleDbConnection conn = new OleDbConnection(connectStr); conn.Open();//注意增删改查的代码均插入在该行代码之后 OleDbCommand comm = conn.CreateCommand(); comm.CommandText = sqlStr; comm.Connection = conn; //这句话位置只能放在这里,不能前边 comm.ExecuteNonQuery(); comm.Dispose(); conn.Close(); catch (Exception ee) MessageBox.Show(ee.Message.ToString()); finally conn.Close(); }2.2 清空数据中的table1表 private void clearDataTable_Click(object sender, EventArgs e) string txtConn = @"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=E:\C#\Example200\AccessLearn\AccessLearn\bin\Debug\myExcise.mdb"; //删除数据表中所有数据 string strcomm = "delete * from table1"; sqlCmd(txtConn, strcomm); //重置ID从1开始 string strIter = "Alter TABLE table1 Alter COLUMN ID COUNTER (1, 1)"; sqlCmd(txtConn, strIter); }2.3结果展示
所谓并行程序开发是我们不关系任务什么时候执行,只关心怎么利用计算机资源更快的执行。并行编程是指软件开发的代码,它能在同一时间执行多个计算任务,提高执行效率和性能一种编程方式,属于多线程编程范畴。所以我们在设计过程中一般会将很多任务划分成若干个互相独立子任务,这些任务不考虑互相的依赖和顺序。NET Framework4.0引入了Task Parallel Library(TPL)实现了基于任务设计而不用处理重复复杂的线程的并行开发框架。它支持数据并行,任务并行与流水线。核心主要是Task,但是一般简单的并行我们可以利用Parallel提供的静态类如下三个方法。 Parallel.Invoke 对给定任务实现并行开发 Parallel.For 对固定数目的任务提供循环迭代并行开发 parallel.Foreach 对固定数目的任务提供循环迭代并行开发注意:所有的并行开发不是简单的以为只要将For或者Foreach换成Parallel.For与Parallel.Foreach这样简单。1 For, Foreach和Parallel.For、Parallel.Foreach1.1 基本分析for与foreach相对于原来的for语句foreach具有更好的执行效率for与Parallel.For区别:从CPU使用方面而言,Parallel.For 属于多线程范畴,可以开辟多个线程使用CPU内核,也就是说可以并行处理程序。For 循环是单线程的,一个线程执行完所有循环。也就说For是同步,Parallel.For 是异步执行。任务的开销大小对并行任务的影响:如果任务很小,那么由于并行管理的附加开销(任务分配,调度,同步等成本),可能导致并行执行并不是最优化方案。Parallel.ForEach 和 ForEach 与 Parallel.For 和 For 一样,一个是异步执行,开辟多个线程。一个是同步执行,开辟一个线程。因此,效率方面同上,主要看执行的什么任务。Parallel.For不能添加ref或out修饰的变量,错误提示为:不能在匿名表达式、lanmda表达式或查询表达式内使用ref或out变量停止并行For循环的方法:在 Parallel.For 或 Parallel.ForEach 循环中,不能使用与顺序循环中相同的 break 或 Exit 语句,这是因为这些语言构造对于循环是有效的,而并行“循环”实际上是方法,不是循环。 相反,可以使用 Stop 或 Break 方法。 Parallel.For 的一些重载接受 Action<int, ParallelLoopState>作为输入参数。 ParallelLoopState 对象由运行时在后台创建,你可以在 lambda 表达式中为它指定你喜欢的任何名称。在 Action<int, ParallelLoopState>的委托方法中调用ParallelLoopState参数的Stop或Break方法。Stop 方法;它将告知循环的所有迭代(包括那些在其他线程上的当前迭代之前开始的迭代)在方便的情况下尽快停止。Break 方法;它会导致其他线程放弃对后续片段的工作(如果它们正忙于任何这样的工作),并在退出循环之前处理完所有前面的元素。区别就在于,Stop仅仅通知其他迭代尽快结束,而Break不仅通知其他迭代尽快结束,同时还要保证退出之前要完成LowestBreakIteration之前的迭代。 例如,对于从 0 到 1000 并行迭代的 for 循环,如果从第 100 此迭代开始调用 Break,则低于 100 的所有迭代仍会运行,从 101 到 1000 的迭代则不必要。而调用Stop方法不保证低于 100 的所有迭代都会运行。1.2 示例代码 public static void test() Parallel.For(1, 5, x=> Console.WriteLine(x); Console.WriteLine("------------------------"); var numbers = Enumerable.Range(103, 8); Parallel.ForEach(numbers, x => Console.WriteLine(x); Console.WriteLine("------------------------"); Parallel.Invoke( ()=>{ Console.WriteLine("ABC");}, ()=>{ Console.WriteLine("xxxOMG");}, ()=>{ Console.WriteLine("MMG");}, ()=>{ Console.WriteLine("oooMMG");}, () => { Console.WriteLine("999ABC"); }, ()=>{ Console.WriteLine("888MMG");} }运行结果截图:2 Parallel.Invoke两个重载方法: public static void Invoke(params Action[] actions); public static void Invoke(ParallelOptions parallelOptions, params Action[] actions);2.1 action调用模式及示例2.1.1 调用方法解释//方式一 Parallel.Invoke(() => Task1(), () => Task2(), () => Task3()); //方式二 Parallel.Invoke(Task1, Task2, Task3); //方式三 Parallel.Invoke( () => Task1(); Task2, delegate () { Task3(); console.write('do someting!');});2.1.2 示例代码public class ParallelInvoke /// <summary> /// Invoke方式一 action /// </summary> public void Client1() Stopwatch stopWatch = new Stopwatch(); Console.WriteLine("主线程:{0}线程ID : {1};开始", "Client1", Thread.CurrentThread.ManagedThreadId); stopWatch.Start(); Parallel.Invoke(() => Task1("task1"), () => Task2("task2"), () => Task3("task3")); stopWatch.Stop(); Console.WriteLine("主线程:{0}线程ID : {1};结束,共用时{2}ms", "Client1", Thread.CurrentThread.ManagedThreadId, stopWatch.ElapsedMilliseconds); private void Task1(string data) Thread.Sleep(5000); Console.WriteLine("任务名:{0}线程ID : {1}", data, Thread.CurrentThread.ManagedThreadId); private void Task2(string data) Console.WriteLine("任务名:{0}线程ID : {1}", data, Thread.CurrentThread.ManagedThreadId); private void Task3(string data) Console.WriteLine("任务名:{0}线程ID : {1}", data, Thread.CurrentThread.ManagedThreadId); }调用: using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Diagnostics; using System.Threading; namespace myParallel class Program static void Main(string[] args) ParallelInvoke pi = new ParallelInvoke(); pi.Client1();
栅格数据集的创建过程创建栅格数据工作空间工厂类,使用API:IRasterWorkspaceFactory myWorkFact = new IRasterWorkspaceFactoryClass();创建栅格数据工作空间:IRasterWorkspace myWorkspace = (IRasterWorkspace )myWorkFact .OpenFromFile(srcFileFolder, 0);//指定为目录项工作空间导入栅格数据集:IRasterDataset rasterDataset = (IRasterDataset)myWorkspace.OpenRasterDataset(srcFileName);创建栅格图层:创建对象:IRasterLayer rasterLayer = new RasterLayerClass();从栅格数据集中得到栅格图层:rasterLayer.CreateFromDataset(rasterDataset );由栅格图层生成栅格属性表:IRasterProps rasterProps = rasterLayer.Raster as IRasterProps ;由栅格数据集构建栅格波段集合:IRasterBandCollection pRasterBandCollection = rasterDataset as IRasterBandCollection;栅格数据集的读取过程单波段栅格数据读取过程(如果用于多波段,设置循环读取多次即可)IRasterBand pRasterBand= pRasterBandCollection.Item(bandIndex);创建元数据像素块:IRawPixels pRawPixel = pRasterBand as IRawPixels;像素块设置:IPixelBlock pixelBlock; //这里定义的是一维像素块像素块的尺寸:IPnt pixelBlockSize = new PntClass(); pixelBlockSize.SetCoords(rasterProps.width, rasterProps.Height);设置读取起始位置:IPnt pOrignPt = new PntClass(); pOrignPt.SetCoords(0,0);//指定起始行列数像素读取:pRawPixel.Read(pOrignPt, pixelBlock); //起始位置,像素块给System.Array赋值:System.Array[] srcPixelArray = new System.Array[3]; srcPixelArray[bandIndex] = (pixelBlock as IPixelBlock3).get_PixelData(0);注意:get_PixelData(0)前的像素块如果是继承字单个波段,则为一个二维像素块;如果继承自三个波段的栅格影像,则为三个二维像素块。因此,此处得到的数组srcPixelArray等价于==>int[] arraySize = {rasterProps.width, rasterProps.Height};System.Array srcArray = System.Array.CreateInstance(typeof(int), arraySize);对于单/三波段栅格数据,像素值被读取并存储在srcPixelArray中;此处应注意在进行数据批量处理时,由于数据包含三个波段,需对数组的每个维度进行释放,释放完成后对数组的整体进行释放;示例代码:for(int i = 0; i < 3; i++) srcPixelArray[i] = null; srcPixelArray = null;三波段栅格数据读取过程(光标法获取三波段像素值)设置读取起始位置:IPnt pOrignPt = new PntClass(); pOrignPt.SetCoords(0,0);创建栅格数据:IRaster2 pRaster2 = rasterLayer.Raster as IRaster2;创建栅格光标:IRasterCursor rasterCursor = pRaster2.CreateCursorEx(pOrignPt);//指定光标起始位置创建栅格像素块:IPixelBlock3 pixelBlock3 = rasterCursor.PixelBlock as IPixelBlock3;得到单波段像素数据:System.Array srcPixelArray = (pixelBlock as IPixelBlock3).get_PixelData(0) as System.Array;栅格数据集的输出过程创建栅格数据工作空间工厂类,使用API:IRasterWorkspaceFactory ouWorkFact = new IRasterWorkspaceFactoryClass();创建栅格数据工作空间:IRasterWorkspace ouWorkspace = (IRasterWorkspace )myWorkFact .OpenFromFile(dstFileFolder, 0);//指定为目录项指定起始像素:IPoint ouPointOrgin = new PointClass(); ouPointOrgin.PutCoords(rasterProps.Extend.LowerLeft.X, rasterProps.Extend.LowerLeft.Y);创建输出栅格数据集IRasterDataset2 ouRasterDataset = (IRasterDataset2)ouWorkspace.CreateRasterDataset(dstFileName, dataFormat, ouPointOrgin, rasterProps.width, rasterProps.Height, rasterProps.MeanCellSize().X, rasterProps.MeanCellSize().Y, bandCnt, rstPixelType.PT_UCHAR, new unkonwnCoordinateSystemClass(), true);创建全波段栅格数据:IRaster ouRaster = ouRasterDataset.CreateFullRaster();创建输出栅格图层:IRasterLayer ouRasterLayer = new RasterLayerClass(); ouRasterLayer .CreateFromDataset(ouRasterDataset);创建输出像素块:IPixelBlock3 ouPixelBlock = ouRaster.CreatePixelBlock(pixelBlockSize) as IPixelBlock3; //需指定像素块的尺寸为输出像素块赋值:ouPixelBlock.set_PixelData(bandIndex, srcPixelArray[bandIndex]);//指定参数为波段索引和该波段对应的像素数组输出栅格数据IRasterEdit rasterEdit = (IRasterEdit)ouRaster;指定左上角起始位置:IPnt leftUp= new PntClass(); leftUp.SetCoords(0,0);写入:rasterEdit.Write(leftUp, (IPixelBlock3 )ouPixelBlock);数据清理:System.Runtime.InteropServices.Marshal.ReleaseComObject(IRasterEdit);
问题说明:一直使用的vs2010的版本,突然换到vs2015,新建项目时发现没有"windows窗体应用程序选项"问题原因:在vs2015中存在Blend for Visual Studio 2015 和 Visual studio2015两种模式,前者倾向于美工界面设计,后者才是程序员经常使用的编码模式。1 Blend for Visual Studio 2015从您的安装路径的...\Microsoft Visual Studio 14.0\Common7\IDE目录下找到Blend.exe双击,进入如下界面:点击新建项目,进入如下界面:2 Visual studio2015从您的安装路径的...\Microsoft Visual Studio 14.0\Common7\IDE目录下找到devenv.exe双击,进入如下界面:点击新建项目,进入如下界面:就可以看到我们熟悉的“windows窗体应用程序”界面了。3 英文界面变中文界面(1)Tools --> Options(2)Environment --> International Settings -->中文(简体)-->OK两点注意事项:(1)设置后完成后,需重启编译器才能生效(2)如果没有下载中文语言包,则点击Get additional languages进入网页https://www.microsoft.com/en-us/download/details.aspx?id=48157,选择Chinese(Simplified),,直接下载即可下载完成后直接安装即可。
控件准备:新建windows窗体应用程序,添加一个标记按钮(btn_tagPos)、标签控件(经度和纬度,实时经纬度显示)、编辑框控件(记录输入的经度和纬度值)、webbroswer控件(webbroswer1)和计时器控件(timer1)实现代码:添加引用:using System.Security.Permissions;在项目的第一行添加代码:1. [PermissionSet(SecurityAction.Demand, Name = "FullTrust")] 2. [System.Runtime.InteropServices.ComVisibleAttribute(true)](1)在窗体加载时,显示地图到webbroswer控件中(IndexMap.html为百度地图显示的文件) private void Form5_Load_1(object sender, EventArgs e) Uri url = new Uri(Application.StartupPath + "\\IndexMap.html"); webBrowser1.Url = url; webBrowser1.ObjectForScripting = this; //webBrowser1.ScriptErrorsSuppressed = true; timer1.Enabled = true; }(2)在计时器中添加代码,用于显示实时坐标private void timer1_Tick(object sender, EventArgs e) string tag_lng = webBrowser1.Document.GetElementById("mouselng").InnerText; string tag_lat = webBrowser1.Document.GetElementById("mouselat").InnerText; double dou_lng, dou_lat; if (double.TryParse(tag_lng, out dou_lng) && double.TryParse(tag_lat, out dou_lat)) this.lab_lb.Text = "当前坐标:" + dou_lng.ToString("F5") + "," + dou_lat.ToString("F5"); catch (Exception ee) //MessageBox.Show(ee.Message); }(3)输入坐标显示经纬度private void btn_tagpos_Click_1(object sender, EventArgs e) if(txb_jingdu == null || txb_weidu == null) MessageBox.Show("请检查是否填入了经纬度坐标!", "坐标错误提示"); return; //"116.399", " 39.910" object[] args = { txb_jingdu.Text, txb_weidu.Text}; webBrowser1.Document.InvokeScript("addMarker", args); }对应html文件的JScript代码,首先清除已有标记,然后在添加新的标记:function addMarker(x, y) { map.clearOverlays(); //清除地图中已有的标记 var point = new BMap.Point(x, y); var marker = new BMap.Marker(point); // 创建标注 map.addOverlay(marker); //用于添加标记 map.centerAndZoom(point, 11); //用于将地图缩放至输入的坐标点 }拓展代码:deletePoint函数,先调用getOverlays()函数用于得到所有覆盖物信息;再调用的removeOverlay()函数是一次移除一个指定覆盖物function deletePoint(){ var allOverlay = map.getOverlays(); for (var i = 0; i < allOverlay.length -1; i++){ if(allOverlay[i].getLabel().content == "我是id=1"){ map.removeOverlay(allOverlay[i]); return false; }附件:用到的IndexMap.html文件 <!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>Hello Map</title> <script type="text/javascript"src="http://api.map.baidu.com/api?key=59db371659c04947a1ff044e80565718&v=1.4&services=true"> </script> <!--加载鼠标测距工具--> <script src="DistanceTool_min.js" type="text/javascript"></script> <!--加载鼠标绘制工具--> <script type="text/javascript" src="DrawingManager_min.js"></script> <link rel="stylesheet" href="DrawingManager_min.css" /> </head> <body> <div id="mouselng" style=""></div> <div id="mouselat" style=""></div> <div style="width:1000px;height:600px;border:1px solid gray" id="container"> </div> </body> </html> <script type="text/javascript"> var map = new BMap.Map("container"); map.centerAndZoom(new BMap.Point(108.876433, 36.269395), 5); map.addControl(new BMap.ScaleControl()); //添加比例尺控件(左下角显示的比例尺控件) map.addControl(new BMap.OverviewMapControl());// 缩略图控件 var ctrl_nav = new BMap.NavigationControl({ anchor: BMAP_ANCHOR_TOP_LEFT, type: BMAP_NAVIGATION_CONTROL_LARGE }); map.addControl(ctrl_nav);//添加标准地图控件(左上角的放大缩小左右拖拽控件) map.enableDragging(); //启用地图拖拽事件,默认启用(可不写) map.enableScrollWheelZoom(); //启用地图滚轮放大缩小 map.enableDoubleClickZoom(); //启用鼠标双击放大,默认启用(可不写) map.enableKeyboard(); //启用键盘上下左右键移动地图 map.enableContinuousZoom(); // 开启连续缩放效果 map.enableInertialDragging(); // 开启惯性拖拽效果 //实时显示地图坐标 strat map.addEventListener("mousemove",GetlngAndlat); function GetlngAndlat(e) { if(e.point.lng!=null) document.getElementById("mouselng").innerHTML=e.point.lng; document.getElementById("mouselat").innerHTML=e.point.lat; //实时显示地图坐标 end //测量距离 strat function openGetDistance() { var myDis=new BMapLib.DistanceTool(map);//map为上面已经初始化好的地图实例 myDis.open(); //测量距离 end //左右击鼠标给地图上放marker strat 放标注,并且将JS的数据传送给WINFORM function PUTANDSEND() { //右键标记 map.addEventListener("rightclick", putAndsend); //左键标记 //map.addEventListener("click", putAndsend); var marker_num = 0; function putAndsend(e) //放标注 var p1=new BMap.Point(e.point.lng,e.point.lat); var myIcon = new BMap.Icon("png-0003.png", new BMap.Size(24, 24)); var marker = new BMap.Marker(p1, { icon: myIcon }); // 创建标注 map.addOverlay(marker); // 将标注添加到地图中 marker_num++;//标注索引,这个是个全局变量 var whichCar=window.external.setWhichCar(); var label=new BMap.Label(whichCar+"号车-坐标"+marker_num+":"+ "("+e.point.lng+","+e.point.lat+")",{offset:new BMap.Size(20,-10)}); marker.setLabel(label); //给WINFORM传值 window.external.PutIntotextBox(marker_num,whichCar,e.point.lng,e.point.lat); //左右击鼠标给地图上放marker end //在地图上画轨迹 strat function DrawOrit1() var Array=[]; var total_num= window.external.getRowsNumber(); for(var i=0;i<=2*total_num-1;i++) Array.push(window.external.Getpoints(i)); var PointArr=[]; for(var i=0;i<=Array.length-1;i+=2) {//偶数索引存经度,奇数存维度 PointArr.push(new BMap.Point(Array[i],Array[i+1])); var polyline = new BMap.Polyline(PointArr, {strokeColor:"blue", strokeWeight:6, strokeOpacity:0.5}); //定义折线 map.addOverlay(polyline); window.external.ClearRows_num();//重置窗体计数器 //在地图上画轨迹 end //在地图上画圆形或者方形 strat // 编写自定义函数,创建标注 function addMarker(point) { var myIcon = new BMap.Icon("png-0003.png", new BMap.Size(24, 24)); var marker = new BMap.Marker(point, { icon: myIcon }); // 创建标注 map.addOverlay(marker); // 将标注添加到地图中 function addMarker(x, y) { map.clearOverlays(); var point = new BMap.Point(x, y); var marker = new BMap.Marker(point); // 创建标注 map.addOverlay(marker); map.centerAndZoom(point, 11); var overlays = []; var complete=function(e) overlays.push(e.overlay); if (e.drawingMode == BMAP_DRAWING_CIRCLE) //随便赋值,刷新一遍数据库(此方法只为演示,实际中要另考虑算法) var test= window.external.SearchAllCars(0); var circle_radius=e.overlay.getRadius();//半径 var circle_point=new BMap.Point(e.overlay.getCenter().lng,e.overlay.getCenter().lat); //从WINFORM里取出数据 var dangerCars=[]; var pointlen=window.external.GetdangerNum(); for(var k=0;k<=pointlen-1;k++) dangerCars.push(window.external.SearchAllCars(k)); var BMappoints=[];//创建百度地图接口规定的数组 for(var j=0;j<=dangerCars.length-1;j+=2) BMappoints.push(new BMap.Point(dangerCars[j],dangerCars[j+1])); for(var i=0;i<=BMappoints.length-1;i++) if(map.getDistance(circle_point,BMappoints[i])<=circle_radius) //AddMarker(BMappoints[i]);//调用添加标注版本V3.0 var myIcon = new BMap.Icon("png-0003.png", new BMap.Size(24, 24)); var marker1 = new BMap.Marker(BMappoints[i], { icon: myIcon }); // 创建标注 map.addOverlay(marker1); // 将标注添加到地图中 //线条样式 var styleOptions = { strokeColor:"blue", //边线颜色。 fillColor:"blue", //填充颜色。当参数为空时,圆形将没有填充效果。 strokeWeight: 3, //边线的宽度,以像素为单位。 strokeOpacity: 1, //边线透明度,取值范围0 - 1。 fillOpacity: 0.3, //填充的透明度,取值范围0 - 1。 strokeStyle: 'solid' //边线的样式,solid或dashed。 //实例化鼠标绘制工具 var drawingManager = new BMapLib.DrawingManager(map, { isOpen: true, //是否开启绘制模式 enableDrawingTool: true, //是否显示工具栏 drawingToolOptions: { anchor: BMAP_ANCHOR_TOP_RIGHT, //位置 offset: new BMap.Size(5, 5), //偏离值 scale: 0.8, //工具栏缩放比例 drawingTypes : [ BMAP_DRAWING_CIRCLE, BMAP_DRAWING_RECTANGLE circleOptions: styleOptions, //圆的样式 rectangleOptions: styleOptions //矩形的样式 //添加鼠标绘制工具监听事件,用于获取绘制结果 drawingManager.addEventListener('overlaycomplete', complete); //回调获得覆盖物信息,未使用该版本 var overlaycomplete = function (e) { overlays.push(e.overlay); var result = ""; result += e.drawingMode + ":"; if (e.drawingMode == BMAP_DRAWING_CIRCLE) { var circle_radius = e.overlay.getRadius(); var circle_point = new BMap.Point(e.overlay.getCenter().lng, e.overlay.getCenter().lat); alert(map.getDistance(circle_point, tests[1])); for (var i = 0; i < 3; i++) { if (map.getDistance(circle_point, tests[i]) <= circle_radius) { //AddMarker(tests[i]); var myIcon = new BMap.Icon("png-0003.png", new BMap.Size(24, 24)); var marker1 = new BMap.Marker(tests[i], { icon: myIcon }); // 创建标注 map.addOverlay(marker1); // 将标注添加到地图中 alert(result); if (e.drawingMode == BMAP_DRAWING_POLYLINE || e.drawingMode == BMAP_DRAWING_POLYGON || e.drawingMode == BMAP_DRAWING_RECTANGLE) { result += ' 所画的点个数:' + e.overlay.getPath()[1].lng; alert(result); //drawingManager.enableCalculate(); //----------------------公用方法,用元素id获取元素的值------------------- function $(id){ return document.getElementById(id); //------------------画矩形,让WINFORM调用--------------- function drawRec(){ drawingManager.setDrawingMode(BMAP_DRAWING_RECTANGLE);} //------------------画圆,让WINFORM调用---------------- function drawCircle(){ drawingManager.setDrawingMode(BMAP_DRAWING_CIRCLE);} //------------------清除所有已画图形,让WINFORM调用-------------------- function clearAll() { for(var i = 0; i < overlays.length; i++){ map.removeOverlay(overlays[i]); overlays.length = 0 //在地图上画圆形或者方形 end </script>
需求说明:北斗周-周内秒转化为日历时,转化为UTC时,转化为GPS周周内秒GPS周-周内秒转化为日历时,转化为UTC时,转化为北斗周-周内秒设计示意图:源代码:using System; using System.Collections.Generic; using System.Linq; using System.Text; //这是一个BDS/GPS周、周内秒与日历时、UTC时的转换与逆转换程序 //自定义缩略语说明:WIS为周内秒,week inner second; NYR,年月日的拼音首字母缩写 //本程序主要实现以下几个功能: //(1) GPS Week WIS <--> NYR //(2) GPS Week WIS <--> UTC //(3) BDS Week WIS <--> NYR //(4) BDS Week WIS <--> UTC //(5) BDS Week WIS <--> GPS Week WIS namespace BDS_GPS_UTC class Program ///功能模块一:GPS周-周内秒与日历时的转换与逆转换/// //GPS周-周内秒到年月日系统的转换 static private DateTime gpsWeekWIS2NYR(int gpsWeek, int gpsWIS) int difFromBegin = gpsWeek * 604800 + gpsWIS; DateTime gpsBeginTime = new DateTime(1980,1,6,0,0,0); return gpsBeginTime.AddSeconds(difFromBegin); //GPS日历时与周-周内秒的转换 static private int[] gpsNYR2WeekWIS(DateTime gpsNYR) int[] gpsWeekWIS = {0, 0}; DateTime gpsBeginUTC = new DateTime(1980,1,6,0,0,0); //计算两个UTC时的时间间隔 TimeSpan interval = gpsNYR - gpsBeginUTC; int gpsWeek = (int)interval.TotalSeconds / 604800; int gpsWIS = (int)interval.TotalSeconds % 604800; gpsWeekWIS[0] = gpsWeek; gpsWeekWIS[1] = gpsWIS; return gpsWeekWIS; ///功能模块二:GPS周-周内秒与UTC时间系统的转换与逆转换/// //GPS周-周内秒到UTC时间系统的转换 static private DateTime gpsWeekWIS2UTC(int gpsWeek, int gpsWIS) DateTime gpsNYR = gpsWeekWIS2NYR(gpsWeek, gpsWIS); //GPS日历时比UTC时快18秒 return gpsNYR.AddSeconds(-18.0); //GPS UTC时间系统到周-周内秒的转换 static private int[] gpsUTC2WeekWIS(DateTime gpsUTC) return gpsNYR2WeekWIS(gpsUTC.AddSeconds(18)); ///功能模块三:BDS周-周内秒与日历时的转换与逆转换/// //BDS周-周内秒到年月日时间系统的转换 static private DateTime bdsWeekWIS2NYR(int bdsWeek, int bdsWIS) int difFromBegin = bdsWeek * 604800 + bdsWIS; DateTime bdsBeginTime = new DateTime(2006, 1, 1, 0, 0, 0); return bdsBeginTime.AddSeconds(difFromBegin); //年月日时间系统到BDS周-周内秒的转换 static private int[] bdsNYR2WeekWIS(DateTime bdsNYR) //先转换到UTC时间系统 DateTime bdsBeginUTC = new DateTime(2006, 1, 1, 0, 0, 0); //计算当前UTC回推出BDS起始时刻UTC的时间差 TimeSpan interval = bdsNYR - bdsBeginUTC; int[] bdsWeekWIS = {0,0}; int bdsWeek = (int)interval.TotalSeconds / 604800; int bdsWIS = (int)interval.TotalSeconds % 604800; bdsWeekWIS[0] = bdsWeek; bdsWeekWIS[1] = bdsWIS; return bdsWeekWIS; ///功能模块四:BDS周-周内秒与UTC时间系统的转换与逆转换/// //BDS周-周内秒到UTC时间系统的转换 static private DateTime bdsWeekWIS2UTC(int bdsWeek, int bdsWIS) DateTime bdsNYR = bdsWeekWIS2NYR(bdsWeek, bdsWIS); //BDS日历时比UTC时快4秒 return bdsNYR.AddSeconds(-4.0); //UTC时间系统到BDS周-周内秒的转换 static private int[] bdsUTC2WeekWIS(DateTime bdsUTC) return bdsNYR2WeekWIS(bdsUTC.AddSeconds(4)); ///功能模块五:GPS周-周内秒与BDS周-周内秒转换与逆转换/// //GPS周-周内秒向BDS周-周周内秒的转换 static private int[] gpsWeekWIS2bdsWeekWIS(int gpsWeek, int gpsWIS) int[] bdsWeekWIS = {0,0}; int difFromBegin = gpsWeek * 604800 + gpsWIS - 1356 * 604800 - 14; int bdsWeek = difFromBegin / 604800; int bdsWIS = difFromBegin % 604800; bdsWeekWIS[0] = bdsWeek; bdsWeekWIS[1] = bdsWIS; return bdsWeekWIS; //BDS周-周内秒到GPS周-周内秒的转换 static private int[] bdsWeekWIS2gpsWeekWIS(int bdsWeek, int bdsWIS) int[] gpsWeekWIS = {0,0}; int secDifGPS2BDS = bdsWeek * 604800 + bdsWIS + 1356 * 604800 + 14; int gpsWeek = secDifGPS2BDS / 604800; int gpsWIS = secDifGPS2BDS % 604800; gpsWeekWIS[0] = gpsWeek; gpsWeekWIS[1] = gpsWIS; return gpsWeekWIS; static void Main(string[] args) int[] gpsWeekWIS = { 2023, 432000}; Console.Write("0 GPS周-周内秒:"); Console.WriteLine("GPS周:{0:D},周内秒:{1:D}", gpsWeekWIS[0], gpsWeekWIS[1]); Console.Write("1.1 GPS周-周内秒对应日历时:"); Console.WriteLine(gpsWeekWIS2NYR(gpsWeekWIS[0], gpsWeekWIS[1])); Console.Write("2.1 GPS周-周内秒对应UTC时:"); Console.WriteLine(gpsWeekWIS2UTC(gpsWeekWIS[0], gpsWeekWIS[1])); Console.Write("5.1 GPS周-周内秒转BDS周-周内秒:"); int[] bdsWeekWIS = gpsWeekWIS2bdsWeekWIS(gpsWeekWIS[0], gpsWeekWIS[1]); Console.WriteLine("北斗周:{0:D},周内秒: {1:D}", bdsWeekWIS[0], bdsWeekWIS[1]); Console.Write("3.1 BDS周-周内秒对应日历时:"); Console.WriteLine(bdsWeekWIS2NYR(bdsWeekWIS[0], bdsWeekWIS[1])); Console.Write("4.1 BDS周-周内秒对应UTC时:"); Console.WriteLine(bdsWeekWIS2UTC(bdsWeekWIS[0], bdsWeekWIS[1])); Console.Write("5.2 BDS周-周内秒转GPS周-周内秒:"); int[] gpsWeekWISFromBDS = bdsWeekWIS2gpsWeekWIS(bdsWeekWIS[0], bdsWeekWIS[1]); Console.WriteLine("GPS周:{0:D},周内秒:{1:D}", gpsWeekWISFromBDS[0], gpsWeekWISFromBDS[1]); //日历时转GPS周-周内秒 Console.Write("1.2 GPS年月日对应周-周内秒:"); DateTime gpsNYR = new DateTime(2018, 10, 19, 0, 0, 0); int[] gpsWeekWISFromGpsNYR = gpsNYR2WeekWIS(gpsNYR); Console.WriteLine("GPS周:{0:D},周内秒:{1:D}", gpsWeekWISFromGpsNYR[0], gpsWeekWISFromGpsNYR[1]); //UTC时间系统转GPS周-周内秒 Console.Write("2.2 UTC对应GPS周-周内秒:"); DateTime gpsUTC = new DateTime(2018, 10, 18, 23, 59, 42); int[] gpsWeekWISFromGpsUTC = gpsUTC2WeekWIS(gpsUTC); Console.WriteLine("GPS周:{0:D},周内秒:{1:D}", gpsWeekWISFromGpsUTC[0], gpsWeekWISFromGpsUTC[1]); //日历时转BDS周-周内秒 Console.Write("3.2 BDS年月日对应周-周内秒:"); DateTime bdsNYR = new DateTime(2018, 10, 18, 23, 59, 46); int[] bdsWeekWISFrombdsNYR = bdsNYR2WeekWIS(bdsNYR); Console.WriteLine("bds周:{0:D},周内秒:{1:D}", bdsWeekWISFrombdsNYR[0], bdsWeekWISFrombdsNYR[1]); Console.Write("4.2 UTC对应bds周-周内秒:"); DateTime bdsUTC = new DateTime(2018, 10, 18, 23, 59, 42); int[] bdsWeekWISFrombdsUTC = bdsUTC2WeekWIS(bdsUTC); Console.WriteLine("bds周:{0:D},周内秒:{1:D}", bdsWeekWISFrombdsUTC[0], bdsWeekWISFrombdsUTC[1]); }算例演示:
需求说明:以WGS-84软件为例,实现大地坐标系(LBH)向空间直角坐标系(XYZ)的转换及其逆转换原理说明:程序源码:using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace XYZ2BLH class Program //输出为度格式的字符串 (度分秒.秒的小数部分) //例如:35度23分32.9秒 表述为352332.9 static string[] XYZ2LBH(double x,double y,double z) double[] blh = {0.0, 0.0, 0.0}; double a = 6378137; double b = 6356752.3142; double e2 = 0.0066943799013; double ePie2 = 0.00673949674227; double xita = Math.Atan(z * a / (Math.Sqrt(x * x + y * y) * b)); double xitaSin3 = Math.Sin(xita) * Math.Sin(xita) * Math.Sin(xita); double xitaCos3 = Math.Cos(xita) * Math.Cos(xita) * Math.Cos(xita); double B = Math.Atan((z + ePie2 * b * xitaSin3) / ((Math.Sqrt(x * x + y * y) - e2 * a * xitaCos3))); double L = Math.Atan(y / x); double N = a / Math.Sqrt(1 - e2 * Math.Sin(B) * Math.Sin(B)); ; double H = Math.Sqrt(x * x + y * y) / Math.Cos(B) - N; //转化为角度 B = 180 * B / Math.PI; if (B < 0.0) { B = B + 90; } L = 180 * L / Math.PI; if (L < 0.0) { L = L + 180; } return new string[] {rad2dms(B), rad2dms(L), H.ToString()}; //获取一个小数的整数部分和小数部分 static double[] modf(double t) t += 1.0e-14;//避免角度转换过程产生无效近似 double t_integer = Math.Floor(t); return new double[] { t_integer, t - t_integer }; //角度转弧度 static double turn1(double t) double[] t1 = modf(t); double[] t2 = modf(t1[1] * 100); double x1 = t1[0]; double x2 = t2[0]; double x3 = t2[1] * 100; //Console.Write("{0:N} \t {1:N}\t {2:N}\r\n", x1, x2, x3); return (x1 + x2 / 60 + x3 / 3600) / 180 * Math.PI; //弧度转角度 static string rad2dms(double rad) int du, fen; double miao; du = (int)rad; fen = (int)((rad - (double)du) * 60); miao = ((rad - (double)du) * 60 - (double)fen) * 60; return du.ToString() + fen.ToString().PadLeft(2,'0') + miao.ToString(); //经度、纬度和大地高转向空间直角坐标 static double[] LBH2XYZ(double[] lbh) double B = turn1(lbh[1]); double L = turn1(lbh[0]); double H = lbh[2]; double A = 1 / 298.257223563; double a = 6378137.0000000000; double E = 2 * A - A * A; double W = Math.Sqrt(1 - E * Math.Sin(B) * Math.Sin(B)); double N = a / W; double[] xyz = { 0.0, 0.0, 0.0 }; xyz[0] = (N + H) * Math.Cos(B) * Math.Cos(L); xyz[1] = (N + H) * Math.Cos(B) * Math.Sin(L); xyz[2] = (N * (1 - E) + H) * Math.Sin(B); return xyz; static void Main(string[] args) double[] lbh = { 108.5743, 32.2352, 100.59 }; double[] xyz = LBH2XYZ(lbh); Console.WriteLine("{0:N6} {1:N6} {2:N6}", xyz[0], xyz[1], xyz[2]); string[] lbhTmp = XYZ2LBH(xyz[0], xyz[1], xyz[2]); Console.WriteLine("{0:N6} {1:N6} {2:N6}", double.Parse(lbhTmp[0]), double.Parse(lbhTmp[1]), double.Parse(lbhTmp[2])); }测试结果:
3.2 代码示例package javaCplex; import ilog.concert.*; import ilog.cplex.*; public class jCplex { public static void main(String[] args) { // TODO Auto-generated method stub double[] lb = { 0.0, 0.0, 0.0}; double[] ub = { 40.0, Double.MAX_VALUE, Double.MAX_VALUE}; try { IloCplex cplex = new IloCplex(); IloNumVar[] x = cplex.numVarArray(3, lb, ub); double[] objvals = { 1.0, 2.0, 3.0 }; cplex.addMaximize(cplex.scalProd(x, objvals)); cplex.addLe(cplex.sum(cplex.prod(-1.0, x[0]), cplex.prod(1.0, x[1]), cplex.prod(1.0, x[2])), 20); cplex.addLe(cplex.sum(cplex.prod(1.0, x[0]), cplex.prod(-3.0, x[1]), cplex.prod(1.0, x[2])), 30); if (cplex.solve()) { cplex.output().println("Solution status = " + cplex.getStatus()); cplex.output().println("Solution value = " + cplex.getObjValue()); double[] val = cplex.getValues(x); int ncols = cplex.getNcols(); for (int j = 0; j < ncols; ++j) cplex.output().println("Column: " + j + " Value = " + val[j]); cplex.end(); } catch (IloException e) { System.err.println("Concert exception '" + e + "' caught"); }3.3 注意事项如果java64位Cplex是32位时,会报错误java.lang.UnsatisfiedLinkError: ....\cplex\bin\x86_win32\cplex1261.dll: Can't load IA 32-bit .dll on a AMD 64-bit platform java.library.path must point to the directory containing the CPLEX shared library try invoking java with java -Djava.library.path=... Exception in thread "main" java.lang.UnsatisfiedLinkError: ilog.cplex.Cplex.CPXopenCPLEX([I)J at ilog.cplex.Cplex.CPXopenCPLEX(Native Method) at ilog.cplex.CplexI.init(CplexI.java:6608) at ilog.cplex.CplexI.<init>(CplexI.java:629) at ilog.cplex.IloCplex.<init>(IloCplex.java:10194) at ilog.cplex.IloCplex.<init>(IloCplex.java:10209) at javaCplex.jCplex.main(jCplex.java:12) 4 Matlab调用Cplex的配置与示例4.1 配置4.1.1 设置路径注意保持Matlab与Cpex的位数一致性,会报类似【未定义函数或变量 'cplexlink1261']的错误32位的配置:64位同上使用help函数验证是否配置成功4.1.2 下载yalmip及配置yalmip的最新下载网址下载解压将其复制到Matlab安装目录的toolbox路径下设置路径配置完后,关闭并重启Matlab,测试:1. >> which issymmetric 2. >> which ishemitian 3. >> which issymmetric4.2 算例编写% 清除工作区 clear;clc;close all; % 创建决策变量 x = sdpvar(1,3); %创建约束 C = [ -x(1) + x(2) + x(3) <= 20 x(1) - 3 * x(2) + x(3) <= 30 0 <= x(1) <= 40 ops = sdpsettings('verbose',0); % 目标函数 z = -(x(1) + 2 * x(2) + 3 * x(3)); % 注意这是求解最大值,默认是求最小值,所以要加上负号 reuslt = optimize(C,z); if reuslt.problem == 0 % problem =0 代表求解成功 value(x) -value(z) % 反转 disp('求解出错'); end4.3 算例结果演示5 python配置Cplex5.1 配置这个比较简单,直接找到安装目录下的cplex\python\2.7\x86_win32下找到Cplex文件夹,将其赋值到python27的安装目录下的Lib\site-packages下,打开python控制台,输入如下代码:import cplex help(cplex)如果可以看到帮助文档则说明配置成功,此外本人还做了python37的测试,发现32位的Cplex不能在64位的python37上匹配成功5.2 编码示例# -*- coding: utf-8 -*- import cplex from cplex.exceptions import CplexError # data common to all populateby functions my_obj = [1.0, 2.0, 3.0] my_ub = [40.0, cplex.infinity, cplex.infinity] my_lb = [0.0, 0.0, 0.0] my_ctype = "CCC" my_colnames = ["x1", "x2", "x3"] my_rhs = [20.0, 30.0] my_rownames = ["r1", "r2"] my_sense = "LL" def populatebyrow(prob): prob.objective.set_sense(prob.objective.sense.maximize) prob.variables.add(obj=my_obj, lb=my_lb, ub=my_ub, types=my_ctype, names=my_colnames) rows = [[["x1", "x2", "x3"], [-1.0, 1.0, 1.0]], [["x1", "x2", "x3"], [1.0, -3.0, 1.0]] prob.linear_constraints.add(lin_expr=rows, senses=my_sense, rhs=my_rhs, names=my_rownames) my_prob = cplex.Cplex() handle = populatebyrow(my_prob) my_prob.solve() except CplexError as exc: print(exc) print() # solution.get_status() returns an integer code print("Solution status = ", my_prob.solution.get_status(), ":") # the following line prints the corresponding string print(my_prob.solution.status[my_prob.solution.get_status()]) print("Solution value = ", my_prob.solution.get_objective_value()) numcols = my_prob.variables.get_num() numrows = my_prob.linear_constraints.get_num() slack = my_prob.solution.get_linear_slacks() x = my_prob.solution.get_values() print('x: ') print(x) 5.3 结果演示6 总结对于C++和C#,都是在VS环境下进行的开发,不存在32位和64位的兼容问题java和Matlab以及Python37建议使用64位的Cpex版本Matlab在效率上还是比较低的
1 C++调用Cplex的在VS2010中的配置及示例代码演示1.1 cplex在vs2010中的配置正常建立一个控制台项目在【项目--属性】下,作如下设置:【C/C++】--【常规】--【附加库目录】,添加如下两个库目录:你的安装位置\concert\include你的安装位置\cplex\include【C/C++】--【预处理器】--【预处理器定义】,粘贴如下内容:WIN32NDEBUG_CONSOLE_LIBIL_STD【连接器】--【附加库目录】,选中如下两个路径:你的安装路径\concert\lib\x86_windows_vs2010\stat_mda你的安装路径\cplex\lib\x86_windows_vs2010\stat_mda【连接器】--【附加依赖项】,复制以下内容:concert.libcplex1261.libilocplex.lib1.2 测试示例1.2.1 测试用例1.2.2 测试代码//**************************************************************// // the test version of Cplex with C++ // time 2019-09-28 // author A & R //*************************************************************// #include <ilcplex/ilocplex.h> #include<cstdlib> #include<iostream> ILOSTLBEGIN //#define ILOSTLBEGIN using namespace std; int main(int argc, char **argv) IloEnv env;//construct an Cplex environment env, which belongs to a handle class IloEnv; IloModel model(env);// define the varies "env" IloNumVarArray vars(env);// define the varies vars(env), the x1, x2, x3 can be expressed with vars(0), vars(1), vars(2) // define the bounds of varies vars.add(IloNumVar(env, 0.0, 40.0)); vars.add(IloNumVar(env)); vars.add(IloNumVar(env)); //objective to optimize: model.add(IloMaximize(env, vars[0]+2*vars[1]+3*vars[2]));//opjective: Maximize the x1+2*x2+3*x3; //subject to: model.add(-vars[0]+vars[1]+vars[2]<=20); model.add(vars[0]-3*vars[1]+vars[2]<=30); //expection processing, refer to "C++ try&catch" IloCplex cplex(model); if(!cplex.solve()){ env.error()<<"Failed to optimize LP."<<endl; throw(-1); IloNumArray vals(env); env.out() << "solution status = "<< cplex.getStatus() << endl; env.out() << "Solution value=" << cplex.getObjective() << endl; cplex.getValues(vals, vars); env.out() << "Values = " << vals << endl; // cathch functions, refer to "C++ try&catch" catch(IloException&e){ cerr << "Concert exception caught:" << e << endl; catch(...){ cerr << "Unknown exception caught" << endl; env.end(); //return 0; system("PAUSE"); return EXIT_SUCCESS; }1.2.3 运行结果2 C#调用Cplex在VS2010下的配置2.1 C#配置Cplex这个配置比较简单,直接添加两个引用即可你的Cplex安装目录\cplex\bin\x86_win32\ILOG.CPLEX.dll"你的Cplex安装目录\cplex\bin\x86_win32\ILOG.Concert.dll"2.2 算例测试及代码2.2.1 算例代码using System; using System.Collections.Generic; using System.Linq; using System.Text; using ILOG.Concert; using ILOG.CPLEX; namespace csCplex class Program static void Main(string[] args) //1 先创建一个Cplex空模型 Cplex cplexModel = new Cplex(); //2 生成决策变量并赋值 INumVar[][] deVar = new INumVar[1][]; double[] lowerBound = { 0.0, 0.0, 0.0}; double[] upBound = { 40.0, double.MaxValue,double.MaxValue }; string[] deVarName = { "x1", "x2", "x3"}; //包含两个变量,下界,上界,变量名称 INumVar[] X = cplexModel.NumVarArray(3, lowerBound, upBound, deVarName); deVar[0] = X; //定义模型目标函数的系数 double[] objCoff = { 1.0, 2.0, 3.0 }; cplexModel.AddMaximize(cplexModel.ScalProd(X, objCoff)); //3 添加约束条件 IRange[][] rng = new IRange[1][]; rng[0] = new IRange[2]; //添加小于等于约束 rng[0][0] = cplexModel.AddLe( cplexModel.Sum(cplexModel.Prod(-1.0, X[0]), cplexModel.Prod(1.0, X[1]),cplexModel.Prod(1.0, X[2])), 20, "约束1"); rng[0][1] = cplexModel.AddLe( cplexModel.Sum(cplexModel.Prod(1.0, X[0]), cplexModel.Prod(-3.0, X[1]), cplexModel.Prod(1.0, X[2])), 30, "约束2"); //4 导出模型 cplexModel.ExportModel("C#调用Cplex演示示例模型.lp"); //5 求解模型 if (cplexModel.Solve()) int nvars = cplexModel.GetValues(deVar[0]).Length; for (int i = 0; i < nvars; i++) cplexModel.Output().WriteLine("x" + i + "=" + cplexModel.GetValues(deVar[0])[i]); cplexModel.End(); catch(ILOG.Concert.Exception e) System.Console.WriteLine("concert exception:" + e); finally System.Console.WriteLine("模型求解完毕"); }2.2.3 运行结果3 Java语言调用Cplex的配置与示例演示注意java的位数要与Cplex的位数一致,64位与32位不兼容3.1 配置添加环境变量您的Cplex安装路径\cplex\bin\x86_win32\cplex1261.dll您的Cplex安装路径\cplex\lib\cplex.jar设置构建路径,【你的java项目,右键】--【Bulid Path】--【Condigure Build Path..】--【Existing Project into Workspce】--【Next】【Add External jars】,选择你安装位置下的\cplex\lib\cplex.jar配置库
1 问题描述从栅格属性中提取分辨率信息、焦点坐标信息、参考坐标系统信息、中央子午线等2 问题解析3 要点分析3.1 ArcGIS的接口与方法主要用到的接口:IRasterPropsIRasterBandCollectionIRasterDatasetIRasterPyramid3IRasterBand栅格属性列表:列数和行数(Columns and Rows):通过IRasterProps的Width和Height属性获取波段数量(Number of Bands):通过IRasterBandCollection接口获取(可以由IRaster对象跳转接口到此接口)像元大小(CellSize(X,Y)):通过IRasterProps的MeanCellSize格式(Format):通过IRasterDataset的Format属性获取源类型(Source Type):可以通过GP工具SetRasterProperties来设置。像素类型(Pixel Type):通过IRasterProps接口的PixelType 属性获取像素位深(Pixel Depth):根据像素类型来判断像素位深无数据值(NoData Value):通过IRasterProps 的NoDataValue属性获取颜色表/色带(Colormap):通过IRaster2接口的Colormap属性获取色带金字塔(Pyramids):通过IRasterPyramid3接口来创建、获取、删除金字塔(PS:用IRasterDataset接口跳转到IRasterPyramid3接口)压缩(Compression):通过IRasterDataset的CompressionType属性获取压缩类型范围(Extent):将IRasterDataset接口对象转换成IGeoDataset对象来范围信息空间参考(Spatial Reference):1)将IRasterDataset接口对象转换成IGeoDataset对象来获取空间参考信息 2)通过IRasterProps 的属性SpatialReference获取 3)其它方法统计(Statistics):通过IRasterBand接口的Statistics属性获取波段的统计信息波段集合:通过IRasterBandCollection 接口来添加、删除、获取波段。3.3 DataGridView的学习总结3.3.1 属性设置DataGridView的最后一行不显示:dataGridView1.AllowUserToAddRows = false;自动填充列宽:AutoSizeColumns: Fill不进行列排序3.3.2 添加新行方法一:使用add方法 //采用Add()方法添加新行 int index1 = dataGridView1.Rows.Add(); dataGridView1.Rows[index1].Cells[0].Value = "行数"; dataGridView1.Rows[index1].Cells[1].Value = myRasterProp.Height.ToString();方法二:添加add(row) private void addPropToDgv(string propDiscription, string propValue) //采用DataGridViewRow添加新行 DataGridViewRow row = new DataGridViewRow(); DataGridViewTextBoxCell textboxcell0 = new DataGridViewTextBoxCell(); textboxcell0.Value = propDiscription; row.Cells.Add(textboxcell0); DataGridViewTextBoxCell textboxcell1 = new DataGridViewTextBoxCell(); textboxcell1.Value = propValue; row.Cells.Add(textboxcell1); //DataGridViewComboBoxCell comboxcell = new DataGridViewComboBoxCell(); //row.Cells.Add(comboxcell); dataGridView1.Rows.Add(row); }3.3.3 绘制行号方式一//显示行号 private void dataGridView1_RowPostPaint(object sender, DataGridViewRowPostPaintEventArgs e) var grid = sender as DataGridView; var rowIdx = (e.RowIndex + 1).ToString(); var centerFormat = new StringFormat() // right alignment might actually make more sense for numbers Alignment = StringAlignment.Center, LineAlignment = StringAlignment.Center var headerBounds = new Rectangle(e.RowBounds.Left, e.RowBounds.Top, grid.RowHeadersWidth, e.RowBounds.Height); e.Graphics.DrawString(rowIdx, this.Font, SystemBrushes.ControlText, headerBounds, centerFormat); }方式二//显示行号 private void dataGridView1_RowPostPaint(object sender, DataGridViewRowPostPaintEventArgs e) SolidBrush b = new SolidBrush(this.dataGridview1.RowHeaderDefaultCellStyle.ForeColor); e.Graphics.DrawString((e.RowIndex + 1).Tostring(System.Golbalization.CultureInfo.CurrentCulture), this.dataGridview1.DefaultCellStyle.Font, b, e.RowBounds.Location.X + 10, e.RowBounds.Location.X + 4); }3.3.4 点击首行或首列选中 //点击列头选中整列 private void dataGridView1_ColumnHeaderMouseClick(object sender, DataGridViewCellMouseEventArgs e) this.dataGridView1.SelectionMode = DataGridViewSelectionMode.FullColumnSelect; dataGridView1.Columns[e.ColumnIndex].Selected = true; //点击行头选中整行 private void dataGridView1_RowHeaderMouseClick(object sender, DataGridViewCellMouseEventArgs e) this.dataGridView1.SelectionMode = DataGridViewSelectionMode.FullRowSelect; dataGridView1.Rows[e.RowIndex].Selected = true; }3.3.5 选中单一的格子 private void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e) if (e.ColumnIndex != -1) this.dataGridView1.SelectionMode = DataGridViewSelectionMode.CellSelect; dataGridView1.Rows[e.ColumnIndex].Selected = true; }4 源码实现using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; using ESRI.ArcGIS.DataSourcesRaster; using ESRI.ArcGIS.Geodatabase; using ESRI.ArcGIS.Carto; using ESRI.ArcGIS.Geometry; //https://blog.csdn.net/yh0503/article/details/52644017 //https://blog.csdn.net/mengxiangzhengfaya/article/details/52985746 namespace WindowsFormsApplication1 public partial class Form1 : Form public Form1() ESRI.ArcGIS.RuntimeManager.Bind(ESRI.ArcGIS.ProductCode.EngineOrDesktop); InitializeComponent(); private void textBox1_DragDrop(object sender, DragEventArgs e) textBox1.Text = ((System.Array)e.Data.GetData(DataFormats.FileDrop)).GetValue(0).ToString(); private void textBox1_DragEnter(object sender, DragEventArgs e) if (e.Data.GetDataPresent(DataFormats.FileDrop)) e.Effect = DragDropEffects.Link; e.Effect = DragDropEffects.None; private void addPropToDgv(string propDiscription, string propValue) //采用DataGridViewRow添加新行 DataGridViewRow row = new DataGridViewRow(); DataGridViewTextBoxCell textboxcell0 = new DataGridViewTextBoxCell(); textboxcell0.Value = propDiscription; row.Cells.Add(textboxcell0); DataGridViewTextBoxCell textboxcell1 = new DataGridViewTextBoxCell(); textboxcell1.Value = propValue; row.Cells.Add(textboxcell1); //DataGridViewComboBoxCell comboxcell = new DataGridViewComboBoxCell(); //row.Cells.Add(comboxcell); dataGridView1.Rows.Add(row); private void btn_GetRasterInfo_Click(object sender, EventArgs e) IWorkspaceFactory myWorkFact = new RasterWorkspaceFactoryClass(); string rasterData = textBox1.Text; IRasterWorkspace myRasterWorkspce = myWorkFact.OpenFromFile(System.IO.Path.GetDirectoryName(rasterData), 0) as IRasterWorkspace; IRasterDataset myRasterDataset = myRasterWorkspce.OpenRasterDataset(System.IO.Path.GetFileName(rasterData)) as IRasterDataset; IRasterLayer myRasterLayer = new RasterLayerClass(); myRasterLayer.CreateFromDataset(myRasterDataset); IRasterProps myRasterProp = myRasterLayer.Raster as IRasterProps; //采用Add()方法添加新行 int index1 = dataGridView1.Rows.Add(); dataGridView1.Rows[index1].Cells[0].Value = "行数"; dataGridView1.Rows[index1].Cells[1].Value = myRasterProp.Height.ToString(); addPropToDgv("列数", myRasterProp.Width.ToString()); addPropToDgv("像素类型", myRasterProp.PixelType.ToString()); addPropToDgv("波段数",(myRasterLayer.Raster as IRasterBandCollection).Count.ToString()); addPropToDgv("压缩类型", myRasterDataset.CompressionType.ToString()); //四个角点的最大最小坐标 addPropToDgv("最大X坐标", myRasterProp.Extent.XMax.ToString()); addPropToDgv("最小X坐标", myRasterProp.Extent.XMin.ToString()); addPropToDgv("最大Y坐标", myRasterProp.Extent.YMax.ToString()); addPropToDgv("最小Y坐标", myRasterProp.Extent.YMin.ToString()); //四个角点的坐标 addPropToDgv("左下X坐标", myRasterProp.Extent.LowerLeft.X.ToString()); addPropToDgv("左下Y坐标", myRasterProp.Extent.LowerLeft.Y.ToString()); addPropToDgv("左上X坐标", myRasterProp.Extent.UpperLeft.X.ToString()); addPropToDgv("左上Y坐标", myRasterProp.Extent.UpperLeft.Y.ToString()); addPropToDgv("右下X坐标", myRasterProp.Extent.LowerRight.X.ToString()); addPropToDgv("右下Y坐标", myRasterProp.Extent.LowerRight.Y.ToString()); addPropToDgv("右上X坐标", myRasterProp.Extent.UpperRight.X.ToString()); addPropToDgv("右上Y坐标", myRasterProp.Extent.UpperRight.Y.ToString()); //X和Y坐标的格网分辨率 addPropToDgv("X尺寸", myRasterProp.MeanCellSize().X.ToString()); addPropToDgv("Y尺寸", myRasterProp.MeanCellSize().Y.ToString()); //参考坐标信息 ISpatialReference pSpatialReference = myRasterProp.SpatialReference; addPropToDgv("空间参考", pSpatialReference.Name.ToString()); //投影坐标系 IProjectedCoordinateSystem pcs = pSpatialReference as IProjectedCoordinateSystem; addPropToDgv("地理坐标系", pcs.GeographicCoordinateSystem.Name); addPropToDgv("基准面", pcs.GeographicCoordinateSystem.Datum.Name); addPropToDgv("参考椭球", pcs.GeographicCoordinateSystem.Datum.Spheroid.Name); addPropToDgv("投影坐标系", pcs.Projection.Name); addPropToDgv("中央子午线", pcs.get_CentralMeridian(true).ToString()); addPropToDgv("线性单位", pcs.CoordinateUnit.Name.ToString()); addPropToDgv("尺度因子", pcs.ScaleFactor.ToString()); addPropToDgv("假东距", pcs.FalseEasting.ToString()); addPropToDgv("假北距", pcs.FalseNorthing.ToString()); //显示行号 private void dataGridView1_RowPostPaint(object sender, DataGridViewRowPostPaintEventArgs e) var grid = sender as DataGridView; var rowIdx = (e.RowIndex + 1).ToString(); var centerFormat = new StringFormat() // right alignment might actually make more sense for numbers Alignment = StringAlignment.Center, LineAlignment = StringAlignment.Center var headerBounds = new Rectangle(e.RowBounds.Left, e.RowBounds.Top, grid.RowHeadersWidth, e.RowBounds.Height); e.Graphics.DrawString(rowIdx, this.Font, SystemBrushes.ControlText, headerBounds, centerFormat); //点击列头选中整列 private void dataGridView1_ColumnHeaderMouseClick(object sender, DataGridViewCellMouseEventArgs e) this.dataGridView1.SelectionMode = DataGridViewSelectionMode.FullColumnSelect; dataGridView1.Columns[e.ColumnIndex].Selected = true; //点击行头选中整行 private void dataGridView1_RowHeaderMouseClick(object sender, DataGridViewCellMouseEventArgs e) this.dataGridView1.SelectionMode = DataGridViewSelectionMode.FullRowSelect; dataGridView1.Rows[e.RowIndex].Selected = true; //选中格子 private void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e) if (e.ColumnIndex != -1) this.dataGridView1.SelectionMode = DataGridViewSelectionMode.CellSelect; dataGridView1.Rows[e.ColumnIndex].Selected = true; }5 结果展示6 参考优质博文:ArcEngine 栅格数据 总结C# ArcEngine获取坐标系、投影类型、计量单位、带号、几度分带、精度
基于C#的ArcEngine二次开发42:空间分析接口及分析(ITopologicalOperator / IRelationalOperator / IProximityOperator)(三)