关于c++:算法笔记零碎知识点

10^n为n+1位数: 1000为10^3 读入double型变量的语法: double a;scanf("%lf",&a);输入double型变量的语法: printf("%f",a);或者 printf("%.2f",a);初始化字符数组的办法: char str[100]= "123a";//正文中为谬误写法//char str[100];//str= "123a";//正文中为谬误写法//char str[100];//str[100]= "123a";

December 5, 2021 · 1 min · jiezi

关于c++:算法笔记错误链表篇

for(int i=first;i!=-1; i=link[i].next){ link[i].flag = true;}上述代码中,i只有在for循环内无效,出了for循环,就有效了

December 5, 2021 · 1 min · jiezi

关于c++:算法笔记广度优先搜索

深度优先搜寻的实质是递归,广度优先搜寻不须要递归 深度优先搜寻不要用栈实现,广度优先搜寻要用队列实现 scanf()按s格局符不能输出带空格的字符串 gets()能输出带空格的字符串 scanf()以回车符作为字符串的终止符,同时不读走回车符,回车符依然留在输出缓冲区中 gets()以回车符作为字符串的终止符,同时将回车符从输出缓冲区读走,但不作为字符串的一部分 《C语言程序设计(苏小红)》P258 当须要读入字符时,能够套用以下代码: scanf("%d%d",&n,&m);for(int i=0; i<n; i++){ getchar();//过滤掉每行前面的换行符 for(int j=0; j<m; j++){ maze[i][j] = getchar(); } maze[i][m+1] = '\0;'}getchar()的作用是从零碎隐含指定的输出设施(即终端键盘)输出一个字符,按回车键示意输出完结,也承受空格 上面举一个迷宫的例子,输出一个迷宫,输出终点起点,通过广度优先搜寻失去最短门路: #include <iostream>#include <stdio.h>#include <stdlib.h>#include <queue>using namespace std;const int maxn = 1000;char maze[maxn][maxn];bool inq[maxn][maxn];int n;int m;struct node{ int x; int y; int step;};node S;node T;node mid;int ans=0;int xChange[4] = {0,0,-1,1};int yChange[4] = {1,-1,0,0};queue<node> link;bool judge(int x,int y){ if(x<0||x>=m||y<0||y>=n) { return false; } if(maze[x][y]=='*' || inq[x][y]==true) { return false; } return true;}int BFS(){ link.push(S); inq[S.x][S.y] = true; while(!link.empty()) { node temp = link.front(); link.pop(); int nowStep = temp.step; if(temp.x == T.x && temp.y == T.y){ ans = nowStep; return nowStep; } for(int i=0; i<4; i++) { int tempX = temp.x+xChange[i]; int tempY = temp.y+yChange[i]; if(judge(tempX,tempY)){ node fresh; fresh.x = tempX; fresh.y = tempY; fresh.step = nowStep+1; link.push(fresh); inq[tempX][tempY] = true; } } }//队列齐全可能为空 return -1;}int main(){ scanf("%d%d",&n,&m); for(int i=0; i<n; i++) { getchar(); for(int j=0; j<m; j++) { maze[i][j] = getchar(); } maze[i][m+1] = '\0'; } scanf("%d%d%d%d",&S.x,&S.y,&T.x,&T.y); printf("%d", BFS()); return 0;} ...

December 5, 2021 · 1 min · jiezi

关于c++:算法笔记第9章第10章各种定义总结

二叉树(Binary Tree): 要么二叉树没有根节点,是一棵空树。要么二叉树由根节点、左子树、右子树组成,且左子树和右子树都是二叉树。满二叉树: 每一层的节点数都达到了当层能达到的最大结点数。 齐全二叉树: 定义:除了最上面一层外,其余层的结点个数都达到了当层能达到的最大结点数,且最上面一层只从左至右间断存在若干结点,而这些间断结点左边的结点全副不存在。 小技巧: 1. 判断某个结点是否为叶结点的标记为:该结点(记下标为root)的左子结点的编号root*2大于结点总个数n。 2. 判断某个结点是否为空结点的标记为:该结点下标root大于结点总个数n。 二叉查找树(Binary Search Tree): 要么二叉查找树是一棵空树。要么二叉查找树由根节点、左子树、右子树组成,其中左子树和右子树都是二叉查找树,且左子树上所有结点的数据域均小于或等于根结点的数据域,右子树上所有结点的数据域均大于根节点的数据域。均衡二叉树(AVL树): AVL树依然是一棵二叉查找树(Binary Search Tree),对于AVL树的任意结点来说,其左子树和右子树的高度之差的绝对值不超过1。 其中左子树和右子树的高度之差称为该结点的均衡因子。 并查集: 并查集是一种保护汇合的数据结构,并查集反对上面两个操作: 合并:合并两个汇合。查找:判断两个元素是否在一个汇合。堆: 堆是一棵齐全二叉树,用priority_queue实现即可,priority_queue默认是大顶堆,如果想用小顶堆,就采纳上面的代码: priority_queue<int,vector<int>,greater<int>> q 数字越小优先级越大 。 度(对树而言): 把结点的子树棵数称为结点的度(degree),而树中结点的最大的度称为树的度(也称为树的宽度)。 度(对图而言): 顶点的度是指和该顶点相连的边的条数,特地是对于有向图来说,顶点的出边条数称为该顶点的出度,顶点的入边条数称为该顶点的入度。 最小生成树: 最小生成树(Minimum Spanning Tree,MST)是在一个给定的无向图 G(V,E)中求一棵树T,使得这棵树领有图G中的所有顶点,且所有边都是来自图G中的边,并且满足整棵树的边权之和最小。 最小生成树有3个性质须要把握: 最小生成树是树,因而其边数等于顶点数减1,且树内肯定不会有环。对给定的图G(V,E),其最小生成树能够不惟一,但其边权之和肯定是惟一的。因为最小生成树是在无向图上生成的,因而其根节点能够是这棵树上的任意一个结点。如果题目中波及最小生成树自身的输入,为了让最小生成树惟一,个别都会间接给出根节点,读者只须要以给出的结点作为根节点来求解最小生成树即可。参考书目:《算法笔记》

December 5, 2021 · 1 min · jiezi

关于c:veth原理两个容器通过veth通信时数据包的收发路径

基于linux内核5.4.54veth是一个虚构网络设备,是通过linux内核网络设备驱动实现的 /* veth设施在内核上注册的调用办法 */static const struct net_device_ops veth_netdev_ops = { .ndo_init = veth_dev_init, /* 初始化设施 */ .ndo_open = veth_open, /* 关上设施 */ .ndo_stop = veth_close, /* 敞开设施 */ .ndo_start_xmit = veth_xmit, /* 传输数据包(重要) */ .ndo_get_stats64 = veth_get_stats64, /* 拷贝硬件统计计数到用户空间 */ .ndo_set_rx_mode = veth_set_multicast_list, /* 外面是空函数,骗人的 */ .ndo_set_mac_address = eth_mac_addr, /* 批改MAC地址 */#ifdef CONFIG_NET_POLL_CONTROLLER .ndo_poll_controller = veth_poll_controller, /* 外面是空函数,骗人的 */#endif .ndo_get_iflink = veth_get_iflink, /* 获取设施的iflink值(应该是编号) */... .ndo_bpf = veth_xdp, /* 设置或查问设施上与XDP相干的状态,以及治理BPF offload。 */ .ndo_xdp_xmit = veth_xdp_xmit, /* 传输XDP数据包 */};通过veth将两个容器连接起来 ...

December 3, 2021 · 1 min · jiezi

关于c#:00043c-登录对话框登录成功后关闭并显示主窗体

/// <summary> /// 应用程序的主入口点。 /// </summary> [STAThread] static void Main() { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false);//这是登录窗体,ShowDialog的形式。dialog返回OK,则显示:ComListForm主窗体。 Login form1 = new Login(); form1.ShowDialog(); if (form1.DialogResult == DialogResult.OK) { Application.Run(new ComListForm()); } else { return; } //Application.Run(new ComListForm()); }在登录按钮click事件中:登录胜利,执行: this.DialogResult = DialogResult.OK; this.Close();

December 3, 2021 · 1 min · jiezi

关于c++:PDFium-渲染

PDFium 是 Chromium 的 PDF 渲染引擎,许可协定为 BSD 3-Clause。不同于 Mozilla 基于 HTML5 的 PDF.js,PDFium 是基于 Foxit Software (福昕软件)的渲染代码,Google 与其单干开源出的。 此外,Qt PDF 模块也选用了 PDFium ,可见 QtWebEngine / QtPdf。 本文将介绍如何用 PDFium 实现一个简略的 PDF 阅读器,代码见:https://github.com/ikuokuo/pd... 。 编译 PDFium应用预编译库:https://github.com/bblanchon/... 不然,参考 PDFium / README 本人编译,实际步骤如下: # get depot_tools, contains: gclient, ninja, gn, ...git clone --depth 1 https://chromium.googlesource.com/chromium/tools/depot_tools.gitexport PATH="$PATH:$HOME/Codes/Star/depot_tools"# get pdfiumcd pdfium-reader/mkdir -p third_party/chromiumcd third_party/chromiumgclient config --unmanaged https://pdfium.googlesource.com/pdfium.gitgclient synccd pdfium# get deps# on linux, install additional build dependencies./build/install-build-deps.sh# gn config# args see the following `out/Release/args.gn`gn args out/Release# ninja build# pdfiumninja -C out/Release pdfium# pdfium_testninja -C out/Release pdfium_test# run sample: pdf > ppm./out/Release/pdfium_test --ppm path/to/myfile.pdf期间 out/Release/args.gn 内容如下: ...

December 3, 2021 · 3 min · jiezi

关于c:单机容器网络

基于linux内核5.4.54昨天分享了veth的原理:veth原理----两个容器通过veth通信时数据包的收发门路个别状况容器间接不会通过veth间接通信,会通过docker0网桥通信明天剖析容器通过veth和docker0网桥的通信门路 单机容器网络结构在宿主机上通过docker创立两个容器时会主动生成如图所示的网络结构 在宿主机上会生成一个docker0网桥容器1和docker0网桥之间通过veth相连,容器2一样简略看一下Namespace网络设备的Namespace:网络设备注册时,会通过net_device->nd_net(网络设备构造体字段)设置Net Namespace。 剖析结构图设施的Namespace:veth0属于Namespace1;veth1属于Namespace2;eth0,docker0,docker0上的两个veth设施属于Host Namespace数据包的Namespace:数据包的Namespace由skb_buff->dev->nd_net(数据包目标设施的Namespace)决定 过程的Namespace:通过clone()创立过程时会通过task_struct->nsproxy(过程构造体字段)为过程设置Namespace,nsproxy->net_ns决定过程的Net Namespace /* nsproxy构造体 其中蕴含了各种命名空间隔离和Cgroup,当前有工夫会多理解 */struct nsproxy { atomic_t count; struct uts_namespace *uts_ns; struct ipc_namespace *ipc_ns; struct mnt_namespace *mnt_ns; struct pid_namespace *pid_ns_for_children; struct net *net_ns; struct cgroup_namespace *cgroup_ns;};Socket套接字的Namespace过程创立Socket时,会设置sock->sk_net为current->nsproxy->net_ns,行将以后过程的Net Namespace传递给sock套接字。 剖析两种状况1. 容器1通过网桥向容器2发送数据包收发门路:过程(容器1)|--通过socket零碎调用进入内核,通过的是Namespace1的网络协议栈kernel层: 创立skb构造体,从用户空间拷贝数据到内核空间TCP/UDP封包IP封包,跑Namespace1的路由和netfilter|--出协定栈进入网络设备调用网络设备驱动的传输数据包函数|veth_xmit: veth驱动注册的传输函数 | veth_forward_skb | __dev_forward_skb: 革除 skb 中可能影响命名空间隔离的所有信息 | 并且会更新数据包要到的网络设备(skb->dev),由veth0改为docker-veth0 | 数据包要跑的协定栈(network namespace)由skb->dev的nd_net字段决定 | XDP钩子点 | netif_rx | netif_rx_internal: cpu软中断负载平衡 | enqueue_to_backlog: 将skb包退出指定cpu的input_pkt_queue队尾 queue为空时激活网络软中断, queue不为空不须要激活软中断,cpu没清空队列之前 会主动触发软中断 每个cpu都有本人的input_pkt_queue(接管队列,默认大小1000,可批改),和process_queue(解决队列),软中断处理函数解决实现process_queue中的所有skb包之后,会将将input_pkt_queue拼接到process_queue input_pkt_queue和process_queue是cpu为非NAPI设施筹备的队列,NAPI设施有本人的队列 始终到这里,数据包门路和veth文档中的两个veth通信的发送阶段是完全一致的,docker0网桥解决数据包次要在__netif_receive_skb_core中cpu解决网络数据包过程:do_softirq()|net_rx_action: 网络软中断处理函数 | napi_poll | n->poll: 调用目标网络设备驱动的poll函数 | veth设施没有定义poll,调用默认poll函数-process_backlog | process_backlog: cpu循环从process_queue中取出skb解决,最多解决300个skb, | 解决队列清空后,拼接input_pkt_queue到process_queue队尾 | __netif_receive_skb | ... | __netif_receive_skb_core数据包解决代码剖析:/** __netif_receive_skb_core代码剖析* 代码做了很多删减,剩下了网桥的解决和数据包传递给下层解决的局部* 其余很多局部例如vlan,xdp,tcpdump等代码删去了*/static int __netif_receive_skb_core(struct sk_buff **pskb, bool pfmemalloc, struct packet_type **ppt_prev){ struct packet_type *ptype, *pt_prev; rx_handler_func_t *rx_handler; struct sk_buff *skb = *pskb; struct net_device *orig_dev; bool deliver_exact = false; int ret = NET_RX_DROP; __be16 type; /* 记录skb包目标设施 */ orig_dev = skb->dev; /* 设置skb包的协定头指针 */ skb_reset_network_header(skb); if (!skb_transport_header_was_set(skb)) skb_reset_transport_header(skb); skb_reset_mac_len(skb); pt_prev = NULL;another_round:... /** * skb包的目标设施是docker-veth0,veth作为了bridge的一个接口 * docker-veth0在注册时会设置rx_handler为网桥的收包函数br_handle_frame * 黄色处代码为调用bridge的br_handle_frame */ rx_handler = rcu_dereference(skb->dev->rx_handler); if (rx_handler) { ... switch (rx_handler(&skb)) { case RX_HANDLER_CONSUMED: /* 已解决,无需进一步解决 */ ret = NET_RX_SUCCESS; goto out; case RX_HANDLER_ANOTHER: /* 再解决一次 */ goto another_round; case RX_HANDLER_EXACT: /* 准确传递到ptype->dev == skb->dev */ deliver_exact = true; case RX_HANDLER_PASS: break; default: BUG(); } }... /* 获取三层协定 */ type = skb->protocol; /* * 调用指定协定的协定处理函数(例如ip_rcv函数) 把数据包传递给下层协定层解决 * ip_rcv函数是网络协议栈的入口函数 * 数据包达到这里会通过netfilter,路由,最初被转发或者发给下层协定栈 */ deliver_ptype_list_skb(skb, &pt_prev, orig_dev, type, &orig_dev->ptype_specific);... if (pt_prev) { if (unlikely(skb_orphan_frags_rx(skb, GFP_ATOMIC))) goto drop; *ppt_prev = pt_prev; } else {drop: if (!deliver_exact) atomic_long_inc(&skb->dev->rx_dropped); else atomic_long_inc(&skb->dev->rx_nohandler); kfree_skb(skb); ret = NET_RX_DROP; }out: *pskb = skb; return ret;}网桥解决代码剖析: ...

December 3, 2021 · 2 min · jiezi

关于c#:详解-Net6-Minimal-API-的使用方式

随着 .Net6 的公布,微软也改良了对之前 ASP.NET Core 构建形式,应用了新的 Minimal API 模式。以前默认的形式是须要在 Startup 中注册 IOC 和中间件相干,然而在 Minimal API 模式下你只须要简略的写几行代码就能够构建一个 ASP.NET Core的Web 利用,堪称十分的简略,加之配合 c# 的 global using 和 Program 的顶级申明形式,使得 Minimal API 变得更为简洁,不得不说 .NET 团队在 .NET 上近几年下了不少功夫,接下来咱们就来大抵介绍下这种极简的应用模式。 1. 应用形式应用 Visual Studio 2022 新建的 ASP.NET Core 6 的我的项目,默认的形式就是 Minimal API 模式,整个 Web 程序的构造看起来更加简略,再i加上微软对 Lambda 的改良,使其能够对 Lambda 参数进行 Attribute 标记,有的场景甚至能够放弃去定义 Controller 类了。 2. 几行代码构建Web程序应用 Minimal API 最简略的形式就是能通过三行代码就能够构建一个 WebApi 的程序,代码如下: var app = WebApplication.Create(args);app.MapGet("/", () => "Hello World");app.Run();是的你没有看错,仅仅这样运行起来就能够,默认监听的 http://localhost:5000 和 https://localhost:5001,所以间接在浏览器输出http://localhost:5000地址就能够看到浏览器输入Hello World字样。 ...

December 3, 2021 · 4 min · jiezi

关于c:PTA-611-求自定类型元素序列的中位数-25-分

本题要求实现一个函数,求N个汇合元素A[]的中位数,即序列中第⌊(N+1)/2⌋大的元素。其中汇合元素的类型为自定义的ElementType 函数接口定义:ElementType Median( ElementType A[], int N );其中给定汇合元素寄存在数组A[]中,正整数N是数组元素个数。该函数须返回N个A[]元素的中位数,其值也必须是ElementType类型。 裁判测试程序样例:#include <stdio.h>#define MAXN 10typedef float ElementType;ElementType Median( ElementType A[], int N );int main (){ ElementType A[MAXN]; int N, i; scanf("%d", &N); for ( i=0; i<N; i++ ) scanf("%f", &A[i]); printf("%.2f\n", Median(A, N)); return 0;}/* 你的代码将被嵌在这里 */输出样例:3 12.3 34 -5输入样例:12.30做法一应用希尔排序(for) ElementType Median( ElementType A[], int N ) { ElementType temp; for (int gap = N / 2; gap > 0; gap /= 2) { for (int i = gap; i < N; i++) { for (int j = i - gap; j >= 0 && A[j] > A[j+gap] ; j-=gap) { temp = A[j]; A[j] = A[j+gap]; A[j+gap] = temp; } } } return A[N/2];}(18条音讯) 6-11 求自定类型元素序列的中位数 (25 分)_LIQIANDI的博客-CSDN博客 ...

December 2, 2021 · 1 min · jiezi

关于c:PTA-69-统计个位数字-15-分

本题要求实现一个函数,可统计任一整数中某个位数呈现的次数。例如-21252中,2呈现了3次,则该函数应该返回3 函数接口定义:int Count_Digit ( const int N, const int D );其中N和D都是用户传入的参数。N的值不超过int的范畴;D是[0, 9]区间内的个位数。函数须返回N中D呈现的次数。 裁判测试程序样例:#include <stdio.h>int Count_Digit ( const int N, const int D );int main(){ int N, D; scanf("%d %d", &N, &D); printf("%d\n", Count_Digit(N, D)); return 0;}/* 你的代码将被嵌在这里 */输出样例:-21252 2输入样例:3做法一如果是正数,须要转换为负数解决将数字拆开放入数组应用 for 遍从来判断是否有雷同的数字int Count_Digit ( const int N, const int D ) { int arr[10] = {0}; int num = N; int count = 0; int numCount = 0; if (num < 0) { num = -num; } while (num >= 10) { arr[count++] = num % 10; num /= 10; } arr[count] = num; for (int i = 0; i <= count; i++) { if (arr[i] == D) { numCount++; } } return numCount;}做法二如果是正数,须要转换为负数解决应用 do ... while 循环先判断一次,能够解决传入值为 0 的问题,当 num 为 0 时,count = 1循环体中将 num 拆开,每拆下来一个数字就比拟是否雷同,如果雷同,count 加 1int Count_Digit ( const int N, const int D ) { int num = N; int count = 0; if (num < 0) { num = -num; } do { if (D == num % 10) { count++; } num /= 10; } while (num > 0); return count;}

December 2, 2021 · 1 min · jiezi

关于c++:经验分享linux-下使用-Makefile-快速构建单工程教程

 欢送关注我的公众号 [极智视界],回复001获取Google编程标准 O_o >_<  o_O O_o ~_~ o_O 大家好,我是极智视界,本教程具体介绍了在 linux 下应用 Makefile 疾速构建单工程的办法。   本文的亮点是疾速构建工程,所以不会简明扼要 Makefile 语法。 间接开始,假如有一个测试 cpp: test.cpp,而后它可能会有一些依赖,如 opencv、cuda 等等,当初给出一个 Makefile,通过简略的配置就能把你的 test 可执行程序编译进去,进行疾速的测试验证工作。 ## MakefileCXX = g++CXX_FLAGS += -std=c++14CXX_FLAGS += -Wl,-rpath-linkINCLUDES += -I../xxxx/include # 头门路INCLUDES += -I../xxx/xxx/includeLINKS += -L../xxx/lib # 库门路LINKS += -L../xxx/xxx/lib LIBS += -lcuda -lcurt -pthread # 增加一些依赖库LIBS += -lopencv_imgproc -lopencv_imgcodecs -lopencv_core -lopencv_dnn# For debug build, use the command: `make debug=1' ifeq ($(debug), 1) # debug 模式 CXX_FLAGS += -DDEBUG -g endifSRCS = test.ccEXECUTABLE = test$(EXECUTABLE): $(SRCS) # 编译指令 $(CXX) $(SRCS) $(CXX_FLAGS) $(INCLUDES) $(LINKS) $(LIBS) -o $(EXECUTABLE)clean: # make clean rm -f $(EXECUTABLE)   目录树如下,也就是把俩文件放同一目录下就行: ...

December 1, 2021 · 1 min · jiezi

关于c++:G2O与多视角点云全局配准优化

背景本人手头有一堆通过初始配准后的三维散乱点云,通过粗配后,全副点云根本对立在了同一个坐标系下,如图1和图2所示。为了获取更好的全局后果,须要对粗配后的点云进行全局配准优化。 图1 点云底面 图2 部分细节 上述点云是基于pcl进行显示,不同的色彩代表不同的点云块,从图1能够显著看出,全局点云"交融"(其实并未交融,只是全副加载显示),成果较差,从图2能够看出,针对[耳朵]局部呈现较大错位。 因为本人之前对G2O多多少少有一点理解,然而也并没有进行过多深刻的钻研。晓得G2O能够用来解决全局优化问题,正好和本人要求解的问题十分十分类似。 因而,便毅然决然的抉择应用G2O来针对本人的问题构建解决方案。 G2O的进一步理解G2O是将非线性优化和图论相结合的产物,大多时候用于解决slam后端优化问题,其本身携带的例子大多也与slam无关。g2o中所谓的图,就是一堆节点和边依照肯定的关系链接而成。其中,节点是要优化的指标,边是各个优化指标之间的关系(也称其误差项,在这里本人更喜爱称为 【关系】)。 基于CMake + VS2017 实现G2O库的装置,装置过程没有做具体记录,根本百度可能解决。 装置完g2o后,依照习惯去翻看其本身源码中所携带的example,以便寻找灵感,在example目录中一眼便看中了【gicp_demo】。 G2O--gicp_demog2o的应用办法根本就是: 申明一个优化器;抉择求解办法;结构图--顶点和边的关系;优化解决。首次看到g2o的gicp时,自认为“该gicp办法是 全局(global)的”,然而事实并非如此,事实上,其甚至不能称为是一个残缺的icp问题 (对于上述红色字体的示意,目前仅仅是集体了解,或者有谬误,也请多多留言斧正,一起交流学习) 咱们晓得,ICP求解是一个迭代计算过程,经典ICP求解的次要步骤为: 输出两片点云AB,求解对应点对(三维模型至多3个不共线的点);基于对应点对,结构A到B的变换矩阵M;将M作用于A,失去A*,并用A*代替A;迭代终止条件(迭代次数或者最小误差度量);反复步骤1--3,直到满足步骤4,终止。输入变换矩阵M。然而细看g2o的gicp_demo,其流程并不如经典ICP求解过程一样,而更像一个ICP中步骤2的求解问题。 再来深刻看看g2o中给出的gicp_demo。 拆解gicp_demo首先还是间接先把g2o官网例子贴出来吧(尽管十分厌恶间接贴他人代码),便于阐明。 在该Demo中,g2o首先申明并设置了优化器optimizer,并制作了蕴含1000个点的汇合true_points作为源点云。 其次,为图增加了两个节点并设置节点ID。这里的节点类型为VertexSE3( class G2O_TYPES_SLAM3D_API VertexSE3 : public BaseVertex<6, Isometry3>),也是次要的优化指标。根据节点增加到图中的程序,将第一次增加的节点视为固定视角;vc->setEstimate(cam);该代码段通知咱们,真正求解的后果是存储在Eigen::Isometry3d类型的相机位姿(实质上是一个矩阵),这里cam参数的类型是Eigen::Isometry3d;这一步其实只是申明了两个空节点,节点参数只是单位Eigen::Isometry3d。 再次,为图增加了1000条边。在此过程中,首先依据节点id获取边所须要链接的两个顶点(节点),vp0和vp1,并基于true_points "制作" 了蕴含噪声的两个三维点pt0和 pt1(这一步其实曾经默认pt0和 pt1为对应点对);而后 申明了一个Edge_V_V_GICP类型的图边构造,该边是一个g2o的二元边(class G2O_TYPES_ICP_API Edge_V_V_GICP : public BaseBinaryEdge<3, EdgeGICP, VertexSE3, VertexSE3>),该二元边别离链接vp0和vp1;g2o还提供了EdgeGICP类型作为观测值,EdgeGICP类型能够寄存对应点对。在该步骤中,肯定要十分留神节点和三维坐标点的所属--对应关系。至此,根本可能将所有信息放入g2o的图中,该步骤次要关怀的在于如何将本人的三维点对放入到g2o图中。 最初,初始化图关系并进行了N次迭代优化,每个节点的优化后果存储在optimizer.vertices()返回值类型的哈希表中,该哈希表中:键--对应节点id,值--对应节点,这里为VertexSE3类型,从VertexSE3取得的Eigen::Isometry3d类型是咱们真正关怀的后果数据。该示例应该构建了如下一张超图,其中图有两个图节点,n1为固定节点,n2为变动的节点,节点之间有1000条边,每条边链接一对对应点,针对ICP问题,对应点中的固定点挂接图节点n1,变动的点挂接图节点n2: 节点--边 void icp() { double euc_noise = 0.01; // noise in position, m //申明优化器 SparseOptimizer optimizer; //是否打印详细信息 optimizer.setVerbose(false); // variable-size block solver //设定一个求解办法 g2o::OptimizationAlgorithmLevenberg* solver = new g2o::OptimizationAlgorithmLevenberg( g2o::make_unique<BlockSolverX>(g2o::make_unique<LinearSolverDense<g2o::BlockSolverX::PoseMatrixType>>())); /*g2o::OptimizationAlgorithmGaussNewton *solver = new g2o::OptimizationAlgorithmGaussNewton( g2o::make_unique<BlockSolverX>(g2o::make_unique<LinearSolverDense<g2o::BlockSolverX::PoseMatrixType>>()));*/ //设定优化器应用的优化办法 optimizer.setAlgorithm(solver); //随机点坐标 vector<Vector3d> true_points; for (size_t i = 0; i < 1000; ++i) { //这里从均匀分布中采样了一组数字 true_points.push_back(Vector3d((g2o::Sampler::uniformRand(0., 1.) - 0.5) * 3, g2o::Sampler::uniformRand(0., 1.) - 0.5, g2o::Sampler::uniformRand(0., 1.) + 10)); } // set up two poses //猜想: 设定两个相机位姿 int vertex_id = 0; for (size_t i = 0; i < 2; ++i) { // set up rotation and translation for this node //平移向量 Vector3d t(0, 0, i); //四元数旋转 Quaterniond q; q.setIdentity(); //李群(非凡欧拉群,蕴含旋转和平移,本人感觉和4*4矩阵相似) Eigen::Isometry3d cam; // camera pose cam = q; //返回平移向量的可写表达式 cam.translation() = t; // set up node //李群。这里作为节点,作为优化变量 VertexSE3 *vc = new VertexSE3(); //设置顶点的估计值 vc->setEstimate(cam); //设置该节点在 图 中的id,以便追踪 vc->setId(vertex_id); // vertex id //打印节点的初始平移和旋转矩阵 cerr << t.transpose() << " | " << q.coeffs().transpose() << endl; // set first cam pose fixed if (i == 0) vc->setFixed(true); // add to optimizer //优化器增加节点 optimizer.addVertex(vc); vertex_id++; } // set up point matches for (size_t i = 0; i < true_points.size(); ++i) { // get two poses //获取前述增加的节点。 /* optimizer.vertices()的返回值是一个哈希表(Map)类型,实质是std::unordered_map<int, Vertex*>, */ VertexSE3* vp0 = dynamic_cast<VertexSE3*>(optimizer.vertices().find(0)->second); VertexSE3* vp1 = dynamic_cast<VertexSE3*>(optimizer.vertices().find(1)->second); // calculate the relative 3D position of the point Vector3d pt0, pt1; pt0 = vp0->estimate().inverse() * true_points[i]; pt1 = vp1->estimate().inverse() * true_points[i]; // add in noise //增加高斯噪声 pt0 += Vector3d(g2o::Sampler::gaussRand(0., euc_noise), g2o::Sampler::gaussRand(0., euc_noise), g2o::Sampler::gaussRand(0., euc_noise)); pt1 += Vector3d(g2o::Sampler::gaussRand(0., euc_noise), g2o::Sampler::gaussRand(0., euc_noise), g2o::Sampler::gaussRand(0., euc_noise)); // form edge, with normals in varioius positions Vector3d nm0, nm1; nm0 << 0, i, 1; nm1 << 0, i, 1; nm0.normalize(); nm1.normalize(); //g20的二元边 Edge_V_V_GICP * e // new edge with correct cohort for caching = new Edge_V_V_GICP(); e->setVertex(0, vp0); // first viewpoint e->setVertex(1, vp1); // second viewpoint EdgeGICP meas; meas.pos0 = pt0; meas.pos1 = pt1; meas.normal0 = nm0; meas.normal1 = nm1; //定义观测值 e->setMeasurement(meas); // e->inverseMeasurement().pos() = -kp; meas = e->measurement(); // use this for point-plane //束缚信息(协方差矩阵的逆) = 点面的精度矩阵信息 e->information() = meas.prec0(0.01); optimizer.addEdge(e); } // move second cam off of its true position //变换第二个点云。 VertexSE3* vc = dynamic_cast<VertexSE3*>(optimizer.vertices().find(1)->second); Eigen::Isometry3d cam = vc->estimate(); cam.translation() = Vector3d(0, 0, 0.2); vc->setEstimate(cam); //初始化整个图构造 optimizer.initializeOptimization(); //计算所有边的误差向量 optimizer.computeActiveErrors(); //输入优化前的误差平方 cout << "Initial chi2(before opt) = " << FIXED(optimizer.chi2()) << endl; optimizer.setVerbose(true); optimizer.optimize(5); //输入优化前的误差平方 cout << "Initial chi2(after opt) = " << FIXED(optimizer.chi2()) << endl; //打印变动矩阵 cout << endl << "Second vertex should be near 0,0,1" << endl; cout << dynamic_cast<VertexSE3*>(optimizer.vertices().find(0)->second) ->estimate().translation().transpose() << endl; cout << dynamic_cast<VertexSE3*>(optimizer.vertices().find(1)->second) ->estimate().translation().transpose() << endl;}测试执行g2o自带的上述例子,最终可能打印出变换矩阵。而后将该例子独自摘出来,换入本人的数据(对应点对),也能输入变换矩阵,而后将变换矩阵作用于点云 ,后果如图3: ...

December 1, 2021 · 5 min · jiezi

关于c:时间相关函数

linux工夫函数有不少,平时用的也比拟多,然而这些函数常常忘了,故记录下来,留作当前编程查问之用。 time函数#include <time.h>time_t time(time_t * t)此函数会返回从公元1970年1月1日的UTC工夫从0时0分0秒算起到当初所通过的秒数。如果t 并非空指针的话,此函数也会将返回值存到t指针所指的内存.产生谬误返回-1. clock_gettime#include <sys/time.h>int clock_gettime(clockid_t clock_t,struct timespec * tsp);此函数用于获取指定的时钟工夫.罕用如下4种时钟:CLOCK_REALTIME 统以后工夫,从1970年1.1日算起CLOCK_MONOTONIC 零碎的启动工夫,不能被设置CLOCK_PROCESS_CPUTIME_ID 本过程运行工夫CLOCK_THREAD_CPUTIME_ID 本线程运行工夫.胜利返回0,产生谬误返回-1。 struct timespec 的构造如下: struct timespec { time_t tv_sec; // seconds long tv_nsec; // and nanoseconds};当clockid_t为CLOCK_REALTIME时,clock_gettime函数跟time函数性能相似。 gettimeofday函数#include <sys/time.h>int gettimeofday (struct timeval * tp, void * tzp);gettimeofday 返回胜利时函数将间隔1970.1.1 的工夫存储在指针tp指向的地址中,struct timeval 的构造如下。tzp 依赖于相干unix平台实现来代表时区。返回值总是返回0. struct timeval { time_t tv_sec; // seconds long tv_usec; // microseconds};localtime和gmtime#include <time.h>struct tm * gmtime(const time_t * calptr);struct tm * localtime(const time_t * calptr);gmtime和localtime 两个函数将日历工夫转换为合成工夫,并将其存在struct tm 构造中. ...

December 1, 2021 · 1 min · jiezi

关于c#:minimalapi介绍

Minimal APIs 是.Net 6 中新增的模板,借助 C# 10 的一些个性以起码的代码运行一个 Web 服务。本文脱离 VS 通过 VS Code,实现一个简略的 Minimal Api 我的项目的开发。 <!-- more --> 创立我的项目新建一个文件夹,用来治理咱们的我的项目文件,文件夹内启动命令行,通过dotnet new web创立我的项目。 Minimal├── obj├── Properties├── appsettings.Development.json├── appsettings.json├── Minimal.csproj└── Program.cs运行我的项目我的项目目录下执行dotnet run,运行我的项目。 PS C:\Users\User01\Desktop\Minimal> dotnet run正在生成...info: Microsoft.Hosting.Lifetime[14] Now listening on: https://localhost:7221info: Microsoft.Hosting.Lifetime[14] Now listening on: http://localhost:5252info: Microsoft.Hosting.Lifetime[0] Application started. Press Ctrl+C to shut down.info: Microsoft.Hosting.Lifetime[0] Hosting environment: Developmentinfo: Microsoft.Hosting.Lifetime[0] Content root path: C:\Users\User01\Desktop\Minimal\运行成果如下: Codingbuilder 实例提供了 Services 属性,能够实现本来 Startup 类 ConfigureServices 办法中注册服务的工作,Configure 办法的一些 Use 操作则通过 app 来实现。 ...

November 30, 2021 · 2 min · jiezi

关于c++:2021-年游戏开发编程语言-Top10CJavaC-霸榜前三

作为寰球增长最快的行业之一,游戏行业在近几年的倒退堪称突飞猛进,其背地的技术撑持功不可没。 近日,analyticsinsight 就出炉了 2021 年游戏我的项目开发编程语言 Top10,其中 C++、Java、C# 霸榜前三,还有不少编程语言都属于当下备受开发者欢送的编程语言。 上面就附上本次 2021 年游戏我的项目开发上榜的编程语言 Top10 列表,一起来看看吧! C++作为一种高级编程语言及游戏我的项目中最好的编程语言之一,C++ 经常被用于构建较大控制台和 Windows 游戏。它提供了许多可扩展性,可用于小型和大型游戏我的项目,且不依赖于平台,这意味着开发者能够简略地将我的项目从一个操作系统挪动到另一个操作系统。比方 The Witcher 3, Dark Souls, Elder Scrolls V: Skyrim, Player Unknown’s Battlegrounds (PUBG), Fortnite 等,都是用 C++ 创立的游戏我的项目。 JAVAJava 是 1995 年创立的通用计算机编程最佳面向对象编程语言之一。Java 被建设为具备尽可能少的依赖性,特地是与过后甚至当初的其余编程语言相比。Java 是"顶级"编程语言之一,也是2021年游戏我的项目中最风行的编程语言之一,让游戏开发人员可能为每个平台构建游戏。比方 Mission Impossible III, Minecraft, FIFA 11 以及Ferrari GT 3: World Track 等都是用 Java 开发的游戏我的项目。 C# 在宽广开发者眼中,C# 是 Windows 和 Xbox 游戏最好的编程语言之一,在像在 Unity 这样的游戏引擎中,C# 作为其编程语言( C++ 是引擎的外围)。比方 Pokemon Go 和 Super Mario Run ,都是用 C# 开发的风行游戏我的项目。 ...

November 29, 2021 · 1 min · jiezi

关于c++:C一个项目里包含多个main函数的解决

在一个我的项目的源文件中创立多个C++文件,初学时为了不便,可能会不小心书写多个main函数(每个C++文件中都有一个main函数),这样会导致编译器报错: ![上传中...]() 如果想要在一个我的项目中蕴含多个main函数能够将C++文件改为不参加生成,具体操作如下: 1.![上传中...]() 2.从生成中排除抉择“是”,确定 ![上传中...]() 3.排除后的文件会有一个红色的小小的标识 4.再次运行就不会出错了 PS 当须要抉择的文件多时,按住Ctrl键能够实现多选

November 25, 2021 · 1 min · jiezi

关于c#:解析可空类型

C# 单问号 ? 与 双问号 ??? 单问号用于对 int、double、bool 等无奈间接赋值为 null 的数据类型进行 null 的赋值,意思是这个数据类型是 Nullable 类型的。 int? i = 3;等同于: Nullable<int> i = new Nullable<int>(3);int i; //默认值0int? ii; //默认值null?? 双问号用于判断一个变量在为 null 的时候返回一个指定的值。 接下来咱们具体阐明。 C# 可空类型(Nullable)C# 提供了一个非凡的数据类型,nullable 类型(可空类型),可空类型能够示意其根底值类型失常范畴内的值,再加上一个 null 值。 例如,Nullable< Int32 >,读作"可空的 Int32",能够被赋值为 -2,147,483,648 到 2,147,483,647 之间的任意值,也能够被赋值为 null 值。相似的,Nullable< bool > 变量能够被赋值为 true 或 false 或 null。 在解决数据库和其余蕴含可能未赋值的元素的数据类型时,将 null 赋值给数值类型或布尔型的性能特地有用。例如,数据库中的布尔型字段能够存储值 true 或 false,或者,该字段也能够未定义。 申明一个 nullable 类型(可空类型)的语法如下: < data_type> ? <variable_name> = null;上面的实例演示了可空数据类型的用法: ...

November 25, 2021 · 1 min · jiezi

关于c++:多线程服务器编程4C多线程系统编程精要

线程原语的选用不间接应用Pthreads,而是应用更为易用的wrapper,封装上面的调用 线程的创立和期待完结mutex的创立、销毁、加锁、解锁条件变量的创立、销毁、期待、告诉、播送在这些wrapper之上进一步构建线程同步组件 ThreadPoolCountDownLatchBlockingQueue (有界/无界)...多线程编程须要留神的中央C++规范库容器和std::string都不是线程平安的iostream不是线程平安的线程的标识符举荐应用gettid零碎调用,它的类型是pid_t,并且是惟一的__thread是GCC内置的线程部分存储设施,效率高,但留神初始化只能应用编译器常量每个文件描述符只由一个线程操作RAII封装文件描述符不要应用多线程+fork不要应用多线程+signal

November 24, 2021 · 1 min · jiezi

关于c++:多线程服务器编程3多线程服务器的使用场合和常用模型

本章钻研对象:分布式计算的网络应用程序,基本功能能够被简略演绎为“收到数据,算一算,收回去”单线程服务器最罕用的为“non-blocking IO + IO multiplexing”,即Reactor模式,例如 lighttpdNginxlibeventJava NIOTwisted(Python)此外还有ASIO应用的Proactor模式 Reactor构造 事件循环(Event-loop)应用epoll进入阻塞监听事件,依照事件类型调用hanlder特点 须要非阻塞编程,回调函数必须是非阻塞的,只能在epoll处阻塞 这导致容易割裂业务逻辑,不容易了解与保护实用于IO密集型 计算太多也会阻塞尽管单线程模型不须要思考同步问题,但不能很好的利用多核,而如果同时应用多个过程,则势必会波及到同步问题多线程服务器阻塞+每个申请新建一个线程阻塞+线程池非阻塞 + IO multiplexing 也即作者所称的“non-blocking IO + one loop per thread”Leader/Follower等高级模式One loop per thread益处 线程数目固定不便地在线程间调配负载IO事件产生的线程是固定的,一个连贯会被注册到某个线程的loop中,并始终由这个线程负责,同一个TCP连贯不必思考并发但多线程的loop相比单线程的loop的要求变高,即须要做到线程平安,重要的问题是“如何容许一个线程往另一个线程的loop里塞货色?” 线程池实用计算工作较多的状况,重要的基础设施是BlockingQueue实现的工作队列或生产者消费者队列把计算工作或待计算数据调配给线程池中的线程过程间通信只用TCP其余IPC办法: pipe,FIFO,音讯队列,共享内存,信号TCP的益处:跨主机,伸缩性,双向,无负作用,可记录,可重现,容易定位故障 多线程服务器的实用场合解决并发连贯的两种形式Go goroutine, python gevent等的语言提供的用户态线程,由语言的runtime自行调度 便宜,能够大量创立通常配合“看起来是阻塞的IO”,这里指对于用户态的调度器阻塞,而不是对于操作系统阻塞,否则用户态多线程无奈成立内核级线程配合Reactor模式,例如libevent,muduo,Netty 数量与CPU数目相当非阻塞IO因为C++并没有第一类的工具,所以本书只思考第二类 model剖析单过程+单线程 : 没有伸缩性单过程+多线程多过程+单线程 复制多份单线程的过程,应用多个TCP port提供服务主过程+worker过程多过程+多线程 : 汇集了2和3的毛病单线程须要fork的时候须要限度程序CPU占用率的时候单线程的Reactor的次要毛病是响应工夫慢,多线程改善这一点多线程IO吞吐(网络/磁盘)是瓶颈时,多线程不会减少吞吐,这时候单线程+单过程就够了CPU算力是瓶颈时,多线程不会减少吞吐,这时候单线程+多过程更适合也更简略比照多过程8外围,压缩100个文件多过程:每个过程压缩1个文件多线程:每个文件用8个线程并行压缩总耗时雷同,因为CPU都是满载的,然而后者能更快拿到第一个压缩完的文件,这体现了多线程的低提早但实际上,线程间算法的并行度很难达到100%,所以:同一个工作,多线程或者会比多过程吞吐量降落一点,但肯定能够带来响应工夫的晋升。多线程的益处在于 能进步响应速度,让IO和计算重叠相比过程每次切换都使CPU Cache生效,线程间切换老本小,因而实用于“工作集”比拟大的状况宰割事务,将IO线程、计算线程和第三方库(例如logging)线程离开多线程应用BlockingQueue在过程间传递数据 计算操作:一个IO线程,8个计算线程(线程池),IO线程向BlockingQueue中增加数据,计算线程收到唤醒后开始计算写操作:一个独自的logging线程,通过一个或多个BlockingQueue对外提供接口,别的线程把日志写入Queue中即可,不须要期待,这样升高了服务线程的响应工夫 留神,读操作并不能利用多线程的便利性,因为无论如何都须要等到后果之后能力持续进行线程池 当计算在每次响应申请中占比比拟高时(20%以上)适宜能简化编程;防止实时创立线程的开销;加重IO线程的累赘(IO线程进行计算的话,就不能相应IO了,会导致响应速度变差)线程池的大小须要阻抗匹配,例如8核CPU,每个计算工作线程的密集计算所占工夫比重为50%,那么16个线程就能跑满全副CPU,线程池太小,会不能高效利用硬件,太大会导致额定的线程切换和内存开销多线程不能缩小工作量,而是一种兼顾的思路让工作提前完结。

November 24, 2021 · 1 min · jiezi

关于c#:ASPNET-使用-Dispose-释放资源的四种方法

Dispose 和 Finalize 是运行的 .NET 和 .NET Core 应用程序开释占用的资源的两种办法。通常,如果应用程序中有非托管资源,应该显式地开释这些资源占用的资源。 因为 Finalize 的非确定性,以及在性能方面的老本很高,因而 Dispose 办法的应用频率远高于 Finalize。其实,咱们能够在一个实现了 IDisposable 接口的类型上应用 Dispose 办法。 本文中提供的代码示例均默认运行在 Visual Studio 2022。 1. 应用 VS2022 创立 ASP.NET Core 我的项目咱们在 Visual Studio 2022 中创立一个 ASP.NET Core 我的项目。依照以下步骤在 Visual Studio 2022 中创立一个新的 ASP.NET Core Web API 6 我的项目。 1) 启动 Visual Studio 2022 IDE。2) 单击 “Create new project”。3) 在 “Create new project” 窗口中,从显示的模板列表中抉择 “ASP.NET Core Web API”。4) 点击下一步。5) 在 “Configure your new project” 窗口中,指定新我的项目的名称和地位。6) 依据您的偏好,可抉择选中 “Place solution and project in the same directory” 复选框。7) 点击下一步。8) 在接下来显示的 “Additional Information” 窗口中,从顶部的下拉列表中抉择 .NET 6.0 作为指标框架。将 “Authentication Type” 保留为 “None”(默认)。确保选中 “Use controllers ...” 选项。9) 确保未选中 “Enable Docker,”、“Configure for HTTPS” 和 “Enable Open API Support” 复选框,因为咱们不会在此处应用任何这些性能。您也能够抉择勾销选中 “Use controllers(勾销选中以应用起码的 API)” 复选框,因为咱们将创立本人的控制器。10) 单击创立。这将在 Visual Studio 2022 中创立一个新的 ASP.NET Core 6 Web API 我的项目。咱们将在本文的后续局部中应用该我的项目来阐明 Dispose 的用法。 ...

