language
large_stringclasses
1 value
text
stringlengths
9
2.95M
C
#include <stdio.h> #include <ctype.h> #include <stdbool.h> #include "terminal_user_input.h" #define YEAR_TRUMP_ELECTED 2016 bool read_boolean(const char* prompt) { my_string answer; bool result; answer = read_string(prompt); answer.str[0] = (char) tolower(answer.str[0]); switch (answer.str[0]) { case 'n': result = false; break; case 'x': result = false; break; default: result = true; } return result; } int trump_age(int year_born) { int result = 0; result = YEAR_TRUMP_ELECTED - year_born; return result; } int main() { my_string name; int age_when_Trump_elected = 0; int year_born = 0; bool brexit; name = read_string("What is your name? "); printf("Your name is: %s\n", name.str); year_born = read_integer("What year were you born? "); age_when_Trump_elected = trump_age(year_born); printf("%s, you were %d years old when Trump was elected.\n", name.str, age_when_Trump_elected); brexit = read_boolean("Do you support Brexit? "); if (brexit) { printf("You support Brexit!\n"); } else { printf("You don't support Brexit!\n"); } read_string("Type 'exit' to continue: "); return 0; }
C
#ifndef SFVFS_HEADER_H #define SFVFS_HEADER_H #include "sfvfs/config.h" #include "sfvfs/fsnode.h" #include <stdbool.h> struct sfvfs_header { struct sfvfs_options option; /* 配置记录 */ uint32_t version; /* 版本号 */ uint16_t umask; /* 挂载文件权限掩码 */ uint16_t dmast; /* 挂载目录权限掩码 */ uint64_t block_count; /* block的数目 */ uint64_t file_sum_size; /* 文件实际使用的总空间 */ uint64_t block_sum_size; /* 文件系统真实占用的空间(不考虑空洞时) */ struct sfvfs_fsnode root_node; } __attribute__((__packed__)); /* 前向声明结构体 */ struct sfvfs_fs; /** * @brief 初始化header, 仅仅应该在文件新被创立时调用一次 * @method voidsfvfs_init_header * @param sfs 文件系统指针 */ extern void sfvfs_init_header (struct sfvfs_fs * sfs); /** * @brief 检查文件系统中读取的header和用户期望的header版本是否一致 * @method intsfvfs_check_header * @param sfs 文件系统指针 * @return 一致返回1, 不一致返回0 */ extern bool sfvfs_check_header (struct sfvfs_fs * sfs); /** * @brief 读取当前文件系统的header * @method intsfvfs_read_header * @param sfs 文件系统指针 * @param header 文件头指针(传NULL会直接将原始映射地址取出来) * @return 成功返回地址, 否则返回NULL */ extern struct sfvfs_header * sfvfs_read_header (struct sfvfs_fs * sfs, struct sfvfs_header * header); /** * @brief 存储文件系统的header * @method intsfvfs_save_header * @param sfs 文件系统指针 * @param header 文件头指针 * @return 成功返回0, 否则返回异常号 */ extern int sfvfs_save_header (struct sfvfs_fs * sfs, struct sfvfs_header * header); /** * @brief 将版本号转换为C风格字符串格式 * @method voidsfvfs_version2string * @param version 版本号 * @param str 储存数据的字符串数组 */ extern void sfvfs_version2string (int version, char str[16]); /** * @brief 将字符串转换为版本号 * @method uint32_tsfvfs_string2version * @param str 字符串数组 * @return 转换后的版本号,失败返回-1 */ extern uint32_t sfvfs_string2version (char str[16]); #endif /* end of include guard: SFVFS_HEADER_H */
C
#include "stdio.h" #define SIZE 10 // Testing shifting functions of asm int main(){ int *testArray = (int*)malloc(sizeof(int)*SIZE); int i; for (i=0; i<SIZE; i++){ *(testArray+i)=i; printf("%d ", testArray[i]); } printf("\n"); int end = testArray+(SIZE); int start = testArray+1; printf("\nChecking shift below\n"); // Move array for one word (4bytes) below ( high adresses -> low addreses) asm volatile( "movl %0, %%ecx\n" // End of the moved area - bottom addr "movl %1, %%ebx\n" // Start of the moved area - highest addr "shift_act: movl (%%ecx), %%eax\n" // Loop: "movl %%eax, -4(%%ecx)\n" // -4(%%ecx) = (%%ecx) "addl $0x4, %%ecx\n" // %%ecx += 4 "cmp %%ecx, %%ebx\n" // if (%%ecx == %%ebx) "jne shift_act\n" // goto loop_act : :"m"(start),"m"(end) :"%ecx","%ebx","%eax" // -4(%%ebx) = %%eax ); // Check // Valid sequence is 1 2 3 4 5 6 7 8 9 9 for (i=0; i<SIZE-1; i++){ if ( testArray[i]!= i+1 ) { printf("Test of shift_below failed\n"); break; } } if (testArray[ SIZE-1] != SIZE-1){ printf("Test of shift_below failed\n"); } //////// for (i=0; i<SIZE; i++){ printf("%d ", testArray[i]); } printf("\nChecking shift_above\n"); end = testArray+SIZE-1; start = testArray; // Move array for one word (4bytes) above ( high adresses <- low addreses) asm( "movl %0, %%ebx\n" // End of the moved area "movl %1, %%ecx\n" // Start of the moved area "backshift_act: movl (%%ecx), %%eax\n" "movl %%eax, 4(%%ecx)\n" "subl $0x4, %%ecx\n" "cmp %%ecx, %%ebx\n" "jng backshift_act\n" ::"m"(start),"m"(end):"%ecx","%ebx","%eax"); for (i=0; i<SIZE; i++){ printf("%d ", testArray[i]); } // Check // Valid sequence is 1 1 2 3 4 5 6 7 8 9 for (i=1; i<SIZE; i++){ if ( testArray[i]!= i ) { printf("Test of shift_above failed"); break; } } if (testArray[0] != 1){ printf("Test of shift_above failed\n"); } /////// return 0; }
C
// Fill out your copyright notice in the Description page of Project Settings. #pragma once #include "CoreMinimal.h" static FORCEINLINE float FSmoothDamp(float Current, float Target, float& CurrentVelocity, float SmoothTime, float MaxSpeed, float DeltaTime) { if (SmoothTime < 0.0001f) return Target; float num = 2.f / SmoothTime; float num2 = num * DeltaTime; float num3 = 1.f / (1.f + num2 + 0.48f * num2 * num2 + 0.235f * num2 * num2 * num2); float num4 = Current - Target; float num5 = Target; float num6 = MaxSpeed * SmoothTime; num4 = FMath::Clamp(num4, -num6, num6); Target = Current - num4; float num7 = (CurrentVelocity + num * num4) * DeltaTime; CurrentVelocity = (CurrentVelocity - num * num7) * num3; float num8 = Target + (num4 + num7) * num3; if (num5 - Current > 0.f == num8 > num5) { num8 = num5; CurrentVelocity = (num8 - num5) / DeltaTime; } return num8; } static FORCEINLINE FVector2D VSmoothDamp2D(const FVector2D& Current, const FVector2D& Target, FVector2D& CurrentVelocity, float SmoothTime, float MaxSpeed, float DeltaTime) { if (SmoothTime < 0.0001f) return Target; FVector2D result; result.X = FSmoothDamp(Current.X, Target.X, CurrentVelocity.X, SmoothTime, MaxSpeed, DeltaTime); result.Y = FSmoothDamp(Current.Y, Target.Y, CurrentVelocity.Y, SmoothTime, MaxSpeed, DeltaTime); return result; } static FORCEINLINE FVector VSmoothDamp(const FVector& Current, const FVector& Target, FVector& CurrentVelocity, float SmoothTime, float MaxSpeed, float DeltaTime) { if (SmoothTime < 0.0001f) return Target; FVector result; result.X = FSmoothDamp(Current.X, Target.X, CurrentVelocity.X, SmoothTime, MaxSpeed, DeltaTime); result.Y = FSmoothDamp(Current.Y, Target.Y, CurrentVelocity.Y, SmoothTime, MaxSpeed, DeltaTime); result.Z = FSmoothDamp(Current.Z, Target.Z, CurrentVelocity.Z, SmoothTime, MaxSpeed, DeltaTime); return result; } static FORCEINLINE FRotator RSmoothDamp(const FRotator& Current, const FRotator& Target, FRotator& CurrentVelocity, float SmoothTime, float MaxSpeed, float DeltaTime) { if (SmoothTime < 0.0001f) return Target; FRotator result; result.Pitch = FSmoothDamp(Current.Pitch, Target.Pitch, CurrentVelocity.Pitch, SmoothTime, MaxSpeed, DeltaTime); result.Yaw = FSmoothDamp(Current.Yaw, Target.Yaw, CurrentVelocity.Yaw, SmoothTime, MaxSpeed, DeltaTime); result.Roll = FSmoothDamp(Current.Roll, Target.Roll, CurrentVelocity.Roll, SmoothTime, MaxSpeed, DeltaTime); return result; }
C
#include <stdio.h> //function prototy[pe int iterative(int n); int recursive(int n); int main() { int result = 0; result = iterative(3); result = recursive(4); printf("result: %d\n",result); return 0; } int iterative(int n) { int total = 0; for (int i = 1; i <= n; ++i) { total = total * i; } return(total); } int recursive(int n) { int total = 0; printf("stacking recursive(%d)\n",n); if (n == 1) { printf("total: %d\n",total); return n; } else { total = n * recursive(n-1); printf("total: %d\n",total); return total; } }
C
#ifdef CUT_MODIFIER_C #include <stdio.h> #include <string.h> #include <stdlib.h> #include "parse.h" void test_func(char *str, char *expected, int i) { char *cutted; cutted = cut_modifier(str); printf("%d:[%s] [%s]\n", i, str, expected); if (strcmp(cutted, expected)) printf("error at %d, output was [%s]\n\n", i, cutted); free(cutted); } int main(void) { char* examples[] = { "input", "expected", "aaa", "aaa", "\"aaa\"", "aaa", "bb\"aaa\"bb", "bbaaabb", "'bb''aaa''bb'", "bbaaabb", "'bb\"aaa\"bb'", "bb\"aaa\"bb", "'\\bb\"aaa\"bb\\'", "\\bb\"aaa\"bb\\", "a\"\\\"\\$\\\\\"a", "a\"$\\a", "a\"b\\\"\\$\\\\b\"a", "ab\"$\\ba", "a\" \\a \\$ \\` \\\" \\\\ \\b \"a", "a \\a $ ` \" \\ \\b a", "\\\\\\\\\\\\", "\\\\\\", "'\\\\\\\\\\\\'", "\\\\\\\\\\\\", "\"\\\\\\\\\\\\\"", "\\\\\\", NULL }; for (int i = 0; examples[i]; i += 2) { test_func(examples[i], examples[i + 1], i / 2); } } #endif
C
#include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <stdlib.h> #include <string.h> #define MAXSTRING 256 int main() { char c; int connectionFD; int ret; char buffer[MAXSTRING]; connectionFD = clientConnection ("lserv"); if (connectionFD < 0) { perror ("Error establishing connection\n"); exit (1); } ret = read (connectionFD, buffer, sizeof (buffer)); if (ret < 0) { perror ("Error reading from connection\n"); exit (1); } while (ret > 0) { write(1, &buffer, ret); ret = read (connectionFD, buffer, sizeof (buffer)); if (ret < 0) { perror ("Error reading from connection\n"); exit (1); } } closeConnection (connectionFD); }
C
#include "comm.h" static int commMsgQueue(int flags)//创建或获取消息队列 { key_t key = ftok("/tmp", 0x6666);//0x6666,only 0~255 if(key < 0) { perror("ftok"); return -1; } int msg_id = msgget(key, flags); if(msg_id < 0) { perror("msgget"); } return msg_id; } int createMsgQueue() { return commMsgQueue(IPC_CREAT|IPC_EXCL|0666);//创建,如果存在返回错误,666权限 } int getMsgQueue() { return commMsgQueue(IPC_CREAT);//获取消息队列 } int destoryMsgQueue(int msg_id) { if(msgctl(msg_id, IPC_RMID, NULL) < 0) { perror("msgctl"); return -1; } return 0; } int sendMsgQueue(int msg_id, int who, char* msg) { struct msgbuf buf; buf.mtype = who; strcpy(buf.mtext, msg); if(msgsnd(msg_id, (void*)&buf, sizeof(buf.mtext), 0) < 0)//sizeof(buf.mtext) { perror("msgsnd"); return -1; } return 0; } int recvMsgQueue(int msg_id, int recvType, char out[]) { struct msgbuf buf; int size=sizeof(buf.mtext); printf("size = %d,out[] = %ld\n",size,sizeof(out)); if(msgrcv(msg_id, (void*)&buf, size, recvType, 0) < 0) { perror("msgrcv"); return -1; } strncpy(out, buf.mtext, size); out[size] = 0; return 0; }
C
///////////////////////////////////////// // LCD configuration //////////////////////////////////////// sbit LCD_RS at RB0_bit; sbit LCD_EN at RB1_bit; sbit LCD_D4 at RB4_bit; sbit LCD_D5 at RB5_bit; sbit LCD_D6 at RB6_bit; sbit LCD_D7 at RB7_bit; sbit LCD_RS_Direction at TRISB0_bit; sbit LCD_EN_Direction at TRISB1_bit; sbit LCD_D4_Direction at TRISB4_bit; sbit LCD_D5_Direction at TRISB5_bit; sbit LCD_D6_Direction at TRISB6_bit; sbit LCD_D7_Direction at TRISB7_bit; //////////////////////////////////////////////// // Define variable /////////////////////////////////////////////// unsigned char i; // variable for transmitting UART data unsigned char t; // variable for receiving UART data void main() { /////////////////////////////////////////////////////////// // input - output confug /////////////////////////////////////////////////////////// TRISB = 0; // make PORTB output for LCD TRISC.F7 = 1; // make RX input TRISC.F6 = 0; // make TX output ///////////////////////////////////////////////////////////// // LCD commands ///////////////////////////////////////////////////////////// Lcd_Init(); Lcd_Cmd(_LCD_CLEAR); Lcd_Cmd(_LCD_CURSOR_OFF); Lcd_Out(1,2,"pic 1"); ///////////////////////////////////////////////////////////// // Initialize UART with a baud rate of 9600 ////////////////////////////////////////////////////////////// UART1_Init(9600); i = 'A'; /////////////////////////////////////////// // For Error message Delay_ms(3000); //send 'a' for first time to anthor pic Uart1_write (i); Delay_ms(20); ///////////////////////////////////////////////////////////// // main program //////////////////////////////////////////////////////////// for ( ; ; ) { //recive data from anthor pic if (Uart1_Data_Ready()) { t = Uart1_Read(); //recived message if( t == 'r' || t == 'R') { Lcd_Cmd(_LCD_CLEAR); Lcd_Chr(2,8,t); i++; //send NEXT CHAR Uart1_write (i); Delay_ms(20); } //error message if( t == 'e' || t == 'E') { Lcd_Cmd(_LCD_CLEAR); Lcd_Chr(2,8,t); //send SAME CHAR Uart1_write (i); Delay_ms(20); } } } }
C
//// fathm_ft.c -- converts 2 fathoms to feet //#include <stdio.h> //int main(void) //{ // int feet, fathoms; // // fathoms = 2; // feet = 6 * fathoms; // printf("There are %d feet in %d fathoms!\n", feet, fathoms); // printf("Yes, I said %d feet!\n", 6 * fathoms); // // return 0; //} // /* qsort example */ #include <stdio.h> /* printf */ #include <stdlib.h> /* qsort */ // int values[] = { 40, 10, 100, 90, 20, 25 }; int compare (const void * a, const void * b) { return ( *(int*)a - *(int*)b ); } int main () { int n; qsort (values, 6, sizeof(int), compare); for (n=0; n<6; n++) printf ("%d ",values[n]); return 0; }
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 custo_esp,preco_bilhete,q_bilhete; printf("Insira o custo do espetaculo teatral:"); scanf("%f",&custo_esp); printf("Insira o preco do bilhete:"); scanf("%f",&preco_bilhete); q_bilhete= custo_esp/preco_bilhete; printf("A quantidade de bilhetes que devem ser vendidos e: %f \n",q_bilhete); return 0; }
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* main.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: wawong <[email protected]> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2018/03/31 06:22:16 by wawong #+# #+# */ /* Updated: 2018/04/01 16:39:04 by wawong ### ########.fr */ /* */ /* ************************************************************************** */ #include <stdlib.h> #include <unistd.h> #include "eval.h" #include "math.h" void ft_putchar(char c) { write(1, &c, 1); } void ft_putnbr(int nb) { int j; j = -2147483647; if (nb < j) { ft_putnbr(nb / 10); ft_putnbr((unsigned int)nb % 10); return ; } if (nb < 0) { ft_putchar('-'); ft_putnbr(-nb); } else if (nb > 9) { ft_putnbr(nb / 10); ft_putnbr((unsigned int)nb % 10); } else ft_putchar(nb + '0'); } void rm_space(char *source) { char *i; char *j; i = source; j = source; while (*j != 0) { *i = *j++; if (*i != ' ') i++; } *i = '*'; *(++i) = '1'; *(++i) = '\0'; } int eval_expr(char *av) { t_formula postfix; char *form; int res; form = av; rm_space(form); postfix = to_postfix(form); res = result(postfix); return (res); } int main(int ac, char **av) { if (ac > 1) { ft_putnbr(eval_expr(av[1])); ft_putchar('\n'); } return (0); }
C
#include<stdio.h> int main() { int i,j,t,temp,n,m,sum; scanf("%d", &t); for(i=1 ; i<=t ; i++){ scanf("%d\n%d", &n,&m); sum=0; if(n>m){ temp=n; n=m; m=temp; } for(j=n ; j<=m ; j++){ if(j%2!=0){ sum = sum + j; } } printf("Case %d: %d\n", i, sum); } return 0; }
C
#include "holberton.h" /** * set_bit - function that sets the value of a bit to 1 at a given index. * @n: pointer of numbers * @index: index position * * Return: 1 if it worked, or -1 if an error occurred */ int set_bit(unsigned long int *n, unsigned int index) { unsigned int num = 1; if (index > 63) return (-1); num <<= index; *n |= num; return (1); }
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* ft_strsplit.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: mbinder <[email protected]> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2013/12/03 17:47:46 by mbinder #+# #+# */ /* Updated: 2015/01/26 17:11:47 by mbinder ### ########.fr */ /* */ /* ************************************************************************** */ #include <string.h> #include <stdlib.h> #include "libft.h" static int count_words(char *str, char c) { int i; int count; i = 0; count = 0; if (str == NULL) return (0); while (str[i]) { while (str[i] == c) i++; if (str[i] != c && str[i] != '\0') count++; while (str[i] != c && str[i] != '\0') i++; } return (count); } static int count_letters(char *str, char c) { int i; i = 0; if (str == NULL) return (0); while (*(str + i) != c && *(str + i) != '\0') i++; return (i); } static int ft_copy(char **tab, char *str, char c) { int i; i = 0; while (str != NULL && *str != '\0') { while (*str == c) str++; if (*str != '\0') { tab[i] = (char*)ft_memalloc(count_letters(str, c) + 1); if (tab[i] == NULL) return (-1); ft_strncpy(tab[i], str, count_letters(str, c)); str = str + count_letters(str, c); i++; } } tab[i] = NULL; return (0); } char **ft_strsplit(const char *s, char c) { char *str; char **tab; size_t len; if (s) { len = ft_strlen(s) + 1; if ((str = (char*)ft_memalloc(sizeof(*str) * (len))) == NULL) return (NULL); ft_strcpy(str, s); if (count_words(str, c) == 0) { free(str); return (NULL); } if ((tab = (char**)ft_memalloc(sizeof(*tab) * (count_words(str, c) + 1)))) ft_copy(tab, str, c); free(str); return (tab); } return (NULL); }
C
#include "AdjacencyList.h" #include "Stack.h" #include<stdio.h> #include<stdlib.h> #include<assert.h> typedef int CostType; static void findDegree(ALGraph *graph,int indegree[]); static CostType *ve = NULL; //the array of earliest occuring time static CostType *vl = NULL; //the array of latest occur time static Stack tt; //topo sort int topoLogicalOrder(ALGraph *graph){ int *indegree,i,v,count; ArcNode *p; Stack st; count = 0; indegree = (int *)malloc(sizeof(int) * graph->vexnum); //save information of entry-degree assert(indegree != NULL); ve = (CostType *)malloc(sizeof(CostType) * graph->vexnum); vl = (CostType *)malloc(sizeof(CostType) * graph->vexnum); assert(ve != NULL && vl != NULL); findDegree(graph,indegree); //initialize indegree initStack(&st); //initialize stack initStack(&tt); for(i=0;i<graph->vexnum;i++){ //push 0-entry-degree vertex into stack if(indegree[i] == 0){ stack_push(&st,i); } ve[i] = vl[i] = 0; } while(!stack_isEmpty(&st)){ stack_pop(&st,&v); stack_push(&tt,v); //save the topo serial count++; //delete arcs related to v for(p=graph->alist[v].firstarc;p!=NULL;p=p->nextarc){ if(--indegree[p->adjvex] == 0){ stack_push(&st,p->adjvex); //push the new 0-entry-degree vertexs } if(ve[v] + *(p->info) > ve[p->adjvex]){ //the maxmum cost ve[p->adjvex] = ve[v] + *(p->info); } } } if(count < graph->vexnum){ return 0; } return 1; } //output the critical path int criticalPath(ALGraph *graph){ int i,j; ArcNode *p; CostType ne,nl; char tag; if(topoLogicalOrder(graph) == 0){ return 0; } for(i=0;i<graph->vexnum;i++){ vl[i] = ve[graph->vexnum-1]; //initialize vl } for(i=0;i<graph->vexnum;i++){ //find the inverse topological serials for(stack_pop(&tt,&j),p=graph->alist[j].firstarc;p!=NULL;p=p->nextarc){ if(vl[j] > vl[p->adjvex] - *(p->info)){ vl[j] = vl[p->adjvex] - *(p->info); } } } for(i=0;i<graph->vexnum;i++){ for(p=graph->alist[i].firstarc;p!=NULL;p=p->nextarc){ ne = ve[i]; //earliest start time nl = vl[p->adjvex] - *(p->info); //latest start time tag = ne == nl ? '*' : ' '; printf("%c--%d-->%d,dut=%d,ne=%d,nl=%d\n",tag,i,p->adjvex,*(p->info),ne,nl); } } } //find the entry degree of each vertex static void findDegree(ALGraph *graph,int indegree[]){ int i; ArcNode *p; for(i=0;i<graph->vexnum;i++){ indegree[i] = 0; } for(i=0;i<graph->vexnum;i++){ for(p=graph->alist[i].firstarc;p != NULL;p=p->nextarc){ indegree[p->adjvex]++; } } }
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* ft_history.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: kyazdani <[email protected]> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2018/03/06 11:41:13 by kyazdani #+# #+# */ /* Updated: 2018/04/16 12:22:21 by kyazdani ### ########.fr */ /* */ /* ************************************************************************** */ #include "sh.h" extern int g_optind; extern char *g_optarg; static int set_bits(int c, int fl) { if (c == 'w') fl |= 1; else if (c == 'r') fl |= 2; else if (c == 's') fl |= 4; else if (c == 'c') fl |= 8; else if (c == 'd') fl |= 16; return (fl); } static int step_2(t_hist **histo, char **str, int flags) { if (!flags) return (print_history(histo, str)); if (8 & flags) return (free_history(histo)); if (16 & flags) return (free_offset_hist(histo, g_optarg)); if (1 & flags) return (full_hist_file(histo, *str)); if (2 & flags) return (append_to_list(histo, *str)); if (4 & flags) return (replace_w_arg(histo, str)); return (0); } int ft_history(t_hist **histo, char **str) { int flags; int c; flags = 0; c = 0; reset_ft_opt(); while ((c = ft_getopt(ft_tablen(str), str, "crswd:")) != -1) { if (ft_strchr("crswd", (char)c)) flags = set_bits(c, flags); else if (c == ':' || c == '?') { ft_putstr_fd("history: usage: history [-c] [-d offset] [n] or \ history -wr [filename] or history -s arg [arg...]\n", STDERR_FILENO); return (1); } } if ((1 & flags) && (2 & flags)) { ft_putendl_fd("42sh: history: cannot use more than one of -rw", 2); return (1); } else return (step_2(histo, &str[g_optind], flags)); }
C
#include <pgmspace.h> #pragma language=extended /* compare unsigned char s1[n], s2[n] */ __x_z int (memcmp_P)(const void *s1, PGM_VOID_P s2, size_t n) { unsigned char uc1, uc2; if (n != 0) do { uc1 = *(*(const unsigned char **)&s1)++; uc2 = *(*(PGM_P*)&s2)++; if (uc1 != uc2) return uc1 < uc2 ? -1 : 1; } while(--n); return n; }
C
/* * color.h - Data structures and function prototypes for coloring algorithm * to determine register allocation. */ #ifndef COLOR_H #define COLOR_H #include "graph.h" #include "liveness.h" struct COL_result { Temp_map coloring; // description of register allocation Temp_tempList spills; // spilled registers }; /** * Given the interference graph, precolored nodes and machine registers, just do * the graph coloring * @param{initial} pre-colored nodes */ struct COL_result COL_color(struct Live_graph ig, Temp_map initial, Temp_tempList regs); #endif
C
#include<stdio.h> int main() { /* struct point01{ char a; char b; int c; }; */ struct point02 { char a; int b; char c; }; printf("%d\n", sizeof(struct point02)); return 0; }
C
#include<stdio.h> #include<stdlib.h> #define ElemType int #define STATUS int #define ERROR -1 #define SUCCESS 1 #define TRUE 1 #define FALSE 0 /* Դͷѭʾ,ֻһָָβԪؽ ԱдӦÿն,ж϶ǷΪ,Ӻͳ㷨 */ typedef struct { ElemType data; struct LNode *next; }QNode,*QueuePtr; typedef struct { QueuePtr front; QueuePtr rear; }Queue,*LinkQueue; STATUS init(LinkQueue *queue); STATUS enQueue(LinkQueue *queue,ElemType element); ElemType deQueue(LinkQueue *queue); ElemType getHead(LinkQueue queue);
C
#include "lexer.h" #include "filehandler.h" #include <ctype.h> #include <stdio.h> #include <stdlib.h> #include <string.h> inline void printSequence(const Sequence *seq) { printf("\n"); for (int i = 0; i < seq->count; i++) printf("%s ", seq->tokens[i].value); printf("\n"); } static inline void allocate(Sequence *seq) { seq->count++; seq->tokens = realloc(seq->tokens, seq->count * sizeof(*seq->tokens)); } inline void cleanUpSeq(Sequence seq) { // while (seq.count--) // free(seq.tokens[seq.count].value); free(seq.tokens); } char *trimwhitespace(char *str) { char *end; // Trim leading space while (isspace((unsigned char)*str)) str++; if (*str == 0) // All spaces? return str; // Trim trailing space end = str + strlen(str) - 1; while (end > str && isspace((unsigned char)*end)) end--; // Write new null terminator character end[1] = ESC; return str; } int isNumeric(const char *s) { if (s == NULL || *s == ESC || isspace(*s)) return 0; char *p; strtod(s, &p); return *p == ESC; } void setTokenValueAttr(const Sequence *seq, char *value, const Attribute attr) { seq->tokens[seq->count - 1].value = value; seq->tokens[seq->count - 1].attr = attr; } Sequence lex(FileContents *fileContents) { Sequence seq = {.count = 0, .tokens = malloc(sizeof(*seq.tokens))}; for (int i = 0; i < fileContents->linecount; i++) { char *line = fileContents->lines[i]; char firstnum = 0; char *rawToken; // First rawToken rawToken = strtok(line, " "); // Loop other tokens while (rawToken != NULL) { // trim whitespace rawToken = trimwhitespace(rawToken); allocate(&seq); if (strcmp(rawToken, FUNC) == 0) { setTokenValueAttr(&seq, rawToken, _funcDef); } else if (seq.tokens[seq.count - 2].attr == _funcDef) { setTokenValueAttr(&seq, rawToken, _funcName); } else if (isNumeric(rawToken)) { if (firstnum == 0 && (seq.tokens[seq.count - 2].attr != _int || seq.tokens[seq.count - 2].attr != _float)) { setTokenValueAttr(&seq, "(", _leftBracket); allocate(&seq); firstnum = 1; } setTokenValueAttr(&seq, rawToken, strchr(rawToken, DOT) ? _float : _int); char *tmp = strtok(NULL, " "); if (tmp == NULL) { allocate(&seq); setTokenValueAttr(&seq, ")", _rightBracket); firstnum = 0; } rawToken = tmp; continue; } else if (strcmp(rawToken, RET_TYPE) == 0) { setTokenValueAttr(&seq, rawToken, _funcReturnType); } else if (seq.tokens[seq.count - 2].attr == _funcReturnType) { setTokenValueAttr(&seq, rawToken, _type); } else if (isOperator(rawToken[strlen(rawToken) - 1])) { setTokenValueAttr(&seq, rawToken, _operator); char c = rawToken[0]; switch (c) { case SUB: case ADD: seq.tokens[seq.count - 1].precedence = 2; seq.tokens[seq.count - 1].associate = left_to_right; break; case MUL: case DIV: case MOD: seq.tokens[seq.count - 1].precedence = 3; seq.tokens[seq.count - 1].associate = left_to_right; break; case LARR: case RARR: seq.tokens[seq.count - 1].precedence = 1; seq.tokens[seq.count - 1].associate = left_to_right; break; default: break; } } else if (strcmp(rawToken, IF) == 0) { setTokenValueAttr(&seq, rawToken, _if); } else if (strcmp(rawToken, ELIF) == 0) { setTokenValueAttr(&seq, rawToken, _elif); } else if (strcmp(rawToken, ELSE) == 0) { setTokenValueAttr(&seq, rawToken, _else); } // used for function calls for now else { setTokenValueAttr(&seq, rawToken, _funcCall); } // Get next rawToken rawToken = strtok(NULL, " "); } } printSequence(&seq); // cleanUpSeq(seq); return seq; }
C
#include <math.h> #include <stdio.h> int main(){ double a, b, c, root1, root2, delta; printf("Enter value for a, b, c:\n"); scanf("%lf %lf %lf", &a, &b, &c); if (a == 0){ printf("The a variable cannot be zero.\n"); return 1; } delta = b * b - 4 * a * c; if (delta > 0){ root1 = ((-b + sqrt(delta)) / (2 * a)); root2 = ((-b - sqrt(delta)) / (2 * a)); printf("x1: %.2lf \nx2: %.2lf\n", root1, root2); return 0; } if (delta == 0){ root1 = root2 = -b / (2 * a); printf("x: %.2lf\n", root1); return 0; } if (delta < 0){ printf("No real root.\n"); return 1; } return 0; }
C
/* ** EPITECH PROJECT, 2019 ** PSU_my_printf_2019 ** File description: ** my_printf.h */ #include <stdarg.h> #ifndef MY_H_ #define MY_H_ #define BASE_HEXA "0123456789abcdef" #define BASE_HEXA_UPPER_CASE "0123456789ABCDEF" #define BASE_OCTAL "01234567" #define BINARY_BASE "01" int check_number_of_stick_on_line(char **map, int line); void formatting_unsigned_int(char, unsigned int); int my_put_nbr_unsigned_int(unsigned int); void formatting_decimal(char, int); int my_put_nbr_long_int(long int); void formatting_hexadecimal(char, unsigned int); void formatting_upper_hexadecimal(char, unsigned int); int my_put_nbr_unsigned_long_int(unsigned long int); int next_char_check(char *, va_list, char *, int); int my_printf(char *, ...); void print_unprintable_char_in_octal(char *, int); int my_putstr(char const *); char modifier_check(char *, va_list, char *, int); int my_charcmp(char, char, char *); int my_strlen(const char *); int my_put_nbr(int); void my_charupcase(char); void print_hexadecimal(va_list, char); void print_upper_hexadecimal(va_list, char); int my_getnbr(const char *); void my_putchar(char ); int my_strcmp(char *, char *); void print_decimal(va_list, char); void print_string(va_list, char); void my_put_nbr_base(unsigned long long int, char *); void print_adress(va_list, char); void print_upper_string(va_list, char); void print_unsigned_int(va_list, char); void print_character(va_list, char); void print_upper_character(va_list, char); void print_octal(va_list, char); void print_binary(va_list, char); void print_unprintable(va_list, char); #endif /* !MY_H_ */
C
#include <stdlib.h> void main(){ int sum = 0, n; scanf("%d", &n); for(int i = 1; i <= n; i++){ sum += i; } printf("%d\n", sum); return; }
C
#include <stdio.h> #include <stdlib.h> #define TRUE (1) #define FALSE (0) typedef int Status; /* 二叉树的二叉链表结点结构定义 */ typedef struct BiTNode { int data; struct BiTNode *lchild, *rchild; } BiTNode, *BiTree; /* 顺序查找,a为数组,n为要查找的数组个数,key为要查找的关键字 */ int Sequential_Search(int *a, int n, int key) { int i; for (i = 1; i <= n; i++) { if (a[i] == key) { return i; } } return 0; } /* 有哨兵顺序查找 */ int Sequential_Search2(int *a, int n, int key) { int i; a[0] = key; // 设置a[0]为关键字值,我们称之为“哨兵” i = n; // 循环从数组尾部开始 while (a[i] != key) { i--; } return i; // 返回0则说明查找失败 } /* 折半查找 */ int Binary_Search(int *a, int n, int key) { int low, high, mid; low = 1; high = n; while (low <= high) { mid = (low + mid) / 2; /* mid = low + (high-low)*(key-a[low])/(a[high]-a[low]) --> 插值 */ if (key < a[mid]) { high = mid - 1; } else if (key > a[mid]) { low = mid + 1; } else { return mid; } } return 0; } /* 斐波那契查找 */ static const int F[10] = {0, 1, 1, 2, 3, 5, 8, 13, 21, 34}; int Fibonacci_Search(int *a, int n, int key) { int low, high, mid, i, k; low = 1; // 定义最低下标为记录首位 high = n; // 定义最高下标为记录末位 k = 0; while (n > F[k] - 1) // 计算n位于斐波那契数列的位置 { k++; } for (i = n; i < F[k] - 1; i++) // 将不满的数值补全 { a[i] = a[n]; } while (low < high) { mid = low + F[k - 1] - 1; // 计算当前分割的下标 if (key < a[mid]) // 若查找记录小于当前分割记录 { high = mid - 1; // 最高下标调整到分割下标mid-1处 k = k - 1; // 斐波那契数列下标减1位 } else if (key > a[mid]) // 若查找记录大于当前分割记录 { low = mid + 1; // 最低下标调整到分割下标mid+1处 k = k - 2; // 斐波那契数列下标减两位 } else { if (mid <= n) { return mid; // 若相等则说明mid即为查找到的位置 } else { return n; // 若mid>n说明是补全数值,返回n } } } return n; } /** * 递归查找二叉排序树T中是否存在key * 指针f指向T的双亲,其初始调用值为NULL * 若查找成功,则指针p指向该数据元素结点,并返回TRUE * 否则指针p指向查找路径上访问的最后一个结点并返回FALSE */ Status SearchBST(BiTree T, int key, BiTree f, BiTree *p) { if (!T) // 查找不成功 { *p = f; return FALSE; } else if (key == T->data) // 查找成功 { *p = T; return TRUE; } else if (key < T->data) { return SearchBST(T->lchild, key, T, p); // 在左子树继续查找 } else { return SearchBST(T->rchild, key, T, p); } } /** * 当二叉排序树T中不存在关键字等于key的数据元素时 * 插入key并返回TRUE,否则返回FALSE */ Status InsertBST(BiTree *T, int key) { BiTree p, s; if (!SearchBST(*T, key, NULL, &p)) // 查找不成功 { s = (BiTree)malloc(sizeof(BiTNode)); s->data = key; s->lchild = s->rchild = NULL; if (!p) { *T = s; // 插入s为新的根结点 } else if (key < p->data) { p->lchild = s; // 插入s为左孩子 } else { p->rchild = s; // 插入s为右孩子 } return TRUE; } else { return FALSE; // 树中已有关键字相同的结点,不再插入 } } /* 从二叉排序树中删除结点p,并重接它的左或右子树 */ Status Delete(BiTree *p) { BiTree q, s; if ((*p)->rchild == NULL) // 右子树空则只需重接它的左子树 { q = *p; *p = (*p)->lchild; free(q); } else if ((*p)->lchild == NULL) // 只需重接它的右子树 { q = *p; *p = (*p)->rchild; free(q); } else { q = *p; s = (*p)->lchild; while (s->rchild) // 转左,然后向右到尽头(找待删结点的前驱) { q = s; s = s->rchild; } (*p)->data = s->data; // s指向被删除结点的直接前驱 if (q != *p) { q->rchild = s->lchild; // 重接q的右子树 } else { q->lchild = s->lchild; // 重接q的左子树 } free(s); } return TRUE; } /* 若二叉排序树T中存在关键字等于key的数据元素时,则删除该数据元素的结点 */ /* 并返回TRUE,否则返回FALSE */ Status DeleteBST(BiTree *T, int key) { if (!*T) { return FALSE; } else { if (key == (*T)->data) { return Delete(T); } else if (key < (*T)->data) { return DeleteBST(&(*T)->lchild, key); } else { return DeleteBST(&(*T)->rchild, key); } } }
C
#include <stdio.h> #include <aSubRecord.h> #include <registryFunction.h> #include <epicsExport.h> #include <string.h> static long profile_value_reverse(aSubRecord *precord) { int lx; int ly; int *x; int *y; // get dimension of camera image data array lx = *(int*) precord->a; ly = *(int*) precord->b; // get data x = (int *) precord->c; y = (int *) precord->d; // compute reverse arrays int i,j; int rx[lx]; int ry[ly]; for(i=lx-1,j=0;i>=0;i--,j++) { rx[j] = x[i]; } for(i=ly-1,j=0;i>=0;i--,j++) { ry[j] = y[i]; } // send to VALA and VALB memcpy(precord->vala,rx,precord->nova*sizeof(int)); memcpy(precord->valb,ry,precord->novb*sizeof(int)); return 0; } static long profile_index(aSubRecord *precord) { int lx; int ly; int i; int type; // get dimension of camera image data array lx = *(int*) precord->a; ly = *(int*) precord->b; type = *(int*)precord->c; // init arrays int x[lx]; int y[ly]; // calculate the array of indexes for the profile in X for(i=0;i<lx;i++) { x[i] = i; //printf("-- %ld ",x[i]); } memcpy(precord->vala,x,precord->nova*sizeof(int)); // calculate the array of indexes for the profile in Y for(i=0;i<ly;i++) { y[i] = i; //printf("== %ld ",y[i]); } memcpy(precord->valb,y,precord->novb*sizeof(int)); return 0; } static long sign_conversion(aSubRecord *precord) { char *imgIn; // get image file path from INPA imgIn = (char *) precord->a; // save data to VALA memcpy(precord->vala, imgIn, precord->nova*sizeof(unsigned char)); return 0; } static long limit_values(aSubRecord *precord) { int i; char *imgIn; char *imgOut; long length; // get image file path from INPA imgIn = (char *) precord->a; imgOut = imgIn; length = (long) precord->noa; for (i=0; i<length; i++) { imgOut[i] = imgIn[i] < 0 ? 127 : imgIn[i]; } // save data to VALA memcpy(precord->vala, imgOut, precord->nova*sizeof(unsigned char)); return 0; } static long change_monitoring(aSubRecord *precord) { // get current image counter int counter_current = *(int*) precord->a; // store current value as previous later for next call *(long *) precord->vala = counter_current; // get the previous value int counter_old = *(int*) precord->b; // output 1 to OUTB is change is detected, 0 otherwise *(long *) precord->valb = counter_current > counter_old ? 1 : 0; return 0; } epicsRegisterFunction(profile_index); epicsRegisterFunction(profile_value_reverse); epicsRegisterFunction(sign_conversion); epicsRegisterFunction(limit_values); epicsRegisterFunction(change_monitoring);
C
/* JTSK-320111 a3_p6.c Sheikh Usman Ali [email protected]*/ // Writing charactwers I #include <stdio.h> #include<ctype.h> int main(void) { char line [100]; float x; int n, i; printf("Enter an float x: \n"); fgets (line , sizeof(line), stdin ); sscanf (line , "%f", &x ); printf("Enter an Int n: \n"); fgets (line , sizeof(line), stdin ); sscanf (line , "%d", &n ); while (n < 0) { printf("Enter again \n"); scanf( "%d", &n); } while (n == 0) { printf("null \n"); printf("Enter again \n"); scanf( "%d", &n); } for( i=0; i<n; i++ ) printf("%f \n",x); }
C
// preprocessor directive to support printing to the display #include <stdio.h> void getInfo(float* PTRprice, float* PTRmarkUp, float* PTRtax, float* PTRdiscount); float calcPrice (float price, float markUp, float tax, float discount); // the main program int main(void) { // declare, define, and initialize some working variables float price; float markUp; float tax; float discount; float listPrice; getInfo(&price, &markUp, &tax, &discount); listPrice = calcPrice(price, markUp, tax, discount); // ask the user for some data printf("The final price, with tax, will be: %0.2f\n", listPrice); return 0; } void getInfo(float* PTRprice, float* PTRmarkUp, float* PTRtax, float* PTRdiscount) { printf("**Enter all the following data in decimal form**\n"); printf("Please enter the Manufacturer's Price (number): \n\t"); scanf("%f", PTRprice); printf("Please enter the Dealer's Mark Up (percentage): \n\t"); scanf("%f", PTRmarkUp); printf("Please enter the Local Sales Tax (percentage): \n\t"); scanf("%f", PTRtax); printf("Please enter the Expected Discount (percentage): \n\t"); scanf("%f", PTRdiscount); } float calcPrice(float price, float markUp, float tax, float discount) { float listPrice; float dealerPrice = price + price * markUp; printf("After dealer mark up: %0.2f\n\n", dealerPrice); float preTax = dealerPrice - price*discount; printf("After dealer discount, but before taxes: %0.2f\n\n", preTax); listPrice = preTax + (preTax)*tax; return listPrice; }
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* options.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: kvignau <[email protected]> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2018/08/27 20:01:14 by kvignau #+# #+# */ /* Updated: 2018/08/27 20:01:17 by kvignau ### ########.fr */ /* */ /* ************************************************************************** */ #include "../includes/ft_ssl.h" t_opts ft_init_opts(void) { t_opts opt; opt.opt = 0; opt.fd = 1; opt.output = NULL; opt.input = NULL; opt.len = 0; return (opt); } int ft_check_options(char *arg, t_opts *opt) { int i; i = 1; while (arg && arg[i]) { if (arg[i] == 'p') opt->opt = opt->opt | OPT_P; else if (arg[i] == 'q') opt->opt = opt->opt | OPT_Q; else if (arg[i] == 'r') opt->opt = opt->opt | OPT_R; else if (arg[i] == 's') opt->opt = opt->opt | OPT_S; else { print_errors("ft_ssl: illegal option -- "); print_errors(&arg[i]); print_errors("\nAvailable options: ft_ssl [-pqrs]\n"); return (EXIT_FAILURE); } i++; } return (EXIT_SUCCESS); } void free_hash_names(char **hash_names) { int i; i = 0; while (hash_names[i]) { free(hash_names[i]); i++; } free(hash_names); } int ft_created_file(t_opts *opt) { if ((opt->fd = open(opt->output, O_WRONLY | O_CREAT | O_TRUNC, 0666)) < 0) { print_errors("ft_ssl: "); print_errors(opt->output); print_errors(": Error creating file\n"); return (EXIT_FAILURE); } return (EXIT_SUCCESS); } int ft_next_arg(char *arg, t_opts *opt) { if ((opt->opt & OPT_O) && !opt->output) { opt->output = strdup(arg); return (EXIT_SUCCESS); } if ((opt->opt & OPT_I) && !opt->input) { opt->input = strdup(arg); return (EXIT_SUCCESS); } return (print_errors("Options error\n")); } int ft_check_des(char *arg, t_opts *opt) { int i; i = 0; while (arg && arg[++i]) { if (arg[i] == 'd') opt->opt = opt->opt | OPT_D; else if (arg[i] == 'e') opt->opt = opt->opt | OPT_E; else if (arg[i] == 'i') opt->opt = opt->opt | OPT_I; else if (arg[i] == 'o') opt->opt = opt->opt | OPT_O; else { print_errors("ft_ssl: illegal option -- "); print_errors(&arg[i]); print_errors("\nAvailable options: ft_ssl hash [-deio]\n"); return (EXIT_FAILURE); } } return (EXIT_SUCCESS); } int ft_options_des(int *i, t_opts *opt, int argc, char **argv) { while ((*i) < argc) { if (argv[(*i)][0] == '-') { if (argv[(*i)][1] == '\0' || argv[(*i)][1] == '-') break ; if (ft_check_des(argv[(*i)], opt) == EXIT_FAILURE) return (EXIT_FAILURE); } else { if (ft_next_arg(argv[(*i)], opt)) return (EXIT_FAILURE); } (*i)++; } if (((opt->opt & OPT_O) && !opt->output) || ((opt->opt & OPT_I) && !opt->input)) return (print_errors("Options error\n")); return (opt->opt & OPT_O ? (ft_created_file(opt)) : (EXIT_SUCCESS)); } int ft_options(int *i, t_opts *opt, int argc, char **argv) { while ((*i) < argc && argv[(*i)][0] == '-') { if (argv[(*i)][1] == '\0') break ; else if (argv[(*i)][1] == '-') { (*i)++; break ; } else if (ft_check_options(argv[(*i)], opt) == EXIT_FAILURE) return (EXIT_FAILURE); (*i)++; } return (EXIT_SUCCESS); } int ft_hash_name(int *hash_choice, t_opts *opt, char *algo) { char **hash_names; hash_names = NULL; hash_names = ft_strsplit(HASH, '|'); algo = ft_strupper(algo); while (hash_names[(*hash_choice)]) { if (ft_strcmp(algo, hash_names[(*hash_choice)]) == 0) { if ((*hash_choice) > 1) opt->opt = opt->opt | OPT_DES; opt->opt = opt->opt | OPT_GH; free_hash_names(hash_names); return (EXIT_SUCCESS); } (*hash_choice)++; } if (hash_names) free_hash_names(hash_names); print_errors("HASH: "); print_errors(algo); print_errors(" does not exist\nAvailable hash ["); print_errors(HASH); return (print_errors("]\n")); }
C
// #include <mysql.h> // #include <stdio.h> // main() { // fprintf(stderr, "Hello Main\n"); // MYSQL *conn; // MYSQL_RES *res; // MYSQL_ROW row; // char *server = "localhost"; // char *user = "root"; // char *password = "root"; /* set me first */ // char *database = "mysql"; // conn = mysql_init(NULL); // /* Connect to database */ // if (!mysql_real_connect(conn, server, // user, password, database, 0, NULL, 0)) { // fprintf(stderr, "%s\n", mysql_error(conn)); // exit(1); // } // /* send SQL query */ // if (mysql_query(conn, "show tables")) { // fprintf(stderr, "%s\n", mysql_error(conn)); // exit(1); // } // res = mysql_use_result(conn); // /* output table name */ // printf("MySQL Tables in mysql database:\n"); // while ((row = mysql_fetch_row(res)) != NULL) // printf("%s \n", row[0]); // /* close connection */ // mysql_free_result(res); // mysql_close(conn); // } #import <stdio.h> #include <stdlib.h> #include "encryptor/sha256.h" int main(int argc, char* argv[]) { // if (argc == 1) { // fprintf(stderr, "ERROR: No arguments were passed. \n\n"); // } // unsigned char text1[] = {"Sebastian"}; // sha256_encryption(text1); // unsigned char text2[] = {"Sebastian"}; // sha256_encryption(text2); SHA256_DECRYPTION_BLK blk; unsigned char psw[] = {"password_5"}; unsigned char encryption[32]; sha256_encryption(psw, encryption); sha256_decryption(&blk, encryption); fprintf(stderr, "The password is: %s\n", blk.psw); return 0; }
C
// SPDX-License-Identifier: GPL-2.0 /* * Boot config tool for initrd image */ #include <stdio.h> #include <stdlib.h> #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <unistd.h> #include <string.h> #include <errno.h> #include <endian.h> #include <linux/kernel.h> #include <linux/bootconfig.h> static int xbc_show_value(struct xbc_node *node, bool semicolon) { const char *val, *eol; char q; int i = 0; eol = semicolon ? ";\n" : "\n"; xbc_array_for_each_value(node, val) { if (strchr(val, '"')) q = '\''; else q = '"'; printf("%c%s%c%s", q, val, q, xbc_node_is_array(node) ? ", " : eol); i++; } return i; } static void xbc_show_compact_tree(void) { struct xbc_node *node, *cnode = NULL, *vnode; int depth = 0, i; node = xbc_root_node(); while (node && xbc_node_is_key(node)) { for (i = 0; i < depth; i++) printf("\t"); if (!cnode) cnode = xbc_node_get_child(node); while (cnode && xbc_node_is_key(cnode) && !cnode->next) { vnode = xbc_node_get_child(cnode); /* * If @cnode has value and subkeys, this * should show it as below. * * key(@node) { * key(@cnode) = value; * key(@cnode) { * subkeys; * } * } */ if (vnode && xbc_node_is_value(vnode) && vnode->next) break; printf("%s.", xbc_node_get_data(node)); node = cnode; cnode = vnode; } if (cnode && xbc_node_is_key(cnode)) { printf("%s {\n", xbc_node_get_data(node)); depth++; node = cnode; cnode = NULL; continue; } else if (cnode && xbc_node_is_value(cnode)) { printf("%s = ", xbc_node_get_data(node)); xbc_show_value(cnode, true); /* * If @node has value and subkeys, continue * looping on subkeys with same node. */ if (cnode->next) { cnode = xbc_node_get_next(cnode); continue; } } else { printf("%s;\n", xbc_node_get_data(node)); } cnode = NULL; if (node->next) { node = xbc_node_get_next(node); continue; } while (!node->next) { node = xbc_node_get_parent(node); if (!node) return; if (!xbc_node_get_child(node)->next) continue; if (depth) { depth--; for (i = 0; i < depth; i++) printf("\t"); printf("}\n"); } } node = xbc_node_get_next(node); } } static void xbc_show_list(void) { char key[XBC_KEYLEN_MAX]; struct xbc_node *leaf; const char *val; int ret; xbc_for_each_key_value(leaf, val) { if ((ret = xbc_node_compose_key(leaf, key, XBC_KEYLEN_MAX)) < 0) { fprintf(stderr, "Failed to compose key %d\n", ret); break; } printf("%s = ", key); if (!val || val[0] == '\0') { printf("\"\"\n"); continue; } xbc_show_value(xbc_node_get_child(leaf), false); } } #define PAGE_SIZE 4096 static int load_xbc_fd(int fd, char **buf, int size) { int ret; *buf = malloc(size + 1); if (!*buf) return -ENOMEM; ret = read(fd, *buf, size); if (ret < 0) return -errno; (*buf)[size] = '\0'; return ret; } /* Return the read size or -errno */ static int load_xbc_file(const char *path, char **buf) { struct stat stat; int fd, ret; fd = open(path, O_RDONLY); if (fd < 0) return -errno; ret = fstat(fd, &stat); if (ret < 0) return -errno; ret = load_xbc_fd(fd, buf, stat.st_size); close(fd); return ret; } static int pr_errno(const char *msg, int err) { pr_err("%s: %d\n", msg, err); return err; } static int load_xbc_from_initrd(int fd, char **buf) { struct stat stat; int ret; u32 size = 0, csum = 0, rcsum; char magic[BOOTCONFIG_MAGIC_LEN]; const char *msg; ret = fstat(fd, &stat); if (ret < 0) return -errno; if (stat.st_size < 8 + BOOTCONFIG_MAGIC_LEN) return 0; if (lseek(fd, -BOOTCONFIG_MAGIC_LEN, SEEK_END) < 0) return pr_errno("Failed to lseek for magic", -errno); if (read(fd, magic, BOOTCONFIG_MAGIC_LEN) < 0) return pr_errno("Failed to read", -errno); /* Check the bootconfig magic bytes */ if (memcmp(magic, BOOTCONFIG_MAGIC, BOOTCONFIG_MAGIC_LEN) != 0) return 0; if (lseek(fd, -(8 + BOOTCONFIG_MAGIC_LEN), SEEK_END) < 0) return pr_errno("Failed to lseek for size", -errno); if (read(fd, &size, sizeof(u32)) < 0) return pr_errno("Failed to read size", -errno); size = le32toh(size); if (read(fd, &csum, sizeof(u32)) < 0) return pr_errno("Failed to read checksum", -errno); csum = le32toh(csum); /* Wrong size error */ if (stat.st_size < size + 8 + BOOTCONFIG_MAGIC_LEN) { pr_err("bootconfig size is too big\n"); return -E2BIG; } if (lseek(fd, stat.st_size - (size + 8 + BOOTCONFIG_MAGIC_LEN), SEEK_SET) < 0) return pr_errno("Failed to lseek", -errno); ret = load_xbc_fd(fd, buf, size); if (ret < 0) return ret; /* Wrong Checksum */ rcsum = xbc_calc_checksum(*buf, size); if (csum != rcsum) { pr_err("checksum error: %d != %d\n", csum, rcsum); return -EINVAL; } ret = xbc_init(*buf, &msg, NULL); /* Wrong data */ if (ret < 0) { pr_err("parse error: %s.\n", msg); return ret; } return size; } static void show_xbc_error(const char *data, const char *msg, int pos) { int lin = 1, col, i; if (pos < 0) { pr_err("Error: %s.\n", msg); return; } /* Note that pos starts from 0 but lin and col should start from 1. */ col = pos + 1; for (i = 0; i < pos; i++) { if (data[i] == '\n') { lin++; col = pos - i; } } pr_err("Parse Error: %s at %d:%d\n", msg, lin, col); } static int init_xbc_with_error(char *buf, int len) { char *copy = strdup(buf); const char *msg; int ret, pos; if (!copy) return -ENOMEM; ret = xbc_init(buf, &msg, &pos); if (ret < 0) show_xbc_error(copy, msg, pos); free(copy); return ret; } static int show_xbc(const char *path, bool list) { int ret, fd; char *buf = NULL; struct stat st; ret = stat(path, &st); if (ret < 0) { ret = -errno; pr_err("Failed to stat %s: %d\n", path, ret); return ret; } fd = open(path, O_RDONLY); if (fd < 0) { ret = -errno; pr_err("Failed to open initrd %s: %d\n", path, ret); return ret; } ret = load_xbc_from_initrd(fd, &buf); close(fd); if (ret < 0) { pr_err("Failed to load a boot config from initrd: %d\n", ret); goto out; } /* Assume a bootconfig file if it is enough small */ if (ret == 0 && st.st_size <= XBC_DATA_MAX) { ret = load_xbc_file(path, &buf); if (ret < 0) { pr_err("Failed to load a boot config: %d\n", ret); goto out; } if (init_xbc_with_error(buf, ret) < 0) goto out; } if (list) xbc_show_list(); else xbc_show_compact_tree(); ret = 0; out: free(buf); return ret; } static int delete_xbc(const char *path) { struct stat stat; int ret = 0, fd, size; char *buf = NULL; fd = open(path, O_RDWR); if (fd < 0) { ret = -errno; pr_err("Failed to open initrd %s: %d\n", path, ret); return ret; } size = load_xbc_from_initrd(fd, &buf); if (size < 0) { ret = size; pr_err("Failed to load a boot config from initrd: %d\n", ret); } else if (size > 0) { ret = fstat(fd, &stat); if (!ret) ret = ftruncate(fd, stat.st_size - size - 8 - BOOTCONFIG_MAGIC_LEN); if (ret) ret = -errno; } /* Ignore if there is no boot config in initrd */ close(fd); free(buf); return ret; } static int apply_xbc(const char *path, const char *xbc_path) { char *buf, *data, *p; size_t total_size; struct stat stat; const char *msg; u32 size, csum; int pos, pad; int ret, fd; ret = load_xbc_file(xbc_path, &buf); if (ret < 0) { pr_err("Failed to load %s : %d\n", xbc_path, ret); return ret; } size = strlen(buf) + 1; csum = xbc_calc_checksum(buf, size); /* Backup the bootconfig data */ data = calloc(size + BOOTCONFIG_ALIGN + sizeof(u32) + sizeof(u32) + BOOTCONFIG_MAGIC_LEN, 1); if (!data) return -ENOMEM; memcpy(data, buf, size); /* Check the data format */ ret = xbc_init(buf, &msg, &pos); if (ret < 0) { show_xbc_error(data, msg, pos); free(data); free(buf); return ret; } printf("Apply %s to %s\n", xbc_path, path); printf("\tNumber of nodes: %d\n", ret); printf("\tSize: %u bytes\n", (unsigned int)size); printf("\tChecksum: %d\n", (unsigned int)csum); /* TODO: Check the options by schema */ xbc_destroy_all(); free(buf); /* Remove old boot config if exists */ ret = delete_xbc(path); if (ret < 0) { pr_err("Failed to delete previous boot config: %d\n", ret); free(data); return ret; } /* Apply new one */ fd = open(path, O_RDWR | O_APPEND); if (fd < 0) { ret = -errno; pr_err("Failed to open %s: %d\n", path, ret); free(data); return ret; } /* TODO: Ensure the @path is initramfs/initrd image */ if (fstat(fd, &stat) < 0) { ret = -errno; pr_err("Failed to get the size of %s\n", path); goto out; } /* To align up the total size to BOOTCONFIG_ALIGN, get padding size */ total_size = stat.st_size + size + sizeof(u32) * 2 + BOOTCONFIG_MAGIC_LEN; pad = ((total_size + BOOTCONFIG_ALIGN - 1) & (~BOOTCONFIG_ALIGN_MASK)) - total_size; size += pad; /* Add a footer */ p = data + size; *(u32 *)p = htole32(size); p += sizeof(u32); *(u32 *)p = htole32(csum); p += sizeof(u32); memcpy(p, BOOTCONFIG_MAGIC, BOOTCONFIG_MAGIC_LEN); p += BOOTCONFIG_MAGIC_LEN; total_size = p - data; ret = write(fd, data, total_size); if (ret < total_size) { if (ret < 0) ret = -errno; pr_err("Failed to apply a boot config: %d\n", ret); if (ret >= 0) goto out_rollback; } else ret = 0; out: close(fd); free(data); return ret; out_rollback: /* Map the partial write to -ENOSPC */ if (ret >= 0) ret = -ENOSPC; if (ftruncate(fd, stat.st_size) < 0) { ret = -errno; pr_err("Failed to rollback the write error: %d\n", ret); pr_err("The initrd %s may be corrupted. Recommend to rebuild.\n", path); } goto out; } static int usage(void) { printf("Usage: bootconfig [OPTIONS] <INITRD>\n" "Or bootconfig <CONFIG>\n" " Apply, delete or show boot config to initrd.\n" " Options:\n" " -a <config>: Apply boot config to initrd\n" " -d : Delete boot config file from initrd\n" " -l : list boot config in initrd or file\n\n" " If no option is given, show the bootconfig in the given file.\n"); return -1; } int main(int argc, char **argv) { char *path = NULL; char *apply = NULL; bool delete = false, list = false; int opt; while ((opt = getopt(argc, argv, "hda:l")) != -1) { switch (opt) { case 'd': delete = true; break; case 'a': apply = optarg; break; case 'l': list = true; break; case 'h': default: return usage(); } } if ((apply && delete) || (delete && list) || (apply && list)) { pr_err("Error: You can give one of -a, -d or -l at once.\n"); return usage(); } if (optind >= argc) { pr_err("Error: No initrd is specified.\n"); return usage(); } path = argv[optind]; if (apply) return apply_xbc(path, apply); else if (delete) return delete_xbc(path); return show_xbc(path, list); }
C
#include "string_util.h" #include <stdlib.h> #include <string.h> /** * * @param buf * @param buf_len * @param term * @param term_len * @return 0 if buf ends with term, 1 otherwise */ int ends_with(char* buf, int buf_len, char* term, int term_len) { if (buf_len < term_len) { return 0; } int i; int ti = term_len-1; for (i = buf_len-1; i >= 0 && ti >= 0; i--, ti--) { if (buf[i] != term[ti]) { return 0; } } return 1; } /** * * @param str * @param str_len * @param pre * @param pre_len * @return 0 if str ends with pre, 1 otherwise */ int starts_with(char* str, int str_len, char* pre, int pre_len) { if (str_len < pre_len) { return 0; } return strncmp(pre, str, pre_len) == 0; } /** * Splits the string pointed to by str by the first instance of delim. * Returns the first split and updates str to point to the second split * @param str * @param delim * @return */ char* strp(char** str, char* delim) { if (*str == NULL) { return NULL; } char* tmp = strstr(*str, delim); if (tmp == NULL) { char* ret = *str; *str = NULL; return ret; } tmp[0] = '\0'; tmp += strlen(delim); char* ret = *str; *str = tmp; return ret; }
C
#include <stdlib.h> #include <stdio.h> #include "server_lib.h" int portNumber = 8080; char buffer[BUFSIZ]; int keyBuffer[BUFSIZ]; int msgBuffer[BUFSIZ]; int resultBuffer[BUFSIZ]; const char *usage = "Usage: otd_enc_d [port #]\n"; void handleClientEncryption(int clientFd) { int encryptionMode = 1; /* Encryption Mode set */ handleClient(clientFd, encryptionMode, buffer, resultBuffer, keyBuffer, msgBuffer); } int main(int argc, char *argv[]) { /* --- Read port from arguments or print usage -- */ if (argc < 2 || atoi(argv[1]) == 0) { printf("%s", usage); return 1; } else { portNumber = atoi(argv[1]); } return startServer("otp_enc_d", portNumber, handleClientEncryption); }
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* ft_split.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: tlavelle <[email protected]> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2020/05/13 18:20:11 by tlavelle #+# #+# */ /* Updated: 2020/05/28 16:54:00 by tlavelle ### ########.fr */ /* */ /* ************************************************************************** */ #include "libft.h" int wordsnb(char const *s, char c) { int number; if (!s) return (0); number = 0; while (*s != 0) { while (*s == c) s++; if (*s != 0) { number++; while (*s != c && *s != 0) s++; } } return (number); } char **ft_free(char **pointer, int index) { while (index >= 0) { free(pointer[index]); index--; } free(pointer); return (NULL); } int ft_length(const char *s, char c) { int length; length = 0; if (*s == '\0') return (0); while (*s != '\0' && *s != c) { length++; s++; } return (length); } char **ft_split(char const *s, char c) { char **pointer; char *str; int index; int length; int numberofw; if (!(numberofw = wordsnb(s, c)) && !s) return (NULL); index = -1; if (!(pointer = (char**)malloc(sizeof(char*) * (numberofw + 1)))) return (NULL); while (++index < numberofw) { while (*s == c) s++; length = ft_length(s, c); if (!(pointer[index] = (char*)malloc(sizeof(char) * (length + 1)))) return (ft_free(pointer, index)); str = pointer[index]; while (length--) *str++ = *s++; *str = '\0'; } pointer[index] = NULL; return (pointer); }
C
#include <stdlib.h> #include <stdio.h> /* 归并排序 分治的思想 */ void Merge(int sourceArr[],int tempArr[],int startIndex,int midIndex,int endIndex) { int i = startIndex,j=midIndex+1,k = startIndex; while(i!=midIndex+1 && j!=endIndex+1) { if(sourceArr[i]>sourceArr[j]) tempArr[k++] = sourceArr[i++]; else tempArr[k++] = sourceArr[j++]; } while(i!=midIndex+1) tempArr[k++] = sourceArr[i++]; while(j!=endIndex+1) tempArr[k++] = sourceArr[j++]; for(i=startIndex;i<=endIndex;i++) sourceArr[i] = tempArr[i]; } //内部使用递归 void MergeSort(int sourceArr[],int tempArr[],int startIndex,int endIndex) { int midIndex; if(startIndex<endIndex) { midIndex=(startIndex+endIndex)/2; MergeSort(sourceArr,tempArr,startIndex,midIndex); MergeSort(sourceArr,tempArr,midIndex+1,endIndex); Merge(sourceArr,tempArr,startIndex,midIndex,endIndex); } } int main(int argc,char * argv[]) { int a[8]={50,10,20,30,70,40,80,60}; int i,b[8]; MergeSort(a,b,0,7); for(i=0;i<8;i++) printf("%d ",a[i]); printf("\n"); return 0; }
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 int /*<<< orphan*/ uint8_t ; typedef int /*<<< orphan*/ lua_State ; typedef int /*<<< orphan*/ SHA1_CTX ; /* Variables and functions */ int /*<<< orphan*/ SHA1Final (int /*<<< orphan*/ *,int /*<<< orphan*/ *) ; int /*<<< orphan*/ SHA1Init (int /*<<< orphan*/ *) ; int /*<<< orphan*/ SHA1Update (int /*<<< orphan*/ *,char const*,int) ; char* luaL_checklstring (int /*<<< orphan*/ *,int,int*) ; int /*<<< orphan*/ lua_pushlstring (int /*<<< orphan*/ *,int /*<<< orphan*/ *,int) ; __attribute__((used)) static int crypto_sha1( lua_State* L ) { SHA1_CTX ctx; uint8_t digest[20]; // Read the string from lua (with length) int len; const char* msg = luaL_checklstring(L, 1, &len); // Use the SHA* functions in the rom SHA1Init(&ctx); SHA1Update(&ctx, msg, len); SHA1Final(digest, &ctx); // Push the result as a lua string lua_pushlstring(L, digest, 20); return 1; }
C
#include<stdio.h> #include<fcntl.h> #include<unistd.h> #include<dirent.h> int main() { int file; DIR* dp; struct dirent* dir; dp = opendir("."); if(dp) { while(dir = readdir(dp)) { if((file = open(dir->d_name, O_RDONLY)) < 0) {fprintf(stderr, "\nError opening file."); exit(-1);} if(!(lseek(file, 0, SEEK_END))) { printf("\nDeleting %s.", dir->d_name); unlink(dir->d_name); } } } }
C
#include <signal.h> //Signal 사용 헤더파일 #include <unistd.h> #include <stdio.h> #include <string.h> #include <errno.h> #include <stdlib.h> //exit() 사용 헤더파일 #include <wiringPi.h> #define PUMP 21 // BCM_GPIO 5 void sig_handler(int signo); // 마지막 종료 함수 int main (void) { signal(SIGINT, (void *)sig_handler); //시그널 핸들러 함수 if (wiringPiSetup () == -1) { fprintf(stdout, "Unable to start wiringPi: %s\n", strerror(errno)); return 1 ; } pinMode (PUMP, OUTPUT) ; for (;;) { printf("here - pump on\n"); digitalWrite (PUMP, 1) ; // On delay (100) ; // ms digitalWrite (PUMP, 0) ; // Off delay (2000) ; } return 0 ; } void sig_handler(int signo) { printf("process stop\n"); digitalWrite (PUMP, 0) ; // Off exit(0); }
C
// Fazer um programa em C leia o valor do empréstimo (double) e calcule o valor da divida após 6 meses, // com uma taxa de juros de 5% ao mês. #include <stdio.h> #include <math.h> int main() { double empr, juros; scanf("%lf", &empr); if (empr < 0) { printf("O VALOR DO EMPRESTIMO NAO PODE SER NEGATIVO\n"); } else { juros=pow(1.05, 6); empr=empr*juros; printf("%.2lf", empr); } return 0; }
C
/* * Author: Piotr Dobrowolski * [email protected] * */ #include <stdio.h> #include "printer.h" #include "board.h" void print_board(struct Board* board) { int i, j; for (i = 0; i < board->height; ++i) { for (j = 0; j < board->width; ++j) { int value = ((int)board->cells[i][j]) == 0 ? ' ' : 'X'; printf("%c", value); } printf("\n"); } }
C
#include two(x) (1 << (x)) int bitrev(n,B) int n, B; { int m, r; for (r=0,m=B-1;m>=0;m--) if ((n >> m) == 1) { r += two(B-1-m); n -= two(m); } return(r); }
C
/* ============================================================================ Name : hello.c Author : Luciano Glielmi Version : 01 Copyright : Your copyright notice Description : Hello World in C, Ansi-style ============================================================================ */ #include <stdio.h> int main(void){ printf("Hello, World!\n"); }
C
#include <caml/mlvalues.h> #include <stdio.h> #include <stdlib.h> int MAX = 1000000; CAMLprim value caml_sieve_last_prime() { int *numbers = (int *)calloc(MAX, sizeof(int)); numbers[0] = 1; numbers[1] = 1; int number, latest_prime; for (number = 2; number <= MAX; number++) { if (!numbers[number]) { latest_prime = number; int next = 2 * number; while (next <= MAX) { numbers[next] = 1; next += number; } } } free(numbers); return Val_int(latest_prime); }
C
#include <stdio.h> #include <stdlib.h> #include <math.h> #include <ctype.h> #pragma warning (disable: 4996) void main() { char entry,productentry; printf("enter your lowercase character \n"); scanf("%c", &entry); printf("your upper case of %c is %c\n", entry, toupper(entry)); system("pause"); }
C
#include <stdio.h> #include "dog.h" #include <stdlib.h> int _strlen(char *s); char *_strdup(char *str); /** * new_dog - a function that creates a new dog. * @name: char pointer to the dog's name * @age: float for dog's age * @owner: char for owner's name * * Return: 0 (success), NULL (failure) */ dog_t *new_dog(char *name, float age, char *owner) { dog_t *puppy; char *name_stored, *owner_stored; /* Allocate memory for the new struct named puppy */ puppy = malloc(sizeof(dog_t)); if (!puppy) return (NULL); /* Store copied string into the variable name_stored */ name_stored = _strdup(name); if (!name_stored && name) { free(puppy); return (NULL); } /* Store copied string for owner into the variable owner_stored */ owner_stored = _strdup(owner); if (!owner_stored && owner) { free(name_stored); free(puppy); return (NULL); } /* Assign the new string and values to the struct named puppy */ puppy->name = name_stored; puppy->age = age; puppy->owner = owner_stored; /* Return the puppy values */ return (puppy); } /** * _strlen - returns the length of a string. * @s: a variable declared as a character. * * Description: uses a function similar to strlen. * Return: Always 0. */ int _strlen(char *s) { int length = 0; while (s[length] != '\0') { length++; } return (length); } /** * _strdup - returns a pointer to a new string whichi is a duplicate of str * @str: a char * * Return: NULL if str is NULL or insufficient mem. Success returns pointer */ char *_strdup(char *str) { /* Declared duplicate and index of the array */ char *dupe; int i = 0; if (str == NULL) { return (NULL); } /* Allocating memory to the pointer for the size of char array */ dupe = malloc(_strlen(str) * sizeof(char) + 1); /* Check to see if memory has been successfully allocated */ if (dupe == NULL) { return (NULL); } /* Starting index at zero, as long as index is less than strlen, increment i */ for (i = 0; i < _strlen(str); i++) { dupe[i] = str[i]; } dupe[i] = '\0'; return (dupe); }
C
/** * @author f4prime * @email [email protected] * @aim a plain model for leetcode */ #include<stdio.h> #include<stdlib.h> #include<string.h> void print_int_star(int *list, int len) { for(int i=0;i<len;i++) printf("%d ",list[i]); putchar('\n'); } void print_int_2star(int **matrix,int row,int col) { for(int i=0;i<row;i++) print_int_star(matrix[i],col); } #define max(a,b) (((a)>(b))?(a):(b)) //Definition for singly-linked list. struct ListNode { int val; struct ListNode *next; }; bool hasCycle(struct ListNode *head) { if(head==NULL) return false; struct ListNode *p=head->next, *q=head; while(p!=NULL&&p!=q) { p=p->next; if(p==NULL) return false; if(p==q) return true; p=p->next; q=q->next; } return p==q; } int main() { return 0; }
C
#include <stdio.h> #include "error.h" #include "hash.h" #include "value.h" #include "gc.h" #include "vm.h" static void tn_list_map (struct tn_vm *vm, int argn) { int i, anynil = 0, pushed = 0; uint8_t gc_on = vm->gc->on; struct tn_value *fn = vm->stack[vm->sp - 1], *ret = &nil, **tail = &ret; struct tn_value **lists = &vm->stack[vm->sp - argn]; struct tn_scope *sc; if (fn->type != VAL_CLSR && fn->type != VAL_CFUN) { tn_error ("non-function function argument passed to list:map\n"); tn_vm_push (vm, &nil); return; } for (i = 0; i < argn - 1; i++) { if (lists[i]->type != VAL_PAIR) { tn_error ("non-list passed to list:map\n"); tn_vm_push (vm, &nil); return; } } vm->gc->on = 0; // disable the GC for this since it won't find a lot of the values we work on while (1) { // push one value from each list passed, then increment the head of that list for (i = argn - 2; i >= 0; i--) { if (lists[i] != &nil) { pushed++; tn_vm_push (vm, lists[i]->data.pair.a); lists[i] = lists[i]->data.pair.b; } else { anynil = 1; vm->sp -= pushed; break; } } if (anynil) break; if (fn->type == VAL_CLSR) { sc = vm->sc; tn_vm_exec (vm, fn->data.cl->ch, fn, NULL, argn - 1); vm->sc = sc; } else if (fn->type == VAL_CFUN) fn->data.cfun (vm, argn - 1); pushed = 0; *tail = tn_pair (vm, tn_vm_pop (vm), &nil); tail = &(*tail)->data.pair.b; } vm->sp -= argn; tn_vm_push (vm, ret); vm->gc->on = gc_on; } static void tn_list_foldl (struct tn_vm *vm, int argn) { struct tn_value *fn, *lst, *init; struct tn_scope *sc; if (argn != 3 || tn_value_get_args (vm, "aaa", &fn, &lst, &init) || (fn->type != VAL_CLSR && fn->type != VAL_CFUN) || (lst != &nil && lst->type != VAL_PAIR)) { tn_error ("invalid arguments passed to list:foldl\n"); tn_vm_push (vm, &nil); return; } tn_vm_push (vm, init); // call fn on each node in the list, along with init // the return value will be used as init for the next iteration while (lst != &nil) { tn_vm_push (vm, lst->data.pair.a); if (fn->type == VAL_CLSR) { sc = vm->sc; tn_vm_exec (vm, fn->data.cl->ch, fn, NULL, argn - 1); vm->sc = sc; } else if (fn->type == VAL_CFUN) fn->data.cfun (vm, 2); lst = lst->data.pair.b; } } static void tn_list_foldr (struct tn_vm *vm, int argn) { struct tn_value *fn, *lst, *init; struct tn_scope *sc; if (argn != 3 || tn_value_get_args (vm, "aaa", &fn, &lst, &init) || (fn->type != VAL_CLSR && fn->type != VAL_CFUN) || (lst != &nil && lst->type != VAL_PAIR)) { tn_error ("invalid arguments passed to list:foldr\n"); tn_vm_push (vm, &nil); return; } tn_vm_push (vm, init); if (lst != &nil) { // call foldr on the tail of lst tn_vm_push (vm, lst->data.pair.b); tn_vm_push (vm, fn); tn_list_foldr (vm, argn); // call fn on the head of lst and the return value of foldr tn_vm_push (vm, lst->data.pair.a); if (fn->type == VAL_CLSR) { sc = vm->sc; tn_vm_exec (vm, fn->data.cl->ch, fn, NULL, argn - 1); vm->sc = sc; } else if (fn->type == VAL_CFUN) fn->data.cfun (vm, 2); } } static void tn_list_filter (struct tn_vm *vm, int argn) { uint8_t gc_on = vm->gc->on; struct tn_value *fn, *lst; struct tn_value *ret = &nil, **tail = &ret; struct tn_scope *sc; if (argn != 2 || tn_value_get_args (vm, "aa", &fn, &lst) || (fn->type != VAL_CLSR && fn->type != VAL_CFUN) || (lst != &nil && lst->type != VAL_PAIR)) { tn_error ("invalid arguments passed to list:filter\n"); tn_vm_push (vm, &nil); return; } vm->gc->on = 0; while (lst != &nil) { tn_vm_push (vm, lst->data.pair.a); if (fn->type == VAL_CLSR) { sc = vm->sc; tn_vm_exec (vm, fn->data.cl->ch, fn, NULL, 1); vm->sc = sc; } else if (fn->type == VAL_CFUN) fn->data.cfun (vm, argn - 1); if (tn_value_true (tn_vm_pop (vm))) { *tail = tn_pair (vm, lst->data.pair.a, &nil); tail = &(*tail)->data.pair.b; } lst = lst->data.pair.b; } tn_vm_push (vm, ret); vm->gc->on = gc_on; } static void tn_list_length (struct tn_vm *vm, int argn) { int len = 0; struct tn_value *lst; if (argn != 1 || tn_value_get_args (vm, "l", &lst)) { tn_error ("invalid argument passed to list:length\n"); tn_vm_push (vm, &nil); return; } while (lst != &nil) { len++; lst = lst->data.pair.b; } tn_vm_push (vm, tn_int (vm, len)); } static void tn_list_ref (struct tn_vm *vm, int argn) { int i, n; struct tn_value *lst; if (argn != 2 || tn_value_get_args (vm, "li", &lst, &n)) { tn_error ("invalid argument passed to list:ref\n"); tn_vm_push (vm, &nil); return; } for (i = 0; i < n && lst != &nil; i++) lst = lst->data.pair.b; tn_vm_push (vm, lst != &nil ? lst->data.pair.a : &nil); } // list:join ([1, 2], [3, 4]) == [1 2 3 4] static void tn_list_join (struct tn_vm *vm, int argn) { struct tn_value *ret, *last; struct tn_value *a, *b; if (argn != 2 || tn_value_get_args (vm, "ll", &a, &b)) { tn_error ("non-list passed to list:join\n"); tn_vm_push (vm, &nil); return; } ret = tn_value_lcopy (vm, a, &last); last->data.pair.b = b; tn_vm_push (vm, ret); } static void tn_list_reverse (struct tn_vm *vm, int argn) { struct tn_value *lst, *tail = &nil; if (argn != 1 || tn_value_get_args (vm, "l", &lst)) { tn_error ("non-list passed to list:reverse\n"); tn_vm_push (vm, &nil); return; } while (lst != &nil) { tail = tn_gc_preserve (tn_pair (vm, lst->data.pair.a, tail)); lst = lst->data.pair.b; } tn_gc_release_list (tail); tn_vm_push (vm, tail); } struct tn_hash *tn_list_module (struct tn_vm *vm) { struct tn_hash *ret = tn_hash_new (8); tn_hash_insert (ret, "map", tn_gc_preserve (tn_cfun (vm, tn_list_map))); tn_hash_insert (ret, "foldl", tn_gc_preserve (tn_cfun (vm, tn_list_foldl))); tn_hash_insert (ret, "foldr", tn_gc_preserve (tn_cfun (vm, tn_list_foldr))); tn_hash_insert (ret, "filter", tn_gc_preserve (tn_cfun (vm, tn_list_filter))); tn_hash_insert (ret, "length", tn_gc_preserve (tn_cfun (vm, tn_list_length))); tn_hash_insert (ret, "ref", tn_gc_preserve (tn_cfun (vm, tn_list_ref))); tn_hash_insert (ret, "join", tn_gc_preserve (tn_cfun (vm, tn_list_join))); tn_hash_insert (ret, "reverse", tn_gc_preserve (tn_cfun (vm, tn_list_reverse))); return ret; }
C
/*******************冒泡排序法******************************** * 冒泡排序法的排序规则存在升序和降序两种,本例采用升序方法 * * 本例中,添加了标识符flag,用于判断每轮是否已经将数据排列完成* **************************************************************/ #include <stdio.h> void bubble_sort(int arr[],int n) { int i,j,flag,temp; for(i = 0; i < n-1; i++) { flag = 1; for(j = 0; j < n-i-1;j++) { if(arr[j] > arr[j+1]) { temp = arr[j]; arr[j] = arr[j+1]; arr[j+1] = temp; flag = 0; } } if(flag == 1) break; } printf("\n本次排序比较操作进行了%d轮" , n+1); return ; } int main() { int a[] = {12,56,36,89,26,66}; int i; printf("排序前顺序为:\n"); for(i = 0;i < 6; i++) { printf("%d\t",a[i]); } printf("\n"); bubble_sort(a,6); printf("排序后顺序为:\n"); for(i = 0; i < 6 ;i++) { printf("%d\t",a[i]); } return 0; }
C
#define _GNU_SOUCES #include "../lib/allhead.h" #define MAX_ALLOCS 100000 int main(int argc, char *argv[]) { char *ptr[MAX_ALLOCS]; int free_step, free_min, free_max, block_size, num_allocs, i; printf("\n"); if (argc < 3 || strcmp(argv[1], "--help") == 0) usage_err("%s num-allocs block-size [step [min [max]]]\n", argv[0]); num_allocs = get_int(argv[1], GN_GT_0, "num-allocs"); if (num_allocs > MAX_ALLOCS) cmd_line_err("num-allocs > %d\n", MAX_ALLOCS); block_size = get_int(argv[2], GN_GT_0 | GN_ANY_BASE, "block-size"); free_step = (argc > 3) ? get_int(argv[3], GN_GT_0, "step") : 1; free_min = (argc > 4) ? get_int(argv[4], GN_GT_0, "min") : 1; free_max = (argc > 5) ? get_int(argv[5], GN_GT_0, "max") : num_allocs; if (free_max > num_allocs) cmd_line_err("free-max > num-allocs\n"); printf("Initial program break: %10p\n", sbrk(0)); printf("Allocating %d*%d bytes\n", num_allocs, block_size); for (i = 0; i < num_allocs; i++) { ptr[i] = malloc(block_size); if (ptr[i] == NULL) err_exit("malloc"); } printf("Program break is now: %10p\n", sbrk(0)); printf("Freeing blocks from %d to %d in steps of %d\n", free_min, free_max, free_step); for (i = free_min - 1; i < free_max; i += free_step) free(ptr[i]); printf("After free(), program break is %10p\n", sbrk(0)); return EXIT_SUCCESS; }
C
#include "stdio.h" #include <sys/types.h> #include <sys/wait.h> #include <sys/types.h> #include <unistd.h> #include <string.h> int main() { pid_t pid = fork(); if(pid==0) { printf("I say bye before diying \n"); char a[80]; sprintf(a, "%i", pid); execl("/bin/echo", "echo", "this is the child", a , NULL); printf("I wont execute\n"); } else { printf("I am the parent process\n"); printf("the %i\n", pid); wait(0); } }
C
/****************************************************************************** * File Name : fpprint.h * Date First Issued : 08/21/2015 * Board : f103 * Description : Format and print floating pt *******************************************************************************/ /* This is used for the F103 since the launchpad compiler was not working for floating pt printf (which works for the 'F4). */ /* Define to prevent recursive inclusion -------------------------------------*/ #ifndef __FPPRINT #define __FPPRINT #include <stdint.h> /* **************************************************************************************/ void fmtprint(int i, float f, char* p); /* @brief : Format floating pt and print (%8.3f) * @param : i = parameter list index * @param : f = floating pt number * @param : p = pointer to description to follow value * ************************************************************************************** */ void fpformat(char* p, double d); /* @brief : Format floating pt to ascii * @param : p = pointer to char buffer to receive ascii result * @param : d = input to be converted * ************************************************************************************** */ #endif
C
#include "knn.h" //find the most frequent class of the bunch int find_most_frequent(uint8_t* neighbours, int num_classes, int k){ int classes[num_classes]; int max = 0; int class; memset((void *)classes, 0, sizeof(int) * num_classes); for(int i =0; i < k; i++){ classes[neighbours[i]] +=1; } for(int i = 0; i < num_classes; i++){ if(classes[i] > max){ max = classes[i]; class = i; } } if(max > 0){ return class; } printf("Error searching for most frequent class'"); return -1; } uint8_t* find_k_nearest(int k, uint8_t* point, uint8_t** data, uint8_t* labels, int num_samples, int num_features){ uint8_t* neighbours = (uint8_t*) malloc(sizeof(uint8_t) * k); double min = DBL_MAX; int idx = 0; double old_min; //iterate through the dataset to find the first neighbour for(int i = 0; i < num_samples; i++){ double distance = euclidean(point, data[i], num_features); if(distance < min){ min = distance; idx = i; } } neighbours[0] = labels[idx]; old_min = min; min = DBL_MAX; //find all other neighbours up to k for( int i = 1; i < k; i++){ for(int j = 0; j < num_samples; j++){ double distance = euclidean(point, data[j], num_features); if(distance < min && distance > old_min){ min = distance; idx = j; } } neighbours[i] = labels[idx]; old_min = min; min = DBL_MAX; } return neighbours; } //calculate euclidean distance double euclidean(uint8_t* point_a, uint8_t* point_b, int size){ double val = 0; for(int i =0; i < size; i++){ val += pow((point_a[i] - point_b[i]), 2); } return sqrt(val); }
C
#include <stdio.h> #include <string.h> int FindSameNum(int* tmp, int sz) { if(tmp == NULL || sz == 0) { return -1; } int i = 0; for(; i < sz; ++i) { int cur = tmp[i]; while(tmp[i] != i) { if(tmp[i] == tmp[cur]) { return tmp[i]; } tmp[i] = tmp[cur]; tmp[cur] = cur; } } return -1; } int main() { int arr[] = {2,3,5,4,3,2,6,7}; int sz = sizeof(arr)/sizeof(arr[0]); int tmp[sz]; memmove(tmp, arr, sz);//利用memmove进行拷贝 int ret = FindSameNum(tmp, sz); printf("ret expected 2 or 3, ret actual %d\n",ret); return 0; }
C
/* * main.c * Copyright (C) 2018 hzshang <[email protected]> * * Distributed under terms of the MIT license. */ #include <stdio.h> #include <stdlib.h> #include <unistd.h> typedef unsigned int uint; typedef unsigned long long ll; int main(int argc, char *argv[]){ setbuf(stdin,0); setbuf(stdout,0); setbuf(stderr,0); printf("do you know heap chunk header?\n"); int r=open("/dev/urandom",0); uint num=0; uint add=0; ulong check; for(int i=0;i<0x10;i++){ ulong* ptr=malloc(num); printf("I called malloc(0x%x), tell me the magic number:",num); scanf("%ld",&check); if (check != ptr[-1]){ printf("emm?\n"); exit(0); } read(r,&add,sizeof(uint)); num+=add%0x233; } printf("Welcome the world of heap overflow!\n"); system("/bin/sh"); return 0; }
C
#include "qtree.h" void print_greetings(); int valid_answer(char *answer); void print_friend_list(Node *friends, char *name); int main (int argc, char **argv) { int stop; QNode *root = NULL; char answer[MAX_LINE]; char name[MAX_LINE]; Node * friends = NULL; Node * interests = NULL; if (argc < 2) { printf ("To run the program ./categorizer <name of input file>\n"); return 1; } interests = get_list_from_file ( argv[1]); if (interests == NULL) return 1; root = add_next_level (root, interests); free_list (interests); //main application loop stop = 0; while (!stop) { print_greetings(); fprintf(stdout, "Please enter your name. Type 'q' to quit\n"); fgets(name, MAX_LINE, stdin); name[strcspn(name, "\r\n")] = '\0'; if(!valid_name(name)){ if (strlen(name) > 128){ fprintf(stderr,"Invalid name, name too long, only the first 128 characters will be used\n\n"); name[128] = '\0'; } else if(strlen(name)< 8){ fprintf(stderr,"Invalid name, name too short\n\n"); continue; } else{ fprintf(stderr,"Invalid name, name should only contain alphanumeric values\n\n"); continue; } } friends = find_user(root, name); if(friends == NULL) { QNode *latest = root; while(latest !=NULL && !stop) { while(1) { fprintf(stdout,"Do you like %s? (y/n)\n", latest->question); fgets(answer, MAX_LINE, stdin); answer[strcspn(answer, "\r\n")] = '\0'; if(valid_answer(answer)) break; fprintf(stderr,"Invalid answer. The answer should be in format {yXX,nXX,qXX,YXX,NXX,QXX}\n"); } stop = (answer[0] == 'q' || answer[0] == 'Q'); if(!stop){ latest = add_user(latest, name, answer[0] == 'y' || answer[0] == 'Y'); } } if(!stop) friends = find_user(root,name); } if(!stop) { print_friend_list(friends, name); fprintf(stdout, "\n"); } } print_qtree (root, 0); free_qtree(root); return 0; } void print_greetings () { printf ("----------------------------------------------\n"); printf ("Friend recommender system. Find people who are just like you!\n"); printf ("CSC209 fall 2016 team. All rights reserved\n"); printf ("----------------------------------------------\n"); } int valid_answer(char *answer) { if(strlen(answer) > 3) return 0; return (answer[0] == 'q' || answer[0] == 'y' || answer[0] == 'n' || answer[0] == 'Q' || answer[0] == 'Y' || answer[0] == 'N'); } void print_friend_list(Node *friends,char *name){ int len = get_list_length(friends) - 1; if(len == 0) { fprintf(stdout, "Sorry,no users with similar interests joined yet\n"); } else { printf("friend recommendations for user %s:\n", name); while (friends != NULL){ if(strcmp(friends->str, name) != 0) { fprintf(stdout,"%s\n", friends->str); } friends = friends->next; } fprintf(stdout,"You have total %d potential friend(s) !!!\n", len); } }
C
#include <math.h> int findFirstElement(double eps) { double a = 1; int n = 0; for (int i = 0; fabs(a) >= eps; ++i) { a = pow(-1, (double)i) * (1 / (((double)i + 1) * ((double)i + 2) * ((double)i + 3))); n = i; if (fabs(a) < eps) break; printf("%.5lf %.d\n", a, n); } return n; }
C
/* * Radix2FFT.c * * Created on: May 16, 2019 * Author: Gusts Kaksis */ #include "Radix2FFT.h" #include <math.h> #define M_2PI 6.283185307179586476925286766559 // 2 * PI #define M_LOG10_2_INV 3.3219280948873623478703194294948 // 1 / Log10(2) void CMult(complex_float_t* dest, complex_float_t* c1, complex_float_t* c2) { dest->re = (c1->re * c2->re) - (c1->im * c2->im); dest->im = (c1->re * c2->im) + (c1->im * c2->re); } void CAdd(complex_float_t* dest, complex_float_t* c1, complex_float_t* c2) { dest->re = c1->re + c2->re; dest->im = c1->im + c2->im; } void CSub(complex_float_t* dest, complex_float_t* c1, complex_float_t* c2) { dest->re = c1->re - c2->re; dest->im = c1->im - c2->im; } void Radix2iFFT(complex_float_t *in, complex_float_t *out, int N) { double iN = 1 / (double)N; complex_float_t* pIn = in; for (int i = 0; i < N; i++, pIn++) { pIn->im *= -1; } Radix2FFT(in, out, N); complex_float_t* pOut = out; for (int i = 0; i < N; i++, pOut++){ pOut->re *= iN; pOut->im *= -1; } } void Radix2FFT(complex_float_t *in, complex_float_t *out, int N) { int stages = (int)ceil(log10((double)N) * M_LOG10_2_INV); // Decimation - sort in samples to out samles complex_float_t* out_start = out; for (int i = 0; i < N; i++, out++) { complex_float_t* x = in + i; unsigned int i_out = 0; unsigned int i_in = i; for (int j = 0; j < stages; j++) { if (i_in & 0x01) { i_out += (1 << (stages - 1 - j)); } i_in >>= 1; if (!i_in) { break; } } out = out_start + i_out; out->re = x->re; out->im = x->im; } // FFT Computation by butterfly calculation complex_float_t WN; complex_float_t TEMP; for (int stage = 1; stage <= stages; stage++) { int butterfly_separation = (int)(pow(2, stage)); int butterfly_width = butterfly_separation / 2; double P = M_2PI / butterfly_separation; for (int j = 0; j < butterfly_width; j++) { if (j != 0) { WN.re = cos(P * j); WN.im = -sin(P * j); } for (int k = j; k < N; k += butterfly_separation) { complex_float_t* pHi = out_start + k; complex_float_t* pLo = pHi + butterfly_width; if (j != 0) { CMult(&TEMP, pLo, &WN); } else { TEMP.re = pLo->re; TEMP.im = pLo->im; } CSub(pLo, pHi, &TEMP); CAdd(pHi, pHi, &TEMP); } } } }
C
/* Design a program that receives two numbers using argv argument and print the following arithmetical operations. add, subtraction, multiplication, dicision */ #include <stdio.h> #include <stdlib.h> int main(int argc, char *argv[]) { int add, sub, mul; float div, one = atoi(argv[1]), two = atoi(argv[2]); add = one + two; sub = one - two; mul = one * two; div = one / two; printf("Add: %d \n", add); printf("Suntraction: %d \n", sub); printf("Multiplication: %d \n", mul); printf("Division: %.2f \n", div); return 0; }
C
#include <stdio.h> #include <string.h> int main(void){ char buff[5]; int pass = 0; printf("\nEntre com a senha: "); fgets(buff,5,stdin); if (strcmp(buff, "1234")) { printf ("\nSenha Errada \n"); } else { printf("\nSenha Correta \n"); pass = 1; } if (pass){ /* O usuário acertou a senha, poderá continuar*/ printf ("\nAcesso liberado \n"); } else { printf("\nAcesso negado \n"); } return 0; } /* a)Pense em uma solução para o problema do exercício 11 que utiliza fgets. Considere que o tamanho máximo de uma senha são 4 dígitos. b)Teste com os seguintes valores a.123 -> acesso negado b.12345 -> acesso liberado c.123456 -> acesso liberado Utilizando o fgets nessa implementação e usando um vetor de 5 posições, a função irá receber apenas os 4 caracteres (máximo que foi estabelecido) e ignorará o resto dos caracteres. Se a sequência dos 4 primeiros dígitos estiverem certos, a estrutura condicional decidirá que a senha está correta e mostrará a mensagem de acesso liberado. */
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 = 0; printf("there is a number between 1 and 100: "); do { printf("guess this number: "); scanf("%d", &a); count ++; if (a > number) { printf("too large \n"); } else if (a < number) { printf("too small \n"); } } while (a != number); printf("great, you guessed %d times to find the right number. \n", count); return 0; }
C
/*Menentukan Bilangan terbesar dari tiga buah bilangan yang diinput dari alat masukan x,y dan z. Dengan asumsi x,y dan z nilainya berbeda. */ #include <stdio.h> int main (){ int x,y,z; printf ("Masukkan nilai x: "); scanf ("%d", &x); printf ("Masukkan nilai y: "); scanf ("%d", &y); printf ("Masukkan nilai z :"); scanf ("%d", &z); if (x==y||x==z||y==z){ printf ("Terdapat inputan yang sama!"); }else { if(x>y){ if(x>z){ printf ("Nilai yang terbesar adalah %d", x); }else { printf ("Nilai yang terbesar adalah %d", z); } }else { if (y>z){ printf ("Nilai yang terbesar adalah %d", y); }else { printf ("Nilai yang terbesar adalah %d", z); } } } return 0; }
C
#include "color_sensor.h" uint16_t color[6] = {0, 0, 0, 0, 0, 0}; //uint16_t blackThreshold[6] = {4000, 3900, 4000, 3500, 3000, 2600}; uint32_t blackThresholdAddress[6] = {0, 1, 2, 3, 4, 5}; uint32_t whiteThresholdAddress[6] = {13, 7, 8, 9, 11, 12}; int blackThreshold[6] = {4000, 4000, 4000, 4000, 4000, 4000}; int whiteThreshold[6] = {700, 700, 700, 700, 700, 700}; void colorSensorInit() { adc1Init(); // for(i = 0; i < 6; i++) { // temp = eepromRead(blackThresholdAddress[i]); // if(temp >= 0) { // blackThreshold[i] = temp; // } // temp = eepromRead(whiteThresholdAddress[i]); // if(temp >= 0) { // whiteThreshold[i] = temp; // } // } // lcd_clear(); // sprintf(temp1, "%4d %4d %4d", blackThreshold[0], blackThreshold[1], blackThreshold[2]); // sprintf(temp2, "%4d %4d %4d", blackThreshold[3], blackThreshold[4], blackThreshold[5]); // sprintf(temp1, "%4d %4d %4d", whiteThreshold[0], whiteThreshold[1], whiteThreshold[2]); // sprintf(temp2, "%4d %4d %4d", whiteThreshold[3], whiteThreshold[4], whiteThreshold[5]); // lcd_putsf(0, 0, temp1); // lcd_putsf(0, 1, temp2); // delayMs(1000); } colorStatus checkColorSensor() { uint8_t i, black = 0, white = 0; for(i = 0; i < 6; i++) { color[i] = adc1Read(i); if(color[i] >= blackThreshold[i]) black++; else if(color[i] <= whiteThreshold[i]) white++; } if(black >= 5) return BLACK; else if(white >= 4) return WHITE; else if(white >= 2) return LINE; else return GRAY; } void tesAdc(void){ uint8_t i; normal(300); while(!button3Pressed()){ lcd_clear(); char temp1[16], temp2[16]; for(i = 0; i < 6; i++) { color[i] = adc1Read(i); } sprintf(temp1, "%4d %4d %4d", color[0], color[1], color[2]); sprintf(temp2, "%4d %4d %4d", color[3], color[4], color[5]); lcd_putsf(0, 0, temp1); lcd_putsf(0 ,1, temp2); delayMs(100); } while(button3Pressed()); } void tesColorSensor() { colorStatus color; normal(300); while(!button3Pressed()) { color = checkColorSensor(); if(color == BLACK) { lcd_putsf(0, 0, "BLACK"); } if(color == GRAY) { lcd_putsf(0, 0, "GRAY"); } if(color == WHITE) { lcd_putsf(0, 0, "WHITE"); } if(color == LINE) { lcd_putsf(0, 0, "LINE"); } delayMs(50); lcd_clear(); } while(button3Pressed()); } void timer5ISRCallBack(void){ uint8_t colorCorrect = 0, i; if(colorTarget == LINE) { for(i = 0; i < 6; i++) { colorStatus colorChecking = checkColorSensor(); if(colorChecking == LINE || colorChecking == WHITE){ colorCorrect++; } } } else if(colorTarget == NOTLINE){ for(i = 0; i < 6; i++) { colorStatus colorChecking = checkColorSensor(); if(colorChecking == GRAY || colorChecking == BLACK){ colorCorrect++; } } } else { for(i = 0; i < 6; i++) { if(checkColorSensor() == colorTarget){ colorCorrect++; } } } if(colorCorrect >= 3) { colorMatch = 1; timer5Stop(); } } void getBlackThreshold() { uint8_t i; char temp1[16], temp2[16]; uint16_t colorMax[6] = {0, 0, 0, 0, 0, 0}; normal(300); lcd_clear(); lcd_putsf(0, 0, "BLACK THRESHOLD"); lcd_putsf(0, 1, "Press OK!"); while(!button4Pressed()) { if(button3Pressed()) { while(button3Pressed()); delayMs(200); return; } } while(button4Pressed()); delayMs(200); while(1) { for(i = 0; i < 6; i++) { color[i] = adc1ReadMean(i); if(color[i] > colorMax[i]) { colorMax[i] = color[i]; } } sprintf(temp1, "%4d %4d %4d", colorMax[0], colorMax[1], colorMax[2]); sprintf(temp2, "%4d %4d %4d", colorMax[3], colorMax[4], colorMax[5]); lcd_clear(); lcd_putsf(0, 0, temp1); lcd_putsf(0, 1, temp2); if(button4Pressed()) { while(button4Pressed()); lcd_clear(); lcd_putsf(0, 0, "GRAY THRESHOLD"); lcd_putsf(0, 1, "Press OK!"); while(!button4Pressed()) { if(button3Pressed()) { while(button3Pressed()); delayMs(200); return; } } while(button4Pressed()); delayMs(200); while(1) { for(i = 0; i < 6; i++) { color[i] = adc1ReadMean(i); } sprintf(temp1, "%4d %4d %4d", color[0], color[1], color[2]); sprintf(temp2, "%4d %4d %4d", color[3], color[4], color[5]); lcd_clear(); lcd_putsf(0, 0, temp1); lcd_putsf(0, 1, temp2); if(button4Pressed()) { while(button4Pressed()); for(i = 0; i < 6; i++) { // eepromWrite(blackThresholdAddress[i], (colorMax[i] - ((colorMax[i] - color[i]) / 4))); blackThreshold[i] = (colorMax[i] - ((colorMax[i] - color[i]) / 6)); } delayMs(200); break; } if(button3Pressed()) { while(button3Pressed()); delayMs(200); break; } } delayMs(200); break; } if(button3Pressed()) { while(button3Pressed()); delayMs(200); break; } } } void getWhiteThreshold() { uint8_t i; char temp1[16], temp2[16]; uint16_t colorMin[6] = {4095, 4095, 4095, 4095, 4095, 4095}; normal(300); lcd_clear(); lcd_putsf(0, 0, "WHITE THRESHOLD"); lcd_putsf(0, 1, "Press OK!"); while(!button4Pressed()) { if(button3Pressed()) { while(button3Pressed()); delayMs(200); return; } } while(button4Pressed()); delayMs(200); while(1) { for(i = 0; i < 6; i++) { color[i] = adc1ReadMean(i); if(color[i] < colorMin[i]) { colorMin[i] = color[i]; } } sprintf(temp1, "%4d %4d %4d", colorMin[0], colorMin[1], colorMin[2]); sprintf(temp2, "%4d %4d %4d", colorMin[3], colorMin[4], colorMin[5]); lcd_clear(); lcd_putsf(0, 0, temp1); lcd_putsf(0, 1, temp2); if(button4Pressed()) { while(button4Pressed()); for(i = 0; i < 6; i++) { // eepromWrite(whiteThresholdAddress[i], colorMin[i] + 500); whiteThreshold[i] = colorMin[i] + 500; } delayMs(200); return; } if(button3Pressed()) { while(button3Pressed()); delayMs(200); return; } } } void checkThreshold() { char temp1[16], temp2[16]; lcd_clear(); lcd_putsf(0, 0, "BLACK THRESHOLD"); lcd_putsf(0, 1, "Press OK!"); while(!button4Pressed()) { if(button3Pressed()) { while(button3Pressed()); delayMs(200); return; } } while(button4Pressed()); delayMs(200); lcd_clear(); sprintf(temp1, "%4d %4d %4d", blackThreshold[0], blackThreshold[1], blackThreshold[2]); sprintf(temp2, "%4d %4d %4d", blackThreshold[3], blackThreshold[4], blackThreshold[5]); lcd_putsf(0, 0, temp1); lcd_putsf(0, 1, temp2); while(!button4Pressed()) { if(button3Pressed()) { while(button3Pressed()); delayMs(200); return; } } while(button4Pressed()); delayMs(200); lcd_clear(); lcd_putsf(0, 0, "WHITE THRESHOLD"); lcd_putsf(0, 1, "Press OK!"); while(!button4Pressed()) { if(button3Pressed()) { while(button3Pressed()); delayMs(200); return; } } while(button4Pressed()); delayMs(200); lcd_clear(); sprintf(temp1, "%4d %4d %4d", whiteThreshold[0], whiteThreshold[1], whiteThreshold[2]); sprintf(temp2, "%4d %4d %4d", whiteThreshold[3], whiteThreshold[4], whiteThreshold[5]); lcd_putsf(0, 0, temp1); lcd_putsf(0, 1, temp2); while(!button4Pressed()) { if(button3Pressed()) { while(button3Pressed()); delayMs(200); return; } } while(button4Pressed()); delayMs(200); } uint8_t checkColorWF(colorStatus color, double y, uint16_t time) { colorStatus colorChecking; uint8_t colorCorrect = 0; uint8_t i = 0; if(color == LINE) { for(i = 0; i < 6; i++) { colorChecking = checkColorSensor(); if(colorChecking == LINE || colorChecking == WHITE){ colorCorrect++; } // delayMs(50); // wf = 0; // return 1; } } else if(color == NOTLINE){ for(i = 0; i < 6; i++) { colorChecking = checkColorSensor(); if(colorChecking == GRAY || colorChecking == BLACK){ colorCorrect++; } } } else { for(i = 0; i < 6; i++) { if(checkColorSensor() == color){ colorCorrect++; } } } if(colorCorrect >= 4) { // delayMs(50); wf = 0; return 1; } else { uint8_t j; for(j = 0; j < 6; j++) { colorCorrect = 0; if(color == LINE) { delayMs(55); moveRobot(0, y, 0, time); for(i = 0; i < 6; i++) { colorChecking = checkColorSensor(); if(colorChecking == LINE || colorChecking == WHITE){ colorCorrect++; } } } else if(color == NOTLINE){ for(i = 0; i < 6; i++) { colorChecking = checkColorSensor(); if(colorChecking == GRAY || colorChecking == BLACK){ colorCorrect++; } } } else { for(i = 0; i < 6; i++) { if(checkColorSensor() == color){ colorCorrect++; } } } if(colorCorrect >= 4) { // delayMs(50); wf = 0; return 1; } } } colorMatch = 0; timer5Start(color); wf = 1; return 0; }
C
#include "nbody.h" #define EQ_TOL 1e-4 #define N_TIME_KEPLER 5000 int main () { int i, j, k, info, nkick = 2; double t[N_TIME_KEPLER], coords_base[12*N_TIME_KEPLER], coords_var[12*N_TIME_KEPLER], mstar = 1.0, mplanet[1] = {1.0e-5}, e[1] = {0.4}, a[1] = {150.0}, t0[1] = {10.0}, pomega[1] = {-0.5}, ix[1] = {0.5}, iy[1] = {1.6}, kicks[2] = {25.0, 100.0}, del_e[3] = {0.0, 0.0, 0.0}, del_a[3] = {0.0, 0.0, 0.0}, del_t0[3] = {0.0, 0.0, 0.0}, del_pomega[3] = {0.0, 0.0, 0.0}, del_ix[3] = {0.0, 0.0, 0.0}, del_iy[3] = {0.0, 0.0, 0.0}, delta; // Initialize the time array. for (k = 0; k < N_TIME_KEPLER; ++k) t[k] = k * 200.0 / N_TIME_KEPLER; // Solve the pure Kepler system. info = kepler_solve (N_TIME_KEPLER, t, mstar, 1, mplanet, a, t0, e, pomega, ix, iy, coords_base); if (info != 0) { fprintf(stderr, "Base Kepler solve failed in variational test.\n"); return 1; } info = variational_solve (N_TIME_KEPLER, t, mstar, 1, mplanet, a, t0, e, pomega, ix, iy, nkick, kicks, del_a, del_t0, del_e, del_pomega, del_ix, del_iy, coords_var); if (info != 0) { fprintf(stderr, "Variational Kepler solve failed.\n"); return 1; } // Check that all of the values are equal. for (k = 0; k < N_TIME_KEPLER; ++k) { for (i = 0; i < 12; ++i) { delta = coords_base[12*k+i] - coords_var[12*k+i]; delta = sqrt(delta * delta); if (delta > EQ_TOL) { fprintf(stderr, "Variational and base coordinates are not equal.\n"); fprintf(stderr, "%d %d %e %e %e\n", k, i, t[k], coords_base[12*k+i], coords_var[12*k+i]); return 1; } } } return 0; }
C
#include "memreg.h" #include "prelude.h" const uint MBLOCK_SIZE = 100; typedef struct MemBlock { uint len; // capacity is fixed, len is how many are filled void** block; // array of pointers to free struct MemBlock* next; // when block is full add a new record } MemBlock; void register_alloc (MemBlock** registry, void* ptr) { if (!(*registry) || ((*registry) && (*registry)->len == MBLOCK_SIZE)) { // block is full, allocate a new one MemBlock* newblock = malloc(sizeof(MemBlock)); newblock->next = *registry; newblock->len = 0; newblock->block = malloc(MBLOCK_SIZE * sizeof(void*)); *registry = newblock; } (*registry)->block[(*registry)->len++] = ptr; } void register_free (MemBlock** registry) { #if MEMREG_SHOW_STATS uint nbblocks = 0; uint nbcells = 0; #endif // MEMREG_SHOW_STATS while (*registry) { MemBlock* tmp = *registry; *registry = tmp->next; for (uint i = 0; i < tmp->len; i++) free(tmp->block[i]); #if MEMREG_SHOW_STATS nbblocks++; nbcells += tmp->len; #endif // MEMREG_SHOW_STATS free(tmp->block); free(tmp); } #if MEMREG_SHOW_STATS printf("-> %d memory blocks deallocated from %p\n", nbblocks, (void*)registry); printf(" total %d * %d + %d = %d cells\n", nbcells / MBLOCK_SIZE, MBLOCK_SIZE, nbcells % MBLOCK_SIZE, nbcells); #endif // MEMREG_SHOW_STATS }
C
#include <stdlib.h> #include "structs.h" /** * Allocate heap memory for storing a U-LP public key. * @param size_t n - security parameter * @param size_t l - message length * @return ulp_public_key* - pointer to the allocated heap memory */ ulp_public_key* ulp_alloc_public_key(size_t n, size_t l) { ulp_public_key* key = malloc(sizeof(ulp_public_key)); if(key == NULL) return NULL; key->n = n; key->l = l; key->A = malloc(n*n*sizeof(key->q)); key->P = malloc(l*n*sizeof(key->q)); if(key->A == NULL || key->P == NULL) { free(key->A); free(key->P); free(key); return NULL; } return key; } /** * Allocate heap memory for storing a U-LP private key. * @param size_t n - security parameter * @param size_t l - message length * @return ulp_private_key* - pointer to the allocated heap memory */ ulp_private_key* ulp_alloc_private_key(size_t n, size_t l) { ulp_private_key* key = malloc(sizeof(ulp_private_key)); if(key == NULL) return NULL; key->n = n; key->l = l; key->S = malloc(l*n*sizeof(key->q)); if(key->S == NULL) { free(key); return NULL; } return key; } /** * Allocate heap memory for storing a U-LP ciphertext. * @param size_t n - security parameter * @param size_t l - message length * @return ulp_ciphertext* - pointer to the allocated heap memory */ ulp_ciphertext* ulp_alloc_ciphertext(size_t n, size_t l) { ulp_ciphertext* ciphertext = malloc(sizeof(ulp_ciphertext)); if(ciphertext == NULL) return NULL; ciphertext->n = n; ciphertext->l = l; ciphertext->c1 = malloc(n*sizeof(uint64_t)); ciphertext->c2 = malloc(l*sizeof(uint64_t)); if(ciphertext->c1 == NULL || ciphertext->c2 == NULL) { free(ciphertext->c1); free(ciphertext->c2); free(ciphertext); return NULL; } return ciphertext; } /** * Deallocate heap memory for a U-LP public key. * @param ulp_public_key* pub_key - pointer to the memory to free */ void ulp_free_public_key(ulp_public_key* pub_key) { if(pub_key != NULL) { free(pub_key->A); free(pub_key->P); free(pub_key); } } /** * Deallocate heap memory for a U-LP private key. * @param ulp_private_key* priv_key - pointer to the memory to free */ void ulp_free_private_key(ulp_private_key* priv_key) { if(priv_key != NULL) { free(priv_key->S); free(priv_key); } } /** * Deallocate heap memory for a U-LP ciphertext. * @param ulp_ciphertext* ciphertext - pointer to the memory to free */ void ulp_free_ciphertext(ulp_ciphertext* ciphertext) { if(ciphertext != NULL) { free(ciphertext->c1); free(ciphertext->c2); free(ciphertext); } }
C
#include <stdio.h> /* 16. Construa um algoritmo que calcule a quantidade de dinheiro gasto por um fumante com cigarros durante n anos. Para isso, necessrio ler a quantidade de cigarros que o fumante fuma por dia, a quantidade de anos que ele fuma e o preo mdio de uma carteira de cigarros. (OBS: Cada carteira de cigarros contm 20 cigarros. Cada ano tm 365 dias.). */ int main() { int dias,anos; float preco, gasto; printf("Digite qtd de cigarros por dia: "); scanf("%i", &dias); printf("Quantidade de anos: "); scanf("%i", &anos); printf("Digite o preco da carteira: "); scanf("%f", &preco); gasto = ((float)(dias*anos*365)/20)*preco; printf("Gasto: %.2f\n", gasto); return 0; }
C
#include<stdio.h> #include<stdlib.h> int main() { int i,n,newn,flag=1; printf("enter the value of n "); scanf("%d",&n); for (newn=2;newn<=n/2;newn++) { flag=1; for (i=2;i<=newn/2;i++) { if (newn%i==0) { flag=0; break; } } if (flag==1) printf("%d",newn); } }
C
#include<stdio.h> #include<stdlib.h> main(int n,char **p) { FILE *f1,*f2,*f3; char *buf1=NULL,*buf2=NULL; int size; f1=fopen(p[1],"a"); if(f1==0) printf("error:can't open the file."); f2=fopen(p[2],"r"); if(f2==0) printf("error:can't open the file 2"); fseek(f2,0,2); size=ftell(f2)+1; rewind(f2); buf1=calloc(1,size); fread(buf1,size-1,1,f2); fwrite(buf1,size,1,f1); fclose(f2); free(buf1); f3=fopen(p[3],"r"); if(f3==0) printf("error:can't open the file 3."); fseek(f3,0,2); size=ftell(f3)+1; rewind(f3); buf2=calloc(1,size); fread(buf2,size-1,1,f3); fwrite(buf2,size,1,f1); fclose(f1); fclose(f3); }
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* ft_strsplit.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: agrodzin <[email protected]> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2018/02/28 10:23:42 by agrodzin #+# #+# */ /* Updated: 2018/03/22 15:22:24 by agrodzin ### ########.fr */ /* */ /* ************************************************************************** */ #include "../includes/libft.h" /* Takes a string and a delimiter and returns an array of fresh strings split by the delimiter */ static int get_word_count(char const *s, char c) { int num_words; int i; num_words = 0; i = 0; while (s[i++]) { if (s[i] == c) num_words++; } return (num_words); } static int largest_word(const char *s, char c) { int i; int j; int largest; j = 0; largest = 0; while (s[j++]) { if (s[j] == c) { if (i > largest) largest = i; i = 0; } i++; } return (largest); } static char **split_strings(int i, char **st_arr, const char *s, char c) { int let; int word; word = 0; let = 0; i = 0; while (s[i]) { if (s[i] == c) { st_arr[word][let] = '\0'; let = -1; word++; } else st_arr[word][let] = s[i]; i++; let++; } return (st_arr); } char **ft_strsplit(char const *s, char c) { char **st_arr; int i; int j; int words; int largest; i = 0; j = 0; if (s == NULL) return (NULL); words = get_word_count(s, c) + 1; largest = largest_word(s, c) + 1; if ((st_arr = (char **)ft_memalloc(sizeof(char*) * words)) == NULL) return (NULL); while (j < words) { if ((st_arr[j] = (char*)ft_memalloc(sizeof(char*) * largest))== NULL) return (NULL); j++; } st_arr[j] = NULL; st_arr = split_strings(i, st_arr, s, c); return (st_arr); }
C
/* TheHuxley - Problema do Igual ou diferente @mauricio */ #include <stdio.h> int main() { int n1,n2, n3; scanf("%d %d %d", &n1, &n2, &n3); if (n1 == n2 && n2 == n3) //1 (Se todos os números são iguais) printf("\n1"); else if (n1 != n2 && n2 != n3) //2 (Se todos os números são diferentes) printf("\n2"); else printf("\n3"); //3 (Se apenas dois números são iguais) return 0; }
C
#include <stdio.h> #include "config.h" int testFileToConfig() { char* s = NULL; size_t len1; int len = getline(&s, &len1, stdin); s[len - 1] = 0; printf("[%s]\n", s); config conf; printf("code = %d\n", fileToConfig(s, &conf)); printConfig(&conf); return(0); } int testParseString() { char* s = NULL; size_t len1; int len = getline(&s, &len1, stdin); s[len - 1] = 0; printf("[%s]\n", s); findKeyRes res = parseString(s); printf("stringN = %d\tkeyPos=%d\tkeyL=%d\teqPos=%d\tvalPos=%d\tvalL=%d\n", res.stringN, res.keyPos, res.keyL, res.eqPos, res.valPos, res.valL); if(res.keyPos != -1 && res.eqPos != -1 && res.valPos != -1) { char* s1 = getSubstr(s, res.keyPos, res.keyL); char* s2 = getSubstr(s, res.valPos, res.valL); printf("correct string: [%s]=[%s]\n", s1, s2); free(s1); free(s2); } return(0); } int testGetKey() { char fn[100]; char key[100]; scanf("%s", fn); scanf("%s", key); char* res = getKey(fn, key); if(res == NULL) printf("Not found\n"); else { printf("[%s]=[%s]\n", key, res); free(res); } return(0); } int testSetKey() { char fn[100]; char key[100]; char* v = malloc(100); scanf("%s", fn); scanf("%s", key); if(!scanf("%s", v)) v = ""; char* res = setKey(fn, key, v); if(res == NULL) printf("Not found %s\n", key); else { printf("[%s]=[%s]\n", key, res); free(res); } return(0); } int main() { // return(testFileToConfig()); // return(testParseString()); // return(testGetKey()); char s[100]; scanf("%s", s); if(!strcmp(s, "edit")) return(testSetKey()); else if(!strcmp(s, "view")) return(testGetKey()); }
C
#include "comunication.h" ///gcc -o main main.c -lcrypto int main(int argc, char **argv) { struct A a; struct B b; struct KM km; initA(&a); initB(&b); initKM(&km); printf("Alegeti Criptosistemul:\n[1] ECB\n[2] OFB\n"); unsigned int type; do{ printf(">"); scanf("%d", &type); }while(type != 1 && type != 2); setType(&a, &b, &km, 1); getMessage(&a, "message.txt"); printf("Criptotextul:\n%s\n", getCriptoTextA(&a)); decryptMessage(&a, &b); printf("Mesajul Primit:\n%s\n", getMessageB(&b)); return 0; }
C
/*=========================================================================== = = = MtkUtcToUtcJd = = = ============================================================================= Jet Propulsion Laboratory MISR MISR Toolkit Copyright 2006, California Institute of Technology. ALL RIGHTS RESERVED. U.S. Government Sponsorship acknowledged. ============================================================================*/ #include "MisrUtil.h" #include "MisrError.h" /* Convert calendar day to Julian day */ static int julday(int year, int month, int day) { long j1; /* Scratch Variable */ long j2; /* Scratch Variable */ long j3; /* Scratch Variable */ j1 = 1461L * (year + 4800L + (month - 14L) / 12L) / 4L; j2 = 367L * (month - 2L - (month - 14L) / 12L * 12L) / 12L; j3 = 3L * ((year + 4900L + (month - 14L) / 12L) / 100L) / 4L; return (int)(day - 32075L + j1 + j2 - j3); } /** \brief Convert UTC date to UTC Julian date * * \return MTK_SUCCESS if successful. * * \par Example: * In this example, we convert the UTC date 2006-08-06T15:04:00.630996Z to a UTC Julian date. * * \code * status = MtkUtcToUtcJd("2006-08-06T15:04:00.630996Z", jdUTC); * \endcode */ MTKt_status MtkUtcToUtcJd( char utc_datetime[MTKd_DATETIME_LEN], /**< [IN] UTC Date time */ double jdUTC[2] /**< [OUT] UTC Julian date */ ) { MTKt_status status_code; /* Return code of this function */ int scanCheck; /* checks the return value of sscanf call */ int year; /* year portion of date */ int month; /* month portion of date */ int day; /* day portion of date */ int hours; /* hours of the given date */ int minutes; /* minutes of the given date */ double seconds; scanCheck = sscanf(utc_datetime,"%4d-%2d-%2dT%2d:%2d:%lfZ", &year, &month, &day, &hours, &minutes, &seconds); if (scanCheck != 6) MTK_ERR_CODE_JUMP(MTK_BAD_ARGUMENT); if (month < 1 || month > 12) MTK_ERR_CODE_JUMP(MTK_BAD_ARGUMENT); if (hours > 23) MTK_ERR_CODE_JUMP(MTK_BAD_ARGUMENT); if (minutes > 59) MTK_ERR_CODE_JUMP(MTK_BAD_ARGUMENT); if (seconds > 60.99999999) { MTK_ERR_CODE_JUMP(MTK_BAD_ARGUMENT); } else if (seconds >= 60.0 && (minutes != 59 || hours != 23)) MTK_ERR_CODE_JUMP(MTK_BAD_ARGUMENT); if (seconds >= 60.0) seconds -= 1.0; jdUTC[1] = (hours * SECONDSperHOUR + minutes * SECONDSperMINUTE + seconds) / SECONDSperDAY; jdUTC[0] = julday(year, month, day) - 0.5; return MTK_SUCCESS; ERROR_HANDLE: return status_code; }
C
/* * timers.c * * Created on: May 6, 2016 * Author: shapa */ #include "timers.h" #include "memman.h" typedef struct timerNode { struct timerNode *next; uint32_t id; uint32_t timeout; _Bool isPeriodic; _Bool isActive; onTimerFire_t cb; void *cbData; uint32_t cnt; } timerNode_t, *timerNode_p; static timerNode_p s_timersListHead = NULL; static timerNode_p s_timersListTail = NULL; static uint32_t getNewHandle(void); static _Bool isTimerHandleUnique(uint32_t handle); static timerNode_p findTimerById(uint32_t handle); uint32_t Timer_newArmed(uint32_t tout, _Bool isPeriodic, onTimerFire_t cb, void *cbData) { uint32_t handle = INVALID_HANDLE; if (!cb || !tout) return INVALID_HANDLE; do { handle = getNewHandle(); } while (!isTimerHandleUnique(handle)); timerNode_p last = s_timersListTail; uint32_t primask = __get_PRIMASK(); __disable_irq(); if (!last && (last = MEMMAN_malloc(sizeof(timerNode_t)))) { last->id = handle; last->cnt = last->timeout = tout; last->isPeriodic = isPeriodic; last->isActive = true; last->cb = cb; last->cbData = cbData; last->next = NULL; s_timersListTail = s_timersListHead = last; } if (!primask) { __enable_irq(); } return handle; } void Timer_rearm(uint32_t id) { if (id == INVALID_HANDLE) return; uint32_t primask = __get_PRIMASK(); __disable_irq(); timerNode_p node = findTimerById(id); if (node) { node->isActive = true; node->cnt = node->timeout; } if (!primask) { __enable_irq(); } } void Timer_disarm(uint32_t id) { if (id == INVALID_HANDLE) return; uint32_t primask = __get_PRIMASK(); __disable_irq(); timerNode_p node = s_timersListHead; while (node) { if (node->id == id) { node->isActive = false; break; } node = node->next; } if (!primask) { __enable_irq(); } } void Timer_delete(uint32_t id) { if (id == INVALID_HANDLE) return; timerNode_p node = s_timersListHead; timerNode_p prev = NULL; uint32_t primask = __get_PRIMASK(); __disable_irq(); while (node) { if (node->id == id) break; prev = node; node = node->next; } if (prev) { prev = node->next; if (node == s_timersListTail) s_timersListTail = prev; MEMMAN_free(node); } else { MEMMAN_free(s_timersListHead); s_timersListHead = s_timersListTail = NULL; } if (!primask) { __enable_irq(); } } void Timer_makeTick(void) { timerNode_p node = s_timersListHead; uint32_t primask = __get_PRIMASK(); __disable_irq(); while (node) { if (node->isActive && !node->cnt--) { node->cb(node->cbData); if (node->isPeriodic) node->cnt = node->timeout; else { uint32_t id = node->id; node = node->next; Timer_delete(id); continue; } } node = node->next; } if (!primask) { __enable_irq(); } } static uint32_t getNewHandle(void) { static uint32_t handle = 0; if (!handle || !++handle) handle = 1; return handle; } static _Bool isTimerHandleUnique(uint32_t handle) { timerNode_p node = s_timersListHead; while (node) { if (node->id == handle) return false; node = node->next; } return true; } static timerNode_p findTimerById(uint32_t handle) { timerNode_p node = s_timersListHead; while (node) { if (handle == node->id) return node; node = node->next; } return NULL; }
C
/******************************************************************************* * @file apps/uart/main.c * @brief This application is a simple uart example. * @author HoYa <[email protected]> ******************************************************************************* * @version v1.0 * @note * - 2018.01.02 Created. ******************************************************************************/ /* Include Headers -----------------------------------------------------------*/ // Standard #include <stdio.h> // System Header #include "stm32f4xx_hal.h" #include "stm32f4xx_nucleo.h" // User Header #include "uart.h" /* Private Function Prototypes -----------------------------------------------*/ static void SystemClock_Config(void); /* Main Function -------------------------------------------------------------*/ int main(void) { HAL_Init(); SystemClock_Config(); BSP_LED_Init(LED2); BSP_PB_Init(BUTTON_USER, BUTTON_MODE_GPIO); uart_init(115200); puts(""); puts("Hello World!\r"); // Test getchar() uint8_t ch; printf("Input char: "); ch = getchar(); puts("\r"); printf("Your input is %c.\r\n", ch); // Test floating point printf/scanf float f; printf("Input float number: "); scanf("%f", &f); puts("\r"); printf("Your input is %f.\r\n", f); char test[] = "This is a test string\r\n"; HAL_UART_Transmit(&hUart2, (uint8_t*)test, sizeof(test), 0xffff); HAL_UART_Transmit_IT(&hUart2, (uint8_t*)test, sizeof(test)); while (1) { BSP_LED_Toggle(LED2); if (BSP_PB_GetState(BUTTON_USER) == RESET) { puts("Pressed\r\n"); } HAL_Delay(500); } return 0; } #ifdef USE_FULL_ASSERT void assert_failed(uint8_t* file, uint32_t line) { (void)file; (void)line; while (1) { } } #endif /* Private Functions ---------------------------------------------------------*/ static void SystemClock_Config(void) { RCC_ClkInitTypeDef RCC_ClkInitStruct; RCC_OscInitTypeDef RCC_OscInitStruct; // Enable Power Control clock. __HAL_RCC_PWR_CLK_ENABLE(); // The voltage scaling allows optimizing the power consumption when the // device is clocked below the maximum system frequency, to update the // voltage scaling value regarding system frequency refer to product // datasheet. __HAL_PWR_VOLTAGESCALING_CONFIG(PWR_REGULATOR_VOLTAGE_SCALE2); // Enable HSI Oscillator and activate PLL with HSI as source. RCC_OscInitStruct.OscillatorType = RCC_OSCILLATORTYPE_HSI; RCC_OscInitStruct.HSIState = RCC_HSI_ON; RCC_OscInitStruct.HSICalibrationValue = 0x10; RCC_OscInitStruct.PLL.PLLState = RCC_PLL_ON; RCC_OscInitStruct.PLL.PLLSource = RCC_PLLSOURCE_HSI; RCC_OscInitStruct.PLL.PLLM = 16; RCC_OscInitStruct.PLL.PLLN = 336; RCC_OscInitStruct.PLL.PLLP = RCC_PLLP_DIV4; RCC_OscInitStruct.PLL.PLLQ = 7; if (HAL_RCC_OscConfig(&RCC_OscInitStruct) != HAL_OK) { return; } // Select PLL as system clock source and configure the HCLK, PCLK1 and PCLK2 // clocks dividers. RCC_ClkInitStruct.ClockType = (RCC_CLOCKTYPE_SYSCLK | RCC_CLOCKTYPE_HCLK | \ RCC_CLOCKTYPE_PCLK1 | RCC_CLOCKTYPE_PCLK2); RCC_ClkInitStruct.SYSCLKSource = RCC_SYSCLKSOURCE_PLLCLK; RCC_ClkInitStruct.AHBCLKDivider = RCC_SYSCLK_DIV1; RCC_ClkInitStruct.APB1CLKDivider = RCC_HCLK_DIV2; RCC_ClkInitStruct.APB2CLKDivider = RCC_HCLK_DIV1; if (HAL_RCC_ClockConfig(&RCC_ClkInitStruct, FLASH_LATENCY_2) != HAL_OK) { return; } }
C
// COA-602 Tarea 9 Ejercicio 5 // Fecha de creacion: 11-Marzo-2020 /********************************************************************************************************************************* Generalice la estrategia para ordenar tres o cinco números enteros, que consiste en buscar mínimos sucesivamente en una lista L1 de tamaño n= 100. Almacene los mínimos en otra lista L2 iniciando en la posición i=0. Cada vez que encuentre un mínimo en L1, marque cada posición, para no incluir dicho valor en la siguiente búsqueda. Imprima L1 y L2 a doble columna. **********************************************************************************************************************************/ #include <stdio.h> #include <stdlib.h> #include <time.h> #define SIZE 100 void aleatoriza_lista(int lista[]); void imprime_listas(int lista1[], int lista2[]); void ordena_lista(int lista1[], int lista2[]); int main() { srand(time(NULL)); int L1[SIZE], L2[SIZE]; aleatoriza_lista(L1); ordena_lista(L1, L2); imprime_listas(L1, L2); return 0; } void aleatoriza_lista(int lista[]) { int i; printf("\n"); for (i = 0; i < SIZE; i++) { lista[i] = rand() % 100; } } void imprime_listas(int lista1[], int lista2[]) { int i; printf(" n\tLista 1\t\tLista 2\n"); for (i = 0; i < SIZE; i++) { printf("%2d\t%d\t\t%d\t\n", i, lista1[i], lista2[i]); } } void ordena_lista(int lista1[], int lista2[]) { int i, j, minimo, pos, lista3[SIZE]; for (i = 0; i < SIZE; i++) lista3[i] = lista1[i]; for (i = 0; i < SIZE; i++) { minimo = 999; for (j = 0; j < SIZE; j++) if (lista3[j] < minimo) { minimo = lista3[j]; pos = j; } lista3[pos] = 999; lista2[i] = minimo; } }
C
#include <stdio.h> #include <assert.h> #include "snake_game.h" snake_game_t game; void remove_food(snake_game_t *game) { int row, col; for (row = 0; row < SNAKE_ROWS; row++) { for (col = 0; col < SNAKE_COLUMNS; col++) { if (game->board[row][col] == SNAKE_FOOD) { game->board[row][col] = SNAKE_EMPTY; } } } return; } void test_init() { int row, col; bool food_found; snake_init(&game); assert(game.paused); assert(!game.game_over); assert(game.score == 1); assert(game.head_row == 4); assert(game.head_col == 4); assert(game.drow == 0); assert(game.dcol == -1); assert(game.board[game.head_row][game.head_col] == 1); // Check that exactly one piece of food exists on the board food_found = false; for (row = 0; row < SNAKE_ROWS; row++) { for (col = 0; col < SNAKE_COLUMNS; col++) { if (game.board[row][col] == SNAKE_FOOD) { assert(!food_found); food_found = true; } else if (row != game.head_row && col != game.head_col) { assert(game.board[row][col] == SNAKE_EMPTY); } } } assert(food_found); printf("Initialization Tests Passed!\n"); return; } void test_move() { snake_init(&game); // When the game is paused, no movement should happend move_snake(&game); assert(game.head_row == 4); assert(game.head_col == 4); assert(game.board[game.head_row][game.head_col] == 1); // Move left game.paused = false; move_snake(&game); assert(game.head_row == 4); assert(game.head_col == 3); assert(game.board[4][4] == SNAKE_EMPTY); assert(game.board[game.head_row][game.head_col] == 1); // Move up game.drow = -1; game.dcol = 0; move_snake(&game); assert(game.head_row == 3); assert(game.head_col == 3); assert(game.board[4][3] == SNAKE_EMPTY); assert(game.board[game.head_row][game.head_col] == 1); // Move right game.drow = 0; game.dcol = 1; move_snake(&game); assert(game.head_row == 3); assert(game.head_col == 4); assert(game.board[3][3] == SNAKE_EMPTY); assert(game.board[game.head_row][game.head_col] == 1); // Move down game.drow = 1; game.dcol = 0; move_snake(&game); assert(game.head_row == 4); assert(game.head_col == 4); assert(game.board[3][4] == SNAKE_EMPTY); assert(game.board[game.head_row][game.head_col] == 1); // Test wrap-around (moving left) game.drow = 0; game.dcol = -1; move_snake(&game); move_snake(&game); move_snake(&game); move_snake(&game); move_snake(&game); assert(game.head_row == 4); assert(game.head_col == 7); assert(game.board[4][4] == SNAKE_EMPTY); assert(game.board[4][3] == SNAKE_EMPTY); assert(game.board[4][2] == SNAKE_EMPTY); assert(game.board[4][1] == SNAKE_EMPTY); assert(game.board[4][0] == SNAKE_EMPTY); assert(game.board[game.head_row][game.head_col] == 1); // Test wrap-around (moving right) game.drow = 0; game.dcol = 1; move_snake(&game); assert(game.head_row == 4); assert(game.head_col == 0); assert(game.board[4][7] == SNAKE_EMPTY); assert(game.board[game.head_row][game.head_col] == 1); // Test wrap-around (moving down) game.drow = 1; game.dcol = 0; move_snake(&game); move_snake(&game); move_snake(&game); move_snake(&game); assert(game.head_row == 0); assert(game.head_col == 0); assert(game.board[4][0] == SNAKE_EMPTY); assert(game.board[5][0] == SNAKE_EMPTY); assert(game.board[6][0] == SNAKE_EMPTY); assert(game.board[7][0] == SNAKE_EMPTY); assert(game.board[game.head_row][game.head_col] == 1); // Test wrap-around (moving up) game.drow = -1; game.dcol = 0; move_snake(&game); assert(game.head_row == 7); assert(game.head_col == 0); assert(game.board[0][0] == SNAKE_EMPTY); assert(game.board[game.head_row][game.head_col] == 1); printf("Movement Tests Passed!\n"); return; } void test_food() { int row, col; bool food_found; snake_init(&game); game.paused = false; // Put the food right in front of the snake, remove the other remove_food(&game); game.board[game.head_row+game.drow][game.head_col+game.dcol] = SNAKE_FOOD; // Test that the snake grows properly move_snake(&game); assert(game.head_row == 4); assert(game.head_col == 3); assert(game.board[4][4] == 1); assert(game.board[game.head_row][game.head_col] == 2); assert(game.score == 2); // Check that a new piece of food was properly generated food_found = false; for (row = 0; row < SNAKE_ROWS; row++) { for (col = 0; col < SNAKE_COLUMNS; col++) { if (game.board[row][col] == SNAKE_FOOD) { assert(!food_found); food_found = true; } else if (row != game.head_row && row != (game.head_row-game.drow) && col != game.head_col && col != (game.head_col-game.dcol)) { assert(game.board[row][col] == SNAKE_EMPTY); } } } assert(food_found); printf("Food Tests Passed!\n"); return; } void test_gameover() { snake_init(&game); game.paused = false; // Grow the size of the snake remove_food(&game); game.board[game.head_row+game.drow][game.head_col+game.dcol] = SNAKE_FOOD; move_snake(&game); assert(game.score == 2); remove_food(&game); game.board[game.head_row+game.drow][game.head_col+game.dcol] = SNAKE_FOOD; move_snake(&game); assert(game.score == 3); remove_food(&game); game.board[game.head_row+game.drow][game.head_col+game.dcol] = SNAKE_FOOD; move_snake(&game); assert(game.score == 4); remove_food(&game); game.board[game.head_row+game.drow][game.head_col+game.dcol] = SNAKE_FOOD; move_snake(&game); assert(game.score == 5); // Intersect the snake with itself game.drow = -1; game.dcol = 0; move_snake(&game); game.drow = 0; game.dcol = 1; move_snake(&game); game.drow = 1; game.dcol = 0; move_snake(&game); assert(game.game_over); assert(game.head_row == 3); assert(game.head_col == 1); assert(game.score == 5); // Try moving the snake after the game is over move_snake(&game); assert(game.game_over); assert(game.head_row == 3); assert(game.head_col == 1); assert(game.score == 5); printf("Game Over Tests Passed!\n"); return; } int main() { test_init(); test_move(); test_food(); test_gameover(); printf("All Tests Passed!\n"); return 0; }
C
#include <stdio.h> int main() { int season = 0; scanf("%d", &season); switch(season) { case 3: case 4: case 5: printf("spring"); break; case 6: case 7: case 8: printf("summer"); break; case 9: case 10: case 11: printf("fall"); break; default: printf("winter"); break; } return 0; }
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* mlx.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: kkostrub <[email protected]> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2018/07/27 11:41:11 by kkostrub #+# #+# */ /* Updated: 2018/07/27 11:50:03 by kkostrub ### ########.fr */ /* */ /* ************************************************************************** */ #include "fdf.h" static void ft_rotate(t_val *fdf, int j, int i) { double shift_x; double shift_y; shift_x = (fdf->map.width / 2); shift_y = (fdf->map.height / 2); fdf->rx1 = j - shift_x; fdf->ry1 = (i - shift_y) * cos(fdf->alpha) + (fdf->map.map[i][j] * fdf->map.k) * sin(fdf->alpha); fdf->rz1 = -(i - shift_y) * sin(fdf->alpha) + (fdf->map.map[i][j] * fdf->map.k) * cos(fdf->alpha); fdf->rx2 = fdf->rx1 * cos(fdf->beta) + fdf->rz1 * sin(fdf->beta); fdf->ry2 = fdf->ry1; fdf->rz2 = -(fdf->rx1) * sin(fdf->beta) - fdf->rz1 * cos(fdf->beta); fdf->rx3 = fdf->rx2 * cos(fdf->gamma) + fdf->ry2 * sin(fdf->gamma); fdf->ry3 = fdf->rx2 * sin(fdf->gamma) + fdf->ry2 * cos(fdf->gamma); fdf->rz3 = fdf->rz2; fdf->rx3 = (fdf->rx3 * fdf->scale_x) + (SIZE_W / 2) + fdf->map.move_x; fdf->ry3 = (fdf->ry3 * fdf->scale_y) + (SIZE_H / 2) + fdf->map.move_y; } static t_val *ft_addr_img(t_val *fdf) { fdf->bpp = 5; fdf->sl = 1; fdf->end = (SIZE_W * SIZE_H); fdf->img_ptr = mlx_new_image(fdf->mlx_ptr, SIZE_W, SIZE_H); fdf->img_data_addr = mlx_get_data_addr(fdf->img_ptr, &fdf->bpp, &fdf->sl, &fdf->end); return (fdf); } void ft_draw_img(t_val *fdf) { fdf->i = -1; while (++(fdf->i) < (fdf->map.height)) { fdf->j = -1; while (++(fdf->j) < (fdf->map.width)) { ft_rotate(fdf, fdf->j, fdf->i); fdf->x1 = fdf->rx3; fdf->y1 = fdf->ry3; if (fdf->j < (fdf->map.width - 1)) { ft_rotate(fdf, fdf->j + 1, fdf->i); fdf->x2 = fdf->rx3; fdf->y2 = fdf->ry3; ft_line(fdf, 1); } if (fdf->i < (fdf->map.height - 1)) { ft_rotate(fdf, fdf->j, fdf->i + 1); fdf->x2 = fdf->rx3; fdf->y2 = fdf->ry3; ft_line(fdf, 2); } } } } int ft_mlx(t_val *fdf) { fdf->scale_x = (SIZE_W * 0.7) / (fdf->map.width); fdf->scale_y = (SIZE_H * 0.7) / (fdf->map.height); fdf->alpha = -0.5; fdf->beta = -0.5; fdf->gamma = 0; fdf->map.k = 1; fdf->map.move_x = 0; fdf->map.move_y = 0; fdf->hints = 1; fdf->mlx_ptr = mlx_init(); fdf->win_ptr = mlx_new_window(fdf->mlx_ptr, SIZE_W, SIZE_H, "fdf"); ft_addr_img(fdf); ft_draw_img(fdf); mlx_put_image_to_window(fdf->mlx_ptr, fdf->win_ptr, fdf->img_ptr, 0, 0); hints(fdf); mlx_hook(fdf->win_ptr, 2, (1L << 0), deal_key, fdf); mlx_loop(fdf->mlx_ptr); return (0); }
C
#include "simpleos.h" Kernel_t Kernel; void SimpleOS_assertFailed() { while(1); } SIMPLE_INLINE Kernel_t *SimpleOS_getKernel(void) { return &Kernel; } uint32_t SimpleOS_Kernel_init(void) { SimpleOS_initScheduler(); SimpleOS_IdleThread_init(); Kernel.IdleTime = 0; Kernel.TimeStamp = 0; return SIMPLE_ERR_OK; } uint32_t SimpleOS_wakeSleepThread(void) { Thread_t *Thread; Thread = Scheduler.SleepingList.Head; while(Thread != SIMPLE_NULL) { Thread->SleepTime -= 1; if(Thread->SleepTime == 0) { if(Thread->Prev == SIMPLE_NULL) { if(Thread->Next == SIMPLE_NULL) { Scheduler.SleepingList.Head = SIMPLE_NULL; Scheduler.SleepingList.Tail = SIMPLE_NULL; } else { Thread->Next->Prev = SIMPLE_NULL; Scheduler.SleepingList.Head = Thread->Next; } } else { if(Thread->Next == SIMPLE_NULL) { Thread->Prev->Next = SIMPLE_NULL; Scheduler.SleepingList.Tail = Thread->Prev; } else { Thread->Prev->Next = Thread->Next; Thread->Next->Prev = Thread->Prev; } } SimpleOS_setThreadReady(Thread); } Thread = Thread->Next; } return SIMPLE_ERR_OK; } void SimpleOS_TimeTickHandler(void) { SimpleOS_checkIPCList(&Scheduler.IPCList); SimpleOS_wakeSleepThread(); }
C
#include <_gl.h> #include <stdio.h> /** Version */ void version(void) { const unsigned char *renderer; const unsigned char *version; renderer = glGetString(GL_RENDERER); version = glGetString(GL_VERSION); printf("Compiled against GLFW %i.%i.%i\n", GLFW_VERSION_MAJOR, GLFW_VERSION_MINOR, GLFW_VERSION_REVISION); printf("Renderer: %s\n", renderer); printf("OpenGL version supported: %s\n", version); } /** * Init a #t_fps. */ void init_fps(t_fps *fps) { fps->frames = 0; fps->t1 = glfwGetTime(); fps->t2 = glfwGetTime(); } /** * Update a #t_fps. */ void run_fps(t_window *window, t_fps *fps) { fps->frames += 1; fps->t2 = glfwGetTime(); fps->dt = (fps->t2 - fps->t1) * 1000; fps->t += fps->dt; if (fps->t2 - fps->t >= 1.0) { bzero(fps->str, 12); sprintf(fps->str, "%.0f", fps->frames); glfwSetWindowTitle(window->w, fps->str); fps->t = fps->t2; fps->frames = 0; } }
C
/*------------------------------------------------------------------------------------- | [FILE NAME] <lcd.c> | | [AUTHOR] <Abdolee> | | [DATE CREATED] <Jan 15, 2020> | | [DESCRIPTION] <the C driver file for the LCD> | |-------------------------------------------------------------------------------------*/ /************************************************* * INCLUDES * *************************************************/ #include"lcd.h" /************************************************* * FUNCTION DEFINITIONS * *************************************************/ /*------------------------------------------------------------------------------------- | [FUNCTION NAME] <LCD_iNIT> | | [DESCRIPTION] < this function is used to InitIalize the LCD from | | the static CONFIG in the H file> | | [ARGS] <VOID> | [RETURNS] <VOID> | |-------------------------------------------------------------------------------------*/ void LCD_Init(void) { /*INIT GPIO selected in the header file*/ SET_BIT(LCD_RW_DDR,LCD_RW_PIN_NUMB); SET_BIT(LCD_RS_DDR,LCD_RS_PIN_NUMB); SET_BIT(LCD_E_DDR,LCD_E_PIN_NUMB); CLEAR_BIT(LCD_RW_PORT,LCD_RW_PIN_NUMB); CLEAR_BIT(LCD_RS_PORT,LCD_RS_PIN_NUMB); CLEAR_BIT(LCD_E_PORT,LCD_E_PIN_NUMB); #if INTERFACE_4BIT #if UPPER_PINS LCD_DATA_DDR|=0X0F; LCD_DATA_PORT&=0xF0; #elif LOWER_PINS LCD_DATA_DDR|=0XF0; LCD_DATA_PORT&=0x0F; #endif /*sending the LCD the command of 4bit mode and 2 lines*/ LCD_SendCommand(SET_4BIT); LCD_SendCommand(FUNCTION_SET_4BIT_2LINE); #elif INTERFACE_8BIT LCD_DATA_DDR=0XFF; LCD_DATA_PORT=0; /*sending the LCD the command of 8bit mode and 2 lines*/ LCD_SendCommand(FUNCTION_SET_8BIT_2LINE); #endif /*enable display and CURSER off command, and clear the display*/ LCD_SendCommand(DESPLAY_ON_CURSER_OFF); LCD_SendCommand(CLEAR_DISPLAY); } /*------------------------------------------------------------------------------------- | [FUNCTION NAME] <LCD_SendCommand> | | [DESCRIPTION] < this function is used to send a command to the LCD> | | [ARGS] <the command wanted to send> | [RETURNS] <VOID> | |-------------------------------------------------------------------------------------*/ void LCD_SendCommand(uint8 a_command) { #if INTERFACE_8BIT CLEAR_BIT(LCD_RS_PORT,LCD_RS_PIN_NUMB); _delay_ms(1); SET_BIT(LCD_E_PORT,LCD_E_PIN_NUMB); _delay_ms(1); LCD_DATA_PORT=a_command; _delay_ms(1); CLEAR_BIT(LCD_E_PORT,LCD_E_PIN_NUMB); _delay_ms(1); CLEAR_BIT(LCD_RS_PORT,LCD_RS_PIN_NUMB); LCD_DATA_PORT=0; #elif INTERFACE_4BIT CLEAR_BIT(LCD_RS_PORT,LCD_RS_PIN_NUMB); _delay_ms(1); SET_BIT(LCD_E_PORT,LCD_E_PIN_NUMB); _delay_ms(1); #if LOWER_PINS LCD_DATA_PORT= (LCD_DATA_PORT&0X0F)|(a_command & 0XF0); #elif UPPER_PINS LCD_DATA_PORT= (LCD_DATA_PORT&0XF0)|((a_command & 0XF0)>>4); #endif _delay_ms(1); CLEAR_BIT(LCD_E_PORT,LCD_E_PIN_NUMB); _delay_ms(1); SET_BIT(LCD_E_PORT,LCD_E_PIN_NUMB); _delay_ms(1); #if LOWER_PINS LCD_DATA_PORT=(LCD_DATA_PORT&0X0F)|((a_command & 0X0F)<<4); #elif UPPER_PINS LCD_DATA_PORT= (LCD_DATA_PORT&0XF0)|(a_command & 0X0F); #endif _delay_ms(1); CLEAR_BIT(LCD_E_PORT,LCD_E_PIN_NUMB); _delay_ms(1); CLEAR_BIT(LCD_RS_PORT,LCD_RS_PIN_NUMB); #if LOWER_PINS LCD_DATA_PORT&=0X0F; #elif UPPER_PINS LCD_DATA_PORT&=0XF0; #endif #endif } /*------------------------------------------------------------------------------------- | [FUNCTION NAME] <LCD_SendChar> | | [DESCRIPTION] < this function is used to send a char to the LCD> | | [ARGS] <the char wanted to send> | [RETURNS] <VOID> | |-------------------------------------------------------------------------------------*/ void LCD_SendChar(uint8 a_char) { #if INTERFACE_8BIT SET_BIT(LCD_RS_PORT,LCD_RS_PIN_NUMB); _delay_ms(1); SET_BIT(LCD_E_PORT,LCD_E_PIN_NUMB); _delay_ms(1); LCD_DATA_PORT=a_char; _delay_ms(1); CLEAR_BIT(LCD_E_PORT,LCD_E_PIN_NUMB); _delay_ms(1); CLEAR_BIT(LCD_RS_PORT,LCD_RS_PIN_NUMB); LCD_DATA_PORT=0; #elif INTERFACE_4BIT SET_BIT(LCD_RS_PORT,LCD_RS_PIN_NUMB); _delay_ms(1); SET_BIT(LCD_E_PORT,LCD_E_PIN_NUMB); _delay_ms(1); #if LOWER_PINS LCD_DATA_PORT= (LCD_DATA_PORT&0X0F)|(a_char & 0XF0); #elif UPPER_PINS LCD_DATA_PORT= (LCD_DATA_PORT&0XF0)|((a_char & 0XF0)>>4); #endif _delay_ms(1); CLEAR_BIT(LCD_E_PORT,LCD_E_PIN_NUMB); _delay_ms(1); SET_BIT(LCD_E_PORT,LCD_E_PIN_NUMB); _delay_ms(1); #if LOWER_PINS LCD_DATA_PORT=(LCD_DATA_PORT&0X0F)|((a_char & 0X0F)<<4); #elif UPPER_PINS LCD_DATA_PORT=(LCD_DATA_PORT&0XF0)|(a_char & 0X0F); #endif _delay_ms(1); CLEAR_BIT(LCD_E_PORT,LCD_E_PIN_NUMB); _delay_ms(1); CLEAR_BIT(LCD_RS_PORT,LCD_RS_PIN_NUMB); #if LOWER_PINS LCD_DATA_PORT&=0X0F; #elif UPPER_PINS LCD_DATA_PORT&=0XF0; #endif #endif } /*------------------------------------------------------------------------------------- | [FUNCTION NAME] <LCD_SendString> | | [DESCRIPTION] < this function is used to send a STRING to the LCD> | | [ARGS] <the STRING wanted to send> | [RETURNS] <VOID> | |-------------------------------------------------------------------------------------*/ void LCD_SendString(char* a_string_Ptr) { while(*(a_string_Ptr)!='\0') { LCD_SendChar(*(a_string_Ptr)); a_string_Ptr++; } } /*------------------------------------------------------------------------------------- | [FUNCTION NAME] <LCD_Sendint> | | [DESCRIPTION] < this function is used to send an INT to the lcd> | | [ARGS] <32 bit INT > | [RETURNS] <VOID> | |-------------------------------------------------------------------------------------*/ void LCD_SendInt(uint32 a_int) { uint16 i=0; /*by dividing the integer into small integers and saving it into an ARR*/ uint16 temp[16]={0}; do{ temp[i]=(a_int%10); a_int/=10; i++; }while(a_int); /*then displaying it element by element, the ARR is displayed backword, to occur the * wanted representation*/ while(i!=0) { LCD_SendChar(48+temp[(i-1)]); --i; } } /*------------------------------------------------------------------------------------- | [FUNCTION NAME] <LCD_SendFloat> | | [DESCRIPTION] < this function is used to send a float to the LCD> | | [ARGS] <the float wanted to send> | [RETURNS] <VOID> | |-------------------------------------------------------------------------------------*/ void LCD_SendFloat(float32 a_float) { /*this method seperate the fraction and the INT and display * every one of them seperatly*/ uint32 frac=(((uint32)((a_float)*1000))%1000); LCD_SendInt(a_float); LCD_SendChar('.'); LCD_SendInt(frac); }
C
int main(){ int x=22,y=44; if(x==23){ x=2; }else{ y=314; } while( x < 21 ) { printf("value of x: %d\n", x); x++; } x=x+x; printf("%d",x); return 0; }
C
/** * @author Dan Noland <[email protected]> */ #include <stdlib.h> #include <stdio.h> #include <string.h> #include "void_ptr_list.h" int str_compare(const void* left, const void* right ); void str_assign(void* dst, const void* src ); void* str_duplicate( const void* data_to_dup ); void str_deallocate( void* ptr); char* random_string(uint32_t min, uint32_t max); void test_setup_helper( vpl_t** lpp, vpl_context_t** cpp ); uint32_t runcase__sort_empty_list(const char* TNAME); uint32_t runcase__sort_one_item(const char* TNAME); uint32_t runcase__sort_two_items(const char* TNAME); uint32_t runcase__copy_and_compare(const char* TNAME); uint32_t runcase__iter_fuzz(const char* TNAME); uint32_t runcase__push_pop_fuzz(const char* TNAME); int str_compare(const void* left, const void* right ) { int result = strcmp((const char*)left, (const char*)right); return(result); } void str_assign(void* dst, const void* src ) { strcpy((char*)dst, (const char*)src); return; } void* str_duplicate( const void* data_to_dup ) { void* result = strdup( (const char*)data_to_dup ); return result; } void str_deallocate( void* ptr) { free(ptr); return; } char* random_string(uint32_t min, uint32_t max) { const char* printable = "1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";//"!@#$%^&*()_+-[]{}:,.<>?"; size_t plen = strlen(printable); uint32_t range = max - min; uint32_t i = 0; uint32_t res_len = min + ((uint32_t)rand()) % range; char* res = calloc( res_len+1, sizeof(char) ); for(i=0; i<res_len; i++) { res[i] = printable[ ((uint32_t)rand())%plen ]; } return(res); } void test_setup_helper( vpl_t** lpp, vpl_context_t** cpp ) { vpl_context_t* ctx = NULL; *cpp = vpl_context_create( ); ctx = *cpp; ctx->compare = str_compare; ctx->assign = str_assign; ctx->duplicate = str_duplicate; ctx->deallocate = str_deallocate; vpl_create( lpp, ctx ); return; } uint32_t runcase__sort_empty_list(const char* TNAME) { //////////////////////// ///// Common setup ///// //////////////////////// vpl_context_t* ctx = NULL; vpl_t* lst = NULL; vpl_iter_t* it = NULL; //char* str = NULL; char* temp_str = NULL; int i = 0; uint32_t result = 1; test_setup_helper( &lst, &ctx ); printf("----- Begin Case %s -----\n", TNAME); fflush(NULL); //////////////////// ///// The case ///// //////////////////// vpl_sort( lst ); for( it = vpl_fwd_iter(lst); !vpl_is_end(it); it = vpl_iter_next(it) ) { temp_str = (char*)vpl_iter_get_data( it ); printf("%s[%d] = %s\n", TNAME, i, temp_str); i += 1; } /////////////////////////// ///// Common teardown ///// /////////////////////////// vpl_iter_free( it ); it = NULL; vpl_free( lst, 1); lst = 0; vpl_context_free(ctx); ctx = 0; printf("----- End Case %s -----\n", TNAME); fflush(NULL); return result; } uint32_t runcase__sort_one_item(const char* TNAME) { //////////////////////// ///// Common setup ///// //////////////////////// vpl_context_t* ctx = NULL; vpl_t* lst = NULL; vpl_iter_t* it = NULL; char* str = NULL; char* temp_str = NULL; int i = 0; uint32_t result = 1; test_setup_helper( &lst, &ctx ); printf("----- Begin Case %s -----\n", TNAME); fflush(NULL); //////////////////// ///// The case ///// //////////////////// str = random_string(10, 50); vpl_push_back( lst, str ); vpl_sort( lst ); for( it = vpl_fwd_iter(lst); !vpl_is_end(it); it = vpl_iter_next(it) ) { temp_str = (char*)vpl_iter_get_data( it ); printf("%s[%d] = %s\n", TNAME, i, temp_str); i += 1; } if( strcmp( temp_str, str ) != 0 ) { printf("Error %s != %s\n", temp_str, str ); result = 0; } /////////////////////////// ///// Common teardown ///// /////////////////////////// vpl_iter_free( it ); it = 0; vpl_free( lst, 1); lst = 0; vpl_context_free(ctx); ctx = 0; printf("----- End Case %s -----\n", TNAME); fflush(NULL); return result; } uint32_t runcase__sort_two_items(const char* TNAME) { //////////////////////// ///// Common setup ///// //////////////////////// vpl_context_t* ctx = NULL; vpl_t* lst = NULL; vpl_iter_t* it = NULL; char* str = NULL; char* temp_str = NULL; int i = 0; uint32_t result = 1; test_setup_helper( &lst, &ctx ); printf("----- Begin Case %s -----\n", TNAME); fflush(NULL); //////////////////// ///// The case ///// //////////////////// const char* str_ary[] = {"aaaaaaaaaaaaaaaaa", "zzzzzzzzzzzzzzzzzzzz"}; str = strdup(str_ary[1]); vpl_push_back( lst, str ); str = strdup(str_ary[0]); vpl_push_back( lst, str ); vpl_sort( lst ); for( it = vpl_fwd_iter(lst); !vpl_is_end(it); it = vpl_iter_next(it) ) { temp_str = (char*)vpl_iter_get_data( it ); printf("%s[%d] = %s\n", TNAME, i, temp_str); if( strcmp( temp_str, str_ary[i] ) != 0 ) { printf("Error %s != %s\n", temp_str, str_ary[i] ); result = 0; break; } i += 1; } /////////////////////////// ///// Common teardown ///// /////////////////////////// vpl_iter_free( it ); it = 0; vpl_free( lst, 1); lst = 0; vpl_context_free(ctx); ctx = 0; printf("----- End Case %s -----\n", TNAME); fflush(NULL); return result; } uint32_t runcase__copy_and_compare(const char* TNAME) { //////////////////////// ///// Common setup ///// //////////////////////// vpl_context_t* ctx_o = NULL; vpl_context_t* ctx = NULL; vpl_context_t* ctx_d = NULL; vpl_t* lst_orig = NULL; vpl_t* lst = NULL; vpl_t* lst_dup = NULL; char* str = NULL; //char* temp_str = NULL; int i = 0; uint32_t result = 1; test_setup_helper( &lst_orig, &ctx_o ); lst_orig->ctx->copy_mode = CM_DEEPCOPY; test_setup_helper( &lst, &ctx ); test_setup_helper( &lst_dup, &ctx_d ); lst_dup->ctx->copy_mode = CM_DEEPCOPY; printf("----- Begin Case %s -----\n", TNAME); fflush(NULL); //////////////////// ///// The case ///// //////////////////// int count = 10 + rand()%100; for(i=0; i<count; i++) { str = random_string(10, 50); //temp_str = strdup( str ); vpl_push_back( lst_orig, str ); vpl_push_back( lst, str ); } if( vpl_compare( lst, lst_orig ) != 0 ) { printf("Orignial compare mismatch\n"); result = 0; return result; } vpl_sort( lst ); vpl_copy( lst_dup, lst ); vpl_sort( lst_orig ); if( vpl_compare( lst_dup, lst_orig ) != 0 ) { printf("Final compare mismatch\n"); result = 0; return result; } /////////////////////////// ///// Common teardown ///// /////////////////////////// vpl_free( lst_orig, 1); lst_orig = 0; vpl_free( lst, 1); lst = 0; vpl_free( lst_dup, 1); lst_dup = 0; vpl_context_free(ctx_o); ctx_o = 0; vpl_context_free(ctx); ctx = 0; vpl_context_free(ctx_d); ctx_d = 0; printf("----- End Case %s -----\n", TNAME); fflush(NULL); return result; } uint32_t runcase__push_pop_fuzz(const char* TNAME) { //////////////////////// ///// Common setup ///// //////////////////////// vpl_context_t* ctx = NULL; vpl_t* lst = NULL; vpl_iter_t* it = NULL; char* str = NULL; char* temp_str = NULL; int i = 0; uint32_t result = 1; test_setup_helper( &lst, &ctx ); printf("----- Begin Case %s -----\n", TNAME); fflush(NULL); //////////////////// ///// The case ///// //////////////////// char* str_ary[100] = {0}; char* recovered_ary[100] = {0}; for(i=0; i<100; i++) { str_ary[i] = random_string(10, 50); } int in_count = 0; int out_count = 0; while(in_count < 100 ) { if(rand()%2 == 0) { // Tails remove an item str = (char*)vpl_pop_back( lst ); if( str ) { recovered_ary[ out_count ] = str; out_count += 1; } } else { // Heads add an item vpl_push_back( lst, str_ary[in_count] ); in_count += 1; } } // pop any stragglers while( (str = (char*)vpl_pop_back( lst )) ) { recovered_ary[ out_count ] = str; out_count += 1; } if(in_count != out_count) { printf("Error: length mismatch\n"); result = 0; return result; } // sort the references & the recovered int changes = 1; while(changes) { changes = 0; for(i=0; i<100-1; i+=1) { if( strcmp(str_ary[i], str_ary[i+1]) > 0 ) { temp_str = str_ary[i]; str_ary[i] = str_ary[i+1]; str_ary[i+1] = temp_str; changes = 1; } if( strcmp(recovered_ary[i], recovered_ary[i+1]) > 0 ) { temp_str = recovered_ary[i]; recovered_ary[i] = recovered_ary[i+1]; recovered_ary[i+1] = temp_str; changes = 1; } } } // final comparison for(i=0; i<100; i+=1) { if( strcmp( recovered_ary[i], str_ary[i] ) != 0 ) { printf("Error %s != %s\n", recovered_ary[i], str_ary[i] ); result = 0; break; } } // cleanup test data for(i=0; i<100; i+=1) { free(str_ary[i]); str_ary[i] = 0; recovered_ary[i] = 0; } /////////////////////////// ///// Common teardown ///// /////////////////////////// vpl_iter_free( it ); it = 0; vpl_free( lst, 1); lst = 0; vpl_context_free(ctx); ctx = 0; printf("----- End Case %s -----\n", TNAME); fflush(NULL); return result; } uint32_t runcase__iter_fuzz(const char* TNAME) { //////////////////////// ///// Common setup ///// //////////////////////// vpl_context_t* ctx = NULL; vpl_t* lst = NULL; vpl_iter_t* it = NULL; char* str = NULL; char* temp_str = NULL; int i = 0; uint32_t result = 1; test_setup_helper( &lst, &ctx ); printf("----- Begin Case %s -----\n", TNAME); fflush(NULL); //////////////////// ///// The case ///// //////////////////// char* str_ary[100] = {0}; char* cur_list[100] = {0}; char* recovered_ary[100] = {0}; for(i=0; i<100; i++) { str_ary[i] = random_string(10, 50); } int in_count = 0; int cur_count = 0; int out_count = 0; int idx = 0; while(in_count < 100 ) { if(rand()%2 == 0) { // Tails remove an item if( cur_count > 0 ) { idx = rand()%cur_count; str = cur_list[ idx ]; it = vpl_find( lst, str ); if( it == NULL ) { result = 0; printf("Error: Failed to find\n"); break; } recovered_ary[ out_count ] = (char*)vpl_iter_get_data( it ); out_count += 1; if(cur_count > 1) { cur_list[idx] = cur_list[cur_count-1]; } cur_count -= 1; vpl_remove( lst, it ); vpl_iter_free( it ); it = 0; } } else { // Heads add an item vpl_push_back( lst, str_ary[in_count] ); cur_list[cur_count] = str_ary[in_count]; cur_count += 1; in_count += 1; } } it = NULL; // pop any stragglers while( cur_count ) { idx = rand()%cur_count; str = cur_list[ idx ]; it = vpl_find( lst, str ); if( it == NULL ) { result = 0; printf("Error: Failed to find\n"); break; } recovered_ary[ out_count ] = vpl_iter_get_data( it ); out_count += 1; if(cur_count > 1) { cur_list[idx] = cur_list[cur_count-1]; } cur_count -= 1; vpl_remove( lst, it ); vpl_iter_free( it ); it = NULL; } if(in_count != out_count) { printf("Error: length mismatch in=[%d] out=[%d]\n", in_count, out_count); result = 0; return result; } // sort the references & the recovered int changes = 1; while(changes) { changes = 0; for(i=0; i<100-1; i+=1) { if( strcmp(str_ary[i], str_ary[i+1]) > 0 ) { temp_str = str_ary[i]; str_ary[i] = str_ary[i+1]; str_ary[i+1] = temp_str; changes = 1; } if( strcmp(recovered_ary[i], recovered_ary[i+1]) > 0 ) { temp_str = recovered_ary[i]; recovered_ary[i] = recovered_ary[i+1]; recovered_ary[i+1] = temp_str; changes = 1; } } } // final comparison for(i=0; i<100; i+=1) { if( strcmp( recovered_ary[i], str_ary[i] ) != 0 ) { printf("Error %s != %s\n", recovered_ary[i], str_ary[i] ); result = 0; break; } } // cleanup test data for(i=0; i<100; i+=1) { free(str_ary[i]); str_ary[i] = 0; recovered_ary[i] = 0; } /////////////////////////// ///// Common teardown ///// /////////////////////////// vpl_iter_free( it ); it = 0; vpl_free( lst, 1); lst = 0; vpl_context_free(ctx); ctx = 0; printf("----- End Case %s -----\n", TNAME); fflush(NULL); return result; } int main(int argc, char *argv[]) { int i = 0; vpl_context_t* sctx = NULL; vpl_t* sl = NULL; argc = argc; argv = argv; /* shut up warnings */ printf("--------- BEGIN LIST_TEST ----------\n"); fflush(NULL); sctx = vpl_context_create( ); sctx->compare = str_compare; sctx->assign = str_assign; sctx->duplicate = str_duplicate; sctx->deallocate = str_deallocate; vpl_create( &sl, sctx ); char* str = NULL; for(i=0; i<50; i++) { str = random_string(10, 50); printf("str[%d] = %s\n", i, str); vpl_push_back( sl, str ); //free(str); } vpl_iter_t* it; char* temp_str = NULL; i = 0; for( it = vpl_fwd_iter(sl); !vpl_is_end( it ); it = vpl_iter_next(it) ) { temp_str = (char*)vpl_iter_get_data( it ); printf("LIST[%d] = %s\n", i, temp_str); i += 1; } vpl_iter_free( it ); it = 0; i = 0; vpl_sort( sl ); for( it = vpl_fwd_iter(sl); !vpl_is_end( it ); it = vpl_iter_next(it) ) { temp_str = (char*)vpl_iter_get_data( it ); printf("SORT_LIST[%d] = %s\n", i, temp_str); i += 1; } vpl_iter_free( it ); it = 0; vpl_free( sl, 1); sl = 0; uint32_t rr=1; rr = runcase__push_pop_fuzz("push_pop_fuzz") && rr; rr = runcase__iter_fuzz("iter_fuzz") && rr; rr = runcase__copy_and_compare("copy_and_compare") && rr; printf("--- Edge Cases ---\n"); // Case - sort one item rr = runcase__sort_empty_list("sort_empty_list") && rr; rr = runcase__sort_one_item("sort_one_item") && rr; rr = runcase__sort_two_items("sort_two_items") && rr; vpl_context_free(sctx); sctx = 0; printf("--------- END LIST_TEST ----------\n"); if( rr ) { printf("ALL TESTS PASS\n"); } else { printf("*** FAILURE ***\n"); } //for(i=0; i<45; i++) { // str = random_string(8, 50); // printf("%d:%s\n", i, str); //} return 0; }
C
#include <stdio.h> #include <string.h> #include <limits.h> #include <stdbool.h> #include <errno.h> #include <sys/time.h> #include <time.h> #include <pthread.h> #include <stdarg.h> #include <sys/types.h> #include <sys/stat.h> #include <stdlib.h> #include <unistd.h> #include "transfer_file_mgr.h" #define MY_PRINTF(format, ...) printf(format"\n", ##__VA_ARGS__) #define TRANSFER_FILE_MGR_WARN_LOG MY_PRINTF #define TRANSFER_FILE_MGR_DEBUG_LOG MY_PRINTF #define TRANSFER_FILE_MGR_ERROR_LOG MY_PRINTF #define TRANSFER_FILE_MGR_INFO_LOG MY_PRINTF #define TRANSFER_FILE_MGR_TRACE_LOG MY_PRINTF typedef void* (*g_alloc_t) (size_t size); typedef void (*g_free_t) (void *ptr); static void* _malloc2calloc(size_t size); static void _free(void *ptr); static g_alloc_t g_tm_alloc = _malloc2calloc; static g_free_t g_tm_free = _free; static void* _malloc2calloc(size_t size) { return calloc(1, size); } static void _free(void *ptr) { if (!ptr) return ; free(ptr); } static bool _is_dir_exsit(const char *dir) { if (!dir) return false; struct stat st; if (lstat(dir, &st)) return false; return S_ISDIR(st.st_mode); } static bool _is_file_exsit(const char *path) { if (!path) return false; struct stat st; if (lstat(path, &st)) return false; return S_ISREG(st.st_mode); } /* @func: * 创建一个目录 */ static bool _create_dir(const char *dir, mode_t mode) { if (!dir) return false; char dir_buf[PATH_MAX] = {0}; char *start = dir_buf; char ch = 0; if (!strchr(dir, '/')) return false; snprintf(dir_buf, sizeof(dir_buf), "%s/", dir); while ((start = strchr(start, '/'))) { ch = *(start + 1); *(start + 1) = '\0'; if (_is_dir_exsit(dir_buf)) goto next; if (-1 == mkdir(dir_buf, mode)) { TRANSFER_FILE_MGR_WARN_LOG("mkdir %s error, errno: %d - %s", dir_buf, errno, strerror(errno)); return false; } next: *(start + 1) = ch; start++; } return true; } /* @func: * 获取文件名 */ static void _filename_get(transfer_file_mgr_t *tm, char *buf, size_t buf_size) { if (!tm || !tm->m_dst_dir || !tm->m_filename || !buf || !buf_size) return ; struct tm tm_s; struct timeval tv; gettimeofday(&tv, NULL); localtime_r(&tv.tv_sec, &tm_s); snprintf(buf, buf_size, "%s%s-%04d%02d%02d%02d%02d%02d%03d%s", tm->m_dst_dir, tm->m_filename, 1900 + tm_s.tm_year, 1 + tm_s.tm_mon, tm_s.tm_mday, tm_s.tm_hour, tm_s.tm_min, tm_s.tm_sec, (int)tv.tv_usec, tm->m_suffix); } /* @func: * 转移文件 */ static void _transfer_file_mgr_do(transfer_file_mgr_t *tm) { if (!tm) return ; char path_dst[PATH_MAX] = {0}; char path_tmp[PATH_MAX] = {0}; snprintf(path_tmp, sizeof(path_tmp), "%s%s%s", tm->m_tmp_dir, tm->m_filename, tm->m_suffix); if (tm->m_write_line == 0) return ; if (!_is_file_exsit(path_tmp)) return ; _filename_get(tm, path_dst, sizeof(path_dst)); if (rename(path_tmp, path_dst) < 0) { TRANSFER_FILE_MGR_WARN_LOG("rename %s to %s error, errno: %d - %s", path_tmp, path_dst, errno, strerror(errno)); return ; } tm->m_write_line = 0; } /* @func: * 创建一个管理器 * @param: * dir: 必须以/结尾 */ transfer_file_mgr_t* transfer_file_mgr_new(const char *tmp_dir, const char *dst_dir, const char *filename, const char *suffix, size_t max_line) { if (!tmp_dir || !dst_dir || !filename || !suffix || !max_line) return NULL; transfer_file_mgr_t *tm = NULL; size_t tmp_dir_len = strlen(tmp_dir); size_t dst_dir_len = strlen(dst_dir); size_t filename_len = strlen(filename); size_t suffix_len = strlen(suffix); if (!(tm = (transfer_file_mgr_t*)g_tm_alloc(sizeof(transfer_file_mgr_t)))) { TRANSFER_FILE_MGR_ERROR_LOG("g_tm_alloc error, errno: %d - %s", errno, strerror(errno)); return NULL; } if (!(tm->m_tmp_dir = (char*)g_tm_alloc(tmp_dir_len + 1))) { TRANSFER_FILE_MGR_ERROR_LOG("g_tm_alloc error, errno: %d - %s", errno, strerror(errno)); goto err; } if (!(tm->m_dst_dir = (char*)g_tm_alloc(dst_dir_len + 1))) { TRANSFER_FILE_MGR_ERROR_LOG("g_tm_alloc error, errno: %d - %s", errno, strerror(errno)); goto err; } if (!(tm->m_filename = (char*)g_tm_alloc(filename_len + 1))) { TRANSFER_FILE_MGR_ERROR_LOG("g_tm_alloc error, errno: %d - %s", errno, strerror(errno)); goto err; } if (!(tm->m_suffix = (char*)g_tm_alloc(suffix_len + 1))) { TRANSFER_FILE_MGR_ERROR_LOG("g_tm_alloc error, errno: %d - %s", errno, strerror(errno)); goto err; } if (pthread_mutex_init(&tm->m_mutex, NULL)) { TRANSFER_FILE_MGR_ERROR_LOG("pthread_mutex_init error, errno: %d - %s", errno, strerror(errno)); goto err; } tm->m_max_line = max_line; memcpy(tm->m_tmp_dir, tmp_dir, tmp_dir_len); tm->m_tmp_dir[tmp_dir_len] = '\0'; memcpy(tm->m_dst_dir, dst_dir, dst_dir_len); tm->m_dst_dir[dst_dir_len] = '\0'; memcpy(tm->m_suffix, suffix, suffix_len); tm->m_suffix[suffix_len] = '\0'; memcpy(tm->m_filename, filename, filename_len); tm->m_filename[filename_len] = '\0'; if (!_is_dir_exsit(tmp_dir)) _create_dir(tmp_dir, 0755); if (!_is_dir_exsit(dst_dir)) _create_dir(dst_dir, 0755); return tm; err: if (tm) { if (tm->m_filename) g_tm_free(tm->m_filename); if (tm->m_tmp_dir) g_tm_free(tm->m_tmp_dir); if (tm->m_dst_dir) g_tm_free(tm->m_dst_dir); if (tm->m_suffix) g_tm_free(tm->m_suffix); } return NULL; } /* @func: * 销毁管理器 */ void transfer_file_mgr_free(transfer_file_mgr_t *tm) { if (!tm) return ; pthread_mutex_lock(&tm->m_mutex); g_tm_free(tm->m_filename); g_tm_free(tm->m_dst_dir); g_tm_free(tm->m_tmp_dir); g_tm_free(tm->m_suffix); pthread_mutex_destroy(&tm->m_mutex); g_tm_free(tm); } /* @func: * 写日志 */ ssize_t transfer_file_mgr_printf(transfer_file_mgr_t *tm, const char *fm, ...) { if (!tm) return -1; va_list ap; FILE *fp = NULL; char path[PATH_MAX] = {0}; int write_len = 0; pthread_mutex_lock(&tm->m_mutex); snprintf(path, sizeof(path), "%s%s%s", tm->m_tmp_dir, tm->m_filename, tm->m_suffix); if (!(fp = fopen(path, "ab+"))) { TRANSFER_FILE_MGR_WARN_LOG("fopen %s error, errno: %d - %s", path, errno, strerror(errno)); goto out; } va_start(ap, fm); write_len = vfprintf(fp, fm, ap); va_end(ap); if (write_len < 0) { write_len = -1; goto out; } else tm->m_write_line++; out: if (fp) { fflush(fp); fclose(fp); } if (tm->m_write_line >= tm->m_max_line) _transfer_file_mgr_do(tm); pthread_mutex_unlock(&tm->m_mutex); return write_len; } /* @func: * 转移日志文件, */ void transfer_file_mgr_do(transfer_file_mgr_t* tm) { if (!tm) return ; pthread_mutex_lock(&tm->m_mutex); _transfer_file_mgr_do(tm); pthread_mutex_unlock(&tm->m_mutex); } #if 1 #include <assert.h> int main() { size_t i = 0; int cnt = 0; transfer_file_mgr_t *tm = NULL; pthread_t pt[10]; assert((tm = transfer_file_mgr_new("/tmp/", "/tmp/f/", "test", ".dat", 70))); pthread_create(&pt[i], NULL, ({ void* _(void *arg) { while (true) { transfer_file_mgr_do(tm); if (cnt == sizeof(pt) / sizeof(pt[0]) - 1) break; sleep(1); } return arg; }; _;}), NULL); for (i = 1; i < sizeof(pt) / sizeof(pt[0]); i++) { pthread_create(&pt[i], NULL, ({ void* _(void *arg) { int j = 0; int line = 100; for (j = 0; j < line; j++) { transfer_file_mgr_printf(tm, "%s:%d - %d\n", __FILE__, __LINE__, j); /* usleep(1000 * 100); */ } cnt++; return arg; }; _;}), NULL); } for (i = 0; i < sizeof(pt) / sizeof(pt[0]); i++) pthread_join(pt[i], NULL); transfer_file_mgr_free(tm); return 0; } #endif
C
#include <stdio.h> int main(void) { int N,input,i; long long result = 0; scanf("%d",&N); for(i=0;i<N;i++) { scanf("%d",&input); result=result+input; } printf("%lld",result-N+1); return 0; }
C
#include <stdio.h> #define inf 999999 #define SIZE 4 int main() { int adj[SIZE][SIZE] = {0,1,0,0, 1,0,1,1, 0,1,0,0, 0,1,0,0}; int path[SIZE][SIZE]; int i, j, k; for(i=0;i<SIZE;i++) for(j=0;j<SIZE;j++) path[i][j] = (i==j)?0:((adj[i][j]==1)?adj[i][j]:inf); for(k=0;k<2;k++){ for(i=0;i<SIZE;i++){ for(j=0;j<SIZE;j++){ if(path[i][j] > path[i][k] + path[k][j]) path[i][j] = path[i][k] + path[k][j]; } } /*for(i=0;i<SIZE;i++){ * for(j=0;j<SIZE;j++) * printf("%d\t",path[i][j]); * printf("\n"); * } * *printf("\n"); */ } for(i=0;i<SIZE;i++){ printf("Reachable from Node %d : ",i+1); for(j=0;j<SIZE;j++){ if(path[i][j]!=inf) printf("%d ", j+1); } printf("\n"); } }
C
#include<stdio.h> int main() { double h,w,p,a; printf("enter the height and width of the reactangle \n"); scanf("%le%le",&h,&w); p=2*(h+w); a=h*w; printf("the perimeter of the rectangle is %le \n the area of the rectangle is %le",p,a); }
C
#include <stdio.h> double media_ponderada(double a, double b, double c); int main(void) { int n, i; double a, b, c; scanf("%d", &n); for(i = 0; i < n; i++) { scanf("%lf %lf %lf", &a, &b, &c); printf("%.1lf\n", media_ponderada(a, b, c)); } return 0; } double media_ponderada(double a, double b, double c) { return (a * 2 + b * 3 + c * 5) / 10; }
C
/* * Copyright (C) 2015-2020 Alibaba Group Holding Limited */ #include <stdio.h> #include <aos/kernel.h> #include <ulog/ulog.h> /** * This use case demonstrates modifying the timer parameters after the timer is created. */ /* module name used by ulog */ #define MODULE_NAME "timer_app" /* timer handle */ static aos_timer_t timer1; /** * timer callback function. * The current use case is executed every 1000ms. */ static void timer1_func(void *timer, void *arg) { /* * Warning: an interface that causes a block is not allowed to be called within this function. * Blocking within this function will cause other timers to run incorrectly. * The printf function may also block on some platforms, so be careful how you call it. */ printf("[timer_change]timer expires\r\n"); } void timer_change(void) { int status; /** * Create timer. Timer starts automatically after successful creation. * some of the parameters are as follows: * fn: timer1_func (this function is called when the timer expires) * ms: 1000 (the cycle of the timer) * repeat: 1 (set to periodic timer) */ status = aos_timer_new(&timer1, timer1_func, NULL, 1000, 1); if (status != 0) { LOGE(MODULE_NAME, "create timer error"); return; } aos_msleep(10000); /* stop the timer before modifying the timer parameter */ aos_timer_stop(&timer1); /* the timer cycle is modified to 2000ms */ aos_timer_change(&timer1, 2000); /* start the timer after the timer parameter modification is complete */ aos_timer_start(&timer1); }
C
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <ctype.h> #include <time.h> #include <math.h> #define INF 1<<30 #define SZ 100000 /*problem id-11346 * *language-ANSI C * */ int main() { int i,j,k,l,m,n,t,x,y,blank=0,test=0; double a,b,s,tmp1,tmp2; scanf("%d",&t); while(t--) { scanf("%lf %lf %lf",&a,&b,&s); if(s==0) { printf("100.000000%%\n"); continue; } if(4*s>=4*a*b) { printf("0.000000%%\n"); continue; } tmp1=s*(log(a)-log(s/b)); tmp1+=s; tmp1*=4; tmp2=tmp1/(4*a*b); tmp2=1-tmp2; tmp2*=100; printf("%.6lf%%\n",tmp2); } return 0; }
C
#include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <errno.h> #include <sys/stat.h> #include <fcntl.h> #include "config.h" #include "page.h" #include "index.h" int main () { errno = 0; int fd = open("./moo.txt", O_RDWR|O_CREAT|O_TRUNC, 0660); int i; int rc; bbdb_pagemap_t *map; bbdb_page_t *page; WARN("open"); map = pagemap_new(fd); WARN("pagemap_new"); pagemap_close(map); WARN("pagemap_close"); map = pagemap_open(fd); WARN("pagemap_open"); for (i=0; i < 200; i++) { page = page_init(map, BBDB_MAGIC_HDR); if (!page) ERR(EXIT_FAILURE, "page_init"); } if (!page_get(map, 0)) ERR(EXIT_FAILURE, "page_get, 0"); pagemap_quiesce_pages(map, 0, 1); WARN("pagemap_quiesce_pages"); if (!page_set_checksum(page)) { WARNX("page_set_checksum failed"); } else { WARNX("page_set_checksum succeeded"); } if (!page_validate_checksum(page)) { WARNX("page_validate_checksum failed"); } else { WARNX("page_validate_checksum succeeded"); } /* Index tests */ index_t *index = index_new(map); WARN("index_new"); for (i=0; i < 200; i++) { index_add(index, page_get(map, i)); } index_close(index); WARN("index_close"); index_open(map); WARN("index_open"); for (i=0; i < 210; i++) { if ((rc = index_lookup(index, i)) < 0) printf("lookup failed %d\n", i); } pagemap_close(map); WARN("pagemap_close"); }
C
#ifndef __board_h__ #define __board_h__ #include <stdio.h> #include <stdlib.h> #include <string.h> #include "./stack.h" #include "./config.h" /* Holds info about the current board */ struct gameinfo { int nrows; int ncols; int winamount; int *board; }; struct scoreboard { int playervplayer; int player1wins; int playerdraws; int playervcomputer; int computerwins; int computerdraws; }; /* Included later since structs above are needed */ #include "./io.h" #include "./win.h" #include "./quicksort.h" /* Updates the current boardsize */ struct gameinfo changeBoardSize(struct gameinfo *); void initGameInfo(struct gameinfo *, struct scoreboard *); /* adds a peice at the bottom of the column*/ /* index, color */ int addPiece(struct gameinfo *, int, int); /* sees if avaible spot to play is good returns */ int checkAvailable(struct gameinfo *, int); /* checks to see if their a path between two indexs */ int dfs(struct gameinfo *boardinfo, int, int); /* Is the player state*/ int player(struct gameinfo *); /* The Computer States */ int easyMode(struct gameinfo *); int hardMode(struct gameinfo *); int computer(struct gameinfo *); #endif
C
/* ** EPITECH PROJECT, 2019 ** AIA_n4s_2018 ** File description: ** mx_add */ #include "n4s.h" mx_t *mx_add_scalar(mx_t *a, double scalar, bool new) { vectori_t size = a->size; mx_t *res = NULL; int x = 0; int y = 0; res = (new ? mx_new(size.x, size.y) : a); while (y < size.y) { x = 0; while (x < size.x) { res->arr[y][x] = a->arr[y][x] + scalar; ++x; } ++y; } return (res); } mx_t *mx_subtract_scalar(mx_t *a, double scalar, bool new) { vectori_t size = a->size; mx_t *res = NULL; int x = 0; int y = 0; res = (new ? mx_new(size.x, size.y) : a); while (y < size.y) { x = 0; while (x < size.x) { res->arr[y][x] = a->arr[y][x] - scalar; ++x; } ++y; } return (res); } mx_t *mx_add(mx_t *a, mx_t *b, bool new) { vectori_t size = a->size; mx_t *res = NULL; int x = 0; int y = 0; if (a->size.x != b->size.x || a->size.y != b->size.y) return (NULL); res = (new ? mx_new(size.x, size.y) : a); while (y < size.y) { x = 0; while (x < size.x) { res->arr[y][x] = a->arr[y][x] + b->arr[y][x]; ++x; } ++y; } return (res); } mx_t *mx_subtract(mx_t *a, mx_t *b, bool new) { vectori_t size = a->size; mx_t *res = NULL; int x = 0; int y = 0; if (a->size.x != b->size.x || a->size.y != b->size.y) return (NULL); res = (new ? mx_new(size.x, size.y) : a); while (y < size.y) { x = 0; while (x < size.x) { res->arr[y][x] = a->arr[y][x] - b->arr[y][x]; ++x; } ++y; } return (res); }
C
/**********************************************************************//** * @file accident_detection.c *************************************************************************/ #include <stdbool.h> #include <stdlib.h> #include "accident_detection.h" #include "accident_data.h" #include "../hardware_boards/car_panel/car_panel.h" #include "../application/scheduler/scheduler.h" #include "../util/r2r_led/r2r_led.h" /* Local variables */ static float cur_temp = 0.0F; static float prev_temp = CONFIG_ALARM_FIRE_TEMP_INIT; /**********************************************************************//** * @ingroup ac_det_pub * Gets the accelerometer data and analysis them to see if a crash has * occurred * Steps in function: * 1. Read accelerometer data * 2. Analysis data * 3. Sets EXT_EMERGENCY_FLAG to EMERGENCY_AUTO_ALARM if crash is detected **************************************************************************/ void check_for_crash(void) { volatile bool _alarm = true; uint8_t i = 0U; int16_t *_acc_buffer = malloc(CONFIG_ALARM_CRASH_NO_OF_READINGS * sizeof(int16_t)); scheduler_acc_get_last_readings_sum(_acc_buffer); for (i = 0U; i < CONFIG_ALARM_CRASH_NO_OF_READINGS; i++) { if ((int16_t)*(_acc_buffer + i) < CONFIG_ALARM_CRASH_TRIGGER_VALUE) { _alarm = false; break; } } free(_acc_buffer); if (_alarm && (EXT_EMERGENCY_FLAG == EMERGENCY_NO_ALARM)) { scheduler_halt(); if (!car_panel_wait_cancel_emmergency()) { EXT_EMERGENCY_FLAG = EMERGENCY_AUTO_ALARM; }else { scheduler_resume(true); } } } /**********************************************************************//** * @ingroup ac_det_pub * Gets the temperature and compare to last read value to see if temperature * has raised to a critical level * Steps in function: * 1. Read temperature * 2. Compare current value with last reading * 3. Sets EXT_EMERGENCY_FLAG to EMERGENCY_AUTO_ALARM if fire is detected **************************************************************************/ void check_for_fire(void) { cur_temp = scheduler_temp_get_last_reading(); if ((prev_temp > CONFIG_ALARM_FIRE_TEMP_INIT) && ((cur_temp - prev_temp) > CONFIG_ALARM_FIRE_TRIGGER_DEGREE) && (EXT_EMERGENCY_FLAG == EMERGENCY_NO_ALARM)) { scheduler_halt(); if (!car_panel_wait_cancel_emmergency()) { EXT_EMERGENCY_FLAG = EMERGENCY_AUTO_ALARM; } else { scheduler_resume(true); } } prev_temp = cur_temp; }
C
/* gcc -c -DARCH_X86_64 rtc.c */ /* gcc -o rtc.exe -D_TEST_ -DARCH_X86_64 rtc.c */ /* In Fortron code: do this: integer(kind=8) :: st,et,res real(kind=8) :: tt,rtmp call get_rtc(st) ..... call get_rtc(et) call get_rtc_res(res) rtmp=res tt=(et-st)/rtmp */ #include <sched.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <sys/time.h> /*#define ARCH_X86*/ /*#define ARCH_X86_64*/ /*#define ARCH_IA64*/ /*#define ARCH_PPC64*/ #if defined(ARCH_X86) static __inline__ unsigned long long get_rtc(void) { unsigned long low, high; do { asm volatile ("rdtsc\n\t" : "=a" (low), "=d" (high)); } while (0); return (((unsigned long long)high << 32)) | ((unsigned long long)low); } #elif defined(ARCH_X86_64) static __inline__ unsigned long long get_rtc(void) { unsigned long long rtc; do { asm volatile ("rdtsc\n\t" "salq $32, %%rdx\n\t" "orq %%rdx, %%rax\n\t" "movq %%rax, %0" : "=r" (rtc) : /* no inputs */ : "%rax", "%rdx"); } while (0); return rtc; } #elif defined(ARCH_IA64) static __inline__ unsigned long long get_rtc(void) { unsigned long long rtc; do { asm volatile ("mov %0=ar.itc" : "=r" (rtc) : /* no inputs */); } while (0); return rtc; } #elif defined(ARCH_PPC64) static __inline__ unsigned long long get_rtc(void) { unsigned long low, high, high2; do { asm volatile ("mftbu %0\n\t" "mftb %1\n\t" "mftbu %2" : "=r" (high), "=r" (low), "=r" (high2)); } while (high != high2); return ((((unsigned long long int)high) << 32) + ((unsigned long long)low)) * 8; } #elif defined(ARCH_NONE) static __inline__ unsigned long long get_rtc(void) { struct timeval Time; unsigned long long time_microsec; gettimeofday(&Time, NULL); time_microsec = (Time.tv_sec*1000000) + Time.tv_usec; return time_microsec; } #else #error please defined ARCH_XXXX #endif /* general rtc_res function. Some processors (such Itanium) can return the */ /* clock resolution, some others don't. Use the general clock to sleep 1s */ /* and make a diff beetween RTC. The precission is enougth to handle */ /* sample of 10e-4 to 10e-2. If you need bigger sample, use the standard OS */ /* method */ static __inline__ unsigned long long get_rtc_res(void) { #if defined(ARCH_NONE) return 1000000L; #endif static unsigned long long res = 0; unsigned long long rtc; if (res != 0) /* the value is in the cache */ return res; rtc = get_rtc(); usleep(1000000); /* usleep doesn't work as desired */ res = get_rtc() - rtc; return res; } static __inline__ unsigned long long get_rtc_perturb(void) { static unsigned long long perturb; unsigned long long rtc1, rtc2; int i; if (perturb != 0) return perturb; for (i = 0; i < 10; ++i) rtc1 = get_rtc(); /* some shoot to load code cache ... */ rtc1 = get_rtc(); /* get base time */ rtc2 = get_rtc(); /* get end time */ perturb = rtc2 - rtc1; /* make diff */ return perturb; } void get_rtc_(unsigned long long *rtc) { *rtc = get_rtc(); } void get_rtc_res_(unsigned long long *res) { *res = get_rtc_res(); } void get_rtc_perturb_(unsigned long long *perturb) { *perturb = get_rtc_perturb(); } #if _TEST_ #define SLEEP_TIME 10 int main(int argc, char *argv[]) { int i, sleep_time; unsigned long long rtc1, rtc2, diff, res, perturb; cpu_set_t mask; printf("pine process to cpu 0\n"); __CPU_ZERO(&mask); __CPU_SET(0, &mask); #if !defined(X86_64) && !defined(X86) if (sched_setaffinity(getpid(), sizeof(cpu_set_t) / sizeof(__cpu_mask), (void *)&mask) == -1) { perror("sched_setaffinity"); return EXIT_FAILURE; } #else if (sched_setaffinity(getpid(), (void *)&mask) == -1) { perror("sched_setaffinity"); return EXIT_FAILURE; } #endif if (argv[1] != NULL) { sleep_time = atoi(argv[1]); if (sleep_time == 0) sleep_time = SLEEP_TIME; } else sleep_time = SLEEP_TIME; printf("sleep %d seconds\n", sleep_time); rtc1 = get_rtc(); sleep(sleep_time); rtc2 = get_rtc(); diff = rtc2 - rtc1; res = get_rtc_res(); perturb = get_rtc_perturb(); printf("rtc1 = %llu ticks\n", (unsigned long long)rtc1); printf("rtc2 = %llu ticks\n", (unsigned long long)rtc2); printf("diff = %lu ticks\n", (unsigned long)(rtc2 - rtc1)); printf("res = %lu ticks = %LG s\n", (unsigned long)(res), ((long double)1.0) / res); printf("perturb = %lu ticks = %LG s\n", (unsigned long)(perturb), ((long double)perturb) / res); printf("time = %LG s\n", (long double)diff / res); return EXIT_SUCCESS; } #endif
C
// // search-insert-position.c // algorithm // // Created by Kai on 2019/7/25. // Copyright © 2019 kai. All rights reserved. // #include "search-insert-position.h" /* https://leetcode.com/problems/search-insert-position/ */ typedef int (*SearchInsertFunc)(int *nums, int numsSize, int target); // MARK:- 方法一、遍历查找 /** 方法一、时间复杂度O(n),空间复杂度O(1) 索引初始为 0 遍历数组,拿当前元素和目标值比较 <=:结果就是当前索引值,>:继续遍历 直到循环结束,返回 numSize */ int searchInsert(int* nums, int numsSize, int target) { return 0; } // MARK:- 方法二、二分查找 int searchInsertBinary(int *nums, int start, int end, int target); /* 方法二、时间复杂度O(log(n)),空间复杂度O(1) 二分查找 */ int searchInsert2(int *nums, int numsSize, int target) { int result = searchInsertBinary(nums, 0, numsSize - 1, target); return result; } int searchInsertBinary(int *nums, int start, int end, int target) { if (start == end) { return target <= nums[start] ? start : start + 1; } int median = (start + end) >> 1; if (target == nums[median]) { return median; } else if (target < nums[median]) { return searchInsertBinary(nums, start, median, target); } else { return searchInsertBinary(nums, median + 1, end, target); } } // MARK:- 测试 static void printArray(int *nums, int numsSize) { printf("nums: "); for (int i = 0; i < numsSize; i++) { printf("%d ", nums[i]); } printf("\n"); } /** nums = {1, 2, 3} numSize = 3 target = 2 result = 1 */ void testSearchInsert1(SearchInsertFunc func) { const int numSize = 3; int nums[numSize] = {1, 2, 3}; int target = 2; int result = func(nums, numSize, target); printArray(nums, numSize); printf("target: %d should be in %d\n", target, result); } /** nums = {1, 2, 3} numSize = 3 target = 1 result = 0 */ void testSearchInsert2(SearchInsertFunc func) { const int numSize = 3; int nums[numSize] = {1, 2, 3}; int target = 1; int result = func(nums, numSize, target); printArray(nums, numSize); printf("target: %d should be in %d\n", target, result); } /** nums = {1, 2, 3} numSize = 3 target = 3 result = 2 */ void testSearchInsert3(SearchInsertFunc func) { const int numSize = 3; int nums[numSize] = {1, 2, 3}; int target = 3; int result = func(nums, numSize, target); printArray(nums, numSize); printf("target: %d should be in %d\n", target, result); } /** nums = {1, 2, 3} numSize = 3 target = 4 result = 3 */ void testSearchInsert4(SearchInsertFunc func) { const int numSize = 3; int nums[numSize] = {1, 2, 3}; int target = 4; int result = func(nums, numSize, target); printArray(nums, numSize); printf("target: %d should be in %d\n", target, result); } /** nums = {1, 2, 3, 3, 10} numSize = 5 target = 0 result = 0 */ void testSearchInsert5(SearchInsertFunc func) { const int numSize = 3; int nums[numSize] = {1, 2, 3}; int target = 0; int result = func(nums, numSize, target); printArray(nums, numSize); printf("target: %d should be in %d\n", target, result); } /** nums = {1, 2, 3, 3, 10} numSize = 5 target = 7 result = 4 */ void testSearchInsert6(SearchInsertFunc func) { const int numSize = 5; int nums[numSize] = {1, 2, 3, 3, 10}; int target = 7; int result = func(nums, numSize, target); printArray(nums, numSize); printf("target: %d should be in %d\n", target, result); } /** nums = {1} numSize = 1 target = 2 result = 1 */ void testSearchInsert7(SearchInsertFunc func) { const int numSize = 1; int nums[numSize] = {1}; int target = 2; int result = func(nums, numSize, target); printArray(nums, numSize); printf("target: %d should be in %d\n", target, result); } void testSearchInsert(void) { testSearchInsert1(searchInsert2); testSearchInsert2(searchInsert2); testSearchInsert3(searchInsert2); testSearchInsert4(searchInsert2); testSearchInsert5(searchInsert2); testSearchInsert6(searchInsert2); testSearchInsert7(searchInsert2); }
C
#include <stdio.h> #define NUM_OF_ELEMS 10 static void posNeg(int arr[], int n) { int positive = 0; int negative = 1; int temp = 0; while (1) { temp = 0; while ((positive < n) && (arr[positive] >= 0)) { positive += 2; } while ((negative < n) && (arr[negative] <= 0)) { negative += 2; } if ((positive < n) && (negative < n)) { temp = arr[positive]; arr[positive] = arr[negative]; arr[negative] = temp; } else { break; } } } int main() { int arr[NUM_OF_ELEMS] = {0}; int index = 0; int n = 0; printf("\nEnter the number of elements\n"); scanf("%d", &n); printf("\nThe number of elements entered are: %d\n", n); printf("\nEnter the elements in an array\n"); for (index = 0; index < n; ++index) { scanf("%d", &arr[index]); } printf("\nThe elements in an array are:\n"); for (index = 0; index < n; ++index) { printf("\n%d\n", arr[index]); } posNeg(arr, n); printf("\nElements in an array after rearranging are:\n"); for (index = 0; index < n; ++index) { printf("\n%d\n", arr[index]); } return 0; }
C
/* * main.c * * Created on: Jan 11, 2021 * Author: huong */ #include "main.h" #include <string.h> #define FALSE 0 #define TRUE 1 void SystemClockConfig(uint8_t clock_seq); void UART2_Init(); void Error_handler(); void TIM2_Init(); void GPIO_Init(); static void settingClockfromPLL(RCC_OscInitTypeDef * osc_int ,uint8_t clock_seq, uint8_t * latency); /* Those variable for configure the UART 2*/ UART_HandleTypeDef huart2; char temp_rev; /*To save one char received from PC with Interrupt*/ uint16_t number_char_receive = 0; char buffer_receive[100]; char receive_finish = FALSE; char * user_data = "The user data: Output compare timer 2\r\n"; /*! GPIO port A variable*/ GPIO_InitTypeDef igpio; /*! The variable for TIMER purpose*/ TIM_HandleTypeDef htime2;/*! the variable to handle the timer 6(basic timer)*/ /** * @fn main() * @return int */ int main() { HAL_Init(); SystemClockConfig(SYS_CLK_50MHZ); UART2_Init(); GPIO_Init(); TIM2_Init(); uint16_t string_length = strlen(user_data); if (HAL_UART_Transmit(&huart2, (uint8_t *) user_data, string_length, HAL_MAX_DELAY) != HAL_OK) { Error_handler(); } if(HAL_TIM_PWM_Start(&htime2, TIM_CHANNEL_1) != HAL_OK){ Error_handler(); } if(HAL_TIM_PWM_Start(&htime2, TIM_CHANNEL_2) != HAL_OK){ Error_handler(); } if(HAL_TIM_PWM_Start(&htime2, TIM_CHANNEL_3) != HAL_OK){ Error_handler(); } if(HAL_TIM_PWM_Start(&htime2, TIM_CHANNEL_4) != HAL_OK){ Error_handler(); } while (1) { __WFI(); } return 0; }/*main*/ /** * @fn void UART2_Init() * @brief Initialization the UART2 peripheral * @var void * @retval void */ void UART2_Init() { huart2.Instance = USART2; /*! This is the base address of USART2*/ huart2.Init.BaudRate = 115200; /*! the baud rate of the transfer*/ huart2.Init.WordLength = UART_WORDLENGTH_8B; /*! Use 8-bit word length or 9-bit word length*/ huart2.Init.StopBits = UART_STOPBITS_1; huart2.Init.Parity = UART_PARITY_NONE; /*! Use the parity or not?*/ huart2.Init.HwFlowCtl = UART_HWCONTROL_NONE; huart2.Init.Mode = UART_MODE_TX_RX; if (HAL_UART_Init(&huart2) != HAL_OK) { Error_handler(); /*! The initialization is not okie*/ } }/*UART2_Init*/ /** * @fn void Error_handler() * @retval void */ void Error_handler() { while (1) { } }/*Error_handler*/ /** * @fn SystemClockConfig * @param clock_seq */ void SystemClockConfig(uint8_t clock_seq) { /*Those variable for configure the System clock*/ RCC_OscInitTypeDef osc_int; RCC_ClkInitTypeDef clk_int; uint8_t Flatency = 0; memset(&osc_int, 0, sizeof(RCC_OscInitTypeDef)); memset(&clk_int, 0, sizeof(RCC_ClkInitTypeDef)); /*select the source of clock for CPU and the bus*/ osc_int.OscillatorType = RCC_OSCILLATORTYPE_HSI; osc_int.HSIState = RCC_HSI_ON; /*Enable the HSI*/ osc_int.HSICalibrationValue = 16; osc_int.PLL.PLLState = RCC_PLL_ON; /*Enable the PLL*/ osc_int.PLL.PLLSource = RCC_PLLSOURCE_HSI; /*the input clock of PLL is HSI(16MHz)*/ settingClockfromPLL(&osc_int ,clock_seq, &Flatency); if (HAL_RCC_OscConfig(&osc_int) != HAL_OK) { Error_handler(); } /*Configure the clock for the bus: AHB, APB, ..*/ clk_int.ClockType = RCC_CLOCKTYPE_SYSCLK | RCC_CLOCKTYPE_HCLK | RCC_CLOCKTYPE_PCLK1 | RCC_CLOCKTYPE_PCLK2; clk_int.SYSCLKSource = RCC_SYSCLKSOURCE_PLLCLK; clk_int.APB2CLKDivider = RCC_HCLK_DIV2; clk_int.AHBCLKDivider = RCC_SYSCLK_DIV2; clk_int.APB1CLKDivider = RCC_HCLK_DIV2; if (HAL_RCC_ClockConfig(&clk_int, Flatency) != HAL_OK) { Error_handler(); } HAL_SYSTICK_Config(HAL_RCC_GetSysClockFreq()/1000); HAL_SYSTICK_CLKSourceConfig(SYSTICK_CLKSOURCE_HCLK); }/*SystemClockConfig*/ /** * @fn settingClockfromPLL * @param osc_int * @param clock_seq * @param latency * @retval void */ static void settingClockfromPLL(RCC_OscInitTypeDef * osc_int, uint8_t clock_seq, uint8_t * latency){ switch(clock_seq){ case SYS_CLK_50MHZ: { /*Calculator the PLL output*/ osc_int->PLL.PLLM = 16;/*the HSI is 16MHz, divide by 16 -> 1MHz*/ osc_int->PLL.PLLN = 100; /*1MHz multiple by 100 -> 100MHz*/ osc_int->PLL.PLLP = 2; /*100MHz divide by 2 -> 50MHz*/ *latency = FLASH_ACR_LATENCY_1WS; break; } case SYS_CLK_84MHZ: { /*Calculator the PLL output*/ osc_int->PLL.PLLM = 16;/*the HSI is 16MHz, divide by 16 -> 1MHz*/ osc_int->PLL.PLLN = 168; /*1MHz multiple by 168 -> 168MHz*/ osc_int->PLL.PLLP = 2; /*168MHz divide by 2 -> 84MHz*/ *latency = FLASH_ACR_LATENCY_2WS; break; } case SYS_CLK_120MHZ: { /*Calculator the PLL output*/ osc_int->PLL.PLLM = 16;/*the HSI is 16MHz, divide by 16 -> 1MHz*/ osc_int->PLL.PLLN = 240; /*1MHz multiple by 240 -> 240MHz*/ osc_int->PLL.PLLP = 2; /*240MHz divide by 2 -> 120MHz*/ *latency = FLASH_ACR_LATENCY_3WS; break; } default: { break; } } }/*settingClockfromPLL*/ /** * @fn void TIM2_Init() * @brief Initialization high level for the TIM2 peripheral * @var void * @retval void */ void TIM2_Init() { TIM_OC_InitTypeDef ichannelConfig;/*! To configure the output compare as PWM*/ memset(&htime2, 0U, sizeof(TIM_HandleTypeDef)); memset(&ichannelConfig, 0U, sizeof(TIM_OC_InitTypeDef)); htime2.Instance = TIM2;/*The address of timer 2*/ htime2.Init.Prescaler = 48; /*the prescaler for clock of timer 2*/ htime2.Init.CounterMode = TIM_COUNTERMODE_UP;/*Default: the counter mode of timer 2 is TIM_COUNTERMODE_UP*/ htime2.Init.Period = 5000; htime2.Init.ClockDivision = TIM_CLOCKDIVISION_DIV1; /*Initialized the timer 2*/ if(HAL_TIM_PWM_Init(&htime2) != HAL_OK){ Error_handler(); } /*Setting the output capture for channel*/ ichannelConfig.OCMode = TIM_OCMODE_PWM1; /*! Select the PWM output mode*/ ichannelConfig.Pulse = (htime2.Init.Period * 40U)/100U; ichannelConfig.OCPolarity = TIM_OCPOLARITY_HIGH; if(HAL_TIM_PWM_ConfigChannel(&htime2, &ichannelConfig, TIM_CHANNEL_1) != HAL_OK){ Error_handler(); } ichannelConfig.Pulse = (htime2.Init.Period * 50U)/100U; if(HAL_TIM_PWM_ConfigChannel(&htime2, &ichannelConfig, TIM_CHANNEL_2) != HAL_OK){ Error_handler(); } ichannelConfig.Pulse = (htime2.Init.Period * 60U)/100U; if(HAL_TIM_PWM_ConfigChannel(&htime2, &ichannelConfig, TIM_CHANNEL_3) != HAL_OK){ Error_handler(); } ichannelConfig.Pulse = (htime2.Init.Period * 70U)/100U; if(HAL_TIM_PWM_ConfigChannel(&htime2, &ichannelConfig, TIM_CHANNEL_4) != HAL_OK){ Error_handler(); } }/*TIM2_Init*/ /** * @brief Output Compare callback in non-blocking mode * @param htim TIM OC handle * @retval None */ void HAL_TIM_OC_DelayElapsedCallback(TIM_HandleTypeDef *htim){ uint32_t temp = 0; if(htim->Channel == HAL_TIM_ACTIVE_CHANNEL_1){ temp = __HAL_TIM_GET_COMPARE(htim, TIM_CHANNEL_1); __HAL_TIM_SET_COMPARE(htim, TIM_CHANNEL_1, temp + 25000U); } else if(htim->Channel == HAL_TIM_ACTIVE_CHANNEL_2){ temp = __HAL_TIM_GET_COMPARE(htim, TIM_CHANNEL_2); __HAL_TIM_SET_COMPARE(htim, TIM_CHANNEL_2, temp + 12500U); } else if(htim->Channel == HAL_TIM_ACTIVE_CHANNEL_3){ temp = __HAL_TIM_GET_COMPARE(htim, TIM_CHANNEL_3); __HAL_TIM_SET_COMPARE(htim, TIM_CHANNEL_3, temp + 6250U); } else if(htim->Channel == HAL_TIM_ACTIVE_CHANNEL_4){ temp = __HAL_TIM_GET_COMPARE(htim, TIM_CHANNEL_4); __HAL_TIM_SET_COMPARE(htim, TIM_CHANNEL_4, temp + 3125U); } else{ /*Do nothing*/ } } /** * @fn GPIO_Init() * @brief Initialized the GPIO A to toggle the LED */ void GPIO_Init(){ igpio.Mode = GPIO_MODE_OUTPUT_PP; /*! Select the output mode for the pin of MCU*/ igpio.Pin = GPIO_PIN_12; /*! Select the pin number*/ igpio.Speed = GPIO_SPEED_FREQ_HIGH; /*! Select the speed*/ igpio.Pull = GPIO_PULLUP; /*! Select the */ /*Init*/ HAL_GPIO_Init(GPIOD, &igpio); }/*GPIO_Init*/