language
large_stringclasses
1 value
text
stringlengths
9
2.95M
C
/** * @file * * The unit tests execution binary. * * @author Sergio Benitez * @date 09/03/2014 */ #include "test.h" /** * The main function. Simply calls the test utils begin_testing function, which * sets up the testing world and calls the _main_test_function. * * @param argc Number of command line arguments. * @param argv Command line arguments. * * @return 0 on success, nonzero otherwise */ int main(int argc, const char *argv[]) { return begin_testing(argc, argv); } /** * The _main_test_function. This function is delcared via the BEGIN_TESTING * macro for easy testing. * * The main test function takes one parameter as a pointer: the result. The main * test function should set result to true if all test suites pass (which * implies all tests pass). If not all test suites pass, it should set result to * false. * * The helper macro/function run_suite can manage the pointer's state when the * main test function function is declared using the appropriate parameter names * as is done by BEGIN_TESTING. The function must be named _main_test_function. * * @param[out] _result Set to true if all test suites pass, false otherwise. */ BEGIN_TESTING { run_suite(extra_credit_create_file_tests); run_suite(extra_credit_delete_file_tests); run_suite(extra_credit_rename_file_tests); }
C
#include <stdio.h> #include <stdlib.h> char isLetter(char a) { if (('a' <= a && a <= 'z') || ('' <= a && a <= '')) { return a; } else if ('A' <= a && a <= 'Z') { return a - ****; } else if ('' <= a && a <= '') { return a - ****; } else { return 0; } } int main() { int i = 0; FILE *in = stdin; while (!feof(in)) { char a; fscanf(in, "%c", &a); if (isLetter(a)) { if (i) { char *word = (char*) malloc (sizeof(char) * (i + 2)); word[i] = a; word[i + 1] = 0; } else } } }
C
#include<stdio.h> #include<conio.h> void main() { int a,s,d,sum=0,i,lt; printf("enter the first number of A.P:"); scanf("%d",&a); printf("enter the totalnumber of A.P:"); scanf("%d",&s); printf("enter the difference of A.P:"); scanf("%d",&d); sum=(s*(2*a+(s-1)*d))/2; lt=a+(s-1)*d; printf(" %d sum of A.P series:"); for(i=a;i<=lt;i=i+d) { if(i!=lt) printf("%d+",i); else printf("%d=%d",i,sum); } getch(); }
C
#include <stdio.h> #include <stdlib.h> #include <netdb.h> #include <string.h> #include <unistd.h> #include <arpa/inet.h> #include <sys/types.h> #include <netinet/in.h> #include <sys/socket.h> #include <errno.h> #define MAXRCVLEN 1024 #define PORTNUM 5555 int main(int argc, char *argv[]) { char *msg; msg = malloc(256); char buffer[MAXRCVLEN + 1]; /* +1 so we can add null terminator */ int len, mysocket; struct sockaddr_in dest; int numrv; int opt; mysocket = socket(AF_INET, SOCK_STREAM, 0); memset(&dest, 0, sizeof(dest)); /* zero the struct */ dest.sin_family = AF_INET; dest.sin_addr.s_addr = INADDR_ANY; //htonl((in_addr_t)0xc0a889fd); dest.sin_port = htons(PORTNUM); /* set destination port number */ printf("Client/destination add:%s\n", inet_ntoa(dest.sin_addr)); int consocket = connect(mysocket, (struct sockaddr *)&dest, sizeof(struct sockaddr)); printf("Press\t 1 - VOIP\n\t 2 - CHAT\n"); scanf("%d", &opt); if (opt == 1) { while (1) { len = recv(mysocket, buffer, MAXRCVLEN, 0); /* We have to null terminate the received data ourselves */ buffer[len] = '\0'; printf("::: %s\n", buffer); printf("\n:"); scanf("%s", msg); send(mysocket, msg, strlen(msg), 0); } } else { while (1) { printf("Recieving File...\n"); filerecv(consocket); wait(5000); } } close(mysocket); return EXIT_SUCCESS; } int filerecv(mysocket) { int bytesReceived = 0; char recvBuff[256]; memset(recvBuff, '0', sizeof(recvBuff)); FILE *fp; fp = fopen("sample_text.txt", "ab"); if (NULL == fp) { printf("Error opening file"); return 1; } while ((bytesReceived = read(mysocket, recvBuff, 256)) > 0) { printf("Bytes received %d\n", bytesReceived); fwrite(recvBuff, 1, bytesReceived, fp); printf("re writting\n"); } if (bytesReceived < 0) { printf("\n Read Error \n"); } return 0; }
C
#include"game.h" void menu() { printf("**********************************\n"); printf("***** 1.play *****\n"); printf("***** 0.exit *****\n"); printf("**********************************\n"); } void game() { //printf("ɨϷ\n");//һϷɣ⡣ //1.׵Ϣ洢 char mine[ROWS][COLUMNS];//1.ѾúõϢ char show[ROWS][COLUMNS];//2.ŲϢ //2.ʼ̣ Initialize_board(mine,ROWS,COLUMNS,'0');//ʼmine Initialize_board(show,ROWS,COLUMNS,'*');//ʼshow //3.ӡ̣ //Display_board(mine, ROW, COLUMN);//ӡmine Display_board(show, ROW, COLUMN);//ӡshow //4.ף Set_mine(mine,ROW,COLUMN); Display_board(mine, ROW, COLUMN);//Ƿ񱻲ú //5.ɨף Find_mine(mine, show, ROW, COLUMN); } void test() { srand((unsigned)time(NULL));// int intput = 0; do { menu(); printf("ѡ:>"); scanf("%d", &intput); switch (intput) { case 1: game(); break; case 0: printf("˳Ϸ\n"); break; default: printf("룡\n"); break; } } while (intput); } int main() { test(); return 0; }
C
/* * simple shell */ #include "os.h" #define MAXARGS 24 #define MAXLINE 128 void eval(char *cmd); void parseline(char *buf, char **argv); int buildin_command(char **argv); int main(void) { char cmd[MAXLINE]; while (1) { printf("> "); Fgets(cmd, MAXLINE, stdin); if (feof(stdin)) { exit(0); } eval(cmd); } return 0; } void eval(char *cmd) { char *argv[MAXARGS]; /* argument list of execve */ char buf[MAXLINE]; /* hold modified command line */ pid_t pid; strcpy(buf, cmd); parseline(buf, argv); if (argv[0] == NULL) { return; /* Ignore empty lines */ } if (!buildin_command(argv)) { if ((pid = Fork()) == 0) { if (execve(argv[0], argv, NULL) < 0) { printf("%s: Command not found.\n", argv[0]); exit(0); } } } // reap zombie if (wait(NULL) < 0) { unix_error("reap error!"); } return; } /* real C! */ void parseline(char *buf, char **argv) { char *delim; int argc; buf[strlen(buf)-1] = ' '; /* replace trailing '\n' */ while (*buf && (*buf == ' ')) { buf++; } /* build argument list */ argc = 0; while ((delim = strchr(buf, ' '))) { argv[argc++] = buf; *delim = '\0'; buf = delim + 1; while (*buf && (*buf == ' ')) { buf++; /* Ignore spaces */ } } argv[argc] = NULL; } int buildin_command(char **argv) { if (!strcmp(argv[0], "quit")) { exit(0); } return 0; }
C
#include <stdio.h> int main() { int l,n; scanf("%d",&l); scanf("%d",&n); int w[n]; int h[n]; int i; for(i=0;i<n;i++) { scanf("%d%d",&w[i],&h[i]); } for (i=0;i<n;i++) { if (w[i]<l || h[i]<l) { printf("UPLOAD ANOTHER\n"); } else if(w[i]==h[i]) { printf("ACCEPTED\n"); } else { printf("CROP IT\n"); } } }
C
#include<stdio.h> #include<string.h> struct k { char name[100]; int id; char phno[13]; char acno[13]; long int inc; }d; int authent(char a[],int b,int c) { int cnt=0,i=0; FILE *p; p=fopen("C:\\Users\\user\\Documents\\file\\PR0.txt","r+"); while(i<c) { fscanf(p,"%s%d%s%s%*d",d.name,&d.id,d.phno,d.acno); if((strcmp(d.phno,a)==0 || strcmp(d.acno,a)==0)&&(d.id==b)) { cnt=1; printf(" WELCOME %s\n",d.name); return cnt; break; } i++; } } int authent2(char a[],char b[],int c) { int cnt=0,i=0; FILE *p; p=fopen("C:\\Users\\user\\Documents\\file\\PR0.txt","r+"); while(i<c) { fscanf(p,"%*s%*d%s%s%*d",d.phno,d.acno); if((strcmp(d.acno,a)==0 || strcmp(d.phno,b)==0)) { cnt=1; return cnt; break; } i++; } }
C
#include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <string.h> #include <arpa/inet.h> #include <sys/socket.h> #include <fcntl.h> #include <sys/sendfile.h> #define BUF_SIZE 1024 #define SMALL_BUF 100 char webpage[] = "HTTP/1.1 200 OK\r\n" "Server:Linux Web Server\r\n" "Content-Type: text/html; charset=UTF-8\r\n\r\n" "<!DOCTYPE html>\r\n" "<html><head><title> My Web Page </title>\r\n" "<style>body {background-color: #0101DF }</style></head>\r\n" "<body><center><h1>Hello World!!</h1><br>\r\n" "<img src=\"dog.jpg\"></center></body></html>\r\n"; void error_handling(char* message); int main(int argc, char* argv[]) { struct sockaddr_in serv_adr, clnt_adr; int serv_sock, clnt_sock; int sin_len; char buf[BUF_SIZE]; int fdimg; char img_buf[500000]; if (argc != 2) { printf("Usage : %s <port>\n", argv[0]); exit(1); } //fdimg = fopen("dog.txt", "rb"); serv_sock = socket(PF_INET, SOCK_STREAM, 0); memset(&serv_adr, 0, sizeof(serv_adr)); serv_adr.sin_family = AF_INET; serv_adr.sin_addr.s_addr = htonl(INADDR_ANY); serv_adr.sin_port = htons(atoi(argv[1])); if (bind(serv_sock, (struct sockaddr*)&serv_adr, sizeof(serv_adr)) == -1) error_handling("bind() error"); if (listen(serv_sock, 20) == -1) error_handling("listen() error"); while (1) { clnt_sock = accept(serv_sock, (struct sockaddr*)&clnt_adr, &sin_len); printf("Connection...."); read(clnt_sock, buf, 2047); printf("%s\n", buf); if (!strncmp(buf, "GET /dog.jpg", 12)) { fdimg = open("dog.jpg", O_RDONLY); read(fdimg, img_buf, sizeof(img_buf)); write(clnt_sock, img_buf, sizeof(img_buf)); close(fdimg); } else write(clnt_sock, webpage, sizeof(webpage) - 1); puts("closing...."); } close(clnt_sock); close(serv_sock); return 0; } void error_handling(char* message) { fputs(message, stderr); fputc('\n', stderr); exit(1); }
C
/* Escreva programa para resolver uma equação de segundo grau, dados os valores dos coeficientes a, b, c ( equação: y = a*x*x + b*x + c) */ #include <stdio.h> #include <stdlib.h> #include <math.h> int main() { float a, b, c; // variaveis de entrada float delta, x1, x2; printf("EQUACAO DO SEGUNDO GRAU\n"); printf("Insira os valores de a, b e c: "); scanf("%f %f %f", &a, &b, &c); printf("\na = %.1f b = %.1f c = %.1f\n\n", a, b, c); delta = b*b - 4 * a * c; if (delta >= 0) { delta = sqrt(delta); x1 = (-b + delta) / (2 * a); x2 = (-b - delta) / (2 * a); printf("x1 = %.4f / x2 = %.4f\n\n", x1, x2); } else { delta = delta * (-1); delta = sqrt(delta); delta = delta / (2 * a); b = -b / (2 * a); printf("x1 = %.4f + %.4f*i / x2 = %.4f - %.4f*i\n\n", b, delta, b, delta); } return 0; }
C
#ifndef LLIST_H #define LLIST_H #include <stdlib.h> struct llist{ long type; struct llist* next; }; typedef struct llist llist; llist* llist_head ; void ll_add( llist* head, long element); void ll_remove( llist* head, long element); int ll_isIn( llist* head, long element); int ll_isEmpty( llist* head); void ll_print( llist* head); #endif
C
// // RegularExpressionExample.h // pangu // // Created by King on 2017/4/15. // Copyright © 2017年 zby. All rights reserved. // /* 1.验证数字: 只能输入1个数字 表达式 ^\d$ 描述 匹配一个数字 匹配的例子 0,1,2,3 不匹配的例子 2.只能输入n个数字 表达式 ^\d{n}$ 例如^\d{8}$ 描述 匹配8个数字 匹配的例子 12345678,22223334,12344321 不匹配的例子 3.只能输入至少n个数字 表达式 ^\d{n,}$ 例如^\d{8,}$ 描述 匹配最少n个数字 匹配的例子 12345678,123456789,12344321 不匹配的例子 4.只能输入m到n个数字 表达式 ^\d{m,n}$ 例如^\d{7,8}$ 描述 匹配m到n个数字 匹配的例子 12345678,1234567 不匹配的例子 123456,123456789 5.只能输入数字 表达式 ^[0-9]*$ 描述 匹配任意个数字 匹配的例子 12345678,1234567 不匹配的例子 E,清清月儿 6.只能输入某个区间数字 表达式 ^[12-15]$ 描述 匹配某个区间的数字 匹配的例子 12,13,14,15 不匹配的例子 7.只能输入0和非0打头的数字 表达式 ^(0|[1-9][0-9]*)$ 描述 可以为0,第一个数字不能为0,数字中可以有0 匹配的例子 12,10,101,100 不匹配的例子 01,清清月儿,http://blog.csdn.net/21aspnet 8.只能输入实数 表达式 ^[-+]?\d+(\.\d+)?$ 描述 匹配实数 匹配的例子 18,+3.14,-9.90 不匹配的例子 .6,33s,67-99 9.只能输入n位小数的正实数 表达式 ^[0-9]+(.[0-9]{n})?$以^[0-9]+(.[0-9]{2})?$为例 描述 匹配n位小数的正实数 匹配的例子 2.22 不匹配的例子 2.222,-2.22,http://blog.csdn.net/21aspnet 10.只能输入m-n位小数的正实数 表达式 ^[0-9]+(.[0-9]{m,n})?$以^[0-9]+(.[0-9]{1,2})?$为例 描述 匹配m到n位小数的正实数 匹配的例子 2.22,2.2 不匹配的例子 2.222,-2.2222,http://blog.csdn.net/21aspnet 11.只能输入非0的正整数 表达式 ^\+?[1-9][0-9]*$ 描述 匹配非0的正整数 匹配的例子 2,23,234 不匹配的例子 0,-4, 12.只能输入非0的负整数 表达式 ^\-[1-9][0-9]*$ 描述 匹配非0的负整数 匹配的例子 -2,-23,-234 不匹配的例子 0,4, 13.只能输入n个字符 表达式 ^.{n}$ 以^.{4}$为例 描述 匹配n个字符,注意汉字只算1个字符 匹配的例子 1234,12we,123清,清清月儿 不匹配的例子 0,123,123www,http://blog.csdn.net/21aspnet/ 14.只能输入英文字符 表达式 ^.[A-Za-z]+$为例 描述 匹配英文字符,大小写任意 匹配的例子 Asp,WWW, 不匹配的例子 0,123,123www,http://blog.csdn.net/21aspnet/ 15.只能输入大写英文字符 表达式 ^.[A-Z]+$为例 描述 匹配英文大写字符 匹配的例子 NET,WWW, 不匹配的例子 0,123,123www, 16.只能输入小写英文字符 表达式 ^.[a-z]+$为例 描述 匹配英文大写字符 匹配的例子 asp,csdn 不匹配的例子 0,NET,WWW, 17.只能输入英文字符+数字 表达式 ^.[A-Za-z0-9]+$为例 描述 匹配英文字符+数字 匹配的例子 1Asp,W1W1W, 不匹配的例子 0,123,123,www,http://blog.csdn.net/21aspnet/ 18.只能输入英文字符/数字/下划线 表达式 ^\w+$为例 描述 匹配英文字符或数字或下划线 匹配的例子 1Asp,WWW,12,1_w 不匹配的例子 3#,2-4,w#$,http://blog.csdn.net/21aspnet/ 19.密码举例 表达式 ^.[a-zA-Z]\w{m,n}$ 描述 匹配英文字符开头的m-n位字符且只能数字字母或下划线 匹配的例子 不匹配的例子 20.验证首字母大写 表达式 \b[^\Wa-z0-9_][^\WA-Z0-9_]*\b 描述 首字母只能大写 匹配的例子 Asp,Net 不匹配的例子 http://blog.csdn.net/21aspnet/ 21.验证网址(带?id=中文)VS.NET2005无此功能 表达式 ^http:\/\/([\w-]+(\.[\w-]+)+(\/[\w- .\/\?%&=\u4e00-\u9fa5]*)?)?$ 描述 验证带?id=中文 匹配的例子 http://blog.csdn.net/21aspnet/, http://blog.csdn.net?id=清清月儿 不匹配的例子 22.验证汉字 表达式 ^[\u4e00-\u9fa5]{0,}$ 描述 只能汉字 匹配的例子 清清月儿 不匹配的例子 http://blog.csdn.net/21aspnet/ 23.验证QQ号 表达式 [0-9]{5,9} 描述 5-9位的QQ号 匹配的例子 10000,123456 不匹配的例子 10000w,http://blog.csdn.net/21aspnet/ 24.验证电子邮件(验证MSN号一样) 表达式 \w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)* 描述 注意MSN用非hotmail.com邮箱也可以 匹配的例子 [email protected] 不匹配的例子 111@1. http://blog.csdn.net/21aspnet/ 25.验证身份证号(粗验,最好服务器端调类库再细验证) 表达式 ^[1-9]([0-9]{16}|[0-9]{13})[xX0-9]$ 描述 匹配的例子 15或者18位的身份证号,支持带X的 不匹配的例子 http://blog.csdn.net/21aspnet/ 26.验证手机号(包含159,不包含小灵通) 表达式 ^13[0-9]{1}[0-9]{8}|^15[9]{1}[0-9]{8} 描述 包含159的手机号130-139 匹配的例子 139XXXXXXXX 不匹配的例子 140XXXXXXXX,http://blog.csdn.net/21aspnet/ 27.验证电话号码号(很复杂,VS.NET2005给的是错的) 表达式(不完美) 方案一 ((\(\d{3}\)|\d{3}-)|(\(\d{4}\)|\d{4}-))?(\d{8}|\d{7}) 方案二 (^[0-9]{3,4}\-[0-9]{3,8}$)|(^[0-9]{3,8}$)|(^\([0-9]{3,4}\)[0-9]{3,8}$)|(^0{0,1}13[0-9]{9}$) 支持手机号但也不完美 描述 上海:02112345678 3+8位 上海:021-12345678 上海:(021)-12345678 上海:(021)12345678 郑州:03711234567 4+7位 杭州:057112345678 4+8位 还有带上分机号,国家码的情况 由于情况非常复杂所以不建议前台做100%验证,到目前为止似乎也没有谁能写一个包含所有的类型,其实有很多情况本身就是矛盾的。 如果谁有更好的验证电话的请留言 匹配的例子 不匹配的例子 28.验证护照 表达式 (P\d{7})|G\d{8}) 描述 验证P+7个数字和G+8个数字 匹配的例子 不匹配的例子 清清月儿,http://blog.csdn.net/21aspnet/ 29.验证IP 表达式 ^(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[1-9])\.(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[1-9]|0)\.(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[1-9]|0)\.(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[0-9])$ 描述 验证IP 匹配的例子 192.168.0.1 222.234.1.4 不匹配的例子 30.验证域 表达式 ^[a-zA-Z0-9]+([a-zA-Z0-9\-\.]+)?\.s|)$ 描述 验证域 匹配的例子 csdn.net baidu.com it.com.cn 不匹配的例子 192.168.0.1 31.验证信用卡 表达式 ^((?:4\d{3})|(?:5[1-5]\d{2})|(?:6011)|(?:3[68]\d{2})|(?:30[012345]\d))[ -]?(\d{4})[ -]?(\d{4})[ -]?(\d{4}|3[4,7]\d{13})$ 描述 验证VISA卡,万事达卡,Discover卡,美国运通卡 匹配的例子 不匹配的例子 32.验证ISBN国际标准书号 表达式 ^(\d[- ]*){9}[\dxX]$ 描述 验证ISBN国际标准书号 匹配的例子 7-111-19947-2 不匹配的例子 33.验证GUID全球唯一标识符 表达式 ^[A-Z0-9]{8}-[A-Z0-9]{4}-[A-Z0-9]{4}-[A-Z0-9]{4}-[A-Z0-9]{12}$ 描述 格式8-4-4-4-12 匹配的例子 2064d355-c0b9-41d8-9ef7-9d8b26524751 不匹配的例子 34.验证文件路径和扩展名 表达式 ^([a-zA-Z]\:|\\)\\([^\\]+\\)*[^\/:*?"<>|]+\.txt(l)?$ 描述 检查路径和文件扩展名 匹配的例子 E:\mo.txt 不匹配的例子 E:\ , mo.doc, E:\mo.doc ,http://blog.csdn.net/21aspnet/ 35.验证Html颜色值 表达式 ^#?([a-f]|[A-F]|[0-9]){3}(([a-f]|[A-F]|[0-9]){3})?$ 描述 检查颜色取值 匹配的例子 #FF0000 不匹配的例子 http://blog.csdn.net/21aspnet/ ^[1-9]\d*\.\d*|0\.\d*[1-9]\d*$ 整数或者小数:^[0-9]+\.{0,1}[0-9]{0,2}$ 只能输入数字:"^[0-9]*$"。 只能输入n位的数字:"^\d{n}$"。 只能输入至少n位的数字:"^\d{n,}$"。 只能输入m~n位的数字:。"^\d{m,n}$" 只能输入零和非零开头的数字:"^(0|[1-9][0-9]*)$"。 只能输入有两位小数的正实数:"^[0-9]+(.[0-9]{2})?$"。 只能输入有1~3位小数的正实数:"^[0-9]+(.[0-9]{1,3})?$"。 只能输入非零的正整数:"^\+?[1-9][0-9]*$"。 只能输入非零的负整数:"^\-[1-9][]0-9"*$。 只能输入长度为3的字符:"^.{3}$"。 只能输入由26个英文字母组成的字符串:"^[A-Za-z]+$"。 只能输入由26个大写英文字母组成的字符串:"^[A-Z]+$"。 只能输入由26个小写英文字母组成的字符串:"^[a-z]+$"。 只能输入由数字和26个英文字母组成的字符串:"^[A-Za-z0-9]+$"。 只能输入由数字、26个英文字母或者下划线组成的字符串:"^\w+$"。 验证用户密码:"^[a-zA-Z]\w{5,17}$"正确格式为:以字母开头,长度在6~18之间,只能包含字符、数字和下划线。 验证是否含有^%&',;=?$\"等字符:"[^%&',;=?$\x22]+"。 只能输入汉字:"^[\u4e00-\u9fa5]{0,}$" 验证Email地址:"^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$"。 验证InternetURL:"^http://([\w-]+\.)+[\w-]+(/[\w-./?%&=]*)?$"。 验证电话号码:"^(\(\d{3,4}-)|\d{3.4}-)?\d{7,8}$"正确格式为:"XXX-XXXXXXX"、"XXXX-XXXXXXXX"、"XXX-XXXXXXX"、"XXX-XXXXXXXX"、"XXXXXXX"和"XXXXXXXX"。 验证身份证号(15位或18位数字):"^\d{15}|\d{18}$"。 验证一年的12个月:"^(0?[1-9]|1[0-2])$"正确格式为:"01"~"09"和"1"~"12"。 验证一个月的31天:"^((0?[1-9])|((1|2)[0-9])|30|31)$"正确格式为;"01"~"09"和"1"~"31"。 匹配中文字符的正则表达式: [\u4e00-\u9fa5] 匹配双字节字符(包括汉字在内):[^\x00-\xff] 匹配空行的正则表达式:\n[\s| ]*\r 匹配html标签的正则表达式:<(.*)>(.*)<\/(.*)>|<(.*)\/> 匹配首尾空格的正则表达式:(^\s*)|(\s*$) 匹配Email地址的正则表达式:\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)* 匹配网址URL的正则表达式:http://([\w-]+\.)+[\w-]+(/[\w- ./?%&=]*)? 手机号码:(^(\d{3,4}-)?\d{7,8})$|(13[0-9]{9})|(15[8-9]{9}) 不会的也可以根据上面介绍的写出来了吧,只是得花点时间了。 验证数字的正则表达式集 验证数字:^[0-9]*$ 验证n位的数字:^\d{n}$ 验证至少n位数字:^\d{n,}$ 验证m-n位的数字:^\d{m,n}$ 验证零和非零开头的数字:^(0|[1-9][0-9]*)$ 验证有两位小数的正实数:^[0-9]+(.[0-9]{2})?$ 验证有1-3位小数的正实数:^[0-9]+(.[0-9]{1,3})?$ 验证非零的正整数:^\+?[1-9][0-9]*$ 验证非零的负整数:^\-[1-9][0-9]*$ 验证非负整数(正整数 + 0) ^\d+$ 验证非正整数(负整数 + 0) ^((-\d+)|(0+))$ 验证长度为3的字符:^.{3}$ 验证由26个英文字母组成的字符串:^[A-Za-z]+$ 验证由26个大写英文字母组成的字符串:^[A-Z]+$ 验证由26个小写英文字母组成的字符串:^[a-z]+$ 验证由数字和26个英文字母组成的字符串:^[A-Za-z0-9]+$ 验证由数字、26个英文字母或者下划线组成的字符串:^\w+$ 验证用户密码:^[a-zA-Z]\w{5,17}$ 正确格式为:以字母开头,长度在6-18之间,只能包含字符、数字和下划线。 验证是否含有 ^%&',;=?$\" 等字符:[^%&',;=?$\x22]+ 验证汉字:^[\u4e00-\u9fa5],{0,}$ 验证Email地址:^\w+[-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$ 验证InternetURL:^http://([\w-]+\.)+[\w-]+(/[\w-./?%&=]*)?$ ;^[a-zA-z]+://(w+(-w+)*)(.(w+(-w+)*))*(?S*)?$ 验证电话号码:^(\(\d{3,4}\)|\d{3,4}-)?\d{7,8}$:--正确格式为:XXXX-XXXXXXX,XXXX-XXXXXXXX,XXX-XXXXXXX,XXX-XXXXXXXX,XXXXXXX,XXXXXXXX。 验证身份证号(15位或18位数字):^\d{15}|\d{}18$ 验证一年的12个月:^(0?[1-9]|1[0-2])$ 正确格式为:“01”-“09”和“1”“12” 验证一个月的31天:^((0?[1-9])|((1|2)[0-9])|30|31)$ 正确格式为:01、09和1、31。 整数:^-?\d+$ 非负浮点数(正浮点数 + 0):^\d+(\.\d+)?$ 正浮点数 ^(([0-9]+\.[0-9]*[1-9][0-9]*)|([0-9]*[1-9][0-9]*\.[0-9]+)|([0-9]*[1-9][0-9]*))$ 非正浮点数(负浮点数 + 0) ^((-\d+(\.\d+)?)|(0+(\.0+)?))$ 负浮点数 ^(-(([0-9]+\.[0-9]*[1-9][0-9]*)|([0-9]*[1-9][0-9]*\.[0-9]+)|([0-9]*[1-9][0-9]*)))$ 浮点数 ^(-?\d+)(\.\d+)? */ /* 一、校验数字的表达式 1 数字:^[0-9]*$ 2 n位的数字:^\d{n}$ 3 至少n位的数字:^\d{n,}$ 4 m-n位的数字:^\d{m,n}$ 5 零和非零开头的数字:^(0|[1-9][0-9]*)$ 6 非零开头的最多带两位小数的数字:^([1-9][0-9]*)+(.[0-9]{1,2})?$ 7 带1-2位小数的正数或负数:^(\-)?\d+(\.\d{1,2})?$ 8 正数、负数、和小数:^(\-|\+)?\d+(\.\d+)?$ 9 有两位小数的正实数:^[0-9]+(.[0-9]{2})?$ 10 有1~3位小数的正实数:^[0-9]+(.[0-9]{1,3})?$ 11 非零的正整数:^[1-9]\d*$ 或 ^([1-9][0-9]*){1,3}$ 或 ^\+?[1-9][0-9]*$ 12 非零的负整数:^\-[1-9][]0-9"*$ 或 ^-[1-9]\d*$ 13 非负整数:^\d+$ 或 ^[1-9]\d*|0$ 14 非正整数:^-[1-9]\d*|0$ 或 ^((-\d+)|(0+))$ 15 非负浮点数:^\d+(\.\d+)?$ 或 ^[1-9]\d*\.\d*|0\.\d*[1-9]\d*|0?\.0+|0$ 16 非正浮点数:^((-\d+(\.\d+)?)|(0+(\.0+)?))$ 或 ^(-([1-9]\d*\.\d*|0\.\d*[1-9]\d*))|0?\.0+|0$ 17 正浮点数:^[1-9]\d*\.\d*|0\.\d*[1-9]\d*$ 或 ^(([0-9]+\.[0-9]*[1-9][0-9]*)|([0-9]*[1-9][0-9]*\.[0-9]+)|([0-9]*[1-9][0-9]*))$ 18 负浮点数:^-([1-9]\d*\.\d*|0\.\d*[1-9]\d*)$ 或 ^(-(([0-9]+\.[0-9]*[1-9][0-9]*)|([0-9]*[1-9][0-9]*\.[0-9]+)|([0-9]*[1-9][0-9]*)))$ 19 浮点数:^(-?\d+)(\.\d+)?$ 或 ^-?([1-9]\d*\.\d*|0\.\d*[1-9]\d*|0?\.0+|0)$ 二、校验字符的表达式 1 汉字:^[\u4e00-\u9fa5]{0,}$ 2 英文和数字:^[A-Za-z0-9]+$ 或 ^[A-Za-z0-9]{4,40}$ 3 长度为3-20的所有字符:^.{3,20}$ 4 由26个英文字母组成的字符串:^[A-Za-z]+$ 5 由26个大写英文字母组成的字符串:^[A-Z]+$ 6 由26个小写英文字母组成的字符串:^[a-z]+$ 7 由数字和26个英文字母组成的字符串:^[A-Za-z0-9]+$ 8 由数字、26个英文字母或者下划线组成的字符串:^\w+$ 或 ^\w{3,20}$ 9 中文、英文、数字包括下划线:^[\u4E00-\u9FA5A-Za-z0-9_]+$ 10 中文、英文、数字但不包括下划线等符号:^[\u4E00-\u9FA5A-Za-z0-9]+$ 或 ^[\u4E00-\u9FA5A-Za-z0-9]{2,20}$ 11 可以输入含有^%&',;=?$\"等字符:[^%&',;=?$\x22]+ 12 禁止输入含有~的字符:[^~\x22]+ 三、特殊需求表达式 1 Email地址:^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$ 2 域名:[a-zA-Z0-9][-a-zA-Z0-9]{0,62}(/.[a-zA-Z0-9][-a-zA-Z0-9]{0,62})+/.? 3 InternetURL:[a-zA-z]+://[^\s]* 或 ^http://([\w-]+\.)+[\w-]+(/[\w-./?%&=]*)?$ 4 手机号码:^(13[0-9]|14[5|7]|15[0|1|2|3|5|6|7|8|9]|18[0|1|2|3|5|6|7|8|9])\d{8}$ 5 电话号码("XXX-XXXXXXX"、"XXXX-XXXXXXXX"、"XXX-XXXXXXX"、"XXX-XXXXXXXX"、"XXXXXXX"和"XXXXXXXX):^(\(\d{3,4}-)|\d{3.4}-)?\d{7,8}$ 6 国内电话号码(0511-4405222、021-87888822):\d{3}-\d{8}|\d{4}-\d{7} 7 身份证号(15位、18位数字):^\d{15}|\d{18}$ 8 短身份证号码(数字、字母x结尾):^([0-9]){7,18}(x|X)?$ 或 ^\d{8,18}|[0-9x]{8,18}|[0-9X]{8,18}?$ 9 帐号是否合法(字母开头,允许5-16字节,允许字母数字下划线):^[a-zA-Z][a-zA-Z0-9_]{4,15}$ 10 密码(以字母开头,长度在6~18之间,只能包含字母、数字和下划线):^[a-zA-Z]\w{5,17}$ 11 强密码(必须包含大小写字母和数字的组合,不能使用特殊字符,长度在8-10之间):^(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{8,10}$ 12 日期格式:^\d{4}-\d{1,2}-\d{1,2} 13 一年的12个月(01~09和1~12):^(0?[1-9]|1[0-2])$ 14 一个月的31天(01~09和1~31):^((0?[1-9])|((1|2)[0-9])|30|31)$ 15 钱的输入格式: 16 1.有四种钱的表示形式我们可以接受:"10000.00" 和 "10,000.00", 和没有 "分" 的 "10000" 和 "10,000":^[1-9][0-9]*$ 17 2.这表示任意一个不以0开头的数字,但是,这也意味着一个字符"0"不通过,所以我们采用下面的形式:^(0|[1-9][0-9]*)$ 18 3.一个0或者一个不以0开头的数字.我们还可以允许开头有一个负号:^(0|-?[1-9][0-9]*)$ 19 4.这表示一个0或者一个可能为负的开头不为0的数字.让用户以0开头好了.把负号的也去掉,因为钱总不能是负的吧.下面我们要加的是说明可能的小数部分:^[0-9]+(.[0-9]+)?$ 20 5.必须说明的是,小数点后面至少应该有1位数,所以"10."是不通过的,但是 "10" 和 "10.2" 是通过的:^[0-9]+(.[0-9]{2})?$ 21 6.这样我们规定小数点后面必须有两位,如果你认为太苛刻了,可以这样:^[0-9]+(.[0-9]{1,2})?$ 22 7.这样就允许用户只写一位小数.下面我们该考虑数字中的逗号了,我们可以这样:^[0-9]{1,3}(,[0-9]{3})*(.[0-9]{1,2})?$ 23 8.1到3个数字,后面跟着任意个 逗号+3个数字,逗号成为可选,而不是必须:^([0-9]+|[0-9]{1,3}(,[0-9]{3})*)(.[0-9]{1,2})?$ 24 备注:这就是最终结果了,别忘了"+"可以用"*"替代如果你觉得空字符串也可以接受的话(奇怪,为什么?)最后,别忘了在用函数时去掉去掉那个反斜杠,一般的错误都在这里 25 xml文件:^([a-zA-Z]+-?)+[a-zA-Z0-9]+\\.[x|X][m|M][l|L]$ 26 中文字符的正则表达式:[\u4e00-\u9fa5] 27 双字节字符:[^\x00-\xff] (包括汉字在内,可以用来计算字符串的长度(一个双字节字符长度计2,ASCII字符计1)) 28 空白行的正则表达式:\n\s*\r (可以用来删除空白行) 29 HTML标记的正则表达式:<(\S*?)[^>]*>.*?</\1>|<.*? /> (网上流传的版本太糟糕,上面这个也仅仅能部分,对于复杂的嵌套标记依旧无能为力) 30 首尾空白字符的正则表达式:^\s*|\s*$或(^\s*)|(\s*$) (可以用来删除行首行尾的空白字符(包括空格、制表符、换页符等等),非常有用的表达式) 31 腾讯QQ号:[1-9][0-9]{4,} (腾讯QQ号从10000开始) 32 中国邮政编码:[1-9]\d{5}(?!\d) (中国邮政编码为6位数字) 33 IP地址:\d+\.\d+\.\d+\.\d+ (提取IP地址时有用) 34 IP地址:((?:(?:25[0-5]|2[0-4]\\d|[01]?\\d?\\d)\\.){3}(?:25[0-5]|2[0-4]\\d|[01]?\\d?\\d)) */
C
#include <stdio.h> #include <stdlib.h> typedef struct temp{ int Data; struct temp* pointer; } Fila; Fila* beginning = NULL; Fila* ending = NULL; Fila* pointer = NULL; int head = 0 , tail = 0; void Queue(int Data){ if(beginning == NULL){ ending = beginning = (Fila*)malloc(sizeof(Fila)); tail = 1; }else{ ending = ending->pointer = (Fila*)malloc(sizeof(Fila)); tail++; } ending->Data = Data; } void ShowQueue(){ int x = 1; pointer = beginning; if(head == tail) puts("Fila vazia"); while(pointer->pointer != NULL){ printf("%d. %d\n", x++, pointer->Data); pointer = pointer-> pointer; } } void DeQueue(){ if(beginning == NULL) return; else if(beginning == ending){ free(beginning); pointer = ending = beginning = NULL; }else{ pointer = beginning->pointer; free(beginning); beginning = pointer; } head++; } int main(int argc, char* argv[]){ int data; for(int i=0; i<10; i++){ Queue(i*3); } ShowQueue(); puts("======================================"); DeQueue(); ShowQueue(); puts("======================================"); DeQueue(); ShowQueue(); puts("======================================"); return 0; }
C
/* * Ronald Rey Lovera ([email protected]) * Smailyn Peña Núñez ([email protected]) * Última modificación: Viernes 30 de agosto de 2013 * Rover bot, Hands-On Competition, Intec * Versión Final * Ingeniería Mecatrónica */ #include <Servo.h> #include <QTRSensors.h> #include <stdio.h> #include <math.h> // Represents a duty cycle of 100% //#define MAX_SPEED 255 const int MAX_SPEED = 255; const int REDUCED_SPEED = 40; // Output pins for motors #define RIGHT_MOTOR_FWD 8 #define RIGHT_MOTOR_RV 7 #define LEFT_MOTOR_RV 9 #define LEFT_MOTOR_FWD 10 #define BIAS 20 // Servo #define SERVO_PIN 3 #define OPEN 90 #define CLOSED 45 Servo gripper; // Box management logic variables #define SAMPLE_AMOUNT 10 #define SENSOR_THRESHOLD (1<<10)/2 boolean stopReached = false; boolean boxGrabbed = false; boolean whiteBox = false; boolean directions[] = {}; int directinosCount = 0; // Constants for the PID Control float Kp = 125, Kd = 14, Ki = 0; #define INIT_DELAY 0 // Sensors PINS #define NUM_SENSORS 8 // number of sensors used #define NUM_SAMPLES_PER_SENSOR 4 // average 4 analog samples per sensor reading #define EMITTER_PIN QTR_NO_EMITTER_PIN // emitter is controlled by digital pin 2 #define BOX_SENSOR 8 unsigned int sensorValues[NUM_SENSORS]; const float SENSOR_POS[] = {0, 1, 2, 3, 4, 5, 6, 7}; const int SENSOR_PINS[] = {0, 1, 2, 3, 4, 5, 6, 7}; QTRSensorsAnalog qtra((unsigned char[]) {0, 1, 2, 3, 4, 5, 6, 7}, // sensors 0 through 7 are connected to analog inputs 0 through 7, respectively NUM_SENSORS, NUM_SAMPLES_PER_SENSOR, EMITTER_PIN); void TurnLeft() { // Set LEFT to REVERSE and // RIGHT to FORWARD analogWrite(LEFT_MOTOR_RV, MAX_SPEED - BIAS - REDUCED_SPEED); analogWrite(LEFT_MOTOR_FWD, 0); analogWrite(RIGHT_MOTOR_FWD, MAX_SPEED - REDUCED_SPEED); analogWrite(RIGHT_MOTOR_RV, 0); } void TurnRight() { // Set RIGHT to REVERSE and // LEFT to FORWARD analogWrite(LEFT_MOTOR_FWD, MAX_SPEED - BIAS - REDUCED_SPEED); analogWrite(LEFT_MOTOR_RV, 0); analogWrite(RIGHT_MOTOR_RV, MAX_SPEED - REDUCED_SPEED); analogWrite(RIGHT_MOTOR_FWD, 0); } void Stop() { analogWrite(LEFT_MOTOR_FWD, 0); analogWrite(LEFT_MOTOR_RV, 0); analogWrite(RIGHT_MOTOR_RV, 0); analogWrite(RIGHT_MOTOR_FWD, 0); } void Push() { analogWrite(LEFT_MOTOR_FWD, MAX_SPEED); analogWrite(RIGHT_MOTOR_FWD, MAX_SPEED); analogWrite(LEFT_MOTOR_RV, 0); analogWrite(RIGHT_MOTOR_RV, 0); } void Retreat() { analogWrite(LEFT_MOTOR_RV, MAX_SPEED); analogWrite(RIGHT_MOTOR_RV, MAX_SPEED); analogWrite(LEFT_MOTOR_FWD, 0); analogWrite(RIGHT_MOTOR_FWD, 0); } // Adjusts the speed of the left and right motors by // varying the PWM duty cycle according to the control signal. // The control signal represents how far right or left the // robot has to turn, not the speed of of the motors. void Drive(float u, boolean showSpeeds = false) { // The PWM frequency is approx. 490 Hz if (u < 0) { analogWrite(RIGHT_MOTOR_FWD, MAX_SPEED + u); analogWrite(LEFT_MOTOR_FWD, MAX_SPEED - BIAS); analogWrite(LEFT_MOTOR_RV, 0); analogWrite(RIGHT_MOTOR_RV, 0); if (showSpeeds) Serial.print("RIGHT = "), Serial.println(MAX_SPEED + u); } else { analogWrite(RIGHT_MOTOR_FWD, MAX_SPEED); analogWrite(LEFT_MOTOR_FWD, MAX_SPEED - u - BIAS); analogWrite(LEFT_MOTOR_RV, 0); analogWrite(RIGHT_MOTOR_RV, 0); if (showSpeeds) Serial.print("LEFT = "), Serial.println(MAX_SPEED - u - BIAS); } } float Sense(boolean show = false) { qtra.read(sensorValues); float sum_sensorWeight = 0.0; float sum_sensorVal = 0.0; for (int i = 0; i < NUM_SENSORS; i++) { if (sensorValues[i] < SENSOR_THRESHOLD) sensorValues[i] = 0; sum_sensorWeight += sensorValues[i]*SENSOR_POS[i]; sum_sensorVal += sensorValues[i]; if (show) Serial.print(sensorValues[i]), Serial.print('\t'); } if ( sum_sensorVal / NUM_SENSORS > SENSOR_THRESHOLD && millis() > 1000) { stopReached = true; // Check if box is white or black // take the average of many samples float sensorAvg = 0.0; for (int i = 0; i < SAMPLE_AMOUNT; i++) sensorAvg += analogRead( BOX_SENSOR ); sensorAvg /= SAMPLE_AMOUNT; /* if (sensorAvg > SENSOR_THRESHOLD) whiteBox = false; else whiteBox = true; */ if (whiteBox) whiteBox = false; else whiteBox = true; return 3.5; } float pos = sum_sensorWeight / sum_sensorVal; if (show) Serial.print(" | "), Serial.println(pos); return (3.5 - pos); } void Control() { static float INTEGRATION = 0; static float DERIVATION = 0; static float PREVERROR = Sense(); static float DELTATIME = 0; static long PREVTIME = millis(); // Control float e = Sense(); // Box management logic if (stopReached) { // ESTE IF SE ENCARGA DE AGARRAR LA CAJA Y REGRESAR CUANDO SE ENCUENTRA // CON UNA LINEA CRUZADA LA PRIMERA VEZ if (!boxGrabbed) { Stop(); delay(250); gripper.write(CLOSED); delay(500); //boxGrabbed = true; TurnRight(); // The first while is to keep the rover turning until // all the sensors are all above white surface. // The second is to keep it turning until it finds the line again. delay(100); while (!isnan(Sense())); delay(100); while (isnan(Sense())); } // ESTE ELSE SE ENCARGA DE DEJAR LA CAJA A UN LADO U OTRO, RETROCEDER, // Y LUEGO GIRAR Y REGRESAR LA SEGUNDA VEZ QUE SE ENCUENTRE CON UNA LINEA CRUZADA else { Stop(); delay(500); gripper.write(OPEN); delay(500); //boxGrabbed = false; // Turn for 0.25 secs, move backwards for 0.5 secs, // and then turn again until finds the line whiteBox ? TurnLeft() : TurnRight(); delay(250); Retreat(); delay(500); whiteBox ? TurnLeft() : TurnRight(); delay(500); } INTEGRATION = 0; DERIVATION = 0; PREVERROR = Sense(); e = PREVERROR; DELTATIME = 0; PREVTIME = millis() - PREVTIME; } long currTime = millis(); DELTATIME = (currTime - PREVTIME)/1000.0; PREVTIME = currTime; if (isnan(PREVERROR)) PREVERROR = e; DERIVATION = (e - PREVERROR)/DELTATIME; PREVERROR = e; INTEGRATION = (INTEGRATION + e*DELTATIME); if (isnan(INTEGRATION)) INTEGRATION = 0; float u = Kp*e; float D = Kd*DERIVATION; float I = Ki*INTEGRATION; if (!isnan(D)) u += D; if (!isnan(I)) u += I; // Limit control signal u to [-MAX_SPEED, MAX_SPEED] if (u > MAX_SPEED - BIAS) u = MAX_SPEED - BIAS; else if (u < -MAX_SPEED) u = -MAX_SPEED; if (stopReached) boxGrabbed = !boxGrabbed; stopReached = false; if (!isnan(u)) Drive(u, true); } void setup() { // For testing Serial.begin(9600); // Attaching gripper's servo motor gripper.attach(SERVO_PIN); gripper.write(OPEN); } void loop() { Control(); }
C
#include "Internal.h" // --------------------------------------------------- // --------------------------------------------------- // ---------- NEPTUNE METHODS ---------- // --------------------------------------------------- // --------------------------------------------------- void insertWindowIntoGlobalList(NeptuneWindow *window) { if (_neptune.windowListHead == NULL) { _neptune.windowListHead = window; return; } NeptuneWindow *tracer = _neptune.windowListHead; while (tracer->next != NULL) tracer = tracer->next; tracer->next = window; } // --------------------------------------------------- // --------------------------------------------------- // ---------- NEPTUNE PUBLIC API ---------- // --------------------------------------------------- // --------------------------------------------------- NEPTUNEAPI NeptuneWindow *neptuneCreateWindow(int width, int height, const char *title) { assert(title != NULL); assert(width >= 0); assert(height >= 0); _NEPTUNE_REQUIRE_INIT_OR_RETURN(NULL); NeptuneWindow *window = (NeptuneWindow *)malloc(sizeof(NeptuneWindow)); window->next = NULL; window->initwidth = width; window->initheight = height; window->title = title; window->resizable = NEPTUNE_TRUE; window->shouldClose = NEPTUNE_FALSE; window->keys = (NeptuneKeyState *)malloc((NEPTUNE_KEY_LAST + 1) * sizeof(NeptuneKeyState)); memset(window->keys, NEPTUNE_RELEASE, NEPTUNE_KEY_LAST + 1); window->mouse = (NeptuneButtonState *)malloc((NEPTUNE_MOUSE_LAST + 1) * sizeof(NeptuneButtonState)); memset(window->mouse, NEPTUNE_RELEASE, NEPTUNE_MOUSE_LAST + 1); memset(&window->callbacks, 0, sizeof(window->callbacks)); platformCreateWindow(window); insertWindowIntoGlobalList(window); return window; } NEPTUNEAPI void neptuneDestroyWindow(NeptuneWindow *window) { assert(window != NULL); _NEPTUNE_REQUIRE_INIT(); platformDestroyWindow(window); } NEPTUNEAPI void neptuneDestroyAllWindows() { _NEPTUNE_REQUIRE_INIT(); if (_neptune.windowListHead == NULL) return; while (_neptune.windowListHead != NULL) { NeptuneWindow *pointer = _neptune.windowListHead->next; neptuneDestroyWindow(_neptune.windowListHead); free(_neptune.windowListHead); _neptune.windowListHead = pointer; } } NEPTUNEAPI NeptuneBool neptuneWindowShouldClose(NeptuneWindow *window) { assert(window != NULL); _NEPTUNE_REQUIRE_INIT_OR_RETURN(NEPTUNE_FALSE); if (window->shouldClose) return window->shouldClose; else return NEPTUNE_FALSE; } NEPTUNEAPI void neptuneSetWindowWrapperPtr(NeptuneWindow *window, void *ptr) { assert(window != NULL); _NEPTUNE_REQUIRE_INIT(); window->wrapperPtr = ptr; } NEPTUNEAPI void *neptuneGetWindowWrapperPtr(NeptuneWindow *window) { assert(window != NULL); _NEPTUNE_REQUIRE_INIT_OR_RETURN(NULL); return window->wrapperPtr; } // --------------------------------------------------- // --------------------------------------------------- // ---------- NEPTUNE GETTER API ---------- // --------------------------------------------------- // --------------------------------------------------- NEPTUNEAPI void neptuneGetWindowSize(NeptuneWindow *window, int *width, int *height) { assert(window != NULL); _NEPTUNE_REQUIRE_INIT(); platformGetWindowSize(window, width, height); }
C
#include <stdlib.h> #include <string.h> #include <inttypes.h> #ifndef __KERNEL__ double strtod_soft( const char *nptr, char **endptr ) { int i, n; char *period_at; char *dash_at; char *exponent_at; char *ep = 0; int64_t ival, frac, div, exp; double f, f_frac; period_at = strchr(nptr, '.'); dash_at = strchr(nptr, '-'); exponent_at = strchr(nptr, 'e'); ival = strtoll(nptr, &ep, 10); f = (double)(ival); if (period_at == 0 || *(period_at+1) == 0) { /* No period, or period at the very end, treat as integer */ if (endptr) *endptr = ep; return f; } frac = strtoll(period_at+1, &ep, 10); /* Fractional part */ div = 1; if (endptr == 0) n = strlen(period_at + 1); else n = *endptr - period_at + 1; for (i = 0; i < n; i++) div *= 10; f_frac = (double)frac / (double)div; if (ival < 0 || (dash_at != 0 && dash_at < period_at)) { f -= f_frac; } else { f += f_frac; } /* Exponent */ if (endptr) *endptr = ep; if (exponent_at == 0 || *(exponent_at+1) == 0|| ep == 0 || exponent_at != ep) { return f; } n = strtoll(exponent_at+1, &ep, 10); if (n < 0) { div = 1; for (i = 0; i < n; i++) div *= 10; f /= (double)div; } else { exp = 1; for (i = 0; i < n; i++) exp *= 10; f *= (double)exp; } return f; } #endif
C
#include <stdio.h> #include <string.h> #include <stdlib.h> char** split_str(char* src, const char* delim, int* length) { char ** res = NULL; int n_delim = 0, i; char * p = strtok (src,delim); /* split string and append tokens to 'res' */ while (p) { res = realloc (res, sizeof (char*) * ++n_delim); if (res == NULL) exit (-1); /* memory allocation failed */ res[n_delim-1] = p; p = strtok (NULL,delim); } /* realloc one extra element for the last NULL */ res = realloc (res, sizeof (char*) * (n_delim+1)); res[n_delim] = 0; *length = n_delim; return res; } int main () { char src[] ="abc/qwe/ccd"; char ** dst; int i,length; printf("INPUT = %s\n",src); dst = split_str(src,"/",&length); printf("OUTPUT = \n"); for (i = 0; i < length; ++i) printf("%s\n", dst[i]); return 0; }
C
// P65 P66 ݿ #define DQ_H P6OUT|=BIT5 #define DQ_L P6OUT&=~BIT5 void delay_ms1(unsigned int t) { while(t--) { _NOP(); } } unsigned char Read_DS(void) { unsigned char i=0 ,v=0; for(i=8;i>0;i--) { P6DIR|=BIT5; DQ_L; v>>=1; DQ_H;//setfree bus P6DIR&=~BIT5; if((P6IN&BIT5)==BIT5) { v|=0x80; } delay_ms1(4); } P6DIR|=BIT5; return(v); } void Write_DS(unsigned char dat) { unsigned char i; for(i=0;i<8;i++) { P6DIR|=BIT5; DQ_L; if(dat&0x01) { DQ_H; } else { DQ_L; } delay_ms1(5); DQ_H; dat>>=1; } delay_ms(5); } void DS18B20_INIT(void) { P6DIR|=BIT5; DQ_H; //DQλ delay_ms1(8); //ʱ DQ_L; //ƬDQ delay_ms1(80); //ȷʱ 480us DQ_H; // P6DIR&=~BIT5; while((P6IN&BIT5)==BIT5); delay_ms1(20); //һҪʱ } unsigned int Read_T(void) { unsigned char a=0; unsigned int b=0; DS18B20_INIT(); Write_DS(0xcc); //Skip ROM Write_DS(0x44); //Start convert delay_ms1(200); DS18B20_INIT(); Write_DS(0xcc); Write_DS(0xbe); //read temp a=Read_DS(); //˳ȡ b=Read_DS(); b<<=8; b|=a; return (b); }
C
#pragma once inline float32x4_t accurate_rcp(float32x4_t x) { float32x4_t r = vrecpeq_f32(x); return vmulq_f32(vrecpsq_f32(x, r), r); } // approximation : lgamma(z) ~= (z+2.5)ln(z+3) - z - 3 + 0.5 ln (2pi) + 1/12/(z + 3) - ln (z(z+1)(z+2)) inline float32x4_t lgamma_ps(float32x4_t x) { float32x4_t x_3 = vaddq_f32(x, vmovq_n_f32(3)); float32x4_t ret = vmulq_f32(vaddq_f32(x_3, vmovq_n_f32(-0.5f)), Eigen::internal::plog(x_3)); ret = vsubq_f32(ret, x_3); ret = vaddq_f32(ret, vmovq_n_f32(0.91893853f)); ret = vaddq_f32(ret, vdivq_f32(vmovq_n_f32(1 / 12.f), x_3)); ret = vsubq_f32(ret, Eigen::internal::plog(vmulq_f32( vmulq_f32(vsubq_f32(x_3, vmovq_n_f32(1)), vsubq_f32(x_3, vmovq_n_f32(2))), x))); return ret; } // approximation : lgamma(z + a) - lgamma(z) = (z + a + 1.5) * log(z + a + 2) - (z + 1.5) * log(z + 2) - a + (1. / (z + a + 2) - 1. / (z + 2)) / 12. - log(((z + a) * (z + a + 1)) / (z * (z + 1))) inline float32x4_t lgamma_subt(float32x4_t z, float32x4_t a) { float32x4_t _1p5 = vmovq_n_f32(1.5); float32x4_t _2 = vmovq_n_f32(2); float32x4_t za = vaddq_f32(z, a); float32x4_t ret = vmulq_f32(vaddq_f32(za, _1p5), Eigen::internal::plog(vaddq_f32(za, _2))); ret = vsubq_f32(ret, vmulq_f32(vaddq_f32(z, _1p5), Eigen::internal::plog(vaddq_f32(z, _2)))); ret = vsubq_f32(ret, a); float32x4_t _1 = vmovq_n_f32(1); float32x4_t _1_12 = vmovq_n_f32(1 / 12.f); ret = vaddq_f32(ret, vsubq_f32(vdivq_f32(_1_12, vaddq_f32(za, _2)), vdivq_f32(_1_12, vaddq_f32(z, _2)))); ret = vsubq_f32(ret, Eigen::internal::plog(vdivq_f32(vdivq_f32(vmulq_f32(za, vaddq_f32(za, _1)), z), vaddq_f32(z, _1)))); return ret; } // approximation : digamma(z) ~= ln(z+4) - 1/2/(z+4) - 1/12/(z+4)^2 - 1/z - 1/(z+1) - 1/(z+2) - 1/(z+3) inline float32x4_t digamma_ps(float32x4_t x) { float32x4_t x_4 = vaddq_f32(x, vmovq_n_f32(4)); float32x4_t ret = Eigen::internal::plog(x_4); ret = vsubq_f32(ret, vdivq_f32(vmovq_n_f32(1 / 2.f), x_4)); ret = vsubq_f32(ret, vdivq_f32(vdivq_f32(vmovq_n_f32(1 / 12.f), x_4), x_4)); ret = vsubq_f32(ret, accurate_rcp(vsubq_f32(x_4, vmovq_n_f32(1)))); ret = vsubq_f32(ret, accurate_rcp(vsubq_f32(x_4, vmovq_n_f32(2)))); ret = vsubq_f32(ret, accurate_rcp(vsubq_f32(x_4, vmovq_n_f32(3)))); ret = vsubq_f32(ret, accurate_rcp(vsubq_f32(x_4, vmovq_n_f32(4)))); return ret; }
C
// // main.c // VTV4002-2 // // Created by Chel Long on 3/2/19. // Copyright © 2019 Chel Long. All rights reserved. // #include <stdio.h> void output (int a[], int n) { for (int i=0; i<n; i++) { printf("%d ", a[i]); } } void insertionSort(int s1[], int s2[], int n) { int key1, key2, j1, j2; for (int i=1; i<n; i++) { key1 = s1[i]; key2 = s2[i]; j1 = i -1; j2 = i -1; while (j1>=0 && s1[j1] > key1) { s1[j1+1] = s1[j1]; j1--; } while (j2>=0 && s2[j2] < key2) { s2[j2+1] = s2[j2]; j2--; } s1[j1+1] = key1; s2[j2+1] = key2; } } int main(int argc, const char * argv[]) { // insert code here... int n; scanf("%d", &n); int s1[n]; int s2[n]; for (int i=0; i<n; i++) { scanf("%d", &s1[i]); } for (int i=0; i<n; i++) { scanf("%d", &s2[i]); } insertionSort(s1, s2, n); output(s1, n); printf("\n"); output(s2, n); printf("\n"); return 0; }
C
//Ozan Gazi onder //windows version of homework 2 #include <stdio.h> #include <windows.h> int main(int argc,char *argv[]) { HANDLE handleIn1,handleIn2; HANDLE handleOut = GetStdHandle (STD_OUTPUT_HANDLE); DWORD nIn=0; DWORD nOut=0; DWORD countbyte = 0; char* buf; int size = 512; buf = (char*) HeapAlloc (GetProcessHeap(),0,size); if(buf == NULL) { printf ("Error!"); return 1; } printf ("\nWelcome to File Copy by Ozan!\n"); printf ("Enter the name of the source file:\n"); handleIn1 = CreateFile (argv[1], GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL); handleIn2 = CreateFile (argv[2], GENERIC_WRITE, FILE_SHARE_WRITE, NULL, CREATE_NEW, FILE_ATTRIBUTE_NORMAL, NULL); if ((handleIn1 == INVALID_HANDLE_VALUE) || (handleIn2 == INVALID_HANDLE_VALUE)) { printf("I can't open the file!"); return 2; } while (ReadFile (handleIn1, buf, size, &nIn, NULL) && nIn > 0) { WriteFile(handleIn2, buf, nIn, &nOut, NULL); if(nIn != nOut) { printf("contents is not copied, Error!"); return 4; } countbyte += nOut; } printf("File Copy was successful, with %d bytes copied.\n", countbyte); CloseHandle(handleIn1); CloseHandle(handleOut); }
C
#pragma once #include <pebble.h> #include "math_fixed.h" #include "gtypes.h" //! @addtogroup Graphics //! @{ //! @addtogroup GraphicsTransforms Transformation Matrices //! \brief Types for creating transformation matrices and utility functions to manipulate and apply //! the transformations. //! //! @{ ////////////////////////////////////// /// Creating Transforms ////////////////////////////////////// //! Convenience macro for GTransformNumber equal to 0 #define GTransformNumberZero ((GTransformNumber){ .integer = 0, .fraction = 0 }) //! Convenience macro for GTransformNumber equal to 1 #define GTransformNumberOne ((GTransformNumber){ .integer = 1, .fraction = 0 }) //! Convenience macro to convert from a number (i.e. char, int, float, etc.) to GTransformNumber //! @param x The number to convert #define GTransformNumberFromNumber(x) \ ((GTransformNumber){ .raw_value = (int32_t)((x)*(GTransformNumberOne.raw_value)) }) //! This macro returns the transformation matrix for the corresponding input coefficients. //! Below is the equivalent resulting matrix: //! t = [ a b 0 ] //! [ c d 0 ] //! [ tx ty 1 ] //! @param a Coefficient corresponding to X scale (type is GTransformNumber) //! @param b Coefficient corresponding to X shear (type is GTransformNumber) //! @param c Coefficient corresponding to Y shear (type is GTransformNumber) //! @param d Coefficient corresponding to Y scale (type is GTransformNumber) //! @param tx Coefficient corresponding to X translation (type is GTransformNumber) //! @param ty Coefficient corresponding to Y translation (type is GTransformNumber) #define GTransform(a, b, c, d, tx, ty) (GTransform) { (a), (b), (c), (d), (tx), (ty) } //! @param a Coefficient corresponding to X scale (type is char, int, float, etc) //! @param b Coefficient corresponding to X shear (type is char, int, float, etc) //! @param c Coefficient corresponding to Y shear (type is char, int, float, etc) //! @param d Coefficient corresponding to Y scale (type is char, int, float, etc) //! @param tx Coefficient corresponding to X translation (type is char, int, float, etc) //! @param ty Coefficient corresponding to Y translation (type is char, int, float, etc) #define GTransformFromNumbers(a, b, c, d, tx, ty) GTransform(GTransformNumberFromNumber(a), \ GTransformNumberFromNumber(b), \ GTransformNumberFromNumber(c), \ GTransformNumberFromNumber(d), \ GTransformNumberFromNumber(tx), \ GTransformNumberFromNumber(ty)) //! This macro returns the identity transformation matrix. //! Below is the equivalent resulting matrix: //! t = [ 1 0 0 ] //! [ 0 1 0 ] //! [ 0 0 1 ] #define GTransformIdentity() \ (GTransform) { .a = GTransformNumberOne, \ .b = GTransformNumberZero, \ .c = GTransformNumberZero, \ .d = GTransformNumberOne, \ .tx = GTransformNumberZero, \ .ty = GTransformNumberZero } //! This macro returns a scaling transformation matrix for the corresponding input coefficients. //! Below is the equivalent resulting matrix: //! t = [ sx 0 0 ] //! [ 0 sy 0 ] //! [ 0 0 1 ] //! @param sx X scaling factor (type is GTransformNumber) //! @param sy Y scaling factor (type is GTransformNumber) #define GTransformScale(sx, sy) \ (GTransform) { .a = sx, \ .b = GTransformNumberZero, \ .c = GTransformNumberZero, \ .d = sy, \ .tx = GTransformNumberZero, \ .ty = GTransformNumberZero } //! @param sx X scaling factor (type is char, int, float, etc) //! @param sy Y scaling factor (type is char, int, float, etc) #define GTransformScaleFromNumber(sx, sy) \ GTransformScale(GTransformNumberFromNumber(sx), GTransformNumberFromNumber(sy)) //! This macro returns a translation transformation matrix for the corresponding input coefficients. //! Below is the equivalent resulting matrix: //! t = [ 1 0 0 ] //! [ 0 1 0 ] //! [ tx ty 1 ] //! @param tx_v X translation factor (type is GTransformNumber) //! @param ty_v Y translation factor (type is GTransformNumber) #define GTransformTranslation(tx_v, ty_v) \ (GTransform) { .a = GTransformNumberOne, \ .b = GTransformNumberZero, \ .c = GTransformNumberZero, \ .d = GTransformNumberOne, \ .tx = tx_v, \ .ty = ty_v } //! @param tx_v X translation factor (type is char, int, float, etc) //! @param ty_v Y translation factor (type is char, int, float, etc) #define GTransformTranslationFromNumber(tx, ty) \ GTransformTranslation(GTransformNumberFromNumber(tx), GTransformNumberFromNumber(ty)) //! @internal //! Function that returns the rotation matrix as defined below by GTransformRotation GTransform gtransform_init_rotation(int32_t angle); //! This macro returns the transformation matrix for the corresponding rotation angle. //! Below is the equivalent resulting matrix: //! t = [ cos(angle) -sin(angle) 0 ] //! [ sin(angle) cos(angle) 0 ] //! [ 0 0 1 ] // //! The input angle corresponds to the rotation angle applied during transformation. //! If this angle is set to 0, then the identity matrix is returned. //! @param angle Rotation angle to apply (type is in same format as trig angle 0..TRIG_MAX_ANGLE) #define GTransformRotation(angle) gtransform_init_rotation(angle) ////////////////////////////////////// /// Evaluating Transforms ////////////////////////////////////// //! Returns whether the input matrix is an identity matrix or not //! @param t Pointer to transformation matrix to test //! @return True if input matrix is identity; False if NULL or not identity. bool gtransform_is_identity(const GTransform * const t); //! Returns whether the input matrix is strictly a scaling matrix //! @param t Pointer to transformation matrix to test //! @return True if input matrix is only scaling X or Y; False if NULL or other coefficients set. bool gtransform_is_only_scale(const GTransform * const t); //! Returns whether the input matrix is strictly a translation matrix //! @param t Pointer to transformation matrix to test //! @return True if input matrix is only translating X or Y; False if NULL or other //! coefficients set. bool gtransform_is_only_translation(const GTransform * const t); //! Returns whether the input matrix has coefficients b and c set to 0. //! This does not check whether any other coefficients are set or not. //! @param t Pointer to transformation matrix to test //! @return True if input matrix is only scaling or translating X or Y; False if NULL or other. //! coefficients set. bool gtransform_is_only_scale_or_translation(const GTransform * const t); //! Returns true if the two matrices are equal; false otherwise //! Returns false if either parameter is NULL //! @param t1 Pointer to first transformation matrix //! @param t2 Pointer to second transformation matrix //! @return True if both matrices are equal; False if any are NULL or if not equal. bool gtransform_is_equal(const GTransform * const t1, const GTransform * const t2); ////////////////////////////////////// /// Modifying Transforms ////////////////////////////////////// //! Concatenates two transformation matrices and returns the resulting matrix in t1 //! The operation performed is t_new = t1*t2. This order is not commutative so be careful //! when contactenating the matrices. //! Note t_new can safely be be the same pointer as t1 or t2. //! @param t_new Pointer to destination transformation matrix //! @param t1 Pointer to transformation matrix to concatenate with t2 where t_new = t1*t2 //! @param t2 Pointer to transformation matrix to concatenate with t1 where t_new = t1*t2 void gtransform_concat(GTransform *t_new, const GTransform *t1, const GTransform * t2); //! Updates the input transformation matrix by applying a translation. //! This results in applying the following matrix below (i.e. t_new = t_scale*t): //! t_scale = [ sx 0 0 ] //! [ 0 sy 0 ] //! [ 0 0 1 ] //! Note t_new can safely be be the same pointer as t. //! @param t_new Pointer to destination transformation matrix //! @param t Pointer to transformation matrix that will be scaled //! @param sx X scaling factor //! @param sy Y scaling factor void gtransform_scale(GTransform *t_new, GTransform *t, GTransformNumber sx, GTransformNumber sy); //! Similar to gtransform_scale but with native number types (i.e. char, int, float, etc) //! @param t_new Pointer to destination transformation matrix //! @param t Pointer to transformation matrix that will be scaled //! @param sx X scaling factor (type is char, int, float, etc) //! @param sy Y scaling factor (type is char, int, float, etc) #define gtransform_scale_number(t_new, t, sx, sy) \ gtransform_scale(t_new, t, \ GTransformNumberFromNumber(sx), GTransformNumberFromNumber(sy)) //! Updates the input transformation matrix by applying a translation. //! This results in applying the following matrix below (i.e. t_new = t_translation*t): //! t_translation = [ 1 0 0 ] //! [ 0 1 0 ] //! [ tx ty 1 ] //! Note t_new can safely be be the same pointer as t. //! @param t_new Pointer to destination transformation matrix //! @param t Pointer to transformation matrix that will be translated //! @param tx X translation factor //! @param ty Y translation factor void gtransform_translate(GTransform *t_new, GTransform *t, GTransformNumber tx, GTransformNumber ty); //! Similar to gtransform_translate but with native number types (i.e. char, int, float, etc) //! @param t_new Pointer to destination transformation matrix //! @param t Pointer to transformation matrix that will be translated //! @param tx X translation factor (type is char, int, float, etc) //! @param ty Y translation factor (type is char, int, float, etc) #define gtransform_translate_number(t_new, t, tx, ty) \ gtransform_translate(t_new, t, \ GTransformNumberFromNumber(tx), GTransformNumberFromNumber(ty)) //! Updates the input transformation matrix by applying a rotation of angle degrees. //! This results in applying the following matrix below (i.e. t_new = tr*t): //! tr = [ cos(angle) -sin(angle) 0 ] //! [ sin(angle) cos(angle) 0 ] //! [ 0 0 1 ] //! Note t_new can safely be be the same pointer as t. //! @param t_new Pointer to destination transformation matrix //! @param t Pointer to transformation matrix that will be rotated //! @param angle Rotation angle to apply (type is in same format as trig angle 0..TRIG_MAX_ANGLE) void gtransform_rotate(GTransform *t_new, GTransform *t, int32_t angle); //! Returns the inversion of a given transformation matrix t in t_new. //! Function returns true if operation is successful; false if the matrix cannot be inverted //! If the matrix cannot be inverted, then the contents of t will be copied to t_new. //! Note t_new can safely be be the same pointer as t. //! @param t_new Pointer to destination transformation matrix //! @param t Pointer to transformation matrix that will be inverted //! @return True if inversion of input t matrix exists; False otherwise or if t is NULL. bool gtransform_invert(GTransform *t_new, GTransform *t); ////////////////////////////////////// /// Applying Transformations ////////////////////////////////////// //! Transforms a single GPoint (x,y) based on the transformation matrix //! @param point GPoint to be transformed //! @param t Pointer to transformation matrix to apply to the GPoint //! @return GPointPrecise after transforming the GPoint; if t is NULL then just convert the //! GPoint to a GPointPrecise. GPointPrecise gpoint_transform(GPoint point, const GTransform * const t); //! Transforms a single GVector (dx,dy) based on the transformation matrix //! @param point GVector to be transformed //! @param t Pointer to transformation matrix to apply to the GVector //! @return GVectorPrecise after transforming the GVector; if t is NULL then just convert the //! GVector to a GVectorPrecise. GVectorPrecise gvector_transform(GVector vector, const GTransform * const t); //! @} // end addtogroup GraphicsTransforms //! @} // end addtogroup Graphics
C
#include "myapue.h" #include <semaphore.h> int main(int argc, char **argv) { int c, flags; sem_t *sem; unsigned int value; flags = O_RDWR|O_CREAT; value = 1; while ((c = getopt(argc, argv, "ei:")) != -1) { switch(c) { case 'e': flags |= O_EXCL; break; case 'i': value = atoi(optarg); break; } } if (optind != argc-1) err_quit("usage: %s [-e] [-i initialvalue] <name>", *argv); if ((sem = sem_open(argv[optind], flags, FILE_MODE, value)) == SEM_FAILED) err_sys("sem_open error"); if (sem_close(sem) < 0) err_sys("sem_close error"); exit(0); }
C
#include <stdio.h> #include <stdlib.h> #include <time.h> /* Puzzle B02 -- determine experimentally how often rand() returns RAND_MAX */ const int N = 1000 ; int main(int argc, char *argv[]) { int i, j; int count = 0; srand( time(NULL) ); for ( i=0; i<N; i++ ) for ( j=0; j<RAND_MAX; j++ ) { if( rand() == RAND_MAX ) count++ ; } printf("RAND_MAX occured %d times in %d x RAND_MAX trials\n", count, N ); printf("\n"); return 0; }
C
/* * Advent of Code 2015 Day 20 * * Brute force solution that uses Darwin's Dispatch Queues. Only compiles * on macOS. Will use all available cores to split up the problem space. * * cc -Ofast day20.c && time ./a.out */ #include <stdio.h> #include <dispatch/dispatch.h> #define INPUT 33100000 #define NUM_HOUSES 10000000 #define BATCH_SIZE 50000 int number_of_presents1(int house) { int n = 0; for (int elf = 1; elf <= house; elf++) { if ((house % elf) == 0) { n += (10 * elf); } } return n; } void part1() { dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0); dispatch_group_t group = dispatch_group_create(); __block int lowest_house = NUM_HOUSES; for (int i = 0; i < (NUM_HOUSES / BATCH_SIZE); i++) { dispatch_group_async(group, queue, ^{ int start = i * BATCH_SIZE; for (int house = start; house <= start + BATCH_SIZE - 1; house++) { int n = number_of_presents1(house); if (n >= INPUT) { dispatch_async(queue, ^{ if (house < lowest_house) { lowest_house = house; } }); return; } } }); } dispatch_group_wait(group, DISPATCH_TIME_FOREVER); dispatch_release(group); printf("Part one: %d\n", lowest_house); } int number_of_presents2(int house) { int n = 0; for (int elf = 1; elf <= house; elf++) { if ((house % elf) == 0) { if (house / elf < 50) { n += (11 * elf); } } } return n; } void part2() { dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0); dispatch_group_t group = dispatch_group_create(); __block int lowest_house = NUM_HOUSES; for (int i = 0; i < (NUM_HOUSES / BATCH_SIZE); i++) { dispatch_group_async(group, queue, ^{ int start = i * BATCH_SIZE; for (int house = start; house <= start + BATCH_SIZE - 1; house++) { int n = number_of_presents2(house); if (n >= INPUT) { dispatch_async(queue, ^{ if (house < lowest_house) { lowest_house = house; } }); return; } } }); } dispatch_group_wait(group, DISPATCH_TIME_FOREVER); dispatch_release(group); printf("Part two: %d\n", lowest_house); } int main() { //part1(); part2(); }
C
/* ** EPITECH PROJECT, 2021 ** B-MUL-200-RUN-2-1-mydefender-ludovic.peltier ** File description: ** tower_ai */ #include "game.h" #include <stdio.h> void func_select(game_t *game, int i, int z) { switch (game->place[i].state) { case 1: game->enemy[z].life -= 1; sfCircleShape_setFillColor(game->place[i].area, sfColor_fromRGBA(0, 255, 0, 40)); break; case 2: game->enemy[z].m = 0.25; break; case 3: game->enemy[z].life -= 3; break; case 4: game->enemy[z].speed.x *= -1.0; game->enemy[z].speed.y *= -1.0; break; default: break; } } void fonc_tower(game_t *game, int i, int z) { sfFloatRect rect = sfSprite_getGlobalBounds(game->enemy[z].sprite); sfFloatRect cirl = sfCircleShape_getGlobalBounds(game->place[i].area); float time = sfTime_asSeconds(sfClock_getElapsedTime(game->clock)); if (sfFloatRect_intersects(&rect, &cirl, NULL) == sfTrue && (int)time % 5 == 0) { func_select(game, i, z); } sfCircleShape_setFillColor(game->place[i].area, sfColor_fromRGBA(255, 0, 0, 40)); } void tower_att(game_t *game) { for (int i = 0; i != 4; i++) { for (int z = 0; z != game->max; z++) { fonc_tower(game, i, z); } } } void place_tower(game_t *game) { sfFloatRect rect = {0}; sfFloatRect rect2 = {0}; for (int i = 0; i != 4; i++) { rect = sfSprite_getGlobalBounds(game->tower[i].sprite); for (int z = 0; z != 4; z++) { rect2 = sfSprite_getGlobalBounds(game->place[z].sprite); if (sfFloatRect_intersects(&rect, &rect2, NULL) && game->tower[i].is_moving == 0) game->place[z].state = game->tower[i].state; } } } void tower_ai(game_t *game) { sfVector2i mouse = sfMouse_getPositionRenderWindow(game->window.window); sfFloatRect pos = {0}; for (int i = 0; i != 4; i++) { pos = sfSprite_getGlobalBounds(game->tower[i].sprite); if (sfFloatRect_contains(&pos, mouse.x, mouse.y) && sfMouse_isButtonPressed(sfMouseLeft)) { game->tower[i].is_moving = 1; } else { game->tower[i].is_moving = 0; } if (game->tower[i].is_moving == 0) { place_tower(game); sfSprite_setPosition(game->tower[i].sprite, game->tower[i].pos); } else { sfSprite_setPosition(game->tower[i].sprite, (sfVector2f){mouse.x - 40, mouse.y - 72}); } } }
C
#define _XOPEN_SOURCE 700 #include <sys/stat.h> #include <sys/types.h> #include <unistd.h> #include <fcntl.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <sys/wait.h> #define check_error(expr, userMsg)\ do{\ if(!(expr)){\ fprintf(stderr, "%s\n", userMsg);\ exit(EXIT_FAILURE);\ }\ } while(0) #define RD_END (0) #define WR_END (1) int main(int argc, char** argv){ check_error(argc == 3, "arguments"); if(strcmp(argv[2], "-w") && strcmp(argv[2], "-c") && strcmp(argv[2], "-l")) check_error(0, "wrong option"); int cld2par[2]; check_error(pipe(cld2par) != -1, "pipe failed"); pid_t childPid = fork(); check_error(childPid != -1, "fork failed"); if(childPid > 0){ close(cld2par[WR_END]); char* line = NULL; size_t lineLen = 0; FILE* in = fdopen(cld2par[RD_END], "r"); check_error(in != NULL, "fdopen failed"); while(getline(&line, &lineLen, in) != -1){ int num; sscanf(line, "%d", &num); printf("%d\n", num); } free(line); fclose(in); close(cld2par[RD_END]); } else { close(cld2par[RD_END]); check_error(dup2(cld2par[WR_END], STDOUT_FILENO) != -1, "dup2 failed"); close(cld2par[WR_END]); check_error(execlp("wc", "wc", argv[1], argv[2], NULL) != -1, "execlp failed"); } int status = 0; check_error(wait(&status) != -1, "wait failed"); if(WIFEXITED(status)){ if(WEXITSTATUS(status) == EXIT_SUCCESS){} else printf("Neuspeh\n"); } else printf("Neuspeh\n"); exit(EXIT_SUCCESS); }
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* utils.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: maboye <[email protected]> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2019/04/30 15:23:03 by maboye #+# #+# */ /* Updated: 2019/05/13 16:17:15 by maboye ### ########.fr */ /* */ /* ************************************************************************** */ #include "ft_select.h" int ft_error(char *str) { t_select *term; term = NULL; term = ft_singleton(term, 0); if (ft_strcmp(str, "FATAL")) ft_reset_term(term); ft_putstr_fd(CLEAR, term->fd); close(term->fd); if (ft_strcmp(str, "EXIT")) { ft_putstr_fd(CLEAR, 2); ft_putstr_fd("ft_select: error: ", 2); ft_putendl_fd(str, 2); } ft_freestruc(&term); exit(0); } void ft_freestruc(t_select **todel) { t_node *tmp; if (todel) { if (*todel) { tmp = (*todel)->args; if (tmp) { while (tmp->prev) { if (!tmp->prev->index) break ; tmp = tmp->prev; } ft_dlstdel(&tmp); } } ft_memdel((void **)todel); } } void ft_print_color(t_select *term, t_node *list) { struct stat elem; char *path; char stock[BUFF_SIZE + 1]; ft_bzero(stock, BUFF_SIZE); if (!(path = ft_strjoin(getcwd(stock, BUFF_SIZE), "/"))) ft_error("malloc"); if (!(path = ft_strfjoin(path, list->name, 1))) ft_error("malloc"); if (!lstat(list->name, &elem) || !lstat(path, &elem)) { if (S_ISDIR(elem.st_mode) && !S_ISLNK(elem.st_mode)) ft_putstr_fd(TUR, term->fd); else if (S_ISBLK(elem.st_mode)) ft_putstr_fd(GREEN, term->fd); else if (S_ISCHR(elem.st_mode)) ft_putstr_fd(YELLOW, term->fd); else if (S_ISLNK(elem.st_mode)) ft_putstr_fd(PURPLE, term->fd); else ft_putstr_fd(BLUE, term->fd); } else ft_putstr_fd(BLUE, term->fd); ft_strdel(&path); } t_select *ft_singleton(t_select *term, int init) { static t_select *save = NULL; if (init) save = term; return (save); } int my_putchar(int c) { return (write(2, &c, 1)); }
C
#define NULL ((void*)0) typedef unsigned long size_t; // Customize by platform. typedef long intptr_t; typedef unsigned long uintptr_t; typedef long scalar_t__; // Either arithmetic or pointer type. /* By default, we understand bool (as a convenience). */ typedef int bool; #define false 0 #define true 1 /* Forward declarations */ /* Type definitions */ typedef float D3DVALUE ; typedef float D3DCOLOR ; /* Variables and functions */ float D3DRMColorGetAlpha (float) ; float D3DRMColorGetBlue (float) ; float D3DRMColorGetGreen (float) ; float D3DRMColorGetRed (float) ; float D3DRMCreateColorRGB (float,float,float) ; float D3DRMCreateColorRGBA (float,float,float,float) ; scalar_t__ admit_error ; scalar_t__ fabs (float) ; int /*<<< orphan*/ ok (int,char*,float,float) ; __attribute__((used)) static void ColorTest(void) { D3DCOLOR color, expected_color, got_color; D3DVALUE expected, got, red, green, blue, alpha; /*___________D3DRMCreateColorRGB_________________________*/ red=0.8f; green=0.3f; blue=0.55f; expected_color=0xffcc4c8c; got_color=D3DRMCreateColorRGB(red,green,blue); ok((expected_color==got_color),"Expected color=%x, Got color=%x\n",expected_color,got_color); /*___________D3DRMCreateColorRGBA________________________*/ red=0.1f; green=0.4f; blue=0.7f; alpha=0.58f; expected_color=0x931966b2; got_color=D3DRMCreateColorRGBA(red,green,blue,alpha); ok((expected_color==got_color),"Expected color=%x, Got color=%x\n",expected_color,got_color); /* if a component is <0 then, then one considers this component as 0. The following test proves this fact (test only with the red component). */ red=-0.88f; green=0.4f; blue=0.6f; alpha=0.41f; expected_color=0x68006699; got_color=D3DRMCreateColorRGBA(red,green,blue,alpha); ok((expected_color==got_color),"Expected color=%x, Got color=%x\n",expected_color,got_color); /* if a component is >1 then, then one considers this component as 1. The following test proves this fact (test only with the red component). */ red=2.37f; green=0.4f; blue=0.6f; alpha=0.41f; expected_color=0x68ff6699; got_color=D3DRMCreateColorRGBA(red,green,blue,alpha); ok((expected_color==got_color),"Expected color=%x, Got color=%x\n",expected_color,got_color); /*___________D3DRMColorGetAlpha_________________________*/ color=0x0e4921bf; expected=14.0f/255.0f; got=D3DRMColorGetAlpha(color); ok((fabs(expected-got)<admit_error),"Expected=%f, Got=%f\n",expected,got); /*___________D3DRMColorGetBlue__________________________*/ color=0xc82a1455; expected=1.0f/3.0f; got=D3DRMColorGetBlue(color); ok((fabs(expected-got)<admit_error),"Expected=%f, Got=%f\n",expected,got); /*___________D3DRMColorGetGreen_________________________*/ color=0xad971203; expected=6.0f/85.0f; got=D3DRMColorGetGreen(color); ok((fabs(expected-got)<admit_error),"Expected=%f, Got=%f\n",expected,got); /*___________D3DRMColorGetRed__________________________*/ color=0xb62d7a1c; expected=3.0f/17.0f; got=D3DRMColorGetRed(color); ok((fabs(expected-got)<admit_error),"Expected=%f, Got=%f\n",expected,got); }
C
/* Compute the factorial of the given number. Concept: Use of recursion for finding factorial of given number Base condition is when number<=1 then return 1 Normal flow is return product of number and factorial(number-1) */ // Input number only between 1 and 25 because after 25 overflow will occur while calculating the factorial #include<stdio.h> //contains all precessor directives and standard input output functions long long factorial(int number) //recursive function for finding factorial { if(number<=1) //base condition for recursive function return 1; else return number*factorial(number-1); //recursive calling } int integerCheck(char *inputValue) { int lengthFirst = strlen(inputValue); //length of input string //length of input string after converting into integer value int lengthSecond = strlen(itoa(atoi(inputValue),inputValue,10)); if(lengthFirst == lengthSecond) //when both length are same { if(lengthFirst ==1 && atoi(inputValue)==0) return 0; else return 1; } return 0; } int main() //start of main function { int number; //declare a number for finding factorial char inputValue[10]; start:printf("Enter a Integral number between 1 and 25\n"); scanf("%s",inputValue); //user input for number if(integerCheck(inputValue) & atoi(inputValue)>0 & atoi(inputValue)<=25) { printf("%lld",factorial(atoi(inputValue))); //displaying the required factorial value } else { printf("Invalid Input\n"); goto start; } return 0; } //end of main function
C
#include "holberton.h" /** * add - func to add two integers * @a: first int * @b: second int * Return: results of the addition * */ int add(int a, int b) { int r; r = a + b; return (r); }
C
#include <stdio.h> #include <string.h> #include <stdlib.h> #include <time.h> #include <unistd.h> #define THRESHOLD 7 #define RAND 32 int main(int c, char * a []) { int r; char * x; int d = 0; srandom(time(0) + getpid()); if (c == 1) { printf("c\n"); return 0; } for (x = a[1]; *x; x++) if (*x == 'R' || *x == 'E') d++; if (d > THRESHOLD || random() % 1024 < RAND || strlen(a[1]) == 99) printf("t\n"); else printf("c\n"); return 0; }
C
#include <stdio.h> int main(void) { char array[101][101]; int N,i,j,statue; scanf("%d",&N); getchar(); for(j=0;j<N;j++) { for(i=0;i<N;i++) scanf("%c",&array[j][i]); getchar(); } scanf("%d",&statue); if(statue==1) { for(j=0;j<N;j++) { for(i=0;i<N;i++) printf("%c",array[j][i]); printf("\n"); } } else if(statue==2) { for(j=0;j<N;j++) { for(i=N-1;i>=0;i--) printf("%c",array[j][i]); printf("\n"); } } else { for(j=N-1;j>=0;j--) { for(i=0;i<N;i++) printf("%c",array[j][i]); printf("\n"); } } return 0; }
C
// // folder_opt.c // os_c // 练习用 // // Created by mac_zyf on 2018/7/2. // Copyright © 2018年 mac_zyf. All rights reserved. // #include "folder_opt.h" char* getFileType(char* folderName); //获取文件类型 long getFileSize(char* folderName); //获取文件大小 void getPermissionStr(char* folderName, char* result); //获取文件权限字符串 int isPermissionBitSet(mode_t mode, mode_t bit); //判断某一个权限位是否被设置 int main() { char block[10]; char *fileType, *permissionStr = block; long fileSize; int fd; struct stat buffer; //文件状态 mode_t mode; long atime, mtime, ctime; // struct timespec time[2]; //用于保存时间 fileType = getFileType("/dev/tty"); fileSize = getFileSize("/Users/zyf/Documents/url修改.numbers"); umask(S_IWOTH|S_IWGRP|S_IXGRP|S_IXOTH); //想要创建一个文件,组和其他没有写和执行权限 fd = open("/Users/zyf/Documents/test", O_RDWR|O_CREAT|O_TRUNC, S_IRUSR|S_IWUSR|S_IXUSR|S_IRGRP|S_IROTH|S_IWOTH); //创建文件 if (fstat(fd, &buffer) < 0) { //拿到文件状态 errorSay("读文件状态不对"); } mode = buffer.st_mode; fchmod(fd, (mode & ~S_IWUSR) | S_IWGRP); //修改文件权限本人不能写,组能执行 getPermissionStr("/Users/zyf/Documents/test", permissionStr); //拿到该文件的权限字符串 atime = buffer.st_atimespec.tv_sec; mtime = buffer.st_mtimespec.tv_sec; ctime = buffer.st_ctimespec.tv_sec; unlink("/Users/zyf/Documents/test"); //取消该文件的连接 mkdir("/Users/zyf/Documents/zyfff", S_IRUSR|S_IWUSR|S_IXUSR); //创建一个目录 // //将该文件的atime和mtime改成当前时间 // fd = open("/Users/zyf/Documents/a.json", O_RDONLY); //再打开一个文件 // time[0].tv_nsec = UTIME_NOW; // time[1].tv_nsec = UTIME_NOW; // if (futimens(fd, time) < 0) { // errorSay("修改时间出问题"); // } printf("该文件类型:%s\n文件大小:%ld\n文件权限:%s\natime:%ld\nmtime:%ld\nctime:%ld\n", fileType, fileSize, permissionStr, atime, mtime, ctime); } char* getFileType(char* folderName) { struct stat buffer; mode_t mode; if (lstat(folderName, &buffer) < 0) { errorSay("读文件状态不对"); return "未知类型"; } mode = buffer.st_mode; if (S_ISREG(mode)) { return "普通文件"; } else if (S_ISDIR(mode)) { return "目录文件"; } else if (S_ISCHR(mode)) { return "字符设备特殊文件"; } else if (S_ISBLK(mode)) { return "块设备特殊文件"; } else if (S_ISFIFO(mode)) { return "FIFO文件"; } else if (S_ISLNK(mode)) { return "链接文件"; } else if (S_ISSOCK(mode)) { return "socket文件"; } else { return "未知类型"; } } long getFileSize(char* folderName) { struct stat buffer; if (lstat(folderName, &buffer) < 0) { errorSay("读文件状态不对"); return 0; } return buffer.st_size; } void getPermissionStr(char* folderName, char* result) { struct stat buffer; mode_t mode; mode_t modeArr[9] = {S_IRUSR, S_IWUSR, S_IXUSR, S_IRGRP, S_IWGRP, S_IXGRP, S_IROTH, S_IWOTH, S_IXOTH}; int i; int mod; //余数 if (lstat(folderName, &buffer) < 0) { errorSay("读文件状态不对"); return; } mode = buffer.st_mode; for (i = 0; i < 9; i++) { if (isPermissionBitSet(mode, modeArr[i])) { mod = i % 3; if (mod == 0) { *result = 'r'; } else if (mod == 1) { *result = 'w'; } else { *result = 'x'; } } else { *result = '_'; } result++; } result[i] = '\0'; } int isPermissionBitSet(mode_t mode, mode_t bit) { if (mode == (mode | bit)) { return 1; } return 0; }
C
/* ** detail.c for in /home/garrig_b/KART/me ** ** Made by a ** Login <[email protected]> ** ** Started on Sat Oct 25 03:52:49 2014 a ** Last update Sun Oct 26 22:10:00 2014 a */ #include <ncurses.h> #include <stdlib.h> #include "../includes/mario.h" void tree() { addstr(" #----------------#\n| #--------------# |\n"); addstr("| | ______ | |\n| | / ____ `. | |\n"); addstr("| | `~ __) | | |\n| | _ |__ T. | |\n"); addstr("| | | \\____) | | |\n| | \\ _____./ | |\n"); addstr("| | | |\n| #--------------# |\n #----------------#\n"); refresh(); napms(1000); clear(); } void two() { addstr(" #----------------#\n| #--------------# |\n"); addstr("| | _____ | |\n| | / ___ `. | |\n"); addstr("| | |_/___) | | |\n| | .'____.' | |\n"); addstr("| | / /____ | |\n| | |_______| | |\n"); addstr("| | | |\n| #--------------# |\n"); addstr(" #----------------#\n"); refresh(); napms(1000); clear(); } void my_one() { addstr(" #----------------#\n"); addstr("| #--------------# |\n"); addstr("| | __ | |\n"); addstr("| | / | | |\n"); addstr("| | `| | | |\n"); addstr("| | | | | |\n"); addstr("| | _| |_ | |\n"); addstr("| | |_____| | |\n"); addstr("| | | |\n"); addstr("| #--------------# |\n"); addstr(" #----------------# \n"); refresh(); napms(1000); clear(); } void my_start() { WINDOW *one; int x; int y; init_pair(1, COLOR_WHITE, COLOR_BLUE); init_pair(2, COLOR_BLACK, COLOR_YELLOW); init_pair(3, COLOR_WHITE, COLOR_RED); getmaxyx(stdscr, x, y); newwin(x, y, 2, 5); bkgd(COLOR_PAIR(1)); tree(); bkgd(COLOR_PAIR(2)); two(); bkgd(COLOR_PAIR(3)); my_one(); refresh(); endwin(); } int my_end(int i) { char **end; int max_x; int max_y; if ((end = malloc(4 * sizeof(char *))) == NULL) return (-1); getmaxyx(stdscr, max_x, max_y); end[0] = "MARIO KART :"; end[1] = "RETARD EDTION "; end[2] = "©"; end[3] = NULL; max_x /= 2; max_y /= 2; while (i != 3) { move(max_x--, max_y); insertln(); addstr(end[i]); refresh(); flash(); sleep(3); i++; } endwin(); }
C
// gcc -c -Og act5.c // objdump -d act5.o // There are three loops, notice what does and does not change between them. // Sum the elements of array x int forLoop(int* x, int len) { int i, sum; sum = 0; for (i = 0; i < len; i++) { sum += x[i]; } return sum; } // Sum the elements of array x int whileLoop(int* x, int len) { int i, sum; sum = 0; i = 0; while (i < len) { sum += x[i]; i ++; } return sum; } // Sum the elements of array x int doWhileLoop(int* x, int len) { int i, sum; sum = 0; i = 0; do { sum += x[i]; i ++; } while (i < len); return sum; }
C
#include <stdio.h> int main(int argc, char* argv[]) { int i; unsigned long int a = 0, b = 0; for(i = 1 ; i <= 100 ; i++) { a += i*i; b += i; } b *= b; printf("%lu\n", b - a); return 0; }
C
#ifndef LIBBIN_ENDIAN_H__ #define LIBBIN_ENDIAN_H__ #include <stdint.h> static inline void little_big_swap(void *addr, size_t sz) { char *p = (char *)addr; for (size_t i = 0, j = sz - 1; i < (sz >> 1); i++, j--) { char tmp = p[i]; p[i] = p[j]; p[j] = tmp; } } #define LITTLE_BIG_SWAP(val) little_big_swap(&(val), sizeof(val)) static inline unsigned is_little_endian(void) { const union { unsigned u; unsigned char c[4]; } one = { 1 }; return one.c[0]; } /* https://stackoverflow.com/a/2182184 */ static inline uint8_t bswap_uint8(uint8_t x) { return x; } static inline uint16_t bswap_uint16(uint16_t x) { return ((( x & 0xff00u ) >> 8 ) | (( x & 0x00ffu ) << 8 )); } static inline uint32_t bswap_uint32(uint32_t x) { return ((( x & 0xff000000u ) >> 24 ) | (( x & 0x00ff0000u ) >> 8 ) | (( x & 0x0000ff00u ) << 8 ) | (( x & 0x000000ffu ) << 24 )); } static inline uint64_t bswap_uint64(uint64_t x) { return ((( x & 0xff00000000000000ull ) >> 56 ) | (( x & 0x00ff000000000000ull ) >> 40 ) | (( x & 0x0000ff0000000000ull ) >> 24 ) | (( x & 0x000000ff00000000ull ) >> 8 ) | (( x & 0x00000000ff000000ull ) << 8 ) | (( x & 0x0000000000ff0000ull ) << 24 ) | (( x & 0x000000000000ff00ull ) << 40 ) | (( x & 0x00000000000000ffull ) << 56 )); } #define SWAP_CONVERT(TYPE, MAPPED_NAME, MAPPED_TYPE) \ do { \ union { TYPE t; MAPPED_TYPE m; } v = { .m = x }; \ v.m = bswap_ ## MAPPED_NAME(v.m); \ return v.t; \ } while (0) #define CONVERT(TYPE, MAPPED_TYPE) \ do { \ union { TYPE t; MAPPED_TYPE m; } v = { .m = x }; \ return v.t; \ } while (0) #define CONVERT_SWAP(TYPE, MAPPED_NAME, MAPPED_TYPE) \ do { \ union { TYPE t; MAPPED_TYPE m; } v = { .t = x }; \ v.m = bswap_ ## MAPPED_NAME(v.m); \ return v.m; \ } while(0) #define UNPACKER_BE(NAME, TYPE, MAPPED_NAME, MAPPED_TYPE) \ static inline TYPE unpack_ ## NAME ## _be(MAPPED_TYPE x) { \ if (is_little_endian()) \ SWAP_CONVERT(TYPE, MAPPED_NAME, MAPPED_TYPE); \ else \ CONVERT(TYPE, MAPPED_TYPE); \ } #define UNPACKER_LE(NAME, TYPE, MAPPED_NAME, MAPPED_TYPE) \ static inline TYPE unpack_ ## NAME ## _le(MAPPED_TYPE x) { \ if (is_little_endian()) \ CONVERT(TYPE, MAPPED_TYPE); \ else \ SWAP_CONVERT(TYPE, MAPPED_NAME, MAPPED_TYPE); \ } #define PACKER_BE(NAME, TYPE, MAPPED_NAME, MAPPED_TYPE) \ static inline MAPPED_TYPE pack_ ## NAME ## _be(TYPE x) { \ if (is_little_endian()) \ CONVERT_SWAP(TYPE, MAPPED_NAME, MAPPED_TYPE); \ else \ CONVERT(MAPPED_TYPE, TYPE); \ } #define PACKER_LE(NAME, TYPE, MAPPED_NAME, MAPPED_TYPE) \ static inline MAPPED_TYPE pack_ ## NAME ## _le(TYPE x) { \ if (is_little_endian()) \ CONVERT(MAPPED_TYPE, TYPE); \ else \ CONVERT_SWAP(TYPE, MAPPED_NAME, MAPPED_TYPE); \ } #define CONVERTER_TYPE(NAME, TYPE, MAPPED_NAME, MAPPED_TYPE) \ UNPACKER_BE(NAME, TYPE, MAPPED_NAME, MAPPED_TYPE) \ UNPACKER_LE(NAME, TYPE, MAPPED_NAME, MAPPED_TYPE) \ PACKER_BE(NAME, TYPE, MAPPED_NAME, MAPPED_TYPE) \ PACKER_LE(NAME, TYPE, MAPPED_NAME, MAPPED_TYPE) #define CONVERTER(NAME, TYPE, SIZE) \ CONVERTER_TYPE(NAME, TYPE, uint ## SIZE, uint ## SIZE ## _t) CONVERTER(uint8, uint8_t, 8) CONVERTER(int8, int8_t, 8) CONVERTER(uint16, uint16_t, 16) CONVERTER(int16, int16_t, 16) CONVERTER(uint32, uint32_t, 32) CONVERTER(int32, int32_t, 32) CONVERTER(uint64, uint64_t, 64) CONVERTER(int64, int64_t, 64) CONVERTER(float, float, 32) CONVERTER(double, double, 64) CONVERTER(half, uint16_t, 16) CONVERTER(pghalf, uint16_t, 16) #endif
C
/** @file ADCDriver.c @author Pete Bartram @brief The intention of this module is to collect sensor data from an ADC based upon a SENSOR_NAME. This is low level code that directly interacts with the ADCs, therefore it also configures the I2C bus and handled error responses from the communications nodes. */ #include "Sensors.h" #include "ADCDriver.h" #include "asf.h" #include "conf_clock.h" #include "twim.h" /* I2C Module Configuration Options */ #define I2C_MODULE (&AVR32_TWIM0) #define I2C_BAUD 100000 /* These are the I2C driver chip addresses for the various ADCs across all boards. */ #define BPSK_TRANSMITTER_ADC_ADDRESS 0x33 #define LBAND_RECEIVER_ADC_ADDRESS 0x34 #define EPS_BOARD_ADC_ADDRESS 0x35 #define I2C_EEPROM_ADDR 0x50 /* This is the maximum number of channels across all ADCs */ #define MAXIMUM_CHANNELS 12 #define NUMBER_OF_ADCS 3 typedef struct _CHANNEL_MAP { uint8_t copyChannel; SENSOR_NAME sensorName; }CHANNEL_MAP; /** Structure used for holding configuration data for a single ADC. */ typedef struct _ADC_CONFIG { uint32_t I2CAddress; /**< The I2C address of the ADC. */ uint8_t configurationByte; /**< The channel configuration byte to send for setting up the ADC. */ uint8_t setUpByte; /**< The setup byte used for configuring an ADC. */ // uint8_t configured; /**< If this is true then the ADC has been correctly configured and is ready for use. */ uint8_t numberOfChannels; /**< The number of configured channels on this ADC. */ CHANNEL_MAP channelMap[MAXIMUM_CHANNELS]; /**< Contains the mapping from each channel read to the output buffer. */ }ADC_CONFIG; /* Contains all information on each ADC and also what channels to write to what location in the output buffer - this includes a flag for deciding whether to copy or not. */ ADC_CONFIG adcConfiguration[NUMBER_OF_ADCS] = { {LBAND_RECEIVER_ADC_ADDRESS, 0x82, 0x07, 4, { 1, TRANSPONDER_RSSI, 1, COMMAND_DOPPLER_SHIFT, 1, COMMAND_RSSI, 1, COMMAND_OSCILATTOR_TEMPERATURE }, }, {BPSK_TRANSMITTER_ADC_ADDRESS, 0x82, 0x0F, 8, { 1, BPSK_REVERSE_POWER, 1, BPSK_FORWARD_POWER, 1, BPSK_POWER_AMPLIFIER_TEMPERATURE, 0, (SENSOR_NAME)0, 1, BPSK_TONE_CURRENT, 1, FM_POWER_AMPLIFIER_TEMPERATURE, 1, BPSK_POWER_AMPLIFIER_CURRENT, 1, FM_POWER_AMPLIFIER_CURRENT }, }, {EPS_BOARD_ADC_ADDRESS, 0x82, 0x15, 12, { 1, EPS_PROCESSOR_TEMPERATURE, 1, STRUCTURE_TEMPERATURE, 1, EPS_DC_TO_DC_CONVERTER_TEMPERATURE, 1, EPS_DC_TO_DC_CONVERTER_CURRENT, 1, EPS_DC_TO_DC_CONVERTER_VOLTAGE, 1, EPS_SMPS_6V_VOLTAGE, 1, EPS_SMPS_9V_VOLTAGE, 1, EPS_SMPS_3V_VOLTAGE, 1, EPS_SMPS_6V_CURRENT, 1, EPS_SMPS_3V_CURRENT, 1, EPS_SMPS_9V_CURRENT, }, } }; uint16_t * p_returnData = 0; /**< Diagnostics data buffer, all retrieved ADC data is to be returned to here. */ uint32_t returnDataSize = 0; /**< The size of the buffer pointed to by p_diagnosticData */ /* Private functions. */ //static ADC_ERROR GetADCDiagnosticsData(&informationStructure); static ADC_ERROR InitialiseI2C(void); static ADC_ERROR ConfigureADC(uint32_t z_ADCNumber); static ADC_ERROR ReadADC(uint32_t z_ADCNumber, uint16_t * z_outputBuffer); static uint16_t ConvertADCTwoByteFormatToAValue(uint16_t z_value); static ADC_ERROR TransferDataToOutput(uint32_t z_adcNumber, uint16_t * z_buffer, uint32_t z_bufferSize, uint16_t * z_outputBuffer, uint32_t z_outputBufferSize); /** * Perform initalisation of the I2C bus, and also send a set up packet to each ADC. * \param[out] z_interface: Pointer to the interface structure for future ADC usage. * \return ADC_ERROR code */ ADC_ERROR ADCInitialise(uint16_t * z_buffer, uint32_t z_size) { ADC_ERROR retVal = NO_ERROR_ADC; if(z_buffer != 0 && z_size != 0) { if(InitialiseI2C() == NO_ERROR_ADC) { /* Store our output buffer location. */ p_returnData = z_buffer; returnDataSize = z_size; retVal = NO_ERROR_ADC; } else { retVal = COULD_NOT_INITIALISE_ADC; } } else { retVal = NO_BUFFER_PROVIDED_ADC; } return retVal; } /** * Perform initalisation of the I2C bus and send a set-up packet to each specified ADC. * \return DIAGNOSTICS_ERROR code */ ADC_ERROR InitialiseI2C(void) { ADC_ERROR retVal = COULD_NOT_INITIALISE_ADC; /* Declared static to allow for testing. */ static const gpio_map_t twim_gpio_map = { {AVR32_TWIMS0_TWCK_0_0_PIN, AVR32_TWIMS0_TWCK_0_0_FUNCTION}, {AVR32_TWIMS0_TWD_0_0_PIN, AVR32_TWIMS0_TWD_0_0_FUNCTION} }; /* Configure clock speeds and addresses for our I2C bus - Declared static to allow for testing. */ static const twi_options_t twimOptions = {CLK_PBA_F, I2C_BAUD, EPS_BOARD_ADC_ADDRESS, 0}; //@todo not convinced that we should be giving the I2C address of another module here! /* Enable the twim module. */ if(gpio_enable_module(twim_gpio_map, sizeof(twim_gpio_map)/sizeof(twim_gpio_map[0])) == GPIO_SUCCESS) { /* Initialise our I2C module */ if(twim_master_init(I2C_MODULE, &twimOptions) == TWI_SUCCESS) { uint32_t numberOfADCs = sizeof(adcConfiguration)/sizeof(adcConfiguration[0]); uint32_t i = 0; /* Assume no error at this point. */ retVal = NO_ERROR_ADC; /* Configure each of our ADCs in order. */ for(i = 0; i < numberOfADCs; i++) { if(ConfigureADC(i) == NO_ERROR_ADC) { /* Record that this ADC has been configured successfully. */ } else { /* We failed to initialise at least one ADC - view the configured flags for diagnostics data. */ retVal = COULD_NOT_INITIALISE_ADC; } } } } return retVal; } ADC_ERROR ConfigureADC(uint32_t z_ADCNumber) { ADC_ERROR retVal = INVALID_ADC_SPECIFIED; twi_package_t adcPacket; /* Ensure we haven't gotten a setup request for an ADC thats not in our table. */ if(z_ADCNumber < sizeof(adcConfiguration)/sizeof(adcConfiguration[0])) { /* Configure our set/configuation packet to send. */ adcPacket.chip = adcConfiguration[z_ADCNumber].I2CAddress; adcPacket.addr[0] = adcConfiguration[z_ADCNumber].configurationByte; adcPacket.addr[1] = adcConfiguration[z_ADCNumber].setUpByte; adcPacket.addr_length = 2; adcPacket.buffer = 0; adcPacket.length = 0; /* Send our setup/configuration packet. */ if(twim_write_packet(I2C_MODULE, &adcPacket) == STATUS_OK) { retVal = NO_ERROR_ADC; } } return retVal; } ADC_ERROR TransferDataToOutput(uint32_t z_adcNumber, uint16_t * z_buffer, uint32_t z_bufferSize, uint16_t * z_outputBuffer, uint32_t z_outputBufferSize) { ADC_ERROR retVal = INVALID_ADC_SPECIFIED; uint32_t i = 0; if(z_buffer != 0 && z_adcNumber < NUMBER_OF_ADCS) { retVal = NO_ERROR_ADC; for(i = 0; i < adcConfiguration[z_adcNumber].numberOfChannels; i++) { if(adcConfiguration[z_adcNumber].channelMap[i].copyChannel != 0) { if(z_outputBufferSize > (uint32_t)adcConfiguration[z_adcNumber].channelMap[i].sensorName) { if(z_bufferSize > i) { z_outputBuffer[(uint32_t)adcConfiguration[z_adcNumber].channelMap[i].sensorName] = ConvertADCTwoByteFormatToAValue(z_buffer[i]); } } } } } return retVal; } /** * Fetch telemetry data from a single ADC channel. * \param[in] z_name: The sensor enumeration to fetch data from. * \param[out] z_buffer: The location to write telemetry data out to. * \return ADC_ERROR code */ ADC_ERROR FetchDiagnosticsData(void) { ADC_ERROR retVal = ADC_NOT_INITIALISED; uint16_t receiveBuffer[MAXIMUM_CHANNELS]; /* Check that we have been initialised. */ if(p_returnData != 0 && returnDataSize != 0) { uint32_t numberOfADCs = sizeof(adcConfiguration)/sizeof(adcConfiguration[0]); uint32_t i = 0; /* Assume no error at this point. */ retVal = NO_ERROR_ADC; /* Read from each of our ADCs in order. */ for(i = 0; i < numberOfADCs; i++) { if(ReadADC(i, receiveBuffer) == NO_ERROR_ADC) { TransferDataToOutput(i, receiveBuffer, sizeof(receiveBuffer)/sizeof(receiveBuffer[0]), p_returnData, returnDataSize); /* @todo Record that we read successfully */ } else { retVal = COULD_NOT_READ_ADC; } } } return retVal; } /** * Read data out of a single ADC channel. * \param[in] z_name: The sensor enumeration to fetch data from. * \param[out] z_buffer: The location to write telemetry data out to. * \return ADC_ERROR code */ ADC_ERROR ReadADC(uint32_t z_ADCNumber, uint16_t * z_outputBuffer) { twi_package_t readADCPacket; ADC_ERROR retVal = INVALID_ADC_SPECIFIED; /* Ensure we haven't gotten a setup request for an ADC thats not in our table. */ if(z_ADCNumber < sizeof(adcConfiguration)/sizeof(adcConfiguration[0])) { /* Configure our read data structure. */ readADCPacket.addr_length = 0; readADCPacket.buffer = (void*)z_outputBuffer; readADCPacket.chip = adcConfiguration[z_ADCNumber].I2CAddress; readADCPacket.length = (adcConfiguration[z_ADCNumber].numberOfChannels * sizeof(uint16_t)); /* Times uint16_t to convert to 1 bits per reading. */ /* Perform a read of the I2C bus. */ if(twim_read_packet(I2C_MODULE, &readADCPacket) == STATUS_OK) { retVal = NO_ERROR_ADC; } } return retVal; } void ADCUninitialise(void) { /* We can no longer assume this data store is valid - delete the reference. */ p_returnData = 0; returnDataSize = 0; } /** * The ADC provides data in a two byte format with the 2MSBs of one byte being used along with the other byte * to produce a 10 bit value that represents the analogue value. * This function will convert from this format into a usable value in a uint32_t. * \param[in] z_value: Value to convert. * \return Converted value. @todo error checking has not been properly considered here! */ uint16_t ConvertADCTwoByteFormatToAValue(uint16_t z_value) { uint16_t retVal = z_value & 0x03FF; return retVal; }
C
#include <stdio.h> #include <stdlib.h> #include<string.h> #include <ctype.h> #include <math.h> #include "linkedList.h" /*This function takes in two strings for name and food group, the number of calories the food contained and a single character representing the type of food (h for healthy, j for junk). The function allocates memory for the struct, initializes the variables to the supplied values, initializes the next pointer to null and returns a pointer to the allocated memory. Returns NULL on failure.The value for name and group are copied into newly allocated memory. The passed-in memory for name and group must be freed elsewhere in the program. Memory for the struct must be freed elsewhere in the program. */ Food * createRecord(char * name, char * group, double calories, char theType) { Food* foodPtr; foodPtr = malloc(sizeof(Food)); if (foodPtr == NULL) { return NULL; /* printf("Error while allocating memory."); exit(0); */ } foodPtr->name = malloc(sizeof(char)*(strlen(name)+1)); if (foodPtr->name == NULL) { return NULL; /* printf("Error while allocating memory."); exit(0); */ } foodPtr->foodGroup = malloc(sizeof(char)*(strlen(group)+1)); if (foodPtr->foodGroup == NULL) { return NULL; /* printf("Error while allocating memory."); exit(0); */ } /* To DO Handle, in case of 'name' or 'foodGroup' is NULL */ strcpy(foodPtr->name,name); strcpy(foodPtr->foodGroup,group); foodPtr->calories = calories; foodPtr->type = theType; foodPtr->next = NULL; return foodPtr; } /*This function takes a pointer to a food linked list element and returns a pointer to a string that contains the information from the struct formatted in the following manner: "Name (Food Group):calories[type] The string should not contain a newline. Calories should be reported to two decimal places, padding where necessary. The string memory is allocated in this function and must be freed elsewhere in the program. */ char * printRecord(Food * toPrint) { char * strToPrint; double temp; char tempChar[50]; char charStr[2] = "\0"; temp = ceilf(toPrint->calories * 100) / 100; snprintf(tempChar,50,"%.2f",temp); if ((toPrint->name != NULL) && (toPrint->foodGroup != NULL)) { strToPrint = malloc(sizeof(char)*((strlen(toPrint->name)+1)+(strlen(toPrint->foodGroup)+1)+(50+1)+(strlen(charStr)))); } else { if ((toPrint->name == NULL) && (toPrint->foodGroup == NULL)) { strToPrint = malloc(sizeof(char)*(1+1+(strlen(tempChar)+1)+(strlen(charStr)))); } else { if (toPrint->name == NULL) { strToPrint = malloc(sizeof(char)*((1)+(strlen(toPrint->foodGroup)+1)+(strlen(tempChar)+1)+(strlen(charStr)))); } else { strToPrint = malloc(sizeof(char)*((strlen(toPrint->name)+1)+(1)+(strlen(tempChar)+1)+(strlen(charStr)))); } } } strcpy(strToPrint, ""); if (toPrint->name == NULL) { strcat(strToPrint," "); } else { strcat(strToPrint,toPrint->name); } strcat(strToPrint," ("); if (toPrint->foodGroup == NULL) { strcat(strToPrint," "); } else { strcat(strToPrint,toPrint->foodGroup); } strcat(strToPrint,"):"); strcat(strToPrint,tempChar); strcat(strToPrint,"["); charStr[0] = toPrint->type; strcat(strToPrint,charStr); strcat(strToPrint,"]"); return strToPrint; } /*Takes a pointer to a list element and frees the memory for the internal variables. the struct itself must be freed separately */ void destroyElement(Food * theElement) { free(theElement->name); theElement->name = NULL; free(theElement->foodGroup); theElement->foodGroup = NULL; } /*addToFront(Food * theList, Food * toBeAdded) Takes a pointer to the head of the list and an initialized list element. Adds the element to the front of the linked list and returns a pointer to the new head of the list. */ Food * addToFront(Food * theList, Food * toBeAdded) { /* To DO Use isEmpty function to check */ if (toBeAdded != NULL) { if (isEmpty(theList)) { theList = toBeAdded; toBeAdded->next = NULL; } else { toBeAdded->next = theList; theList = toBeAdded; } } return theList; } /*addToBack(Food * theList, Food * toBeAdded) Takes a pointer to the head of the list and an initialized list element. Adds the element to the back of the linked list and returns a pointer to the head of the list. */ Food * addToBack(Food * theList, Food * toBeAdded) { Food * tempFood; tempFood = theList; /* To DO Use isEmpty function to check */ if (toBeAdded != NULL) { if (isEmpty(theList)) { theList = toBeAdded; toBeAdded->next = NULL; } else { while (tempFood->next != NULL) { tempFood = tempFood->next; } tempFood->next = toBeAdded; toBeAdded->next = NULL; } } return theList; } /*removeFromFront(Food * theList) Takes a pointer to the head of the list. Removes the front item from the head of the list. Does not free the memory for the item removed. Returns a pointer to the head of the list. Returns NULL if the list is empty*/ Food * removeFromFront(Food * theList) { Food * tempFoodOne; /* To DO Use isEmpty function to check */ if (isEmpty(theList)) { return NULL; } tempFoodOne = theList; theList = theList->next; tempFoodOne->next = NULL; return theList; } /*removeFromBack(Food * theList) Takes a pointer to the head of the list. Removes the last item from the head of the list. Does not free the memory for the item removed. Returns a pointer to the head of the list. Returns NULL if the list is empty. */ Food * removeFromBack(Food * theList) { Food * tempFood; Food * newLast; newLast = tempFood = theList; /* To DO Use isEmpty function to check */ if (isEmpty(theList)) { return NULL; } while (tempFood->next != NULL) { newLast = tempFood; tempFood = tempFood->next; } newLast->next = NULL; tempFood->next = NULL; return theList; } /*getLastItem(Food * theList) Takes a pointer to the head of the list. Returns a pointer to the item at the end of the list. Returns NULL if the list is empty. */ Food * getLastItem(Food * theList) { Food * tempFood; tempFood = theList; /* To DO Use isEmpty function to check */ if (isEmpty(theList)) { return NULL; } while (tempFood->next != NULL) { tempFood = tempFood->next; } return tempFood; } /*isEmpty(Food * theList) Takes a pointer to the head of the list. Returns true if the list is empty and false if the list has elements. */ bool isEmpty(Food * theList) { if (theList == NULL) { return true; } else { return false; } } /*printList(Food * theList) Takes a pointer to the head of the list. Prints to stdout all of the elements of the list (formatted as specified for the printRecord function) separated by newlines. */ void printList(Food * theList) { char * stringToPrint = NULL; if (!(isEmpty(theList))) { do { stringToPrint = printRecord(theList); printf("%s \n",stringToPrint); free(stringToPrint); stringToPrint = NULL; theList = theList->next; } while (theList != NULL); } } /*destroyList(Food * theList) Takes a pointer to the list and frees the memory for each struct in the list. Handles an empty list gracefully. */ void destroyList(Food * theList) { Food * tempList; if (!(isEmpty(theList))) { do { tempList = theList->next; destroyElement(theList); free(theList); theList = NULL; theList = tempList; } while (theList != NULL); } }
C
#include<stdio.h> int division(int, long long int *, long long int *); int main(void) { int n; int num = 0; long long int a, b; while(scanf("%lld %lld %d", &a, &b, &n) != EOF) { printf("%d.", division(num, &a, &b)); int i; for(i = 0; i < n; i++) printf("%d", division(num, &a, &b)); printf("\n"); } return 0; } int division(int num, long long int *a, long long int *b) { num = *a / *b; *a = *a % *b; *a *= 10; return num; }
C
#include "ft_printf.h" int int_length(unsigned int n) { int res; res = 0; while (n > 0) { res++; n /= 10; } return (res); } int print_int(int n, int zeros, int spaces) { int res; int i; int len; int sp = spaces; len = 0; res = 0; i = 0; zeros = (n < 0) ? zeros - 1 : zeros; if (n < 0) { n *= -1; res++; len += write(1,"-",1); } i = 0; while (i++ < (sp + zeros) - int_length(n)) len += (spaces > 0 && spaces--) ? write(1," ",1) : write(1,"0",1); /*i = 0; while (i++ < zeros - int_length(n)) len += write(1,"0",1);*/ len += (n != -2147483648) ? ft_d_conversion(n) : write(1,"2147483648",10); return (len); } int print_unsigned(unsigned int n, int zeros, int spaces) { int i; int len; spaces++; len = 0; i = 0; while (i++ < zeros - int_length(n)) len += write(1,"0",1); len += ft_u_conversion(n); return (len); } int print_x(unsigned int x,int zeros, int spaces) { int i; int len; spaces++; len = 0; i = 0; while (i++ < zeros - ft_x_len(x)) len += write(1,"0",1); len += ft_x_conversion(x); return (len); } int print_xx(unsigned int x,int zeros, int spaces) { int i; int len; spaces++; len = 0; i = 0; while (i++ < zeros - ft_x_len(x)) len += write(1,"0",1); len += ft_xx_conversion(x); return (len); } int print_point(const char **s, int zeros, va_list vl) { int spaces; int i; i = 0; spaces = (*(*s)++ != '*') ? ft_atoi(*s) : va_arg(vl,int); if (**s == '*') (*s)++; while (**s <= '9' && **s >= '0') (*s)++; if (**s == 'd') return (print_int(va_arg(vl,int), zeros - (zeros - spaces), zeros - spaces)); return (1); } int ft_0_flag(const char **s, va_list vl) { int zeros; zeros = 0; while (**s == '0') (*s)++; zeros = (**s != '*') ? ft_atoi(*s) : va_arg(vl,int); if (**s == '*') (*s)++; while (**s >= '0' && **s <= '9') (*s)++; if (**s == 'd' || **s == 'i') return(print_int(va_arg(vl,int),zeros,0)); else if (**s == 'u') return(print_unsigned(va_arg(vl,unsigned int),zeros,0)); else if (**s == 'x') return(print_x(va_arg(vl,unsigned int),zeros,0)); else if (**s == 'X') return(print_xx(va_arg(vl,unsigned int),zeros,0)); else if (**s == '.') return(print_point(s,zeros,vl)); return (0); }
C
#define _CRT_SECURE_NO_WARNINGS 1 #include<stdio.h> #include<string.h> char* my_swap(char* str,int len) { char* stars = str; char* end = str + len; --end; char tmp; while (end > stars) { tmp = *end; *end = *stars; *stars = tmp; stars++; end--; } return str; } int main() { char str[100]; gets(str); int len = strlen(str); my_swap(str,len); return 0; }
C
#include <stdio.h> main(){ int ano; char sexo; printf("Informe o ano de nascimento: "); scanf("%d", &ano); printf("Informe o sexo (M/F): "); scanf(" %c", &sexo); if((sexo == 'M') && ((2015 - ano) >= 18)) printf("Servico militar obrigatorio!"); else printf("isento do servico militar"); }
C
#include <stdio.h> // Julian canlender vs Gregorian canlender int isLeapYear(int year) { if((year%4==0)&&(year%100!=0)) { return 1; } if(year%400==0) { return 1; } return 0; } int days(int year, int month, int day) { int res=day; month--; switch(month) { case 11: res+=30; case 10: res+=31; case 9: res+=30; case 8: res+=31; case 7: res+=31; case 6: res+=30; case 5: res+=31; case 4: res+=30; case 3: res+=31; case 2: res+=28; case 1: res+=31; } if(isLeapYear(year)&&month>=2) { res++; } return res; } int valid(int year, int month, int day) { // test year if(year<=0) return 0; // test month if(month<=0||month>=13) return 0; // test day if(day<=0) return 0; if(month== 1&&day>31) return 0; if(isLeapYear(year)==0&&month== 2&&day>28) return 0; if(isLeapYear(year)==1&&month== 2&&day>29) return 0; if(month== 3&&day>31) return 0; if(month== 4&&day>30) return 0; if(month== 5&&day>31) return 0; if(month== 6&&day>30) return 0; if(month== 7&&day>31) return 0; if(month== 8&&day>31) return 0; if(month== 9&&day>30) return 0; if(month==10&&day>31) return 0; if(month==11&&day>30) return 0; if(month==12&&day>31) return 0; return 1; } int main() { int day=23; int month=4; int year=2019; printf("Input: year month day(Three Integers):\n"); while(1) { if(scanf("%d %d %d",&year,&month,&day)==3) { if(valid(year,month,day)==1) { break; } else { printf("%d.%d.%d is invalid!\n",year,month,day); } } // else // { // while(getchar()!='\n') //Eat invalid input // { // } // printf("Please Input Three Integers!!!\n"); // } } printf("%d.%d.%d is No.%d days of the year!\n",year,month,day,days(year,month,day)); return 0; }
C
#include "utils.h" //************************************************* //! Create and bind the port to an available fd /*! \param port \li The string representation of the port number \return \li The new fd on success, -1 otherwise */ //************************************************* int create_and_bind(char *port) { struct addrinfo hints; struct addrinfo *result, *rp; int s, sfd; memset(&hints, 0, sizeof(struct addrinfo)); hints.ai_family = AF_UNSPEC; hints.ai_socktype = SOCK_STREAM; hints.ai_flags = AI_PASSIVE; s = getaddrinfo(NULL, port, &hints, &result); if (s != 0) { fprintf(stderr, "getaddrinfo: %s\n", gai_strerror(s)); return -1; } for (rp = result; rp != NULL; rp = rp->ai_next) { sfd = socket(rp->ai_family, rp->ai_socktype, rp->ai_protocol); if (sfd == -1) continue; s = bind(sfd, rp->ai_addr, rp->ai_addrlen); if (s == 0) { // bind successfully break; } close(sfd); } if (rp == NULL) { fprintf(stderr, "cound not bind\n"); return -1; } freeaddrinfo(result); return sfd; } //************************************************* //! Set a fd in non-blocking mode /*! \param fd \li The file descriptor \return \li 0 on success, -1 otherwise */ //************************************************* int make_socket_non_blocking(int fd) { int flags, s; flags = fcntl(fd, F_GETFL, 0); if (flags == -1) { perror("fcntl"); return -1; } flags |= O_NONBLOCK; s = fcntl(fd, F_SETFL, flags); if (s == -1) { perror("fcntl"); return -1; } return 0; } //************************************************* //! Open the listen fd /*! \param port \li The port number \return \li fd on success, -1 otherwise */ //************************************************* int open_listenfd(int port) { if (port <= 0) { port = 3000; } int listenfd, optval=1; struct sockaddr_in serveraddr; /* Create a socket descriptor */ if ((listenfd = socket(AF_INET, SOCK_STREAM, 0)) < 0) return -1; /* Eliminates "Address already in use" error from bind. */ if (setsockopt(listenfd, SOL_SOCKET, SO_REUSEADDR, (const void *)&optval , sizeof(int)) < 0) return -1; /* Listenfd will be an endpoint for all requests to port on any IP address for this host */ bzero((char *) &serveraddr, sizeof(serveraddr)); serveraddr.sin_family = AF_INET; serveraddr.sin_addr.s_addr = htonl(INADDR_ANY); serveraddr.sin_port = htons((unsigned short)port); if (bind(listenfd, (struct sockaddr *)&serveraddr, sizeof(serveraddr)) < 0) return -1; /* Make it a listening socket ready to accept connection requests */ if (listen(listenfd, LISTENQ) < 0) return -1; return listenfd; }
C
int Solution::diffPossible(vector<int> &A, int B) { int k=1; for(int i=0;i<A.size()-1&&k<A.size(); ){ int dif=A[i]+B; if(dif==A[k]&&k!=i) return 1; if(A[k]>dif) { i++; }else{ k++; } } return 0; }
C
#include <stdio.h> int main_1() { int test_case; int i; int a, b; int temp; int result; scanf_s("%d", &test_case); for (i = 0; i<test_case; i++) { scanf_s("%d %d", &a, &b); temp = a % 10; switch (temp) { case 1: result = 1; break; case 2: b = b % 4 ; if (b == 0) result = 6; else if(b == 1) result = 2; else if (b == 2) result = 4; else result = 8; break; case 3: b %= 4; if (b == 0) result = 1; else if (b == 1) result = 3; else if (b == 2) result = 9; else result = 7; break; case 4: b = b % 2; if (b == 0) result = 6; else result = 4; break; case 5: result = 5; break; case 6: result = 6; break; case 7 : b %= 4; if (b == 0) result = 1; else if (b == 1) result = 7; else if (b == 2) result = 9; else result = 3; break; case 8 : b %= 4; if (b == 0) result = 6; else if (b == 1) result = 8; else if (b == 2) result = 4; else result = 2; break; case 9 : b = b % 2; if (b == 0) result = 1; else result = 9; break; case 0 : result = 10; break; } printf("%d\n", result); } return 1; }
C
//Sorgente scritto da Marco Meli. Remember, Smagen is the way. #include <stdio.h> int massimo (int a, int b, int c); int main () { int a,b,c, max; printf ("Inserisci A: "); scanf ("%d", &a); printf ("\nInserisci B: "); scanf ("%d", &b); printf ("\nInserisci C: "); scanf ("%d", &c); max = massimo (a,b,c); printf ("\nIl valore massimo e': %d\n", max); return 0; } int massimo (int a, int b, int c) { if (a>=b && a>=c) return a; if (b>=a && b>=c) return b; //if (c>=a && c>=b) return c; return c; }
C
#ifndef employee_H_INCLUDED #define employee_H_INCLUDED typedef struct { int id; char nombre[128]; int horasTrabajadas; int sueldo; }Employee; /** \brief creates a dynamic memory space * * \return Employee* returns a pointer to the created memory space * */ Employee* employee_new(); /** \brief creates a dynamic memory space with parameters * * \param char* receive a pointer to id * \param char* receive a pointer to nombre * \param char* receive a pointer to horasTrabajadas * \param char* receive a pointer to sueldo * \return Employee* return a pointer to the created memory space * */ Employee* employee_newParametros(char* idStr,char* nombreStr,char* horasTrabajadasStr,char* sueldoStr); /** \brief remove an employee * * \return void * */ void employee_delete(); /** \brief saves a variable per parameter in the structure * * \param Employee Employee* receive the structure employee * \param id int receive id * \return int return (1) ok, error (0) * */ int employee_setId(Employee* Employee,int id); /** \brief gets a value from the structure and returns it by parameter * * \param Employee Employee* receive the structure employee * \param id int* receive a pointer to id * \return int return (1) ok, error (0) * */ int employee_getId(Employee* Employee,int* id); /** \brief saves a variable per parameter in the structure * * \param Employee Employee* receive the structure employee * \param nombre char* receive a pointer to name * \return int return (1) ok, error (0) * */ int employee_setNombre(Employee* Employee,char* nombre); /** \brief gets a value from the structure and returns it by parameter * * \param Employee Employee* receive the structure employee * \param nombre char* receive a pointer to name * \return int return (1) ok, error (0) * */ int employee_getNombre(Employee* Employee,char* nombre); /** \brief saves a variable per parameter in the structure * * \param Employee Employee* receive the structure employee * \param horasTrabajadas int receive a pointer to horasTrabajadas * \return int return (1) ok, error (0) * */ int employee_setHorasTrabajadas(Employee* Employee,int horasTrabajadas); /** \brief gets a value from the structure and returns it by parameter * * \param Employee Employee* receive the structure employee * \param horasTrabajadas int* recieve horasTrabajadas * \return int return (1) ok, error (0) * */ int employee_getHorasTrabajadas(Employee* Employee,int* horasTrabajadas); /** \brief saves a variable per parameter in the structure * * \param Employee Employee* receive the structure employee * \param sueldo int receive a pointer to sueldo * \return int return (1) ok, error (0) * */ int employee_setSueldo(Employee* Employee,int sueldo); /** \brief gets a value from the structure and returns it by parameter * * \param Employee Employee* receive the structure employee * \param sueldo int* receive sueldo * \return int return (1) ok, error (0) * */ int employee_getSueldo(Employee* Employee,int* sueldo); /** \brief sorting criteria by name * * \param e1 Employee* receive an item 1 * \param e2 Employee* receive an item 2 * \return int returns if I can order or not * */ int employee_CompareByName(void* e1, void* e2); /** \brief sorting criteria by id * * \param e1 Employee* receive an item 1 * \param e2 Employee* receive an item 2 * \return int returns if I can order or not * */ int employee_CompareById(void* e1, void* e2); #endif // employee_H_INCLUDED
C
//work21 #include<stdio.h> #include<string.h> int main(){ char basic[20][20], new_basic[20][20]; int n; memset(basic, '\0', sizeof(basic)); memset(new_basic, '\0', sizeof(new_basic)); scanf("%s", basic); int new_i=0, new_j=0; for(int i=0; i<20; i++){ ///q@নG for(int j=0; j<20; j++){ new_basic[new_i][new_j]=basic[i][j]; if(basic[i][j]==' '){ basic[i][j]='\0'; new_basic[new_i][new_j]='\0'; new_i++;new_j=0; }else{ new_j++; } //printf("i=%d, j=%d, new_basic[i][j]=%c\n", i, j, new_basic[i][j]); } } for(int i=0; i<20; i++){ ///sNGL}Cs^basic for(int j=0; j<20; j++){ basic[i][j]=new_basic[i][j]; //printf("basic[i][j]=%c\n", basic[i][j]); } } scanf("%d\n", &n); int amount_array[n][20]; for(int k=0; k<n; k++){ printf("n=%d\n", n); printf("k=%d\n", k); char temp[20][20];memset(temp, '\0', sizeof(temp)); char new_temp[20][20];memset(new_temp, '\0', sizeof(new_temp)); scanf("%s", temp); new_i=0;new_j=0; for(int i=0; i<20; i++){ ///q@নG for(int j=0; j<20; j++){ new_temp[new_i][new_j]=temp[i][j]; if(temp[i][j]==' '){ temp[i][j]='\0'; new_temp[new_i][new_j]='\0'; new_i++;new_j=0; }else{ new_j++; } //printf("i=%d, j=%d, temp[i][j]=%c\n", i, j, temp[i][j]); } } for(int i=0; i<20; i++){ ///sNG}C^temp for(int j=0; j<20; j++){ temp[i][j]=new_temp[i][j]; //printf("temp=%c\n", temp[i][j]); } } for(int i=0; i<20; i++){ for(int j=0; j<20; j++){ //printf("................"); //printf("compare//%c, %c, %d\n", temp[i][j], basic[i][j], temp[i][j]==basic[i][j]); if(temp[i][j]==basic[i][j]){ amount_array[k][i]=1; }else{ amount_array[k][i]=0; break; } } } //printf("===========================\n"); } for(int i=0; i<n; i++){ for(int j=0; j<20; j++){ //printf("////////////////////"); printf("%d",amount_array[i][j]); } printf("\n"); } } /* happy birthday to you 4 happy to you birthday birthday to you happy birthday output:2 */
C
#include <stdio.h> #define MAX_SIZE 1000 void swap(int *a, int *b); void bubbleSort(int *arr, int n); int minSum(int *arr, int n); int main() { int arr[MAX_SIZE]; int N; scanf("%d", &N); for (int i = 0; i < N; i++) scanf("%d", &arr[i]); printf("%d\n", minSum(arr, N)); return 0; } void swap(int *a, int *b) { int temp; temp = *a; *a = *b; *b = temp; } void bubbleSort(int *arr, int n) { for (int i = 0; i <= n - 2; i++) { for (int j = 0; j <= n - 2 - i; j++) { if (arr[j] >= arr[j + 1]) swap(&arr[j], &arr[j + 1]); } } } int minSum(int *arr, int n) { int pSum = 0; int cSum = 0; bubbleSort(arr, n); for (int i = 0; i < n; i++) { pSum += arr[i]; cSum += pSum; } return cSum; }
C
/* 5) Construa um algoritmo que contenha uma lista dinmica homognea para guardar nmeros digitados pelo usurio, solicite ao usurio a quantidade de nmero e os nmeros e depois os imprima em tela. R.: */ #include <stdio.h> typedef struct lista{ int num; struct lista *prox; }LISTA; LISTA* insercao(LISTA* inicio, int num); void impressao(LISTA *inicio); int main (void){ int quantidade, numero; LISTA *l = NULL; printf("Digite a quantidade: "); scanf("%i",&quantidade); fflush(stdin); while (quantidade >= 1){ printf("Digite um numero:"); scanf("%i",&numero); fflush(stdin); l=insercao(l, numero); quantidade--; } impressao(l); return 0; } LISTA* insercao(LISTA *inicio, int num){ LISTA *l = (LISTA*) malloc(sizeof(LISTA)); l->num=num; if(inicio == NULL){ inicio=l; l->prox=NULL; }else{ l->prox=inicio; inicio=l; } return inicio; } void impressao(LISTA *inicio){ LISTA *aux; aux=inicio; while(aux!=NULL){ printf("%i, ",aux->num); aux=aux->prox; } }
C
#ifndef _MODEL_H_ #define _MODEL_H_ #include <stdint.h> #include "Insight.h" /* Custom model declaration. Is an array of 4 elements: - 1st is the vbo id - 2nd is the vao id - 3nd is the ibo id - 4th is the indices count */ typedef uint32_t Insight_Model[4]; /*! Returns a pointer to a model in memory with indices. */ INSIGHT_API void insight_model(Insight_Model self, const float* const vertices, const uint32_t* const indices, uintptr_t vert_size, uintptr_t indices_count); /*! Starts using the given model, so the user can start managing the model. */ INSIGHT_API void insight_model_begin(Insight_Model self); /*! Draw the model onto screen. NOTE: 'model_begin' and 'model_end', should be called before and after this function, respectively. */ INSIGHT_API void insight_model_draw(Insight_Model self, GLenum type); /*! Stops using the current binded model, so the user cannot handle it anymore. */ INSIGHT_API void insight_model_end(); /*! Deletes the memory of the given model. */ INSIGHT_API void insight_model_finalize(Insight_Model self); /* * ============================================================== * * IMPLEMENTATION * * =============================================================== */ #ifdef INSIGHT_MODEL_IMPL #include <malloc.h> #include <assert.h> INSIGHT_API void insight_model(Insight_Model self, const float* const vertices, const uint32_t* const indices, uintptr_t vert_size, uintptr_t indices_count) { /* allocate the vao on the first element of the array */ glGenVertexArrays(1, &self[0]); glBindVertexArray(self[0]); glGenBuffers(1, &self[1]); glBindBuffer(GL_ARRAY_BUFFER, self[1]); glBufferData(GL_ARRAY_BUFFER, vert_size, vertices, GL_STATIC_DRAW); glGenBuffers(1, &self[2]); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, self[2]); glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(uint32_t) * indices_count, indices, GL_STATIC_DRAW); glEnableVertexAttribArray(0); glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, sizeof(float) * 5, (void*)0); glEnableVertexAttribArray(1); glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, sizeof(float) * 5, (void*)(sizeof(float) * 3)); glDisableVertexAttribArray(0); glDisableVertexAttribArray(1); glBindVertexArray(0); glBindBuffer(GL_ARRAY_BUFFER, 0); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0); self[3] = (uint32_t)indices_count; } INSIGHT_API void insight_model_begin(Insight_Model self) { glBindVertexArray(self[0]); glEnableVertexAttribArray(0); glEnableVertexAttribArray(1); glEnableVertexAttribArray(2); } INSIGHT_API void insight_model_draw(Insight_Model self, GLenum type) { glDrawElements(type, self[3], GL_UNSIGNED_INT, NULL); } INSIGHT_API void insight_model_end() { glDisableVertexAttribArray(0); glDisableVertexAttribArray(1); glDisableVertexAttribArray(2); glBindVertexArray(0); } INSIGHT_API void insight_model_finalize(Insight_Model self) { glDeleteVertexArrays(1, &self[0]); glDeleteBuffers(1, &self[1]); glDeleteBuffers(1, &self[2]); } #endif /* !INSIGHT_MODEL_IMPL */ #endif /* !_MODEL_H_ */
C
#include <stdio.h> #include <string.h> #define MAX_LINE 80 //function main begins program execution int main(void) { //initialize array string char line[MAX_LINE];//sets char delim[] = " ,.!;:\n";// sets up word separators char *words, *ptr; //counter loop initiation int count = 0; //Output question to user for entering words in a string printf("Enter line of text \n"); fgets(line,MAX_LINE,stdin); ptr= line;//define pointer //While loop to count the number of words in the string while ((words = strtok(ptr, delim)) !=NULL) {printf("\n%s\n",words);//Output the number of words count++;//add every word found in the string into the counter ptr = NULL;//continue adding until it becomes 0 or null }//end while printf("%d word(s) in this string \n",count);//Ouput the number of words in the string }//end function main
C
// // Created by ids on 18-4-17. // #include "unp.h" void Bind(int fd, const struct sockaddr *sa, socklen_t salen) { if (bind(fd, sa, salen) < 0) { printf("bind error\n"); exit(1); } } int Accept(int fd, struct sockaddr *sa, socklen_t *salenptr) { int n; again: if ((n = accept(fd, sa, salenptr)) < 0) { #ifdef EPROTO if (errno == EPROTO || errno == ECONNABORTED) #else if (errno == ECONNABORTED) #endif goto again; else printf("accept error\n"); } return (n); } void Connect(int fd, const struct sockaddr *sa, socklen_t salen) { if (connect(fd, sa, salen) < 0) { printf("connect error\n"); exit(1); } } void Listen(int fd, int backlog) { if (listen(fd, backlog) < 0) { printf("listen error\n"); exit(1); } }
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* parse_command.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: kboddez <[email protected]> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2017/04/28 17:49:44 by kboddez #+# #+# */ /* Updated: 2017/04/28 17:50:15 by kboddez ### ########.fr */ /* */ /* ************************************************************************** */ #include "shell.h" static int manage_chev(t_env *e, int *i) { if (*i && e->line[*i - 1] == '&') { ft_putchar('\n'); return (ft_error(NULL, "Ambiguous redirection", NULL)); } else if (*i + 1 < (int)ft_strlen(e->line)) { if (e->line[*i + 1] && e->line[*i + 1] != '&') return (check_parsing_double(e, i, e->line[*i])); while (e->line[*i + 1] && e->line[*i + 2] && (e->line[*i + 2] == ' ' || e->line[*i + 2] == '\t') && e->line[*i + 2]) delete_char(e, (*i + 2)); } else if (*i > 1 && e->line[*i - 1] == e->line[*i] && e->line[*i - 2] == e->line[*i]) insert_char(e, ' ', *i); return (1); } int parse_command(t_env *e) { int i; char quote; i = -1; quote = '\0'; while (e->line[++i]) { if (((e->line[i] == '\"') && ((i - 1 >= 0 && e->line[i - 1] != '\\') || !i)) || e->line[i] == '\'') { if (!quote) quote = e->line[i]; else if (quote == e->line[i]) quote = '\0'; } else if (!quote && (e->line[i] == '|' || e->line[i] == '<')) check_parsing_double(e, &i, e->line[i]); else if (!quote && e->line[i] == '&') check_parsing_ampersand(e, &i); else if (!quote && e->line[i] == ';') check_parsing_simple(e, &i, e->line[i]); else if (!quote && e->line[i] == '>' && manage_chev(e, &i) == -1) return (-1); } return (1); }
C
#ifndef FILE_SYSTEM_H #define FILE_SYSTEM_H void init_bitmap(); void print_bitmap(); void print_blocks(); void init_dir(); void print_ofts(); void print_fds(); //https://stackoverflow.com/questions/389827/namespaces-in-c typedef struct { //create a new file with the specified name sym_name void (* const create)(char* filename); //destroy the named file //returns 1 on success, 0 on error int (* const destroy)(char* filename); //open the named file for reading and writing //returns an index value which is used by subsequent read, write, lseek, or close operations (OFT index) int (* const open)(char* filename); //closes the specified file //returns the oft_index on success //returns -1 on error int (* const close)(int index); // -- operations available after opening the file --// //returns the number of successfully read bytes from file into main memory //reading begins at the current position of the file int (* const read)(int index,char* mem_area,int count); //returns number of bytes written from main memory starting at mem_area into the specified file //writing begins at the current position of the file int (* const write)(int index,char* mem_area,int count); //move to the current position of the file to pos, where pos is an integer specifying //the number of bytes from the beginning of the file. When a file is initially opened, //the current position is automatically set to zero. After each read or write //operation, it points to the byte immediately following the one that was accessed last. int (* const lseek)(int index, int pos); //displays list of files and their lengths void (* const directory)(); //restores ldisk from file.txt or create a new one if no file exists int (* const init)(char* filename); //save ldisk to file.txt int (* const save)(char* filename); //returns 0 if block is free, otherwise it returns 1 if block is taken int (* const isBitEnabled)(int logical_index); void (* const enableBit)(int logical_index); void (* const disableBit)(int logical_index); } filespace_struct; extern filespace_struct const file_system; #endif
C
/* This program predicts whether or not a car with a given licence plate and at a given time can be out on the road from Monday to Friday according to Pico y Placa restriction in Quito, Ecuador */ #include <stdio.h> int checkPlate(int plateNum); int checkDate(char *d); int checkTime(int hour, int minute); void checkRestriction(int dayNum, int plateNum); void allowedOut(void); void notAllowedOut(void); int main (void){ int i = 0; int plateNumber = 0; int plateDigit = 0; int time_h = 0; int time_m = 0; int time = 0; char day[10]; int dayNumber = 0; //Input plate number is stored as integer in variable plateNumber printf("\nEnter 4 digits of plate number:\nOnly enter the digits not the letters.\n\n"); scanf("%d",&plateNumber); //Check if input plate number is not negative, zero or greater than 9999 //Only last digit is kept from plate number in plateDigit //If plate number is not valid it is assigned a value of 10 which will terminate the program plateDigit = checkPlate(plateNumber); if (plateDigit == 10) { printf("Invalid plate number!\n"); return 0; } //Input day is stored as a String in variable day printf("\nEnter, from Monday to Friday, the day in which the car will go out:\n\n"); scanf("%s",day); //Assign a number to the day entered from 1 to 5, 0 is used to assign Saturday and Sunday //If day name is not valid it is assigned a value of 10 which will terminate the program dayNumber = checkDate(day); if (dayNumber == 10) { printf("Invalid day!\n"); return 0; } //Input hour and minutes are stored in variables time_h and time_m respectively printf("\nEnter the time for the car to go out in 24 hour format:\nEnter first the hour, then enter the minutes.\n\n"); scanf("%d%d",&time_h,&time_m); //Check if hours and minutes are valid //If time is not valid it is assigned a value of 5000 which will terminate the program time = checkTime(time_h,time_m); if (time == 5000) {return 0;} printf("\nOn a %s, at %02d:%02d, a car with plate number ending in %d is:\n\n", day, time_h, time_m, plateDigit); //Check if input time is within restriction hours (7:00 - 9:30 and 16:00 - 19:30) if ((time >= 700 && time <= 950) || (time >= 1600 && time <= 1950)){ //Switch case to check whether number plate can go out depending on the day previously assigned to dayNumber checkRestriction(dayNumber,plateDigit); } else { allowedOut(); //If time is outside restriction hours every car is allowed to go out } return 0; //Program ends } int checkPlate(int plateNum){ if ((plateNum <= 0) || (plateNum >= 10000)) { return 10; } return plateNum % 10; //returns only last digit } int checkDate(char *d){ int dayNumber = 0; if (d[0] == 's' || d[0] == 'S'){ //Saturday or Sunday dayNumber = 0; } else if (d[0] == 'm' || d[0] == 'M'){ //Monday dayNumber = 1; } else if (d[1] == 'u' || d[1] == 'U'){ //Tuesday dayNumber = 2; } else if (d[0] == 'w' || d[0] == 'W'){ //Wednesday dayNumber = 3; } else if (d[1] == 'h' || d[1] == 'H'){ //Thursday dayNumber = 4; } else if (d[0] == 'f' || d[0] == 'F'){ //Friday dayNumber = 5; } else { //Anything else is invalid return 10; } return dayNumber; } int checkTime(int hour, int minute){ if (hour > 23 || hour < 0){ printf("Invalid hour!\n"); return 5000; } if (minute > 59 || minute < 0){ printf("Invilid minutes!\n"); return 5000; } return 100 * hour + (100 * minute / 60); } void checkRestriction(int dayNum, int plateNum){ //Switch case to check whether number plate can go out depending on the day previously assigned to dayNumber switch (dayNum){ case 0: allowedOut(); //No restriction on weekends break; case 1: if (plateNum == 1 || plateNum == 2){ //Restriction to 1 and 2 on Monday notAllowedOut(); } else { allowedOut(); } break; case 2: if (plateNum == 3 || plateNum == 4){ //Restriction to 3 and 4 on Tuesday notAllowedOut(); } else { allowedOut(); } break; case 3: if (plateNum == 5 || plateNum == 6){ //Restriction to 5 and 6 on Wednesday notAllowedOut(); } else { allowedOut(); } break; case 4: if (plateNum == 7 || plateNum == 8){ //Restriction to 7 and 8 on Thursday notAllowedOut(); } else { allowedOut(); } break; case 5: if (plateNum == 9 || plateNum == 0){ //Restriction to 9 and 0 on Friday notAllowedOut(); } else { allowedOut(); } break; } } void allowedOut(void){ printf("ALLOWED TO GO OUT\n\n"); } void notAllowedOut(void){ printf("NOT ALLOWED TO GO OUT\n\n"); }
C
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <libxml/parser.h> #include <libxml/tree.h> #include "director.h" int main () { const char* szFilePath = "files//director.xml"; const int DirNum = 3; Director directors[DirNum]; xmlDocPtr doc = xmlParseFile (szFilePath); xmlNodePtr rootElement = xmlDocGetRootElement(doc); int i = 0; for (xmlNodePtr currentNode = rootElement->xmlChildrenNode; currentNode != NULL && i < DirNum; currentNode = currentNode->next ) if (xmlStrcmp(currentNode->name, "director") == 0) DirectorInitialize (&directors[i++], doc, currentNode); for (int i = 0; i < DirNum; i++) DirectorPrintData(&directors[i]); for (int i = 0; i < DirNum; i++) DirectorDeinitialize (&directors[i]); xmlFreeDoc(doc); xmlCleanupParser(); return 0; }
C
#include<stdio.h> #include<string.h> #define N 10001 int judge(int n,char ch,char b[N]) { int i; for(i=0;i<n;i++) { if(ch==b[i])return 0; } return 1; } int main() { char a[N],b[N]; gets(a); gets(b); int i; for(i=0;i<strlen(a);i++) { if(judge(strlen(b),a[i],b)) printf("%c",a[i]); } }
C
/* *** Definisi ABSTRACT DATA TYPE COMMAND *** */ #ifndef COMMAND_H #define COMMAND_H #include "../boolean.h" #include "../point/point.h" #define Nil -1 typedef struct { /* BUILD = 1 UPGRADE = 2 BUY = 3 UNDO = 4 */ /* ID WAHANA "Candy Crush" = 11 "Chocolate Forest" = 12 "Bombom car" = 13 "Lemon Splash" = 14 "Candy Village" = 15 "Candy Swing" = 16 "Blackforest Tornado" = 17 ID MATERIAL air = 21 kayu = 22 batu = 23 besi = 24 */ int comm; /* ID Command */ int name; /* ID Wahana */ int amount; /* Diisi jumlah material yang dibutuhkan, isi Nil jika tidak membutuhkan komponen ini */ int gold; /* Uang yang dibutuhkan */ int map; /* Diisi peta 1/2/3/4, isi Nil jika tidak membutuhkan komponen ini */ POINT coordinate; /* Diisi koordinat dalam peta dengan selektor di adt point, isi Nil jika tidak membutuhkan komponen ini */ int time; /* Diisi waktu yang dibutuhkan dalam command yang digunakan, isi Nil jika tidak membutuhkan komponen ini */ } COMMAND; /* *** Notasi Akses: Selektor COMMAND *** */ #define Comm(C) (C).comm #define Name(C) (C).name #define Amount(C) (C).amount #define Gold(C) (C).gold #define Map(C) (C).map #define Coordinate(C) (C).coordinate #define Time(C) (C).time /* *** DEFINISI PROTOTIPE PRIMITIF *** */ /* *** Konstruktor membentuk COMMAND *** */ COMMAND MakeCOMMAND(int comm, int name, int amount, int gold, int map, POINT coordinate, int time); /* Membentuk sebuah COMMAND dari komponen-komponennya */ void MakeEmptyCOMMAND(COMMAND *C); /* Membentuk sebuah COMMAND yang komponenya nil */ void TulisCOMMAND(COMMAND C); /* Nilai C ditulis ke layar dengan format "(comm,name,amount,map,(X,Y),time)"*/ /* I.S. C terdefinisi */ /* F.S. C tertulis di layar dengan format "(comm,name,amount,map,(X,Y),time)" */ #endif
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* string.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: agardina <[email protected]> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2019/12/11 19:39:22 by agardina #+# #+# */ /* Updated: 2019/12/11 19:40:13 by agardina ### ########.fr */ /* */ /* ************************************************************************** */ #include "prototypes.h" int print_s(va_list ap, t_conv *conv) { int len; char *str; str = (char *)va_arg(ap, char *); if (!conv->prec) len = 0; else if (conv->prec != 0 && !str) len = conv->prec == -1 ? 6 : ft_min(6, conv->prec); else len = conv->prec == -1 ? ft_strlen(str) : ft_min(ft_strlen(str), conv->prec); if (!conv->minus) { if (!conv->zero) put_spaces(conv->width - len, conv); else put_zeros(conv->width - len, conv); } if (!str) puts_no_format(conv, "(null)", len); else puts_no_format(conv, str, len); if (conv->minus) put_spaces(conv->width - len, conv); return (conv->width - len > 0 ? conv->width : len); }
C
#include<stdio.h> int mishu(int n, int x); int main() { int m; int n; int x; scanf("%d %d", &n, &x); int a[n+1]; int sum = 0; int i,j; for(i=0; i<n; i++) { scanf("%d", &a[i]); } for(j=0; j<n; j++) { m = mishu(j, x); sum = sum + a[j] * m; } printf("%d", sum); } int mishu(int n, int x) { int i; int result = 1; for(i=0; i<n; i++){ result *= x; } return result; }
C
#include<stdio.h> int bas,son,dizi[10000][10000],q[3][1000000]; int px,py,n,m,fx,fy; void fare(int x,int y) { while(bas<=son) { fx=q[1][bas]; fy=q[2][bas]; bas++; if(fy+1!=m+1 &&(dizi[fx][fy]+1<dizi[fx][fy+1] || dizi[fx][fy+1]==0)) { son++; q[1][son]=fx; q[2][son]=fy+1; dizi[fx][fy+1]=dizi[fx][fy]+1; } if(fx+1!=n+1 && (dizi[fx][fy]+1<dizi[fx+1][fy] || dizi[fx+1][fy]==0)) { son++; q[1][son]=fx+1; q[2][son]=fy; dizi[fx+1][fy]=dizi[fx][fy]+1; } if(fy-1!=0 &&(dizi[fx][fy]+1<dizi[fx][fy-1] || dizi[fx][fy-1]==0)) { son++; q[1][son]=fx; q[2][son]=fy-1; dizi[fx][fy-1]=dizi[fx][fy]+1; } if(fx-1!=0 &&(dizi[fx][fy]+1<dizi[fx-1][fy] || dizi[fx-1][fy]==0)) { son++; q[1][son]=fx-1; q[2][son]=fy; dizi[fx-1][fy]=dizi[fx][fy]+1; } } } int main () { int i,j; FILE *oku; // varsa labirent icin txt oku=fopen("labirent.out","r"); // labirent buyuklugu scanf("%d %d",&n,&m); // labirent tanimlama for(i=1;i<=n;i++) { for(j=1;j<=m;j++) { scanf(" %d",&dizi[i][j]); dizi[i][j]*=-1; } } // fare kordinati scanf("%d %d",&fx,&fy); dizi[fx][fy]=1; q[1][1]=fx; q[2][1]=fy; bas=1; son=1; // peynir kordinati scanf(" %d %d",&px,&py); // peynirin yerini fareyle bulan fonksiyon fare(fx,fy); // labirentin yeniden yazdirildigi kisim for(i=1;i<=n;i++) { for(j=1;j<=m;j++) { printf(" %d\t",dizi[i][j]); } printf("\n"); } //printf("%d",dizi[px][py]); }
C
/** * \file Partie1.h * \brief dfinitions des prototypes des fonctions relatives la partie 1 */ #ifndef FONCTIONSPARTIEUN_H #define FONCTIONSPARTIEUN_H #include "constantes.h" /** * \fn int** creePalette(DonneesImageRGB *image, int *nombreDeCouleurs) * \brief Determine le nombre N de couleurs differentes * * \param image * \param nombreDeCouleurs * * \return palette */ int** creePalette(DonneesImageRGB *image, int *nombreDeCouleurs); /** * \fn int* tableauPalette(int bleu, int vert, int rouge) * \brief Stocke les couleurs dtermines dans un tableau Palette * * \param bleu * \param vert * \param rouge * * \return tableau */ int* tableauPalette(int bleu, int vert, int rouge); /** * \fn bool testCouleursPalette(int **palette, int bleu, int vert, int rouge, int *nombreDeCouleurs) * \brief Test les couleurs du tableau Palette * * \param palette * \param bleu * \param vert * \param rouge * \param nombreDeCouleurs * * \return boolean */ bool testCouleursPalette(int **palette, int bleu, int vert, int rouge, int *nombreDeCouleurs); /** * \fn int** creeMatrice(int **palette, DonneesImageRGB *image, int *nombreDeCouleurs) * \brief Transforme le tableau d'octets en une matrice hauteurImage x largeurImage d'entiers * * \param palette * \param image * \param nombreDeCouleurs * * \return matrice */ int** creeMatrice(int **palette, DonneesImageRGB *image, int *nombreDeCouleurs); /** * \fn unsigned char* creeImage(int **matrice, int **palette, DonneesImageRGB *image) * \brief Transforme une matrice en tableau d'octets * * \param matrice * \param image * \param palette * * \return tableau */ unsigned char* creeImage(int **matrice, int **palette, DonneesImageRGB *image); #endif
C
#include <stdio.h> #include <stdlib.h> int main() { int cm; cm=152.0; int kg; kg=45.0; float m; m=cm/100.0; int bmi; bmi=kg/ (m*m); printf("bmi=%d\n", bmi); printf("m=%f\n", m); }
C
#pragma once #include "vec.h" struct mat3 { mat3() : xx(1.0f), xy(0.0f), xz(0.0f), yx(0.0f), yy(1.0f), yz(0.0f), zx(0.0f), zy(0.0f), zz(1.0f) {} mat3( float _xx, float _xy, float _xz, float _yx, float _yy, float _yz, float _zx, float _zy, float _zz) : xx(_xx), xy(_xy), xz(_xz), yx(_yx), yy(_yy), yz(_yz), zx(_zx), zy(_zy), zz(_zz) {} mat3(vec3 r0, vec3 r1, vec3 r2) : xx(r0.x), xy(r0.y), xz(r0.z), yx(r1.x), yy(r1.y), yz(r1.z), zx(r2.x), zy(r2.y), zz(r2.z) {} vec3 r0() const { return vec3(xx, xy, xz); } vec3 r1() const { return vec3(yx, yy, yz); } vec3 r2() const { return vec3(zx, zy, zz); } vec3 c0() const { return vec3(xx, yx, zx); } vec3 c1() const { return vec3(xy, yy, zy); } vec3 c2() const { return vec3(xz, yz, zz); } float xx, xy, xz, yx, yy, yz, zx, zy, zz; }; static inline mat3 operator+(mat3 m, mat3 n) { return mat3( m.xx + n.xx, m.xy + n.xy, m.xz + n.xz, m.yx + n.yx, m.yy + n.yy, m.yz + n.yz, m.zx + n.zx, m.zy + n.zy, m.zz + n.zz); } static inline mat3 operator-(mat3 m, mat3 n) { return mat3( m.xx - n.xx, m.xy - n.xy, m.xz - n.xz, m.yx - n.yx, m.yy - n.yy, m.yz - n.yz, m.zx - n.zx, m.zy - n.zy, m.zz - n.zz); } static inline mat3 operator/(mat3 m, float v) { return mat3( m.xx / v, m.xy / v, m.xz / v, m.yx / v, m.yy / v, m.yz / v, m.zx / v, m.zy / v, m.zz / v); } static inline mat3 operator*(float v, mat3 m) { return mat3( v * m.xx, v * m.xy, v * m.xz, v * m.yx, v * m.yy, v * m.yz, v * m.zx, v * m.zy, v * m.zz); } static inline mat3 mat3_zero() { return mat3( 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f); } static inline mat3 mat3_transpose(mat3 m) { return mat3( m.xx, m.yx, m.zx, m.xy, m.yy, m.zy, m.xz, m.yz, m.zz); } static inline mat3 mat3_mul(mat3 m, mat3 n) { return mat3( dot(m.r0(), n.c0()), dot(m.r0(), n.c1()), dot(m.r0(), n.c2()), dot(m.r1(), n.c0()), dot(m.r1(), n.c1()), dot(m.r1(), n.c2()), dot(m.r2(), n.c0()), dot(m.r2(), n.c1()), dot(m.r2(), n.c2())); } static inline mat3 mat3_transpose_mul(mat3 m, mat3 n) { return mat3( dot(m.c0(), n.c0()), dot(m.c0(), n.c1()), dot(m.c0(), n.c2()), dot(m.c1(), n.c0()), dot(m.c1(), n.c1()), dot(m.c1(), n.c2()), dot(m.c2(), n.c0()), dot(m.c2(), n.c1()), dot(m.c2(), n.c2())); } static inline vec3 mat3_mul_vec3(mat3 m, vec3 v) { return vec3( dot(m.r0(), v), dot(m.r1(), v), dot(m.r2(), v)); } static inline vec3 mat3_transpose_mul_vec3(mat3 m, vec3 v) { return vec3( dot(m.c0(), v), dot(m.c1(), v), dot(m.c2(), v)); } static inline mat3 mat3_from_angle_axis(float angle, vec3 axis) { float a0 = axis.x, a1 = axis.y, a2 = axis.z; float c = cosf(angle), s = sinf(angle), t = 1.0f - cosf(angle); return mat3( c+a0*a0*t, a0*a1*t-a2*s, a0*a2*t+a1*s, a0*a1*t+a2*s, c+a1*a1*t, a1*a2*t-a0*s, a0*a2*t-a1*s, a1*a2*t+a0*s, c+a2*a2*t); } static inline mat3 mat3_outer(vec3 v, vec3 w) { return mat3( v.x * w.x, v.x * w.y, v.x * w.z, v.y * w.x, v.y * w.y, v.y * w.z, v.z * w.x, v.z * w.y, v.z * w.z); } static inline vec3 mat3_svd_dominant_eigen( const mat3 A, const vec3 v0, const int iterations, const float eps) { // Initial Guess at Eigen Vector & Value vec3 v = v0; float ev = (mat3_mul_vec3(A, v) / v).x; for (int i = 0; i < iterations; i++) { // Power Iteration vec3 Av = mat3_mul_vec3(A, v); // Next Guess at Eigen Vector & Value vec3 v_new = normalize(Av); float ev_new = (mat3_mul_vec3(A, v_new) / v_new).x; // Break if converged if (fabs(ev - ev_new) < eps) { break; } // Update best guess v = v_new; ev = ev_new; } return v; } static inline void mat3_svd_piter( mat3& U, vec3& s, mat3& V, const mat3 A, const int iterations = 64, const float eps = 1e-5f) { // First Eigen Vector vec3 g0 = vec3(1, 0, 0); mat3 B0 = A; vec3 u0 = mat3_svd_dominant_eigen(B0, g0, iterations, eps); vec3 v0_unnormalized = mat3_transpose_mul_vec3(A, u0); float s0 = length(v0_unnormalized); vec3 v0 = s0 < eps ? g0 : normalize(v0_unnormalized); // Second Eigen Vector mat3 B1 = A; vec3 g1 = normalize(cross(vec3(0, 0, 1), v0)); B1 = B1 - s0 * mat3_outer(u0, v0); vec3 u1 = mat3_svd_dominant_eigen(B1, g1, iterations, eps); vec3 v1_unnormalized = mat3_transpose_mul_vec3(A, u1); float s1 = length(v1_unnormalized); vec3 v1 = s1 < eps ? g1 : normalize(v1_unnormalized); // Third Eigen Vector mat3 B2 = A; vec3 v2 = normalize(cross(v0, v1)); B2 = B2 - s0 * mat3_outer(u0, v0); B2 = B2 - s1 * mat3_outer(u1, v1); vec3 u2 = mat3_svd_dominant_eigen(B2, v2, iterations, eps); float s2 = length(mat3_transpose_mul_vec3(A, u2)); // Done U = mat3(u0, u1, u2); s = vec3(s0, s1, s2); V = mat3(v0, v1, v2); }
C
#include <errno.h> #include <sys/types.h> #include <sys/wait.h> #include "proc.h" #include "log.h" int last_proc; int proc_slot; proc_t processes[MAX_PROCESSES]; int proc_spawn(spawn_proc_pt proc, void *args, char *name, int respawn) { int s; pid_t pid; spawn_proc_pt proc_tmp = proc; void *args_tmp = args; for (s = 0; s < last_proc; s++) { if (processes[s].pid == -1) { /* must exited */ proc_tmp = processes[s].proc; args_tmp = processes[s].args; break; } } if (s == MAX_PROCESSES) { log_write(LOG_ERRO, "no more than %d processes can be spawned", MAX_PROCESSES); return -1; } proc_slot = s; pid = fork(); if (pid < 0) { return -1; } else if (pid == 0) { proc_tmp(args_tmp); } processes[s].pid = pid; if (respawn) return pid; processes[s].args = args; processes[s].name = name; processes[s].proc = proc; if (s == last_proc) last_proc++; return pid; } void proc_wait(void) { pid_t pid; int i, status; char *proc_name; for (;;) { pid = waitpid(-1, &status, WNOHANG); if (pid == 0) return; if (pid == -1) { if (errno == EINTR) continue; else return; } proc_name = "unknown process"; for (i = 0; i < last_proc; i++) { if (processes[i].pid == pid) { processes[i].pid = -1; proc_spawn(NULL, NULL, NULL, 1); proc_name = processes[i].name; break; } } if (WTERMSIG(status)) { log_write(LOG_INFO, "%s(%d) exited on signal %d", proc_name, pid, WTERMSIG(status)); } else { log_write(LOG_INFO, "%s(%d) exited with code %d", proc_name, pid, WEXITSTATUS(status)); } } }
C
/* 计算最高分 */ #include <stdio.h> #define NUMBER 5 /*学生人数*/ int tensu[NUMBER]; /*数组定义*/ int top(void); /*函数top的函数原型声明*/ int main(void) { extern int tensu[]; /*数组的声明(可以省略)*/ int i; printf("请输入%d名学生的分数\n", NUMBER); for (i = 0; i < NUMBER; i++) { printf("%d:", i + 1); scanf("%d", &tensu[i]); } printf("最高分=%d\n", top()); return 0; } /*返回数组tensu的最大值*/ int top(void) { extern int tensu[]; /*数组的声明(可以省略)*/ int i; int max = tensu[0]; for (i = 1; i < NUMBER; i++) if (tensu[i] > max) { max = tensu[i]; } return max; }
C
#include <stdio.h> #include <stdlib.h> int main (){ char character; scanf ("%c", &character); if (character == 'A'|| character == 'I' || character == 'U' || character == 'E' || character == 'O'){ printf ("Vowel"); } else{ printf ("Consonant"); } return 0; }
C
/* Ini deklarasi fungsi */ void handleInterrupt21 (int AX, int BX, int CX, int DX); void printString(char *string); //done void readString(char *string); //done void readSector(char *buffer, int sector); //done void writeSector(char *buffer, int sector); //done void readFile(char *buffer, char *filename, int *success); void clear(char *buffer, int length); //Fungsi untuk mengisi buffer dengan 0 (done) void writeFile(char *buffer, char *filename, int *sectors); void executeProgram(char *filename, int segment, int *success); void printLogo(); //Fungsi Matematika int mod(int x, int y); //done int div(int a,int b); //done //Main Function int main() { char buffer[512 * 20]; int suc; printLogo(); makeInterrupt21(); interrupt(0x21, 0x4, buffer, "key.txt", &suc); if (suc) { interrupt(0x21,0x0, "Key : ", 0, 0); interrupt(0x21,0x0, buffer, 0, 0); } else { interrupt(0x21, 0x6, "milestone1", 0x2000, &suc); } while (1); } void handleInterrupt21 (int AX, int BX, int CX, int DX) { char AL, AH; AL = (char) (AX); AH = (char) (AX >> 8); switch (AL) { case 0x00: printString(BX); break; case 0x01: readString(BX); break; case 0x02: readSector(BX, CX); break; case 0x03: writeSector(BX, CX); break; case 0x04: readFile(BX, CX, DX, AH); break; case 0x05: writeFile(BX, CX, DX, AH); break; case 0x06: executeProgram(BX, CX, DX, AH); break; default: printString("Invalid interrupt"); } } // Implementasi fungsi void printString(char *string) { int i = 0; while(string[i] != '\0'){ interrupt(0x10, 0xE00 + string[i], 0, 0, 0); i++; } } void readString(char *string) { int i = 0; int idx = 0; char input; do { input = interrupt(0x16, 0, 0, 0, 0); if (input == '\r') { string[idx] = '\0'; interrupt(0x10, 0xE00 + input, 0, 0, 0); } else if (input != '\b') { interrupt(0x10, 0xE00 + input, 0, 0, 0); string[idx] = input; idx++; } else if (idx > 0) { idx--; interrupt(0x10, 0xE00+ '\b', 0, 0, 0); } } while (input != '\r'); interrupt(0x10, 0xE00 + '\r', 0, 0, 0); } void readSector(char *buffer, int sector) { interrupt(0x13, 0x201, buffer, div(sector, 36) * 0x100 + mod(sector, 18) + 1, mod(div(sector, 18), 2) * 0x100); } void writeSector(char *buffer, int sector) { interrupt(0x13, 0x301, buffer, div(sector, 36) * 0x100 + mod(sector, 18) + 1, mod(div(sector, 18), 2) * 0x100); } void readFile(char *buffer, char *filename, int *success) { char dir[512]; char entry[32]; int fileFound; int i; int j; int ij; int startLast20Bytes; int k; char check = 0; readSector(dir, 2); for (i = 0; i < 512; i+=32) { fileFound = 1; for (ij = 0; ij < 12; ij++) { if (filename[ij] == '\0') { break; } else if (dir[i + ij] != filename[ij]) { fileFound = 0; break; } } if (fileFound) { check = 1; break; } } if (!check) { *success = 0; return; } else { startLast20Bytes = i + 12; for (k = 0; k < 20; k++) { if (dir[startLast20Bytes + k] == 0) { break; } else { readSector(buffer + k * 512, dir[startLast20Bytes + k]); } } *success = 1; return; } } void clear(char *buffer, int length) { //Fungsi untuk mengisi buffer dengan 0 int i; for(i = 0; i < length; ++i){ buffer[i] = 0x00; } } void writeFile(char *buffer, char *filename, int *sectors) { char map[512]; char dir[512]; char sectorBuffer[512]; int dirIndex; readSector(map, 1); readSector(dir, 2); for (dirIndex = 0; dirIndex < 16; ++dirIndex) { if (dir[dirIndex * 32] == '\0') { break; } } if (dirIndex < 16) { int i, j, sectorCount; for (i = 0, sectorCount = 0; i < 256 && sectorCount < *sectors; ++i) { if (map[i] == 0x00) { ++sectorCount; } } if (sectorCount < *sectors) { *sectors = 0; //insufficient return; } else { clear(dir + dirIndex * 32, 32); for (i = 0; i < 12; ++i) { if (filename[i] != '\0') { dir[dirIndex * 32 + i] = filename[i]; } else { break; } } for (i = 0, sectorCount = 0; i < 256 && sectorCount < *sectors; ++i) { if (map[i] == 0x00) { map[i] = 0xFF; dir[dirIndex * 32 + 12 + sectorCount] = i; clear(sectorBuffer, 512); for (j = 0; j < 512; ++j) { sectorBuffer[j] = buffer[sectorCount * 512 + j]; } writeSector(sectorBuffer, i); ++sectorCount; } } } } else { *sectors = -1; //insufficient dir entries return; } writeSector(map, 1); writeSector(dir, 2); } void executeProgram(char *filename, int segment, int *success) { char buffer[20 * 512]; int i; readFile(buffer, filename, success); if (*success) { for (i=0; i<20 * 512; i++) { putInMemory(segment, i, buffer[i]); } launchProgram(segment); } } void printLogo () { printString(" /\\ /\\\r\n"); printString("/ \'._ (\\_/) _.'/ \\\r\n"); printString("|.''._'--(o.o)--'_.''.|\r\n"); printString(" \\_ / `;=/ \" \\=;` \\ _/\r\n"); printString(" `\\__| \\___/ |__/`\r\n"); printString("jgs \\(_|_)/\r\n"); printString(" \" ` \"\r\n"); } //Implementasi Fungsi Matematika int mod(int x, int y) { while (x>=y) { x-=y; }return x; } int div (int x, int y) { int ratio = 0; while(ratio*y <= x) { ratio += 1; }return(ratio-1); }
C
#include <os_server.h> #include <sys/socket.h> #include <sys/poll.h> #include <sys/un.h> #include <ftw.h> #include <worker.h> #include <fs.h> static ssize_t datadir_size = 0; static ssize_t datadir_entries = 0; void dispatcher_cleanup() { int err = close(os_serverfd); if (err < 0) err_close(os_serverfd); //Remove socket file at SOCKET_ADDR err = unlink(SOCKET_ADDR); if (err < 0) err_unlink(SOCKET_ADDR); if (VERBOSE) fprintf(stderr, "OBJSTORE: %s succesfully unlinked\n", SOCKET_ADDR); //Free client_list from memory myhash_free(client_list, HASHTABLE_SIZE); } static int calc_stats(const char *fpath, const struct stat *sb, int typeflag) { if (typeflag == FTW_F) { datadir_size = datadir_size + sb->st_size; datadir_entries++; } return 0; } static void stats() { //Print amount of connected clients fprintf(stdout, "\nSTATS: Connected clients: %d\n", worker_num); //Do a file tree walk on the data folder and calculate size and number of files (i.e number of objects) datadir_size = 0; datadir_entries = 0; int err = ftw("data", &calc_stats, 64); if (err < 0) err_ftw("data"); fprintf(stdout, "STATS: Data folder size: %ld bytes\n", datadir_size); fprintf(stdout, "STATS: Objects stored: %ld\n", datadir_entries); } void *dispatch(void *arg) { //Init pollfd struct struct pollfd pollfds[2]; pollfds[0] = (struct pollfd){os_serverfd, POLLIN, 0}; pollfds[1] = (struct pollfd){os_signalfd[0], POLLIN, 0}; //Dumb buffer for signal pipe char empty[1]; long maxclients = sysconf(_SC_OPEN_MAX); while(OS_RUNNING) { //Poll both the socket fd and the signal pipe fd int ev = poll(pollfds, 2, 10); if (ev < 0) err_poll(os_serverfd); //Check if we have a pending connection, accept only if the number of connected clients is < 500 to avoid breaking the fd limit if (ev == 1 && (pollfds[0].revents & POLLIN) && worker_num < maxclients / 2 - 64) { //Accept connection int client_fd = accept(os_serverfd, NULL, NULL); if (client_fd < 0) err_accept(); int err = pthread_mutex_lock(&worker_num_mtx); if (err != 0) err_pthread("pthread_mutex_lock"); worker_num++; err = pthread_mutex_unlock(&worker_num_mtx); if (err != 0) err_pthread("pthread_mutex_unlock"); //Create a worker thread for the client int *ptr = (int*)malloc(sizeof(int)); if (ptr == NULL) { err_malloc((size_t)sizeof(int)); exit(EXIT_FAILURE); } *ptr = client_fd; pthread_t wk; err = pthread_create(&wk, NULL, &worker_loop, (void*)ptr); if (err != 0) err_pthread("pthread_create"); if (VERBOSE) fprintf(stderr, "OBJSTORE: Client connected on socket %d\n", client_fd); } //If there's something on the receiving end of the pipe (got SIGUSR1) then print stats if (ev == 1 && (pollfds[1].revents & POLLIN)) { read(os_signalfd[0], &empty, 1); stats(); } } //Wait for all the worker threads to shutdown int err = pthread_mutex_lock(&worker_num_mtx); if (err != 0) err_pthread("pthread_mutex_lock"); while (worker_num > 0) { err = pthread_cond_wait(&worker_num_cond, &worker_num_mtx); if (err != 0) err_pthread("pthread_cond_wait"); } dispatcher_cleanup(); err = pthread_mutex_unlock(&worker_num_mtx); if (err != 0) err_pthread("pthread_mutex_unlock"); pthread_exit(NULL); }
C
#include<stdio.h> struct line { double c; double x; double y; }; struct point { double x; double y; }; struct line line_equation(struct point p1,struct point p2) { struct line l1; if(p1.x==p2.x && p1.y==p2.y) { l1.x=1; l1.y=0; l1.c=p1.x; return l1; } else { l1.y=(p2.x-p1.x); l1.x=(p1.y-p2.y); l1.c=((p1.y*(p1.x-p2.x) )+ (p1.x*(p2.y-p1.y))); } return l1; } int main() { struct point p1,p2; printf("Enter the first x- co ordinate\n"); scanf("%lf",&p1.x); printf("Enter the first y- co ordinate\n"); scanf("%lf",&p1.y); printf("Enter the second x- co ordinate\n"); scanf("%lf",&p2.x); printf("Enter the second y- co ordinate\n"); scanf("%lf",&p2.y); struct line l1; l1=line_equation(p1,p2); printf("The entered line is : "); printf("%lfX + %lfY + %lf = 0",l1.x,l1.y,l1.c); }
C
#include "UART.h" // transmit a char to uart void uart_transmit( unsigned char data ) { // wait for empty transmit buffer while ( ! ( UCSR1A & ( 1 << UDRE1 ) ) ) ; // put data into buffer, sends data UDR1 = data; } // read a char from uart unsigned char uart_receive(void) { while (!( UCSR1A & ( 1 << RXC1) )) ; return UDR1; } // init uart void uart_init(void) { // set baud rate unsigned int baud = BAUD_PRESCALE; UBRR1H = (unsigned char) (baud >> 8 ); UBRR1L = (unsigned char)baud; // enable receiver and transmitter UCSR1B = ( 1 << RXEN1 ) | ( 1 << TXEN1 ); // set frame format ( 8data, 2stop ) UCSR1C = ( 1 << USBS1 ) | ( 3 << UCSZ10 ); } // write a string to the uart void uart_print( char data[] ) { uint8_t c = 0; for ( c = 0; c < strlen(data); c++ ) uart_transmit(data[c]); } /*void uart_flush( void ) { volatile unsigned char dummy; while ( UCSR1A & (1<<RXC1) ) dummy = UDR1; }*/ void uart_read_string(char * DATA){ uint8_t cnt = 0; char tmp = 0; while ((tmp = uart_receive())!=13){ DATA[cnt] = tmp; cnt++; } DATA[cnt] = '\0'; uart_print(DATA); uart_print("\n"); //uart_flush(); } bool comp_func (char *str1,char *str2){ bool if_equal = false; for (uint8_t i = 0;i<BUFFER;i++) { if(str1[i]==str2[i]) { if(str1[i]=='\0') { if_equal = true; return if_equal; } }else break; } return if_equal; }
C
/* * Copyright (c), 2012, Braveyly * All rights reserved * * File name:qstack.h * Abstract:stack through queue api * * Current version:v0.1 * Author:braveyly * Date:2012-4-10 * Modification:first version * Revise version: * Author: * Date: * Modification: */ #ifndef _STACK_H #define _STACK_H #include <stdio.h> #include "queue.h" #ifdef DEBUG #define _(CODE) (printf("DEBUG-%d:",__LINE__), CODE) #else #define _(CODE) #endif typedef void ( *item_show_fn )( void* ); typedef void ( *item_destroy_fn )( void* ); typedef struct _qstack_ { Queue *q1; Queue *q2; }Qstack; /*stack construct and destruct*/ Qstack* create_qstack(show_item, destroy_item); void destroy_qstack( Qstack * ); /*append and pop in the tail*/ int qstack_push( Qstack*, void*); void* qstack_pop(Qstack*); int get_qstack_count( Qstack* s ); #endif /* * End of file */
C
#include "myutils.h" int main() { long int num; int i; printf("Enter the Number"); scanf("%d",&num); i=isPrime(num); print("%d",i); printf("\n Factorial of num :%ld",factorial(num)); printf("\n Palindrome :%ld",isPalindrome(num)); printf("\n Vsum is:%ld",vsum(3,3,4,5)); return 0; }
C
#include <stdio.h> void plusandminus( int a, int b, int * c , int * d ); int main() { int a,b,c=0,d=0; scanf("%d%d",&a,&b); plusandminus( a, b, &c , &d );//此处调用 plusandminus 函数 printf("%d %d\n" , c , d ); // return 0; } /* 在调试代码时候,你应该在这里完成函数的定义部分的代码,调试好之后提交这段代码 */ void plusandminus( int a, int b, int * c , int * d ) { *c = a+b; *d = a-b; }
C
/* * Check if assignment is available, where * operand is structure. */ #include <stdio.h> struct inner { int a; int b; }; struct outer { struct inner i; }; int main(void) { struct outer o; struct inner i = { 1, 2 }; o.i = i; printf("o.i.a = %d, o.i.b = %d\n", o.i.a, o.i.b); return 0; }
C
#include <avr/io.h> #include <avr/interrupt.h> void UART_putchar(unsigned char data) { /* Wait for empty transmit buffer */ while ( !( UCSRA & (1<<UDRE)) ); /* Put data into buffer, sends the data */ UDR = data; } // end of UART_putchar() void UART_putstring(unsigned char *txt) { uint8_t i; for(i=0;i<255;i++) { if(!txt[i]) break; UART_putchar(txt[i]); } } unsigned char UART_getchar(void) { /* Wait for data to be received */ while ( !(UCSRA & (1<<RXC)) ); /* Get and return received data from buffer */ return UDR; } // end of UART_getchar() void UART_init(unsigned int ubrr) { UBRRH = (unsigned char)(ubrr>>8); UBRRL = (unsigned char)ubrr; /* Enable receiver and transmitter */ UCSRB = (1<<RXEN)|(1<<TXEN)|(1<<RXCIE); /* Set frame format: 8data, 2stop bit */ UCSRC = (1<<URSEL)|(1<<USBS)|(3<<UCSZ0); } // end of UART_init() //SIGNAL (SIG_UART_RECV) ISR(USART_RXC_vect ) { //unsigned char c; //c = UDR; }
C
#include <stdio.h> #include <conio.h> int main() { int range,sequence; printf("Enter the value of n : "); scanf("%d",&range); int a=0,b=1; printf("%d %d",a,b); for(int i=1;i<=range-2;i++) { sequence=a+b; a=b; b=sequence; printf(" %d",sequence); } getch(); return 0; }
C
// Copyright (C), 1998-2013, Tencent // Author: [email protected] // Date: 2013-3-5 // Different implementations for GetNthPreviousDay() and GetNthNextDay() with // different time tradeoffs. GetNthNextDay chooses which one to use based on N. // These are in a different compilation unit because they are implementation // details, but we need to unit test them. #ifndef APP_QZAP_COMMON_UTILITY_TIME_UTILITY_INTERNAL_H__ #define APP_QZAP_COMMON_UTILITY_TIME_UTILITY_INTERNAL_H__ // The same arguments as GetNthPreviousDay (and GetNthNextDay), but we assume // the inputs are verified and n is non-negative. These are implemented by // iteratively moving forward (or backward) one month at a time until we have // added (or subtracted) N days. // These are O(n), but have a small constant. extern void GetNthPreviousDayCarefully(int n, int *y, int *m, int *d); extern void GetNthNextDayCarefully(int n, int *y, int *m, int *d); #endif // APP_QZAP_COMMON_UTILITY_TIME_UTILITY_INTERNAL_H__
C
#include<stdio.h> int main() { int n; n=200; while(n<=300) { if(n%2==0) printf("\t%d",n); n+=1; } }
C
#include <stdio.h> // Quick Sort // ð⵵ : O(n * log n) // Ư ū ڿ ڸ ( ) . int number = 10; int data[10] = { 1, 10, 5, 8, 7, 6, 4 ,3 ,2, 9 }; void quickSort(int* data, int start, int end) { if (start >= end) { // Ұ ϳ return; } int key = start; // key ù° int i = start + 1; // int j = end; // int temp; while (i <= j) { // ݺ while (i <= end && data[i] <= data[key]) { // key ū ݺ, i <= end && data[i] >= data[key] ++i; } while (data[j] >= data[key] && j > start) { // key ݺ, data[j] <= data[key] && j > start --j; } if (i > j) { // temp = data[j]; data[j] = data[key]; data[key] = temp; } else { // temp = data[i]; data[i] = data[j]; data[j] = temp; } } quickSort(data, start, j - 1); quickSort(data, j + 1, end); } void show() { int i; for (i = 0; i < number; ++i) { printf("%d ", data[i]); } } int main(void) { quickSort(data, 0, number - 1); show(); return 0; }
C
/* ** EPITECH PROJECT, 2018 ** delete_env_variable.c ** File description: ** delete env variable */ #include <stdlib.h> #include "include/proto.h" void delete_env_variables(env_t **env_lst, char *prompt) { for (char *s = NULL ; prompt[0] != 0; prompt++) { if (prompt[0] == ' ' && prompt[1] != ' ') { prompt++; s = my_strcpy_special(prompt); delete_variable(env_lst, s); free(s); } for (; (*env_lst)->prev != 0; *env_lst = (*env_lst)->prev); *env_lst = (*env_lst)->next; } } void delete_variable(env_t **env_lst, char *name) { for (; (*env_lst)->next != 0; *env_lst = (*env_lst)->next) { if (my_strcmp_env((*env_lst)->env_name, name) == 0) found_variable_to_delete(env_lst); } if (my_strcmp_env((*env_lst)->env_name, name) == 0) found_variable_to_delete(env_lst); } void found_variable_to_delete(env_t **env_lst) { free((*env_lst)->env_name); free((*env_lst)->env_value); if ((*env_lst)->next == 0 && (*env_lst)->prev != 0) { *env_lst = (*env_lst)->prev; free((*env_lst)->next); (*env_lst)->next = 0; } else if ((*env_lst)->prev == 0 && (*env_lst)->next != 0) { *env_lst = (*env_lst)->next; free((*env_lst)->prev); (*env_lst)->prev = 0; } else if ((*env_lst)->prev != 0 && (*env_lst)->next != 0) variable_in_middle_of_list(env_lst); } void variable_in_middle_of_list(env_t **env_lst) { env_t *tmp = malloc(sizeof(env_t)); if (!tmp) exit(84); tmp = (*env_lst)->next; *env_lst = (*env_lst)->prev; (*env_lst)->next = tmp; tmp->prev = *env_lst; }
C
/********************************************************************************/ /* ddosĿͻ˳ */ /* ̳߳ */ /* ip:ÿһʱƶ˷ͱip */ /* :ȴƶ˷Ϳ */ /* 𹥻:ýй */ /********************************************************************************/ #include <netinet/in.h> #include <sys/types.h> #include <sys/socket.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <sys/time.h> #include <pthread.h> #include <unistd.h> #include <arpa/inet.h> #include "globalData.h" #include "attack.h" #include "getconfigfromtext.h" int pthread_shutdown; /********************************************************************************/ /* ʼȫò */ /* :1ʧ;0ʼɹ */ /********************************************************************************/ int init() { printf("Version: %s\n",VERSION); int ret; char mess_conf[5][VALUE_MAX_LENGTH];//5Ϊ ret = GetAllConfig("config",&mess_conf[0][0],5);//ǰ5òֵ if(!ret){ printf("X Error:get init config error.\n"); return 1; } strcpy(server_ip,mess_conf[0]); port_server = atoi(mess_conf[1]); port_server_sendip = atoi(mess_conf[2]); port_server_sendresult = atoi(mess_conf[3]); wait_time = atoi(mess_conf[4]); //printf("%s,%d,%d,%d,%d\n",server_ip,port_server,port_server_sendip,port_server_sendresult,wait_time); printf("Action: init success.\n"); return 0; } /********************************************************************************/ /* ÿһʱŷͱip */ /* :1ʧ;0ͳɹ */ /********************************************************************************/ void *sendIp() { struct sockaddr_in server_addr; int sockfd; if( (sockfd=socket(AF_INET,SOCK_STREAM,0)) < 0){ printf("X Waring: send ip:create socket failed.\n"); } bzero(&server_addr,sizeof(server_addr)); server_addr.sin_family = AF_INET; if(inet_aton(server_ip,&server_addr.sin_addr) == 0){ printf("X Waring: send ip:server ip address wrong.\n"); } server_addr.sin_port = htons(port_server_sendip); while(1){ if(connect(sockfd,(struct sockaddr*)&server_addr, sizeof(server_addr)) < 0){ printf("X Waring: send ip:can not connect to %s.\n",server_ip); } else{ send(sockfd,"connect",7,0); } sleep(wait_time); } close(sockfd); } int main(int argc,char *argv[]) { #ifndef DDOS_NO_CONTROL_ON if(init()){ printf("[Error] init error.\n"); exit(1); } #endif #if (!defined DDOS_NO_CONTROL_ON)&&(!defined DDOS_NO_SEND_IP) //߳ÿһʱŷͱip pthread_t pid; int err; err=pthread_create(&pid,NULL,sendIp,NULL); if(err!=0){ printf("X Error: create pthread to send ip error.\n"); exit(1); } #endif #ifndef DDOS_NO_CONTROL_ON //,ȡƶ struct sockaddr_in server_addr; struct sockaddr_in client_addr; int server_socket,new_server_socket; socklen_t length; if((server_socket=socket(PF_INET,SOCK_STREAM,0)) < 0){ printf("X Error: create socket to connect control server failed.\n"); exit(1); } bzero(&server_addr,sizeof(server_addr)); server_addr.sin_family = AF_INET; server_addr.sin_addr.s_addr = htons(INADDR_ANY); server_addr.sin_port = htons(port_server); if( bind(server_socket,(struct sockaddr*)&server_addr,sizeof(server_addr))==-1){ printf("X Error: bind port : %d failed.\n", port_server); exit(1); } if ( listen(server_socket, LENGTH_OF_LISTEN_QUEUE) == -1 ){ printf("X Error: listen from control server failed.\n"); exit(1); } while (1) { pthread_t pid_attack; pthread_attr_t attr; length = sizeof(client_addr); new_server_socket = accept(server_socket,(struct sockaddr*)&client_addr,&length); if ( new_server_socket < 0){ printf("X Error: accept from control server failed.\n"); break; } char buffer[BUFFER_SIZE]; bzero(buffer, BUFFER_SIZE); length = recv(new_server_socket,buffer,BUFFER_SIZE,0); if (length < 0){ printf("X Error: recieve command from control server failed.\n"); break; } char str_get[MAX_SIZE+1]; bzero(str_get, MAX_SIZE+1); strncpy(str_get, buffer, strlen(buffer)>MAX_SIZE?MAX_SIZE:strlen(buffer)); if(strcmp(str_get,"get_configFile")==0) { //ļ send(new_server_socket,"ok:get_configFile",17,0); FILE * fp = fopen("attackconfig.xml","w"); if(fp == NULL){ printf("X Error: File:can't open file attackconfig.xml to write.\n"); break; } bzero(buffer,BUFFER_SIZE); int recvlength = 0; int write_length = 0; int flag_write_config = 0; while((recvlength=recv(new_server_socket,buffer,BUFFER_SIZE,0))>0){ //if(!strcmp(buffer,"::over:send_configFile")) // break; write_length = fwrite(buffer,sizeof(char),recvlength,fp); if (write_length<recvlength){ printf("X Error: write to file attackconfig.xml failed.\n"); flag_write_config = 1; } //printf("%s",buffer); bzero(buffer,BUFFER_SIZE); } if(write_length==0){ printf("X Error: write to file attackconfig.xml failed.\n"); flag_write_config = 1; } fclose(fp); if(!flag_write_config){ printf("Action: Recieve File attackconfig.xml From WebControl Finished.\n"); //send(new_server_socket,"ok:over_configFile",18,0);//˷ļɹıʾ } else{ //send(new_server_socket,"failed:over_configFile",22,0); } } else if(strcmp(str_get,"exec_startAttack")==0) { //ʼ pthread_shutdown=0; int err_attack; pthread_attr_init(&attr); pthread_attr_setdetachstate(&attr,PTHREAD_CREATE_DETACHED); err_attack=pthread_create(&pid_attack,&attr,startAttack,"attackconfig.xml"); pthread_attr_destroy(&attr); if(err_attack!=0){ printf("X Error: create pthread error.\n"); send(new_server_socket,"failed:start_attack",19,0); //exit(1); }else{ send(new_server_socket,"ok:get_exec",11,0);//Ѿյ,ִйĽattackResult.txtļ } } else if(strcmp(str_get,"exec_stopAttack")==0) { //;ֹͣ pthread_shutdown=1; printf("Action: Attacking is stopping...\n"); send(new_server_socket,"ok:get_exec",11,0); } else { // printf("X Error: get command wrong.\n"); } close(new_server_socket);//رͻ˵ } //رռõsocket close(server_socket); #endif #ifdef DDOS_NO_CONTROL_ON if(argc==1) startAttack("attackconfig.xml"); else startAttack(argv[1]); #endif return 0; }
C
/* ** EPITECH PROJECT, 2018 ** number.c ** File description: ** function returns a value */ #include <stdlib.h> #include <unistd.h> char *my_revstr(char *str) { int i = 0; int j = 0; char c ; while (str[i] != '\0') { i++; } for (j; j < i - 1; j++) { c = str[j]; str[j] = str[i - 1]; str[i - 1] = c; i--; } return (str); } int my_getnbr(char const *str) { int nb = 0; int minus = 1; for (int i = 0; str[i] == '+' || str[i] == '-'; i++) if (str[i] == '-') minus = minus * -1; for (int i = 0; str[i]; i++) if (str[i] >= '0' && str[i] <= '9') { nb *= 10; nb += str[i] - '0'; } return (nb * minus); } int get_int_size(int nb) { int counter = 0; if (nb == 0) return (1); while (nb > 0) { counter++; nb = nb / 10; } return (counter); } char *int_to_str(int nb) { char *dest = 0; int pos = 0; dest = malloc(sizeof(char) *(12)); if (nb < 0) { nb *= -1; dest[pos] = '-'; pos++; } while (nb > 9) { dest[pos] = nb % 10 + '0'; nb /= 10; pos++; } dest[pos] = nb + '0'; dest[pos + 1] = '\0'; return (dest); } char *int_to_str2(int nb) { char *str = NULL; int size = 0; if (nb <= 0) return (NULL); for (int tmp = nb; tmp > 9; tmp /= 10, size++); str = malloc((size + 1) * sizeof(char)); str[size] = 0; for (int i = 0; i < size; nb /= 10, i++) str[i] = nb % 10 + 48; my_revstr(str); return (str); }
C
#ifndef SHOWLINKEDLIST_H_INCLUDED #define SHOWLINKEDLIST_H_INCLUDED #include<stdio.h> #include<stdlib.h> #include "Structure.h" void showList(){ struct LinkedList *node; node = start; if(start == NULL){ printf("\n UnderFlow!"); return; }else{ printf("\n LinkedList is as follow:\n\n start "); while(node != NULL){ printf("--> %d ",node->info); node = node->next; } printf("--> NULL"); } } #endif // SHOWLINKEDLIST_H_INCLUDED
C
/* ============================================================================ Name : openSSL_https.c Author : AnhPT Version : Copyright : Your copyright notice Description : Hello World in C, Ansi-style ============================================================================ */ #include <sys/types.h> #include <sys/socket.h> #include <netinet/in.h> #include <arpa/inet.h> #include <netdb.h> #include <unistd.h> #include <errno.h> #define ISVALIDSOCKET(s) ((s) >= 0) #define CLOSESOCKET(s) close(s) #define SOCKET int #define GETSOCKETERRNO() (errno) #include <stdio.h> #include <string.h> #include <stdlib.h> #include <time.h> #include "openssl/crypto.h" #include "openssl/x509.h" #include "openssl/pem.h" #include "openssl/ssl.h" #include "openssl/err.h" #include "aes.h" #include "mbedtls/aes.h" #include "mbedtls/md.h" #define MAX_BUFF 1024 #define MAX_LENGTH_DATA 1024 #define IV "00000000000000000000000000000000" char *key = "00001111222233334444555566667777"; char *iv = "00000000000000000000000000000000"; char *data = "EEEEFFFFGGGGHHHH"; unsigned char hex_sha512_key[128] = {0}; unsigned char sha512_key[64] = {0}; static unsigned char g_psk[512] = {0}; static int generate_random_number() { int number = 0; time_t t; srand((unsigned)time(&t)); number = rand() % (MAX_LENGTH_DATA * 2); return number; } static int unhexify(unsigned char *obuf, const char *ibuf) { int len = 0; unsigned char c, c2; /* Warning: The length of the input stream have to be an even number */ len = (strlen(ibuf) >> 1); while(*ibuf != 0) { c = *ibuf++; if(c >= '0' && c <= '9') c -= '0'; else if(c >= 'a' && c <= 'f') c -= 'a' - 10; else if(c >= 'A' && c <= 'F') c -= 'A' - 10; c2 = *ibuf++; if(c2 >= '0' && c2 <= '9') c2 -= '0'; else if(c2 >= 'a' && c2 <= 'f') c2 -= 'a' - 10; else if(c2 >= 'A' && c2 <= 'F') c2 -= 'A' - 10; *obuf++ = (c << 4) | c2; } return len; } static void hexify(unsigned char *obuf, const unsigned char *ibuf, int len) { unsigned char l, h; while(len != 0) { h = *ibuf / 16; l = *ibuf % 16; if(h < 10) *obuf++ = '0' + h; else *obuf++ = 'a' + h - 10; if(l < 10) *obuf++ = '0' + l; else *obuf++ = 'a' + l - 10; ++ibuf; len--; } } static int generate_sha512(unsigned char *input, unsigned char *output) { int ret = -1; mbedtls_md_context_t sha_ctx; if(input == NULL || output == NULL) { printf("Invalid NULL parameter"); return -1; } if(input[0] == 0x00) { printf("Invalid empty string parameter"); return -2; } ret = mbedtls_md_setup(&sha_ctx, mbedtls_md_info_from_type(MBEDTLS_MD_SHA512), 1); if(ret != 0) { printf(" ! mbedtls_md_setup() returned -0x%04x\n", -ret); mbedtls_md_free(&sha_ctx); return ret; } mbedtls_md_starts(&sha_ctx); mbedtls_md_update(&sha_ctx, input, strlen((char *)input)); mbedtls_md_finish(&sha_ctx, output); mbedtls_md_free(&sha_ctx); return 0; } static int encrypt_aes128(char *hex_key_string, char *hex_iv_string, unsigned char *src_string, unsigned char *dst_str, int *encrypt_size) { unsigned char key_str[100]; unsigned char iv_str[100]; unsigned char size_data[20]; mbedtls_aes_context ctx; int key_len, data_len, cbc_result; memset(key_str, 0x00, 100); memset(iv_str, 0x00, 100); memset(size_data, 0x00, 20); mbedtls_aes_init(&ctx); key_len = unhexify(key_str, hex_key_string); unhexify(iv_str, hex_iv_string); data_len = strlen((char *)src_string); if(data_len < 1) { printf("Error: encrypt_aes128() length data (%d)", data_len); mbedtls_aes_free(&ctx); return -1; } if(data_len % 16 != 0) { data_len = ((data_len / 16) + 1) * 16; } if(data_len > MAX_LENGTH_DATA) { printf("Error: encrypt_aes128() length data over (%d)", MAX_LENGTH_DATA); mbedtls_aes_free(&ctx); return -1; } sprintf((char *)size_data, "SSL%04d%04d", data_len, generate_random_number()); mbedtls_aes_setkey_enc(&ctx, key_str, key_len * 8); cbc_result = mbedtls_aes_crypt_cbc(&ctx, MBEDTLS_AES_ENCRYPT, 16, iv_str, size_data, dst_str); if(cbc_result != 0) { printf("Error: encrypt_aes128() length data"); mbedtls_aes_free(&ctx); return -2; } cbc_result = mbedtls_aes_crypt_cbc(&ctx, MBEDTLS_AES_ENCRYPT, data_len, iv_str, src_string, dst_str + 16); if(cbc_result != 0) { printf("Error: encrypt_aes128()"); } mbedtls_aes_free(&ctx); *encrypt_size = (data_len + 16); return cbc_result; } static int decrypt_aes128(char *hex_key_string, char *hex_iv_string, unsigned char *src_string, unsigned char *dst_str) { int random_number; int key_len, data_len, cbc_result, ret = 0; unsigned char key_str[100]; unsigned char iv_str[100]; unsigned char size_data[20]; mbedtls_aes_context ctx; if(strlen((char *)src_string) <= 0) { printf("Error decrypt_aes128 length data source"); return -1; } memset(key_str, 0x00, 100); memset(iv_str, 0x00, 100); memset(size_data, 0x00, 20); mbedtls_aes_init(&ctx); key_len = unhexify(key_str, hex_key_string); unhexify(iv_str, hex_iv_string); mbedtls_aes_setkey_dec(&ctx, key_str, key_len * 8); cbc_result = mbedtls_aes_crypt_cbc(&ctx, MBEDTLS_AES_DECRYPT, 16, iv_str, src_string, size_data); if(cbc_result != 0) { printf("Error: decrypt AES 128"); mbedtls_aes_free(&ctx); return -1; } ret = sscanf((char *)size_data, "SSL%04d%04d", &data_len, &random_number); if(ret != 2) { printf("Error, cannot parse length data"); mbedtls_aes_free(&ctx); return -1; } if(data_len % 16 != 0) { data_len = ((data_len / 16) + 1) * 16; } if(data_len > MAX_LENGTH_DATA) { printf("Error decrypt_aes128 length data over %d", MAX_LENGTH_DATA); mbedtls_aes_free(&ctx); return -2; } cbc_result = mbedtls_aes_crypt_cbc(&ctx, MBEDTLS_AES_DECRYPT, data_len, iv_str, src_string + 16, dst_str); if(cbc_result != 0) { printf("Error decrypt_aes128\n"); } mbedtls_aes_free(&ctx); return cbc_result; } static void init_psk(char *psk, size_t len, int mode) { printf("inside init_psk()\n"); char sPSK[64] = {0}; char sIdentity[64] = {0}; char response_pskidentity[128] ="faeqv3q53vmgihp35aatirjjmr"; char response_pdkkey[128] = "25B8B1234412461F15F6E561F55E346C"; if(psk == NULL) { printf("Error: NULL pointer"); return; } memset(psk, 0x00, len); strcpy(sIdentity, response_pskidentity+16); strcpy(sPSK, response_pdkkey+17); printf("Use dynamic Identity & Pre-shared Key\n"); snprintf(psk, len, "%s%s", sIdentity, sPSK); printf("PSK: %s\n", psk); return; } int main(int argc, char *argv[]) { #if defined(_WIN32) WSADATA d; if (WSAStartup(MAKEWORD(2, 2), &d)) { fprintf(stderr, "Failed to initialize.\n"); return 1; } #endif /* SSL_library_init(); OpenSSL_add_all_algorithms(); SSL_load_error_strings(); SSL_CTX *ctx = SSL_CTX_new(TLS_client_method()); if (!ctx) { fprintf(stderr, "SSL_CTX_new() failed.\n"); return 1; }*/ if (argc < 3) { fprintf(stderr, "usage: https_simple hostname port\n"); return 1; } char *hostname = argv[1]; char *port = argv[2]; init_psk((char*)g_psk, sizeof(g_psk), 1); generate_sha512(g_psk, sha512_key); hexify(hex_sha512_key, sha512_key, 16); printf("[Hex] SHA512 Key:\r\n%s\n", hex_sha512_key); printf("Configuring remote address...\n"); struct addrinfo hints; memset(&hints, 0, sizeof(hints)); hints.ai_socktype = SOCK_STREAM; struct addrinfo *peer_address; unsigned char socket_data_size[32] = {0}; if (getaddrinfo(hostname, port, &hints, &peer_address)) { fprintf(stderr, "getaddrinfo() failed. (%d)\n", GETSOCKETERRNO()); exit(1); } printf("Remote address is: "); char address_buffer[100]; char service_buffer[100]; getnameinfo(peer_address->ai_addr, peer_address->ai_addrlen, address_buffer, sizeof(address_buffer), service_buffer, sizeof(service_buffer), NI_NUMERICHOST); printf("%s %s\n", address_buffer, service_buffer); printf("Creating socket...\n"); SOCKET server; server = socket(peer_address->ai_family, peer_address->ai_socktype, peer_address->ai_protocol); if (!ISVALIDSOCKET(server)) { fprintf(stderr, "socket() failed. (%d)\n", GETSOCKETERRNO()); exit(1); } printf("Connecting...\n"); if (connect(server, peer_address->ai_addr, peer_address->ai_addrlen)) { fprintf(stderr, "connect() failed. (%d)\n", GETSOCKETERRNO()); exit(1); } freeaddrinfo(peer_address); printf("Connected.\n"); char buffer[]="action=command&command=get_udid"; unsigned char encrypt_buffer[MAX_LENGTH_DATA] = {0}; unsigned char decrypt_buffer[MAX_LENGTH_DATA] = {0}; int encrypt_size; char sizebuf[4]={0}; /*sprintf(buffer, "GET /?action=command&command=get_udid HTTP/1.1\r\n"); sprintf(buffer + strlen(buffer), "Host: %s:%s\r\n", hostname, port); sprintf(buffer + strlen(buffer), "Connection: close\r\n"); sprintf(buffer + strlen(buffer), "User-Agent: https_simple\r\n"); sprintf(buffer + strlen(buffer), "\r\n");*/ //sprintf(buffer, "action=command&command=get_udid"); printf("before encrypt !....."); encrypt_aes128((char *)hex_sha512_key, IV, (unsigned char*)buffer, encrypt_buffer, &encrypt_size); printf("encrypt buffer = %s\n", encrypt_buffer); printf("encrypt done!.....\n\n"); //send the data length to the server first sprintf(sizebuf, "%d\n", encrypt_size); send(server, sizebuf, sizeof(sizebuf), 0); // Then,send the encrypted buffer int bytes_sent = send(server, encrypt_buffer, encrypt_size, 0); printf("Sent %d bytes.\n", bytes_sent); //decrypt_aes128((char *)hex_sha512_key, IV, (unsigned char*)encrypt_buffer, decrypt_buffer); //printf("Decrypted buffer:\n%s", decrypt_buffer); //printf("Sent Headers:\n%s", buffer); if((recv(server, socket_data_size, 4, 0)!=4)){ fprintf(stderr, "ERROR:size receive != 4\n"); } while(1) { //int bytes_received = SSL_read(ssl, buffer, sizeof(buffer)); int bytes_received = recv(server, buffer, MAX_LENGTH_DATA, 0); if (bytes_received < 1) { printf("\nConnection closed by peer.\n"); break; } decrypt_aes128((char *)hex_sha512_key, IV, (unsigned char*)buffer, decrypt_buffer); printf("Received (%d bytes): '%.*s'\n", bytes_received, bytes_received, decrypt_buffer); } //end while(1) printf("\nClosing socket...\n"); //SSL_shutdown(ssl); CLOSESOCKET(server); //SSL_free(ssl); /* SSL_CTX_free(ctx);*/ #if defined(_WIN32) WSACleanup(); #endif printf("Finished.\n"); return 0; }
C
#include <sys/time.h> #include "olc.h" #include "shared.c" int main(int argc, char* argv[]) { return run(argc, argv); } static void encode(void) { char code[256]; int len; OLC_LatLon location; // Encodes latitude and longitude into a Plus+Code. location.lat = data_pos_lat; location.lon = data_pos_lon; len = OLC_EncodeDefault(&location, code, 256); ASSERT_STR_EQ(code, "8FVC2222+22"); ASSERT_INT_EQ(len, 11); } static void encode_len(void) { char code[256]; int len; OLC_LatLon location; // Encodes latitude and longitude into a Plus+Code with a preferred length. location.lat = data_pos_lat; location.lon = data_pos_lon; len = OLC_Encode(&location, data_pos_len, code, 256); ASSERT_STR_EQ(code, "8FVC2222+22GCCCC"); ASSERT_INT_EQ(len, 16); } static void decode(void) { OLC_CodeArea code_area; // Decodes a Plus+Code back into coordinates. OLC_Decode(data_code_16, 0, &code_area); ASSERT_FLT_EQ(code_area.lo.lat, 47.000062496); ASSERT_FLT_EQ(code_area.lo.lon, 8.00006250000001); ASSERT_FLT_EQ(code_area.hi.lat, 47.000062504); ASSERT_FLT_EQ(code_area.hi.lon, 8.0000625305176); ASSERT_INT_EQ(code_area.len, 15); } static void is_valid(void) { // Checks if a Plus+Code is valid. int ok = !!OLC_IsValid(data_code_16, 0); ASSERT_INT_EQ(ok, 1); } static void is_full(void) { // Checks if a Plus+Code is full. int ok = !!OLC_IsFull(data_code_16, 0); ASSERT_INT_EQ(ok, 1); } static void is_short(void) { // Checks if a Plus+Code is short. int ok = !!OLC_IsShort(data_code_16, 0); ASSERT_INT_EQ(ok, 0); } static void shorten(void) { // Shorten a Plus+Codes if possible by the given reference latitude and // longitude. char code[256]; OLC_LatLon location; location.lat = data_ref_lat; location.lon = data_ref_lon; int len = OLC_Shorten(data_code_12, 0, &location, code, 256); ASSERT_STR_EQ(code, "CJ+2VX"); ASSERT_INT_EQ(len, 6); } static void recover(void) { char code[256]; OLC_LatLon location; location.lat = data_ref_lat; location.lon = data_ref_lon; // Extends a Plus+Code by the given reference latitude and longitude. int len = OLC_RecoverNearest(data_code_6, 0, &location, code, 256); ASSERT_STR_EQ(code, "9C3W9QCJ+2VX"); ASSERT_INT_EQ(len, 12); }
C
#include <stdio.h> #include <stdlib.h> /* run this program using the console pauser or add your own getch, system("pause") or input loop */ int main(int argc, char *argv[]) { float numero_horas,salario_min,salario_receber,horas_trabalhadas,salario_bruto,imposto; printf("Insira o valor do salario minimo:"); scanf("%f",&salario_min); printf("Insira o numero de horas trabalhadas:"); scanf("%f",&numero_horas); horas_trabalhadas= salario_min/2; salario_bruto= horas_trabalhadas*numero_horas; imposto= (3/100)*salario_bruto; salario_receber= salario_bruto-imposto; printf("O salario a receber e: %f ",salario_receber); return 0; }
C
#include <stdio.h> int get_sum(int a , int b) { // Good luck int sum = 0; if(a > b){ int temp = a; a = b; b = temp; } printf("a: %d; b: %d\n", a, b); for(int i = a; i <= b; i++){ sum += i; } printf("%d\n", sum); return sum; } int main(){ get_sum(6, 4); get_sum(-1, -10); get_sum(-2, 3); return 0; }
C
#include <stdio.h> #include <stdlib.h> #include <time.h> int main () { srand(time(0)); int number=rand()%100+1; int count=0; int a; printf("Ѿһ1-100"); do{ printf("²"); scanf("%d",&a); count++; if(a>number){ printf(""); }else if(a<number){ printf("С"); } }while(a!=number); printf("ϲ%dβ¶",count); return 0; }
C
#ifndef __QUEUE_H__ #define __QUEUE_H__ #ifdef __cplusplus extern "C" { #endif typedef struct node { struct node *prev; struct node *next; } node_t; typedef struct queue { node_t headNode; } queue_t; inline void vQueue_Init(queue_t *pxQueue); inline node_t * pxQueue_First_Node(queue_t *pxQueue); inline node_t * pxQueue_Last_Node(queue_t *pxQueue); inline void vQueue_Append_Node(queue_t *pxQueue, node_t *pxNode); inline void vQueue_Push_Node(queue_t *pxQueue, node_t *pxNode); inline void vNode_Remove(node_t *pxNode); inline node_t * pxQueue_Remove_First_Node(queue_t *pxQueue); inline node_t * pxQueue_Remove_Last_Node(queue_t *pxQueue); inline void vNode_Insert(node_t *pxPrevNode, node_t *pxNewNode); #ifdef __cplusplus } //extern "C" #endif #endif
C
/* * Program: * Election.c * * Written by Li Jialong */ #include <stdio.h> #include <sys/types.h> #include <unistd.h> #include <sys/wait.h> #include <signal.h> #include <pthread.h> #include <stdlib.h> #include <time.h> #include <string.h> #include <ctype.h> #include <sys/time.h> #include <semaphore.h> #include <sys/socket.h> #include <sys/un.h> #include <netdb.h> #include <netinet/in.h> #include <arpa/inet.h> #define MAXLINE 100 #define DEFAULT_DNS_IP "8.8.8.8" #define DEFAULT_LOCAL_NAME "jialong" #define DEFAULT_DNS_PORT 50489 /* *Global variables */ int n;//the total client number is n. int tcp_port,udp_port,remote_tcp_port; int i=0,j=0; int conn_no = 0,token_num = 0,broadcast_num = 0;//connection # ,received token #,received broadcast token #. int flag,notseen = 1;//some flags int nbytes;//Received data number. int leader;//leader index char msg[100];//Message char line[100];//command line char *ip_address; char token[10],peer_token[10];//peer_token is the client's final token. char *T[10];//store the every token client receive char *BT[10];//store the broadcasted token char buf[100]; char ipvfour[INET_ADDRSTRLEN]; struct hostent *host,*he; struct sockaddr_in local_address; /* * Record the connected peer IP and TCP. */ struct connected_table { int cnnID; int fd; char *ip; char *hostname; unsigned short int local_tcp; unsigned short int remote_tcp; }; /* * Token table */ struct token_table{ char *IP; int remote_port; char tk[10]; }; /* * Broadcast table */ struct broadcast_table{ char MsgID[8]; char tok[10]; unsigned int UDPPort; char ip_addr[5]; }; /* * Parse function */ void parseLine(char *line, char *command_array[]) { char *p; int count=0; p=strtok(line, " "); while(p != 0) { command_array[count]=p; count++; p=strtok(NULL," "); } } /* * Function: Main function. */ int main(int argc,char *argv[]) { socklen_t len; int socktcp,sockudp,client_sockfd; char *command_array[100]; struct connected_table peer_conn[100]; struct token_table tt[100]; struct broadcast_table bt[100]; struct sockaddr_in serv_addr,localAddr,serv_addr_tcp,serv_addr_udp,client_addr; struct in_addr ipv4addr; printf("Election> "); //get command line. gets(line); parseLine(line,command_array); //command: citizen <n> <tcp_port> <udp_port> if(strcmp(command_array[0],"citizen") == 0) { n = atoi(command_array[1]); tcp_port = atoi(command_array[2]); udp_port = atoi(command_array[3]); } else { printf("UNKNOWN COMMAND.\n"); } //create tcp socket socktcp = socket(AF_INET, SOCK_STREAM, 0); if (socktcp < 0) { perror("ERROR opening socket.\n"); exit(1); } int optval = 1; setsockopt(socktcp, SOL_SOCKET, SO_REUSEADDR,(const void *)&optval , sizeof(int)); //create udp socket sockudp = socket(AF_INET, SOCK_DGRAM, 0); if (sockudp < 0) { perror("ERROR opening socket.\n"); exit(2); } setsockopt(sockudp, SOL_SOCKET, SO_REUSEADDR,(const void *)&optval , sizeof(int)); serv_addr_tcp.sin_family = AF_INET; serv_addr_tcp.sin_addr.s_addr = htonl(INADDR_ANY); serv_addr_tcp.sin_port = htons(tcp_port); serv_addr_udp.sin_family = AF_INET; serv_addr_udp.sin_addr.s_addr = htonl(INADDR_ANY); serv_addr_udp.sin_port = htons(udp_port); if ( bind(socktcp, (struct sockaddr *) &serv_addr_tcp, sizeof(serv_addr_tcp)) < 0 ) { printf("Error binding tcp socket!!!\n"); } if ( bind(sockudp, (struct sockaddr *) &serv_addr_udp, sizeof(serv_addr_udp)) < 0 ) { printf("Error binding udp socket!!!\n"); } //listen to the local tcp port. if (listen(socktcp,5) < 0 ) { perror("Listen error.\n"); } printf("Election> "); fflush(stdout); int fmax; fd_set read_fds; if(socktcp > sockudp) { fmax = socktcp; } else { fmax = sockudp; } while(1) { FD_ZERO(&read_fds); //add TCP socket fd FD_SET(socktcp,&read_fds); //add UDP socket fd FD_SET(sockudp,&read_fds); //add stdin fd FD_SET(0,&read_fds); for(int i = 0; i < conn_no; i++) { FD_SET(peer_conn[i].fd,&read_fds); } if( select(fmax+1,&read_fds,NULL,NULL,NULL) < 0) { perror("Select error.\n"); exit(1); } if( FD_ISSET(0,&read_fds) ) { //get command line. gets(line); parseLine(line,command_array); //command: connect <ip-address> <tcp-port> if(strcmp(command_array[0],"connect") == 0) { struct sockaddr_in serv_addr; ip_address = command_array[1]; remote_tcp_port = atoi(command_array[2]); int sockfd = socket(AF_INET, SOCK_STREAM, 0); if (sockfd < 0) { perror("ERROR opening socket.\n"); exit(2); } serv_addr.sin_family = AF_INET; host = gethostbyname(ip_address); memcpy(&serv_addr.sin_addr.s_addr, host->h_addr, host->h_length); serv_addr.sin_port = htons(remote_tcp_port); if( connect(sockfd, (struct sockaddr *) &serv_addr, sizeof(serv_addr)) < 0 ) { perror("Connection Failed!!!\n"); exit(3); } else { if(sockfd > fmax) { fmax = sockfd; } socklen_t length = sizeof localAddr; getsockname(sockfd, (struct sockaddr *) &localAddr, &(length)); int localPort = ntohs(localAddr.sin_port); printf("Connection has been established to host %s , port %d !\n" ,inet_ntoa(serv_addr.sin_addr),ntohs(serv_addr.sin_port) ); inet_pton(AF_INET,inet_ntoa(serv_addr.sin_addr),&ipv4addr); he = gethostbyaddr(&ipv4addr,sizeof(ipv4addr),AF_INET); //record the peer's IP address and TCP port peer_conn[conn_no].cnnID = conn_no+1; peer_conn[conn_no].ip = inet_ntoa(serv_addr.sin_addr); peer_conn[conn_no].hostname = he->h_name; peer_conn[conn_no].local_tcp = localPort; peer_conn[conn_no].remote_tcp = ntohs(serv_addr.sin_port); peer_conn[conn_no].fd = sockfd; conn_no++; printf("Election> "); fflush(stdout); } } //command : ready else if(strcmp(command_array[0],"ready") == 0) { printf("Network is ready,please initialize the tokens: "); gets(token); //Initial MessageID srandom( time(0) ); for(int i = 0; i < 7 ; i++ ) { msg[i] = (random() % 10 + 48); } msg[7] = '0'; //MessageType msg[8] = '0'; //PayloadLength msg[9] = '1'; msg[10] = '0'; //Payload:token[0..10]->msg[11-21] for(int j = 0; j < 10; j++) { msg[j+11] = token[j]; } //send private message to all its peer for(int i = 0;i < conn_no; i++) { send(peer_conn[i].fd,msg,strlen(msg),0); } printf("Election> "); fflush(stdout); } //command : info else if(strcmp(command_array[0],"info") == 0) { struct sockaddr_in server_address; int sock_fd = 0, pton_ret, sock_name_no, host_name_no; char server_ip[MAXLINE] = DEFAULT_DNS_IP; char local_name[MAXLINE] = DEFAULT_LOCAL_NAME; uint16_t server_port = DEFAULT_DNS_PORT; socklen_t len; memset((void *) &server_address, 0, sizeof(server_address)); server_address.sin_family = AF_INET; server_address.sin_port = htons(server_port); pton_ret = inet_pton(AF_INET, server_ip, &server_address.sin_addr); if (pton_ret <= 0) { printf("inet_pton() failed\n"); } //create a UDP socket if ((sock_fd = socket(AF_INET, SOCK_DGRAM, 0)) < 0) { printf("socket() failed\n"); } if (connect(sock_fd, (struct sockaddr *) &server_address,sizeof(server_address)) == -1) { printf("connect() failed\n"); exit(0); } len = sizeof(local_address); sock_name_no = getsockname(sock_fd, (struct sockaddr *) &local_address,&len); if (sock_name_no < 0) { printf("getsockname() error\n"); } printf("IP address | hostname | TCP port | UDP port \n"); printf("--------------------------------------------------\n"); printf("%10s",inet_ntoa(local_address.sin_addr)); printf("|"); host_name_no = gethostname(local_name, MAXLINE); if (host_name_no < 0) { printf("gethostname() error\n"); } printf("%20s", local_name); printf(" |"); printf("%6d", tcp_port); printf(" | "); printf("%6d", udp_port); printf(" | \n"); printf("\n"); printf("Election> "); fflush(stdout); } //command : show-conn else if(strcmp(command_array[0],"show-conn") == 0) { printf("cnnID | IP | hostname | local port | remote port \n"); printf("------------------------------------------------------\n"); for(int i = 0; i < conn_no;i++) { printf("%2d",peer_conn[i].cnnID); printf(" | "); printf("%10s",peer_conn[i].ip); printf(" | "); printf("%16s",peer_conn[i].hostname); printf(" | "); printf("%6d",peer_conn[i].local_tcp); printf(" | "); printf("%6d\n",peer_conn[i].remote_tcp); } printf("\n"); printf("Election> "); fflush(stdout); } //command : self-token else if(strcmp(line,"self-token") == 0) { if(flag > 0) { printf("Self-token is : "); for(int count = 0; count < 10 ; count++) { printf("%c",peer_token[count]); } printf("\n"); } else { printf("WAITING ON PEER_TOKEN.\n"); } printf("Election> "); fflush(stdout); } //command : all-tokens else if(strcmp(command_array[0],"all-tokens") == 0) { printf("IP | remote port | token \n"); printf("------------------------------------------\n"); for(int i = 0; i < token_num ; i++) { printf("%10s",tt[i].IP); printf(" | "); printf("%6d",tt[i].remote_port); printf(" | "); for(int j = 0; j < 10; j++) { printf("%c",tt[i].tk[j]); } printf("\n"); } for(int i = 0;i < broadcast_num;i++) { inet_ntop(AF_INET,bt[i].ip_addr,ipvfour,INET_ADDRSTRLEN); printf("%10s",ipvfour); printf(" | "); printf("%6d",bt[i].UDPPort); printf(" | "); for(int j = 0; j < 10; j++) { printf("%c",bt[i].tok[j]); } printf("\n"); } printf("Election> "); fflush(stdout); } //command : exit else if(strcmp(command_array[0],"exit") == 0) { exit(0); } //other command will display error. else { printf("UNKNOWN COMMAND.\n"); printf("Election> "); fflush(stdout); } } //receice new connection if( FD_ISSET(socktcp,&read_fds) ) { len = sizeof(client_addr); client_sockfd = accept(socktcp, (struct sockaddr *) &client_addr, &len); if (client_sockfd < 0) { perror("ERROR opening client socket.\n"); exit(3); } if(client_sockfd > fmax) { fmax = client_sockfd; } printf("Received the connection from host %s ,port %d .\n",inet_ntoa(client_addr.sin_addr), ntohs(client_addr.sin_port) ); inet_pton(AF_INET,inet_ntoa(client_addr.sin_addr),&ipv4addr); he = gethostbyaddr(&ipv4addr,sizeof(ipv4addr),AF_INET); peer_conn[conn_no].cnnID = conn_no+1; peer_conn[conn_no].ip = inet_ntoa(client_addr.sin_addr); peer_conn[conn_no].hostname = he->h_name; peer_conn[conn_no].local_tcp = tcp_port; peer_conn[conn_no].remote_tcp = ntohs(client_addr.sin_port); peer_conn[conn_no].fd = client_sockfd; conn_no++; printf("Election> "); fflush(stdout); } //receive UDP data if( FD_ISSET(sockudp,&read_fds) ) { struct sockaddr rv_addr; len = sizeof rv_addr; //received salute message recvfrom(sockudp,buf,sizeof buf,0,&rv_addr,&len); char temp_token[10]; for(int i = 0; i < 10; i++) { temp_token[i] = buf[i+11]; } printf( "Leader received the salute message from peer : "); for(int i = 0 ; i < 10 ; i++) { printf("%c",temp_token[i]); } printf("\n"); } //receive user's TCP data. for(int k = 0; k < conn_no ; k++) { struct sockaddr_storage addr; char ipstr[1000]; int temp_port; len = sizeof(struct sockaddr_in); if( FD_ISSET(peer_conn[k].fd,&read_fds) ) { //receive TCP data if(nbytes = recv(peer_conn[k].fd,buf,100,0) <= 0) { if(nbytes == 0) { printf("selectserver: socket %d hung up\n", peer_conn[k].fd); } else { perror("Recv.\n"); exit(0); } close(peer_conn[k].fd); FD_CLR(peer_conn[k].fd, &read_fds); } else { //receive private message if(buf[8] == '0') { char tmp[10]; for(int i = 0; i < 10; i++) { tmp[i] = buf[i+11]; } getpeername(peer_conn[k].fd, (struct sockaddr*)&addr, &len); struct sockaddr_in *s = (struct sockaddr_in *)&addr; temp_port = ntohs(s->sin_port); inet_ntop(AF_INET, &s->sin_addr, ipstr, sizeof ipstr); printf("Received the token: "); for(int i = 0; i < 10; i++) { printf("%c",tmp[i]); } printf(" from host %s ,port %d .\n",ipstr,temp_port); tt[token_num].IP = ipstr; tt[token_num].remote_port = temp_port; strcpy(tt[token_num].tk,tmp); token_num++; //Determine its own token if(token_num == conn_no) { char max[10]; strcpy(max,tt[0].tk); for(int i = 1; i < token_num;i++) { if( strcmp(max,tt[i].tk) < 0 ) { strcpy(max,tt[i].tk); } } strcpy(peer_token,max); printf("My own token is:"); for(int i = 0; i < 10; i++) { printf("%c",peer_token[i]); } printf("\n"); //If determine the peer token ,then flag = 1. flag = 1; //broadcast its own token to all its peers //Initial MessageID srandom( time(0) ); for(int i = 0; i < 7 ; i++ ) { msg[i] = (random() % 10 + 48); } msg[7] = '0'; //MessageType msg[8] = '1'; //PayloadLength msg[9] = '1'; msg[10] = '6'; for(int i = 0;i < 10;i++) { msg[i+11] = peer_token[i]; } memcpy(&msg[21],&local_address.sin_addr.s_addr,4*sizeof(char) ); memcpy(&msg[25],&udp_port,2*sizeof(char)); //send its own token to all its peers for(int i = 0; i < conn_no ; i++) { send(peer_conn[i].fd,msg,strlen(msg),0); } } printf("Election> "); fflush(stdout); } //receive broadcast message if(buf[8] == '1') { char msgID[8],t[10],port[2],ip[4]; unsigned short int port_num; //Get the MessageID for(int i = 0;i < 8; i++) { msgID[i] = buf[i]; } //Get the token for(int i = 0; i < 10; i++) { t[i] = buf[i+11]; } //Get the IPAddress for(int i = 0; i < 4;i++) { ip[i] = buf[i+21]; } //Get the UDPPort for(int i = 0; i < 2;i++) { port[i] = buf[i+25]; } memcpy( &port_num,port,2*sizeof(char) ); for(int i = 0;i < broadcast_num; i++) { //If it has already seen the message,discard it if(strcmp(bt[i].MsgID,msgID) == 0) { printf("Discard this broadcast token!\n"); notseen = 0; } } //If the message has not been seen,save and forward it. if(notseen > 0) { strcpy(bt[broadcast_num].MsgID,msgID); strcpy(bt[broadcast_num].tok,t); printf( "Received the broadcast peer token: "); for(int i = 0; i < 10; i++) { printf("%c",bt[broadcast_num].tok[i]); } printf("\n"); memcpy(&bt[broadcast_num].ip_addr,ip,4*sizeof(char) ); memcpy(&bt[broadcast_num].UDPPort,&port_num,2*sizeof(char) ); broadcast_num++; //Forward the message to all its peers except initializer. for(int j = 0;j < conn_no;j++) { if( j != k ) { send(peer_conn[j].fd,buf,strlen(buf),0); } } } } //If receive all other's peer token. if( ( broadcast_num == n-1 )&&( flag == 1 ) ) { char max[10]; strcpy(max,bt[0].tok); leader = 0; for(int i = 1;i < broadcast_num;i++) { if( strcmp(max,bt[i].tok) < 0 ) { leader = i; strcpy(max,bt[i].tok); } } //send the salute message if ( strcmp(max,peer_token) > 0 ) { int sock; char saluteMsg[100]; struct sockaddr_in dest; //send the UDP message to the leader. sock = socket(AF_INET,SOCK_DGRAM,0); dest.sin_family = AF_INET; inet_ntop(AF_INET,bt[leader].ip_addr,ipvfour,INET_ADDRSTRLEN); inet_pton(AF_INET,ipvfour,&dest.sin_addr); dest.sin_port = htons(bt[leader].UDPPort); //printf("destination is %s ,port is %d ",ipvfour,bt[leader].UDPPort); srandom( time(0) ); for(int i = 0; i < 7 ; i++ ) { saluteMsg[i] = (random() % 10 + 48); } saluteMsg[7] = '0'; //MessageType saluteMsg[8] = '2'; //PayloadLength saluteMsg[9] = '3'; saluteMsg[10] = '6'; //msg[11..20] for(int i = 0; i < 10 ;i++) { saluteMsg[i+11] = peer_token[i]; } //msg[21..36] char MessageText[100] = "ALL HAIL THE MIGHTY LEADER"; for(int i = 0; i < 26 ; i++) { saluteMsg[i+21] = MessageText[i]; } if ( sendto(sock,saluteMsg,strlen(saluteMsg),0,(struct sockaddr *)&dest,sizeof dest) < 0) { perror("Send fail!!!\n"); } else { printf("Send the salute message to the leader!!!\n"); } } printf("Election> "); fflush(stdout); } } } } } }
C
#include<PIC.h> #include<stdio.h> #define sl1 RA1 #define sl2 RC0 #define sl3 RC1 #define sl4 RC2 unsigned char disp[25]={0xfc,0x60,0xda,0xf2,0x66,0xb6,0xbe,0xe0,0xfe,0xf6}; char ds1=0,ds2=0,ds3=0,ds4=0; void delay(unsigned int); void display(); void incrementd(); void main() { TRISB=0x00; TRISA=0x00; TRISC=0x00; int i,j; while(1) { for(j=0;j<=5;j++) display(); incrementd(); } } void display() { sl1=0; sl2=1; sl3=1; sl4=1; PORTB=disp[ds1]; delay(1); sl1=1; sl2=0; sl3=1; sl4=1; PORTB=disp[ds2]; delay(1); sl1=1; sl2=1; sl3=0; sl4=1; PORTB=disp[ds3]; delay(1); sl1=1; sl2=1; sl3=1; sl4=0; PORTB=disp[ds4]; delay(1); } void delay(unsigned int del) { int d1,d2; for(d1=0;d1<=del;d1++) for(d2=0;d2<=120;d2++); } void incrementd() { ds1=ds1+1; if (ds1>9) { ds1=0; ds2=ds2+1; if (ds2>9) { ds2=0; ds3=ds3+1; if (ds3>9) { ds3=0; ds4=ds4+1; if(ds4>9) { ds1=0; ds2=0; ds3=0; ds4=0; } else return; } else return; } else return; } else return; }
C
/* How do you calculate the maximum subarray of a list of numbers? Kadane Algorithm */ #include<stdio.h> int max(int x, int y) { return (y > x)? y : x; } int maxSubArraySum(int a[], int size) { int max_so_far = a[0], i; int curr_max = a[0]; for (i = 1; i < size; i++) { curr_max = max(a[i], curr_max+a[i]); max_so_far = max(max_so_far, curr_max); } return max_so_far; } /* Driver program to test maxSubArraySum */ int main() { int a[] = {-2, -3, 4, -1, -2, 1, 5, -3}; int n = sizeof(a)/sizeof(a[0]); int max_sum = maxSubArraySum(a, n); printf("Maximum contiguous sum is %d\n", max_sum); return 0; }
C
#include <stdio.h> #include <string.h> // for strlen() #include <stdlib.h> // for exit() #include "Auxiliary.h" #include "CreateTCPClientSocket.h" #define RCVBUFSIZE 32 /* Size of receive buffer */ int main (int argc, char *argv[]) { int sock; /* Socket descriptor */ char * echoString; /* String to send to echo server */ char echoBuffer[RCVBUFSIZE]; /* Buffer for received string */ int echoStringLen; /* Length of string to echo */ int bytesRcvd; /* Bytes read in single recv() */ int i; /* counter for data-arguments */ parse_args (argc, argv); sock = CreateTCPClientSocket (argv_ip, argv_port); for (i = 0; i < argv_nrofdata; i++) { echoString = argv_data [i]; echoStringLen = strlen (echoString); /* Determine input length */ delaying(); char sendBuffer[32]; //printing the sending data printf("%s \n", argv_data[i]); strcpy(sendBuffer, argv_data[i]); // TODO: add code to send this string to the server; use send() send (sock,sendBuffer,sizeof(sendBuffer), 0); // TODO: add code to display the transmitted string in verbose mode; use info_s(sendBuffer, sendBuffer); // TODO: add code to receive & display the converted string from the server // use recv() & printf() bytesRcvd = recv (sock, echoBuffer, RCVBUFSIZE-1, 0); //check if there is something received if(bytesRcvd < 0) { printf("there was an error in receiving \n"); } else { printf("received data are: %s \n", echoBuffer); for(int i = 0; i < sizeof(echoBuffer); i++) { echoBuffer[i] = 0; } } } close (sock); info ("close & exit"); exit (0); }
C
#include "_fmtspec.h" #include "_scanf.h" #include "ctype.h" #include "errno.h" #include "limits.h" #include "locale.h" #include "stdarg.h" #include "stdbool.h" #include "stdio.h" #include "stdlib.h" #include "string.h" static size_t read_count = 0; /* Total number of characters read */ static size_t converted = 0; /* Total number of specifiers processed */ static int error_state = 0; /* The most recently flagged error */ static int load_charvalue(_get_func_t get, _unget_func_t unget, void *src, char s[], size_t n); static int load_scanvalue(_get_func_t get, _unget_func_t unget, void *src, char s[], size_t n, int *scanset, int exclude); static int load_strvalue(_get_func_t get, _unget_func_t unget, void *src, char s[], size_t n); static int load_intvalue(_get_func_t get, _unget_func_t unget, void *src, char s[], size_t n, int is_unsigned, int is_hex); static int load_fpvalue(_get_func_t get, _unget_func_t unget, void *src, char s[], size_t n, int is_hex); static size_t integer_end(_get_func_t get, _unget_func_t unget, void *src, size_t n, int base); static int trim_leading(_get_func_t get, _unget_func_t unget, void *src); static int match_literal(_get_func_t get, _unget_func_t unget, void *src, char match); /* @description: Worker function for the scanf family. */ int _scanf(_get_func_t get, _unget_func_t unget, void *src, const char *fmt, va_list args) { _scanspec_t spec = {0}; read_count = 0; converted = 0; while (*fmt) { if (*fmt != '%') { if (isspace(*fmt)) { /* Discard all leading whitespace from both the source and format string. */ trim_leading(get, unget, src); while (isspace(*fmt)) ++fmt; } else { /* Try to match a literal character in the format string */ if (match_literal(get, unget, src, *fmt++) == EOF) break; } } else { size_t count = _load_scanspec(&spec, fmt); char s[BUFSIZ]; int n = 0; if (count == 0) { /* The specifier was invalid */ error_state = ESFMT; break; } fmt += count; /* Jump past the encoding specifier */ if (spec.field_width == 0) { /* Assume no field width means the maximum possible */ spec.field_width = INT_MAX; } if (spec.type == _SPEC_LITERAL) { /* Try to match a specifier starter character from the source */ if (match_literal(get, unget, src, '%') == EOF) break; } else if (spec.type == _SPEC_COUNT) { /* No encoding, the read character count was requested */ if (!spec.suppressed) *va_arg(args, int*) = read_count; } else if (spec.type == _SPEC_CHAR || spec.type == _SPEC_STRING || spec.type == _SPEC_SCANSET) { /* The three specifiers are similar, select which one to run */ switch (spec.type) { case _SPEC_CHAR: n = load_charvalue(get, unget, src, s, spec.field_width); break; case _SPEC_STRING: n = load_strvalue(get, unget, src, s, spec.field_width); break; case _SPEC_SCANSET: n = load_scanvalue(get, unget, src, s, spec.field_width, spec.scanset, spec.nomatch); break; } if (n == 0 && converted == 0) break; if (n > 0 && !spec.suppressed) { /* Only %s null terminates the destination */ memcpy(va_arg(args, char*), s, n + (spec.type == _SPEC_STRING)); ++converted; } } else if (spec.type >= _SPEC_SCHAR && spec.type <= _SPEC_PTRDIFFT) { /* Extract and convert signed integer values */ n = load_intvalue(get, unget, src, s, spec.field_width, false, spec.format == _SPEC_FMT_HEX); if (n == 0 && converted == 0) break; if (n > 0 && !spec.suppressed) { /* Out of range values invoke undefined behavior, so we'll play DS9000 here */ long long value = strtoull(s, 0, spec.format); switch (spec.type) { case _SPEC_SCHAR: *va_arg(args, signed char*) = (signed char)value; break; case _SPEC_SHORT: *va_arg(args, short*) = (short)value; break; case _SPEC_INT: *va_arg(args, int*) = (int)value; break; case _SPEC_LONG: *va_arg(args, long*) = (long)value; break; case _SPEC_LLONG: /* Fall through */ case _SPEC_INTMAXT: *va_arg(args, long long*) = value; break; case _SPEC_PTRDIFFT: *va_arg(args, int*) = (int)value; break; } ++converted; } } else if (spec.type >= _SPEC_UCHAR && spec.type <= _SPEC_PTRDIFFT) { /* Extract and convert unsigned integer values */ n = load_intvalue(get, unget, src, s, spec.field_width, true, spec.format); if (n == 0 && converted == 0) break; if (n > 0 && !spec.suppressed) { /* Out of range values invoke undefined behavior, so we'll play DS9000 here */ unsigned long long value = strtoull(s, 0, spec.format); switch (spec.type) { case _SPEC_UCHAR: *va_arg(args, unsigned char*) = (unsigned char)value; break; case _SPEC_USHORT: *va_arg(args, unsigned short*) = (unsigned short)value; break; case _SPEC_UINT: *va_arg(args, unsigned int*) = (unsigned int)value; break; case _SPEC_ULONG: *va_arg(args, unsigned long*) = (unsigned long)value; break; case _SPEC_ULLONG: /* Fall through */ case _SPEC_UINTMAXT: *va_arg(args, unsigned long long*) = value; break; case _SPEC_SIZET: *va_arg(args, unsigned int*) = (unsigned int)value; break; } ++converted; } } else if (spec.type >= _SPEC_FLOAT && spec.type <= _SPEC_LDOUBLE) { /* Extract and convert floating point values */ n = load_fpvalue(get, unget, src, s, spec.field_width, false); if (n == 0 && converted == 0) break; if (n > 0 && !spec.suppressed) { /* Out of range values invoke undefined behavior, so we'll play DS9000 here */ switch (spec.type) { case _SPEC_FLOAT: *va_arg(args, float*) = strtof(s, 0); break; case _SPEC_DOUBLE: *va_arg(args, double*) = strtod(s, 0); break; case _SPEC_LDOUBLE: *va_arg(args, long double*) = strtold(s, 0); break; } ++converted; } } } } return (converted == 0 || error_state) ? EOF : converted; } /* @description: Extracts up to n characters into the specified buffer. */ int load_charvalue(_get_func_t get, _unget_func_t unget, void *src, char s[], size_t n) { size_t i; for (i = 0; i < n; ++i) { int ch = get(src, &read_count); if (ch == EOF) { unget(&ch, src, &read_count); break; } s[i] = (char)ch; } return i; } /* @description: Extracts up to n valid scanset characters into the specified buffer. */ int load_scanvalue(_get_func_t get, _unget_func_t unget, void *src, char s[], size_t n, int *scanset, int exclude) { size_t i; for (i = 0; i < n; ++i) { int ch = get(src, &read_count); if (ch == EOF || ((exclude && scanset[ch]) || (!exclude && !scanset[ch]))) { unget(&ch, src, &read_count); break; } s[i] = (char)ch; } s[i] = '\0'; return i; } /* @description: Extracts a whitespace delimited string into the specified buffer. */ int load_strvalue(_get_func_t get, _unget_func_t unget, void *src, char s[], size_t n) { if (trim_leading(get, unget, src) == EOF) return 0; else { size_t i; for (i = 0; i < n; ++i) { int ch = get(src, &read_count); if (ch == EOF || isspace(ch)) { unget(&ch, src, &read_count); break; } s[i] = (char)ch; } s[i] = '\0'; return i; } } /* @description: Extracts a valid integer string representation into the specified buffer. */ int load_intvalue(_get_func_t get, _unget_func_t unget, void *src, char s[], size_t n, int is_unsigned, int base) { if (trim_leading(get, unget, src) == EOF) return 0; else { size_t i = 0, iend; if (!base) base = 10; /* Assume decimal */ /* Get a count of valid locale friendly integer characters */ iend = integer_end(get, unget, src, n, base); if (!iend) { /* There are no valid groups */ return 0; } while (n--) { int ch = get(src, &read_count); if (ch == EOF) break; /* Further error check anything that's not a thousands separator */ if (ch != *localeconv()->thousands_sep) { if (i == 0 && (ch == '-' || ch == '+')) { if (is_unsigned) { /* The sign isn't in an expected location */ unget(&ch, src, &read_count); break; } } else if (_digitvalue(ch, base) == -1) { if (!(base == 16 && i == 1 && tolower(ch) == 'x')) { /* Alternate format characters aren't in an expected location */ unget(&ch, src, &read_count); break; } continue; /* Skip over alternate format characters */ } } /* Always add even the thousands separator */ s[i++] = (char)ch; } s[i] = '\0'; return i; } } /* @description: Extracts a valid floating point string representation into the specified buffer. */ int load_fpvalue(_get_func_t get, _unget_func_t unget, void *src, char s[], size_t n, int is_hex) { if (trim_leading(get, unget, src) == EOF) return 0; else { int (*is_digit)(int) = is_hex ? isxdigit : isdigit; char exponent = is_hex ? 'p' : 'e'; bool in_exponent = false; bool seen_decimal = false; bool seen_digit = false; int last = EOF; size_t i, iend; /* Find the end of the integer part of the mantissa */ iend = integer_end(get, unget, src, n, 10); /* At this point iend is either greater than zero (there was a valid integer part), or it's zero (no integer part) and the next character is a decimal point. Anything else represents a format error for the value. */ if (!iend) { int ch = get(src, &read_count); /* ch being EOF falls into this test naturally */ if (ch != *localeconv()->decimal_point) { unget(&ch, src, &read_count); return 0; } } for (i = 0; i < n; ++i) { int ch = get(src, &read_count); if (ch == EOF) break; else if (is_digit(ch)) seen_digit = true; else { /* Only ignore the thousands separator when we're in the integer part. Otherwise all subsequent checks apply and a thousands separator is erroneous. */ if (i >= iend || ch != *localeconv()->thousands_sep) { if (ch == '+' || ch == '-') { if (last != EOF && !(in_exponent && tolower(last) == exponent)) { /* The sign isn't in an expected location */ unget(&ch, src, &read_count); break; } } else if (tolower(ch) == 'x' && !(is_hex && i == 1)) { /* Alternate format characters aren't in an expected location */ unget(&ch, src, &read_count); break; } else if (tolower(ch) == exponent) { if (!seen_digit) { /* We can't have an exponent without a value */ unget(&ch, src, &read_count); break; } in_exponent = true; } else if (ch == *localeconv()->decimal_point) { if (in_exponent) { /* The decimal isn't in an expected location */ unget(&ch, src, &read_count); break; } seen_decimal = true; } else { /* Invalid character */ unget(&ch, src, &read_count); break; } } } /* Always add even the thousands separator */ s[i] = (char)ch; last = ch; } s[i] = '\0'; return i; } } /* @description: Locates the end of the first valid integer string from the source. This function is aware of the current locale's LC_NUMERIC setting. */ size_t integer_end(_get_func_t get, _unget_func_t unget, void *src, size_t n, int base) { char *grouping = localeconv()->grouping; int group_len = 0, group_size = *grouping; int stack[BUFSIZ]; int top = 0; size_t i = 0; if (!*localeconv()->thousands_sep) { /* Avoid potentially a lot of work if the locale doesn't support separators */ return n; } /* Find the end of the possible characters */ while (i++ < n && (stack[top] = get(src, &read_count)) != EOF && !isspace(stack[top])) ++top; if (i < n) { /* We stopped on an invalid character */ unget(&stack[top--], src, &read_count); } while (top >= 0) { if (top == 0 && group_size && _digitvalue(stack[i], base) != -1) i = 0; else if (top > 0 && group_size && ++group_len == group_size) { if (top - 1 == 0 || stack[top - 1] != *localeconv()->thousands_sep) { /* Invalid group: reset grouping, mark the end and proceed */ grouping = localeconv()->grouping; group_size = *grouping; group_len = 0; i = top; /* Save 1 past the last valid character */ } else { /* Valid group: move to the next grouping level */ if (*grouping && *++grouping) group_size = *grouping; group_len = 0; /* Skip over the separator so we don't error on the next iteration */ unget(&stack[top--], src, &read_count); } } else if ((stack[top] == '-' || stack[top] == '+') && top > 0) { /* Invalid sign: reset grouping, mark the end and proceed */ grouping = localeconv()->grouping; group_size = *grouping; group_len = 0; i = top; /* Save 1 past the last valid character */ } else if (!(stack[top] == '-' || stack[top] == '+') && _digitvalue(stack[top], base) == -1) { /* Invalid digit: reset grouping, mark the end and proceed */ grouping = localeconv()->grouping; group_size = *grouping; group_len = 0; i = top; /* Save 1 past the last valid character */ } unget(&stack[top--], src, &read_count); } return i; } /* @description: Extract and discard leading whitespace from the source. */ int trim_leading(_get_func_t get, _unget_func_t unget, void *src) { int ch; do { if ((ch = get(src, &read_count)) == EOF) break; } while (isspace(ch)); /* Push back the non-whitespace character that broke the loop */ unget((char*)&ch, src, &read_count); return ch; } /* @description: Extract and match a specific character value from the source. */ int match_literal(_get_func_t get, _unget_func_t unget, void *src, char match) { int ch = get(src, &read_count); /* Match a literal character */ if (ch != match) { unget(&ch, src, &read_count); return EOF; } return ch; }
C
#include <stdio.h> #include<stdlib.h> int main(){ int a, i, j, k; scanf("%d",&a); for(i = 1; i <= a; i++){ for(j = 1; j <= a - i; j++){ printf(" "); } for( k = 1; k <= 2 * i - 1; k++){ printf("*"); } printf("\n"); } return 0; }