November 24, 2021 · 2 min · jiezi

关于c++:多线程服务器编程2线程同步精要

线程同步的四项准则最低限度的共享对象,缩小须要同步的场合应用高级的并发构件,如TaskQueue,Producer-Consumer Queue,CountDownLatch等非不得已应用底层同步原语时,只应用非递归的互斥器和条件变量,慎用读写锁,不要应用信号量除了应用atomic整数外,不本人编写lock-free代码,也不要应用内核级同步原语互斥器(mutex)应用准则应用RAII手法封装mutex的创立、销毁、加锁、解锁 保障了锁的失效期间等于一个作用域(Scoped Locking),在死锁产生时有助于定位保障了不手工调用lock和unlock保障了不跨过程和线程调用锁保障了不遗记解锁和反复加锁只应用非递归的mutex(即不可重入的mutex)每次结构Guard对象时,思考一路上曾经持有的锁(函数调用栈),避免因桎梏程序不同导致的死锁为什么只应用非递归的mutex同一个线程能够反复对递归的mutex加锁,但不能反复对非递归的mutex加锁在同一个县城里屡次对非递归的mutex加锁会导致死锁两者性能差异不大起因 非递归的锁能提前暴露出编程问题死锁除了线程间的死锁,单个线程也会造成死锁在保障应用Scoped Locking时,能够通过剖析调用栈失去起因条件变量应用条件变量实现的BlockingQueuemuduo::MutexLock mutex;muduo::Condition cond(mutex);std::deque<int> queue;int dequeue(){ MutexLockGuard lock(mutex); while(queue.empty()){ cond.wait(); // unlock mutex and wait (原子地) } assert(!queue.empty()); int top = queue.front(); queue.pop_front(); return top;}void enqueue(int x){ { MutexLockGuard lock(mutex); queue.push_back(x); } cond.notify(); // wakeup the wait side}每次退出都调用notify(),而不是notifyall()是为了防止惊群效应不只在0->1的时候notify(),而是每加一次告诉一次,是当存在多个消费者时,能高效地唤醒他们,不然只唤醒了一个详见 https://book.douban.com/annot...应用条件变量实现CountDownLatch(倒计时)class CountDownLatch : boost::noncopyable{ public: explicit CountDownLatch(int count); void wait(); void countDown(); private: mutable MutexLock mutex_; Condition condition_; int count_;}void CountDownLatch::wait(){ MutexLockGuard lock(mutex_); whilt(count_>0){ condition_.wait(); }}void CountDownLatch::countDown(){ MutexLockGuard lock(mutex_); --count_; if(count_ == 0){ condition_.notifyAll(); }}封装MutexLock、MutexLockGuard、Condition的实现class MutexLock : boost::noncopyable{ public: MutexLock() :holder_(0) { pthread_mutex_init(&mutex_NULL); } ~MutexLock() { assert(hoilder_ == 0); pthread_mutex_destory(&mutex); } bool isLockedByThisThread(){ return holder_ == CurrentThread::tid(); } void assertLocked(){ assert(isLockedByThisThread()); } void lock(){ pthread_mutex_lock(&mutex); holder_ = CurrentThread::tid(); } void unlock(){ holder_ = 0; pthread_mutex_unlock(); } pthread_mutex_t* getPthreadMutex(){ return &mutex; } private: pthread_mutex_t mutex_; pid_t holder_; }class MutexLockGuard : boost::noncopyable{ public: explicit MutexLockGuard(MutexLock& mutex) :mutex_(mutex) { mutex_.lock(); } ~MutexLockGuard(){ mutex_.unlock; } private: MutexLock& mutex_;}#define MutexLockGuard(x) static_assert(false,"Missing mutex guard variable name!")class Condition : boost::noncopyable{ public: explicit Condition(MutexLock& mutex) :mutex_(mutex) { pthread_cond_init(&pcond_,NULL); } ~Condition(){ pthread_cond_destory(&pcond_); } void wait(){ pthread_cond_wait(&pcond_,mutex_.getPthreadMutex()); } void notify(){ pthread_cond_signal(&pcond_); } void notifyAll(){ pthread_cond_boardcast(&pcond); } private: MutexLock& mutex_; pthread_cond_t pcond_;}小结线程同步的四项准则:尽量应用高级同步设施对于其余的工作,应用一般互斥器和条件变量,采纳RAII手法和Scooped Locking

November 23, 2021 · 1 min · jiezi

关于c#:手把手教你学Dapr-9-可观测性

目录手把手教你学Dapr - 1. .Net开发者的大时代 手把手教你学Dapr - 2. 必须晓得的概念 手把手教你学Dapr - 3. 应用Dapr运行第一个.Net程序 手把手教你学Dapr - 4. 服务调用 手把手教你学Dapr - 5. 状态治理 手把手教你学Dapr - 6. 公布订阅 手把手教你学Dapr - 7. Actors 手把手教你学Dapr - 8. 绑定 手把手教你学Dapr - 9. 可观测性 介绍通过Tracing(跟踪)、Metrics(指标)、Logs(日志)和Health(运行状况)监控应用程序。 分布式跟踪Dapr 应用 Zipkin 协定进行分布式跟踪 和 Metrics 收集。因为 Zipkin 协定的普遍性,许多后端都是开箱即用的,例如 Stackdriver、Zipkin、New Relic 等。联合 OpenTelemetry Collector,Dapr 能够将跟踪导出到许多其余后端,包含但不限于 Azure Monitor、Datadog、Instana、Jaeger 和 SignalFX。 Tracing设计Dapr 在 Dapr Sidecar 中增加了一个 HTTP/gRPC 中间件。中间件拦挡所有 Dapr 和应用程序流量,并主动注入关联 ID 以跟踪分布式事务。这种设计有几个益处: 无需代码检测。应用可配置的跟踪级别主动跟踪所有流量。跨微服务的一致性跟踪行为。跟踪是在 Dapr Sidecar 上配置和治理的,因而它在由不同团队制作并可能用不同编程语言编写的服务之间保持一致。可配置和可扩大。利用 Zipkin API 和 OpenTelemetry Collector,Dapr 跟踪能够配置为与风行的跟踪后端一起应用,包含客户可能领有的自定义后端。您能够同时定义和启用多个导出器。<!-- more --> ...

November 19, 2021 · 3 min · jiezi

关于c#:如何提高C-StringBuilder的性能

本文探讨应用C# StringBuilder 的最佳实际,用于缩小内存调配,进步字符串操作的性能。 在 .NET 中,字符串是不可变的类型。每当你在 .NET 中批改一个字符串对象时,就会在内存中创立一个新的字符串对象来保留新的数据。相比之下,StringBuilder 对象代表了一个可变的字符串,并随着字符串大小的增长动静地扩大其内存调配。 String 和 StringBuilder 类是你在 .NET Framework 和 .NET Core 中解决字符串时常常应用的两个风行类。然而,每个类都有其长处和毛病。 BenchmarkDotNet 是一个轻量级的开源库,用于对 .NET 代码进行基准测试。BenchmarkDotNet 能够将你的办法转化为基准,跟踪这些办法,而后提供对捕捉的性能数据的洞察力。在这篇文章中,咱们将利用 BenchmarkDotNet 为咱们的 StringBuilder 操作进行基准测试。 要应用本文提供的代码示例,你的零碎中应该装置有 Visual Studio 2019 或者以上版本。 1. 在Visual Studio中创立一个控制台应用程序我的项目首先让咱们在 Visual Studio中 创立一个 .NET Core 控制台应用程序我的项目。假如你的零碎中曾经装置了 Visual Studio 2019,请依照上面的步骤创立一个新的 .NET Core 控制台应用程序我的项目。 启动 Visual Studio IDE。点击 "创立新我的项目"。在 "创立新我的项目 "窗口中,从显示的模板列表中抉择 "控制台应用程序(.NET外围)"。点击 "下一步"。在接下来显示的 "配置你的新我的项目 "窗口中,指定新我的项目的名称和地位。点击创立。这将在 Visual Studio 2019 中创立一个新的 .NET Core 控制台应用程序我的项目。咱们将在本文的后续章节中应用这个我的项目来解决 StringBuilder。 2. 装置 BenchmarkDotNet NuGet包要应用 BenchmarkDotNet,你必须装置 BenchmarkDotNet 软件包。你能够通过 Visual Studio 2019 IDE 内的 NuGet 软件包管理器,或在 NuGet 软件包管理器控制台执行以下命令来实现。 ...

November 18, 2021 · 2 min · jiezi

关于c:编程艺术剖析-darknet-loadweights-接口

 欢送关注我的公众号 [极智视界],回复001获取Google编程标准 O_o >_<  o_O O_o ~_~ o_O 本文剖析下 darknet load_weights 接口,这个接口次要做模型权重的加载。 1、darknet 数据加载流程   之前的文章曾经介绍了一下 darknet 指标检测的数据加载流程,并介绍了.data、.names 和 .cfg 的加载实现。   接下来这里 load_weights 接口次要做 .weights 模型权重的加载。 2、load_weights 接口   先来看一下接口调用: load_weights(&net, weightfile);   其中 net 为 network 构造体的实例,weightfile 为权重的文件门路,看一下 load_weights 的实现: /// parser.cvoid load_weights(network *net, char *filename){ load_weights_upto(net, filename, net->n);}   次要调用了 load_weights_upto 函数: /// parser.cvoid load_weights_upto(network *net, char *filename, int cutoff){#ifdef GPU if(net->gpu_index >= 0){ cuda_set_device(net->gpu_index); // 设置 gpu_index } #endif fprintf(stderr, "Loading weights from %s...", filename); fflush(stdout); // 强制马上输入 FILE *fp = fopen(filename, "rb"); if(!fp) file_error(filename); int major; int minor; int revision; fread(&major, sizeof(int), 1, fp); // 一些标记位的加载 fread(&minor, sizeof(int), 1, fp); fread(&revision, sizeof(int), 1, fp); if ((major * 10 + minor) >= 2) { printf("\n seen 64"); uint64_t iseen = 0; fread(&iseen, sizeof(uint64_t), 1, fp); *net->seen = iseen; } else { printf("\n seen 32"); uint32_t iseen = 0; fread(&iseen, sizeof(uint32_t), 1, fp); *net->seen = iseen; } *net->cur_iteration = get_current_batch(*net); printf(", trained: %.0f K-images (%.0f Kilo-batches_64) \n", (float)(*net->seen / 1000), (float)(*net->seen / 64000)); int transpose = (major > 1000) || (minor > 1000); int i; for(i = 0; i < net->n && i < cutoff; ++i){ // 辨认不同算子进行权重加载 layer l = net->layers[i]; if (l.dontload) continue; if(l.type == CONVOLUTIONAL && l.share_layer == NULL){ load_convolutional_weights(l, fp); } if (l.type == SHORTCUT && l.nweights > 0) { load_shortcut_weights(l, fp); } if (l.type == IMPLICIT) { load_implicit_weights(l, fp); } if(l.type == CONNECTED){ load_connected_weights(l, fp, transpose); } if(l.type == BATCHNORM){ load_batchnorm_weights(l, fp); } if(l.type == CRNN){ load_convolutional_weights(*(l.input_layer), fp); load_convolutional_weights(*(l.self_layer), fp); load_convolutional_weights(*(l.output_layer), fp); } if(l.type == RNN){ load_connected_weights(*(l.input_layer), fp, transpose); load_connected_weights(*(l.self_layer), fp, transpose); load_connected_weights(*(l.output_layer), fp, transpose); } if(l.type == GRU){ load_connected_weights(*(l.input_z_layer), fp, transpose); load_connected_weights(*(l.input_r_layer), fp, transpose); load_connected_weights(*(l.input_h_layer), fp, transpose); load_connected_weights(*(l.state_z_layer), fp, transpose); load_connected_weights(*(l.state_r_layer), fp, transpose); load_connected_weights(*(l.state_h_layer), fp, transpose); } if(l.type == LSTM){ load_connected_weights(*(l.wf), fp, transpose); load_connected_weights(*(l.wi), fp, transpose); load_connected_weights(*(l.wg), fp, transpose); load_connected_weights(*(l.wo), fp, transpose); load_connected_weights(*(l.uf), fp, transpose); load_connected_weights(*(l.ui), fp, transpose); load_connected_weights(*(l.ug), fp, transpose); load_connected_weights(*(l.uo), fp, transpose); } if (l.type == CONV_LSTM) { if (l.peephole) { load_convolutional_weights(*(l.vf), fp); load_convolutional_weights(*(l.vi), fp); load_convolutional_weights(*(l.vo), fp); } load_convolutional_weights(*(l.wf), fp); if (!l.bottleneck) { load_convolutional_weights(*(l.wi), fp); load_convolutional_weights(*(l.wg), fp); load_convolutional_weights(*(l.wo), fp); } load_convolutional_weights(*(l.uf), fp); load_convolutional_weights(*(l.ui), fp); load_convolutional_weights(*(l.ug), fp); load_convolutional_weights(*(l.uo), fp); } if(l.type == LOCAL){ int locations = l.out_w*l.out_h; int size = l.size*l.size*l.c*l.n*locations; fread(l.biases, sizeof(float), l.outputs, fp); fread(l.weights, sizeof(float), size, fp);#ifdef GPU if(gpu_index >= 0){ push_local_layer(l); }#endif } if (feof(fp)) break; } fprintf(stderr, "Done! Loaded %d layers from weights-file \n", i); fclose(fp);}   以上有几个点不容易看懂,如以下这段: ...

November 17, 2021 · 4 min · jiezi

关于c#:手把手教你学Dapr-8-绑定

目录手把手教你学Dapr - 1. .Net开发者的大时代 手把手教你学Dapr - 2. 必须晓得的概念 手把手教你学Dapr - 3. 应用Dapr运行第一个.Net程序 手把手教你学Dapr - 4. 服务调用 手把手教你学Dapr - 5. 状态治理 手把手教你学Dapr - 6. 公布订阅 手把手教你学Dapr - 7. Actors 手把手教你学Dapr - 8. 绑定 介绍应用绑定,您能够应用来自内部零碎的事件触发您的应用程序,或与内部零碎交互。这个构建块为您和您的代码提供了几个益处: 打消连贯和轮询音讯零碎(如队列和音讯总线)的复杂性关注业务逻辑,而不是如何与零碎交互的实现细节让您的代码不受 SDK 或库的影响解决重试和故障复原运行时在绑定之间切换构建可移植的应用程序,其中设置了特定于环境的绑定,不须要更改代码输出绑定输出绑定用于在产生来自内部资源的事件时触发您的应用程序。可选的payload和元数据能够与申请一起发送。 为了从输出绑定接管事件: 定义形容绑定类型及其元数据(连贯信息等)的组件 YAML侦听传入事件的 HTTP 端点,或应用 gRPC proto 库获取传入事件输入绑定输入绑定容许您调用内部资源。可选的payload和元数据能够与申请一起发送。 为了调用输入绑定: 定义形容绑定类型及其元数据(连贯信息等)的组件 YAML应用 HTTP 或 gRPC 办法调用具备可选payload的绑定应用场景应用绑定,你的代码能够被来自不同资源的传入事件触发,这些资源能够是任何货色:队列、消息传递管道、云服务、文件系统等。 这对于事件驱动解决、数据管道或只是对事件做出个别反馈并进行进一步解决是现实的。 Dapr 绑定容许您: 在不蕴含特定 SDK 或库的状况下接管事件在不更改代码的状况下替换绑定专一于业务逻辑而不是事件资源实现目前Dapr还不反对跨Dapr互调用,而yaron给出的解决方案之一就是绑定目前绑定反对40中组件,包含Aliyun、Azure、AWS等多家云服务厂商的产品,也包含常见的如Cron, kafka, MQTT, SMTP, Redis以及各种MQ等。 以下图片是.Net Dapr官网教程里的一个示例 配置组件本篇文章将用rabbitmq来演示(为什么不必redis,因为redis翻车了,只反对output,没留神看supported),如前几篇文章所说,先配置yaml 装置rabbitmq docker pull rabbitmq:3.8.25-management运行rabbitmq ...

November 17, 2021 · 1 min · jiezi

关于c#:手把手教你学Dapr-7-Actors

介绍Actor模式将Actor形容为最低级别的“计算单元”。换句话说,您在一个独立的单元(称为actor)中编写代码,该单元接管音讯并一次解决一个音讯,没有任何并发或线程。 再换句话说,依据ActorId划分独立计算单元后,雷同的ActorId重入要排队,能够了解为lock(ActorId) 注:这里有个反例,就是重入性的引入,这个概念目前还是Preview,它容许同一个链内能够反复进入,判断的规范不止是ActorId这么简略,即本人调本人是被容许的。这个默认是敞开的,须要手动开启,即默认不容许本人调本人。 当您的代码解决一条音讯时,它能够向其余参与者发送一条或多条音讯,或者创立新的参与者。底层运行时治理每个参与者运行的形式、工夫和地点,并在参与者之间路由音讯。 大量的Actor能够同时执行,Actor彼此独立执行。 Dapr 蕴含一个运行时,它专门实现了 Virtual Actor 模式。 通过 Dapr 的实现,您能够依据 Actor 模型编写 Dapr Actor,而 Dapr 利用底层平台提供的可扩展性和可靠性保障。 什么时候用ActorsActor 设计模式非常适合许多分布式系统问题和场景,但您首先应该思考的是该模式的束缚。一般来说,如果呈现以下状况,请思考应用Actors模式来为您的问题或场景建模: 您的问题空间波及大量(数千个或更多)小的、独立且孤立的状态和逻辑单元。您心愿应用不须要与内部组件进行大量交互的单线程对象,包含跨一组Actors查问状态。您的 Actor 实例不会通过收回 I/O 操作来阻塞具备不可预测提早的调用者。Dapr Actor每个Actor都被定义为Actor类型的实例,就像对象是类的实例一样。 例如,可能有一个执行计算器性能的Actor类型,并且可能有许多该类型的Actor散布在集群的各个节点上。每个这样的Actor都由一个Acotr ID惟一标识。 生命周期Dapr Actors是虚构的,这意味着他们的生命周期与他们的内存体现无关。因而,它们不须要显式创立或销毁。Dapr Actors运行时在第一次收到对该Actor ID 的申请时会主动激活该Actor。如果一个Actor在一段时间内没有被应用,Dapr Actors运行时就会对内存中的对象进行垃圾回收。如果稍后须要从新激活,它还将放弃对参与者存在的理解。如果稍后须要从新激活,它还将放弃对 Actor 的所有原有数据。 调用 Actor 办法和揭示会重置闲暇工夫,例如揭示触发将使Actor放弃沉闷。无论Actor是沉闷还是不沉闷,Actor揭示都会触发,如果为不沉闷的Actor触发,它将首先激活演员。Actor 计时器不会重置闲暇工夫,因而计时器触发不会使 Actor 放弃活动状态。计时器仅在Actor处于活动状态时触发。 Reminders 和 Timers 最大的区别就是Reminders会放弃Actor的活动状态,而Timers不会Dapr 运行时用来查看Actor是否能够被垃圾回收的闲暇超时和扫描距离是可配置的。当 Dapr 运行时调用 Actor 服务以获取反对的 Actor 类型时,能够传递此信息。 因为Virtual Actor模型的存在,这种Virtual Actor生命周期形象带来了一些注意事项,事实上,Dapr Actors实现有时会偏离这个模型。 第一次将音讯发送到Actor ID时,Actor被主动激活(导致构建Actor对象)。 通过一段时间后,Actor对象将被垃圾回收。被回收后再次应用Actor ID将导致结构一个新的Actor对象。 Actor 的状态比对象的生命周期长,因为状态存储在 Dapr 运行时配置的状态治理组件中。 注:Actor被垃圾回收之前,Actor对象是会复用的。这里会导致一个问题,在.Net Actor类中,构造函数在Actor存活期间只会被调用一次。散发和故障转移为了提供可扩展性和可靠性,Actor 实例散布在整个集群中,Dapr 依据须要主动将它们从故障节点迁徙到衰弱节点。 ...

November 17, 2021 · 4 min · jiezi

关于c:C-语言为什么不会过时

本文整顿自网络 作者: 赵岩/Serdar等 01、为什么C语言不会过期评估任何一门编程语言,都是招人骂的。永远是这样。就像是春寒料峭的节令,街上穿棉袄和穿单衣的擦肩而过,单方肯定是同时在心里呈现了两个字:“傻逼!”这个在心理学上有个业余的名字:叫做“二逼”景象! 那我为啥还要做这个挨骂的事呢?作为《C语言点滴》《drop of knowledge of C++》书籍的作者,《C语言新思维,第二版》的译者(赵岩老师),我感觉我有责任零碎的介绍一下这本语言,他的特点,还有他的将来。这个问题对很多刚刚踏入程序猿这个行业的老手至关重要。因为他们有深深的担心,万一C语言就像Fortran那样过期了怎么办? 先上一个表,这个就是驰名的TIOBE语言排行榜。目前它是一个最权威的一个语言风行度的排行榜。 就在5月,时隔5年,C语言再次当先Java,荣登TIOBE编程语言排行榜第一! 排名前十的别离是: C,Java,Python,C++,C#,Visual Basic.NET,JavaScript,PHP,SQL和R。 有没有发现亮点?没错, 第一易主了,C 语言反超了 Java 。要晓得,C 语言上次第一还是在 5 年前,是什么起因让其“卷土重来”了呢? 时隔五年,C语言重回榜首。 据TIOBE CEO Paul Jansen 的猜想,“这听起来可能很不堪设想,然而某些编程语言的确能够从这种状况中受害。"嵌入式语言(C 和 C++ 等)越来越风行,因为它们被用于医疗设施软件中。 对所有的编程语言,他们的最初的目标其实就是两种:进步硬件的运行效率和进步程序员的开发效率。 遗憾的是,这两点是不可能并存的!你只能选一样。在进步硬件的运行效率这一方面,C语言没有竞争者!举个简略的例子,实现一个列表,C语言用数组int a[3],通过编译当前变成了(基地址+偏移量)的形式。对于计算机来说,没有运算比加法更快,没有任何一种办法比(基地址+偏移量)的存取方法更快。 C语言曾经把硬件的运行效率压缩到了极致。这种设计思维带来的问题就是易用性和安全性的缺失。例如,你不能在数组中混合保留不同的类型,否则编译器没有方法计算正确的偏移量。同时C语言对于谬误的偏移量也充耳不闻,这就是C语言中臭名远扬的越界问题。 C语言自夸的“置信程序员”都是丑陋的说辞,它的惟一目标就是快,要么飞速的运行,要么飞速的解体。C语言只关怀程序飞的高不高,不关怀程序猿飞的累不累。就是这样! 当初来看看那些非C的语言,他们的短处都在于进步程序员的开发效率上。或者反对动静的列表,或者反对平安的列表。然而退出任何的中间层,退出任何的平安测验,它不可能比(基地址+偏移量+无测验)的形式更快。这个世界上不存在“开发容易,运行快”的语言,开发容易毕竟来源于对底层的一层一层又一层的包装。 当初答复两个最广泛的问题:硬件这么便宜了,有必要让软件更快吗?有这种疑难的人大部分都是网吧的固定客户,他们了解的计算机只在电脑城,他们了解的计算只是游戏和播放硬盘中的小电影。不要玩个游戏开个挂就乐得不行不行的,别忘了还有全实景仿真,还有3D渲染,还有主动驾驶。 人在开车的时候,每秒要收集60个不同的物体,而后依据这60个物体的不同组合和反映来做20个最重要的决定。而后从这20多个决定当选一个执行。所以就算用上最快的硬件,主动驾驶当初还不敢说能像人那样开车。就算是主动驾驶胜利了,下一步还要主动航行呢?因为咱们老早就预言了:你咋不入地呢! 所以说:计算速度永远是不够的!因为新的利用会越来越简单,越来也实时。对了!我还忘了一个更重要的限度:计算的能耗!NASA飞行器上的CPU最多就是32位的,说进去你可能不信,国内空间站上没有一个CPU是64位的,我猜一个最次要的起因是航天员不爱看硬盘小电影吧。 另外一个风行的疑难是:我能够创造一种同样快的语言,然而没有C语言那么多的坑。想法是能够的,而且还真巧有这个语言,真巧它的名字叫D语言,真巧没有太多的人用!这是因为一个根本的事实。当初有太多,太多太多的C代码,他们大部分都在失常工作,就像Linux, Window, MacOS,Unix,Vxworks。你没有看错,这些操作系统的内核都是C,我尽管不确定C在Window中所占的比例,然而我置信微软的人不会傻到用C#去全副改写一个操作系统的内核。你想让这些人去用你的全新的语言,这就不是“有点”很傻,很天真了! 而且有些代码,咱们基本就不能改!NASA一个简略的5个CPU飞控软件编写结束后,要进行一种“全笼罩”测试。如果CPU A坏了会产生什么?如果CPU A,B坏了呢?如果CPU A,C坏了呢。。。。?如果你违心,你能够做个简略的数学组合。测试结束后,别说重写,就算加个正文都不行。因为主管payload的大妈会十分庄重的质问你,为什么你上报的货色数量减少了,然而品质没有减少?你须要和她具体的解释:硬件和软件是不同的,硬件是那种摸起来硬硬的货色,然而软件不是那种摸起来软软的货色。看着大妈鄙夷的眼神,这个时候你会十分悔恨本人手欠退出的哪一行正文。你还别不当真,这个是NASA的实在故事。 那为什么C语言还降落这么多呢?很简略,有些工作自身就不是C语言的。我上学的时候还用C语言编过窗口界面呢?而后很快微软的人就推出了MFC,就是一大堆宏把底层的C windowAPI包装了起来。 再起初这个技术也过期了。因为微软的人意识到,带有窗口的应用程序说到底不是C语言的本职工作,再这么一层一层包下去就有露馅的危险,于是他们创造了一个全新的语言C#来负责这个工作。 Java也是这样,突出网络,易用,平安,跨平台。无论是Java, c#还是python, 他们都无意避开进步硬件的运行效率这个问题,因为这个问题上没方法和C竞争,也无奈撼动Linux, Unix,GNU tool这些已有C代码的地位。剩下的就只是进步程序员的开发效率上大作文章。这对C语言是坏事,把本人不善长的货色去掉,让本人跑的更快! 随同着嵌入和实时零碎的衰亡,AI,机器人,主动驾驶等。这些都是C语言的外围利用,而且在这种利用下面,C语言没有竞争者。所以我感觉C语言会稳固在本人外围的利用中,并开始逐渐回升。 最初说点闲话,C++不会淘汰C语言。有了对象后你会发现再俭朴的对象也消耗资源,而且有了对象当前,总是情不自禁的去想继承这个事,一但继承实现了,你会发现继承带来的麻烦远超过你的设想。Java的发明人James被问到如果能够从新设计Java语言的话,第一个要做什么事?他说:“去掉对象”!作为一个已婚,有两个孩子的程序猿,我感同身受。如果大家感兴趣,我能够再写一个博客,聊聊C++和C的实在区别所在。 如果你看到这里,还什么都没记住。那就只记住一点:没人能预测将来。 如果再有人对你说C语言曾经过期了,最好本人思考一下,能求真最好,如果不能,至多要做到存疑。 02、为什么C仍占据统治位置?于一种计算机行业的技术来说尤其如此。自1972年诞生以来,C语言始终放弃龙腾虎跃的状态,时至今日它依然是咱们用来搭建软件世界的根底建筑材料之一。 但有时一种技术可能长期存在,只是因为人们还没有来得及创造新的货色来取代它而已。在过来的几十年里,呈现了许多其余语言——其中一些明确地被设计用于挑战C的主导地位,有些语言试图凭借本人的人气缓缓瓦解C语言的统治位置。 为C须要被替换掉的观点辩论是简略的。编程语言钻研和软件开发实际都暗示了如何比C更好地去做事。但历经数十年的钻研和开发,C语言的位置却仍旧巩固。很少有其余语言可能在性能、裸机兼容性或通用性等方面击败它。不过,2018年C是如何与那些明星编程语言竞争的呢,其中细节仍值得一看。 C vs. C ++当然了,C最常被拿来与C ++进行比拟,正如其名称自身所暗示的那样,C++作为对C语言的扩大而被创立进去。C ++和C之间的差别能够概括为C++更加宽泛(褒)或更加宽泛(贬),具体取决于这个问题你是问的C还是C++程序员。(笑) ...

November 17, 2021 · 1 min · jiezi

关于c++:Ubuntu2004配置PCL库

目前钻研的方向是基于车载激光雷达进行路线环境的三维高精地图的构建。这种高精地图是以车载激光雷达采集的点云为基准,以图像为辅助来进行路线环境信息的辨认的提取。其中对点云的解决非常重要,针对点云进行工作,肯定绕不开PCL库。PCL(PointCloudLibrary)是一个独立凋谢的2D/3D点云跨平台C++库。PCL蕴含多个模块,如点云获取、滤波、宰割、配准、检索、特征提取、辨认、追踪、曲面重建、可视化等,为点云解决提供了极大的便当。 之前学习PCL的时候是在win10下,win10配置PCL库非常繁琐,容易出错。此外,当初小组的工作站和我本人的集体笔记本都是Ubuntu20.04,因而在Ubuntu20.04上进行PCL库的装置和配置。 整顿了网上的攻略,装置步骤如下: 1. 装置各种依赖 sudo apt-get updatesudo apt-get install git build-essential linux-libc-devsudo apt-get install cmake cmake-guisudo apt-get install libusb-1.0-0-dev libusb-dev libudev-devsudo apt-get install mpi-default-dev openmpi-bin openmpi-commonsudo apt-get install libflann1.9 libflann-devsudo apt-get install libeigen3-devsudo apt-get install libboost-all-devsudo apt-get install libqhull* libgtest-dev sudo apt-get install freeglut3-dev pkg-config sudo apt-get install libxmu-dev libxi-dev sudo apt-get install mono-complete sudo apt-get install libopenni-dev sudo apt-get install libopenni2-dev sudo apt-get install libvtk7-deb libvtk6-devsudo apt-get install qt5-default其中依照网上攻略执行sudo apt-get install libflann1.8 libflann-dev一步时产生谬误,显示显示无奈定位包libflann1.8。查阅Ubuntu Packages后发现18.04后须要libflann1.9版本,改成sudo apt-get install libflann1.9 libflann-dev后胜利装置 ...

November 16, 2021 · 2 min · jiezi

关于c#:C-线程锁和单多线程简单使用

前言:博主昨天在用C#写毕设的时候遇到了一个问题,就是博主的发送命令,须要循环发送,然而要我的接管是有1秒延时,于是就呈现了,我循环发送命令,最初只收到了,最初两条命令的值,于是在一些大佬群里问有没有人会C#的线程锁,失去的回答是这门语言用的人很少,于是博主翻阅材料自学了一下,学了之后就想写进去和大家一起分享一下,除了线程锁,顺带提一下多线程,写的不好,不喜勿喷。 每日一遍,情绪愉悦 1.首先看看咱们的问题 咱们能够看到咱们的循环失去的值会十分疾速的失去答案,然而我在做我的项目的时候须要这个循环函数期待我的接管回答,于是咱们要用到线程锁这方面的常识。 private static object lockObj = new object();//定义线程锁 private int num = 0; private void Test() { while (true) { lock (lockObj)//锁住这个代码块 { num++; string name = Thread.CurrentThread.Name;//获取线程名 textBox1.AppendText(name+"测试:"+num);//这个是TextBox1的追加 textBox1.AppendText(System.Environment.NewLine); Thread.Sleep(2000);//将线程挂起,相当于进行2秒 if (num>=10)//让这个线程执行10次就退出 { break; } } } }这个是应用单线程实现的成果,private void Test(),咱们在定义线程的时候就会在线程Thread(Test)外面定义为Test函数名,代表着,线程跑这个函数,while (true)示意这个线程始终在这里跑直到退锁,lock (lockObj)代表上锁,把这个代码块锁住直到解锁,相当于始终在这运行,只有咱们不退锁,博主只是应用break退出,Sleep代表线程挂起,相当于进行期待了。咱们应用这个能够实现循环函数期待回答。 单线程只须要建设一个线程就能够啦, while (true)能够依据本人的实例来定义线程数量,实践上是线程越多,越快,然而也要思考线程节约。 //单线程 Thread thred1 = new Thread(Test);//定义一个线程 thred1.Name = "thred1";//线程名 thred1.IsBackground = true;//设置为后盾线程就是True thred1.Start();//开始执行这个线程 int n = thred1.ManagedThreadId;//这个线程ID的标识 Console.WriteLine(n);博主再应用多线程操作一下,博主建设了两个线程跑的这个程序,通过看那个name能够看进去,一个Thread1一个Thred2,咱们会发现博主的退出的条件是,大于或等于10就退出,实践上应该在10就进行,然而咱们应用了两个线程,在第二个线程达到的时候咱们的num曾经为10了,线程一曾经退出了,所以到了11,线程二才退出, ...

November 16, 2021 · 1 min · jiezi

关于c#:c执行windows模拟登录

登录代码 /// <summary> /// 登录权限 /// </summary> /// <param name="path"></param> /// <param name="userName"></param> /// <param name="passWord"></param> /// <returns></returns> public bool ConnectState(string path, string userName, string passWord) { bool Flag = false; Process proc = new Process(); try { proc.StartInfo.FileName = "cmd.exe"; proc.StartInfo.UseShellExecute = false; proc.StartInfo.RedirectStandardInput = true; proc.StartInfo.RedirectStandardOutput = true; proc.StartInfo.RedirectStandardError = true; proc.StartInfo.CreateNoWindow = true; proc.Start(); string dosLine = "net use " + path + " " + passWord + " /user:" + userName; proc.StandardInput.WriteLine(dosLine); proc.StandardInput.WriteLine("exit"); while (!proc.HasExited) { proc.WaitForExit(1000); } string errormsg = proc.StandardError.ReadToEnd(); proc.StandardError.Close(); if (string.IsNullOrEmpty(errormsg)) { Flag = true; } else { throw new Exception(errormsg); } } catch (Exception ex) { DisplaylistboxMsg(ex.Message); } finally { proc.Close(); proc.Dispose(); } return Flag; }执行登录 private void 登录_Click(object sender, EventArgs e) { bool userbool = ConnectState(@"\\**.**.*.*",User.Text,Pwd.Text); if (userbool) { DisplaylistboxMsg("登录胜利:"+User.Text); } else { DisplaylistboxMsg("登录失败"); } }

November 15, 2021 · 1 min · jiezi

关于c#:手把手教你学Dapr-6-发布订阅

介绍公布/订阅模式容许微服务应用音讯互相通信。生产者或发布者在不晓得哪个应用程序将接管它们的状况下向主题发送音讯。这波及将它们写入输出通道。同样,消费者或订阅者订阅该主题并接管其音讯,而不晓得是什么服务产生了这些音讯。这波及从输入通道接管音讯。两头音讯代理负责将每条音讯从输出通道复制到所有对该音讯感兴趣的订阅者的输入通道。当您须要将微服务彼此拆散时,这种模式特地有用。 Dapr 中的公布/订阅 API 提供至多一次(at-least-once)的保障,并与各种音讯代理和队列系统集成。 您的服务所应用的特定实现是可插入的,并被配置为运行时的 Dapr Pub/Sub 组件。 这种办法打消了您服务的依赖性,从而使您的服务能够更便携,更灵便地适应更改。 Dapr 公布/订阅构建块提供了一个与平台无关的 API 来发送和接管音讯。您的服务将音讯公布到命名主题,并订阅主题以应用这些音讯。 下图显示了一个“shipping”服务和一个“email”服务的例子,它们都订阅了“cart”服务公布的主题。每个服务都会加载指向同一公布/订阅音讯总线组件的公布/订阅组件配置文件,例如 Redis Streams、NATS Streaming、Azure Service Bus 或 GCP Pub/Sub。 下图具备雷同的服务,然而这次显示的是 Dapr 公布 API,它发送“订单”主题和订阅服务上的订单端点,这些主题音讯由 Dapr 公布到。 个性Cloud Events音讯格局为了启用音讯路由并为每条音讯提供额定的上下文,Dapr 应用 CloudEvents 1.0 标准作为其音讯格局。应用程序应用 Dapr 发送到主题的任何音讯都会主动“包装”在 Cloud Events 信封中,应用 datacontenttype 属性的 Content-Type 标头值。 Dapr 实现了以下 Cloud Events 字段: idsourcespecversiontypedatacontenttype (Optional)以下示例显示了 CloudEvent v1.0 中序列化为 JSON 的 XML 内容: { "specversion" : "1.0", "type" : "xml.message", "source" : "https://example.com/message", "subject" : "Test XML Message", "id" : "id-1234-5678-9101", "time" : "2020-09-23T06:23:21Z", "datacontenttype" : "text/xml", "data" : "<note><to>User1</to><from>user2</from><message>hi</message></note>"}音讯订阅Dapr 应用程序能够订阅已公布的主题。 Dapr 容许您的应用程序订阅主题的两种办法: ...

November 15, 2021 · 3 min · jiezi

关于c#:语法特性总结

C# 10已与.NET 6、VS2022一起公布,本文依照.NET的公布程序,依据微软官网文档整顿C#中一些乏味的语法个性。 注:基于不同.NET平台创立的我的项目,默认反对的C#版本是不一样的。上面介绍的语法个性,会阐明引入C#的版本,在应用过程中,须要留神应用C#的版本是否反对对应的个性。C#语言版本控制,可参考官网文档。 匿名函数匿名函数是C# 2推出的性能,顾名思义,匿名函数只有办法体,没有名称。匿名函数应用delegate创立,可转换为委托。匿名函数不须要指定返回值类型,它会依据return语句主动判断返回值类型。 注:C# 3后推出了lambda表达式,应用lambda能够以更简洁的形式创立匿名函数,应尽量应用lambda来创立匿名函数。与lambda不同的是,应用delegate创立匿名函数能够省略参数列表,可将其转换为具备任何参数列表的委托类型。 // 应用delegate关键字创立,无需指定返回值,可转换为委托,可省略参数列表(与lambda不同)Func<int, bool> func = delegate { return true; };主动属性从C# 3开始,当属性拜访器中不须要其它逻辑时,能够应用主动属性,以更简洁的形式申明属性。编译时,编译器会为其创立一个仅能够通过get、set拜访器拜访的公有、匿名字段。应用VS开发时,能够通过snippet代码片段prop+2次tab疾速生成主动属性。 // 属性老写法private string _name;public string Name{ get { return _name; } set { _name = value; }}// 主动属性public string Name { get; set; }另外,在C# 6当前,能够初始化主动属性: public string Name { get; set; } = "Louzi";匿名类型匿名类型是C# 3后推出的性能,它无需显示定义类型,将一组只读属性封装到单个对象中。编译器会主动推断匿名类型的每个属性的类型,并生成类型名称。从CLR的角度看,匿名类型与其它援用类型没什么区别,匿名类型间接派生自object。如果两个或多个匿名对象指定了程序、名称、类型雷同的属性,编译器会把它们视为雷同类型的实例。在创立匿名类型时,如果不指定成员名称,编译器会把用于初始化属性的名称作为属性名称。 匿名类型多用于LINQ查问的select查问表达式。匿名类型应用new与初始化列表创立: // 应用new与初始化列表创立匿名类型var person = new { Name = "Louzi", Age = 18 };Console.WriteLine($"Name: {person.Name}, Age: {person.Age}");// 用于LINQvar productQuery = from prod in products select new { prod.Color, prod.Price };foreach (var v in productQuery){ Console.WriteLine("Color={0}, Price={1}", v.Color, v.Price);}LINQC# 3推出了杀手锏性能,查问表达式,即语言集成查问(LINQ)。查问表达式以查问语法示意查问,由一组相似SQL的语法编写的子句组成。 ...

November 14, 2021 · 5 min · jiezi

关于c++:MatrixMatrix-Multiplication

Program Assignment #2Due day: NOV. 16, 2021Problem 1: Matrix-Matrix MultiplicationIn the first hands-on lab section, this lab introduces a famous and widely-used exampleapplication in the parallel programming field, namely the matrix-matrix multiplication.You will complete key portions of the program in the CUDA language to compute thiswidely-applicable kernel.In this lab you will learn:‧ How to allocate and free memory on GPU.‧ How to copy data from CPU to GPU.‧ How to copy data from GPU to CPU.‧ How to measure the execution times for memory access and computationrespectively.‧ How to invoke GPU kernels.Your output should look like this:Input matrix file name:Setup host side environment and launch kernel:Allocate host memory for matrices M and N.M:N:Allocate memory for the result on host side.Initialize the input matrices.Allocate device memory.Copy host memory data to device.Allocate device memory for results.Setup kernel execution parameters. ...

November 12, 2021 · 2 min · jiezi

关于c#:手把手教你学Dapr-5-状态管理

介绍应用状态治理,您的应用程序能够将数据作为键/值对存储在反对的状态存储中。 您的应用程序能够应用 Dapr 的状态治理 API 应用状态存储组件来保留和读取键/值对,如下图所示。例如,通过应用 HTTP POST,您能够保留键/值对,通过应用 HTTP GET,您能够读取键并返回其值。 个性可插拔状态存储Dapr 数据存储被建模为组件,能够在不更改代码的状况下更换它。例如:MySQL、Redis、Azure CosmosDB等。 可配置的状态存储行为Dapr 容许开发人员将额定的元数据附加到状态操作申请中,用以形容申请的解决形式。如: 并发要求一致性要求默认状况下,您的应用程序应假设数据存储最终统一并应用最初写入获胜的并发模式 并发Dapr 反对应用 ETags 的乐观并发管制 (OCC)。当申请状态时,Dapr 总是将 ETag 属性附加到返回的状态。当用户代码尝试更新或删除状态时,应该通过申请注释附加 ETag 以进行更新或通过 If-Match 标头进行删除。只有当提供的 ETag 与状态存储中的 ETag 匹配时,写操作能力胜利。建议您在应用 ETag 时应用重试策略来弥补此类抵触。 如果您的应用程序在写入申请时省略 ETag,则 Dapr 在解决申请时会跳过 ETag 查看。与应用 ETag 的先写赢模式相比,这本质上启用了最初写赢模式。 主动加密Dapr 反对应用程序状态的主动客户端加密,并反对密钥轮换。这是一项预览性能,所有 Dapr 状态存储都反对。 一致性Dapr 反对强一致性和最终一致性,最终一致性作为默认行为。 当应用强一致性时,Dapr 在确认写入申请之前期待所有正本(或指定的仲裁)确认。当应用最终一致性时,一旦底层数据存储承受写入申请,Dapr 就会立刻返回,即便这是单个正本。批量操作Dapr 反对两种类型的批量操作 - 批量(bulk)或多(multi)。 注:bulk与multi的区别在于bulk不是事务性的,multi是事务处理。 Actor状态事务状态存储可用于存储Actor状态。要指定用于Actor的状态存储,请在状态存储组件的元数据局部中将属性 actorStateStore 的值指定为 true。 注:Actors 状态以特定计划存储在事务状态存储中容许统一的查问。所以只能有一个状态存储组件被用于所有的Actor。 间接查问状态存储Dapr 无需任何转换即可保留和检索状态值。您能够间接从底层状态存储查问和聚合状态。 例如,要在 Redis 中获取与应用程序 ID “myApp” 关联的所有状态键,请应用: ...

November 12, 2021 · 2 min · jiezi

关于c:C-语言基础来喽

大家好,我是程序员cxuan!明天和大家一起学习C 语言根底! 前言C 语言是一门形象的、面向过程的语言,C 语言广泛应用于底层开发,C 语言在计算机体系中占据着不可代替的作用,能够说 C 语言是编程的根底,也就是说,不论你学习任何语言,都应该把 C 语言放在首先要学的地位上。上面这张图更好的阐明 C 语言的重要性 <img src="https://s1.ax1x.com/2020/09/10/wG83gx.png" alt="01" border="0" style="zoom:50%;" > 能够看到,C 语言是一种底层语言,是一种零碎层级的语言,操作系统就是应用 C 语言来编写的,比方 Windows、Linux、UNIX 。如果说其余语言是光鲜亮丽的表面,那么 C 语言就是灵魂,永远那么朴实无华。 原文链接:C 语言根底,来喽! C 语言个性那么,既然 C 语言这么重要,它有什么值得咱们去学的中央呢?咱们不应该只因为它重要而去学,咱们更在意的是学完咱们能学会什么,能让咱们取得什么。 C 语言的设计C 语言是 1972 年,由贝尔实验室的丹尼斯·里奇(Dennis Ritch)和肯·汤普逊(Ken Thompson)在开发 UNIX 操作系统时设计了C语言。C 语言是一门风行的语言,它把计算机科学实践和工程实际实践完满的交融在一起,使用户可能实现模块化的编程和设计。 计算机科学实践:简称 CS、是系统性钻研信息与计算的实践根底以及它们在计算机系统中如何实现与利用的实用技术的学科。C 语言具备高效性C 语言是一门高效性语言,它被设计用来充分发挥计算机的劣势,因而 C 语言程序运行速度很快,C 语言可能正当了应用内存来取得最大的运行速度 C 语言具备可移植性C 语言是一门具备可移植性的语言,这就意味着,对于在一台计算机上编写的 C 语言程序能够在另一台计算机上轻松地运行,从而极大的缩小了程序移植的工作量。 C 语言特点C 语言是一门简洁的语言,因为 C 语言设计更加凑近底层,因而不须要泛滥 Java 、C# 等高级语言才有的个性,程序的编写要求不是很严格。C 语言具备结构化管制语句,C 语言是一门结构化的语言,它提供的管制语句具备结构化特色,如 for 循环、if⋯ else 判断语句和 switch 语句等。C 语言具备丰盛的数据类型,不仅蕴含有传统的字符型、整型、浮点型、数组类型等数据类型,还具备其余编程语言所不具备的数据类型,比方指针。C 语言可能间接对内存地址进行读写,因而能够实现汇编语言的次要性能,并可间接操作硬件。C 语言速度快,生成的指标代码执行效率高。上面让咱们通过一个简略的示例来阐明一下 C 语言 ...

November 12, 2021 · 8 min · jiezi

关于c#:如何完成复杂查询的动态构建

有的时候,你须要动静构建一个比较复杂的查问条件,传入数据库中进行查问。而条件自身可能来自前端申请或者配置文件。那么这个时候,表达式树,就能够帮忙到你。本文咱们将通过几个简短的示例来理解如何实现这些操作。 微软MVP实验室研究员 你也可能接到过这些需要: (图片从模型进行查问)(基于配置查问) 明天咱们看看表达式树如何实现这些需要。 Where当中能够传入固定的条件以下是一个简略的单元测试用例。接下来,咱们将这个测试用例改的面目全非。 [Test]public void Normal(){ var re = Enumerable.Range(0, 10).AsQueryable() // 0-9 .Where(x => x >= 1 && x < 5).ToList(); // 1 2 3 4 var expectation = Enumerable.Range(1, 4); // 1 2 3 4 re.Should().BeEquivalentTo(expectation);}Queryable中的Where就是一种表达式树因为是 Queryable 的关系,所以Where当中的其实是一个表达式,那么咱们把它独自定义进去,顺便水一下文章的长度。 [Test]public void Expression00(){ Expression<Func<int, bool>> filter = x => x >= 1 && x < 5; var re = Enumerable.Range(0, 10).AsQueryable() .Where(filter).ToList(); var expectation = Enumerable.Range(1, 4); re.Should().BeEquivalentTo(expectation);}表达式能够通过Lambda隐式转换Expression 右侧是一个 Lambda ,所以能够捕捉上下文中的变量。这样你便能够把 minValue 和 maxValue 独自定义进去。于是乎你能够从其余中央来获取 minValue 和 maxValue 来扭转 filter。 ...

November 10, 2021 · 5 min · jiezi

关于c++:COMP26020-C软件管理

COMP26020 Part 1– Assignment 2:Library Management Software in C++The goal of this assignment is to implement a set of C++ classes that aim to be used in a library managementsoftware. The library holds documents of different types (novels, comics and magazines) with various attributes(title, author, etc.) and users can borrow and return documents. You are given a header file library.h with thedifferent classes definitions including inheritance relationships as well as the prototypes for all classes’ methods. Afirst task is to implement each of these methods in a single C++ source file, library.cpp. To test yourimplementation, you are given a test suite in the form of a program that instantiates the classes in question, andperforms various sanity checks. A second task is to write a Makefile to automate the build of that test program.You can download an archive with the library header file as well as the test suite sources here:https://olivierpierre.github....Class HierarchyThe library.h header defines 5 classes which are briefly presented below. Note that more detailed informationabout the methods to implement is present in the header’s source code in the form of comments.• Document is an abstract class defining attributes and methods common to all the documents that can beheld in the library. Attributes include the document’s title, year of release, and quantity held in the library.It defines various methods for printing the document’s information on the standard output, getting itsconcrete type (novel/comic/magazine), and various getters/setters including methods forborrowing/returning the document from/to the library.• Novel, Comic and Magazine represent the concrete types ofdocuments. Each inheritates from Document as depicted on thefigure on the right. They differ slightly in attributes: a novel and acomic have an author, comics and magazines have an issue number,and a magazines do not have an author. Each class also defines therelevant getters/setters.• The last class, Library, represents the library i.e. a collection of documents, held in a vector attribute.The library class defines various methods for actions such as adding, removing, searching, borrowing,returning documents, printing the library content on the standard output or dumping it in a CSV file.Test SuiteTo test your implementation you are given a basic test suite in the form of a C++ file, test-suite.cpp. It’s a C++program (i.e. it contains a main function) that includes library.h. It instantiates/manipulates objects from all theaforementioned classes, and performs many sanity checks. This program uses the Catch1test framework andrequires two additional source files to be compiled: catch.cpp and catch.h. You can compile and run the testprogram as follows:$ g++ test-suite.cpp library.cpp catch.cpp -o test-suite$ ./test-suiteObviously the compilation command will fail as long as you don’t implement all of the methods invoked in the testsuite. Once it compiles and run, the program will list the tests executed and which test succeeded/failed. It is agood idea to investigate the suite source file test-suite.cpp in order to understand what is checked for eachtest. The suite is divided into tests cases enclosed into TEST_CASE() { ... } statements. A test case will failwhen one of the REQUIRE( <condition> ) or CHECK( <condition> ) statements it contains fails, i.e. whencondition evaluates to false. To complete the assignment you do not need to understand the content of catch.hand catch.cpp, these files implement the Catch engine and are rather complicated.1 https://github.com/catchorg/C...Document class hierarchyTo avoid typing the long build command, automate dependency management, and speed up the test suite build,you should write a Makefile as presented in the course.The test suite is not fully comprehensive and, although passing all the tests it contains means that a good chunk ofthe assignment has been accomplished and that the implementation seems functional, it does not mean thateverything is perfect. When marking, an extended test suite will be used, and other good C/C++ programmingpractices mentioned in the course will be taken into account such as proper memory management, code style, etc.Documents/Library Printing and CSV Output FormatsThe print() method, when called on a novel, should print on the standard the novel’s attributed following thisformat:Novel, title: Harry Potter, author: J. K. Rowling, year: 1997, quantity: 1For a comic:Comic, title: Watchmen, author: Alan Moore, issue: 1, year: 1986, quantity: 10And for a magazine:Magazine, title: The New Yorker, issue: 1, year: 1925, quantity: 20The print() method called on a library containing these 3 documents should produce:Harry Potter, author: J. K. Rowling, year: 1997, quantity: 1Comic, title: Watchmen, author: Alan Moore, issue: 1, year: 1986, quantity: 10Magazine, title: The New Yorker, issue: 1, year: 1925, quantity: 20Finally, the dumpCSV() method called on the same library should use low level file I/O functions (open, etc.) toproduce a file with the following format:novel,Harry Potter,J. K. Rowling,,1997,1comic,Watchmen,Alan Moore,1,1986,10magazine,The New Yorker,,1,1925,20Because of the cohort’s size, the exercise will be partially marked using automated tools and for that reason it isvery important to respect these formats to the letter to avoid loosing points.Deliverables, Submission & DeadlineThere are two deliverables: the completed library.cpp file, as well as the Makefile automating the build of thetest suite. The submission is made through the CS Department’s Gitlab. You should have a fork of the repositorynamed “26020-lab2-library_<your username>”. Make sure you push to that precise repository and not anotherone, failure to do so may result in the loss of some/all points. Submit your deliverables by pushing thecorresponding files on the master branch and creating a tag named lab2-submission to indicate that thesubmission is ready to be marked.The deadline for this assignment is 11/11/2021 5pm London time.Marking SchemeThe exercise will be marked out of 10, using the following marking scheme:• The program is functional, and passes the basic test suite /5• The program passes extended tests /2• The Makefile is functional and properly written /1• The program follows the good C programming practices covered in the course regarding dynamic; memoryallocation, parameter management, code style /2 ...

November 9, 2021 · 5 min · jiezi

关于c++:c学习

include门路查找     头文件是一种文本文件,应用文本编辑器将代码编写好之后,以扩展名.h保留。头文件中个别放一些重复使用的代码,例如函数申明、变量申明、常数定义、宏的定义等等。当应用#include语句将头文件援用时,相当于将头文件中所有内容,复制到#include处。#include有两种写法模式,别离是:     #include <> : 间接到零碎指定的某些目录中去找某些头文件。     #include "" : 先到源文件所在文件夹去找,而后再到零碎指定的某些目录中去找某些头文件。 编译单元(模块)     点击编译按钮生成可执行文件时,编译器做了两步工作: 将每个.cpp(.c)和相应的.h文件编译成obj文件;将工程中所有的obj文件进行LINK,生成最终.exe文件。     那么,谬误可能在两个中央产生: 编译时的谬误,这个次要是语法错误;链接时的谬误,次要是反复定义变量等。     编译单元指在编译阶段生成的每个obj文件。     一个obj文件就是一个编译单元。     一个.cpp(.c)和它相应的.h文件独特组成了一个编译单元。     一个工程由很多编译单元组成,每个obj文件里蕴含了变量存储的绝对地址等。 申明与定义     函数或变量在申明时,并没有给它理论的物理内存空间,它有时候可保障你的程序编译通过;     函数或变量在定义时,它就在内存中有了理论的物理空间。      如果你在编译单元中援用的内部变量没有在整个工程中任何一个中央定义的话,那么即便它在编译时能够通过,在连贯时也会报错,因为程序在内存中找不到这个变量。      函数或变量能够申明屡次,但定义只能有一次。 动态全局变量(static)     留神应用static润饰变量,就不能应用extern来润饰,即static和extern不可同时呈现。     static润饰的全局变量的申明与定义同时进行,即当你在头文件中应用static申明了全局变量,同时它也被定义了。     static润饰的全局变量的作用域只能是自身的编译单元。在其余编译单元应用它时,只是简略的把其值复制给了其余编译单元,其余编译单元会另外开个内存保留它,在其余编译单元对它的批改并不影响自身在定义时的值。即在其余编译单元A应用它时,它所在的物理地址,和其余编译单元B应用它时,它所在的物理地址不一样,A和B对它所做的批改都不能传递给对方。     多个中央援用动态全局变量所在的头文件,不会呈现重定义谬误,因为在每个编译单元都对它开拓了额定的空间进行存储。 全局常量(const)     const独自应用时,其个性与static一样(每个编译单元中地址都不一样,不过因为是常量,也不能批改,所以就没有多大关系)。     const与extern一起应用时,其个性与extern一样。 参考链接:https://blog.csdn.net/candyli...

November 9, 2021 · 1 min · jiezi

关于c:自动化集成测试之解放程序员的利器真香

✨程序猿思维:能用工具解决的事绝不能入手!!!1.什么是CI/CD?CI (Continuous Integration):继续集成继续集成是指程序开发者将代码块推送到Git近程仓库时,每次Push或Merge都将触发并运行一系列脚本来构建、测试和验证提交的代码,验证通过后合并到仓库分支中。 CD (Continuous Deployment) :继续部署继续部署是继续集成的下一步动作,即通过CI形式胜利将代码合入指定仓库后,再将应用程序部署到生产环境的一系列动作。 CI/CD形式能够在开发阶段更及时的发现问题,升高代码审核人员的工作量,并进步代码品质,从而确保部署到生产环境的所有代码都合乎为应用程序建设的代码规范。CI/CD最大的劣势就在于主动执行脚本,从开发到部署简直不须要人为干涉。 CI/CD在国外大型开源我的项目中使用广泛,多人开发、单人开发、非开源我的项目一样能够很好的使用CI/CD能力。此外,CI/CD还能够灵便搭建,播种意想不到的便利性,帮忙程序员从反复而繁冗的工作中解放出来,更何况程序猿总喜爱说 2. CI/CD原理与流程CI/CD 继续集成的工具有Circle CI、Travis CI、Jenkins、Gitee Go、GitLab CI/CD等。当CI/CD与代码托管工具齐全集成时会带来微小的便利性,如GitLab CI/CD、Gitee Go,能够将代码的提交、审查与主动合入联合在一起,借助工具来把控开发代码的品质,并且排除人为干涉的误差性。 CI/CD的原理: 各大CI/CD工具的工作原理根本大同小异,以GitLab CI/CD为例。 GitLab CI/CD是怎么工作起来的呢?总结起来就两点: 将.gitlab-ci.yml文件增加到近程仓库的根目录;为GitLab我的项目仓库配置一个Runner。 说人话,.gitlab-ci.yml能够了解为流水线文件,应用 YAML语法形容,.gitlab-ci.yml文件形容了你要做什么事件,在此文件中指定构建、测试和部署的脚本。把.gitlab-ci.yml放到远端分支的根目录,你每次push或Merge代码到Git近程仓库时,Runner都会主动触发CI pipeline,去执行.gitlab-ci.yml流水线文件中形容的事。 Runner很好了解,就是一个用来跑仓库代码的构建、测试和部署的机器,能够是本地PC,也能够是一台服务器。Runner怎么配置、装置、注册,依据GitLab的阐明循序渐进就能够啦。 CI/CD的流程: 一旦你将提交推送到近程仓库的分支上,那么你为该我的项目设置的CI/CD管道将会被触发。GitLab CI/CD 是这样做: 运行自动化脚本(串行或并行) 代码Review并取得批准 构建并测试你的利用就像在你本机中看到的那样,应用Review Apps预览每个合并申请的更改 代码Review并取得批准合并feature分支到默认分支,同时主动将此次更改部署到生产环境如果呈现问题,能够轻松回滚通过GitLab UI所有的步骤都是可视化的 3.CI/CD集成计划抉择什么CI零碎? 这取决于你的需要以及打算应用它的形式。 CircleCI倡议用于小型我的项目,其次要指标是尽快开始集成。 当你从事开源我的项目时,倡议应用Travis CI,这些我的项目应在不同环境中进行测试。 Jenkins被举荐用于大型项目,在这些我的项目中,你须要进行大量自定义,这些自定义能够通过应用各种插件来实现, 你能够在这里更改简直所有内容,但此过程可能须要一段时间。 Gitee Go是Gitee外部集成的CI/CD工具,目前反对 Maven、Gradle、npm、Python、Ant、PHP、Golang等工具和语言的继续构建与集成能力。Gitee Go是属于Gitee的增值服务,须要你破费一笔小的费用。 GitLab CI/CD是GitLab外部集成的CI/CD工具,收费且高度集成是其最大特色。 这里列出了局部集成计划: VS Code + GitLab + GitLab CI/CD + ECS: VS Code + Gitee + Jenkins + ECS: ...

November 9, 2021 · 1 min · jiezi

关于c++:Linux多线程服务器编程笔记1

C++中实现线程平安的对象创立、回调与析构写出线程平安的类并不难,应用同步原语爱护外部状态即可STL大多类都不是线程平安的,须要在内部加锁保障多个线程同时拜访平安的对象创立惟一的要求就是不要在结构期间泄露this指针,即 - 不要在构造函数中注册任何回调- 不要把this指针传给跨线程的对象- 即便在最初一行也不能够,因为这个类可能是基类,它的构造函数最初一行不等于结构实现起因:在执行构造函数期间对象没有实现初始化,如果this指针被写了泄露给了其余对象,那么别的线程可能会拜访这个半成品 平安的对象销毁对象析构函数的竞态条件1.析构某个对象时,如何得悉是否有他人在用它?2.析构某个对象时,它是否可能正在被另一个线程析构?3.调用某个对象的成员函数时,如何保障它仍旧活着?析构函数会不会碰巧执行到一半?对象析构函数的设计难点1.mutex不是方法,因为锁只是用来爱护对象外部数据的,不能来爱护对象自身,不能解决任何问题 2.面向对象中宽泛应用的三种对象关系,都依赖于对象晓得“其余对象是否还活着”的能力 a. compositionb. aggregationc. association其中,composition在多线程中不会有什么麻烦,因为对象x的生命周期由其owner惟一管制,但后两者,对象的分割是借由指针或援用实现的,因而可能会呈现下面提到的竞态条件。 解决办法 :shared_ptr / weak_ptr即在对象间中引入一层中间层,不再应用裸指针,而是智能指针,作为一个辅助的管理者(援用计数)。 shared_ptr管制对象的生命周期,是强援用,只有有一个指向x对象的shared_ptr存在,x就不会析构,当援用计数降为0时或reset()时,x保障会被销毁。weak_ptr不管制对象生命周期,但晓得对象是否或者,如果对象没死,那么能够晋升为无效的shared_ptr,从而援用对象,并保障在这个期间对象不析构,如果对象死了,那么会返回空的shared_ptr。晋升行为是线程平安的。shared_ptr和weak_ptr的计数是原子操作,性能不俗然而 ❗ shared_ptr和weak_ptr自身的线程安全级别与std::string和STL的容器一样,见上面的探讨对于shared_ptr的探讨shared_ptr并不线程平安:能够多个线程同时读,不能多个线程同时写(析构算写)shared_ptr的线程平安和它指向对象的线程平安是两回事访问共享的shared_ptr,须要加上互斥锁 void read(){ shared_ptr<Foo> localPtr; { MutexLockGuard lock(mutex); localPtr = globalPtr; // read globalPtr } // use localPtr since here,读写localPtr无需加锁,因为是栈上对象,只有以后线程可见 do_it(localPtr); // 这里函数的参数应是reference to const,防止复制}weak_ptr和shared_ptr用错,可能会导致一些对象永远不被析构,通常做法是owner领有指向child的shared_ptr,child持有owner的weak_ptr拷贝开销:因为拷贝会创立一份正本,须要批改援用计数,开销较大,但须要拷贝的中央不多,通常shared_ptr作为参数时都是const reference。RAII 资源获取即初始化C++区别于其余编程语言的最重要的个性每一个明确的资源配置动作(如new)都应该在繁多语句中执行,并在该寄居中立即将配置取得的资源交给handle对象(如shared_ptr),程序中个别不呈现delete线程平安的对象池实现一个StcokFactory, 依据key返回Stock对象 版本1: 利用weak_ptr和shared_ptr治理 class StockFactory : boost::noncopyable{ public: boost::shared_ptr<Stock> get(const string& key) { boost::shared_ptr<Stock> pStock; muduo::MutexLockGuard lock(mutex_); boost::weak_ptr<Stock>& wkStock = stocks_[key]; // 如果这里是shared_ptr,则对象永远不会被析构 pStock = wkStock.lock(); if (!pStock) { pStock.reset(new Stock(key)); wkStock = pStock; // wkStock is a reference } return pStock; } private: mutable muduo::MutexLock mutex_; std::map<string, boost::weak_ptr<Stock> > stocks_;};问题: 存在轻微的内存透露,map中的key:weak_ptr会始终存在,在key无限时没什么问题,在key范畴很大时会造成内存透露 ...

November 8, 2021 · 2 min · jiezi

关于c:C是如何调用C接口的

✨有的时候,当我想在c代码中调用c++接口,而后就编译报错了!!!引出问题C++反对函数重载的, 函数名雷同然而参数不同的重载函数在编译后链接的名字并不相同而能够被辨认, 这种状况下, 咱们引入一个中间层的办法同样能够实现C中调用C++的函数接口。 其实这与C中调用C++非重载根本函数成员的实现没有什么区别, 只是为各个重载函数均实现一套接口而已。 通常的做法//test.cpp#include <iostream>#include "hello.h"int getNum() { std::cout << "get number" << std::endl; return 123456;}这时,咱们须要对该c++函数,进行申明,通知编译器,须要按c的命名规定来: //test.h#ifdef __cplusplusextern "C" {#endifint getNum();#ifdef __cplusplus}#endif#endif这时,咱们就能够在C源码中调用getNum接口了。 重载函数如果你想在 C 里调用重载函数,则必须提供不同名字的包装,这样能力被 C 代码调用。首先是咱们的C++接口, 如下所示: // add.cpp//#include <iostream>int add(const int a, const int b){ return (a + b);}double add(const double a, const double b){ //std::cout <<a <<", " <<b <<std::endl; return (a + b);}咱们为此实现一个中间层libadd.cpp, 通过C++编译器用extern "C"将其编译成C编译器可辨认的接口: // libadd.cppint add(const int a, const int b);double add(const double a, const double b);#ifdef __cplusplusextern "C"{#endifint call_cpp_add_int(const int a, const int b){ return add(a, b);}double call_cpp_add_double(const double a, const double b){ return add(a, b);}#ifdef __cplusplus}#endif最初是咱们的C源程序, 调用咱们的中间层: ...

November 8, 2021 · 1 min · jiezi

关于c++:C是如何调用C接口的

✨有的时候,当我想在c++代码中调用c接口,而后就编译报错了!!!引出问题你可能会奇怪,C++不是兼容C吗?间接调用不就能够了?为什么会有这样的状况呢?设想一下,有些接口是用C实现的,并提供了库,那么C++中该如何应用呢? 咱们先不做任何区别对待,看看一般状况下会产生什么意想不到的事件。首先提供一个C接口: //test.c#include"test.h"void testCfun(){ printf("I am c fun\n"); return;}咱们在这里编译成C指标文件: gcc -c test.c另外提供一个头文件test.h: #include<stdio.h>void testCfun();咱们的C++代码调用如下: //main.cpp#include"test.h"#include<iostream>using namespace std;int main(void){ /*调用C接口*/ cout<<"start to call c function"<<endl; testCfun(); cout<<"end to call c function"<<endl; return 0;}编译: $ g++ -o main main.cpp test.o/tmp/ccmwVJqM.o: In function `main':main.cpp:(.text+0x21): undefined reference to `testCfun()'collect2: error: ld returned 1 exit status很可怜,最初的链接报错了,说找不到testCfun,然而咱们的确定义了这个函数。为什么会找不到呢? 揭开迷雾咱们都晓得,C++中函数反对重载,而C并不反对。C++为了反对函数重载,它在“生成”函数符号信息时,不能仅仅通过函数名,因为重载函数的函数名都是一样的,所以它还要依据入参,命名空间等信息来确定惟一的函数签名。 或者说C++生成函数签名的形式与C不统一,所以即使是函数名一样,对于C和C++来说,它们最终的函数签名还是不一样。当然这里又是另外一回事了,咱们不细说。咱们看看两个文件里的函数符号有什么区别: $ nm test.o|grep testCfun0000000000000000 T testCfun$ nm main.o|grep testCfun U _Z8testCfunv所以它们两个能链接在一起才真是奇怪了呢!名字都不同,还怎么链接? 解决办法那么如何解决呢?很显然,咱们必须通知链接器,这是一个C接口,而不是C++接口,所以须要退出 extern C,咱们批改test.h #include<stdio.h>extern "C"{void testCfun();}这里用extern "C"将testCfun接口包裹起来,通知编译器,这里的是C接口哈,你要按C代码的形式解决。再次编译: ...

November 8, 2021 · 1 min · jiezi

关于c:如何编译多个c文件

编译多文件咱们有以下三个文件file1.c #include "stdio.h"#include "file2.h"int main(void){ printf("%s:%s:%d\n", __FILE__, __FUNCTION__, __LINE__); foo(); return 0;}file2.h void foo(void);file2.c #include <stdio.h>#include "file2.h"void foo(void) { printf("%s:%s:%d \n", __FILE__, __FUNCTION__, __LINE__); return;}执行 gcc file1.c file2.c -o server 生成可执行程序server, 执行./server 咱们能够失去以下输入 file1.c:main:5file2.c:foo:5这样就能够编译多文件的程序了。linux下还须要make程序来自动化编译等操作。增加Makefile文件 server : file1.o file2.o $(CC) -o $@ $^.PHONY: cleanclean: rm *.o server执行make, 就能编译程序了。执行make clean 就会删除make产生的临时文件。Makefile有以下模式 target: require action其中target时产物,require时生成target的依赖。 action是动作,能够是编译程序的动作,也可能是输入些信息。下面的例子中target是server, 依赖是file1.o, file2.o。 make会主动.o 文件执行 cc -c .c -o *.o 命令。下面例子中执行cc -c file1.c -o file1.o 和 cc -c file2 -o file2.o。$(CC) 是内置变量,linux下会解释成cc。$@是target, $^是require。这样就能生成可执行程序server了。上面加了个clean, 因为不是真正的文件,须要用.PHONY: clean 阐明是伪文件。 ...

November 4, 2021 · 1 min · jiezi

关于c:编程艺术剖析-darknet-parsenetworkcfg-接口

 欢送关注我的公众号 [极智视界],回复001获取Google编程标准 O_o >_<  o_O O_o ~_~ o_O 本文剖析和介绍一下 darknet parse_network_cfg 接口,这个接口比拟硬核,次要做模型构造的加载与算子的实现。 1、darknet 数据加载例程   之前的文章《【编程艺术】分析 darknet read_data_cfg 接口》曾经介绍了一下 darknet 指标检测的数据加载流程,并介绍了.data 和 .names 的加载实现。   接下来这里 parse_network_cfg 接口次要做 .cfg 模型构造的加载,外面波及的货色略微多一些。 2、parse_network_cfg 接口   来看一下 parse_network_cfg 的实现: network parse_network_cfg(char *filename){ return parse_network_cfg_custom(filename, 0, 0);}   能够看到外面调用了 parse_network_cfg_custom 函数,这是次要的性能实现函数,也是这里重点要分析的。这个函数的实现有 451 行,这里就不间接贴了,筛选一些比拟要害的中央拿出来说一下。 首先是读 cfg: list *sections = read_cfg(filename);   读 cfg 采纳 read_cfg 接口,先须要说一下 darknet 里用链表存网络结构的数据结构:整个网络采纳链表进行存储,链表的值域为 section 块,section 块寄存 [net]、[convolution]、[yolo]... 这些构造,来看一下 section 的定义就很清晰了,其中 type 就是记录块的类别,即 [net] 或 [convolution] 或 [yolo] 等字符串。 ...

November 3, 2021 · 3 min · jiezi

关于c#:手把手教你学Dapr-4-服务调用

介绍通过应用服务调用,您的应用程序能够应用规范的gRPC或HTTP协定与其余应用程序牢靠、平安地通信。 为什么不间接用HttpClientFactory呢先问几个问题: 如何发现和调用不同服务的办法如何平安地调用其余服务,并对办法利用访问控制如何解决重试和瞬态谬误如何应用分布式跟踪指标来查看调用图来诊断生产中的问题此时你会发现这些事件HttpClientFactory没有帮你实现,而在微服务中这些又是必不可少的能力,接下来看看服务调用都做了什么 服务调用如何工作的先看一下两个服务之间的调用程序 服务A 向服务B发动一个HTTP/gRPC的调用。调用转到了本地的Dapr sidecarDapr应用名称解析组件发现服务B的地位Dapr 将音讯转发至服务 B的 Dapr sidecar 注: Dapr sidecar之间的所有调用都通过gRPC来进步性能。 仅服务与 Dapr sidecar之间的调用能够是 HTTP或gRPC 服务B 的 Dapr sidecar将申请转发至服务B 上的特定端点 (或办法) 。 服务B 随后运行其业务逻辑代码服务B 发送响应给服务A。 响应将转至服务B 的Dapr sidecarDapr 转发响应至服务A 的 Dapr sidecar服务 A 接管响应命名空间作用域默认状况下,调用同一个命名空间的其余服务能够间接应用AppID(假如是:nodeapp) localhost:3500/v1.0/invoke/nodeapp/method/neworder服务调用也反对跨命名空间调用,在所有受反对的宿主平台上,Dapr AppID遵循FQDN格局,其中包含指标命名空间。 FQDN:(Fully Qualified Domain Name)全限定域名:同时带有主机名和域名的名称。(通过符号“.”) 例如:主机名是bigserver,域名是mycompany.com,那么FQDN就是bigserver.mycompany.com 注:FQDN是通过符号.来拼接域名的,这也就解释了AppID为什么不能用符号.,这里不记住的话,应该会有不少小伙伴会踩坑 比方.net开发者习惯用 A.B.C 来命名我的项目,但AppID须要把.换成-且所有单词最好也变成小写 (a-b-c),倡议把它变成约定恪守 比方调用命名空间:production,AppID:nodeapp localhost:3500/v1.0/invoke/nodeapp.production/method/neworder这在K8s集群中的跨名称空间调用中特地有用 服务间安全性通过托管平台上的互相(mTLS)身份验证,包含通过Dapr Sentry服务的主动证书转移,能够确保Dapr应用程序之间的所有调用的平安。 下图显示了自托管应用程序的状况。 访问控制应用程序能够管制哪些其余应用程序能够调用它们,以及通过拜访策略受权它们做什么。 这使您可能限度具备个人信息的敏感应用程序不被未经受权的应用程序拜访,并联合服务到服务的平安通信,提供了软多租户部署。 具体的访问控制后续章节会介绍重试在调用失败和瞬态谬误的状况下,服务调用执行主动重试,并在回退时间段内执行。 注:主动重试,默认是开启的,能够关。但如果不关且业务又不反对幂等是很危险的。倡议服务的接口要设计反对幂等,这在微服务里也是一个标配的抉择。 导致重试的谬误有: 网络谬误,包含端点不可用和回绝连贯。 因为在调用/被调用的Dapr sidecars上更新证书而导致的身份验证谬误。 每次呼叫重试的回退距离为1秒,最多为3次。 通过gRPC与指标Sidecar连贯的超时工夫为5秒 可插拔的服务发现Dapr能够在各种托管平台上运行。 为了启用服务发现和服务调用,Dapr应用可插拔的名称解析组件。 例如,K8s名称解析组件应用K8s DNS服务来解析集群中运行的其余应用程序的地位。 自托管机器能够应用mDNS名称解析组件。 Consul名称解析组件能够在任何托管环境中应用,包含K8s或自托管环境 ...

November 3, 2021 · 2 min · jiezi

关于c#:手把手教你学Dapr-3-使用Dapr运行第一个Net程序

留神: 文章中提到的命令行工具即是Windows Terminal/PowerShell/cmd其中的一个,举荐应用Windows Terminal 运行命令行工具的时候倡议以管理员身份,防止踩坑 为了保障操作顺畅,倡议应用PowerShell先执行一下set-ExecutionPolicy RemoteSigned 装置Docker因为Dapr CLI默认会在Docker内启动 redis、zipkin、placement。 当然这些也不是必须要装置的,只是举荐装置能够体验Dapr的残缺能力,不便后续章节的学习。 下载并装置Docker Desktop https://www.docker.com/produc...装置WSL2,应用命令行工具执行命令 wsl --instal如果不能应用wsl间接装置的话能够手动装置,运行PowerShell并执行上面两句命令dism.exe /online /enable-feature /featurename:Microsoft-Windows-Subsystem-Linux /all /norestartdism.exe /online /enable-feature /featurename:VirtualMachinePlatform /all /norestart如果你再次遇到谬误提醒:0x800f080c 性能名称 VirtualMachinePlatform 未知。请保障本人的操作系统版本在Windows 10 build 18917以上重启电脑后下载WSL2内核 https://wslstorestorage.blob....运行命令行工具,设置默认应用WSL2 wsl --set-default-version 2下载Ubuntu 20.04 https://www.microsoft.com/sto...设置Docker应用WSL2 你“可能”须要一个小工具不能说的机密,看文件名猜性能 https://github.com.cnpmjs.org...装置Dapr CLI官网解释:Dapr CLI 是您用于各种 Dapr 相干工作的次要工具。 您能够应用它来运行一个带有Dapr sidecar的应用程序, 以及查看sidecar日志、列出运行中的服务、运行 Dapr 仪表板。 CLI是必须要装置吗?其实也不是,但老手不倡议去体验这些骚操作。后续文章会解说脱离dapr cli工作。运行Windows Terminal或PowerShell,执行命令,这里要急躁期待一下 iwr -useb https://raw.githubusercontent.com/dapr/cli/master/install/install.ps1 | iex如果是cmd执行上面命令: powershell -Command "iwr -useb https://raw.githubusercontent.com/dapr/cli/master/install/install.ps1 | iex"验证装置,从新关上命令行工具执行命令dapr,看到上面的提醒即装置正确 __ ____/ /___ _____ _____ / __ / __ '/ __ \/ ___/ / /_/ / /_/ / /_/ / / \__,_/\__,_/ .___/_/ /_/===============================Distributed Application RuntimeUsage: dapr [command]Available Commands: completion Generates shell completion scripts components List all Dapr components. Supported platforms: Kubernetes configurations List all Dapr configurations. Supported platforms: Kubernetes dashboard Start Dapr dashboard. Supported platforms: Kubernetes and self-hosted help Help about any command init Install Dapr on supported hosting platforms. Supported platforms: Kubernetes and self-hosted invoke Invoke a method on a given Dapr application. Supported platforms: Self-hosted list List all Dapr instances. Supported platforms: Kubernetes and self-hosted logs Get Dapr sidecar logs for an application. Supported platforms: Kubernetes mtls Check if mTLS is enabled. Supported platforms: Kubernetes publish Publish a pub-sub event. Supported platforms: Self-hosted run Run Dapr and (optionally) your application side by side. Supported platforms: Self-hosted status Show the health status of Dapr services. Supported platforms: Kubernetes stop Stop Dapr instances and their associated apps. . Supported platforms: Self-hosted uninstall Uninstall Dapr runtime. Supported platforms: Kubernetes and self-hosted upgrade Upgrades a Dapr control plane installation in a cluster. Supported platforms: KubernetesFlags: -h, --help help for dapr -v, --version version for daprUse "dapr [command] --help" for more information about a command.初始化Dapr应用命令行工具执行命令 ...

November 3, 2021 · 3 min · jiezi

关于c#:手把手教你学Dapr-2-必须知道的概念

Sidecar 边车Dapr API提供Http和gRPC两种通信形式。 运行形式则能够是容器也能够是过程(Windows开发举荐应用Self Hosted,后续会解释)。 这样的益处是与运行环境无关,且独立运行不须要利用蕴含Dapr运行时的代码。只须要通过SDK集成即可,这使得Dapr与利用的逻辑拆散。 Building blocks 构建块官网解释:可通过规范HTTP或gRPC api拜访的模块化最佳实际 艰深一点来说,就是API目前反对的构建块如下,但1.5很快会出一个新的Configuration API(从这个新的API又印证了构建块的实质),由阿里-敖小剑牵头整顿的 Github Issue: https://github.com/dapr/dapr/... 这个提案很长,很波折。认真看会发现中外开发大环境下的一些思维碰撞。微软绝对激进,阿里绝对激进但也更求实。最终长达几个月的强烈探讨下定版。 期间自己也有幸与阿里-敖小剑和阿里-典礼(Layotto的研发同学,Layotto兼容Dapr协定,是蚂蚁在做)开过语音会议一起聊过对于Configuration API的一些设计问题。 服务调用状态治理公布订阅绑定Actor(这个不倡议翻译回中文)可观测性平安 Components 组件官网解释:被用于构建块和应用程序的模块化性能 Dapr 应用模块化设计,将性能作为组件来提供。 每个组件都有接口定义。 所有组件都是可插拔的,因而您能够将组件换为另一个具备雷同接口的组件。 联合构建块来看,组件有接口定义。而构建块则通过接口将组件的性能串联起来 基于对Dapr设计的了解,咱们的MASA Framework也定义出了 BuildingBlocks 和 Contrib,与dapr会有些许不同 起因如下: 由BuildingBlocks定义规范、串业务流程让Contrib变成咱们的最佳实际,并容许开发从新定义BuildingBlocks的具体实现,在保障性能残缺的前提下提供更合乎业务场景的性能又有参考代码聚焦外围代码稳定性,提供单元测试覆盖率保障,共享公众智慧组件与构建块并不是一一对应的,组件能够被不同的构建块复用,比方Actor构建块内的状态治理也是用的状态存储组件 状态存储服务发现中间件公布订阅代理绑定密钥存储Configuration 配置官网解释:变更Dapr Sidecar或全局Dapr零碎服务的行为 配置定义和部署模式为YAML文件 在官网文档的Component sepcs能够看到每个组件提供了多少种实现,每个实现个性反对状况 除此之外不同组件的配置文件格式也是包罗万象 官网文档对于组件配置的解说十分具体,这里举个例子,Redis状态治理的配置文件格式 你须要变更的局部曾经用<>和 # 做了标记 参考自:https://docs.dapr.io/referenc...apiVersion: dapr.io/v1alpha1kind: Componentmetadata: name: <NAME> namespace: <NAMESPACE>spec: type: state.redis version: v1 metadata: - name: redisHost value: <HOST> - name: redisPassword value: <PASSWORD> - name: enableTLS value: <bool> # Optional. Allowed: true, false. - name: failover value: <bool> # Optional. Allowed: true, false. - name: sentinelMasterName value: <string> # Optional - name: maxRetries value: # Optional - name: maxRetryBackoff value: # Optional - name: ttlInSeconds value: <int> # OptionalObservability 可观测性官网解释:通过跟踪、指标、日志和健康状况监督利用 ...

November 1, 2021 · 1 min · jiezi

关于c#:c文件压缩解压

c#文件压缩/解压压缩private void skinButton1_Click(object sender, EventArgs e) { FilesUploadFor.ZipDirectory(foldertozip.Text,zipedfilename.Text); filesUploadFor.DisplaylistboxMsg("压缩实现"); }ZipDirectory压缩用的是库函数 /// <summary> /// 压缩文件夹 /// </summary> /// <param name="folderToZip">须要压缩的文件夹</param> /// <param name="zipedFileName">压缩后的Zip残缺文件名</param> public static void ZipDirectory(string folderToZip, string zipedFileName) { ZipDirectory(folderToZip, zipedFileName, string.Empty, true, string.Empty, string.Empty, true); } /// <summary> /// 压缩文件夹 /// </summary> /// <param name="folderToZip">须要压缩的文件夹</param> /// <param name="zipedFileName">压缩后的Zip残缺文件名(如D:\test.zip)</param> /// <param name="isRecurse">如果文件夹下有子文件夹,是否递归压缩</param> /// <param name="password">解压时须要提供的明码</param> /// <param name="fileRegexFilter">文件过滤正则表达式</param> /// <param name="directoryRegexFilter">文件夹过滤正则表达式</param> /// <param name="isCreateEmptyDirectories">是否压缩文件中的空文件夹</param> public static void ZipDirectory(string folderToZip, string zipedFileName, string password, bool isRecurse, string fileRegexFilter, string directoryRegexFilter, bool isCreateEmptyDirectories) { FastZip fastZip = new FastZip(); fastZip.CreateEmptyDirectories = isCreateEmptyDirectories; fastZip.Password = password; fastZip.CreateZip(zipedFileName, folderToZip, isRecurse, fileRegexFilter, directoryRegexFilter); }解压缩 private void skinButton2_Click(object sender, EventArgs e) { filesUploadFor.UnZip(zipedfilename.Text,""); filesUploadFor.DisplaylistboxMsg("解压缩实现"); }UnZip解压用的是库函数 ...

November 1, 2021 · 2 min · jiezi

关于c++:编程艺术谈谈和分享-Google-编程规范

 欢送关注我的公众号 [极智视界],回复001获取Google编程标准 O_o >_<  o_O O_o ~_~ o_O 本文介绍和分享一下 Google 编程标准。   刚接触编程的同学往往更加偏向于代码性能的实现,而疏忽代码编写标准,这会导致你写的代码极难保护,造成你的代码只有你能看懂的困境。特地是波及较大型我的项目,须要多人协同开发的场景,更是对代码标准的约定与对立要求严苛,这很好了解,代码标准便于我的项目的迭代、保护与对接。   对于开源我的项目也是一样,每个较大的开源我的项目都有本人的格调指南,以便于开源我的项目的推广,这个格调指南是对于如何为该我的项目编写代码的一系列约定,当所有代码均保持一致的格调, 在了解大型代码库时会变得更为轻松。格调的含意涵盖范围广, 从变量应用驼峰格局 (camelCase)到决不应用全局变量再到决不应用异样,这些都是代码编程的标准。   Google 常常会公布一些开源我的项目,意味着会承受来自其余代码贡献者的代码,然而如果代码贡献者的编程格调与 Google 的不统一,会给代码阅读者和其余代码提交者造成不小的困扰。Google 因而公布了《Google 编程标准》这份指南,使所有提交代码的人都能获知 Google 的编程格调。规定的作用就是防止凌乱,但规定自身肯定须要具备权威性、有说服力并且是感性的,正好 Google 的这份编程标准具备这些个性,目前这份编程标准成为了越来越多开发者代码编程的统一标准,Google 目前曾经公布了五份中文版的分格指南:   (1) Google C++ 格调指南;   (2) Google Objective-C 格调指南;   (3) Google Python 格调指南; (4) Google Shell 格调指南;   (5) Google Javascript 格调指南; 当然对于以上的这些在我的公众号里回复 001 你都能拿到,中文版我的项目采纳 reStructuredText 纯文本标记语法,并应用 Sphinx 生成 HTML / CHM/ PDF 等文档格局。 ...

November 1, 2021 · 1 min · jiezi

关于c++:xmake-v259-发布改进-C20-模块并支持-Nim-Keil-MDK-和-Unity-Build

xmake 是一个基于 Lua 的轻量级跨平台构建工具,应用 xmake.lua 保护我的项目构建,相比 makefile/CMakeLists.txt,配置语法更加简洁直观,对老手十分敌对,短时间内就能疾速入门,可能让用户把更多的精力集中在理论的我的项目开发上。 这个版本,咱们减少了大量重量级的新个性,例如:Nim 语言我的项目的构建反对,Keil MDK,Circle 和 Wasi 工具链反对。 另外,咱们对 C++20 Modules 进行了大改良,不仅反对最新 gcc-11, clang 和 msvc 编译器,而且还得模块间依赖做了主动剖析,实现最大水平的并行化编译反对。 最初,还有一个比拟有用的个性就是 Unity Build 反对,通过它咱们能够对 C++ 代码的编译速度做到很大水平的晋升。 我的项目源码官网文档入门课程新个性介绍Nimlang 我的项目构建最近,咱们新增了对 Nimlang 我的项目的构建反对,相干 issues 见:#1756 创立空工程咱们能够应用 xmake create 命令创立空工程。 xmake create -l nim -t console testxmake create -l nim -t static testxmake create -l nim -t shared test控制台程序add_rules("mode.debug", "mode.release")target("test") set_kind("binary") add_files("src/main.nim")$ xmake -v[ 33%]: linking.release test/usr/local/bin/nim c --opt:speed --nimcache:build/.gens/test/macosx/x86_64/release/nimcache -o:build/macosx/x86_64/release/test src/main.nim[100%]: build ok!动态库程序add_rules("mode.debug", "mode.release")target("foo") set_kind("static") add_files("src/foo.nim")target("test") set_kind("binary") add_deps("foo") add_files("src/main.nim")$ xmake -v[ 33%]: linking.release libfoo.a/usr/local/bin/nim c --opt:speed --nimcache:build/.gens/foo/macosx/x86_64/release/nimcache --app:staticlib --noMain --passC:-DNimMain=NimMain_B6D5BD02 --passC:-DNimMainInner=NimMainInner_B6D5BD02 --passC:-DNimMainModule=NimMainModule_B6D5BD02 --passC:-DPreMain=PreMain_B6D5BD02 --passC:-DPreMainInner=PreMainInner_B6D5BD02 -o:build/macosx/x86_64/release/libfoo.a src/foo.nim[ 66%]: linking.release test/usr/local/bin/nim c --opt:speed --nimcache:build/.gens/test/macosx/x86_64/release/nimcache --passL:-Lbuild/macosx/x86_64/release --passL:-lfoo -o:build/macosx/x86_64/release/test src/main.nim[100%]: build ok!动静库程序add_rules("mode.debug", "mode.release")target("foo") set_kind("shared") add_files("src/foo.nim")target("test") set_kind("binary") add_deps("foo") add_files("src/main.nim")$ xmake -rv[ 33%]: linking.release libfoo.dylib/usr/local/bin/nim c --opt:speed --nimcache:build/.gens/foo/macosx/x86_64/release/nimcache --app:lib --noMain -o:build/macosx/x86_64/release/libfoo.dylib src/foo.nim[ 66%]: linking.release test/usr/local/bin/nim c --opt:speed --nimcache:build/.gens/test/macosx/x86_64/release/nimcache --passL:-Lbuild/macosx/x86_64/release --passL:-lfoo -o:build/macosx/x86_64/release/test src/main.nim[100%]: build ok!C 代码混合编译add_rules("mode.debug", "mode.release")target("foo") set_kind("static") add_files("src/*.c")target("test") set_kind("binary") add_deps("foo") add_files("src/main.nim")Nimble 依赖包集成残缺例子见:Nimble Package Example ...

October 31, 2021 · 5 min · jiezi

关于c++:More-Effective-C技术篇要求或禁止对象产生于heap之中

要求对象产生于heap中,意思是须要阻止clients不得应用new以外的办法产生对象。比拟好的办法就是将destructor定义为private,因为constructor的类型太多,所以依然将constructor定义为public。而后定义一个pseudo destructor来调用真正的destructor。示例如下: class HeapBasedObject {public: HeapBasedObject() {} void destroy() const { delete this; } // pseudo destructorprivate: ~HeapBasedObject() {}};int main(){ //HeapBasedObject h; HeapBasedObject *ph = new HeapBasedObject; //delete ph; ph->destroy();}禁止对象产生于heap中,则是要让clients不能应用new办法来产生对象。办法就是将operator new和operator delete定义为private。示例如下: #include <stdlib.h>class NoHeapBasedObject {public: NoHeapBasedObject() {} ~NoHeapBasedObject() {}private: static void *operator new(size_t size) {} static void operator delete(void *ptr) {}};int main(){ NoHeapBasedObject nh; static NoHeapBasedObject snh; //NoHeapBasedObject *pnh = new NoHeapBasedObject;}下例是实现的一个判断某个对象是否位于heap内的基类HeapTracked。 #include <stdlib.h>#include <list>#include <iostream>class HeapTracked {public: class MissingAddress{}; //地址异样 virtual ~HeapTracked() = 0; static void *operator new(size_t size); static void operator delete(void *ptr); bool isOnHeap() const;private: typedef const void* RawAddress; static std::list<RawAddress> addresses;};std::list<HeapTracked::RawAddress> HeapTracked::addresses;HeapTracked::~HeapTracked() {}void* HeapTracked::operator new(size_t size) { void* memPtr = ::operator new(size); // 获得内存。 addresses.push_front(memPtr); // 将其地址置于list头部。 return memPtr;}void HeapTracked::operator delete(void *ptr) { auto it = std::find(addresses.begin(), addresses.end(), ptr); if (it != addresses.end()) { addresses.erase(it); ::operator delete(ptr); } else { throw MissingAddress(); }}bool HeapTracked::isOnHeap() const { auto rawAddress = dynamic_cast<const void*>(this); auto it = std::find(addresses.begin(), addresses.end(), rawAddress); return it != addresses.end();}class Object: public HeapTracked {public: Object() {} ~Object() {}};int main(){ Object o1; Object* o2 = new Object; std::cout << "o1 isOnHeap = " << o1.isOnHeap() << std::endl; std::cout << "o2 isOnHeap = " << o2->isOnHeap() << std::endl;}

October 31, 2021 · 1 min · jiezi

关于c:15213-动态内存分配

15-213 / 14-513 / 15-513, Fall 2021Malloc Lab: Writing a Dynamic Storage AllocatorAssigned: October 12, 2021This lab requires submitting two versions of your code: one as an initial checkpoint, and the second asyour final version. The due dates of each part are indicated in the following table:Version Due Date Max. Grace Days Last Hand-in Date Weight in Final GradeCheckpoint Oct. 26 2 Oct. 28 4%Final Nov. 2 2 Nov. 4 7%Don’t forget that due dates are at 11:59pm Eastern Time (presently UTC-4). See section 7 for details on howeach section is scored.1 IntroductionIn this lab you will write a dynamic memory allocator which will consist of the malloc, free, realloc, andcalloc functions. Your goal is to implement an allocator that is correct, efficient, and fast.We strongly encourage you to start early. The total time you spend designing and debugging can easilyeclipse the time you spend coding.Bugs can be especially pernicious and difficult to track down in an allocator, and you will probably spenda significant amount of time debugging your code. Buggy code will not get any credit.This lab has been heavily revised from previous versions. Do not rely on advice or information you mayfind on the Web or from people who have done this lab before. It will most likely be misleading or outrightwrong.1 Be sure to read all of the documentation carefully and especially study the baseline implementationwe have provided.1Not to mention the fact that it would be an academic integrity violation!1Contents1 Introduction 12 Logistics 33 Required Functions 44 Support Routines 65 Programming Rules 76 Driver Programs 96.1 Trace files . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 96.2 Command-line arguments . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 107 Scoring 117.1 Autograded score . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 117.1.1 Performance index . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 117.1.2 Utilization . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 117.1.3 Throughput . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 127.1.4 Autograded deductions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 127.2 Heap Consistency Checker . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 137.3 Style . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 137.4 Handin Instructions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 148 Useful Tips 159 Office Hours 1610 Strategic Advice 17A Performance Evaluation 19A.1 Approximate Expected Results from Optimizations . . . . . . . . . . . . . . . . . . . . . . 19A.2 Machine Dependencies . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19A.3 Performance Points . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19B Viewing Heap Contents with GDB 21B.1 Viewing the heap without a helper function . . . . . . . . . . . . . . . . . . . . . . . . . . 21B.2 Viewing the heap with the hprobe helper function . . . . . . . . . . . . . . . . . . . . . . 2222 LogisticsThis is an individual project. You should do this lab on one of the Shark machines.To get your lab materials, click “Download Handout” on Autolab, enter your Andrew ID, and follow theinstructions. Then, clone your repository on a Shark machine by running:$ git clone https://github.com/cmu15213f2...<YOUR USERNAME>.gitor, if you use SSH keys, All the code for your allocator must be in this file. The rest of theprovided code allows you to evaluate your allocator. Using the command make will generate four driverprograms: mdriver, mdriver-dbg, mdriver-emulate, and mdriver-uninit, as described in section 6.Your final autograded score is computed by driver.pl, as described in section 7.1.To test your code for the checkpoint submission, run mdriver and/or driver.pl with the -C flag. Totest your code for the final submission, run mdriver and/or driver.pl with no flags.These commands will report accurate utilization numbers for your allocator. They will only reportapproximate throughput numbers. The Autolab servers will generate different throughput numbers, andthe servers’ numbers will determine your actual score. This is discussed in more detail in Section 7.33 Required FunctionsYour allocator must implement the following functions. They are declared for you in mm.h and you will findstarter definitions in mm.c. Note that you cannot alter mm.h in this lab.bool mm_init(void);void *malloc(size_t size);void free(void *ptr);void realloc(void ptr, size_t size);void *calloc(size_t nmemb, size_t size);bool mm_checkheap(int);We provide you two versions of memory allocators:mm.c: A fully-functional implicit-list allocator. We recommend that you use this code as your starting point.Note that the provided code does not implement block coalescing. The absence of this feature will causeexternal fragmentation to be very high, so you should implement coalescing. We strongly recommendconsidering all cases you need to implement before writing code for coalesce_block; the lectureslides should help you identify and reason about these cases.mm-naive.c: A functional implementation that runs quickly but gets very poor utilization, because it neverreuses any blocks of memory.Your allocator must run correctly on a 64-bit machine. It must support a full 64-bit address space, eventhough current implementations of x86-64 machines support only a 48-bit address space.Your submitted mm.c must implement the following functions:bool mm_init(void): Performs any necessary initializations, such as allocating the initial heap area. Thereturn value should be false if there was a problem in performing the initialization, true otherwise.You must reinitialize all of your data structures each time this function is called, because thedrivers call your mm_init function every time they begin a new trace to reset to an empty heap.void *malloc(size_t size): Returns a pointer to an allocated block payload of at least size bytes. Theentire allocated block should lie within the heap region and should not overlap with any other allocatedblock.Your malloc implementation must always return 16-byte aligned pointers, even if size is smaller than16.void free(void *ptr) : If ptr is NULL, does nothing. Otherwise, ptr must point to the beginning of ablock payload returned by a previous call to malloc, calloc, or realloc and not already freed. Thisblock is deallocated. Returns nothing.void realloc(void ptr, size_t size): Changes the size of a previously allocated block.If size is nonzero and ptr is not NULL, allocates a new block with at least size bytes of payload,copies as much data from ptr into the new block as will fit (that is, copies the smaller of size, or thepayload size of ptr, bytes), frees ptr, and returns the new block.If size is nonzero but ptr is NULL, does the same thing as malloc(size).If size is zero, does the same thing as free(ptr) and then returns NULL.Your realloc implementation will have only minimal impact on measured throughput or utilization. Acorrect, simple implementation will suffice.4void *calloc(size_t nmemb, size_t size): Allocates memory for an array of nmemb elements ofsize bytes each, initializes the memory to all bytes zero, and returns a pointer to the allocated memory.Your calloc implementation will have only minimal impact on measured throughput or utilization. Acorrect, simple implementation will suffice.bool mm_checkheap(int line): Scans the entire heap and checks it for errors. This function is calledthe heap consistency checker, or simply heap checker.A quality heap checker is essential for debugging your malloc implementation. Many malloc bugsare too subtle to debug using conventional gdb techniques. A heap consistency checker can help youisolate the specific operation that causes your heap to become inconsistent.Because of the importance of the consistency checker, it will be graded, by hand; section 7.2 describesthe requirements for your implementation in greater detail. We may also require you to write your heapchecker before coming to office hours.The mm_checkheap function takes a single integer argument that you can use any way you want. Onetechnique is to use this argument to pass in the line number where it was called, using the LINEmacro:mm_checkheap(__LINE__);This allows you to print the line number where mm_checkheap was called, if you detect a problem withthe heap.The driver will sometimes call mm_checkheap; when it does this it will always pass an argument of 0.The semantics of malloc, realloc, calloc, and free match the semantics of the functions with thesame names in the C library. You can type man malloc in the shell for more documentation.54 Support RoutinesTo satisfy allocation requests, dynamic memory allocators must themselves request memory from the operatingsystem, using “primitive” system operations that are less flexible than malloc and free. In this lab, youwill use a simulated version of one such primitive. It is implemented for you in memlib.c and declared inmemlib.h.void *mem_sbrk(intptr_t incr): Expands the heap by incr bytes, and returns a generic pointer to thefirst byte of the newly allocated heap area. If the heap cannot be made any larger, returns (void *)-1. (Caution: this is different from returning NULL.)Each time your mm_init function is called, the heap has just been reset to zero bytes long.mem_sbrk cannot make the heap smaller; it will fail (returning (void *) -1) if size is negative.(Data type intptr_t is defined to be a signed integer large enough to hold a pointer. On our machinesit is the same size as size_t, but signed.)This function is based on the Unix system call sbrk, but we have simplified it by removing the abilityto make the heap smaller.You can also use these helper functions, declared in memlib.h:void *mem_heap_lo(void): Returns a generic pointer to the first valid byte in the heap.void *mem_heap_hi(void): Returns a generic pointer to the last valid byte in the heap.Caution: The definition of “last valid byte” may not be intuitive! If your heap is 8 bytes large, then thelast valid byte will be 7 bytes from the start—not an aligned address.size_t mem_heapsize(void): Returns the current size of the heap in bytes.You can also use the following standard C library functions, but only these: memcpy, memset, printf,fprintf, and sprintf.Your mm.c code may only call the externally-defined functions that are listed in this section. Otherwise, itmust be completely self-contained.65 Programming Rules• Any allocator that attempts to detect which trace is running will receive a penalty of 20 points. Onthe other hand, you should feel free to write an adaptive allocator—one that dynamically tunes itselfaccording to the general characteristics of the different traces.• You may not change any of the interfaces in mm.h, or any of the other C source files and headers besidesmm.c. (Autolab only processes your mm.c; it will not see changes you make to any other file.) However,we strongly encourage you to use static helper functions in mm.c to break up your code into small,easy-to-understand segments.• You may not change the Makefile (again, Autolab will not see any changes you make there) and yourcode must compile with no warnings using the warnings flags we selected.• You are not allowed to declare large global data structures such as large arrays, trees, or lists in mm.c.You are allowed to declare small global arrays, structs, and scalar variables, and you may have as muchconstant data (defined with the const qualifier) as you like. Specifically, you may declare no morethan 128 bytes of writable global variables, total. This is checked automatically, as described inSection 7.1.4.The reason for this restriction is that global variables are not accounted for when calculating yourmemory utilization. If you need a large data structure for some reason, you should allocate space for itwithin the heap, where it will count toward external fragmentation.• Dynamic memory allocators cannot avoid doing operations that the C standard labels as “undefinedbehavior.” They need to treat the heap as a single huge array of bytes and reinterpret those bytes asdifferent data types at different times. It is rarely appropriate to write code in this style, but in thislab it is necessary.We ask you to minimize the amount of undefined behavior in your code. For example, instead ofdirectly casting between pointer types, you should explicitly alias memory through the use of unions.Additionally, you should confine the pointer arithmetic to a few short helper functions, as we have triedto do in the handout code.• In the provided baseline code, we use a zero-length array to declare a payload element in the blockstruct. This is a non-standard compiler extension, which, in general, we discourage the use of, but inthis lab we feel it is better than any available alternative.A zero-length array is not the same as a C99 “flexible array member;” it can be used in places where aflexible array member cannot. For example, a zero-length array can be a member of a union. Usingzero-length arrays this way is our recommended strategy for declaring a block struct that might containpayload data, or might contain something else (such as free list pointers).• The practice of using macros instead of function definitions is now obsolete. Modern compilers canperform inline substitution of small functions, eliminating the overhead of function calls. Use of inlinefunctions provides better type checking and debugging support.In this lab, you may only use #define to define constants (macros with no parameters) and debuggingmacros that are enabled or disabled at compile time. Debugging macros must have names that beginwith the prefix “dbg_” and they must have no effect when the macro-constant DEBUG is not defined.Here are some examples of allowed and disallowed macro definitions:7 ...

October 31, 2021 · 35 min · jiezi

关于c:C进阶19编译过程简介

Summary1)编译器个别由以下4局部组成:预处理器、编译器、汇编器、链接器 2)点击Build之后,IDE会进行预编译(生成两头.i文件)、编译(生成汇编代码.s文件)、汇编(生成指标文件.o文件)、链接(生成可执行程序.out文件)。 3)预编译会做的事件:解决正文(应用空格代替);开展宏(删除'#define');解决#结尾的符号(包含解决条件编译指令、开展头文件、#pragma指令等) 4)编译器所做工作 对预处理.i文件进行词法剖析、语法分析、语义剖析 词法剖析:剖析关键字、标识符、立刻数等是否非法语法分析:剖析表达式是否恪守语法规定语义剖析:在语法分析的根底上进一步剖析表达式是否非法剖析完结后进行代码优化生成相应的汇编代码文件5)汇编器所做工作 将汇编代码转变为机器的可执行指令每条汇编语句简直都对应一条机器指令编译过程简介1、预编译预编译做的是文本处理工作: 正文用空格代替开展所有的宏定义,并将#define删除解决条件编译指令#if, #ifdef, #elif, #else, #endif解决#include,开展被蕴含的头文件保留编译器须要应用的#pragma指令预处理指令示例:gcc - E test.c -o test.i 2、编译编译器所做工作 对预处理.i文件进行词法剖析、语法分析、语义剖析 词法剖析:剖析关键字、标识符、立刻数等是否非法语法分析:剖析表达式是否恪守语法规定语义剖析:在语法分析的根底上进一步剖析表达式是否非法剖析完结后进行代码优化生成相应的汇编代码文件编译指令示例:gcc -S test.i -o test.s 3、汇编汇编器所做工作 将汇编代码转变为机器的可执行指令每条汇编语句简直都对应一条机器指令汇编指令示例:gcc -c test.s -o test.o(.o文件被称为指标文件,并不是最终的可执行程序;个别一个.c文件就对应到一个.o指标文件) 本文总结自“狄泰软件学院”唐佐林老师《C语言进阶课程》。如有错漏之处,恳请斧正。

October 30, 2021 · 1 min · jiezi

关于c++:open-code-reading

C/C++ Projectsglog: 10/27/2021-10/28/2021cJSON: 10/28/2021-10/29/2021luaprotobufgrpc: https://grpc.io/libstdc++follyredisnginxmemcached

October 30, 2021 · 1 min · jiezi

关于c:C进阶18三目运算符和逗号表达式

Summary1)在C语言中,三目运算符返回的后果是一个右值,并不是一个变量(不能放在赋值符号左侧) 2)三目运算符的返回类型: 通过隐式类型转换规定返回b和c中的较高类型(留神:char和short在运算时会隐式转换成int)当b和c不能隐式转换到同一类型时编译出错3)逗号表达式(exp1, exp2, ... expN) 逗号表达式用于将多个子表达式连贯为一个表达式逗号表达式的值为最初一个子表达式的值(前N-1个子表达式能够没有返回值)计算程序为从左到右4)个别一行代码实现某种性能时,往往须要用到递归 + 逗号表达式 + 三目运算符 三目运算符和逗号表达式1、三目运算符三目运算符(expression ? a : b):当expression的值为真时,返回a的值;否则返回b的值。 代码浏览 int a = 1;int b = 2;int c = 0;c = a < b ? a : b; // c = 1 (a < b ? a : b) = 3; // error, lvalue required as left operand of assignment三目运算符(expression ? a : b)的返回类型: 通过隐式类型转换规定返回b和c中的较高类型当b和c不能隐式转换到同一类型时编译出错 char c = 0;short s = 0;int i = 0;double d = 0;char* p = "str";printf("%d\n", sizeof(c ? c : s)); // 4, 返回类型隐式转换为intprintf("%d\n", sizeof(i ? i : d)); // 8,返回类型隐式转换为doubleprintf("%d\n", sizeof(d ? d : p)); // error,double和char*不能隐式类型转换为同一类型2、逗号表达式逗号表达式(exp1, exp2, ... expN) ...

October 29, 2021 · 2 min · jiezi

关于c#:c文件上传下载功能实现

NuGet 装置SqlSugarModel文件下新建 DbContext 类 public class DbContext { public DbContext() { Db = new SqlSugarClient(new ConnectionConfig() { ConnectionString = "server=localhost;uid=root;pwd=woshishui;database=test", DbType = DbType.MySql, InitKeyType = InitKeyType.Attribute,//从个性读取主键和自增列信息 IsAutoCloseConnection = true,//开启主动开释模式和EF原理一样我就不多解释了 }); //调式代码 用来打印SQL Db.Aop.OnLogExecuting = (sql, pars) => { Console.WriteLine(sql + "rn" + Db.Utilities.SerializeObject(pars.ToDictionary(it => it.ParameterName, it => it.Value))); Console.WriteLine(); }; } //留神:不能写成动态的,不能写成动态的 public SqlSugarClient Db;//用来处理事务多表查问和简单的操作 public SimpleClient<uploading> uploadingdb { get { return new SimpleClient<uploading>(Db); } }//用来解决Student表的罕用操作 }uploading实体类[SugarTable("uploading")] public class uploading { //指定主键和自增列,当然数据库中也要设置主键和自增列才会无效 [SugarColumn(IsPrimaryKey = true, IsIdentity = true)] public int id { get; set; } public string name { get; set; } public string path { get; set; } }UploadingManager class UploadingManager : DbContext { public List<uploading> Query() { try { List<uploading> data = Db.Queryable<uploading>() .Select(f => new uploading { name = f.name, path = f.path }) .ToList(); return data; } catch (Exception e) { Console.WriteLine(e); throw; } } public List<string> GetName(string name) { List<string> data = Db.Queryable<uploading>() .Where(w=>w.name== name) .Select(f => f.path) .ToList(); return data; } }窗体加载读取到数据库字段name并赋值 ...

October 29, 2021 · 2 min · jiezi

关于c#:NETCore31-使用Jwt保护api

摘要本文演示如何向无效用户提供jwt,以及如何在webapi中应用该token通过JwtBearerMiddleware中间件对用户进行身份认证。 认证和受权区别?首先咱们要弄清楚认证(Authentication)和受权(Authorization)的区别,免得混同了。认证是确认的过程中你是谁,而受权围绕是你被容许做什么,即权限。显然,在确认容许用户做什么之前,你须要晓得他们是谁,因而,在须要受权时,还必须以某种形式对用户进行身份验证。 什么是JWT?依据维基百科的定义,JSON WEB Token(JWT),是一种基于JSON的、用于在网络上申明某种主张的令牌(token)。JWT通常由三局部组成:头信息(header),音讯体(payload)和签名(signature)。 头信息指定了该JWT应用的签名算法: header = '{"alg":"HS256","typ":"JWT"}'HS256示意应用了HMAC-SHA256来生成签名。 音讯体蕴含了JWT的用意: payload = '{"loggedInAs":"admin","iat":1422779638}'//iat示意令牌生成的工夫未签名的令牌由base64url编码的头信息和音讯体拼接而成(应用"."分隔),签名则通过公有的key计算而成: key = 'secretkey' unsignedToken = encodeBase64(header) + '.' + encodeBase64(payload) signature = HMAC-SHA256(key, unsignedToken)最初在未签名的令牌尾部拼接上base64url编码的签名(同样应用"."分隔)就是JWT了: token = encodeBase64(header) + '.' + encodeBase64(payload) + '.' + encodeBase64(signature)# token看起来像这样: eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJsb2dnZWRJbkFzIjoiYWRtaW4iLCJpYXQiOjE0MjI3Nzk2Mzh9.gzSraSYS8EXBxLN_oWnFSRgCzcmJmMjLiuyu5CSpyHIJWT经常被用作爱护服务端的资源(resource),客户端通常将JWT通过HTTP的Authorization header发送给服务端,服务端应用本人保留的key计算、验证签名以判断该JWT是否可信: Authorization: Bearer eyJhbGci*...<snip>...*yu5CSpyHI筹备工作应用vs2019创立webapi我的项目,并且装置nuget包 Microsoft.AspNetCore.Authentication.JwtBearerStartup类ConfigureServices 增加认证服务 services.AddAuthentication(options => { options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme; options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme; options.DefaultScheme = JwtBearerDefaults.AuthenticationScheme; }).AddJwtBearer(options => { options.SaveToken = true; options.RequireHttpsMetadata = false; options.TokenValidationParameters = new TokenValidationParameters() { ValidateIssuer = true, ValidateAudience = true, ValidAudience = "https://xx", ValidIssuer = "https://xx", IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("SecureKeySecureKeySecureKeySecureKeySecureKeySecureKey")) }; });Configure 配置认证中间件 ...

October 29, 2021 · 1 min · jiezi

关于c++:COMP1521-MIPS讲解

10/26/21, 11:39 AM COMP1521 21T3 — Assignment 1: minesweeper, MIPS minesweeper 1/11Assignment 1: minesweeper, MIPS minesweeperversion: 1.6 last updated: 2021-10-18 20:00:00Aimsto give you experience writing MIPS assembly codeto give you experience with data and control structures in MIPSGetting StartedCreate a new directory for this assignment called minesweeper, change to this directory, and fetch the provided code by running thesecommands:$ mkdir minesweeper$ cd minesweeper$ 1521 fetch minesweeperIf you're not working at CSE, you can download the provided files as a zip file or a tar file.This will add the following files into the directory:grid.h: some grid related constants in C, such as its size.grid.s: the MIPS version of grid.h.beginner.[hs]: more constants in C and MIPS.intermediate.[hs]: more constants in C and MIPS.expert.[hs]: more constants in C and MIPS.minesweeper.c: a reference implementation of Minesweeper in C.minesweeper.s: a stub assembly file to complete.MinesweeperHow to play Minesweeperminesweeper.c is an implementation of the classic game Minesweeper. The objective of the game is to clear a board that contains hidden"mines" or bombs without detonating any of them. To do this, you will need to use the clues on the board, which indicate how manybombs are in the adjacent cells.At any point, you can perform 2 actions:Marking a cell - marking or flagging a cell that you think might be a bomb,Revealing a cell - revealing the cell. If it is an empty cell, then all of the surrounding empty cells will also be revealed. Revealing acell containing a bomb is game over.Once you have revealed all cells that do not contain a bomb, you win the game.Before starting the assignment, it is recommended that you understand how to play Minesweeper. A good place to start is Google'sbuilt-in minesweeper game that can be found here.minesweeper.cThe assignment version of Minesweeper is played on a grid represented by a 2D array of 8-bit ints (int8_t **grid). Each element in the2D array represents a cell on the grid. For each element in the 2D array, 7 of the 8 bits are used to represent information regarding thatcell, as shown in the diagram below.is_marked - 1 if cell is marked, 0 if not.is_revealed - 1 if cell is revealed, 0 if not.is_bomb - 1 if cell is a bomb, 0 if not.value - number of bombs in adjacent cells, including diagonally adjacent cells. This will hold the value of 0 - 8 as there are a totalof 8 adjacent cells. The value 0 represents an empty cell.10/26/21, 11:39 AM COMP1521 21T3 — Assignment 1: minesweeper, MIPS minesweeper 2/11You can use bitwise operations to extract or set relevant bits. The relevant masks are #defined at the top of the minesweeper.c file.By default, the game is played on a 10x10 grid. However, you can change these settings to play on a different sized grid by changing the ...

October 29, 2021 · 21 min · jiezi

关于c:新手必须要注意的编程范式

编程语言与成百种编程语言(Programming Language)相比,编程范式(Programming Paradigm、范式)要少得多。如图所示,共有 27 种范式。少数范式之间仅相差一个或几个概念。 次要的范式最罕用的范式有三个:过程试编程,面向对象编程(OOP),函数式编程(FP)。而后咱们介绍一下新兴的第四种范式也就是面向切面编程(AOP)。 过程试编程过程式编程(Procedural programming)的外围在于模块化,在实现过程中应用了状态,依赖了内部变量,导致很容易影响左近的代码,可读性较低,前期的保护老本也较高。 过程试编程经验了倒退的两个阶段,非结构化到结构化: 非机构化编程(Unstructured programming):机器语言和汇编语言的编程范式被认为是非结构化编程,没有封装函数的概念,代码中 goto 语句满天飞的状态。 结构化编程(Structured programming):形象了机器的行为,屏蔽了局部计算机的硬件细节。代表语言就是咱们罕用的 C 语言。 有时结构化编程,也称作过程式编程,或面向过程编程。 def get_shannon_info(output): """获取shannon类型flash卡信息"""def check_health(): time_left = float(sub_info["life_left"]) if time_left < DISK_ALARM_LIFETIME: message = "time left is less than {}%".format(DISK_ALARM_LIFETIME) return message temperature = float(sub_info["temperature"].split()[0]) if temperature > DISK_ALARM_TEMPERATURE: message = "temperature is over than {} C".format(DISK_ALARM_TEMPERATURE) return message return "healthy"http://tags.astro.sina.com.cn... result = {}all_info = _get_shannon_info(output)for info in all_info: sub_info = {} sub_info["available_capacity"] = info.get("disk_capacity", "") sub_info["device_name"] = info.get("block_device_node", "") sub_info["firmware_version"] = info.get("firmware_version", "") sub_info["interface"] = "PCIe" sub_info["life_left"] = str(info.get("estimated_life_left", "").replace("%", "")) sub_info["pcie_id"] = info.get("pci_deviceid", "") sub_info["pcie_length"] = "" sub_info["pcie_type"] = "" sub_info["physical_read"] = info.get("host_read_data", "") sub_info["physical_write"] = info.get("total_write_data", "") sub_info["serial_number"] = info.get("serial_number") sub_info["temperature"] = info.get("controller_temperature") sub_info["type"] = info["type"] sub_info["error_msg"] = check_health() sub_info["status"] = "ok" if sub_info["error_msg"] == "healthy" else "error" if sub_info["serial_number"]: result[sub_info["serial_number"]] = sub_info else: result[sub_info["device_name"]] = sub_inforeturn result面向对象编程面向对象编程(Object-oriented programming)的外围在于形象,提供清晰的对象边界。联合封装、集成、多态个性,升高了代码的耦合度,晋升了零碎的可维护性。C++ 和 之后的 Java 成为支流。 ...

October 29, 2021 · 3 min · jiezi

关于c#:C-利用委托事件进行窗体间的传值

定义委托定义了一个参数是string ,无返回值的委托,名为 SendMessageToChildForms。 public delegate void SendMessageToChildForms(string s);委托实例化实质就是实例化了一个事件event public event SendMessageToChildForms smtcf_event;执行的办法public void ToShowGetMessage(string s){ this.lb_收到内容.Text=s;}绑定办法在一实例化的一个委托事件上绑定子窗体的具体方法 Parameter frm_child = new Parameter(); smtcf_event += frm_child.ToShowGetMessage; frm_child.Show();触发委托 if (smtcf_event != null) //判断委托事件是否为空,如果委托不为空才执行 { smtcf_event.Invoke("12212");// 能够省略Invoke 简写为smtcf(this.textBox1.Text.Trim()); }

October 28, 2021 · 1 min · jiezi

关于c++:TCP-IP网络编程学习笔记

根本数据结构和函数示意IPv4地址的构造体:struct sockaddr_in{ sa_family_t sin_family; //示意地址族 uint16_t sin_port; //示意16位的端口号(包含TCP和UDP) struct in_addr sin_addr; //32位的ip地址 char sin_zer[8] ; //不应用 };对于in_addr:struct in_addr{ In_addr_t s_addr;//32位IP地址}对于下面定义的成员变量类型,大部分都是在POSIX外面定义好了的,属于跨平台可移植的根本数据类型的别名。 对于sockaddr_in成员变量的剖析: sin_family: 对于每种协定实用于不同的地址族。典型的有: AF_INET : IPv4协定应用的地址族AF_INET6 : IPv6协定应用的地址族AF_LOCAL : 本地通信sin_port: 以网络字节序列保留端口号sin_zero: 字节填充符,无非凡的含意。对于socket过程须要绑定socket地址。对应的函数是bind 具体用法: bind(serv_sock, (struct sockaddr*) &serv_addr, sizeof(serv_addr));这里须要留神的是struct sockaddr*这个数据结构。在原先老版本的unix网络通信中并没有sockaddr_in这个数据结构,只有sockaddr struct sockaddr { sa_family_t sin_family; char sa_data[14]; //地址信息} 留神这里的sa_data数组蕴含了sockaddr_in数据结构中前面的所有信息,包含端口号、IP地址等等,这样的结果是编程起来十分不不便。所以前面把这个数据结构转换为了sockaddr_in,但同时也保障了字节序列和这个数据结构统一。因而这里即使应用了强制类型转换也不会影响数据的含意。 网络字节序列因为不同的机器CPU采纳的存储策略也不同。有些采纳大端法,有些采纳小端法。为了放弃在不同机器之间进行网络通信数据格式的对立,网络序列对立采纳大端法。所以在小端法的机器上发送数据时,首先要转换为大端法。对应的零碎API: unsigned short htons(unsigned short);//htons:host to network , short numberunsigned long htonl(unsigned long);//host to net , long number unsigned short ntohs(unsigned short);//net to host, short number…………网络地址初始化对于IP地址的示意,因为咱们大部分时候是以点分十进制表示法来了解的。然而计算机保留的是二进制序列,所以在初始化真正的IP地址时,咱们须要可能在点分十进制和二进制之间相互转换的API ...

October 27, 2021 · 6 min · jiezi

关于c#:手把手教你学Dapr-1-Net开发者的大时代

Dapr全称Distributed Application Runtime,分布式应用运行时 Dapr的口号简化云原生利用开发,聚焦在利用的外围逻辑,让代码简略、可移植 Dapr的指标最佳实际的构建块任何语言或框架一致性,可移植,凋谢的API驳回规范可扩大和可插拔的组件与平台无关(本地,云计算,边缘计算等)社区驱动,供应商(厂商)中立Dapr的设计思路这里首先要先了解几个问题,而后再看Dapr如何解决这些问题的 以下材料都有英文原图,中文翻译为集体了解,英文好的小伙伴能够间接看原图。微服务为什么很难开发者要构建本人的运行时解决分布式应用问题运行时反对的开发语言无限,且有严格控制的个性(性能)汇合运行时的可移植性无限,个别只反对特定的基础架构平台 分布式应用的需要内容引自 Multi-Runtime Microservices Architecture https://www.infoq.com/article...留神:二级内容不与图片对应,把性能组合成场景 生命周期 更快的公布周期自动化部署从谬误中复原自动化伸缩网络 服务发现跟踪与遥测(可观测性)信息替换:点对点、公布/订阅,智能路由状态 服务编排、工作流分布式单例(Actor)长期调度(Cron)幂等性有状态谬误复原缓存绑定 转换协定反对不同的音讯替换模式:轮询、事件驱动、申请/应答等转换音讯格局执行自定义谬误复原过程平安机制 传统中间件和云原生比照传统中间件以各种SDK的形式提供能力,而云原生平台则通过各种外围的Runtime,目前来看比拟乏味的是,大家不谋而合的抉择了Sidecar。 多运行时微服务边界K8s和容器在多语言应用程序的生命周期治理方面获得了微小的飞跃,并为将来的翻新奠定了根底Service Mesh在K8s上失去了改良,具备先进的网络性能,并开始深刻应用程序Knative通过疾速伸缩来关注无服务器的工作负载,解决了服务编排和事件驱动的绑定需要Dapr以K8s、Knative和Service Mesh的思维为根底,深入研究利用程序运行时,解决有状态的工作负载、绑定和集成需要,充当古代分布式中间件 次要分为3个局部,K8s、机甲运行时(网关、Dapr + Knative)、业务逻辑。 Dapr的呈现能够让开发者更专一于业务逻辑,而业务逻辑则作为服务运行时。 多运行时的益处业务逻辑和一直减少的分布式系统关注点之间的松耦合。 业务逻辑常常变动,取决于业务优先级。 而分布式原语则由软件供应商提供,作为库、容器、服务来应用。这些代码会依据供应商优先级、公布周期、安全补丁、开源治理规定等而变动。 他们相互看不到对方,也无法控制对方。 Dapr的劣势:Any language, anywhere与语言无关,与平台无关 分布式应用运行时官网解释 帮忙开发人员构建事件驱动的、弹性的分布式应用程序。 无论是在本地、云中还是在边缘设施上,都能够帮忙你解决构建微服务所带来的挑战,并放弃代码与平台无关。能够看到Dapr更具象化了 与应用程序通过HTTP和gRPC通信外部有一些构建块运行在云上 Dapr与服务网格开发者更聚焦在代码层面,通过SDK(图中没有标注)与dapr的构建块通信,面向localhost编程运维更关注安全性、可观测性、健壮性等问题上。而流量管控的局部,dapr(可能是临时的)没有。 Sidecar的世界利用于Sidecar通信是通过Dapr API(曾经被封装成不同开发语言的SDK),这个过程中通过OpenTelemetry反对了可观测性(即跟踪、日志、指标)利用之间通过Sidecar通信,反对mTLS,这个指服务调用(即Service Invocation)Sidecar 之间通过gRPC(图片中没有显示),Bindings,Pub/Sub都能够通信可观测性无处不在,通过Prometheus、Zipkin、Fluentd等,可视化OpenTelemetry中的局部数据但目前据我所知没有一个能够对立接管残缺OpenTelemetry的,如果有的话欢送纠错。状态治理也是由Sidecar代理的 对于.Net的意义.Net SDK是微软亲儿子,让.Net和Java一起在新起点站在了同一起跑线分布式应用运行时给.Net的新架构带来了新的思路和时机减速.Net技术栈的更新迭代共享开源生态咱们正在口头,新的框架、新的生态咱们的指标是自在的、易用的、可塑性强的、功能丰富的、强壮的。 所以咱们借鉴Building blocks的设计理念,正在做一个新的框架MASA Framework,它有哪些特点呢? 原生反对Dapr,且容许将Dapr替换成传统通信形式架构不限,单体利用、SOA、微服务都反对反对.Net原生框架,升高学习累赘,除特定畛域必须引入的概念,保持不造新轮子丰盛的生态反对,除了框架以外还有组件库、权限核心、配置核心、故障排查核心、报警核心等一系列产品外围代码库的单元测试覆盖率90%+开源、收费、社区驱动还有什么?咱们在等你,一起来探讨通过几个月的生产我的项目实际,已实现POC,目前正在把之前的积攒重构到新的开源我的项目中目前源码已开始同步到Github(文档站点在布局中,会缓缓欠缺起来): MASA.BuildingBlocks MASA.Contrib MASA.Utils MASA.EShop BlazorComponent MASA.Blazor QQ群:7424099 微信群:加技术经营微信(MasaStackTechOps),备注来意,邀请进群 (文章转载自:鬼谷子)

October 27, 2021 · 1 min · jiezi

关于c#:netCore30webapi到前端vue后端

创立api我的项目 创立实现启动F5!! 如图 数据库我用的是mysql 用efcore框架进行数据操作 开发环境:Win10 + VS2019 Mysql服务器版本:8.0.16下载并装置插件(必备)MySQL-Connector-net-6.9.12MySQL for Visual Studio 2.0.5用Nuget形式装置MySql.Data.Entity-6.9.12(MySql.Data.EntityFrameworkCore.Design!!两种都试过没问题,后面一种会报提醒不兼容),MySql.Data-6.9.12 MySql.Data.EntityFrameworkCore留神!!! 装置的2个dll版本号必须统一以及对应MySQL-Connector-net版本雷同 根目录新建Models文件创立实体类 gj public class gj { // <summary> /// 主键 /// </summary> public int id { get; set;}/// <summary>/// 题目/// </summary>public string method { get; set;}/// <summary>/// 内容/// </summary>public string text { get; set;}/// <summary>/// 状态 1失常 0删除/// </summary>public string type { get; set;}}public class DbModel:DbContext {public DbSet<gj> gj { set; get;}//protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)// => optionsBuilder.UseMySQL(@"Server=localhost;database=testapp;uid=root;pwd=woshishui");public DbModel(DbContextOptions<DbModel> options) : base(options) {}}appsettings.json配置数据连贯 ...

October 26, 2021 · 1 min · jiezi

关于c#:c使用SoundPlayer播放wav格式音频

应用System.Media名称空间下的类SoundPlayer 能够让咱们很不便的播放wav波形声音文件。SoundPlayer类其实就是对winmm.dll文件中API函数的封装。 SoundPlayer类的应用很简略。如下: SoundPlayer player = new SoundPlayer();player.SoundLocation = "音乐文件名";player.Load();player.Play();其中Play办法是异步办法,会在另一个线程中播放。如果咱们有时候须要等声音播放结束之后再进行下一步操作。即声音播放须要阻塞以后线程。就能够应用PlaySync()办法SoundPlayer类的毛病:只能播放wav文件;在winxp下播放文件比拟大或位率比拟高的状况,PlaySync同步播放会有播放不齐全的问题。这个问题的产生是因为winmm.dll的版本问题引起的。在xp下winmm.dll的版本是5。在win7下是6。win7下就没有问题。如果要解决在xp下播放不齐全的问题。能够应用xp下的录音机关上声音文件,把声音文件另存为7kbit/s的位率格局,但这样声音成果就很差了。实现援用System.Media名称空间下的类SoundPlayer SoundPlayer player = new SoundPlayer();办法调用Play();public void Play() { **player.SoundLocation** = @".x0pbk-swz4q.wav"; //读取音频文件 **player.Load(); **//同步模式 **player.Play(); ** if (MessageBox.Show("播放音樂中,通过旋转耳机上的旋钮测试音量,若聲音播放失常则选是,反之否", "提醒", MessageBoxButtons.YesNo, MessageBoxIcon.Information) == DialogResult.No) { DisplaylistboxMSG("Headset測試結果為異常"); } else { DisplaylistboxMSG("Headset測試結果為失常"); } player.Stop(); //进行播放 player.Dispose();}

October 26, 2021 · 1 min · jiezi

关于c#:cNAudio-录音功能实现

在网上找了很多相似录音教程成果都不好,或基本不能录音,代码由网上借鉴批改(残缺实现录音播放性能) NAudioNAudio为.NET平台下的开源库,采纳ML-PL协定,开源地址:https://github.com/naudio/NAudio。 NAudio功能强大,且其入门容易。弱小在于:它反对许多音频操作,可实现多种API播放与录制、多种不同音频格式、音频格式转换(重采样、位深、声道等)、音频编码、多通道播放、音频成果解决等等(具体介绍能够看Github readme)。 新建RecordController首先新建援用类 RecordController public class RecordController { public WaveIn mWavIn; public WaveFileWriter mWavWriter; /// <summary> /// 开始录音 /// </summary> /// <param name="filePath"></param> public void StartRecord(string filePath) { mWavIn = new WaveIn(); mWavIn.DataAvailable += MWavIn_DataAvailable; // mWavIn.RecordingStopped += MWavIn_RecordingStopped; 有抵触 mWavWriter = new WaveFileWriter(filePath, mWavIn.WaveFormat); mWavIn.StartRecording(); } /// <summary> /// 进行录音 /// </summary> public void StopRecord() { mWavIn?.StopRecording(); mWavIn?.Dispose(); mWavIn = null; mWavWriter?.Close(); mWavWriter = null; } //这个办法在调用敞开时会有抵触 private void MWavIn_RecordingStopped(object sender, StoppedEventArgs e) { //mWavIn?.Dispose(); //mWavIn = null; //mWavWriter?.Close(); //mWavWriter = null; } private void MWavIn_DataAvailable(object sender, WaveInEventArgs e) { mWavWriter.Write(e.Buffer, 0, e.BytesRecorded); int secondsRecorded = (int)mWavWriter.Length / mWavWriter.WaveFormat.AverageBytesPerSecond; }}应用在主界面援用 RecordController record = new RecordController(); ...

October 26, 2021 · 1 min · jiezi

关于c#:c获取文件夹目录下文件信息

应用程序可能只容许用户抉择文佳夹而非文件,,在增加时,只有抉择增加这个文佳夹,就是只抉择了文佳夹,而不是文件,这就要用到FloderBrowertDIalog控件对话框 FolderBrowserDialog控件对话框的罕用属性 Description 在对话框中提供描述性的音讯 RootFloder 指定对话框开始浏览的根文件夹 SelectedPath 指定用户所选的文件夹 ShowNewFloderButton 指定新建文件夹按钮是否显示在对话框中 private void button1_Click(object sender, System.EventArgs e) { //浏览文件夹 this.folderBrowserDialog1.ShowDialog(); if(this.folderBrowserDialog1.SelectedPath.Trim()!="") this.textBox1.Text=this.folderBrowserDialog1.SelectedPath.Trim();}private void button2_Click(object sender, System.EventArgs e) { //显示指定文件夹下的文件 if(this.textBox1.Text.Trim()=="") return; this.listBox1.Items.Clear(); string[] MyFiles=System.IO.Directory.GetFiles(this.textBox1.Text); this.listBox1.Items.AddRange(MyFiles); //foreach(string File in MyFiles) // this.listBox1.Items.Add(File);}======================================================================================= 本文链接:原创文章转载请注明

October 26, 2021 · 1 min · jiezi

关于c#:winform-启动外部程序

//class外面放入这段代码[DllImport("shell32.dll")]public static extern int ShellExecute(IntPtr hwnd, StringBuilder lpszOp, StringBuilder lpszFile, StringBuilder lpszParams, StringBuilder lpszDir, int FsShowCmd);//须要关上的中央插入此段代码ShellExecute(IntPtr.Zero, new StringBuilder("Open"), new StringBuilder("test.exe"), new StringBuilder(""), new StringBuilder(@"C:\文件夹名"), 1);

October 26, 2021 · 1 min · jiezi

关于c#:c利用定时器自动备份数据库mysql

援用dllmysql.data.dll是MySQL数据库中一款必备的驱动文件,次要用于.net编程和MySQL数据库的连贯,蕴含不同版本的mysql.data.dll,反对32位和64位零碎 MySqlBackup疾速备份或还原 MySql数据库,原理是应用MySqlBackup.dll 中的备份和还原办法,将数据库的信息转换为对应的sql语句,而后进行解决。 MySql.Data.dllMySqlbackup.dll动态类新建一个连贯字符串动态类 public static class mysql{public static string constr = "database=test;Password=明码;user ID=root;server=ip地址";public static MySqlConnection conn = new MySqlConnection(constr);}定时器启动winform timer1.Interval = 1000; //代表一秒运行一次timer1.Enabled = true; //启动备份代码利用winform窗体 timer定时器控件 C#调用MySqlBackup.dll 备份Mysql数据库 private void timer1_Tick(object sender, EventArgs e) { if (booql) { booql = false; if (DateTime.Now.Hour == 10 && DateTime.Now.Minute == 00) //工夫10点 { string time1 = System.DateTime.Now.ToString("d").Replace("/", "-"); string file = ".//mysql/" + time1 + "_test.sql"; using (MySqlCommand cmd = new MySqlCommand()) { using (MySqlBackup mb = new MySqlBackup(cmd)) { cmd.Connection = mysql.conn; mysql.conn.Open(); mb.ExportToFile(file); mysql.conn.Close(); MessageBox.Show("数据库已主动备份本地"); } } } }}

October 26, 2021 · 1 min · jiezi

关于c#:mysql数据库备份还原

援用dllMySql.Data.dll, MySqlbackup.dll建动态类public static class mysql{public static string constr = "database=test;Password=明码;user ID=root;server=ip地址";public static MySqlConnection conn = new MySqlConnection(constr);}备份代码DialogResult result = MessageBox.Show("备份门路默认在以后程序下", "提醒", MessageBoxButtons.YesNo, MessageBoxIcon.Question);if (result == DialogResult.Yes) { string time1 = System.DateTime.Now.ToString("d").Replace("/", "-"); string file = ".//mysql/" + time1 + "_test.sql"; using (MySqlCommand cmd = new MySqlCommand()) { using (MySqlBackup mb = new MySqlBackup(cmd)) { cmd.Connection = mysql.conn; mysql.conn.Open(); mb.ExportToFile(file); mysql.conn.Close(); MessageBox.Show("已备份"); } }} else { return;}还原代码string file = textBox1.Text;if (file == "") { MessageBox.Show("不能为空"); return;}DialogResult result = MessageBox.Show("确定还原吗?", "还原", MessageBoxButtons.YesNo, MessageBoxIcon.Question);if (result == DialogResult.Yes) { try { using (MySqlCommand cmd = new MySqlCommand()) { using (MySqlBackup mb = new MySqlBackup(cmd)) { cmd.Connection = mysql.conn; mysql. conn.Open(); mb.ImportFromFile(file); mysql. conn.Close(); MessageBox.Show("已还原"); } } } catch (Exception ex) { MessageBox.Show(ex.Message); }} else { return;}

October 26, 2021 · 1 min · jiezi

关于c:C进阶17和操作符分析

Summary1)++和--参加混合运算后果是不确定的,如r = (i++) + (i++);等 C++只规定了++和--对应指令的绝对执行秩序(取值和自增的绝对程序)++和--对应的汇编指令不肯定间断执行在混合运算中,++和--的汇编指令可能被打断执行 (取值和自增可能被打断了,两头插入了其余代码)2)编译器的贪婪法 编译器以从左向右的程序,一个一个地尽可能多的读入字符当读入的字符不可能和曾经读入的字符组成非法符号为止3)空格能够作为C语言中一个残缺符号的休止符,编译器读入空格后会立刻对之前读入的符号进行解决。 ++和--操作符分析1、Demo1以下代码的输入是? int i = 0;int r = 0;r = (i++) + (i++) + (i++);printf("i = %d\n, r = %d\n", i, r);r = (++i) + (++i) + (++i);printf("i = %d\n, r = %d\n", i, r);代码初步剖析: 第一行输入:i = 3, r = 3; // 依照从左向右的计算方法,i先取值,再自增, // 则r = 0 + 1 + 2 = 3;第二行输入:i = 6, r = 16; // 同上,r = 4 + 5 + 6 = 15;以上代码在VS2015编译器的理论输入后果为: ...

October 25, 2021 · 2 min · jiezi

关于c++:c11新特性完美转发

什么是完满转发? 它指的是函数模板能够将本人的参数“完满”地转发给外部调用的其它函数。 完满,示意能保障被转发参数的左、右值属性不变。“不完满“函数举例: template<typename T>void function(T t) // 非援用,形参会对实参进行拷贝。{ // 对于函数外部来说,t有本人的名称,也能够获取它的存储地址,因而它永远都是左值。 otherdef(t);} 12345传递给 otherdef() 函数的参数 t 永远都是左值。C++11实现完满转发: 问题1:怎么解决函数模板参数的左、右值接管问题? C++11 规范中规定,通常状况下右值援用模式的参数只能接管右值,不能接管左值。 但对于函数模板中应用右值援用语法定义的参数来说,它不再恪守这一规定,既能够接管右值,也能够接管左值(此时的右值援用又被称为“万能援用”)。template<typename T>void function(T &&t) //既能够承受左值,又能够承受右值{ otherdef(t); // t持续传参,在otherdef()中又变成了左值} 12345记住:在实现完满转发时,只有函数模板的参数类型为 T&&,则 C++ 能够自行精确地断定出理论传入的实参是左值还是右值。问题2:如何将函数模板接管到的形参连同其左、右值属性,一起传递给被调用的函数? C++11引入了一个模板函数 forword() 。//实现完满转发的函数模板template <typename T>void function(T&& t) { otherdef(forward<T>(t)); //将函数模板接管到的形参连同其左、右值属性,一起传递给被调用的函数 } 1 2 3 4 5残缺代码示例: include <iostream>using namespace std;//重载被调用函数,查看完满转发的成果void otherdef(int & t) { cout << "lvalue\n";}void otherdef(const int & t) { cout << "rvalue\n";}//实现完满转发的函数模板template <typename T>void function(T&& t) { ...

October 25, 2021 · 1 min · jiezi

关于c:C语言-浮点型存储

浮点型存储形式依照IEEE 754 规定贮存浮点型数据 #include <stdio.h>int main(){ int n = 9; //原码反码补码 //00000000000000000000000000001010 float* pFloat = (float*)&n; printf("n=%d\n",n); printf("*pFloat=%f\n",*pFloat); //以浮点数的视角看内存中贮存的二进制数据 //0(S负数) 00000000 (E 0+127) 000000000001010 (M) *pFloat = 9.0; //以浮点数的形式贮存二进制数据 //1001.0 1.001*2^3 E=3 //0 10000010 001000000000000000 printf("num=%d\n",n); //以整型形式读取 printf("*pFloat=%f\n",*pFloat); //浮点数形式读取 return 0;}更多建站及源码交易信息请见 GoodMai好买网

October 25, 2021 · 1 min · jiezi

关于c:CPT109-C难点解析

CPT109 C Programming and Software Engineering 1 – ASSESSMENT 1Assessment Number 1Contribution to Overall Marks 15%Issue Date Monday, 11th October 2021 (Week 5)Submission Deadline Monday, 25th October 2021, 00:01 (Week 7)Assessment OverviewThis assessment aims at testing some basic concepts of C programming and initiates theroutine of code development using the software development process (SDP). There are 3exercises, for exercise 1 and 2 only your code needs to be submitted. For exercise 3 you mustsubmit code and your SDP report. The SDP was presented in Lecture 1 you should only focuson the first five steps: ...

October 22, 2021 · 3 min · jiezi

关于c++:C之父Bjarne-Stroustrup倾情献作现代C白皮书

这是 C++ 之父 Bjarne Stroustrup 的 HOPL4 论文的中文版。 HOPL 是 History of Programming Languages(编程语言历史)的缩写,是 ACM(Association of Computing Machines,国内计算机协会)旗下的一个会议,约每十五年举办一次。Bjarne 的这篇论文是他为 2021 年 HOPL IV 会议筹备的论文,也是他的第三篇 HOPL 论文。在这三篇前后距离近三十年的论文里,Bjarne 记录了 C++ 的残缺历史,从 1979 年到 2020 年。这篇 HOPL4 论文尤其重要,因为它涵盖了 C++98 之后的所有 C++ 版本,从 C++11 直到 C++20。如果你对更晚期的历史也感兴趣的话,则能够参考他的其余 HOPL 论文,及他在 1994 年出版的《C++ 语言的设计与演变》(The Design and Evolution of C++)。 鉴于这篇论文对于 C++ 从业者的重要性,寰球 C++ 及系统软件技术大会的主办方 Boolan 组织了一群译者,把这篇重要论文翻译成了中文,让 C++ 开发人员对 C++ 的设计准则和历史有一个零碎的理解。 加入论文翻译工作的译者有(按拼音序):陈常筠、高辉、何荣华、何一娜、侯晨、侯金亭、彭亚、王奎、王绍新、吴咏炜、徐宁、杨文波、于波、余水清、翟华明、章爱国、张云潮。 论文翻译的校对和体例对立工作由吴咏炜、杨文波、张云潮实现。最初的公布由吴咏炜实现。 欢送大家来评论区收费支付C++白皮书 2021寰球C++及系统软件技术大会11月25-26日上海万豪虹桥大酒店

October 22, 2021 · 1 min · jiezi

关于c:32547-unix编程

32547 Faculty of Engineering and Information TechnologySubject 32547 UNIX Systems Programming, Spring 2021AssignmentDescriptionThis assignment is an individual programming assignment using Python. It addresses objectives 2and 3 as listed in the Subject Outline document.No limits apply to the number of lines of code of the program.Assignments are to be completed individually (this might be checked with the use of anti‐plagiarism tools such as Turnitin). You should not receive help in the preparation of thisassignment, nor ask anyone else to prepare it on your behalf in any way.  MarksThe assignment corresponds to 30% of the total marks.SubmissionThe completed assignment is due by 5:00pm of Friday 29 October 2021.  PLEASE PAY ATTENTION TO THE FOLLOWING SUBMISSION INSTRUCTIONS: ...

October 22, 2021 · 6 min · jiezi

关于c++:封装构造和析构2

没有任何返回值。初始化列表, 效率更高,用不了this指针一是应用初始化列表,二是在构造函数体内进行赋值操作。应用初始化列表次要是基于性能问题,对于内置类型,如int, float等,应用初始化类表和在构造函数体内初始化差异不是很大,然而对于类类型来说,最好应用初始化列表,为什么呢?由下面的测试可知,应用初始化列表少了一次调用默认构造函数的过程,这对于数据密集型的类来说,是十分高效的。同样看下面的例子,咱们应用初始化列表来实现Test2的构造函数 struct Test2{ Test1 test1 ;Test2(Test1 &t1):test1(t1){}} 应用同样的调用代码,输入后果如下。 construct Test1copy constructor for Test1第一行输入对应 调用代码的第一行。第二行输入对应Test2的初始化列表,间接调用拷贝构造函数初始化test1,省去了调用默认构造函数的过程。所以一个好的准则是,能应用初始化列表的时候尽量应用初始化列表。举例 lass X {public: int m_i; X(int value = 0) :m_i(value) { printf("this = %p", this); cout << "X(int)构造函数被调用" << endl; } X(const X &tmpv) { printf("this = %p", this); cout << "X拷贝构造函数被调用" << endl; } X& operator=(const X &tmpv) { printf("this = %p", this); cout << "X拷贝赋值运算符被调用" << endl; return *this; } ~X() { printf("this = %p", this); cout << "X析构函数被调用" << endl; }};class Y{public: X xobj;//类类型对象 Y(int tmpvalue) :xobj(1000)//这里结构了xobj,此处若没有应用初始化成员列表,消耗了一次结构函数调用的机会 // 编译器角度(没用初始化列表) //X xobj; //xobj.X::X(); // 编译器角度(用了初始化列表) //X xobj; //xobj.X::X(1000); { //xobj = 1000;//若不应用初始化列表。这里结构一个长期对象,把长期对象内容给了xobj,之后开释xobj //编译器视角 //x tmpobj;// (1)生成长期对象 //tmpobj.X::X(1000);// (2)长期对象调用构造函数 //xobj.X::operator=(tmpobj);// (3)调用拷贝赋值运算符 //tmpobj.X::~X(); // (4)调用析构函数 }};

October 22, 2021 · 1 min · jiezi

关于c++:类和对象

类和类型**类型** 变量int a;long long b;char c;double d;float e;类 对象Cat cat; 栈空间,编译器保护Cat * ptr_cat = new cat(); 堆空间, 程序员本人保护内存区:代码区 常量区, 堆, 栈一个类在内存中须要占多大的内存空间呢:是由成员变量的动态属性决定的, 还有一个额定的因素占用内存空间: 虚办法(TODO)编译器主动创立一个八字节的虚函数表,是链表的构造1231123 内存对齐 内存对齐基本上是通明的,这是编译器该干的活,编译器为程序中的每个数据单元安顿在适合的地位上,从而导致了雷同的变量,不同申明程序的构造体大小的不同。缩小不必要的内存开销, int放在一起 double 放在一起 采纳#pragma pack(1) 解决序列化和反序列化带来的内存对齐问题//52个字节了,减少成员办法不影响类对象的内存大小(虚办法除外),为什么要这么设计呢?成员办法存在代码段的,class People{string name;int age;double height;double weight;};//56个字节 //加上一行后变成了52对齐class People{string name;int age;double height;double weight;int children;};//64个字节class People{string name;int age;int children;double height;double weight;void say(string word);};//56个字节编译后存在内存中say变成了 void say(People * this, string word);类封装class默认private, struct 默认public 私有继承(public)私有继承在C++中是最罕用的一种继承形式,咱们先来看一个示例: 1 #include<iostream> 2 using namespace std; 3 class Father{ 4 public: 5 Father()=default; 6 void Father_show1(){ 7 cout<<"调用Father类的public办法:Father_show1"<<endl; 8 } 9 protected:10 void Father_show2(){11 cout<<"调用Father类的protected办法:Father_show2"<<endl;12 }13 private:14 void Father_show3(){15 cout<<"调用Father类的private办法:Father_show3"<<endl;16 }17 }; 18 19 class Son:public Father{20 public:21 Son()=default;22 void Son_fun1(){23 cout<<"调用Son类的public办法:Son_fun1"<<endl;24 Father_show1();25 Father_show2();26 //Father_show3(); //谬误:无奈调用Father类的private办法 27 }28 protected:29 void Son_fun2(){30 cout<<"调用Son类的protected办法:Son_fun2"<<endl;31 Father_show1();32 Father_show2();33 //Father_show3(); //谬误:无奈调用Father类的private办法 34 }35 private:36 void Son_fun3(){37 cout<<"调用Son类的private办法:Son_fun3"<<endl;38 Father_show1();39 Father_show2();40 //Father_show3();//谬误:无奈调用Father类的private办法 41 }42 };43 44 int main(){45 Son s;46 s.Son_fun1(); //正确,只能调用对象的public办法47 s.Father_show1();48 //s.Son_fun2(); //谬误:不能调用对象的protected办法49 //s.Father_show2();50 //s.Son_fun3(); //谬误:不能调用对象的private办法51 //s.Father_show3();52 return 0;53 }对私有继承的了解:三种属性能力的强弱:public<protected<private在C++的继承中,子类会继承父类中除构造函数和析构函数之外的所有成员(正所谓儿子无奈继承父亲的生死) 。而私有继承(public)就相当于先将从父类那里继承的全副成员放到子类的public局部,如下: ...

October 20, 2021 · 4 min · jiezi

关于c:从c到c

mapinsert和emplace区别,插入构造体时,emplace比insert少一次拷贝结构,举荐应用emplace结构的两种办法 map[1] = 2map.insert(std::pair<int, int>(2, 4));map.emplace(2,4)操作符重载 mymap[1] = 2;mymap[2] = 3;mymap[1] = 4;//mymap.size() == 2然而输入mymap[10]的值等于0, 同时size变成了3, 起因:会调配一个默认值为0给新的key, 这个val到底是否无效, 所以记得用find的办法,保障是无效的键值对map之间的赋值, 会耗费十分对的资源, map2 = map1,耗时931个时钟, map提供了swap办法, 不是内存拷贝,malloc这样的操作,只是把两者指针做替换,只耗费1个时钟,后续参考右值。multiple_map,容许key雷同容许传入第三个参数, 仿函数 map<int, int, less<int> > mymap;

October 19, 2021 · 1 min · jiezi

关于c:CSc-352-链接表实现

CSc 352 (Spring 2019): Assignment 11Due Date: 11:59PM Wed, May 1The purpose of this assignment is to work with linked lists, memory allocation, command linearguments, reading from a file, using free(), representing graphs, and doing more complicatedmanipulation of pointers.General Requirements Your C code should adhere to the coding standards for this class as listed in theDocuments section on the Resources tab for Piazza. This includes protecting againstbuffer overflows whenever you read strings.Your programs should indicate if they executed without any problems via their exitstatus, i.e., the value returned by the program when it terminates:Execution Exit StatusNormal, no problems 0Error or problem encountered 1Under bash you can check the exit status of a command or program cmd by typing thecommand "echo $?" immediately after the execution of cmd. A program can exit withstatus n by executing "exit(n)" anywhere in the program, or by having main() executethe statement "return(n)".Remember your code will be graded on lectura using a grading script. You should testyour code on lectura using the diff command to compare your output to that of theexample executable.Your code must show no errors when run with valgind.You must free all your allocated memory before your program exits.TestingExample executables of the programs will be made available. You should copy and run theseprograms on lectura to test your program’s output and to answer questions you might have abouthow the program is supposed to operate. Our class has a home directory on lectura which is:/home/cs352/spring19You all have access to this directory. The example programs will always be in the appropriateassignments/assg#/prob# subdirectory of this directory. They will have the same name as theassigned program with “ex” added to the start and the capitalization changed to maintaincamelback. So, for example, if the assigned program is theBigProgram, then the exampleexecutable will be named exTheBigProgram. You should use the appropriate UNIXcommands to copy these executables to your own directory.Your programs will be graded by a script. This will include a timeout for all test cases. Theremust be a timeout or programs that don’t terminate will cause the grading script to never finish.This time out will never be less than 10 times the time it takes the example executable tocomplete with that test input and will usually be much longer than that. If your program takes anexceedingly long time to complete compared to the example code, you may want to think abouthow to clean up your implementation.MakefilesYou will be required to include a Makefile with each program. Running the command:make progNameshould create the executable file progName, where progName is the program name listed for theproblem. The gcc commands in your Makefile that create the object files must include the -Wallflag. Other than that, the command may have any flags you desire.Submission InstructionsYour solutions are to be turned in on the host lectura.cs.arizona.edu. Since the assignment willbe graded by a script, it is important you have the directory structure and the names of the filesexact. Remember that UNIX is case sensitive, so make sure the capitalization is also correct. Forall our assignments the directory structure should be as follows: The root directory will be namedassg#, where # is the number of the current assignment. Inside that directory should be asubdirectory for each problem. These directories will be named prob# where # is the number ofthe problem within the assignment. Inside these directories should be any files required by theproblem descriptions.To submit your solutions, go to the directory containing your assg11 directory and use thefollowing command:turnin cs352s19-assg11 assg11Problemsprob1: baconWrite a program called bacon which calculates the Bacon score(https://en.wikipedia.org/wiki... ) of various actors based on theinformation given in an input file. Kevin Bacon is a movie actor and the Bacon score for anymovie actor is the number of movies it takes to connect Kevin Bacon with that actor. Thedefinition is as follows: Kevin Bacon has a Bacon score of 0 Any actor who was in a movie with Kevin Bacon has a Bacon score of 1 For any actor X, if the lowest possible Bacon score of any actor X has been in a moviewith is N, the X's Bacon score is N + 1It may be hard to follow the outline above, but the concept is not that deep. Read through thewiki page linked to above if you are confused.Basically, this is a graph problem. The actors are the vertices. The edges connecting the actorsare movies. There is an edge between the vertices representing actors A and B if and only if Aand B appeared in a movie together. An actor's Bacon score is then the smallest number of edgesconnecting the actor to Kevin Bacon. Invocation: Your program will be invoked with a required argument giving the file nameof a text file containing movie names and cast lists and an optional flag to tell theprogram whether to print out just the Bacon score or to print out the score together withthe path that generated it. The invocation will look like:bacon [-l] inFilewhere inFile is the name of a file which contains the movie list from which you willbuild your graph and –l (that's a lowercase L) is an optional flag. To make our program"UNIX like" we will allow the arguments to appear in any order and the option flag maybe specified multiple times. Here are some examples of legal invocations:bacon myFile –lbacon –l –l myFilebacon myFileThe following would be illegal invocations:bacon –l //has no file specifiedbacon fileName fileName //too many argumentsbacon –ll myFile //not a legal optionIf the invocation is illegal, you should print an error message to stderr indicating how theprogram is used, and exit with a status of 1. If you are confused about what is legal andwhat is not, experiment with the example executable. Movie File: The movie file whose name is given as a command line argument willcontain a list of movies and their cast lists. The format of the file is as follows:Move: <name of movie><actor 1><actor 2><actor n>Movie: <name of movie><actor 1> . . .where the actors listed (one per line) after the movie name are the actors in that movie.An example input file is in the subdirectory for this project of the class home directory onlectura. The file may contain blank lines (lines containing only white space) and theseshould be ignored. A single space will follow the keyword "Movie:". The name of themovie is considered to be the string starting at the character beyond that space andcontinuing until the end of the line but NOT including the '\n'. The actor's name iseverything on the line except for the possible newline ('\n') at the end. To simplify theprogram, do not worry about trimming white space from the ends of the lines (other thanthe '\n') or capitalization. In other words the actor's "John Wayne", "John Wayne ", "johnwayne", and " John Wayne" can all be considered to be different by your program. Behavior: After reading the file of cast lists and creating your graph, your program willdo the following:read in a line from stdin containing an actor's namecompute the Bacon score for that actor (using a breadth first search)print the Bacon score (and the connecting actors and movies if –l option invoked)to stdout according to the format specified below.until no further input can be read. ? Assumptions: You can assume the following:o The movie file, if it exists, is in correct format. In other words you may assumethe first nonblank line contains a movie name. You may also assume that if a linestarts with "Movie: ", then the line continues with some name. Note that sinceblank lines are legal, and empty file is in fact a legal movie file. Output: Output should be printed to stdout. To print out the score, use the formatprintf("Score: %d\n", score)where score is the calculated Bacon score. If there is no path between the actor and KevinBacon, your program should print "Score: No Bacon!" on a single line.If the actor queried is not in the graph, print a message to stderr and continue readingqueries. As always, whenever you print to stderr, when your program finally exits itshould exit with a status of 1.The –l optionIf the –l option is specified when the program is invoked, your program should print thelist of movies and actors connecting the queried actor to Kevin Bacon. The format for thisoutput should be<Queried Actor>was in <Movie Name> with<Actor>was in <Movie Name> with<Actor>. . .was in <Movie Name> withKevin BaconKeeping track of this list is more difficult and only 10% of the test cases will involve thisoption and they will be for extra credit. In other words you can still get 90/90 (100%) onthe assignment even if you fail to implement the –l option (you must still recognize aninvocation with the –l option as legal though), or 100/90 if you correctly implement the –loption. Also note that while the Bacon score is unique, the list printed out may not be.This means that if you are testing this option you may end up with a different output thanthe example executable and still be correct. Don't worry about getting the same list as theexample as long as your list is correct. When I test this part of the program I will use testcases that have only one path to generate the Bacon score. You may want to create suchtest cases yourself. (The example movie file should do.)? Data Structures:Once again you will use linked lists to represent the graph. The vertices of the graph willbe the actors. The edges will be the movies. If you are implementing the –l option theedges will need to contain the movie name.There are certainly variations on this. I used a linked list of actors. Each actor contains alinked list of movies (nodes which point to a movie). Each movie contains a linked list ofactors (nodes pointing to an actor). The Algorithm:A depth first search will not work here. A depth first search finds if there is a pathbetween two vertices. We want to find the shortest path between two vertices. Toaccomplish this, we will use a breadth first search. A depth first search recursivelysearches all the children of each vertex. A breadth first search puts all the children on aqueue. This way all the children are search before the grandchildren, etc. Here is thealgorithm for a breadth first search:BFS(Start, Target)mark Start as queuedset level of Start to 0add Start to the queuewhile queue is not empty do Take A from top of queue For all children C of A do if C == Target return level of A + 1 //found, score A.level + 1 if C not queued mark C as queued set level of C to level of A + 1 add C to queuereturn Target not found //If you get through loop without //finding Target, there is no//path from Start to TargetNote that in C you will have to implement this queue with a linked list. Don't forget tofree it again after you're done using it.Here's a hint for implementing the –l option. It requires you be able to trace the path fromStart to Target. If some actor A is put on the queue when looking at the children of someactor B, the path to A comes from B. If your structure for nodes of the queue contains alink to this "parent" node, then you can following these links from the queue node for theTarget back to the queue node for the Start. (i.e. It records your path.) Error Conditions:o Fatal errors: Bad invocation of program; input file cannot be opened for reading.o Non-fatal errors: Queried actor is not in the graph.

October 18, 2021 · 10 min · jiezi

关于c++:More-Effective-C技术篇将constructor和nonmember-function虚化

所谓virtual constructor是某种函数,视其取得的输出,可产生不同类型的对象。有一种特地的virtual constructor——所谓virtual copy constructor——也被宽泛地使用、virtual copy constructor会返回一个指针,指向其调用者(某对象)的一个新正本。基于这种行为,virtual copy constructor通常以copyself或cloneself命令,或者间接命名为clone。当derived class从新定义其base class的一个虚函数时,不再须要肯定得申明与本来雷同的返回类型。如果函数的返回类型是个指针或援用,指向一个base class,那么derived class的函数能够返回一个指向该base class的derived class的指针或援用。这样就能够申明出像virtual copy constructor这样的函数。non-member function的虚化非常容易:写一个虚函数做理论工作,再写一个什么都不做的非虚函数,只负责调用虚函数。为了缩小函数调用老本,能够将非虚函数inline化。上面就是virtual copy constructor和virtual non-member function的例子。 #include <iostream>#include <list>class NLComponent{public: // 申明 virtual copy constructor virtual NLComponent *clone() const = 0; virtual std::ostream& print(std::ostream& s) const = 0; NLComponent() {} virtual ~NLComponent() {}};class TextBlock : public NLComponent{public: // virtual copy constructor TextBlock *clone() const override {return new TextBlock(*this);} std::ostream& print(std::ostream& s) const override { s << "I'm TextBlock" << std::endl; return s; }};class Graphic : public NLComponent{public: // virtual copy constructor Graphic *clone() const override {return new Graphic(*this);} std::ostream& print(std::ostream& s) const override { s << "I'm Graphic" << std::endl; return s; }};// 将 Non-Member Function的行为虚化inline std::ostream& operator<<(std::ostream& s, const NLComponent& c){ return c.print(s);}class NewsLetter{public: NewsLetter() {} ~NewsLetter() {} // copy constructor NewsLetter(const NewsLetter& rhs); void AddComponet(NLComponent* c); void PrintComponents();private: std::list<NLComponent*> components;};NewsLetter::NewsLetter(const NewsLetter& rhs){ for (auto it = rhs.components.begin(); it != rhs.components.end(); it++) { components.push_back((*it)->clone()); }}void NewsLetter::AddComponet(NLComponent* c){ components.push_back(c);}void NewsLetter::PrintComponents(){ for (auto it = components.begin(); it != components.end(); it++) { std::cout << *(*it); }}int main(){ TextBlock tb; Graphic gp; NewsLetter nl1; nl1.AddComponet(&tb); nl1.AddComponet(&gp); NewsLetter nl2(nl1); nl2.PrintComponents();}

October 17, 2021 · 1 min · jiezi

关于c:COMP-321-编程指南

COMP 321April 24, 2019Questions on this exam may refer to the textbook as well as to the manual pages on CLEAR.Therefore, you should not start the exam until you are in a position to access both.As a reminder, the notation fdopen(3) means that the manual page for the function fdopencan be displayed with the command man 3 fdopen.You may review any section of the textbook and any manual page on CLEAR during the exam,and not just those explicitly referenced by the questions. Moreover, you may review any of thelecture notes, labs, and assignments that the instructors have provided to you or any notes thatyou have taken for this class. You may also use CLEAR to develop and test your C code for thisexam. You may not consult any other sources of information, including other textbooks, web sites,or people, aside from the instructors.This is a 5 hour exam. You must take the exam in one continuous block of time. You maytake one break of up to one hour during the exam. Your exam period begins as soon as you lookat any page of the exam other than these instructions. Indicate in your exam submission the dateand time at which you start the exam, the time at which you start your break, the time at whichyou end your break, and the time at which you end the exam.Once you begin the exam, you may not discuss the exam with anyone other than the instructorsuntil the end of the finals period. If you find anything in the exam to be ambiguous, clearly stateall of the assumptions that you are making in solving the problem.All of the questions have brief answers of either a single paragraph or a single C function thatis small in size. Always explain your answer and comment any C code you write to explain whatit does. Most of your score will be determined by your explanation. Turn in your answers throughCanvas by 5PM on Wednesday, May 1st. Submit your answers in the form of a text file (.txt),following the same formatting guidelines as for your programming assignments.1 of 8 ...

October 17, 2021 · 5 min · jiezi

关于c++:sizeof与内存对齐总结

1.根本类型sizeof运算符返回类型或者数据对象的长度(字节), int a=1; float b=1.0; double c=1.0; long d=1; char e = '1'; cout<<sizeof(a)<<" "<<sizeof(b)<<" "<<sizeof(c)<<" "<<sizeof(d)<<" "<<sizeof(e)<<endl; cout<<sizeof(int)<<" "<<sizeof(float)<<" "<<sizeof(double)<<" "<<sizeof(long)<<" "<<sizeof(char)<<endl;输入: 4 4 8 8 14 4 8 8 12.动态数组将sizeof运算符用于动态数组名,失去的是整个数组的字节数,用于数组元素,则失去的是元素长度。 int arr[3]={1,1,1}; float arr1[3]={1.0,1.0,1.0}; double arr2[3]={1.0,1.0,1.0}; cout<<sizeof(arr)<<" "<<sizeof(arr1)<<" "<<sizeof(arr2)<<endl; cout<<sizeof(arr[0])<<" "<<sizeof(arr1[1])<<" "<<sizeof(arr2[2])<<endl;输入: 12 12 244 4 83.动静数组然而当sizeof运算符用于动静数组,就很神奇。 vector<int>arr1(1,0); vector<int>arr2(2,0); vector<int>arr3(3,0); cout<<sizeof(arr1)<<" "<<sizeof(arr2)<<" "<<sizeof(arr3)<<endl;输入: 24 24 24能够看到不论vector有多少元素,输出都是24,为啥? 这是因为 vector 是C++规范库中的容器类,其外部实现了三个指针, start;finish;end_of_storage;别离代表头, 尾(理论应用), vector 存储尾部(占用的,通常大于理论应用),finish-start对应于size(),end_of_storage-start对应于capacity(),如下图所示: ...

October 17, 2021 · 1 min · jiezi

关于c++:COMP9319-2018s2-Assignment-2-BWT

COMP9319 2018s2 Assignment 2: BWTThis assignment contains two tasks: BWT encode and backward search.RequirementsBWT encodeYour first task in this assignment is to create a special BWT encoder that will encode a file with delimiter-separated text values (similar to a CSV file) into two files: a BWT encoded file; and an auxiliary positional information file. Your BWT encoded file may carry some positional information (i.e., first record, second record, and so on; whilst the size of the BWT encoded file is the same as the original file, and the frequencies of each character in these two files are the same). The BWT encoded file must be the same size as the original text file, and the auxiliary must not be larger than the original text file. (Note that different students may have different, working schemes to capture this positional information). ...

October 16, 2021 · 11 min · jiezi

关于c++:Assignment-3-Description-jack编序器

Assignment 3 Description: Computer Systems (2000_7081 Combined) https://myuni.adelaide.edu.au... 1/7 Assignment 3 Descripon Assignment 3 - Jack Compiler Weighng and Due DatesMarks for this assignment contribute 20% of the overall course mark.Marks for functionality will be awarded automatically by the web submission system.Due dates: Milestone - 11:55pm Friday of week 11, Final - 11:55pm Monday of week 13.Late penalties: For each part, the maximum mark awarded will be reduced by 25% per day /part day late. If your mark is greater than the maximum, it will be reduced to the maximum.Core Body of Knowledge (CBOK) Areas: abstraction, design, hardware and software, dataand information, and programming.Project DescriponIn this assignment you will complete a variation of projects 10 and 11 in the nand2tetris course,reworked descriptions of Nand2Tetris Projects 10 and 11 are shown below. In particular, you willwrite the following programs that are used to implement different components of an optimisingJack compiler that compiles a Jack class into Hack Virtual Machine (VM) code:parser - this parses a Jack program and constructs an abstract syntax tree.codegen - this takes an abstract syntax tree and outputs equivalent VM code.pretty - this takes an abstract syntax tree and produces a carefully formatted Jack program.optimiser-r* - this copies an abstract syntax tree and removes redundant code wherepossible.lint^ - this takes an abstract syntax tree and annotates it with warning and / or errormessages.Notes:^Only for students enrolled in the undergraduate offering, COMP SCI 2000.*Only for students enrolled in the postgraduate offering, COMP SCI 7081.SVN RepositoryNote: this assignment assumes that you have already created directories for every assignment,workshop, project and exam in your svn repository, as described on the Startup Files forWorkshops and Assignments (https://myuni.adelaide.edu.au... for-workshops-and-assignments) page. ...

October 15, 2021 · 10 min · jiezi

关于c++:EEE102-软件工程

EEE102 Assessment 3 EEE102 C++ Programming and Software Engineering IIAssessment 3Assessment Number 3Contribution to Overall Marks 35%Submission Deadline Wednesday, 01-May-2019, 23:59How the work should be submitted?SOFT COPY ONLY !(MUST be submitted through ICE so that the TAs can run your programs during marking.)Make sure your name and ID are printed on the cover page of your report.Assessment OverviewThis assessment aims at testing some basic concepts of C++ programming and initiates the routine ofcode development using the software development process (SDP), namely the five main steps of thesoftware development process: ...

October 15, 2021 · 4 min · jiezi

关于c++:设计模式必备知识点六大设计原则

设计模式,即Design Patterns,是指在软件设计中,被重复应用的一种代码设计教训。 应用设计模式的目标是为了可重用代码,进步代码的可扩展性和可维护性。 设计模式这个术语是上个世纪90年代由Erich Gamma、Richard Helm、Raplh Johnson和Jonhn Vlissides四个人总结提炼进去的,并且写了一本 Design Patterns 的书。我的项目地址: https://gitee.com/baichen9187... 一,开闭准则开闭准则的定义开闭准则是最根底的设计准则,它领导咱们如何建设一个稳固,灵便的零碎。开闭准则定义如下: Software entities like classes,modules and functions should be openfor extension but closed for modifications.OOP实践中5个准则之一(别离是S O L I D,繁多职责准则、开闭准则、里氏替换、接口隔离、依赖反转) 一个软件实体如类,模块和函数应该对扩大凋谢,对批改敞开。 什么是开闭准则开闭准则明确的通知咱们:实体实现应该对扩大凋谢,对批改敞开,其含意是说一个实体应该通过扩大来实现变动,而不是通过批改已有的代码来实现变动的。那什么是实体呢?软件实体包含以下几个局部: 我的项目或软件产品中依照肯定的逻辑规定划分的模块形象和类办法 开闭准则的作用开闭准则是面向对象程序设计的终极目标,它使软件实体领有肯定的适应性和灵活性的同时具备稳定性和延续性。具体来说,其作用如下。 对软件测试的影响软件恪守开闭准则的话,软件测试时只须要对扩大的代码进行测试就能够了,因为原有的测试代码依然可能失常运行。能够进步代码的可复用性粒度越小,被复用的可能性就越大;在面向对象的程序设计中,依据原子和形象编程能够进步代码的可复用性。能够进步软件的可维护性恪守开闭准则的软件,其稳定性高和延续性强,从而易于扩大和保护。开闭准则的长处进步代码复用性进步可维护性进步灵活性易于测试#include <iostream>class Number {protected: double pi = 3.1415926;public: virtual double getCircularArea(int d) = 0; virtual double getRectangularArea(int a, int b) = 0;};class NumberArea : public Number {public: double getCircularArea(int r) { return ((double)r * r) * this->pi; } double getRectangularArea(int a, int b) { return (double)a * b; }};int main(){ NumberArea num; double cricular = num.getCircularArea(1); std::cout << cricular << std::endl; }二,繁多职责准则繁多职责定义繁多职责准则(SRP:Single responsibility principle)又称繁多性能准则,面向对象五个根本准则(SOLID)之一。它规定一个类应该只有一个发生变化的起因。该准则由罗伯特·C·马丁(Robert C. Martin)于《麻利软件开发:准则、模式与实际》一书中给出的。马丁示意此准则是基于汤姆·狄马克(Tom DeMarco)和Meilir Page-Jones的著述中的内聚性准则倒退出的。 ...

October 12, 2021 · 5 min · jiezi

关于c++:xmake-v258-发布新增-PascalSwig-程序和-Lua53-运行时支持

xmake 是一个基于 Lua 的轻量级跨平台构建工具,应用 xmake.lua 保护我的项目构建,相比 makefile/CMakeLists.txt,配置语法更加简洁直观,对老手十分敌对,短时间内就能疾速入门,可能让用户把更多的精力集中在理论的我的项目开发上。 这个版本,咱们次要减少了对 Pascal 语言我的项目和 Swig 模块的构建反对,而对于上个版本新增的 Vala 语言反对,咱们也做了进一步改良,减少了对动静库和动态库的构建反对。 除此之外,xmake 当初也曾经反对了可选的 Lua5.3 运行时,提供更好的跨平台反对能力,目前 xmake 曾经可能在 LoongArch 架构上失常运行。 我的项目源码官网文档入门课程新个性介绍Pascal 语言反对目前,咱们能够应用跨平台的 Free pascal 工具链 fpc 去编译构建 Pascal 程序,例如: 控制台程序add_rules("mode.debug", "mode.release")target("test") set_kind("binary") add_files("src/*.pas")动静库程序add_rules("mode.debug", "mode.release")target("foo") set_kind("shared") add_files("src/foo.pas")target("test") set_kind("binary") add_deps("foo") add_files("src/main.pas")咱们也能够通过 add_fcflags() 接口增加 Pascal 代码相干的编译选项。 更多例子见:Pascal examples Vala 库编译反对上个版本,咱们新增了对 Vala 语言的反对,然而之前只能反对控制台程序的编译,无奈生成库文件。而这个版本中,咱们额定减少了对动态库和动静库的编译反对。 动态库程序咱们可能通过 add_values("vala.header", "mymath.h") 设置导出的接口头文件名,通过 add_values("vala.vapi", "mymath-1.0.vapi") 设置导出的 vapi 文件名。 add_rules("mode.release", "mode.debug")add_requires("glib")target("mymath") set_kind("static") add_rules("vala") add_files("src/mymath.vala") add_values("vala.header", "mymath.h") add_values("vala.vapi", "mymath-1.0.vapi") add_packages("glib")target("test") set_kind("binary") add_deps("mymath") add_rules("vala") add_files("src/main.vala") add_packages("glib")动静库程序add_rules("mode.release", "mode.debug")add_requires("glib")target("mymath") set_kind("shared") add_rules("vala") add_files("src/mymath.vala") add_values("vala.header", "mymath.h") add_values("vala.vapi", "mymath-1.0.vapi") add_packages("glib")target("test") set_kind("binary") add_deps("mymath") add_rules("vala") add_files("src/main.vala") add_packages("glib")更多例子见:Vala examples ...

October 12, 2021 · 4 min · jiezi

关于c:C进阶16位运算符

Summary1)C语言中的位运算符: 运算符意义规定&按位与全1得1,有0得0I按位或有1得1,全0得0^按位异或雷同为0,不同得1~取反1变0, 0变1<<左移高位抛弃,低位补0·>>右移高位补符号位,低位舍弃2)左移、右移的留神点: 左操作数必须是整数类型 char和short被隐式转换为int后进行操作右操作数的范畴必须为:[0,31],否则后果未定义(不同编译器处理结果不同)左移运算符<<将运算数的二进制位左移,成果相当于乘以2的n次方,效率更高右移运算符>>将运算数的二进制位右移,成果相当于除以2的n次方,效率更高防止位运算符、逻辑运算符、数学运算符等混合运算,如果必须这样,应用括号示意好计算程序。(单算移比、按逻三赋)3)位运算留神点: 位运算没有短路规定,每个操作数都会参加运算位运算的后果是整数,而不是0或1位运算的优先级高于逻辑运算(单算移比 按逻三赋)4)替换两个整形变量的值: Demo1:局部和形式:不应用两头变量,但存在溢出的问题 #define SWAP(a, b) \{ \ a = a + b; \ b = a - b; \ a = a - b; \}Demo2:位运算形式:应用异或(两个雷同的值异或后果为0,任何数和0异或仍为自身) #define SWAP(a, b) \{ \ a = a ^ b; \ b = a ^ b; \ a = a ^ b; \}位运算符分析C语言最后设计用来开发UNIX操作系统,操作系统运行于硬件平台之上,必然会波及位运算,须要对硬件的bit位(0和1)进行操作。C语言中位运算间接映射到了硬件零碎中的位运算。位运算符间接对bit位进行操作,其效率最高。 1、C语言中的位运算符运算符意义规定&按位与全1得1,有0得0I按位或有1得1,全0得0^按位异或雷同为0,不同得1~取反1变0, 0变1<<左移高位抛弃,低位补0·>>右移高位补符号位,低位舍弃2、左移和右移的留神点左操作数必须是整数类型 char和short被隐式转换为int后进行操作右操作数的范畴必须为:[0,31],否则后果未定义(不同编译器处理结果不同)左移运算符<<将运算数的二进制位左移,成果相当于乘以2的n次方,效率更高右移运算符>>将运算数的二进制位右移,成果相当于除以2的n次方,效率更高 Demo1 d << 2; // error, 左操作数必须是整型 int x = 10 >> 1; // ok,"右移等效除以2的n次方",输入5 int y = -1 << 1; // ok,"左移等效乘以2的n次方",输入-2 int z = 3 << -1; // -1不在[0,31]范畴中,后果未定义,不同编译器不同解决 // 编译器亦提醒了谬误:Possible overflow in shift operation // gcc 1, 左移-1相当于右移1,那就除以2,失去了1 // bcc -2147483648, int的最小值 // vc 0, 原本就未定义,给你0把防止位运算符、逻辑运算符、数学运算符等混合运算,如果必须这样,应用括号示意好计算程序。(单算移比、按逻三赋) ...

October 10, 2021 · 1 min · jiezi

关于c++:C基础总结

C++语法根底(数据类型、运算符、程序流程构造、数组、函数、指针、构造体)1 C++初识1.1规范代码格局#include<iostream>using namespace std;int main() { cout << "Hello world" << endl; system("pause"); return 0;}1.2 正文作用:在代码中加一些阐明和解释,不便本人或其余程序员程序员浏览代码 两种格局 单行正文:// 形容信息 通常放在一行代码的上方,或者一条语句的开端,==对该行代码阐明==多行正文: /* 形容信息 */ 通常放在一段代码的上方,==对该段代码做整体阐明==提醒:编译器在编译代码时,会疏忽正文的内容1.3 变量作用:给一段指定的内存空间起名,不便操作这段内存 语法:数据类型 变量名 = 初始值; //变量的定义//语法:数据类型 变量名 = 初始值int a = 10;留神:C++在创立变量时,必须给变量一个初始值,否则会报错1.4 常量作用:用于记录程序中不可更改的数据 C++定义常量两种形式 \#define 宏常量: #define 常量名 常量值 ==通常在文件上方定义==,示意一个常量永远不可批改const润饰的变量 const 数据类型 常量名 = 常量值 ==通常在变量定义前加关键字const==,润饰该变量为常量,不可批改能够通过指针援用批改//1、宏常量 永远不可批改#define day 7int main() { //2、const润饰变量 能够通过指针援用批改 const int month = 12; system("pause"); return 0;}1.5 关键字作用:关键字是C++中事后保留的单词(标识符) 在定义变量或者常量名字的时候,不要用关键字C++关键字如下: asmdoifreturntypedefautodoubleinlineshorttypeidbooldynamic_castintsignedtypenamebreakelselongsizeofunioncaseenummutablestaticunsignedcatchexplicitnamespacestatic_castusingcharexportnewstructvirtualclassexternoperatorswitchvoidconstfalseprivatetemplatevolatileconst_castfloatprotectedthiswchar_tcontinueforpublicthrowwhiledefaultfriendregistertrue deletegotoreinterpret_casttry 提醒:在给变量或者常量起名称时候,不要用C++得关键字,否则会产生歧义。 ...

October 10, 2021 · 4 min · jiezi

关于c:ELEC129-C语法解说

Department of Electrical Engineering and ElectronicsIntroduction toProgramming in C(ELEC129)Assignment 4Introduction to Programming in C (ELEC129) Assignment 4Dept. Electrical Eng. & Electronics Page 2 / 4 University of LiverpoolObjectivesTo design, implement and document modular programs that use functions and I/O files.AssessmentThis assignment is an assessed component and the mark for this work will contribute towardsthe overall module mark. The weight of Assignment 4 is 12%. The marking criteria can befound in the Exam Resources section of ELEC129 in VITAL.This assignment is composed of a number of exercises. The relative weight of each exercise onthe overall assignment mark is indicated between brackets.InstructionsStudents are required to do all exercises and submit a single Word file in the Assessmentsection of ELEC129 in VITAL (https://vital.liv.ac.uk) by Monday 04/03/2019 at 17:00 (5pm) UKlocal time (week 6 of semester 2). Delay penalties apply. Please double check your report andmake sure your work is in its final form before submission as the online application will notallow resubmissions. Email submissions and/or resubmissions will not be accepted.Submissions must be a single Word file containing the work done by the student (studentname and student ID should be clearly stated in the first page). The file must contain twoparts for each exercise proposed in this assignment as detailed below.Part I: The first part must contain the source code. Please use font Courier New with a size of 8points, use indentation to make the code readable, and observe the following requirements: The source code must be the result of your own original and individual work. The source code must be entirely written in the C programming language. Source codewritten in any other programming languages (e.g., C++) will receive a mark of zero. The use of global variables is (in general) not needed in ELEC129 assignments and itsuse is not allowed unless otherwise stated. All variables should be local to a function(i.e., declared within the body of a function). The use of global variables will bepenalised. If you are in doubt, ask a lab demonstrator to check your source code. All exercises can be solved based on concepts explained in previous lectures. Studentsare allowed to use concepts from other (future) chapters but this is not expected. Feelfree to discuss your approach to solving the exercises with a lab demonstrator.Part II: The second part must contain a detailed explanation of the software developmentprocess followed by the student (i.e., the first five steps of the software development method): ...

October 9, 2021 · 6 min · jiezi

关于c:100ASKIMX6ULLPRO开发板QT移植过程说明

百问网对于 Qt 的移植过程没有做非常具体且零碎的阐明,导致初学者的我在移植时破费了较多工夫,特此写下此文给有须要的人参考。下述阐明基于百问网提供的环境进行形容 (网上搜寻到的个别是在全新环境进行构建)。一、应用repo获取内核及工具链等1. 配置repo下载 repo 工具前须要设置git的邮箱和用户名,git邮箱和用户名请依据集体状况进行配置。 book@100ask:~$ git config --global user.email "user@100ask.com"book@100ask:~$ git config --global user.name "100ask"留神: 请先配置git邮箱和用户名,否则会导致下载失败(如下为参考示例图)。 2. 下载源码执行以下4条命令,为不便大家复制,第3条是很长的命令,应用了\来换行,须要一并拷贝: book@100ask:~$ git clone https://e.coding.net/codebug8/repo.gitbook@100ask:~$ mkdir -p 100ask_imx6ull-sdk && cd 100ask_imx6ull-sdkbook@100ask:~/100ask_imx6ull-sdk$ ../repo/repo init -u \ https://gitee.com/weidongshan/manifests.git -b \linux-sdk -m imx6ull/100ask_imx6ull_linux4.9.88_release.xml --no-repo-verifybook@100ask:~/100ask_imx6ull-sdk$ ../repo/repo sync -j4留神: 是在 book@100ask:~$ 目录下执行的操作 二、配置穿插编译工具链1. 设置穿插工具链关上配置文件 vim ~/.bashrc, 在文件开端增加以下命令 export ARCH=armexport CROSS_COMPILE=arm-buildroot-linux-gnueabihf-export PATH=$PATH:/home/book/100ask_imx6ull-sdk/ToolChain/arm-buildroot-linux-gnueabihf_sdk-buildroot/bin设置结束后,要执行 source ~/.bashrc 命令使其失效,这条命令是加载这些设置的环境变量 2. 测试穿插工具链测试环境变量: book@100ask:~$ echo $ARCHarmbook@100ask:~$ echo $CROSS_COMPILEarm-buildroot-linux-gnueabihf-测试穿插编译器: book@100ask:~$ arm-buildroot-linux-gnueabihf-gcc -v ...

October 9, 2021 · 2 min · jiezi

关于c++:C-gRPC-Quick-Start

简介gRPC是一种由Google推出的RPC框架,开源,跨语言,跨平台,高性能。 gRPC次要是基于protobuf设计实现的。 本文次要介绍如何在C++中应用gRPC。 装置不像Java,配置一个maven插件,增加相应的maven依赖,就能够搭建好gRPC环境。 C++个别须要下载gRPC的源码,而后编译构建,失去须要的库文件,protoc编译器,以及gRPC插件。 下载源码git clone --recurse-submodules -b v1.41.0 https://github.com/grpc/grpccd grpc创立cmake构建目录mkdir -p cmake/buildcd cmake/build生成makefilecmake -DgRPC_INSTALL=ON \ -DgRPC_BUILD_TESTS=OFF \ -DCMAKE_INSTALL_PREFIX=$MY_INSTALL_DIR \ ../..MY_INSTALL_DIR变量指定了最终生成的库文件,protoc的装置地位,linux零碎个别为/usr/local 构建make -j装置make install此命令会依据第三部指定的MY_INSTALL_DIR的,将构建进去的库装置到相应的地位。比方protoc就放在${MY_INSTALL_DIR}/bin目录下, 头文件就放在${MY_INSTALL_DIR}/include/grpc目录下。 当然,执行上述命令须要装置g++, cmake, git等工具。 HelloWorld应用gRPC首先须要写proto文件,形容rpc,供客户端和服务端应用。 proto文件接口定义hello.proto // protobuf版本syntax = "proto3";// rpc申请的定义message HelloRequest { optional string name = 1;}// rpc响应的定义message HelloReply { optional string message = 1;}// rpc服务的定义,两个函数service HelloWorld { rpc SayHello (HelloRequest) returns (HelloReply) {} rpc SayHelloAgain (HelloRequest) returns (HelloReply) {}}服务端proto仅定义了接口,还须要在服务端写程序,实现rpc。server.cc #include "hello.grpc.pb.h"#include <string>#include <grpcpp/grpcpp.h>// rpc服务实现class HelloServiceImpl : public HelloWorld::Service{ grpc::Status SayHello(grpc::ServerContext* context, const HelloRequest* req, HelloReply* rsp) { std::cout << "Request SayHello From " << context->peer() << std::endl; rsp->set_message("hello " + req->name() + "!"); return grpc::Status::OK; } grpc::Status SayHelloAgain(grpc::ServerContext* context, const HelloRequest* req, HelloReply* rsp) { std::cout << "Request SayHelloAgain From " << context->peer() << std::endl; rsp->set_message("hello " + req->name() + " again!!"); return grpc::Status::OK; }};// 启动运行int main(int argc, char** argv){ std::string address("localhost:5000"); HelloServiceImpl service; grpc::ServerBuilder builder; builder.AddListeningPort(address, grpc::InsecureServerCredentials()); builder.RegisterService(&service); std::unique_ptr<grpc::Server> server(builder.BuildAndStart()); std::cout << "Server Listening on port: " << address << std::endl; server->Wait(); return 0;}客户端客户端调用服务端的,client.cc ...

October 8, 2021 · 2 min · jiezi

关于c:C进阶15逻辑运算符

Summary1)&&表达式从左向右计算,当遇到条件为假时,整个表达式为假,前面的表达式都不再执行,是为短路规定; 2) ||表达式从左向右计算,当遇到条件为真时,整个表达式为真,前面的表达式都不再执行,是为短路规定; 3)逻辑表达式中&&比||的优先级更高,体现为:当&&和||在同一个表达式中呈现时,整个表达式被看作一个||表达式。先计算&&表达式,最初计算整个的||表达式,某个表达式为真的时候,整个||表达式就短路了。 4)C语言中的逻辑非"!"只意识0(假),其余的任何值都是非0(真)。"!"罕用于if语句中判断表达式是否为假;也可用于将一个整数变为1,如!!100; 逻辑运算符的荫蔽知识点1、&& 和 || 中的短路规定|| 从左向右开始计算:当遇到条件为真时进行计算,整个表达式为真;所有条件都为假时表达式才为假 int LogicFunc(int i){ printf("LogicFunc(int i) : %d\n", i); return i;}int main(){ if(LogicFunc(1) || LogicFunc(0)) { printf("Logic expression is true"); } else { printf("Logic expression is false"); }}输入:LogicFunc(int i) : 1Logic expression is true起因:逻辑||表达式的短路规定,第1个表达式LogicFunc(1)返回1,为true,第二个表达式因为短路规定并未执行&& 从左向右开始计算:当遇到条件为假时进行计算,整个表达式为假;所有条件都为真时表达式才为真 int LogicFunc(int i){ printf("LogicFunc(int i) : %d\n", i); return i;}int main(){ if(LogicFunc(0) && LogicFunc(1)) { printf("Logic expression is true"); } else { printf("Logic expression is false"); }}输入:LogicFunc(int i) : 0Logic expression is false起因:逻辑&&表达式的短路规定,第1个表达式LogicFunc(0)返回0,false,第二个表达式因为短路规定并未执行2、&& 和 || 混合运算时的规定逻辑表达式中&&比||的优先级更高,体现为:当&&和||在同一个表达式中呈现时,整个表达式被看作一个||表达式。先计算&&,最初计算||。 ...

October 7, 2021 · 1 min · jiezi

关于c:鸿蒙内核源码分析双向链表篇-谁是内核最重要结构体-开篇致敬鸿蒙内核开发者-v111

子曰:“见贤思齐焉,见不贤而内自省也。” 《论语》:里仁篇 百篇博客系列篇.本篇为: v01.xx 鸿蒙内核源码剖析(双向链表篇) | 谁是内核最重要构造体 根底工具相干篇为:v01.xx 鸿蒙内核源码剖析(双向链表) | 谁是内核最重要构造体v19.xx 鸿蒙内核源码剖析(位图治理) | 谁能一分钱分两半花v20.xx 鸿蒙内核源码剖析(用栈形式) | 程序运行场地由谁提供v31.xx 鸿蒙内核源码剖析(定时器) | 哪个工作的优先级最高v34.xx 鸿蒙内核源码剖析(原子操作) | 谁在为原子操作保驾护航v35.xx 鸿蒙内核源码剖析(工夫治理) | 谁是内核根本工夫单位谁是鸿蒙内核最重要的构造体?答案肯定是: LOS_DL_LIST(双向链表),它长这样. typedef struct LOS_DL_LIST {//双向链表,内核最重要构造体 struct LOS_DL_LIST *pstPrev; /**< Current node's pointer to the previous node *///前驱节点(左手) struct LOS_DL_LIST *pstNext; /**< Current node's pointer to the next node *///后继节点(右手)} LOS_DL_LIST;构造体够简略了吧,只有前后两个指向本人的指针,但恰好是因为太简略,所以才太不简略. 就像氢原子一样,宇宙中无处不在,占比最高,起因是因为它最简略,最稳固! 内核的各个模块都能看到双向链表的身影,下图是各处初始化双向链表的操作,因为太多了,只截取了局部: 很多人问图怎么来的, source insight 4.0 是浏览大型C/C++工程的必备工具,要用4.0否则中文有乱码. [下载 source insight 4.0 破解版] ...

October 7, 2021 · 3 min · jiezi

关于c:CSE-232-C语言编程

CSE 232 Spring 2019Programming Project 05Assignment OverviewThis assignment is worth 40 points (4.0% of the course grade) and must be completed and turnedin before 11:59pm on Monday, Feb 25th. That's two weeks because of the midterm on Thur, Feb14th.BackgroundSteganographySteganography (https://en.wikipedia.org/wiki...) is the process of hiding a "secretmessage" in another text file, image or even sound file. It differs from cryptography in that theoverall file/video/audio looks reasonably normal and still conveys information, making it hard totell that there is a secret hidden inside. We are going to write a steganographic encoder/decoderfor text.A Simple SteganographyWe are going to take a plaintext message, one that anyone can read, and embed in that message asecret message which someone, who knows the code, can decipher.The process is this. We are going to take the plaintext message, reduce the plaintext message toall lower case, then encode the secret message in the plaintext based on combinations ofUPPER or lower case. Thus it is the sequence of upper and lower case letters in the plaintextmessage that encode our secret message.We do this as follows. Each individual letter of the secret message is turned into a binary stringof 5 0's and 1's. Exactly 5 for each letter. We will only recognize letters and will ignore any othercharacters in the secret message. For each of these binary strings, we take the next 5 letters of theplaintext and modify them as follows: for every 0 in the secret message binary string we lowercase the plaintext letter, for every 1 we upper case the letter. We do this only for letters, ignoringall other characters in the plaintext. Let's consider the following example. The secret message is"help " and the original text is "Mom please send more money!" The index of each letter is itsposition in the alphabet with 'a' at 0, 'z' at 25.Secret letter 'h' 'e' 'l' 'p'Letter index 7 4 11 15binary 00111 00100 01011 01111Encoded 5 letters moM PL eaSe s eNd MO rE MONThe new message, with the encoded secret message would be (hard to write with autocorrect)"moM PLeaSe seNd MOrE MONey!". As we said, we can only capitalize letters so we ignore(don’t count as one of the 5 letters) any other character in the plaintext message which just getspassed through unaltered.Reverse the process for decoding: take 5 letters from the encoded plaintext, ignoring any othercharacters, determine the binary string the capitalization indicates, and add the new letter thatbinary string represents as the next letter of the secret message.Rules of the Process. we ignore non-alphabetic characters in the plaintext and pass them through to theencoded text as is. we also ignore any non-alphabetic characters in the secret message. Those non-alphabeticcharacters will not be encoded. Thus spaces will be lost in decoding the secret message,as will any numbers of punctuation marks. if there are "left over" letters in the plaintext, letters we do not require to encode a portionof the secret message) we just pass them through into the encoded text unchanged. if there are not enough letters in the plaintext to encode the secret message, that is anerror condition and we indicate as such and quit. We mentioned that, if there are more letters than necessary to encode the secret messagein the plaintext, then we just pass the "extra" letters through. On decoding that may creategarbage at the end of our decoded message. That’s OKASCIIAs a note, you don't need a string to turn a letter into an index number. The index order of anascii letter can be found by subtracting the character 'a' from any other lower-case letter. Thusthe letter 'f' is index 5, found by 'f' – 'a' . You did this in lab last week.Program Specificationsstring lower_case(string s) returns the lower case version of the input string s, that is all alphabetic characters areconverted to lower case.string to_binary(char c) returns 5 bit string that is the index of the character argument.o if the provided character is not a lower-case alphabetic character, return the emptystring.char from_binary(string bit_str) returns the character that the 5 bit binary string bit_str represents.o if any of the following conditions are not true: the size of bit_str is 5 every element of bit_str must be a ‘1’ or a ‘0’ the character produced must be a lower case letter return the character 0 (the NULL char).bool check_message(string plaintext, string secret_message) returns true if there are at least 5x the count of characters in secret_message as inplaintext, false otherwise? Remember, only alphabetic characters matter, all other characters in the plaintext areignored. We are counting whether there are enough useable characters in plaintext.string encode(string plaintext, string secret_message) plaintext and secret_message should be converted to lower case by lower_case the plaintext string should have been checked by check_messageo if check_message is false, return the string "Error". otherwise returns encoded_text encoded (as described) with the secret_message.string decode(string to_decode) returns the original secret_message as a string.o if there were more characters in to_decode than 5*characters in thesecret_message, you will get extra ‘a’ characters at the end of the decodedmessage.o if the number of characters in to_decode is not a multiple of 5, it will be ragged.By that I mean that you will get 4 or less characters at the end of to_decode. Sincewe cannot turn those characters into a secret_message character (we need 5),they should be ignored.DeliverablesYou will turn in one file: proj05_functions.cpp inside a directory names proj05 .Weprovide you with proj05_functions_05.h , as well as a main proj05_main.cpp youcan use to test your functions. However, Mimir can test the individual functions without a mainprogram which is how the tests are structured. It is still a good idea for you to test your own codewith a main. This will be the last time we provide you with a main you can use to test yourfunctions. You should start doing that yourself.Remember to include your section, the date, project number and comments and you do notprovide main.cpp. If you turn in a main with your code Mimir it will be ignored. ...

October 6, 2021 · 6 min · jiezi

关于c:C语言实现三子棋

C语言实现三子棋(通过数组)须要蕴含的头文件 include <stdio.h>include <stdlib.h>include <time.h>创立一个全局数组因为如果数组大小变动,游戏规则和实现思路都会有很大的变动,所以不进行宏定义常量来定义数组char board3;设计主程序框架game()函数为游戏过程框架int main(){ do{ int i = 0; printf("1.Start the game\n"); printf("2.Quit the game\n"); printf("Please enter your options->"); scanf("%d", &i); switch (i) { case 1: game(); //game()函数为游戏过程框架 break; case 2: return 0; default: printf("Input error,please enter again!\n"); break; }} while(1);}设计游戏过程框架void game(){ initBoard();srand((unsigned)time(NULL)); //生成随机种子,前面须要生成随机坐标char temp = ' '; //定义一个字符变量,用于接管前面判断函数返回值,用于决定游戏输赢do{ printBoard(); //打印棋盘的函数 userPlay(); //玩家下棋的函数 temp = judge(); //判断游戏是否分出输赢 if (temp != ' ') break; robotPlay(); //电脑下棋的函数 temp = judge();} while (temp == ' ');printBoard();switch (temp){ case '@': printf("User WIN!\n"); break; case '$': printf("Bobot WIN!\n"); break; case '*': printf("Dogfall !\n"); break; dafault: break;}}设计棋盘款式有趣味的能够搞的更加花里胡哨,这里草草了事,呸,简略设计一下 哈//##########// | | //_|_|_// | | //_|_|_// | |//##########打印棋盘重点就在这了,棋盘设计的再牛逼,也得能打印进去才行这里棋盘设计的比拟繁难,打印起来也比较简单,要害是思路要清晰void printBoard(){ ...

October 3, 2021 · 2 min · jiezi

关于c++:CISC235-Data-Structures

CISC-235 Data StructuresAssignment 2February 5, 20191 ProblemsIn this assignment, you will implement a binary search tree structure and associatedfunctions. The goal of this assignment is to: get familiar with the implementation of a binary (search) tree.use stacks (you need to implement the stack ADT as well).get familiar with iterative/recursive operations on a binary (search) tree.1.1 Implementation of Stack Using Array-based List: 10pointsCreate a class named Stack using array-based list provided by a particularprogramming language (e.g., List in Python). Your class should contain aninitialization function, as well as the following functions (we just mention thename of each function, you need determine what is the input): isEmpty, this function checks whether the current Stack instance is empty.It should return true if the Stack is empty. push, this function should takes a data item as input and add it into theStack. pop, this function should return the data item on the top of the currentStack and remove it from the Stack. top, this function should return the data item on the top of the currentStack without modifying the Stack. size, this function should return the number of data items in the Stack.11.2 Implementation a Binary Search Tree: 80 pointsBinary search tree (BST) is a special type of binary tree which satisfies thebinary search property, i.e., the key in each node must be greater than any keystored in the left sub-tree, and less than any key stored in the right sub-tree.See a sample binary search tree below:Figure 1: Binary Search Tree 1Your task is to create a class named BinarySearchTree satisfying the followingrequirements (you can create more instance variables if you want):1) Each node inside the BST has at least these attributes: value(data storedin the node), leftChild (reference to another node), and rightChild (referenceto another node)2) Must have an insert function (i.e., insert a new node). You may assumethat the values to be stored in the tree are integers.3) Must have a searchPath function that returns a list of all the values visitedon the search path. For example, on a particular tree T, T.searchPath(10)might return 8, 20, 15, 14, 10.4) Must have a getTotalDepth function that computes the sum of thedepths of all nodes in the tree. Your getTotalDepth function should runin O(n) time. Hint: if a node knows its own depth, it can tell its childrenwhat their depth is. Each node can add its own depth to the total depthreported by its children, and return that sum. The value returned by theroot will be the total depth of the tree.5) Mush have a getWeightBalanceFactor function. The weight balancefactor of a binary tree is a measure of how well-balanced it is, i.e., howevenly its nodes are distributed between the left and right subtrees ofeach node. More specifically, weight balance factor of a binary tree is themaximum value of the absolute value of (number of nodes in left subtreenumberof nodes in right subtree) for all nodes in the tree. For example,given the binary search tree shown in Figure 2, your function should returnalthough if you just look at the root node, the difference in the numberof nodes in the left subtree and right subtree is 1.2Figure 2: Binary Search Tree 21.3 Reconstruct a Binary Search Tree From a File Usinga Stack: 30 pointsCreate a loadTreeFromFile function in the above BinarySearchTree class.This function takes a String filename as input, and return a BinarySearchTreeobject. The file list the nodes of the tree in post-order sequence, one node perline. Each line contains a string which is the data value stored in the node, andtwo other 0/1 tags. The first tag indicates whether or not this node has a leftchild, the second tag indicates whether the node has a right child. For example,to reconstruct the sample binary search tree in Figure 1, the input file containsthe following lines:0 00 01 10 00 11 1The above information is sufficient to uniquely determine any binary tree.The tree can be reconstructed from the file using the following algorithm:create empty stack of BinarySearchTreewhile there is another line of input in the file:read a line (containing data and 2 tags)if the second tag is 1, pop an element from the stack and call itright_treeif the first tag is 1, pop an element from the stack and call itleft_treecrate a new binary search tree with data as its root and left_treeand right_tree as its subtrees (if they exist)push the new tree onto your stackWhen you exit the while loop, the stack should contains one element and that3is the tree you want to return. Note that you should check the second tag(indicating if the node has right child or not) first. And if your right tree andleft tree is empty, you should create a new tree with only one node, i.e., theroot node. You should use the Stack you created in Section 1.1.1.4 Test Code and Style: 30 pointsYou must comment your code, and write test code. In your test code, youshould:1) Reconstruct a binary search tree T (should be the one shown in Figure 1)by reading a file containing the lines shown in Section 1.3.2) Calculate the total depth of T.3) Calculate the Weight Balance Factor of T.4) Insert a new value, i.e., 5, into T.5) Print path of searching the value 5.6) Calculate the total depth of T.7) Calculate the Weight Balance Factor of T.Assignment RequirementsThis assignment is to be completed individually (we have the right to run anyclone detection tool). You need submit your documented source code (Stackclass + BinarySearchTree class + test code). If you have multiple files, pleasecombine all of them into a .zip archive and submit it to OnQ system. The .ziparchive should contain your student number. Deadline: Feb-18 12:00am, 2019.WX:codehelp

October 3, 2021 · 5 min · jiezi

关于c:c学习笔记-Dynamic-Thesky

1.int整型相除后果取整舍小数 2.两个小数不能做取模运算 3.前置递增++a:让变量a(此处为a)+1 前置与后置递增的区别:前置先让变量+1而后进行表达式运算 4.非真即假,a=10,10>0为真;!a=0,a取反则为假即为0,!!a非假值为1(非零则为真) 5.switch语句中只能放整型或字符 6.while循环当条件为真时才执行,在"输入0-9"的实例中,当num实现while循环后其值为10 7.rand() % 100 //此处将会随机生成一个0-99的数字(rand为伪随机) 8.获取三位数的个位:对数字取模于10十位:先整除10在取模于10(解析:先转化为两位数在进行获取个位数的操作)百位:除以100 9.若应用优化好的支流编译器则在循环内定义变量不会被反复调配 10.嵌套循环中的i能够重复使用,可能是独立于循环中的,编译器容许套娃,然而最好不要,会升高程序可读性.(套娃循环) 11.嵌套循环中输入的雷同的变量(例如i),存在就近准则,即输入最近的i 12.在初始化数组数据的时候,没有填写的数据(间断的开端的数)会用0补充 13.内存地址是随机调配 ,每次运行都会产生扭转 14.数组名是常量不能进行赋值 15.指针本质是用于保留地址的变量,但因起非凡用处所以另起概念,某种层面上:指针==变量==地址 16.&:取址 *取值,指针在指向数组的时候可不加&//详见第29条,在指向数组中某一元素的时候用& 17.解援用: 把地址对应的内容解进去,并 援用 ; 即p== p(指针)对应(或指向)的内容(p就是p对用内容的援用) 18.空指针好比:int a = 0,然而指针开始的时候没有地址给他"指",指向null就和给a赋的值0的意义差不多 19.函数中参数为数组时,数组主动进化成数组中第一个数据的首地址,:arr[i] == *(arr+i)即拜访arr[第一个数据+i]中的数据;这也是为什么i<len(数组长度)的起因,因为传递的形参是第一个数据的地址,此时数组的数据个数就等于len-1.(留神点:第一个数组计数点为0;用数组长度//假设为3;求最初一个元素则示意为3-1//0,1,2中2是最初一个元素,但他有三个元素所以须要减1) 20.构造体:创立构造体变量的时候关键字可省略,而构造体变量定义的时候不可省略 21.在main()函数里定义的同名变量会屏蔽掉main函数外的全局变量,(在外定义的是全局在内定义的是部分,) 22.当局部变量被定义时,零碎不会对其初始化,您必须自行对其初始化。定义全局变量时,零碎会主动初始化为下列值[int 0char ''float、double 0.0pointer nullptr (C语言是NULL)//NULL和nullptr在指针层面上代表的都是空值,然而因为Null自身是宽泛意义上的空值(0之类的)所带来的在c++上的局限性,c++定义了一种新的专门的空指针值类型] 23.在函数内应用同名的全局变量和局部变量:在全局变量之前加上域名解析则援用全局变量(::a是全局)24.static润饰的全局动态变量只在以后源文件内应用;动态修饰符用于将函数内的值从栈区放到全局区(不会因为来到作用域而被开释或回收掉),变为全局变量,能够返回该变量并可在内部操作该变量 25.在一个文件中有某变量的定义,则在其余应用到该变量的文件中应申明该变量(此时不可赋值) 26.一般数组中以数组名用cout来输入,只会失去一串地址;用字符数组则会输入数组中的内容. 27.指针不同的数据类型指向的变量或常量的数据类型不同,能够记为:某类型的指针指向同类型的数据 28.形参为指向实参地址的指针,当对形参的指向操作时,就相当于对实参自身进行的操作 &height[0] 就是获得是数组第一个元素的地址,假如地址为 1000;&height 是间接对数组名进行取地址,这个时候就是获得是 height 整个数组的地址,指向蕴含 10 个元素的 int 型数组,height 等价于 &height[0],height+1 会将地址加 4 个字节(不肯定是四个,视类型而定);但 &height+1 就是将地址减少 10*4 个字节(取地址符优先级大于加号个,故取地址符依照其结合律先与height联合之后对联合值进行加1操作)30.传递参数和传递地址的区别:传递参数时复制实参,如果传入数据过多会影响执行效率;当传递参数过多时应用传递地址,这样只传入四个字节,或者用facetoface 31.类的权限分为:私有、公有、爱护权限,私有权限类内和类外都能够拜访,爱护和公有只能类内拜访(区别在于爱护权限子对象也能够拜访,而公有权限子对象不能够拜访),类内拜访即应用构造函数:例如在函数体内应用赋值语句"属性 = 内部变量",而后通过调用该函数实现类内拜访 ...

October 3, 2021 · 1 min · jiezi

关于c:在写矩阵转换时发现的一个for循环括号的问题

在写矩阵转换时发现的一个for循环的问题最近在写c语言作业的一个矩阵转换的时候,程序运行没有问题,但输入总是存在问题。起初与敌人探讨了一下,最初发现问题存在于for循环的括号问题。以此记录一下,不便学习。 以上是问题代码,输入后果如下 咱们来细分一下代码 #include <stdio.h>int main(){ int i,j,t; int a[3][3] = {{1,2,3},{4,5,6},{7,8,9}}; for(i=0;i<3;i++) for(j=0;j<3;j++) printf("%d",a[i][j]); /*输入原始矩阵*/ printf("\n"); 以下为该代码输入后果 为什么会呈现这样呢?在c primer外面讲述for循环的定义是这样的: for(condition1;condition2;condition3) statement也就是说执行主体的完结靠的是statement的完结,即一个语句的完结。天然,下面的代码它只思考了第二个for循环外面的printf语句,而没有执行转行命令。(\n) 在存在多个逻辑语句的状况下,for循环外面须要用到大括号,即:{} 咱们扭转一下代码,试试看 for(i=0;i<3;i++) for(j=0;j<3;j++) { printf("%d",a[i][j]); /*输入原始矩阵*/ printf("\n"); }后果如下: 很显著,咱们在第二个for循环外面加了大括号,换行指令立即在第二个for循环中执行了。 咱们再改一下,看一看。 for(i=0;i<3;i++){ for(j=0;j<3;j++) printf("%d",a[i][j]); /*输入原始矩阵*/ printf("\n");}输入后果如下: 很显著,在整体的for循环外面(第一个for循环),它先执行了第二个for循环外面的指令,在第二个for循环外面的指令实现了,实现了换行。 一个清晰明了的例子: 很显著,他是先遍历完一个for才输入test的,阐明test的输入语句和遍历输入不在一个for下的。 总之,咱们都要养成写一个工整代码的习惯,这不仅是为了不便他人查看,更是为了日后咱们了解本人的代码,比方我当初写代码的时候,根本在for循环都会加个括号,这样会不便我了解代码是在哪个模块运行的。同时,缩进也显得十分重要,对于你了解本人的代码来说。 感激:DynamicLab - The_sky

October 3, 2021 · 1 min · jiezi