language
large_stringclasses
1 value
text
stringlengths
9
2.95M
C
/* * Copyright (c) 2002, Intel Corporation. All rights reserved. * Created by: rolla.n.selbak REMOVE-THIS AT intel DOT com * This file is licensed under the GPL license. For the full content * of this license, see the COPYING file at the top level of this * source tree. * Test pthread_cancel * It may return an error number of: * -[ESRCH] No thread could be found corresponding to that thread ID * It shall not return an error code of [EINTR] * * STEPS: * 1. Create a thread * 2. Wait 'till the thread has ended execution * 3. Send a cancel request to the thread (which isn't existing anymore) * 3. It should return an error code of [ESRCH], else test fails. * */ #include <pthread.h> #include <stdio.h> #include <errno.h> #include "posixtest.h" void *a_thread_func() { pthread_exit(0); return NULL; } int main() { pthread_t new_th; int ret; /* Create a new thread. */ if(pthread_create(&new_th, NULL, a_thread_func, NULL) != 0) { perror("Error creating thread\n"); return PTS_UNRESOLVED; } /* Wait for thread to finish execution. */ pthread_join(new_th, NULL); /* Try and cancel thread. It should return an error because it * already is canceled and doesn't exist anymore. */ ret=pthread_cancel(new_th); if(ret != 0) { if(ret == ESRCH) { printf("Test PASSED\n"); return PTS_PASS; } printf("Test FAILED: Returned error code other than [ESRCH]\n"); return PTS_FAIL; } printf("Test PASSED: *NOTE: Returned 0 on error, though standard states 'may' fail.\n"); return PTS_PASS; }
C
#include <stdio.h> #define LEN 30 struct string { char String[LEN]; } #define ITEM(T) \ _Generic((T), struct string \ : struct string, default \ : int, float \ : float, double \ : double, long \ : long)(T) int main(int argc, char **argv) { float x = 45.0f; long double y = ITEM(x); printf("%.17Lf\n", y); return 0; }
C
#include "sym_table.h" #include <string.h> #include <stdlib.h> #define MAX_SIZE_VAR 50 #define MAX_LENGTH_VAR 20 static Var val_array[MAX_SIZE_VAR]; static int var_num = 0; Var create_var(char *name,float value,int level) { //printf("create new var-------\n"); Var newvar = val_array[var_num]; //printf("111111111-------\n"); char *newname = malloc(MAX_LENGTH_VAR*sizeof(char)); //printf("2222222--------\n"); strcpy(newname,name); //printf("33333333-------\n"); newvar.name = newname; newvar.value = value; newvar.level = level; //printf("44444444-------\n"); val_array[var_num] = newvar; //printf("55555555--------\n"); var_num++; return newvar; } Var modify_var(char *name,float value) { //printf("modify a var-----\n"); Var oldvar; //printf("1111111-----\n"); int i; for(i=var_num-1;i>=0;i--) { Var temp = val_array[i]; if(strcmp(temp.name,name) == 0) { temp.value = value; val_array[i] = temp; oldvar = temp; break; } } return oldvar; } float get_var(char *name) { //printf("get the var------\n"); int i; for(i=var_num-1;i>=0;i--) { //printf("11111111\n"); Var temp = val_array[i]; //printf("22222222\n"); if(strcmp(temp.name,name) == 0) { //printf("33333333\n"); return temp.value; } //printf("44444444\n"); } //printf("55555555\n"); return 0.0; } void pop_var(int level_num) { //printf("delete the var-----\n"); //printf("print the array------\n"); //print(); int i; for(i=var_num-1;i>=0;i--) { if(val_array[i].level == level_num+1) var_num--; else break; } } /* void print() { for(int i=var_num-1;i>=0;i--) { printf("name: %s value: %f level: %d\n",val_array[i].name, val_array[i].value,val_array[i].level ); } }*/
C
#include<stdio.h> int checkPrime(int number); int checkArmStrong(int number); int main(){ int number,flag; printf("Enter a number:"); scanf("%d",&number); flag=checkPrime(number); if(flag==1) printf("Number is Prime\n"); else printf("NUmber is not prime\n"); flag=checkArmStrong(number); if(flag==1) printf("Number is Armstrong number.\n"); else printf("Number is not Armmstrong number.\n"); return 0; } int checkPrime(int n){ int i,flag; flag=1; for(i=2;i<=n/2;i++){ if(n%i==0) flag=0; break; } return flag; } int checkArmStrong(int n){ int number,temp,flag=1; number=n; int i=0; temp=n; int digit,sum; sum=0; while(n!=0){ n/=10; i++; } while(number!=0){ digit=number%10; sum+=pow(digit,i); number/=10; } if(sum==temp) return flag; }
C
/* * For each file specified on the command line, this program will * read the file, determine the left margin (minimum number of spaces * appearing on each non-trivial line), and then remove that number * of spaces from each line. Does not handle tabs. * * Used to compress long, formatted text files. Released into Public * Domain. * - Tim Kientzle */ #include <stdio.h> char inbuff[1000]; char tmpname[50]; char fname[50]; main() { FILE *fp,*tmp; int mintab; int i; long total; pflinit();total=0L; strcpy(tmpname,"UnTab_tmp_XXXXX"); mktemp(tmpname); unlink(tmpname); while (gets(fname)) { if(fp=fopen(fname,"r+")) { /* Copy from fp to tmp, and find out how much to trim */ mintab=1000; tmp=fopen(tmpname,"w"); while(fgets(inbuff,1000,fp)) { fputs(inbuff,tmp); for(i=0;inbuff[i]==' ';i++) ; if(i<mintab && inbuff[i]!=0 && inbuff[i]!='\n') mintab=i; } fclose(tmp); fclose(fp); printf("%s: Minimum tab = %d\n",fname,mintab); if(mintab!=0) { /* Now, copy from tmp to fp, deleting extra spaces */ fp=fopen(fname,"w"); tmp=fopen(tmpname,"r"); while(fgets(inbuff,1000,tmp)) { i=strlen(inbuff)-1; while(i>=0 && (inbuff[i]==' ' || inbuff[i]=='\n') ) i--; inbuff[++i]='\n'; inbuff[++i]='\0'; for(i=0;i<mintab && inbuff[i]!='\n' && inbuff[i]; i++) ; fputs(inbuff+i,fp); total +=i; } fclose(fp); fclose(tmp); } } else printf("%s: error #%d\n",fname,errno); } unlink(tmpname); printf("Total # leading spaces stripped: %ld\n",total); }
C
// Shell. #include "types.h" #include "user.h" #include "fcntl.h" // Parsed command representation #define EXEC 1 #define REDIR 2 #define PIPE 3 #define LIST 4 #define BACK 5 #define MAXARGS 10 struct cmd { int type; }; struct execcmd { int type; char *argv[MAXARGS]; char *eargv[MAXARGS]; }; struct redircmd { int type; struct cmd *cmd; char *file; char *efile; int mode; int fd; }; struct pipecmd { int type; struct cmd *left; struct cmd *right; }; struct listcmd { int type; struct cmd *left; struct cmd *right; }; struct backcmd { int type; struct cmd *cmd; }; int fork1 (void); // Fork but panics on failure. void panic (char *); struct cmd *parsecmd (char *); // Execute cmd. Never returns. void runcmd (struct cmd *cmd) { int p[2]; struct backcmd *bcmd; struct execcmd *ecmd; struct listcmd *lcmd; struct pipecmd *pcmd; struct redircmd *rcmd; if (cmd == 0) exit (); switch (cmd->type) { default: panic ("runcmd"); case EXEC: ecmd = (struct execcmd *) cmd; if (ecmd->argv[0] == 0) exit (); exec (ecmd->argv[0], ecmd->argv); printf (2, "exec %s failed\n", ecmd->argv[0]); break; case REDIR: rcmd = (struct redircmd *) cmd; close (rcmd->fd); if (open (rcmd->file, rcmd->mode) < 0) { printf (2, "open %s failed\n", rcmd->file); exit (); } runcmd (rcmd->cmd); break; case LIST: lcmd = (struct listcmd *) cmd; if (fork1 () == 0) runcmd (lcmd->left); wait (); runcmd (lcmd->right); break; case PIPE: pcmd = (struct pipecmd *) cmd; if (pipe (p) < 0) panic ("pipe"); if (fork1 () == 0) { close (1); dup (p[1]); close (p[0]); close (p[1]); runcmd (pcmd->left); } if (fork1 () == 0) { close (0); dup (p[0]); close (p[0]); close (p[1]); runcmd (pcmd->right); } close (p[0]); close (p[1]); wait (); wait (); break; case BACK: bcmd = (struct backcmd *) cmd; if (fork1 () == 0) runcmd (bcmd->cmd); break; } exit (); } int getcmd (char *buf, int nbuf) { printf (2, "$ "); memset (buf, 0, nbuf); gets (buf, nbuf); if (buf[0] == 0) // EOF return -1; return 0; } int main (void) { static char buf[100]; int fd; // Assumes three file descriptors open. while ((fd = open ("console", O_RDWR)) >= 0) { if (fd >= 3) { close (fd); break; } } // Read and run input commands. while (getcmd (buf, sizeof (buf)) >= 0) { if (buf[0] == 'c' && buf[1] == 'd' && buf[2] == ' ') { // Clumsy but will have to do for now. // Chdir has no effect on the parent if run in the child. buf[strlen (buf) - 1] = 0; // chop \n if (chdir (buf + 3) < 0) printf (2, "cannot cd %s\n", buf + 3); continue; } if (fork1 () == 0) runcmd (parsecmd (buf)); wait (); } exit (); } void panic (char *s) { printf (2, "%s\n", s); exit (); } int fork1 (void) { int pid; pid = fork (); if (pid == -1) panic ("fork"); return pid; } //PAGEBREAK! // Constructors struct cmd * execcmd (void) { struct execcmd *cmd; cmd = malloc (sizeof (*cmd)); memset (cmd, 0, sizeof (*cmd)); cmd->type = EXEC; return (struct cmd *) cmd; } struct cmd * redircmd (struct cmd *subcmd, char *file, char *efile, int mode, int fd) { struct redircmd *cmd; cmd = malloc (sizeof (*cmd)); memset (cmd, 0, sizeof (*cmd)); cmd->type = REDIR; cmd->cmd = subcmd; cmd->file = file; cmd->efile = efile; cmd->mode = mode; cmd->fd = fd; return (struct cmd *) cmd; } struct cmd * pipecmd (struct cmd *left, struct cmd *right) { struct pipecmd *cmd; cmd = malloc (sizeof (*cmd)); memset (cmd, 0, sizeof (*cmd)); cmd->type = PIPE; cmd->left = left; cmd->right = right; return (struct cmd *) cmd; } struct cmd * listcmd (struct cmd *left, struct cmd *right) { struct listcmd *cmd; cmd = malloc (sizeof (*cmd)); memset (cmd, 0, sizeof (*cmd)); cmd->type = LIST; cmd->left = left; cmd->right = right; return (struct cmd *) cmd; } struct cmd * backcmd (struct cmd *subcmd) { struct backcmd *cmd; cmd = malloc (sizeof (*cmd)); memset (cmd, 0, sizeof (*cmd)); cmd->type = BACK; cmd->cmd = subcmd; return (struct cmd *) cmd; } //PAGEBREAK! // Parsing char whitespace[] = " \t\r\n\v"; char symbols[] = "<|>&;()"; int gettoken (char **ps, char *es, char **q, char **eq) { char *s; int ret; s = *ps; while (s < es && strchr (whitespace, *s)) s++; if (q) *q = s; ret = *s; switch (*s) { case 0: break; case '|': case '(': case ')': case ';': case '&': case '<': s++; break; case '>': s++; if (*s == '>') { ret = '+'; s++; } break; default: ret = 'a'; while (s < es && !strchr (whitespace, *s) && !strchr (symbols, *s)) s++; break; } if (eq) *eq = s; while (s < es && strchr (whitespace, *s)) s++; *ps = s; return ret; } int peek (char **ps, char *es, char *toks) { char *s; s = *ps; while (s < es && strchr (whitespace, *s)) s++; *ps = s; return *s && strchr (toks, *s); } struct cmd *parseline (char **, char *); struct cmd *parsepipe (char **, char *); struct cmd *parseexec (char **, char *); struct cmd *nulterminate (struct cmd *); struct cmd * parsecmd (char *s) { char *es; struct cmd *cmd; es = s + strlen (s); cmd = parseline (&s, es); peek (&s, es, ""); if (s != es) { printf (2, "leftovers: %s\n", s); panic ("syntax"); } nulterminate (cmd); return cmd; } struct cmd * parseline (char **ps, char *es) { struct cmd *cmd; cmd = parsepipe (ps, es); while (peek (ps, es, "&")) { gettoken (ps, es, 0, 0); cmd = backcmd (cmd); } if (peek (ps, es, ";")) { gettoken (ps, es, 0, 0); cmd = listcmd (cmd, parseline (ps, es)); } return cmd; } struct cmd * parsepipe (char **ps, char *es) { struct cmd *cmd; cmd = parseexec (ps, es); if (peek (ps, es, "|")) { gettoken (ps, es, 0, 0); cmd = pipecmd (cmd, parsepipe (ps, es)); } return cmd; } struct cmd * parseredirs (struct cmd *cmd, char **ps, char *es) { int tok; char *q, *eq; while (peek (ps, es, "<>")) { tok = gettoken (ps, es, 0, 0); if (gettoken (ps, es, &q, &eq) != 'a') panic ("missing file for redirection"); switch (tok) { case '<': cmd = redircmd (cmd, q, eq, O_RDONLY, 0); break; case '>': cmd = redircmd (cmd, q, eq, O_WRONLY | O_CREATE, 1); break; case '+': // >> cmd = redircmd (cmd, q, eq, O_WRONLY | O_CREATE, 1); break; } } return cmd; } struct cmd * parseblock (char **ps, char *es) { struct cmd *cmd; if (!peek (ps, es, "(")) panic ("parseblock"); gettoken (ps, es, 0, 0); cmd = parseline (ps, es); if (!peek (ps, es, ")")) panic ("syntax - missing )"); gettoken (ps, es, 0, 0); cmd = parseredirs (cmd, ps, es); return cmd; } struct cmd * parseexec (char **ps, char *es) { char *q, *eq; int tok, argc; struct execcmd *cmd; struct cmd *ret; if (peek (ps, es, "(")) return parseblock (ps, es); ret = execcmd (); cmd = (struct execcmd *) ret; argc = 0; ret = parseredirs (ret, ps, es); while (!peek (ps, es, "|)&;")) { if ((tok = gettoken (ps, es, &q, &eq)) == 0) break; if (tok != 'a') panic ("syntax"); cmd->argv[argc] = q; cmd->eargv[argc] = eq; argc++; if (argc >= MAXARGS) panic ("too many args"); ret = parseredirs (ret, ps, es); } cmd->argv[argc] = 0; cmd->eargv[argc] = 0; return ret; } // NUL-terminate all the counted strings. struct cmd * nulterminate (struct cmd *cmd) { int i; struct backcmd *bcmd; struct execcmd *ecmd; struct listcmd *lcmd; struct pipecmd *pcmd; struct redircmd *rcmd; if (cmd == 0) return 0; switch (cmd->type) { case EXEC: ecmd = (struct execcmd *) cmd; for (i = 0; ecmd->argv[i]; i++) *ecmd->eargv[i] = 0; break; case REDIR: rcmd = (struct redircmd *) cmd; nulterminate (rcmd->cmd); *rcmd->efile = 0; break; case PIPE: pcmd = (struct pipecmd *) cmd; nulterminate (pcmd->left); nulterminate (pcmd->right); break; case LIST: lcmd = (struct listcmd *) cmd; nulterminate (lcmd->left); nulterminate (lcmd->right); break; case BACK: bcmd = (struct backcmd *) cmd; nulterminate (bcmd->cmd); break; } return cmd; }
C
#include <stdio.h> #include "structbib.h" typedef struct { char** string; int quantidade; int capacidade; } lista_string; lista_string* Criar(int cap){ typedef struct { char** string; int quantidade; int capacidade; } lista; lista* pl; pl = (lista*) malloc(sizeof(lista)); pl->capacidade = cap; pl->string = (char**) malloc(cap*sizeof(char**)); return(pl); }
C
#include "tscheme.h" static int get_char(FILE *stream) { int c = getc(stream); return c; } static void unget_char(int c, FILE *stream) { ungetc(c, stream); } static int peek_char(FILE *stream) { int c = get_char(stream); unget_char(c, stream); return c; } static bool delimiter_p(int c) { return isspace(c) || c == '(' || c == ')' || c == EOF; } static void skip_space(FILE *stream) { // printf("> skip_space\n"); int c; c = get_char(stream); while (isspace(c)) { c = get_char(stream); } unget_char(c, stdin); // printf("< skip_space\n"); } // [-+]?[0-9]+ static bool string_number_p(const char *s) { if (*s == '-' || *s == '+') { s++; } bool got_digit = false; while (isdigit(*s)) { got_digit = true; s++; } return got_digit && (*s == 0); } static object *read_symbol_or_number(FILE *stream) { char s[MAX_TOKEN_LEN + 1]; int i = 0; int c; while (!delimiter_p(c = get_char(stream))) { s[i++] = c; if (i >= MAX_TOKEN_LEN) { fatal("token length error"); } } s[i] = '\0'; object *obj; if (string_number_p(s)) { obj = make_number(s); } else { obj = make_symbol(s); } return obj; } object *read_string(FILE *stream) { // TODO escape char s[MAX_TOKEN_LEN + 1]; int i = 0; while (true) { int c = get_char(stream); if (c == EOF) { fatal("string terminate error"); } if (c == '\"') { break; } if (i >= MAX_TOKEN_LEN) { fatal("too long string"); } s[i++] = c; } s[i] = '\0'; return make_string(s); } object *read_list(FILE *stream) { skip_space(stream); int c = get_char(stream); if (c == ')') { return NIL; } INTERNAL_ERROR("can't read list"); } object *read() { FILE *stream = stdin; skip_space(stream); int c = get_char(stream); if (c == '\"') { return read_string(stream); } else if (c == '(') { return read_list(stream); } else if (c == ')') { fatal("extra close parenthesis"); } unget_char(c, stream); return read_symbol_or_number(stream); }
C
/* * main.c * * Created: 12/15/2016 9:22:55 PM * Author: Benjamin Sejdic & George Albert Florea */ #include "TestButtons.h" #include "../src/asf.h" #include "../delayFunctions.h" int main(void) { /* Initialize the SAM system */ SystemInit(); board_init(); sysclk_init(); pinMode(GREEN_BUTTON, INPUT); /* set green button as an input */ pinMode(YELLOW_BUTTON, INPUT); /* set yellow button as an input */ pinMode(RED_BUTTON, INPUT); /* set red button as an input */ //delayMicroseconds(200); pinMode(GREEN_LED, OUTPUT); /* set green led as an output */ pinMode(YELLOW_LED, OUTPUT); /* set yellow led as an output */ pinMode(RED_LED, OUTPUT); /* set red led as an output */ pinMode(UNLOCKED_LED, OUTPUT); /* set big led as an output */ //delayMicroseconds(200); digitalWrite(GREEN_LED, LOW); digitalWrite(YELLOW_BUTTON, LOW); digitalWrite(RED_BUTTON, LOW); digitalWrite(UNLOCKED_LED, LOW); //delayMicroseconds(200); while(1) { if(digitalRead(GREEN_BUTTON) == HIGH) { //delayMicroseconds(200); digitalWrite(GREEN_LED, HIGH); } else if(digitalRead(YELLOW_BUTTON) == HIGH) { //delayMicroseconds(200); digitalWrite(YELLOW_LED, HIGH); } else if(digitalRead(RED_BUTTON) == HIGH) { //delayMicroseconds(200); digitalWrite(RED_LED, HIGH); } //delayMicroseconds(500); digitalWrite(GREEN_LED, LOW); digitalWrite(YELLOW_BUTTON, LOW); digitalWrite(RED_BUTTON, LOW); } }
C
#include <stdint.h> #include <stdio.h> #include <util/delay.h> #include <avr/io.h> #include "lcd_driver.h" #include "port_macros.h" #include "go2.c" int main() { // Initializing the buttons unsigned int last_left_button_state = (PINB & (1 << 1)); unsigned int left_button_pressed = 0; unsigned int last_right_button_state = (PINB & (1 << 5)); unsigned int right_button_pressed = 0; unsigned int last_middle_button_state = (PINB & (1 << 4)); int i; int p; DDRD |= (1 << 1); //configure pin as output // Aware i can do all of these next few lines in 2 lines but this robot is so fucky and just was not working when i did it all like this //DDRB &= ~ (50); //PORTB |= 50 // Left Button DDRB &= ~(1 << 1); PORTB |= (1 << 1); //Right Button DDRB &= ~(1 << 5); PORTB |= (1 << 5); //Middle Button DDRB &= ~(1 << 4); PORTB |= (1 << 4); char constants[2][4][8] = {{"slow ", "med ", "fast "}, {"fw ", "rv ", "cw ", "ccw "}}; // List of the options on the LCD int commands[4][3] = {}; // Empty list that gets filled with instructions as you enter them initialize_LCD_driver(); LCD_execute_command(TURN_ON_DISPLAY); uint8_t iter = 0; uint8_t done = 0; while (1) { LCD_execute_command(CLEAR_DISPLAY); uint8_t spd = 0; // Holds speed uint8_t step = 0; // the current step of whats being chosen : 0 is speed, 1 is direction, 2, is duration, 3 is choosing to enter another command uint8_t dir = 0; // Direction uint8_t val = 0; // Temp variable, theoretically i could rewrite all of this code only using this one variable but it works right now and we dont really care about how // much memory were using yet LCD_print_String(constants[0][0]); // Sets up the lcd to print the first option // Choosing the speed while (1) { if (done) { break; } // To show the current value the user is selecting. //Pulser for left button -- Taken from lab 7 if ((PINB & (1 << 1)) != last_left_button_state) { if ((PINB & (1 << 1)) == 0) { left_button_pressed = 1; } last_left_button_state = (PINB & (1 << 1)); } else { left_button_pressed = 0; } //Pulser for right button if ((PINB & (1 << 5)) != last_right_button_state) { if ((PINB & (1 << 5)) == 0) { right_button_pressed = 1; } last_right_button_state = (PINB & (1 << 5)); } else { right_button_pressed = 0; } // Middle button code, I put all of the functionality in here and not in the other two above for no reason. I was rushing if ((PINB & (1 << 4)) != last_middle_button_state) { if ((PINB & (1 << 4)) == 0) { LCD_execute_command(CLEAR_DISPLAY); step += 1; // Every time the middle button is pressed it will go to the next option to chose so it has to increment step switch (step) // Different functionality for each option { case 1: commands[iter][0]=val; val = 0; LCD_print_String(constants[1][val]); break; case 2: commands[iter][1]= val; val = 0; LCD_print_hex16(val); break; case 3: commands[iter][2] = val; spd = dir = val = 0; if (iter < 3) { LCD_print_String("addY/N"); // Asks to add another command if yes then itll go back to the top of this huge loop otherwise } else { LCD_print_hex16(commands[0][0]); int i; for (i = 0; i <= iter; i++) // It goes here, and does a for loop with each of the instructions here { go(commands[i][0], commands[i][1], commands[i][2]); // This is the function that will do the commands, you dont have to keep it as "go()" } done = 1; } break; default: break; } } last_middle_button_state = (PINB & (1 << 4)); } // A pressed if (left_button_pressed == 1) // This just toggles left through the options { if (val > 0) { val -= 1; } LCD_execute_command(CLEAR_DISPLAY); if (step < 2) { LCD_print_String(constants[step][val]); } else if (step == 2) { LCD_print_hex16(val); } else { iter++; break; } } //C pressed -- Toggles right through the options if (right_button_pressed == 1) { if (step < 2) { if (val < (step ? 3 : 2)) { val += 1; } LCD_execute_command(CLEAR_DISPLAY); LCD_print_String(constants[step][val]); } else if (step == 2) { val++; LCD_execute_command(CLEAR_DISPLAY); LCD_print_hex16(val); } else { LCD_print_hex16(commands[0][0]); int p; for (p = 0; p <= iter; p++) { LCD_execute_command(CLEAR_DISPLAY); LCD_print_hex16(p); go(commands[p][0], commands[p][1], commands[p][2]); } done = 1; } } _delay_us(10000); // really high delay so i dont have to worry about debouncing the buttons } } return 0; }
C
/* tpblockscope3.c: block scope test for switch */ int main() { int a = 1; int b = 1; int c = 2; switch (a) { case 0: { int a = 20; int b = 30; a = a + 1; b = 10; c = a + b; } break; case 1: { int a = 50; int b = 60; a = a + 1; b = 20; c = a + b; } break; default: break; } c = c + a; printf("%d \n", c); }
C
#ifndef MOTORS_H #define MOTORS_H #include "mseduino.h" #include "hall.h" #define FOREVER ~(0(size_t)) #define TURN_TICKS 6 #define MOTOR_LEFT_A J28 #define MOTOR_LEFT_B J26 #define MOTOR_RIGHT_A J25 #define MOTOR_RIGHT_B J24 #define CLIMB_MOTOR_A J22 #define CLIMB_MOTOR_B J21 #define LEFT_REVERSE 1 #define LEFT_FORWARD 2 #define RIGHT_FORWARD 3 #define RIGHT_REVERSE 4 #define CLIMB_FORWARD 5 #define CLIMB_REVERSE 6 #define S_FORWARD 225 #define S_SPIN 175 #define S_REVERSE S_FORWARD #define S_SEARCH 125 #define S_STOP 250 #define S_CLIMB 250 typedef enum { STOPPED, FORWARD, REVERSE } MotorState; typedef enum { CW, // Counterclockwise CCW // Clockwise } Rotation; #define STOP_TIME_DEFAULT 50 size_t STOP_TIME = STOP_TIME_DEFAULT; MotorState left_motor_state = STOPPED; MotorState right_motor_state = STOPPED; uint8_t ticks_target = 0; uint8_t speed = 0; // Motor Setup void setup_motors() { ledcAttachPin(MOTOR_LEFT_A, LEFT_REVERSE); ledcAttachPin(MOTOR_LEFT_B, LEFT_FORWARD); ledcAttachPin(MOTOR_RIGHT_A, RIGHT_FORWARD); ledcAttachPin(MOTOR_RIGHT_B, RIGHT_REVERSE); ledcSetup(LEFT_REVERSE, 20000, 8); ledcSetup(LEFT_FORWARD, 20000, 8); ledcSetup(RIGHT_FORWARD, 20000, 8); ledcSetup(RIGHT_REVERSE, 20000, 8); ledcAttachPin(CLIMB_MOTOR_A, CLIMB_FORWARD); ledcAttachPin(CLIMB_MOTOR_B, CLIMB_REVERSE); ledcSetup(CLIMB_FORWARD, 20000, 8); ledcSetup(CLIMB_REVERSE, 20000, 8); } // Get the reverse of the current motor direction MotorState reverse_of(MotorState dir) { switch (dir) { case STOPPED: return STOPPED; case FORWARD: return REVERSE; case REVERSE: return FORWARD; } } // Start the climbing motor void climb() { ledcWrite(CLIMB_FORWARD, S_CLIMB); } // Stop the climbing motor void stop_climb() { ledcWrite(CLIMB_FORWARD, 0); } // Start driving the bot in the specified directions // for a certain number of hall ticks at a specified speed void start_drive(MotorState left_dir, MotorState right_dir, size_t ticks, uint8_t speed) { reset_hall_ticks(); ticks_target = ticks; left_motor_state = left_dir; right_motor_state = right_dir; switch (left_dir) { case FORWARD: ledcWrite(LEFT_FORWARD, speed); break; case REVERSE: ledcWrite(LEFT_REVERSE, speed); break; } switch (right_dir) { case FORWARD: ledcWrite(RIGHT_FORWARD, speed); break; case REVERSE: ledcWrite(RIGHT_REVERSE, speed); break; } } // Drive forward so many hall ticks void drive_forward(size_t ticks) { start_drive(FORWARD, FORWARD, ticks, S_FORWARD); } // Reverse so many hall ticks void reverse(size_t ticks) { start_drive(REVERSE, REVERSE, ticks, S_REVERSE); } // Spin the robot in the specified direction // at a specific speed for so many hall ticks void spin(size_t ticks, uint8_t speed, Rotation rot) { if(rot == CCW) { start_drive(REVERSE, FORWARD, ticks, speed); } else { start_drive(FORWARD, REVERSE, ticks, speed); } } // Check to see if the robot is stopped bool stopped() { return left_motor_state == STOPPED && right_motor_state == STOPPED; } size_t stop_time = 0; bool stopping = false; // Stop the driving motors void stop_motors() { ledcWrite(LEFT_FORWARD, 0); ledcWrite(LEFT_REVERSE, 0); ledcWrite(RIGHT_FORWARD, 0); ledcWrite(RIGHT_REVERSE, 0); left_motor_state = STOPPED; right_motor_state = STOPPED; } // Stop the robot by quickly reversing the motors void stop() { reset_hall_ticks(); if(stopped()) { return; } stopping = true; stop_time = millis() + STOP_TIME; MotorState left_dir = reverse_of(left_motor_state); MotorState right_dir = reverse_of(right_motor_state); left_motor_state = left_dir; right_motor_state = right_dir; switch (left_dir) { case FORWARD: ledcWrite(LEFT_FORWARD, S_STOP); break; case REVERSE: ledcWrite(LEFT_REVERSE, S_STOP); break; } switch (right_dir) { case FORWARD: ledcWrite(RIGHT_FORWARD, S_STOP); break; case REVERSE: ledcWrite(RIGHT_REVERSE, S_STOP); break; } } // The drive maintence function // when the robot drives enough hall ticks // this function will stop the robot void drive() { if(left_motor_state == STOPPED && right_motor_state == STOPPED) { return; } if(left_hall_ticks > ticks_target || right_hall_ticks > ticks_target) { stop(); } if(stopping && millis() > stop_time) { stopping = false; stop_motors(); } } #endif
C
#include "deqll.h" #include <stdio.h> #include <stdlib.h> #include <assert.h> // DO NOT MODIFY THIS STRUCTURE struct dllnode { int item; struct dllnode *prev; struct dllnode *next; }; // DO NOT MODIFY THIS STRUCTURE struct dequeue { struct dllnode *front; struct dllnode *back; }; // dequeue_create() creates a new empty queue // effects: allocates memory (client must call dequeue_destroy) struct dequeue *dequeue_create(void) { struct dequeue *q = malloc(sizeof(struct dequeue)); q->front = NULL; // set null pointers q->back = NULL; // set null pointers return q; } // dequeue_is_empty(q) determines if double ended queue q is empty // time: O(1) bool dequeue_is_empty(const struct dequeue *q) { return q->front == NULL; // check whether the front is null or not } // dequeue_front(q) returns the front item in the double ended queue q // requires: double ended queue is not empty // time: O(1) int dequeue_front(const struct dequeue *q) { assert(q->front);// check whether the front pointer is null or not assert(!dequeue_is_empty(q)); return q->front->item; // return the item } // dequeue_back(q) returns the back item in the double ended queue q // requires: double ended queue is not empty // time: O(1) int dequeue_back(const struct dequeue *q) { assert(q->back); //check whether the back pointer is null or not assert(!dequeue_is_empty(q)); return q->back->item; // return the item } // dequeue_remove_front(q) returns and removes the front item from q // requires: double ended queue is not empty // effects: modifies q // time: O(1) int dequeue_remove_front(struct dequeue *q) { assert(q->front); int retval = q->front->item; // return value struct dllnode *backup = q->front; // to free create dummy pointer q->front = q->front->next; // iterate if(q->front != NULL){ q->front->prev = NULL; }else{ q->back = NULL; } free(backup); return retval; } // dequeue_remove_back(q) returns and removes the back item from q // requires: double ended queue is not empty // effects: modifies q // time: O(1) int dequeue_remove_back(struct dequeue *q) { assert(q->back); assert(!dequeue_is_empty(q)); int retval = q->back->item; // dummy pointer to free struct dllnode *backup = q->back; // remove the last one q->back = q->back->prev; if( q->back != NULL){ q->back->next = NULL; }else{ q->front = NULL; } free(backup); return retval; } // dequeue_add_front(item, q) adds item to the front of q // effects: modifies q // time: O(1) void dequeue_add_front(int item, struct dequeue *q) { // create the node that will be added struct dllnode *node = malloc(sizeof(struct dllnode)); node->item = item; node->next = NULL; node->prev = NULL; // add if (q->front == NULL) { q->back = node; } else { q->front->prev = node; node->next = q->front; } q->front = node; } // dequeue_add_back(item, q) adds item to the back of queue q // effects: modifies q // time: O(1) void dequeue_add_back(int item, struct dequeue *q){ // create the node that will be added struct dllnode *node = malloc(sizeof(struct dllnode)); node->item = item; node->next = NULL; node->prev = NULL; // add if (q->front == NULL) { q->front = node; } else { node->prev = q->back; q->back->next = node; } q->back = node; } // dequeue_destroy(q) frees all memory for q // requires: q must be from a previous malloc // effects: q is no longer valid void dequeue_destroy(struct dequeue *q) { // kill all items while (!dequeue_is_empty(q)) { dequeue_remove_front(q); } // kil the wrapper free(q); } // DO NOT MODIFY THIS FUNCTION // dequeue_print(q) prints the contents of q // effects: prints to output void dequeue_print(const struct dequeue *q) { struct dllnode *temp = q->front; printf("Dequeue:\n"); printf("Front -> "); while (temp) { printf("%d -> ", temp->item); temp = temp->next; } printf("NULL\n"); temp = q->back; printf("Back -> "); while (temp) { printf("%d -> ", temp->item); temp = temp->prev; } printf("NULL\n"); }
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 */ /* Variables and functions */ unsigned int strlen (char const*) ; __attribute__((used)) static void strfmt( const char *str, char *strout) { unsigned int i,j ; for(i=0,j=0;i<=strlen(str);i++,j++) if((strout[j]=str[i])=='\t') { strout[j++]='\\'; strout[j]='t'; } }
C
#ifndef U_NODE_H #define U_NODE_H #ifdef __cplusplus extern "C" { #endif struct XNode { char ip[15]; int port; char name[256]; }; typedef struct XNode * XNodePtr; /*! \fn int node_from_string(const char * str, XNodePtr p) * \brief Create nodes from a XML string. * \param str a XML string. * \param p a node. * \return 0 for success, or -1 for fail. */ int node_from_string(const char * str, XNodePtr p); /*! \fn const char * node_to_string(XNodePtr p, char * str) * \brief Convert nodes to a XML string. * \param p a node. * \param str a XML string. * \return str for success, or NULL for fail. */ const char * node_to_string(XNodePtr p, char * str); #ifdef __cplusplus } #endif #endif /* U_NODE_H */
C
if (true) { print(true); } else { print(false); } int i = 0; while (i < 10) { print(i); i++; } int i = 0; int N = 2; while (i < N) { print("i"); print(i); int j = 0; while (j < N) { print("j"); print(j); int k = 0; while (k < N) { print("k"); print(k); k++; } j++; } i++; }
C
#include "lists.h" /** * insert_dnodeint_at_index - insert new node at a given index * @h: pointer to first node passed by reference * @idx: index in which is going to be inserted the node * @n: value to insert in that node * Return: address of new node on success otherwise NULL */ dlistint_t *insert_dnodeint_at_index(dlistint_t **h, unsigned int idx, int n) { unsigned int i; dlistint_t *temp = NULL, *save_pos = NULL, *new = malloc(sizeof(dlistint_t)); if (new == NULL || h == NULL || (*h == NULL && idx > 0)) return (NULL); temp = *h, new->n = n, new->prev = NULL, new->next = NULL; if (temp == NULL) { *h = new; return (new); } if (idx == 0) { new->next = *h; temp->prev = new; *h = new; return (new); } for (i = 0; i < idx && temp != NULL; i++) { if (i + 1 == idx) { save_pos = temp->next; if (save_pos == NULL) new->prev = temp; temp->next = new; } temp = temp->next; } if (i == idx) { temp->next = save_pos; if (save_pos != NULL) { temp->prev = temp->next->prev; temp->next->prev = temp; } return (new); } return (NULL); }
C
#include "ft_printf.h" void ft_format_p(int *count, va_list *argc) { unsigned long point; point = (unsigned long)va_arg (*argc, void *); write (1, "0x", 2); (*count) += 2; ft_putpoint(point, count); }
C
#include <stdio.h> int main() { int i; /* i : variable de type entier */ int j; /* j : variable de type entier */ i = 22; /* i vaut 22 */ j = i; /* on recopie la valeur de i dans j donc j vaut aussi 22 à présent */ printf ("i vaut %d\n", i); /* Affiche la valeur de i */ printf ("i + j vaut %d\n", i + j); /* Affiche la valeur de i + j */ return 0; } /* 1) Compile : gcc -o prog_name prog_name.c 2) Execute : ./prog_name */
C
#include <stdio.h> #include<string.h> #pragma warning (disable:4996) // ڷ н带 Է ޾Ƽ ġϸ α ޼ // ġ ޼ Բ 3ȸ н带 Է¹ް void main() { const char* my_password = "sonbc"; char input_password[30]; int index; const int max_counter = 3; for (index = 0; index < max_counter;index++) { // printf("н带 Էϼ: "); fputs("йȣ Էϼ: ", stdout); // scanf("%s", input_password); gets(input_password); if (!strcmp(my_password, input_password)) { puts("йȣ ġմϴ."); puts("α ϰڽϴ."); break; }else { printf("йȣ %dȸ ġմϴ.", index + 1); if (index == max_counter - 1) { printf("\n%dȸ ġǾǷ ӽ÷ װڽϴ.\n", index + 1); puts(" ߰ Ͽ йȣ 缳 ֽʽÿ"); break; } puts("ٽ Էϼ."); } } }
C
#include<stdio.h> main() { int i,j,k,n; int G[100][100],temp[100][100]; //freopen("in.txt","r",stdin); scanf("%d",&n); for(i=0; i<n; i++) for(j=0; j<n; j++) { scanf("%d",G[i]+j); temp[i][j]=G[i][j]; } for(i=0;i<n;i++) for(j=0;j<n;j++) for(k=0;k<n;k++) if(G[i][j]&&G[j][k]) temp[i][k]=1; for(i=0;i<n;i++) { for(j=0;j<n-1;j++) printf("%d ",temp[i][j]); printf("%d\n",temp[i][n-1]); } }
C
#include <sys/types.h> #include <sys/stat.h> #include <sys/uio.h> #include <unistd.h> #include <fcntl.h> #include <stdlib.h> /** * read_textfile - reads a text file and prints the contents to STDOUT * @filename: the filename * @letters: number of letters * Return: the number of letters read and printed, 0 on failure */ ssize_t read_textfile(const char *filename, size_t letters) { int f = -1, err = 0, len = 0; char *temp; if (!filename) return (0); temp = malloc(sizeof(char) * letters); if (!temp) return (0); f = open(filename, O_RDONLY); if (f < 0) { free(temp); return (0); } err = read(f, temp, letters); if (err < 0) { free(temp); return (0); } while (temp && temp[len]) len++; err = write(STDOUT_FILENO, temp, len); free(temp); close(f); if (err < 0) return (0); return ((ssize_t)err); }
C
/** * math sample * 2020-07-01 K.OHWADA */ // expm1: // computes the e (Euler's number, 2.7182818) raised to the given power arg, minus 1.0 // https://en.cppreference.com/w/c/numeric/math/expm1 #include <stdio.h> #include <stdlib.h> #include <math.h> /* * main */ int main(void) { for(int i=0; i<11; i++) { double x = (double)i; double y = expm1(x); printf(" expm1( %.1f) : %.3f \n", x, y); } return EXIT_SUCCESS; }
C
/* * lapack_dgttrf.c * *This program is a C interface to dgttrf. * * Written by Remi Delmas. * */ #include "../include/lapack_f77.h" #include "../include/lapack_enum.h" #include "../include/lapack_aux.h" void lapack_dgttrf(const int n, double * dl, double * d, double * du, double * du2, int * ipiv, int * info ) { #ifdef F77_INT F77_INT F77_n=n; int i_local; F77_INT F77_ipiv[n*1]; for(i_local=0;i_local<n*1;i_local++) { F77_ipiv[i_local]=(F77_INT) ipiv[i_local]; } F77_INT F77_info[1]; #else #define F77_n n #define F77_ipiv ipiv #define F77_info info #endif f77_dgttrf(&F77_n, dl, d, du, du2, F77_ipiv, F77_info); #ifdef F77_INT for(i_local=0;i_local<n*1;i_local++) { ipiv[i_local]=(int) F77_ipiv[i_local]; } info[0]=(int) F77_info[0]; #endif }
C
/*compile-errors:*/ /*compile-result:1*/ /*save-event:compile*/ #include<stdio.h> int main() { int y; scanf("%d",&y); //stores the year { if(y%4==0) //divisiblity by 4 { if(y%100==0) //divisiblity by 100 {if(y%400==0) //divisiblity by 400 printf("Leap Year"); else printf("Not Leap Year");} else printf("Leap Year"); } else printf("Not Leap Year"); } return 0; }
C
#include<stdio.h> int x,y,z; int find(int x,int y,int z); find(int x,int y,int z) { int i,t,s,days=0; if(x%4==0)t=1; else t=0; for(i=1;i<y;i++) { if(i==2)s=2-t; else s=0;days=days+30+i%2-s; } days=days+z; return(days); } void main() { int year,month,date,day;scanf("%d%d%d",&year,&month,&date); day=find(year,month,date); printf("这一天是该年的第%d天\n",day); }
C
#include <stdio.h> int main(int argc, char **argv) { int i; unsigned int val; argc--; argv++; if (!argc) { printf("Usage: bits hex-val\n"); return 1; } printf("\t\t"); for (i = 31; i >= 0; i--) { printf(" %2d", i); if (i && !(i&0x7)) printf(" | "); } printf("\n"); while (argc--) { sscanf(*argv, "%x", &val); argv++; printf("%0#10x\t", val); for (i = 31; i >= 0; i--) { printf(" %c", val&0x80000000 ? '*' : ' '); val <<= 1; if (i && !(i&0x7)) printf(" | "); } printf("\n"); } return 0; }
C
#include <stdlib.h> #include <stdio.h> #include <string.h> #define MAX 100 typedef struct{ char marca[30]; char placa[9]; char modelo[50]; int tipoMarcha; // 1=Auto, 2=Manual int qtdPortas; } Veiculo; Veiculo criarVeiculo(char* placa, char* modelo, char* marca, int qportas, int tmarcha){ Veiculo v; strcpy(v.marca, marca); strcpy(v.modelo, modelo); strcpy(v.placa, placa); v.qtdPortas = qportas; v.tipoMarcha = tmarcha; return v; } typedef struct{ int cont; Veiculo dados[MAX]; } Lista; Lista* criarLista(){ Lista *l; l = (Lista*)malloc(sizeof(Lista)); if(l != NULL){ l->cont = 0; } return l; } void destruirLista(Lista* l){ free(l); } int tamanhoLista(Lista* l){ if(l == NULL) return -1; else return l->cont; } int estahVaziaLista(Lista* l){ if(l == NULL) return -1; else return l->cont == 0; } int estaCheiaLista(Lista* l){ if(l == NULL) return -1; else return l->cont == MAX; } int inserirNoFinalLista(Lista* l, Veiculo v){ if(l==NULL) return 0; if(estaCheiaLista(l)) return 0; l->dados[l->cont] = v; l->cont++; return 1; } int inserirNoInicioLista(Lista* l, Veiculo v){ int i; if(l==NULL) return 0; if(estaCheiaLista(l)) return 0; for(i=l->cont-1; i>=0; i--){ l->dados[i+1] = l->dados[i]; } l->dados[0] = v; l->cont++; return 1; } int inserirNoMeioLista(Lista* l, Veiculo v, int posicao){ int i; if(l==NULL) return 0; if(estaCheiaLista(l)) return 0; for(i=l->cont-1; i>=posicao; i--){ l->dados[i+1] = l->dados[i]; } l->dados[posicao] = v; l->cont++; return 1; } int inserirOrdenado(Lista* l, Veiculo v){ int i, posicao; if(l==NULL) return 0; if(estaCheiaLista(l)) return 0; if(estahVaziaLista(l)) posicao = 0; else{ // Acha a posicao para inserir for(i=l->cont-1; i>=0 && (strcmp(l->dados[i].placa, v.placa) > 0); i--){ l->dados[i+1] = l->dados[i]; } posicao = i+1; } l->dados[posicao] = v; l->cont++; return 1; } void imprimirVeiculo(Veiculo v){ printf("=======================================\n"); printf("Veiculo: \n"); printf("\tPlaca: %s\n", v.placa); printf("\tMarca: %s\n", v.marca); printf("\tModelo: %s\n", v.modelo); printf("\tTipo: %s\n", v.tipoMarcha == 1 ? "AUTOMATICO" : "MANUAL"); printf("\t%d portas\n", v.qtdPortas); printf("=======================================\n\n"); } void imprimirDadosLista(Lista* l){ int i; if(l != NULL){ if(!estahVaziaLista(l)){ for(i=0; i<l->cont; i++){ imprimirVeiculo(l->dados[i]); } }else{ printf("Lista esta vazia!\n"); } }else{ printf("Lista nao foi criada!\n"); } } int buscaBinaria (char* x, Lista* l) { int inf,sup,meio; inf=0; sup=(l->cont-1); while (inf<=sup) { meio=(inf+sup)/2; if (strcmp(l->dados[meio].placa, x) == 0) return meio; else if (strcmp(l->dados[meio].placa, x) > 0) sup=meio-1; else inf=meio+1; } return -1; /* no encontrado */ }
C
#include <stdio.h> int main(){ int p[2][10] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}; int n, i, j, sum = 0, max = 0; for(i = 0; i < 10; i++){ scanf("%d", &p[0][i]); sum = sum + p[0][i]; } for(i = 0; i < 10; i++){ for(j = 0; j < i; j++){ if(p[0][i] == p[0][j]) p[1][j]++; } } for(i = 0; i < 10; i++){ if(p[1][i] > max) n = p[0][i]; } //for(i = 0; i < 10; i++) //printf("%d ", p[1][i]); printf("%d\n%d", sum/10, n); }
C
#ifndef __CONNECTION_H__ #define __CONNECTION_H__ #define MAX_REMOTE_CONNECTIONS_ALLOWED 1 /** Démarre le mode télécommande \param port Port sur lequel écouter password Mot de passe permettant de se logger \return 0 si tout est ok */ int start_remote_control( unsigned int port, char* password ); /** Arrête le mode télécommande */ void stop_remote_control(); #ifndef __COMMAND_INTERPRET_H__ /** Ajoute une nouvelle commande avec son handler \param command_name Chaine par laquelle la commande doit commencer command_desc Chaine décrivant la commande handler Le handler associé à la commande \return RCTRL_OK si tout est ok, RCTRL_CANNOT_ADD_COMMAND sinon */ int add_command( char* command_name, char* command_desc, int (*handler)( int, const char* ) ); #endif // __COMMAND_INTERPRET_H__ #endif // __CONNECTION_H__
C
// // pwm.c // cxg-60ewt // // Created by Leonid Mesentsev on 26/11/2019. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // #include <stm8s.h> #include <pwm.h> /****************************************************************************** * * Initialize PWM * in: mode, channels to use * * To generate the PWM signals the TIM2 peripheral must be configured as follows: * ● Output state enabled for each channel * ● Output compare active low for each channel * ● Preload register enabled for each channel * ● PWM output signal frequency = 125 Hz: * – The timer source clock frequency is 16 MHz (fCPU by default) and the prescaler is * set to 7 to obtain a TIM2 counter clock of 125 kHz (16000000 / 2^7 = 125000) * – PWM output signal frequency can be set according to the following equation: * PWM output signal frequency = TIM2 counter clock/(TIM2_ARR + 1) * (in our case TIM2_ARR = 999, so PWM output signal frequency is 125 Hz) (125000 / (999 + 1) = 125) * ● PWM mode for each channel. To obtain a different PWM duty cycle value on each channel the TIM2_CCRxx register must be set according to this equation: * Channel x duty cycle = [TIM2_CCRxx/(TIM2_ARR + 1)] * 100 * (CCRXX / (999 + 1)) * 100 = 0.1 * CCRXX, поэтому duty_cycle в функции PWM_duty умножен на 10 (стр. 96) * * ПОМНИТЕ: если вы изменили ARR, не забудьте пересчитать CCRXX! Прежде чем изменять значения в этом файле, внимательно прочтите и пймите формулу, * наче PWM может не завестись, что приведет к 0 на управляющем пине и, следовательно, к неконтролируемому нагреву ТЭНа. * * By default we have: * – Channel 1: TIM2_CCR1x register value is 500, so channel 1 of TIM2 generates a PWM signal with a frequency of 2 KHz and a duty cycle of 50%. * – Channel 2: TIM2_CCR2x register value is 750, so channel 2 of TIM2 generates a PWM signal with a frequency of 2 KHz and a duty cycle of 75%. * – Channel 3: TIM2_CCR3x register value is 250, so channel 3 of TIM2 generates a PWM signal with a frequency of 2 KHz and a duty cycle of 25%. * */ void PWM_init(uint8_t ch) { TIM2_PSCR = 7; /* 16000000 / (2^7 * (1 + 999)) = 125 Hz */ int _TIM2_ARR = 999; /* 125 Hz */ TIM2_ARRH = (_TIM2_ARR >> 8) & 0xff; TIM2_ARRL = _TIM2_ARR & 0xff; if (ch & PWM_CH1) { TIM2_CCR1H = 0; TIM2_CCR1L = 0; TIM2_CCMR1 = 0x68; /* PWM mode 1, use preload register */ TIM2_CCER1 |= 0x01; /* output enable, normal polarity */ } if (ch & PWM_CH2) { TIM2_CCR2H = 0; TIM2_CCR2L = 0; TIM2_CCMR2 = 0x68; TIM2_CCER1 |= 0x10; } if (ch & PWM_CH3) { TIM2_CCR3H = 0; TIM2_CCR3L = 0; TIM2_CCMR3 = 0x68; TIM2_CCER2 |= 0x01; } TIM2_CR1 = 0x81; /* use TIM2_ARR preload register, enable */ } /****************************************************************************** * * Set duty count * in: channel(s), new duty count (times 1/2 microsecond) */ void PWM_duty(uint8_t ch, uint16_t duty) { duty = duty * 10; uint8_t dH, dL; dH = (duty >> 8) & 0xff; dL = duty & 0xff; if (ch & PWM_CH1) { TIM2_CCR1H = dH; TIM2_CCR1L = dL; } if (ch & PWM_CH2) { TIM2_CCR2H = dH; TIM2_CCR2L = dL; } if (ch & PWM_CH3) { TIM2_CCR3H = dH; TIM2_CCR3L = dL; } }
C
#include <stdio.h> #include <stdlib.h> struct Node { int data; struct Node*left; struct Node*right; }; struct Node*root=NULL; void insert() { int key; struct Node*p=(struct Node*)malloc(sizeof(struct Node)); struct Node*r,*t=root; printf("Enter the value\n"); scanf("%d",&key); p->data=key; p->left=NULL; p->right=NULL; if(root==NULL) { root=p; return; } else { while(t) { r=t; if(key<t->data) t=t->left; else if(key>t->data) t=t->right; else { printf("Already exist\n"); return ; } } if(key>r->data) r->right=p; else r->left=p; } return p; } void search( ) { int key,flag=0; struct Node*p=(struct Node*)malloc(sizeof(struct Node)); struct Node*r,*t=root; printf("Enter the value\n"); scanf("%d",&key); p->data=key; p->left=NULL; p->right=NULL; while(t) { if(key==t->data) { flag=1; break; } else if(key>t->data) t=t->right; else t=t->left; } if(flag==1) printf("Found\n"); else printf("Not Found\n"); } void inOrder(struct Node*p) { if(p) { inOrder(p->left); printf("%d\t",p->data); inOrder(p->right); } } void preOrder(struct Node*p) { if(p) { printf("%d\t",p->data); preOrder(p->left); preOrder(p->right); } } void postOrder(struct Node*p) { if(p) { postOrder(p->left); postOrder(p->right); printf("%d\t",p->data); } } struct Node *Rinsert( struct Node*p,int key) { struct Node*t=NULL; if(p==NULL) { t=(struct Node*)malloc(sizeof(struct Node)); t->data=key; t->right=t->left=NULL; return t; } if(key<p->data) p->left=Rinsert(p->left,key); else if(key>p->data) p->right=Rinsert(p->right,key); return p; }; int Height(struct Node*p) { int x,y; if(p==NULL) return 0; x=Height(p->left); y=Height(p->right); return x>y?x+1:y+1; } struct Node*Inpre(struct Node*p) { while(p && p->right!=NULL) p=p->right; return p; }; struct Node* InSucc(struct Node*p) { while(p && p->left!=NULL) p=p->left; return p; }; struct Node* Delete(struct Node*p,int key) { struct Node*q; if(p==NULL) return NULL; if(p->left==NULL && p->right==NULL) { if(p==root) root=NULL; free(p); return NULL; } if(key<p->data) p->left=Delete(p->left,key); else if(key>p->data) p->right=Delete(p->right,key); else { if(Height(p->left)>Height(p->right)) { q=Inpre(p->left); p->data=q->data; p->left=Delete(p->left,q->data); } else { q=InSucc(p->right); p->data=q->data; p->right=Delete(p->right,q->data); } } return p; }; int main() { int n,i,ch; printf("Create a Binary Tree\nEnter the number of element\n"); scanf("%d",&n); for(i=0;i<n;i++) { insert(); } while(1) { printf("\n1.Insert Using Recursion\n2.Delete\n3.PREORDER\n4.INORDER\n5.POSTORDER\n6.Search\n7.Insert\n100.Exit\nEnter your choice\n"); scanf("%d",&ch); switch(ch) { case 1: { int key; printf("Enter the value\n"); //work if already root is present scanf("%d",&key); //Or first call to make root Rinsert(root,key); // root=Rinsert(root,key) } break; case 4: inOrder(root); break; case 3: preOrder(root); break; case 5: postOrder(root); break; case 6: search(); break; case 2: { int key; printf("Enter the element to delete\n"); scanf("%d",&key); Delete(root,key); } break; case 7: insert(); break; default:printf("InValid Input\n"); break; case 100: exit(0); } } return 0; }
C
#include <stdio.h> #include <stdlib.h> #include <string.h> int main(int argc, char *argv[]) { char buff[30]; strcpy(buff,argv[1]); printf("\n%s\n",buff); return 0; }
C
#include "ftp.h" int FtpLogByteSizeSet(int Bytesize) { if(Bytesize > MAXBZ) return 0; ByteSize = Bytesize; return 1; } void get_current_time(char* time_str) { time_t timep; struct tm * p; time(&timep); p = localtime(&timep); sprintf(time_str,"%d%d%d%d%d",1900+p->tm_year,p->tm_mon,p->tm_mday,p->tm_hour,p->tm_min); return; } void get_current_date(char* date) { time_t timep; struct tm * p; time(&timep); p = localtime(&timep); sprintf(date,"%d%d%d",1900+p->tm_year,p->tm_mon,p->tm_mday); return; } int FtpCreatLogFile(char* filename) { char stime[MAX]; memset(&stime, '\0', MAX); int fd = 0; if(filename == NULL) return 0x29; get_current_date(stime); if(strlen(stime) <= 0) return 0x29; sprintf(filename, "%s%s%s", FTP_LOG, LOGNAME , stime); fd = open(filename, O_CREAT | O_APPEND);//problem here if(fd == -1) return 0x17; close(fd); return 0; } int FtpOpenLogFile(char* filename) { int iRet = 0; iRet = open(filename, O_RDWR); if(iRet < 0) return -1; return iRet; } int FtpCloseLogFile(int fileid) { int iRet = 0; struct flock lock; lock.l_whence = SEEK_SET; lock.l_start = 0; lock.l_len = 0; lock.l_type = F_UNLCK; fcntl(fileid, F_SETLKW, &lock); iRet = close(fileid); if(iRet < 0) return iRet; return 0; } int FtpCountBuff(char *buff) { int iRet = 0; if(buff == NULL) return -1; iRet = sizeof(buff); return iRet; } int FtpCountFile(int filed) { int iRet = 0; struct stat buf; iRet = fstat(filed,&buf); if(iRet == 0) { iRet = buf.st_size; return iRet; } return -1; } int spacecoute(char* buff) { int iRet = 0; if(buff == NULL) return -1; iRet = strlen(buff); if(iRet <= 0) return -1; if(isalnum(buff[iRet-2])&&isalnum(buff[iRet-1])&& (iRet > ByteSize)) { iRet--; while(isalnum(buff[iRet])) iRet--; buff[++iRet]=0; iRet = strlen(buff); } return iRet; } int formatstr(char* buff) { int iRet = 0; if(buff == NULL) return -1; iRet = strlen(buff); if(iRet <= 0) return -1; return iRet; } int countenter(char *buff) { int iRet = 0; int iResult = 0; if(buff == NULL) return -1; while(buff[iResult]) { if(buff[iResult]=='\n') iRet++; iResult++; } return iRet; } int count(char *buff) { int iRet = 0; int iResult = 0; if(buff == NULL) return -1; iRet = sizeof(buff); if(iRet <= 0) return -1; iRet--; while(buff[iRet]!='\n') { iResult++; iRet--; } return iResult; } int FWrite(int fd, char* buff) { int iRet = 0; int i = 0; int ibyte = 0; char str[MAXBZ]; char word[MAXBZ*2]; char pp[MAX]; FILE *fp; char fill[MAXBZ]; memset(str, '\0', MAXBZ); memset(word, '\0', MAXBZ*2); memset(pp, '\0', MAX); memset(fill, '\0', MAXBZ); if(buff == NULL) return -1; fp = fdopen(fd,"a+"); if(fp == NULL) return -1; fseek(fp,0,SEEK_END); iRet = formatstr(buff); if(iRet>ByteSize) { while(ibyte != strlen(buff)) { memset(str, 0, sizeof(str)); i = strlen(buff) - ibyte; if(i < ByteSize) { memcpy(str,&(buff[ibyte]),i); } else { memcpy(str,&(buff[ibyte]),ByteSize); } ibyte += strlen(str); iRet = write(fd,str,strlen(str)); write(fd,"\n",1); if(iRet == -1) return -1; } } else { iRet = 0; iRet = write(fd,buff,strlen(buff)); if( iRet == -1) return -1; write(fd,"\n",1); if( iRet == -1) return -1; } return 0; } int FtpLogWrite(int* fd, char* buff) { int iRet = 0; int iResult = 0; char filename[MAX]; struct flock lock; memset(filename,0, sizeof(filename)); lock.l_whence = SEEK_SET; lock.l_start = 0; lock.l_len = 0; lock.l_type = F_WRLCK; if(fd == NULL) return -1; if(buff == NULL) return -1; if( (iRet = fcntl(*fd, F_SETLKW, &lock)) < 0 ) return -1; iRet = FtpCountBuff(buff); iResult = FtpCountFile(*fd); if(iRet+iResult > FileSize) { iRet=FtpCloseLogFile(*fd); //error if(iRet == -1) { return -1; } iRet = FtpCreatLogFile(filename); if(iRet == -1 ) { return -1; } *fd = FtpOpenLogFile(filename); //error if(*fd == -1) { return -1; } iResult = FWrite(*fd,buff); } else { iResult = FWrite(*fd,buff); } if(iResult != -1) return 0; return iRet; } void record_log(int opt, char* target_name, unsigned char result) { char stime[MAX]; char log_info[512]; memset(log_info, '\0', 512); memset(stime, '\0', MAX); get_current_time(stime); switch(opt) { case LSTARTUP: sprintf(log_info, "%s%s%s%s\n", TIMECHAR, stime, OPTCHAR, "ftp process start-up"); write_log(log_info); break; case LPROCESSEXITSTART: sprintf(log_info, "%s%s%s%s\n", TIMECHAR, stime, OPTCHAR, "process exit start"); write_log(log_info); break; case LPROCESSEXIT: if(result == 0) { sprintf(log_info, "%s%s%s%s\n", TIMECHAR, stime, OPTCHAR, "process exit"); } else { sprintf(log_info, "%s%s%s%s%s%s%0x\n", TIMECHAR, stime, OPTCHAR, "process exit", RESULTCHAR, LERROR, result); } write_log(log_info); break; case LCOPYSTART: sprintf(log_info, "%s%s%s%s%s%s\n", TIMECHAR, stime, OPTCHAR, "copy start", FILENAMECHAR, target_name); write_log(log_info); break; case LCOPYEND: if(result == 0) { sprintf(log_info, "%s%s%s%s%s%s%s%s\n", TIMECHAR, stime, OPTCHAR, "copy end", FILENAMECHAR, target_name, RESULTCHAR, SUCCESSED); } else { sprintf(log_info, "%s%s%s%s%s%s%s%s%0x\n", TIMECHAR, stime, OPTCHAR, "copy end", FILENAMECHAR, target_name, RESULTCHAR, LERROR, result); } write_log(log_info); break; case LCANCELSTART: sprintf(log_info, "%s%s%s%s\n", TIMECHAR, stime, OPTCHAR, "cancel start"); write_log(log_info); break; case LCANCELEND: if(result == 0) { sprintf(log_info, "%s%s%s%s%s%s\n", TIMECHAR, stime, OPTCHAR, "cancel end", RESULTCHAR, SUCCESSED); } else { sprintf(log_info, "%s%s%s%s%s%s%0x\n", TIMECHAR, stime, OPTCHAR, "cancel end", RESULTCHAR, LERROR, result); } write_log(log_info); break; case LPROCESSERROR: sprintf(log_info, "%s%s%s%s%s%s%0x\n", TIMECHAR, stime, OPTCHAR, "process error occured", RESULTCHAR, LERROR, result); write_log(log_info); break; default: break; } return; } void write_log(char* input_info) { struct flock lock; lock.l_whence = SEEK_SET; lock.l_start = 0; lock.l_len = 0; lock.l_type = F_UNLCK; if(input_info == NULL) return; FtpLogWrite(&log_fp, input_info); fcntl(log_fp, F_SETLKW, &lock); return; } int get_sem(key_t key, int* semid) { union semun sem ; sem.val = 0; *semid = semget(key, 0, 0); if (*semid == -1) return -1; return 0; } int get_env_var(void) { int rev = 0; int cmd_sem = 0 , sta_sem = 0; int shmid = 0 ,sta_id = 0; key_t shm_key = 0 , sta_key = 0; if((shm_key = ftok( FTP_PATH , 0 )) == (key_t)-1) //ftp's key create { return -1; } if((shmid = shmget( shm_key , sizeof(struct ST_SHM) , 0 )) == -1) { return -1; } cmd_shm_id = shmid; if((sta_key = ftok( FTP_PATH , 1 )) == (key_t)-1) //ftp's key create { return -1; } if((sta_id = shmget( sta_key , sizeof(struct ST_STATUS) , 0 )) == -1) { return -1; } sta_shm_id = sta_id; rev = get_sem(shm_key, &cmd_sem); if(rev) return rev; cmd_sem_id = cmd_sem; rev = get_sem(sta_key, &sta_sem); if(rev) return rev; sta_sem_id = sta_sem; if(pthread_mutex_init(&status_lock, NULL) != 0) { return 0x29; } if(pthread_mutex_init(&cancel_lock, NULL) != 0) { return 0x29; } if(pthread_mutex_init(&fileget_lock, NULL) != 0) { return 0x29; } return 0; } int create_tmpdir(void) { int rev = 0; rev = make_dir(TEMP_DIR1); if(rev) return rev; rev = make_dir(TEMP_DIR2); if(rev) return rev; return 0; } int make_logdir(void) { int rev = 0; rev = make_dir(FTP_LOG); if(rev) return rev; return 0; } int set_env(void) { int rev = 0; /*return's value*/ char filename[MAX]; memset(filename, '\0', MAX); rev = make_logdir(); if(rev) return rev; rev = FtpCreatLogFile(filename); if(rev) return rev; log_fp = FtpOpenLogFile(filename); if(log_fp < 0) return 0x17; rev = create_tmpdir(); if(rev) return rev; return 0; }
C
# include<stdio.h> # include<stdlib.h> int map[5][5]; int dir[4][2]={1,0,-1,0,0,1,0,-1}; struct node { int x,y; }; struct node queue[50],record[5][5]; void bfs() { int head,tail,i; struct node now,next; head=tail=0; now.x=queue[tail].x; now.y=queue[tail].y; tail++; while(head<tail) { now=queue[head++]; for(i=0;i<4;i++) { next.x=now.x+dir[i][0]; next.y=now.y+dir[i][1]; if(next.x>=0&&next.y>=0&&next.x<5&&next.y<5&&map[next.x][next.y]==0) { record[next.x][next.y].x=now.x; record[next.x][next.y].y=now.y; if(next.x==4&&next.y==4) return ; else { map[next.x][next.y]=1; queue[tail++]=next; } } } } } int main() { int i,j,k,m,n; struct node now; for(i=0;i<5;i++) for(j=0;j<5;j++) scanf("%d",&map[i][j]); now.x=0; now.y=0; map[0][0]=1; queue[0]=now; bfs(); k=0; queue[k].x=4; queue[k++].y=4; i=j=4; while(i!=0||j!=0) { m=i;n=j; i=record[m][n].x; j=record[m][n].y; queue[k].x=i; queue[k++].y=j; } for(i=k-1;i>=0;i--) printf("(%d, %d)\n",queue[i].x,queue[i].y); return 0; }
C
#include<stdio.h> #include<stdlib.h> typedef struct data { char ch; struct data *next; }data; typedef struct list { data *head, *tail; }list; void init(list *l); void enlist(list *l, char ch); void remov(list *l, char ch); int searchlist(list *l, char ch); int isempty(list *l); int charsearch(list *l, char ch); int length(list *l); void printlist(list *l);
C
int main() { int a[2][1000],i=0,j,c=1000,b=0,m[1000]={0}; while(1) { cin>>a[0][i]; if (cin.get() =='\n') break; i++; } i = 0; while(1) { cin>>a[1][i]; if (cin.get() =='\n') break; i++; } for(j=0;j<=i;j++) { if(a[0][j]<c) c=a[0][j]; if(a[1][j]>b) b=a[1][j]; } for(;c<b;c++) for(j=0;j<=i;j++) { if(a[0][j]<=c&&a[1][j]>c) m[c]++; } for(j=0;j<b;j++) { if(m[0]< m[j]) m[0]=m[j]; } cout << i+1 <<' '<<m[0]; return 0; }
C
/* Программа 03-1.с – пример создания нового процесса с одинаковой работой процессов ребенка и родителя */ #include <sys/types.h> #include <unistd.h> #include <stdio.h> int main() { pid_t pid, ppid; int a = 0; (void)fork(); /* При успешном создании нового процесса с этого места псевдопараллельно начинают работать два процесса: старый и новый */ /* Перед выполнением следующего выражения значение переменной a в обоих процессах равно 0 */ a = a+1; /* Узнаем идентификаторы текущего и роди- тельского процесса (в каждом из процессов !!!) */ pid = getpid(); ppid = getppid(); /* Печатаем значения PID, PPID и вычислен- ное значение переменной a (в каждом из процессов !!!) */ printf("My pid = %d, my ppid = %d, result = %d\n", (int)pid, (int)ppid, a); return 0; }
C
/* ** EPITECH PROJECT, 2018 ** nm objdump ** File description: ** nm get sections */ #include <string.h> #include <stdio.h> #include "nm.h" static int get_sections32(elf_t *elf, char *file) { int i = -1; int ret = 0; size_t size = 0; Elf32_Shdr start = elf->shdr32[elf->ehdr32->e_shstrndx]; char *str = (char *)((void *)elf->ehdr32 + start.sh_offset); while (++i < elf->ehdr32->e_shnum) { if (elf->shdr32[i].sh_type == SHT_SYMTAB) { elf->sym32 = (Elf32_Sym *)((void *)elf->ehdr32 + elf->shdr32[i].sh_offset); size = elf->shdr32[i].sh_size / sizeof(Elf32_Sym); } else if (!strcmp(".strtab", str + elf->shdr32[i].sh_name)) elf->str_tab = (char *)((void *)elf->ehdr32 + elf->shdr32[i].sh_offset); } if (size == 0) return (dprintf(2, "./my_nm: %s: no symbols\n", file), 0); ret = build_list32(elf, size); return (ret); } static int get_sections64(elf_t *elf, char *file) { int i = -1; int ret = 0; size_t size = 0; Elf64_Shdr start = elf->shdr[elf->ehdr->e_shstrndx]; char *str = (char *)((void *)elf->ehdr + start.sh_offset); while (++i < elf->ehdr->e_shnum) { if (elf->shdr[i].sh_type == SHT_SYMTAB) { elf->sym = (Elf64_Sym *)((void *)elf->ehdr + elf->shdr[i].sh_offset); size = elf->shdr[i].sh_size / sizeof(Elf64_Sym); } else if (!strcmp(".strtab", str + elf->shdr[i].sh_name)) elf->str_tab = (char *)((void *)elf->ehdr + elf->shdr[i].sh_offset); } if (size == 0) return (dprintf(2, "./my_nm: %s: no symbols\n", file), 0); ret = build_list(elf, size); return (ret); } int get_sections(elf_t *elf, int version, file_info_t *file_info, char *str) { int ret = 0; if (version == 32) { elf->shdr32 = file_info->data + elf->ehdr32->e_shoff; ret = get_sections32(elf, str); } else { elf->shdr = file_info->data + elf->ehdr->e_shoff; ret = get_sections64(elf, str); } return (ret); }
C
#include <errno.h> #include <stdio.h> #include <unistd.h> int main() { char BUFF[1024]; int lu; while ((lu = read(3, &BUFF, 1024)) > 0) { int a_ecrire = lu; char *pos = BUFF; while(a_ecrire) { int ecrit = write(1, pos, a_ecrire); a_ecrire -= ecrit; pos += ecrit; } } if (lu < 0) perror("problème de lecture"); return 0; }
C
#include <stdio.h> #include <stdlib.h> #include "lists.h" /** * print_dlistint - fucntion to print all elemnnt of DLlist * @h: head of the list * Return: number of nodes */ size_t print_dlistint(const dlistint_t *h) { const dlistint_t *p = NULL; int i = 0; p = h; while (p) { printf("%d\n", p->n); p = p->next; i++; } return (i); }
C
#include <stdio.h> #include <stdlib.h> typedef struct network{ double d; double * p_d; } network; void hello(){ printf("hello\n"); } network * get_net(){ network * net = malloc(sizeof(network)); return net; } void free_net(network * net){ free(net); } int main(){ hello(); network * net = get_net(); net->d = 10.10; printf("net->d: %f \n", net->d); free_net(net); printf("net->d: %f \n", net->d); return 0; }
C
/* ** EPITECH PROJECT, 2018 ** flags.c ** File description: ** first part of flags */ #include <stdarg.h> void my_putchar(char c); int my_put_nbr(int nb); int my_putstr(char const *str); int flags_with_base_management(int argument, va_list display); int easy_flags_management(int argument, va_list display) { switch (argument){ case 'c': my_putchar(va_arg(display, int)); break; case 'd': case 'i': my_put_nbr(va_arg(display, int)); break; case 's': my_putstr(va_arg(display, char *)); break; case '%': my_putchar('%'); break; default: flags_with_base_management(argument, display); } return (0); }
C
#include "Wave.h" #include "delay.h" void Wave_Init() { GPIO_InitTypeDef GPIO_InitStructure; TIM_TimeBaseInitTypeDef TIM_TimeBaseStructure; NVIC_InitTypeDef NVIC_InitStructure; RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM3, ENABLE); //ʱʹ RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA, ENABLE); //ʹA˿ʱ //ʹTrig,ΪΪ͵ƽ GPIO_InitStructure.GPIO_Pin = GPIO_Pin_5; GPIO_InitStructure.GPIO_Mode = GPIO_Mode_Out_PP;// GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;//ٶ50MHz GPIO_Init(GPIOA, &GPIO_InitStructure); GPIO_ResetBits(GPIOA,GPIO_Pin_5); //ʹEcho,Ϊ GPIO_InitStructure.GPIO_Pin = GPIO_Pin_6; GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IPD; GPIO_Init(GPIOA, &GPIO_InitStructure); TIM_TimeBaseStructure.TIM_Period = 49999; //һ¼װԶװؼĴڵֵ 5000Ϊ500ms TIM_TimeBaseStructure.TIM_Prescaler =71; //ΪTIMxʱƵʳԤƵֵ 10KhzļƵ TIM_TimeBaseStructure.TIM_ClockDivision = 0; //ʱӷָ:TDTS = Tck_tim TIM_TimeBaseStructure.TIM_CounterMode = TIM_CounterMode_Up; //TIMϼģʽ TIM_TimeBaseInit(TIM3, &TIM_TimeBaseStructure); //TIM_TimeBaseInitStructָIJʼTIMxʱλ TIM_ITConfig( //ʹܻʧָTIMж TIM3, //TIM2 TIM_IT_Update , ENABLE //ʹ ); NVIC_InitStructure.NVIC_IRQChannel = TIM3_IRQn; //TIM3ж NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = 0; //ռȼ0 NVIC_InitStructure.NVIC_IRQChannelSubPriority = 3; //ȼ3 NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE; //IRQͨʹ NVIC_Init(&NVIC_InitStructure); //NVIC_InitStructָIJʼNVICĴ TIM_Cmd(TIM3, DISABLE); //ʧTIMx } void TIM3_IRQHandler(void) //TIM3ж { if (TIM_GetITStatus(TIM3, TIM_IT_Update) != RESET) //ָTIMжϷ:TIM жԴ { TIM_ClearITPendingBit(TIM3, TIM_IT_Update ); //TIMxжϴλ:TIM жԴ } } float Wave_star() { int timer=0; float distance_cm=0; Trig_H//һߵƽ delay_us(20); Trig_L TIM3->CNT=0; while(!Echo); TIM_Cmd(TIM3, ENABLE); while(Echo&&(TIM3->CNT < TIM3->ARR-10)); TIM_Cmd(TIM3, DISABLE); timer=TIM_GetCounter(TIM3); TIM3->CNT=0; distance_cm=timer/58.0; delay_ms(50); return distance_cm; }
C
#include <stdio.h> #include <string.h> #include <math.h> #include <ft2build.h> #include FT_FREETYPE_H #include <freetype/ftglyph.h> #define TTF_PI 3.1415926535 #define FT2_SRC_COLOR_KEY 0x1000 /* (ṩӿڸû): 1. ֵɫ : Ĭλɫ 2. ǷЧ : Ĭϲ÷ЧΪЧҪĿռ 3. ת : ĬΪתûתǶȣΧ0360 4. Ƿʾ : ĬΪʾ 5. Ƿֱʾ : ĬΪֱʾ */ void putpixel(int x, int y, unsigned long color); int ft2_draw_pixmap(FT_Bitmap *bitmap, FT_Int x, FT_Int y) { int i, j; unsigned char *buf = bitmap->buffer; int w = bitmap->width, h = bitmap->rows; for(i=0; i<h; i++) { for(j=0; j<w; j++) { unsigned char c = buf[i*w+j]; unsigned long rgb = 0; /* gray to rgb 㷨 */ /* rgb = grey * 0x00010101 (888) * /* /*********************************/ #if 0 // о rgb = c == 0? FT2_SRC_COLOR_KEY: c < 128 ? FT2_SRC_COLOR_KEY: 0xffffff; #else // ޾ rgb = c == 0? FT2_SRC_COLOR_KEY: c * 0x00010101; if(0 == c) { rgb = FT2_SRC_COLOR_KEY; } else { rgb = (c<<16) + (c << 8) + c; } rgb = 0xffffff & rgb; // ЧIJɫ #endif if(FT2_SRC_COLOR_KEY != rgb) { putpixel(j+x, i+y, rgb); } } } return 0; } int ft2_draw_bitmap(FT_Bitmap *bitmap, FT_Int x, FT_Int y) { int i, j, k; unsigned char *buf = bitmap->buffer; int w = bitmap->pitch; //pitch can be either positive or negative int h = bitmap->rows; w = w>0?w:-w; for(i=0; i<h; i++) { for(j=0; j<w; j++) { unsigned char c = buf[i*w+j]; for(k=0; k<8; k++) { unsigned int bit = c&(1<<(7-k)); // 7-k if(bit) { putpixel(x+j*8+k, y+i, 0xff); } else { //putpixel(j*8+k, i, 0xff0000); } } } } return 0; } void draw_string(FT_Face face, unsigned short *string, int num_chars) { FT_GlyphSlot slot = face->glyph; /* a small shortcut */ FT_Matrix matrix; int n; FT_Vector pen; /* untransformed origin */ FT_Error error; int target_height = 500; pen.x = 200*64; pen.y = (target_height-200)*64; matrix.xx = (FT_Fixed)( cos( 0 ) * 0x10000L ); matrix.xy = (FT_Fixed)(-sin( 0 ) * 0x10000L ); matrix.yx = (FT_Fixed)( sin( 0 ) * 0x10000L ); matrix.yy = (FT_Fixed)( cos( 0 ) * 0x10000L ); for ( n = 0; n < num_chars; n++ ) { /* set transformation */ FT_Set_Transform( face, &matrix, &pen ); /* load glyph image into the slot (erase previous one) */ error = FT_Load_Char( face, string[n], FT_LOAD_RENDER ); //| FT_LOAD_FORCE_AUTOHINT | FT_LOAD_MONOCHROME | FT_LOAD_VERTICAL_LAYOUT); ft2_draw_pixmap( &slot->bitmap, slot->bitmap_left, target_height - slot->bitmap_top ); #if 0 /* increment pen position */ pen.x += slot->advance.x; pen.y += slot->advance.y; #else /* decrement pen position */ pen.x -= slot->advance.x; pen.y -= slot->advance.y; #endif } } void kern(FT_Face face, unsigned short *text, int num_chars) { FT_GlyphSlot slot = face->glyph; /* a small shortcut */ FT_UInt glyph_index; FT_Bool use_kerning; FT_UInt previous; int pen_x, pen_y, n; FT_Error error; pen_x = 100; pen_y = 100; use_kerning = FT_HAS_KERNING( face ); previous = 0; for ( n = 0; n < num_chars; n++ ) { /* convert character code to glyph index */ glyph_index = FT_Get_Char_Index( face, text[n] ); /* retrieve kerning distance and move pen position */ if ( use_kerning && previous && glyph_index ) { FT_Vector delta; FT_Get_Kerning( face, previous, glyph_index, FT_KERNING_DEFAULT, &delta ); pen_x += delta.x >> 6; } /* load glyph image into the slot (erase previous one) */ error = FT_Load_Glyph( face, glyph_index, FT_LOAD_RENDER ); if ( error ) continue; /* ignore errors */ /* now draw to our target surface */ ft2_draw_pixmap( &slot->bitmap,pen_x + slot->bitmap_left,pen_y - slot->bitmap_top ); /* increment pen position */ pen_x += slot->advance.x >> 6; /* record current glyph index */ previous = glyph_index; } } // center static void compute_string_bbox( FT_BBox *abbox, FT_Glyph *glyphs, FT_Vector *pos, int num_glyphs) { FT_BBox bbox; int n; /* initialize string bbox to "empty" values */ bbox.xMin = bbox.yMin = 320000; bbox.xMax = bbox.yMax = -320000; /* for each glyph image, compute its bounding box, */ /* translate it, and grow the string bbox */ for ( n = 0; n < num_glyphs; n++ ) { FT_BBox glyph_bbox; FT_Glyph_Get_CBox( glyphs[n], ft_glyph_bbox_pixels,&glyph_bbox ); glyph_bbox.xMin += pos[n].x; glyph_bbox.xMax += pos[n].x; glyph_bbox.yMin += pos[n].y; glyph_bbox.yMax += pos[n].y; if ( glyph_bbox.xMin < bbox.xMin ) bbox.xMin = glyph_bbox.xMin; if ( glyph_bbox.yMin < bbox.yMin ) bbox.yMin = glyph_bbox.yMin; if ( glyph_bbox.xMax > bbox.xMax ) bbox.xMax = glyph_bbox.xMax; if ( glyph_bbox.yMax > bbox.yMax ) bbox.yMax = glyph_bbox.yMax; } /* check that we really grew the string bbox */ if ( bbox.xMin > bbox.xMax ) { bbox.xMin = 0; bbox.yMin = 0; bbox.xMax = 0; bbox.yMax = 0; } /* return string bbox */ *abbox = bbox; } static void center_draw( FT_BBox string_bbox, FT_Glyph *glyphs, FT_Vector *pos, int num_glyphs) { /* compute string dimensions in integer pixels */ int string_width, string_height, start_x, start_y; int my_target_width = 500, my_target_height = 500; int n; FT_Error error; string_width = string_bbox.xMax - string_bbox.xMin; string_height = string_bbox.yMax - string_bbox.yMin; /* compute start pen position in 26.6 cartesian pixels */ start_x = ( ( my_target_width - string_width ) / 2 ) * 64; start_y = ( ( my_target_height - string_height ) / 2 ) * 64; for ( n = 0; n < num_glyphs; n++ ) { FT_Glyph image; FT_Vector pen; image = glyphs[n]; pen.x = start_x + (pos[n].x<<6); pen.y = start_y + (pos[n].y<<6); error = FT_Glyph_To_Bitmap( &image, FT_RENDER_MODE_MONO,&pen, 0 ); // FT_RENDER_MODE_NORMAL FT_RENDER_MODE_MONO if ( !error ) { FT_BitmapGlyph bit = (FT_BitmapGlyph)image; ft2_draw_bitmap( &bit->bitmap,bit->left,my_target_height - bit->top ); FT_Done_Glyph( image ); } } } void center(FT_Face face, unsigned short *text, int num_chars) { #define MAX_GLYPHS 20 FT_GlyphSlot slot = face->glyph; /* a small shortcut */ FT_UInt glyph_index; FT_Bool use_kerning; FT_UInt previous; int pen_x, pen_y, n; FT_Glyph glyphs[MAX_GLYPHS]; /* glyph image */ FT_Vector pos [MAX_GLYPHS]; /* glyph position */ FT_UInt num_glyphs; FT_Error error; FT_BBox bbox; pen_x = 0; /* start at (0,0) */ pen_y = 0; num_glyphs = 0; use_kerning = FT_HAS_KERNING( face ); previous = 0; for ( n = 0; n < num_chars; n++ ) { /* convert character code to glyph index */ glyph_index = FT_Get_Char_Index( face, text[n] ); /* retrieve kerning distance and move pen position */ if ( use_kerning && previous && glyph_index ) { FT_Vector delta; FT_Get_Kerning( face, previous, glyph_index,FT_KERNING_DEFAULT, &delta ); pen_x += delta.x >> 6; } /* store current pen position */ pos[num_glyphs].x = pen_x; pos[num_glyphs].y = pen_y; /* load glyph image into the slot without rendering */ error = FT_Load_Glyph( face, glyph_index, FT_LOAD_MONOCHROME ); // FT_LOAD_MONOCHROME FT_LOAD_DEFAULT if ( error ) continue; /* ignore errors, jump to next glyph */ /* extract glyph image and store it in our table */ error = FT_Get_Glyph( face->glyph, &glyphs[num_glyphs] ); if ( error ) continue; /* ignore errors, jump to next glyph */ /* increment pen position */ pen_x += (slot->advance.x >> 6); /* record current glyph index */ previous = glyph_index; /* increment number of glyphs */ num_glyphs++; } compute_string_bbox(&bbox, glyphs, pos, num_glyphs); center_draw(bbox, glyphs, pos, num_glyphs); #undef MAX_GLYPHS } // advance render typedef struct TGlyph_ { FT_UInt index; /* glyph index */ FT_Vector pos; /* glyph origin on the baseline */ FT_Glyph image; /* glyph image */ } TGlyph, *PGlyph; static void advance_compute_string_bbox( FT_BBox *abbox, TGlyph *glyphs, int num_glyphs ) { FT_BBox bbox; int n; bbox.xMin = bbox.yMin = 320000; bbox.xMax = bbox.yMax = -320000; for ( n = 0; n < num_glyphs; n++ ) { FT_BBox glyph_bbox; FT_Glyph_Get_CBox( glyphs[n].image, ft_glyph_bbox_pixels, &glyph_bbox ); if (glyph_bbox.xMin < bbox.xMin) bbox.xMin = glyph_bbox.xMin; if (glyph_bbox.yMin < bbox.yMin) bbox.yMin = glyph_bbox.yMin; if (glyph_bbox.xMax > bbox.xMax) bbox.xMax = glyph_bbox.xMax; if (glyph_bbox.yMax > bbox.yMax) bbox.yMax = glyph_bbox.yMax; } if ( bbox.xMin > bbox.xMax ) { bbox.xMin = 0; bbox.yMin = 0; bbox.xMax = 0; bbox.yMax = 0; } *abbox = bbox; } static advance_render_draw(FT_BBox string_bbox, TGlyph *glyphs, int num_glyphs, double angle) { FT_Vector start, pen; FT_Matrix matrix; int string_width, string_height; int my_target_width = 500; int my_target_height = 500; int n; FT_Error error; /* get bbox of original glyph sequence */ advance_compute_string_bbox(&string_bbox, glyphs, num_glyphs); /* compute string dimensions in integer pixels */ string_width = (string_bbox.xMax - string_bbox.xMin) / 64; string_height = (string_bbox.yMax - string_bbox.yMin) / 64; /* set up start position in 26.6 cartesian space */ start.x = ( ( my_target_width - string_width ) / 2 ) * 64; start.y = ( ( my_target_height - string_height ) / 2 ) * 64; /* set up transform (a rotation here) */ matrix.xx = (FT_Fixed)( cos( angle ) * 0x10000L ); matrix.xy = (FT_Fixed)(-sin( angle ) * 0x10000L ); matrix.yx = (FT_Fixed)( sin( angle ) * 0x10000L ); matrix.yy = (FT_Fixed)( cos( angle ) * 0x10000L ); for ( n = 0; n < num_glyphs; n++ ) { FT_Glyph image; FT_Vector pen; FT_BBox bbox; /* create a copy of the original glyph */ error = FT_Glyph_Copy( glyphs[n].image, &image ); if ( error ) { continue; } /* transform copy (this will also translate it to the */ /* correct position */ pen.x = start.x + (glyphs[n].pos.x<<6); // calculate start position pen.y = start.y + (glyphs[n].pos.y<<6); FT_Glyph_Transform( image, &matrix, &pen ); /* check bounding box; if the transformed glyph image */ /* is not in our target surface, we can avoid rendering it */ FT_Glyph_Get_CBox( image, ft_glyph_bbox_pixels, &bbox ); if ( bbox.xMax <= 0 || bbox.xMin >= my_target_width || bbox.yMax <= 0 || bbox.yMin >= my_target_height ) { continue; // skip error, continue draw next } // convert glyph image to bitmap error = FT_Glyph_To_Bitmap(&image, FT_RENDER_MODE_NORMAL, NULL, // not additional move pen 1 ); // destroy the glyph copy! that's image buffer if ( !error ) { FT_BitmapGlyph bit = (FT_BitmapGlyph)image; ft2_draw_pixmap( &bit->bitmap,bit->left,my_target_height - bit->top ); FT_Done_Glyph( image ); } } } void advance_render(FT_Face face, unsigned short *text, int num_chars, double angle) { #define MAX_GLYPHS 20 FT_GlyphSlot slot = face->glyph; /* a small shortcut */ FT_Bool use_kerning; FT_UInt previous; int pen_x, pen_y, n; FT_BBox bbox; TGlyph glyphs[MAX_GLYPHS]; /* glyphs table */ PGlyph glyph; /* current glyph in table */ FT_UInt num_glyphs; FT_Error error; pen_x = 0; /* start at (0,0) */ pen_y = 0; num_glyphs = 0; use_kerning = FT_HAS_KERNING( face ); previous = 0; glyph = glyphs; for ( n = 0; n < num_chars; n++ ) { glyph->index = FT_Get_Char_Index( face, text[n] ); if ( use_kerning && previous && glyph->index ) { FT_Vector delta; FT_Get_Kerning( face, previous, glyph->index, FT_KERNING_DEFAULT, &delta ); pen_x += delta.x >> 6; } /* store current pen position */ glyph->pos.x = pen_x; glyph->pos.y = pen_y; error = FT_Load_Glyph( face, glyph->index, FT_LOAD_DEFAULT ); if ( error ) continue; error = FT_Get_Glyph( face->glyph, &glyph->image ); if ( error ) continue; /* translate the glyph image now */ FT_Glyph_Transform( glyph->image, 0, &glyph->pos ); pen_x += (slot->advance.x >> 6); previous = glyph->index; /* increment number of glyphs */ glyph++; } /* count number of glyphs loaded */ num_glyphs = glyph - glyphs; advance_render_draw(bbox, glyphs, num_glyphs, angle); #undef MAX_GLYPHS } int ttf_main(void) { FT_Library library; FT_Face face; FT_GlyphSlot slot; FT_Vector delt = {100, 100}; FT_Error error; char* filename; unsigned char* text; unsigned char *text_cn; double angle; double degree = 0.0; int target_height; int num_chars; filename = ".\\res\\res_freetype\\fz.ttf"; text = "hello"; text_cn = "\x60\x4f\x7d\x59\x2d\x4e\xfd\x56"; degree = 30.0; #if 0 num_chars = strlen( text ); #else num_chars = 4; #endif angle = (degree/180.0)*TTF_PI; /* use 25 degrees */ target_height = 500; error = FT_Init_FreeType(&library); /* initialize library */ /* error handling omitted */ error = FT_New_Face(library, filename, 0, &face); /* create face object */ /* error handling omitted */ /* use 50pt at 100dpi */ error = FT_Set_Char_Size(face, 100*32, 0, 100, 0); /* set character size */ /* error handling omitted */ slot = face->glyph; draw_string(face, text_cn, num_chars); //kern(face, (unsigned short *)text_cn, num_chars); //center(face, text_cn, num_chars); //advance_render(face, (unsigned short *)text_cn, num_chars, angle); // generate a bitmap //ft2_show_image(); // show bitmap buffer FT_Done_Face( face ); FT_Done_FreeType( library ); return 0; } /* EOF */
C
#include "ft_ultimate_div_mod.c" #include <stdio.h> int main() { int a=6, b=2; ft_ultimate_div_mod(&a, &b); printf("a=%d %d\n", a, b); // printf("a=%d\n", a); return 0; }
C
/* ---------------------------------------------------- */ /* Displaying all System V message queues on the system */ /* -----------------------------------------------------*/ #define _GNU_SOURCE #include <sys/types.h> #include <sys/msg.h> #include "tlpi_hdr.h" int main(int argc, char* argv[]) { int maxind, ind, msqid; struct msqid_ds ds; struct msginfo msginfo; /* Obtain size of kernel 'entries' array */ maxind = msgctl(0, MSG_INFO, (struct msqid_ds*)&msginfo); if (maxind == -1) errExit("msgctl-MSG_INFO"); printf("maxind:%d\n\n", maxind); printf("index id key messages\n"); /* Retrieve and display information from each element of 'entries' array */ for (ind = 0; ind <= maxind; ind++) { msqid = msgctl(ind, MSG_STAT, &ds); if (msqid == -1) { if (errno != EINVAL && errno != EACCES) errMsg("msgctl-MSG_STAT"); continue; } printf("%4d %8d 0x%08lx %7ld\n", ind, msqid, (unsigned long)ds.msg_perm.__key, (long)ds.msg_qnum); } exit(EXIT_SUCCESS); }
C
// Swapping two numbers #include <stdio.h> int main() { int x,y,temp; printf("Enter the value of x and y\n"); scanf("%d%d",&x,&y); printf("Before swapping\nx=%d\ny=%d\n",x,y); temp = x; x = y; y = temp; // Using temp to swap storing x to temp and y to x then moving temp to y printf("After Swapping\nx=%d\ny=%d\n",x,y); return 0; }
C
const char base64_charset[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" "abcdefghijklmnopqrstuvwxyz" "0123456789" "+/"; /* base64_decode: Description: Encode a char array to a base64 encoded string Parameters: bytes_to_encode: the char array to encode len_to_encode: the length of the array Return value: the base64 encoded string */ static String base64_encode(char *bytes_to_encode, int len_to_encode) { int len_encoded = (ceil(len_to_encode) / 3) * 4; char bytes_encoded[len_encoded + 1]; int pos_in = 0; int pos_out = 0; while (pos_in < len_to_encode) { char out[4]; int counter = 0; out[0] = (bytes_to_encode[pos_in + 0] & 0xfc) >> 2; out[1] = (bytes_to_encode[pos_in + 0] & 0x03) << 4; if (pos_in + 1 < len_to_encode) { out[1] += (bytes_to_encode[pos_in + 1] & 0xf0) >> 4; out[2] = (bytes_to_encode[pos_in + 1] & 0x0f) << 2; counter++; } if (pos_in + 2 < len_to_encode) { out[2] += (bytes_to_encode[pos_in + 2] & 0xc0) >> 6; out[3] = (bytes_to_encode[pos_in + 2] & 0x3f); counter++; } bytes_encoded[pos_out + 0] = base64_charset[out[0]]; bytes_encoded[pos_out + 1] = base64_charset[out[1]]; bytes_encoded[pos_out + 2] = counter ? base64_charset[out[2]] : '='; bytes_encoded[pos_out + 3] = counter == 2 ? base64_charset[out[3]] : '='; pos_in += 3; pos_out += 4; } bytes_encoded[pos_out] = '\0'; return String(bytes_encoded); } /* base64_encode_str: Description: Prepares arguments from a string and executes the base64_encode function with them to return its result. Parameters: string_to_encode: a string to encoded Return value: the base64 encoded string */ static String base64_encode_str(String string_to_encode) { int len_to_encode = string_to_encode.length(); if (!len_to_encode) { return String(); } char bytes_to_encode[len_to_encode + 1]; string_to_encode.toCharArray(bytes_to_encode, len_to_encode + 1); return String(base64_encode(bytes_to_encode, len_to_encode)); }
C
#include "holberton.h" /** * _strlen - Calculate the lenght of a string * @s: The array to be evaluated * * Return: On success 1. * On error, -1 is returned, and errno is set appropriately. */ int _strlen(char *s) { int i = 0; while (s[i] != '\0') i++; return (i); } /** * append_text_to_file - Append content to a file * @filename: The name of the file * @text_content: The content of the file * * Return: Number of printed bytes * On error, terun NULL */ int append_text_to_file(const char *filename, char *text_content) { int fd, wr; if (filename == NULL) return (-1); if (text_content != NULL) { fd = open(filename, O_WRONLY | O_APPEND); if (fd == -1) return (-1); wr = write(fd, text_content, _strlen(text_content)); if (wr == -1) return (-1); } else { fd = open(filename, O_WRONLY); if (fd == -1) return (-1); } close(fd); return (1); }
C
#include "linkedList.h" #include <opencv2\highgui\highgui_c.h> /* Gets a linked list of frames and prints every frame details input: The first node of a FrameNode linked list */ void printFrames(FrameNode* head) // O(n) { FrameNode* current = head; printf("\t%-20s%-20s%-20s\n", "Name", "Duration", "Path"); while (current) { printf("\t%-20s%-20d%-20s\n", current->frame->name, current->frame->duration, current->frame->path); current = current->next; } } /* Gets a linked list of frames creates and adds a new frame, requesting from the user the frame properties. input: Pointer to the first node of a FrameNode linked list */ void addFrameToList(FrameNode** head, char name[MAX_LEN], int* time, char dir[MAX_LEN]) // O(n) { Frame* newFrame = 0; FrameNode* newFrameNode = 0; newFrame = (Frame*)malloc(sizeof(Frame)); //Allocates heap memory for the new Frame strncpy(newFrame->name, name, MAX_LEN); strncpy(newFrame->path, dir, MAX_LEN); newFrame->duration = *time; newFrameNode = (FrameNode*)malloc(sizeof(FrameNode)); //Allocates heap memory for the new FrameNode newFrameNode->frame = newFrame; newFrameNode->next = NULL; insertAtEnd(head, newFrameNode); //Inserts the new node to the end of the list of frames } /* Moves a requested frame to a new index. input: a pointer to the first node of a linked list */ void changeFrameIndex(FrameNode** head) // O(n) { char frameName[MAX_LEN] = { 0 }; int newIndex = 0, counter = ONE, nodeToMoveIndex = 0; FrameNode* originalHead = *head, *nodeToMove = NULL, *current = originalHead, *prev = NULL, *temp = NULL; printf("Enter the frame you want to move: "); myFgets(frameName, MAX_LEN); printf("Enter the new index: "); scanf("%d", &newIndex); while (current != NULL && strcmp(current->frame->name, frameName)) //Goes through all frames until the requested frame to move is found { counter++; prev = current; current = current->next; } nodeToMoveIndex = counter; //Save the index of the frameNode to move nodeToMove = current; //Save the pointer of the frameNode to move if (current != NULL && counter != newIndex && newIndex > 0 && newIndex <= getAmountOfFrames(*head)) //Checks if a frame name was found and the new index to move is not the index of the node itself { if (prev != NULL) { prev->next = nodeToMove->next; //Cut "node to move" from list } else //If the "node to move" is in the beginning { *head = originalHead->next; originalHead = *head; } current = *head; counter = ONE; if (newIndex == LIST_BEGINNING) //If requested to move the node to the beginning { nodeToMove->next = originalHead; *head = nodeToMove; //Update the moved node as the beginning of the list } else { while (current != NULL && counter < newIndex - ONE) //Goes through the nodes until the new index for the node we want to move { counter++; current = current->next; } temp = current->next; current->next = nodeToMove; nodeToMove->next = temp; } } } /* Gets a linked list and returns it's length input: The first node of a linked list output: The amount of nodes in the list */ int getAmountOfFrames(FrameNode* head) // O(n) { int len = 0; FrameNode* current = head; while (current) { len++; current = current->next; } return len; } /* Gets a list of frames and changes every frame's duration from user input input: Pointer to the first node of a FrameNode linked list */ void changeAllFramesDuration(FrameNode** head) // O(n) { FrameNode* current = *head; char frameToCheck[MAX_LEN] = { 0 }; int newDuration = 0; printf("Enter the duration for all frames: "); checkDurationInput(scanf("%d", &newDuration), &newDuration); getchar(); if (*head) //Checks if list is empty { while (current != NULL) { current->frame->duration = newDuration; current = current->next; } } } /* Gets a list of frames and changes a certain frame's duration from user input input: Pointer to the first node of a FrameNode linked list */ void changeFrameDuration(FrameNode** head) // O(n) { FrameNode* current = *head; char frameToCheck[MAX_LEN] = { 0 }; int newDuration = 0, changed = 0; printf("Enter the name of the frame: "); myFgets(frameToCheck, MAX_LEN); printf("Enter the new duration for this frame: "); checkDurationInput(scanf("%d", &newDuration), &newDuration); while (current != NULL && changed != TRUE) { if (!strcmp(current->frame->name, frameToCheck)) { current->frame->duration = newDuration; changed = TRUE; } current = current->next; } if (!changed) //If none of the frames were changed { printf("**\"%s\" is not in the list of frames\n\n", frameToCheck); } } /* Gets a list of frames and removes a certain frame from the list, from user input input: Pointer to the first node of a FrameNode linked list */ void removeFrame(FrameNode** head) // O(n) { FrameNode* current = *head; FrameNode* temp = NULL; char name[MAX_LEN] = { 0 }; int gotRemoved = FALSE; printf("Enter the name of the frame you wish to erase: "); myFgets(name, MAX_LEN); if (*head) //Checks if the list is empty { if (!(strcmp((*head)->frame->name, name))) //Checks the first frame { *head = (*head)->next; free(current); gotRemoved = TRUE; } else { while (current->next != NULL) //Checks the rest of frames { if (!strcmp(current->next->frame->name, name)) { gotRemoved = TRUE; temp = current->next; //Saves the pointer of the node we want to free current->next = temp->next; free(temp); } else { current = current->next; } } } } if (!gotRemoved) //If nothing had been removed { printf("**\"%s\" is not in the list of frames\n\n", name); } } /* Gets a list of frames and inserts a new frame node to the end of the list input: Pointer to the first node of a FrameNode linked list, a new frameNode to insert */ void insertAtEnd(FrameNode** head, FrameNode* newFrameNode) // O(n) { FrameNode* current = *head; if (!*head) //Checks if the list is empty -> make the new frame the first node { *head = newFrameNode; } else { while (current->next != NULL) { current = current->next; } current->next = newFrameNode; newFrameNode->next = NULL; } } /* Gets a list of frames, a frame name and checks if that frame exist input: Pointer to the first node of a FrameNode linked list, a frame name to check output: True if the frame exist, else false */ int checkFrameExist(FrameNode* head, char* frameToCheck) // O(n) { FrameNode* current = head; int exist = FALSE; while (current != NULL && exist != TRUE) { if (!strcmp(current->frame->name, frameToCheck)) { exist = TRUE; } current = current->next; } return exist; } /* Gets a list of frames, a directory and checks if there is an openable image in that directory input: a directory to check output: true if the directory points to an openable image, else false */ int checkValidDir(char* dir) // O(1) { IplImage* image = cvLoadImage(dir, COLOR_CODE); int validImage = 0; if (image) //Checks if the image is not empty { validImage = TRUE; } cvReleaseImage(&image); return validImage; } /* Gets empty variables of frame properties, and requests input for the new frame input: an empty directory string, empty frame name string, empty frame duration integer */ void getFrameProperties(char dir[MAX_LEN], char name[MAX_LEN], int* time) // O(1) { printf("Please insert frame path: "); myFgets(dir, MAX_LEN); printf("Please insert frame duration (in muliseconds): "); checkDurationInput(scanf("%d", time), time); getchar(); printf("Please choose a name for that frame: "); myFgets(name, MAX_LEN); } /* Gets the result of the frame duration input of the user and checks if it's valid. input: scanf results of the frame duration, the frame duration */ void checkDurationInput(int scanResult, int* duration) { int chr = 0, rv = scanResult; while (rv != SCAN_ONCE || *duration < MIN_DURATION) //Checks if the duration is invalid or a number was not scanned { do { chr = getchar(); } while ((chr != EOF) && (chr != '\n')); printf("**Please insert a valid value: "); rv = scanf("%d", duration); } } /* Gets a list of frames and frees the allocated memory of every FrameNode and Frame input: Pointer to the first node of a FrameNode linked list */ void freeGif(FrameNode** head) // O(n) { FrameNode* temp = NULL; FrameNode* current = *head; while (current != NULL) //Until the end of the list { temp = current; //Saves the pointer of the node we want to free current = current->next; free(temp->frame); free(temp); } *head = NULL; } /* Gets the properties of a frame and checks if they are valid input: a pointer to a linked list of frames, frame directory, frame name and frame duration output: 1 if all properties are valid, else 0 */ int checkInput(FrameNode** head, char dir[MAX_LEN], char name[MAX_LEN], int* time) // O(n) { int flag = 0; if (checkFrameExist(*head, name)) { printf("**The name is already taken, please enter another name\n\n"); } else if (!checkValidDir(dir)) { printf("**Unable to open file, please enter another directory\n\n"); } else if (*time < MIN_DURATION) { printf("**Time argument is invalid\n\n"); } else { flag = TRUE; } return flag; } /* A function will perform the fgets command and also remove the newline that might be at the end of the string - a known issue with fgets. input: the buffer to read into, the number of chars to read */ void myFgets(char str[], int n) // O(1) { fgets(str, n, stdin); str[strcspn(str, "\n")] = 0; } /* Gets a linked list and reverses it. input: a pointer to a linked list to reverse */ void reverseAllFrames(FrameNode** head) //O(n) { FrameNode* prev = NULL; FrameNode* current = *head; FrameNode* next = NULL; while (current != NULL) { next = current->next; //Save the pointer to the next node current->next = prev; //Set the next of the current node the previous node prev = current; //Move the previous node position ahead current = next; //Move the current node position ahead } *head = prev; } /* Copies a list of frames and returns the duplicate input: a linked list of frames to display output: a duplicate of the linked list */ FrameNode* copyFrameList(FrameNode* listToCopy) // O(n) { FrameNode* current = listToCopy; FrameNode* newList = NULL; while (current->next != NULL) { addFrameToList(&newList, current->frame->name, &(current->frame->duration), current->frame->path); current = current->next; } return newList; }
C
/* * Main program to benchmark hash functions * Part of the xxHash project * Copyright (C) 2019-2021 Yann Collet * GPL v2 License * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. * * You can contact the author at: * - xxHash homepage: https://www.xxhash.com * - xxHash source repository: https://github.com/Cyan4973/xxHash */ /* === dependencies === */ #include <stdio.h> /* printf */ #include <limits.h> /* INT_MAX */ #include "bhDisplay.h" /* bench_x */ /* === defines list of hashes `hashCandidates` and NB_HASHES *** */ #include "hashes.h" /* === parse command line === */ #undef NDEBUG #include <assert.h> /*! * readIntFromChar(): * Allows and interprets K, KB, KiB, M, MB and MiB suffix. * Will also modify `*stringPtr`, advancing it to position where it stopped reading. */ static int readIntFromChar(const char** stringPtr) { static int const max = (INT_MAX / 10) - 1; int result = 0; while ((**stringPtr >='0') && (**stringPtr <='9')) { assert(result < max); result *= 10; result += (unsigned)(**stringPtr - '0'); (*stringPtr)++ ; } if ((**stringPtr=='K') || (**stringPtr=='M')) { int const maxK = INT_MAX >> 10; assert(result < maxK); result <<= 10; if (**stringPtr=='M') { assert(result < maxK); result <<= 10; } (*stringPtr)++; /* skip `K` or `M` */ if (**stringPtr=='i') (*stringPtr)++; if (**stringPtr=='B') (*stringPtr)++; } return result; } /** * isCommand(): * Checks if string is the same as longCommand. * If yes, @return 1, otherwise @return 0 */ static int isCommand(const char* string, const char* longCommand) { assert(string); assert(longCommand); size_t const comSize = strlen(longCommand); return !strncmp(string, longCommand, comSize); } /* * longCommandWArg(): * Checks if *stringPtr is the same as longCommand. * If yes, @return 1 and advances *stringPtr to the position which immediately * follows longCommand. * @return 0 and doesn't modify *stringPtr otherwise. */ static int longCommandWArg(const char** stringPtr, const char* longCommand) { assert(stringPtr); assert(longCommand); size_t const comSize = strlen(longCommand); int const result = isCommand(*stringPtr, longCommand); if (result) *stringPtr += comSize; return result; } /* === default values - can be redefined at compilation time === */ #ifndef SMALL_SIZE_MIN_DEFAULT # define SMALL_SIZE_MIN_DEFAULT 1 #endif #ifndef SMALL_SIZE_MAX_DEFAULT # define SMALL_SIZE_MAX_DEFAULT 127 #endif #ifndef LARGE_SIZELOG_MIN_DEFAULT # define LARGE_SIZELOG_MIN_DEFAULT 9 #endif #ifndef LARGE_SIZELOG_MAX_DEFAULT # define LARGE_SIZELOG_MAX_DEFAULT 27 #endif static int display_hash_names(void) { int i; printf("available hashes : \n"); for (i=0; i<NB_HASHES; i++) { printf("%s, ", hashCandidates[i].name); } printf("\b\b \n"); return 0; } /* * @return: hashID (necessarily between 0 and NB_HASHES) if present * -1 on error (hname not present) */ static int hashID(const char* hname) { int id; assert(hname); for (id=0; id < NB_HASHES; id++) { assert(hashCandidates[id].name); if (strlen(hname) != strlen(hashCandidates[id].name)) continue; if (isCommand(hname, hashCandidates[id].name)) return id; } return -1; } static int help(const char* exename) { printf("Usage: %s [options]... [hash]\n", exename); printf("Runs various benchmarks at various lengths for the listed hash functions\n"); printf("and outputs them in a CSV format.\n\n"); printf("Options: \n"); printf(" --list Name available hash algorithms and exit \n"); printf(" --mins=LEN Starting length for small size bench (default: %i) \n", SMALL_SIZE_MIN_DEFAULT); printf(" --maxs=LEN End length for small size bench (default: %i) \n", SMALL_SIZE_MAX_DEFAULT); printf(" --minl=LEN Starting log2(length) for large size bench (default: %i) \n", LARGE_SIZELOG_MIN_DEFAULT); printf(" --maxl=LEN End log2(length) for large size bench (default: %i) \n", LARGE_SIZELOG_MAX_DEFAULT); printf(" [hash] Optional, bench all available hashes if not provided \n"); return 0; } static int badusage(const char* exename) { printf("Bad command ... \n"); help(exename); return 1; } int main(int argc, const char* argv[]) { const char* const exename = argv[0]; int hashNb = 0; int nb_h_test = NB_HASHES; int largeTest_log_min = LARGE_SIZELOG_MIN_DEFAULT; int largeTest_log_max = LARGE_SIZELOG_MAX_DEFAULT; size_t smallTest_size_min = SMALL_SIZE_MIN_DEFAULT; size_t smallTest_size_max = SMALL_SIZE_MAX_DEFAULT; int arg_nb; for (arg_nb = 1; arg_nb < argc; arg_nb++) { const char** arg = argv + arg_nb; if (isCommand(*arg, "-h")) { assert(argc >= 1); return help(exename); } if (isCommand(*arg, "--list")) { return display_hash_names(); } if (longCommandWArg(arg, "--n=")) { nb_h_test = readIntFromChar(arg); continue; } /* hidden command */ if (longCommandWArg(arg, "--minl=")) { largeTest_log_min = readIntFromChar(arg); continue; } if (longCommandWArg(arg, "--maxl=")) { largeTest_log_max = readIntFromChar(arg); continue; } if (longCommandWArg(arg, "--mins=")) { smallTest_size_min = (size_t)readIntFromChar(arg); continue; } if (longCommandWArg(arg, "--maxs=")) { smallTest_size_max = (size_t)readIntFromChar(arg); continue; } /* not a command: must be a hash name */ hashNb = hashID(*arg); if (hashNb >= 0) { nb_h_test = 1; } else { /* not a hash name: error */ return badusage(exename); } } /* border case (requires (mis)using hidden command `--n=#`) */ if (hashNb + nb_h_test > NB_HASHES) { printf("wrong hash selection \n"); return 1; } printf(" === benchmarking %i hash functions === \n", nb_h_test); if (largeTest_log_max >= largeTest_log_min) { bench_largeInput(hashCandidates+hashNb, nb_h_test, largeTest_log_min, largeTest_log_max); } if (smallTest_size_max >= smallTest_size_min) { bench_throughput_smallInputs(hashCandidates+hashNb, nb_h_test, smallTest_size_min, smallTest_size_max); bench_throughput_randomInputLength(hashCandidates+hashNb, nb_h_test, smallTest_size_min, smallTest_size_max); bench_latency_smallInputs(hashCandidates+hashNb, nb_h_test, smallTest_size_min, smallTest_size_max); bench_latency_randomInputLength(hashCandidates+hashNb, nb_h_test, smallTest_size_min, smallTest_size_max); } return 0; }
C
/***************************************************************************** * | File : OLED_Driver.c * | Author : Waveshare team * | Function : 0.9inch OLED using SSD1306 control * | Info : *---------------- * | This version: V1.0 * | Date : 2018-04-17 * | Info : Basic version ******************************************************************************/ #include "OLED_Driver.h" #include <stdio.h> //#include "Show_Lib.h" #include "string.h" /******************************************************************************* function: Common register initialization *******************************************************************************/ static void OLED_InitReg() { OLED_WriteReg(0xAE); OLED_WriteReg(0x40);//---set low column address OLED_WriteReg(0xB0);//---set high column address OLED_WriteReg(0xC8);//-not offset OLED_WriteReg(0x81); OLED_WriteReg(0xff); OLED_WriteReg(0xa1); OLED_WriteReg(0xa6); OLED_WriteReg(0xa8); OLED_WriteReg(0x1f); OLED_WriteReg(0xd3); OLED_WriteReg(0x00); OLED_WriteReg(0xd5); OLED_WriteReg(0xf0); OLED_WriteReg(0xd9); OLED_WriteReg(0x22); OLED_WriteReg(0xda); OLED_WriteReg(0x02); OLED_WriteReg(0xdb); OLED_WriteReg(0x49); OLED_WriteReg(0x8d); OLED_WriteReg(0x14); OLED_WriteReg(0xaf); } void OLED_Clear(void) { char Column,Page; for(Page = 0; Page < OLED_Page; Page++) { OLED_WriteReg(0xb0 + Page); //Set page address OLED_WriteReg(0x00); //Set display position - column low address OLED_WriteReg(0x10); //Set display position - column high address for(Column = 0; Column < OLED_Column; Column++) OLED_WriteData(0xff); } } void OLED_Init(void) { OLED_InitReg(); OLED_Clear(); } void OLED_SendBuf(UBYTE *Buf) { char Column,Page; UBYTE *ptr = Buf; for(Page = 0; Page < OLED_Page; Page++) { OLED_WriteReg(0xb0 + Page); OLED_WriteReg(0x00); OLED_WriteReg(0x10); for(Column = 0; Column < OLED_Column; Column++) { OLED_WriteData(*ptr); ptr++; } } }
C
#include <stdio.h> #include <stdlib.h> #include <string.h> void selection_sort (long int v[], int size) { int i, j, posMenor = 0; long int temp; for (i = 0; i < size - 1; i++) { posMenor = i; for (j = i + 1; j < size; j++) { if (v[j] < v[posMenor]) posMenor = j; } temp = v[i]; v[i] = v[posMenor]; v[posMenor] = temp; } } long int compare (const void *a, const void *b) { if (*(long int*)a > *(long int*)b) { return 1; } else if (*(long int*)a < *(long int*)b) { return -1; } else { return 0; } } int main () { FILE* fp; fp = freopen("input3.txt", "r", stdin); char buf[1000009]; memset(buf, 0, 1000009); if (fp != NULL) { fgets(buf, 1000009, fp); long int n = strtol(buf, NULL, 10); long int numeros[n]; memset(numeros, 0, n); long int i; char *pEnd = NULL; fgets(buf, 1000009, fp); for (i = 0; i < n; i++) { numeros[i] = strtol(buf, &pEnd, 10); memcpy(buf, &pEnd[1], strlen(pEnd)); fgets(buf, 1000009, fp); } //selection_sort(numeros, n); qsort(numeros, n, sizeof(long int), compare); for (i = 0; i < n; i++) { printf("%d ", numeros[i]); } } return (0); }
C
#include "stdafx.h" #include "resource.h" #include "GameBoard.h" /*****************************************Ϸ****************************************/ struct GameBoard* New_GameBoard(HWND parent/**/, int x, int y, int nWidth, int nHeight) { WNDCLASSEX wndClass = {sizeof(WNDCLASSEX)}; struct GameBoard* gameBoard = (struct GameBoard*)calloc( 1, sizeof(struct GameBoard) ); /* עᴰ*/ wndClass.style = CS_HREDRAW | CS_VREDRAW;//CS_HREDRAWˮƽĿȱ仯ʱػ.CS_VREDRAW ڴֱĿȱ仯ʱػ. wndClass.lpfnWndProc = GameBoard_Proc;//lpfnWndProcָijָ wndClass.hCursor = LoadCursor(NULL, IDC_CROSS);//һܣúһӦصĿִļEXEļָĹԴ wndClass.lpszClassName = GAMEBOARD_NAME; RegisterClassEx(&wndClass); /* ʼ*/ gameBoard->delete = GameBoard_Delete; /* ʼ*/ gameBoard->m_handle = CreateWindow(GAMEBOARD_NAME, NULL, WS_CHILD | WS_VISIBLE, x, y, nWidth, nHeight, parent, NULL, NULL, NULL); SetWindowLongPtr( gameBoard->m_handle, GWLP_USERDATA, (LONG_PTR)gameBoard ); gameBoard->m_bitmap = CreateCompatibleBitmap( GetDC(gameBoard->m_handle), GAMEBOARD_WIDTH, GAMEBOARD_HEIGHT );/*úָ豸ص豸ݵλͼ*/ gameBoard->m_drawer = CreateCompatibleDC( GetDC(gameBoard->m_handle) ); SelectObject(gameBoard->m_drawer, gameBoard->m_bitmap); return gameBoard; } /*****************************************¼*******************************************/ static LRESULT CALLBACK GameBoard_Proc(HWND window,/**/ UINT/*int*/ nMessage,/*¼ʶ*/ WPARAM wParam/*¼Ӳ*/, LPARAM lParam/*¼Ӳ*/) { struct GameBoard* gameBoard = (struct GameBoard*)GetWindowLongPtr(window, GWLP_USERDATA); switch (nMessage) { case WM_PAINT://WndProcĵڶϢΪWM_PAINTϢWindowsǺҪġʾһʾ //ݻȫΪЧڱ롰»桱ʱϢ֪ͨ GameBoard_OnPaint(gameBoard); break; } return DefWindowProc(window, nMessage, wParam, lParam); } /***********************ػ¼ӦУ̨λͼƵǰ̨**************************/ static void GameBoard_OnPaint(struct GameBoard* gameBoard) { PAINTSTRUCT ps = {0}; BeginPaint(gameBoard->m_handle, &ps);//BeginPaintΪָڽлͼ׼ýͻͼйصϢ䵽һPAINTSTRUCTṹ BitBlt(ps.hdc, 0, 0, GAMEBOARD_WIDTH, GAMEBOARD_HEIGHT, gameBoard->m_drawer, 0, 0, SRCCOPY);//úָԴ豸еؽλ飨bit_blockתԴ͵Ŀ豸 EndPaint(gameBoard->m_handle, &ps); } /***************************************ɾϷ*************************************/ static void GameBoard_Delete(struct GameBoard* gameBoard) { DeleteObject(gameBoard->m_drawer); DeleteObject(gameBoard->m_bitmap); DestroyWindow(gameBoard->m_handle); free(gameBoard); }
C
#include<conio.h> #include<stdio.h> #include<stdlib.h> int main() { float matrizA[3][3]; float matrizAB[3][4] = {{3,2,4,1},{1,1,2,2},{4,3,-2,3}}; float vetorX[3]; float pivo = 0, m = 0; int i, j, k; int ordem = 3; for(i=0; i<ordem; i++) { pivo = matrizAB[i][i]; for(j=0; j<=ordem; j++) { matrizAB[i][j] = matrizAB[i][j] / pivo; } for(k=0; k<ordem; k++) { if (i != k) { m = matrizAB[k][i]; for(j=0; j<=ordem; j++) { matrizAB[k][j] = matrizAB[k][j] - (matrizAB[i][j] * m); } } } } for (i=0; i<ordem; i++) { for(j=0; j<=ordem; j++) { if (j==ordem) vetorX[i] = matrizAB[i][j]; else matrizA[i][j] = matrizAB[i][j]; } } printf("A Matriz AB :\n"); for(i=0 ; i<ordem ; i++ ) { for(j=0 ; j<=ordem ; j++ ) { printf("|%.1f| ", matrizAB[i][j]); } printf("\n"); } printf("\nA Matriz multiplicadora :\n"); for(i=0 ; i<ordem ; i++ ) { printf("|%.1f| ", vetorX[i]); } getch(); }
C
/** * set_bit - Sets the value of a bit to 1 at a given index. * @n: Number to Modify. * @index: Index of the bit to be set to 1. * Return: 1 if success, -1 if not. */ int set_bit(unsigned long int *n, unsigned int index) { if (index >= 64) return (-1); *n |= 1 << index; return (1); }
C
#define _CRT_SECURE_NO_WARNINGS 1 // versionĿ # include <windows.h> # include <iostream> # pragma push_macro // ý̺Ͳϵͳİ汾Ϣļʾ void main() { // ȡ̵ID DWORD dwIdThis = ::GetCurrentProcessId(); // һ̺ͱİ汾ҲԷ0Աָһ DWORD dwVerReq = ::GetProcessVersion(dwIdThis); WORD wMajorReq = (WORD)(dwVerReq>16); WORD wMinorReq = (WORD)(dwVerReq & 0xffff); std::cout << "Process ID:" << dwIdThis << ",requires OS:" << wMajorReq << wMinorReq << std::endl; // ð汾ϢݽṹԱ㱣ϵͳİ汾Ϣ OSVERSIONINFOEX osvix; ::ZeroMemory(&osvix, sizeof(osvix)); osvix.dwOSVersionInfoSize = sizeof(osvix); // ȡ汾Ϣͱ ::GetVersionEx(reinterpret_cast<LPOSVERSIONINFO>(&osvix)); std::cout << "Running on OS:" << osvix.dwMajorVersion << "." << osvix.dwMinorVersion << std::endl; // ʾ̵ǰȼ DWORD dwProcessP : GetPriorityClass(GetCurrentProcess()); std::cout << "Current process priority is:"; switch (dwProcessP){ case HIGH_PRIORTY_CLASS: std::cout << "High"; break; case NORMAL_PRIORTY_CLASS: std::cout << "Normal"; break; case IDLE_PRIORTY_CLASS: std::cout << "Idle"; break; case REALTIME_PRIORTY_CLASS: std::cout << "RealTime"; break; default: std::cout << "unknow"; break; } std::cout << std::endl; // NTS (Windows 2000) ϵͳȨ if (osvix.dwPlatformld == VER_PLATFORM_WIN32_NT && osvix.dwMajorVersion >= 5) { if (dwProcessP != HIGH_PRIORITY_CLASS){ // ǰȼhighıȼ ::SetPriorityClass( ::GetCurrentProcess(), // һ HIGH_PRIORITY_CLASS); // ıΪhigh // û dwProcessP = GetPriorityClass(GetCurrentProcess()); std::cout << "The process priority have been changed to "; switch (dwProcessP) { case HIGH_PRIORITY_CLASS: std::cout << "High"; break; case NORMAL_PRIORITY_CLASS: std::cout << "Normal"; break; case IDLE_PRIORITY_CLASS: std::cout << "Idle"; break; case REALTIME_PRIORITY_CLASS: std::cout << "Realtime"; break; default: std::cout << "<unknow>"; break; } std::cout << std::endl; } }
C
#include <stdio.h> double calc(char op, double num1, double num2); int main() { char op; double num1; double num2; printf("Select operand to use (+, -, *, /):\n"); scanf(" %c", &op); // " %c", space needed to get char printf("Input first number:\n"); scanf("%lf", &num1); printf("Input second number:\n"); scanf("%lf", &num2); printf("Result is equal to: %f\n", calc(op, num1, num2)); return 0; } double calc(char op, double num1, double num2) { if (op == '+') { return num1 + num2; } else if (op == '-') { return num1 - num2; } else if (op == '*') { return num1 * num2; } else if (op == '/') { return num1 / num2; } else { printf("Invalid operator\n"); return 0; } }
C
// (C) 2021 Quenio. Licensed under CC0 1.0: https://creativecommons.org/publicdomain/zero/1.0 #include <stdio.h> int main() { int count = 0; int c; while ((c = getchar()) != EOF) { if (c == '\n') { count++; } } printf("line count = %d\n", count); }
C
/* * Copyright (c) 1991 Michael Landy * * Disclaimer: No guarantees of performance accompany this software, * nor is any responsibility assumed on the part of the authors. All the * software has been tested extensively and every effort has been made to * insure its reliability. */ /* * greybar - generate a ramp of grey bars * * usage: greybar [-s barheight [barwidth]] [-n numbar] [-f frames] * [-nc numcolor] * [-g mingrey maxgrey | -i mingrey step] >oseq * * Creates a sequence consisting of a ramp of vertical grey bars. -s * specifies the size of each bar (barheight defaults to 512 and barwidth to * 16). -n specifies the number of bars (the default is enough to make the * width of the image be 512 or nearly so). The frame will be output the * number of times specified by -f times that specified by -nc. * The leftmost bar has greylevel mingrey. * The greylevels either step by the amount specified by -i, or so as to * reach the maximum level specified by -g. The default is `-g 0 255'. * * to load: cc -o greybar greybar.c -hipsh -lhips * * HIPS 2 - Michael Landy - 8/16/91 */ #include <stdio.h> #include <hipl_format.h> static Flag_Format flagfmt[] = { {"s",{LASTFLAG},1,{{PTINT,"512","barheightr"}, {PTINT,"16","barwidth"},LASTPARAMETER}}, {"n",{LASTFLAG},1,{{PTINT,"-1","numbars"},LASTPARAMETER}}, {"f",{LASTFLAG},1,{{PTINT,"1","frames"},LASTPARAMETER}}, {"nc",{LASTFLAG},1,{{PTINT,"1","numcolor"},LASTPARAMETER}}, {"g",{"i",LASTFLAG},2,{{PTBOOLEAN,"TRUE"},{PTINT,"0","mingrey"}, {PTINT,"255","maxgrey"},LASTPARAMETER}}, {"i",{"g",LASTFLAG},2,{{PTINT,"-1","mingrey"},{PTINT,"-1","step"}, LASTPARAMETER}}, LASTFLAG}; int main(argc,argv) int argc; char **argv; { h_boolean gflag; int frames,nc,f,bh,bw,nb,gmin,gmax,imin,istep; double min,step; struct header hd; Progname = strsave(*argv); parseargs(argc,argv,flagfmt,&bh,&bw,&nb,&frames,&nc,&gflag,&gmin,&gmax, &imin,&istep,FFNONE); if (nb < 0) nb = 512 / bw; if (nb <= 0) nb = 1; init_header(&hd,"","",frames*nc,"",bh,nb*bw,PFBYTE,nc,""); write_headeru(&hd,argc,argv); alloc_image(&hd); if (gflag) { min = gmin; step = ((float) gmax - gmin) / (nb - 1); } else { min = imin; step = istep; } h_greybar(&hd,bw,min,step); frames *= nc; for (f=0;f<frames;f++) write_image(&hd); return(0); }
C
/* ** my_strcmp.c for my_strcmp in /home/thibrex/delivery/CPool_Day06/tests ** ** Made by Cornolti Thibaut ** Login <thibrex@epitech.net> ** ** Started on Mon Oct 10 11:28:45 2016 Cornolti Thibaut ** Last update Sun Nov 6 22:27:33 2016 yann probst */ int my_strcmp(char *s1, char *s2) { int i; i = 0; while (s1[i] != 0 || s2[i] != 0) { if (s1[i] != s2[i]) return ((s1[i] - s2[i] < 0) ? -1 : 1); i += 1; } return (0); }
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* get_single_arg_arr.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: twalton <marvin@42.fr> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2017/07/14 21:03:51 by twalton #+# #+# */ /* Updated: 2017/07/14 21:03:51 by twalton ### ########.fr */ /* */ /* ************************************************************************** */ #include "checker.h" static int check_leading_zeros(char *arg) { if (arg[0] == '0' && arg[1]) return (-7); if ((arg[0] == '-' || arg[0] == '+') && arg[1] == '0' && arg[2]) return (-7); if ((arg[0] == '-' || arg[0] == '+') && arg[1] == '0' && !arg[2]) return (-8); return (1); } static int is_valid_arg(char *arg) { int i; i = 0; if (arg[0] == '-' || arg[0] == '+' || ft_isdigit(arg[0])) ++i; else return (-1); while (arg[i]) { if (!ft_isdigit(arg[i])) return (-1); ++i; } if (i == 1 && (arg[0] == '-' || arg[0] == '+')) return (-6); if (check_leading_zeros(arg) < 0) return (check_leading_zeros(arg)); if (arg[0] == '-' && ft_atoi(arg) == 0) return (-5); if (arg[0] != '-' && ft_atoi(arg) == -1) return (-4); return (1); } static void check_for_duplicates(int *arr) { int i; int j; i = 1; j = 2; while (i <= arr[0]) { while (j <= arr[0]) { if (arr[i] == arr[j]) arr[0] = -3; j++; } i++; j = i + 1; } } int *get_single_arg_arr(char *str) { char **strarr; int i; int *arr; if (!(strarr = ft_strsplit(str, ' '))) return (NULL); if (strarr[0] == NULL) return ((int*)1); i = 0; while (strarr[i]) ++i; if (!(arr = malloc(sizeof(int) * (i + 1)))) return (NULL); i = 1; while (strarr[i - 1]) { if ((arr[0] = is_valid_arg(strarr[i - 1])) <= 0) return (arr); arr[i] = ft_atoi(strarr[i - 1]); ++i; } arr[0] = i - 1; check_for_duplicates(arr); return (arr); }
C
#include "edicao.h" void alocarMemoria(Ptr_imagem ptr_imagem) { ptr_imagem->pixel = (Pixel **) malloc(ptr_imagem->alt * sizeof(Pixel *)); for (int i = 0; i < ptr_imagem->alt; i++) { ptr_imagem->pixel[i] = (Pixel *) malloc(ptr_imagem->larg * sizeof(Pixel)); } } bool isppm(char *caminhoImagem) { int nomeTam = strlen(caminhoImagem); bool achou = false; if (nomeTam > 4) { achou = true; int startIndex = nomeTam - 1; for (int i = startIndex; i >= 0; i--) { if (i == startIndex && caminhoImagem[i] != 'm') { achou = false; break; } else if (i == startIndex - 1 && caminhoImagem[i] != 'p') { achou = false; break; } else if (i == startIndex - 2 && caminhoImagem[i] != 'p') { achou = false; break; } else if (i == startIndex - 3 && caminhoImagem[i] != '.') { achou = false; break; } } } if (!achou) { return false; } return true; } char *lerImagem(Ptr_imagem ptr_imagem, char *caminhoImagem) { if (!isppm(caminhoImagem)) { return "Por favor, escolha uma imagem do tipo .ppm"; } FILE *imagem; imagem = fopen(caminhoImagem, "r"); if (imagem == NULL) { return "Ocorreu um erro ao abrir a imagem"; } // Leitura do código da imagem. Para confirmar que realmente haverá a manipulação de um arquivo P3 fscanf(imagem, "%s", ptr_imagem->cod); if (strcmp(ptr_imagem->cod, "P3") != 0) { fclose(imagem); return "Apenas o código P3 é suportado"; } fscanf(imagem, "%i", &ptr_imagem->larg); fscanf(imagem, "%i", &ptr_imagem->alt); alocarMemoria(ptr_imagem); fscanf(imagem, "%i", &ptr_imagem->max); for (int i = 0; i < ptr_imagem->alt; i++) { for (int j = 0; j < ptr_imagem->larg; j++) { fscanf(imagem, "%hhu", &ptr_imagem->pixel[i][j].vermelho); fscanf(imagem, "%hhu", &ptr_imagem->pixel[i][j].verde); fscanf(imagem, "%hhu", &ptr_imagem->pixel[i][j].azul); } } fclose(imagem); return NULL; } void gravarImagem(Ptr_imagem ptr_imagem, char *caminhoImagem) { FILE *imagem; if (!isppm(caminhoImagem)) { strcat(caminhoImagem, ".ppm"); } imagem = fopen(caminhoImagem, "w"); fprintf(imagem, "%s\n", ptr_imagem->cod); fprintf(imagem, "%i ", ptr_imagem->larg); fprintf(imagem, "%i\n", ptr_imagem->alt); fprintf(imagem, "%i\n", ptr_imagem->max); for (int i = 0; i < ptr_imagem->alt; i++) { for (int j = 0; j < ptr_imagem->larg; j++) { fprintf(imagem, "%hhu ", ptr_imagem->pixel[i][j].vermelho); fprintf(imagem, "%hhu ", ptr_imagem->pixel[i][j].verde); fprintf(imagem, "%hhu\n", ptr_imagem->pixel[i][j].azul); } } fclose(imagem); free(ptr_imagem->pixel); } void filtroEscalaCinza(Ptr_imagem ptr_imagem) { for (int i = 0; i < ptr_imagem->alt; i++) { for (int j = 0; j < ptr_imagem->larg; j++) { Pixel pixel = ptr_imagem->pixel[i][j]; int mediaCores = (ptr_imagem->pixel[i][j].vermelho + ptr_imagem->pixel[i][j].verde + ptr_imagem->pixel[i][j].azul) / 3; ptr_imagem->pixel[i][j].vermelho = mediaCores; ptr_imagem->pixel[i][j].verde = mediaCores; ptr_imagem->pixel[i][j].azul = mediaCores; } } } void ampliar(Ptr_imagem ptr_imagem, int amp) { // A variável ampliar será responsável por receber a apliação que o usuário deseja usar Imagem imagemTemp; imagemTemp.larg = ptr_imagem->larg * amp; imagemTemp.alt = ptr_imagem->alt * amp; alocarMemoria(&imagemTemp); for (int i = 0, k = 0; i < ptr_imagem->alt && k < imagemTemp.alt; k++) { if (k % amp == 0 && k != 0) { i++; } for (int j = 0, l = 0; j < ptr_imagem->larg && l < imagemTemp.larg; l++) { if (l % amp == 0 && l != 0) { j++; } imagemTemp.pixel[k][l] = ptr_imagem->pixel[i][j]; } } free(ptr_imagem->pixel); ptr_imagem->larg = imagemTemp.larg; ptr_imagem->alt = imagemTemp.alt; ptr_imagem->pixel = imagemTemp.pixel; } void reduzir(Ptr_imagem ptr_imagem, int red) { Imagem imagemTemp; imagemTemp.larg = ptr_imagem->larg / red; imagemTemp.alt = ptr_imagem->alt / red; alocarMemoria(&imagemTemp); int redQuad = red * red; for(int i = 0, k = 1; i < imagemTemp.alt && k < ptr_imagem->alt; i++, k += red) { for(int j = 0, l = 1; j < imagemTemp.larg && l < ptr_imagem->larg; j++, l += red) { int somaRed = 0; int somaGreen = 0; int somaBlue = 0; for (int m = 0, n = 0, o = 0; m < redQuad; m++) { n++; if (m % red == 0 && m != 0) { o++; } if (n > 1) { n = 0; } if (o > 1) { o = 0; } somaRed += ptr_imagem->pixel[k - n][l - o].vermelho; somaGreen += ptr_imagem->pixel[k - n][l - o].verde; somaBlue += ptr_imagem->pixel[k - n][l - o].azul; } imagemTemp.pixel[i][j].vermelho = somaRed / redQuad; imagemTemp.pixel[i][j].verde = somaGreen / redQuad; imagemTemp.pixel[i][j].azul = somaBlue / redQuad; } } free(ptr_imagem->pixel); ptr_imagem->alt = imagemTemp.alt; ptr_imagem->larg = imagemTemp.larg; ptr_imagem->pixel = imagemTemp.pixel; } void rotacionar(Ptr_imagem ptr_imagem, int angulo) { Imagem imagemTemp; imagemTemp.alt = ptr_imagem->larg; imagemTemp.larg = ptr_imagem->alt; alocarMemoria(&imagemTemp); for (int i = ptr_imagem->alt - 1, j = 0; j < ptr_imagem->alt && i >= 0; j++, i--) { for (int k = 0; k < ptr_imagem->larg; k++) { imagemTemp.pixel[k][i] = ptr_imagem->pixel[j][k]; } } free(ptr_imagem->pixel); ptr_imagem->alt = imagemTemp.alt; ptr_imagem->larg = imagemTemp.larg; ptr_imagem->pixel = imagemTemp.pixel; } void filtroMascara(Ptr_imagem ptr_imagem, float mascara[3][3]) { Imagem imagemTemp; imagemTemp.alt = ptr_imagem->alt; imagemTemp.larg = ptr_imagem->larg; alocarMemoria(&imagemTemp); float vermelho; float verde; float azul; for (int i = 0; i < ptr_imagem->alt; i++) { for (int j = 0; j < ptr_imagem->larg; j++) { vermelho = 0; verde = 0; azul = 0; if (i > 0) { if (j > 0) { vermelho += ptr_imagem->pixel[i - 1][j - 1].vermelho * mascara[0][0]; verde += ptr_imagem->pixel[i - 1][j - 1].verde * mascara[0][0]; azul += ptr_imagem->pixel[i - 1][j - 1].azul * mascara[0][0]; } vermelho += ptr_imagem->pixel[i - 1][j].vermelho * mascara[0][1]; verde += ptr_imagem->pixel[i - 1][j].verde * mascara[0][1]; azul += ptr_imagem->pixel[i - 1][j].azul * mascara[0][1]; if (j < ptr_imagem->larg - 1) { vermelho += ptr_imagem->pixel[i - 1][j + 1].vermelho * mascara[0][2]; verde += ptr_imagem->pixel[i - 1][j + 1].verde * mascara[0][2]; azul += ptr_imagem->pixel[i - 1][j + 1].azul * mascara[0][2]; } } if (j > 0) { vermelho += ptr_imagem->pixel[i][j - 1].vermelho * mascara[1][0]; verde += ptr_imagem->pixel[i][j - 1].verde * mascara[1][0]; azul += ptr_imagem->pixel[i][j - 1].azul * mascara[1][0]; } vermelho += ptr_imagem->pixel[i][j].vermelho * mascara[1][1]; verde += ptr_imagem->pixel[i][j].verde * mascara[1][1]; azul += ptr_imagem->pixel[i][j].azul * mascara[1][1]; if (j < ptr_imagem->larg - 1) { vermelho += ptr_imagem->pixel[i][j + 1].vermelho * mascara[1][2]; verde += ptr_imagem->pixel[i][j + 1].verde * mascara[1][2]; azul += ptr_imagem->pixel[i][j + 1].azul * mascara[1][2]; } if (i < ptr_imagem->alt - 1) { if (j > 0) { vermelho += ptr_imagem->pixel[i + 1][j - 1].vermelho * mascara[2][0]; verde += ptr_imagem->pixel[i + 1][j - 1].verde * mascara[2][0]; azul += ptr_imagem->pixel[i + 1][j - 1].azul * mascara[2][0]; } vermelho += ptr_imagem->pixel[i + 1][j].vermelho * mascara[2][1]; verde += ptr_imagem->pixel[i + 1][j].verde * mascara[2][1]; azul += ptr_imagem->pixel[i + 1][j].azul * mascara[2][1]; if (j < ptr_imagem->larg - 1) { vermelho += ptr_imagem->pixel[i + 1][j + 1].vermelho * mascara[2][2]; verde += ptr_imagem->pixel[i + 1][j + 1].verde * mascara[2][2]; azul += ptr_imagem->pixel[i + 1][j + 1].azul * mascara[2][2]; } } vermelho = vermelho > 255 ? 255 : vermelho < 0 ? 0 : vermelho; verde = verde > 255 ? 255 : verde < 0 ? 0 : verde; azul = azul > 255 ? 255 : azul < 0 ? 0 : azul; imagemTemp.pixel[i][j].vermelho = vermelho; imagemTemp.pixel[i][j].verde = verde; imagemTemp.pixel[i][j].azul = azul; } } free(ptr_imagem->pixel); ptr_imagem->alt = imagemTemp.alt; ptr_imagem->larg = imagemTemp.larg; ptr_imagem->pixel = imagemTemp.pixel; } void filtroBinarizar(Ptr_imagem ptr_imagem, int binarizar) { for (int i = 0; i < ptr_imagem->alt; i++) { for (int j = 0; j < ptr_imagem->larg; j++) { int media = (ptr_imagem->pixel[i][j].vermelho + ptr_imagem->pixel[i][j].verde + ptr_imagem->pixel[i][j].azul) / 3; if (media > binarizar) { ptr_imagem->pixel[i][j].vermelho = 255; ptr_imagem->pixel[i][j].verde = 255; ptr_imagem->pixel[i][j].azul = 255; } else { ptr_imagem->pixel[i][j].vermelho = 0; ptr_imagem->pixel[i][j].verde = 0; ptr_imagem->pixel[i][j].azul = 0; } } } } void filtroNegativo(Ptr_imagem ptr_imagem) { for (int i = 0; i < ptr_imagem->alt; i++) { for (int j = 0; j < ptr_imagem->larg; j++) { ptr_imagem->pixel[i][j].vermelho = (unsigned char) (255 - (int) ptr_imagem->pixel[i][j].vermelho); ptr_imagem->pixel[i][j].verde = (unsigned char) (255 - (int) ptr_imagem->pixel[i][j].verde); ptr_imagem->pixel[i][j].azul = (unsigned char) (255 - (int) ptr_imagem->pixel[i][j].azul); } } } void filtroPixelizar(Ptr_imagem ptr_imagem) { Pixel mediaPixel; // i+=1 efeito fica tipo gaussiano for (int i = 1; i < ptr_imagem->alt; i+=2) { for (int j = 1; j < ptr_imagem->larg; j+=2) { mediaPixel.vermelho = (ptr_imagem->pixel[i - 1][j - 1].vermelho + ptr_imagem->pixel[i - 1][j].vermelho + ptr_imagem->pixel[i][j- 1].vermelho + ptr_imagem->pixel[i][j].vermelho) /4; mediaPixel.verde = (ptr_imagem->pixel[i - 1][j - 1].verde + ptr_imagem->pixel[i- 1][j].verde + ptr_imagem->pixel[i][j- 1].verde + ptr_imagem->pixel[i][j].verde) /4; mediaPixel.azul = (ptr_imagem->pixel[i - 1][j - 1].azul + ptr_imagem->pixel[i- 1][j].azul + ptr_imagem->pixel[i][j- 1].azul + ptr_imagem->pixel[i][j].azul) /4; ptr_imagem->pixel[i - 1][j - 1] = mediaPixel; ptr_imagem->pixel[i - 1][j] = mediaPixel; ptr_imagem->pixel[i][j - 1] = mediaPixel; ptr_imagem->pixel[i][j] = mediaPixel; } } } void filtroSobel(Ptr_imagem ptr_imagem) { const char borHor[3][3] = {{-1, 0, 1 }, {-2, 0, 2}, {-1, 0, 1}}; const char borVert[3][3] = {{1, 2, 1}, {0, 0, 0 }, {-1, -2, -1}}; Imagem imagemTemp; imagemTemp.alt = ptr_imagem->alt; imagemTemp.larg = ptr_imagem->larg; alocarMemoria(&imagemTemp); int valorHor, valorVert, novoPixel; // Retirar da bordar indíces negativos for (int i = 1; i < (ptr_imagem->alt)-1; i++) { for (intgcc src/main.c src/funcoes.c -o bin/main -lm j = 1; j < (ptr_imagem->larg)-1; j++) { valogcc src/main.c src/funcoes.c -o bin/main -lmrHor = 0; valogcc src/main.c src/funcoes.c -o bin/main -lmrVert = 0; for (int k = 0; k < 3; k++){ for (int l = 0; l < 3; l++){ valorHor += ((ptr_imagem->pixel[i-1+k][j-1+l].vermelho) * (borHor[k][l])); valorVert += ((ptr_imagem->pixel[i-1+k][j-1+l].vermelho) * (borVert[k][l])); } } novoPixel = sqrt(pow(valorVert, 2) + pow(valorHor, 2)); imagemTemp.pixel[i][j].vermelho = novoPixel; imagemTemp.pixel[i][j].verde = novoPixel; imagemTemp.pixel[i][j].azul = novoPixel; } } free(ptr_imagem->pixel); ptr_imagem->alt = imagemTemp.alt; ptr_imagem->larg = imagemTemp.larg; ptr_imagem->pixel = imagemTemp.pixel; } void filtroGaussiano(Ptr_imagem ptr_imagem) { int gaussianos[5][5] = {{ 2, 4, 5, 4, 2 },{ 4, 9, 12, 9, 4 },{ 5, 12, 15, 12, 5 },{ 4, 9, 12, 9, 4 },{ 2, 4, 5, 4, 2 }}; Imagem imagemTemp; imagemTemp.alt = ptr_imagem->larg; imagemTemp.larg = ptr_imagem->alt; alocarMemoria(&imagemTemp); for (int i = 0; i < ptr_imagem->alt; i++) { for (int j = 0; j < ptr_imagem->larg; j++) { int vermelho = 0; int verde = 0; int azul = 0; for (int k = 0; k < 5; k++) { for (int l = 0; l < 5; l++) { if(k+2+i < ptr_imagem->alt && k-2+i >= 0 && j-2+1 >= j+2+k < ptr_imagem->larg){ vermelho += ptr_imagem->pixel[i-2+k][j-2+l].vermelho * gaussianos[k][l]; verde += ptr_imagem->pixel[i-2+k][j-2+l].verde * gaussianos[k][l]; azul += ptr_imagem->pixel[i-2+k][j-2+l].azul * gaussianos[k][l]; } } imagemTemp.pixel[i][j].vermelho = vermelho / 159; imagemTemp.pixel[i][j].verde = verde / 159; imagemTemp.pixel[i][j].azul = azul / 159 ; } } } free(ptr_imagem->pixel); ptr_imagem->alt = imagemTemp.alt; ptr_imagem->larg = imagemTemp.larg; ptr_imagem->pixel = imagemTemp.pixel; }
C
/* c6-5.h Ķ(ӣֵ)洢ʾ */ typedef struct CSNode { TElemType data; struct CSNode *firstchild,*nextsibling; }CSNode,*CSTree;
C
/* switch statement: as the declaration of the case labels */ #include <stdio.h> void keyword_case(void) { enum { AIRPLANE, CAR, TRAIN } tool = 0; switch (tool) { case AIRPLANE: printf("airplane\n"); break; case CAR: printf("air\n"); break; case TRAIN: printf("train\n"); break; default: printf("unknown\n"); break; } } int main(void) { keyword_case(); return 0; } /* https://en.cppreference.com/w/c/keyword/case */
C
#include "linked_list.h" #include "stddef.h" #include "stdlib.h" #include "stdio.h" /* create a new node */ /* returns a pointer to the newly created node */ /* print an error message and return NULL if an error occurs */ Node *initialise_node(void) { Node *node; node = (Node*) malloc(sizeof(Node)); if (node==NULL){ printf("error"); return NULL; } /*node->data=NULL;*/ node->next=NULL; node->prev=NULL; return node; } /* free memory for node *node */ /* print an error message and return if node is NULL */ void free_node(Node *node) { if(node==NULL) { /*printf("free node error\n");*/ return; } free(node); } /* create a new linked list */ /* returns a pointer to the newly created list */ /* print an error message and return NULL if an error occurs */ LinkedList *initialise_linked_list(void) { LinkedList *list; list = (LinkedList *) malloc(sizeof(LinkedList)); if (list==NULL){ printf("error"); return NULL; } list->head = NULL; list->tail = NULL; return list; } /* free memory for linked list *list */ /* frees memory for all nodes in linked list and list itself */ /* print an error message and return if list is NULL */ void free_linked_list(LinkedList *list) { Node* node; Node* nodecancel; if (list==NULL) { /*printf("error in linked list function\n");*/ return; } node = list->head; while ( node!=NULL) { nodecancel=node; node=nodecancel->next; free(nodecancel); } free(list); return; } /* create and add node to the tail of linked list *list */ /* and set data stored at node to *data */ /* should return a pointer to the new node */ /* should return NULL if an error occurs */ Node *append_linked_list(LinkedList *list, void *data) { Node *node; if(list==NULL){ /*printf("you cant append to an empty list\n");*/ return NULL; } node = initialise_node(); node->data = data; if (list->tail == NULL) { list->head=node; list->tail=node; return node; } list->tail->next = node; node->prev = list->tail; list->tail = node; node->data = data; return node; } /* create and add node to the head of linked list *list */ /* and set data stored at node to *data */ /* should return a pointer to the new node */ /* should return NULL if an error occurs */ Node *prepend_linked_list(LinkedList *list, void *data) { Node *node; if (list == NULL) { /*printf("error on create add node\n");*/ return NULL; } node = initialise_node(); node->data=data; if (list->tail == NULL) { node->next=NULL; node->prev=NULL; list->head=node; list->tail=node; }else{ list->head->prev=node; node->next=list->head; list->head=node; } return node; } /* remove head from linked list *list */ /* print an error message and return if list is NULL or empty */ void remove_head_linked_list(LinkedList *list) { Node *node; if(list==NULL){ /*printf("Error on remove head\n");*/ return ; } if ( list->head == NULL ) { printf("Error on remove head\n"); return; } if (list->head->next == NULL){ /* node = list->head; list->head = NULL; list->tail = NULL; free_node(node);*/ return; } node = list->head; list->head = list->head->next; list->head->prev = NULL; free_node(node); return; } /* remove tail from linked list *list */ /* print an error message and return if list is NULL or empty */ void remove_tail_linked_list(LinkedList *list) { Node *node; if(list==NULL){ /*printf("error on remove tail\n");*/ return ; } if ( list->tail == NULL ) { printf("error on remove tail\n"); return; } if (list->tail->prev == NULL){ /*node = list->tail; list->tail = NULL; list->head = NULL; free_node(node);*/ return; } node = list->tail; list->tail = list->tail->prev; list->tail->next = NULL; free_node(node); return; } /* print data stored in linked list *list to stdout */ /* prints data from head to tail */ /* prints each node data on a newline */ /* user gives pointer to function *print_func which is called to print data */ /* print an error message and return if list or print function is NULL */ /* don't print anything if the list is empty */ void print_linked_list(LinkedList *list, void (*print_func)(void *)) { Node *node; if(list==NULL || print_func==NULL){ /*printf("error on print linked list\n");*/ return; } node=list->head; while(node!=NULL) { print_func(node->data); node=node->next; } return; } /* print char pointed to by *ptr to stdout */ void print_char(void *ptr) { fprintf(stdout,"%c\n",*((char*)ptr)); } /* print int pointed to by *ptr to stdout */ void print_int(void *ptr) { fprintf(stdout,"%d\n",*((int*)ptr)); } /* print double pointed to by *ptr to stdout */ void print_double(void *ptr) { fprintf(stdout,"%f\n",*((double*)ptr)); } /* print a string pointed to by *ptr to stdout */ void print_string(void *ptr) { fprintf(stdout,"%s\n",(char*)ptr); }
C
#define ex1 #include <stdio.h> #include <stdlib.h> #include <conio.h> #include <locale.h> #ifdef ex1 /*1 - Escreva um programa que receba uma letra via teclado. Escreva uma funcao que pesquise esta letra dentro do vetor abaixo. Imprima o resultado da pesquisa no video na funcao main(). Passe como informacao para a funcao a letra digitada.(utilize o comando return). O vetor deve ser uma variavel global. vetor -> b,d,f,h,j,k,m,o,q,s,u,w,y*/ char c[] = {'b','d','f','h','j','k','m','o','q','s','u','w','y'}; int letra(char a){ int i,x; for (i = 0;i <= 13; i++){ if (c[i] == a){ x = 1;}} if (x == 1){ return 1; }else{ return 0;}} int main() { inicio: setlocale(LC_ALL, "portuguese"); char a,resp; printf("Digite uma letra e veja se ela esta contida no nosso vetor:"); a = getche(); if(letra(a) == 1){ printf("\n\nA letra que voc digitou FOI encontrada no nosso vetor!\nLetra digitada: %c.\nVetor: b,d,f,h,j,k,m,o,q,s,u,w,y.\n", a); }else{ printf("\n\nA letra que voc digitou NO foi encontrada no nosso vetor!\nLetra digitada: %c.\nVetor: b,d,f,h,j,k,m,o,q,s,u,w,y.\n", a);} printf("\nDeseja rodar o programa de novo ? S/N "); resp = getch(); if(resp == 'S' || resp == 's'){ system("cls"); goto inicio; } } #endif // ex1 #ifdef ex2 /*2 - Escreva um programa que receba na funcao main() 2 valores inteiro. Escreva uma funcao para cada operacoes aritmeticas e passe como parametro os 2 valores recebidos na funcao main(). Retorne os resultados usando o comando return e imprima-os no video na funcao main().*/ int soma(int x, int y) { int r; r = x + y; return r; } int sub(int x, int y) { int r; r = x - y; return r; } int mult(int x, int y) { int r; r = x * y; return r; } float divi(int x, int y) { float r; r = (float)x / (float)y; return r; } void main() { setlocale(LC_ALL, "portuguese"); char resp; int x,y,som,su,mul; float div; do{ printf("Digite dois nmeros para realizar as quatro operaes com eles: "); scanf("%i %i", &x,&y); som = soma(x,y); su = sub(x,y); mul = mult(x,y); div = divi(x,y); printf("\n%i + %i = %i.\n", x, y, som); printf("\n%i - %i = %i.\n", x, y, su); printf("\n%i * %i = %i.\n", x, y, mul); printf("\n%i / %i = %f.\n", x, y, div); printf("\nDeseja rodar o programa de novo ? S/N "); resp = getch();system("cls"); }while(resp == 'S' || resp == 's'); } #endif // ex2 #ifdef ex3 /*3. Reescreva o programa do exercicio anterior para receber via teclado n valores. Os n valores nao sao definidos previamente.*/ int soma(int a, int b) { return a+b; } int sub(int a, int b) { return a-b; } int mult(int a, int b) { return a*b; } float divi(float a, float b) { return (float)a/(float)b; } void main() { setlocale(LC_ALL, "portuguese"); char resp; int i, n, val1, val2; int aux, aux1, aux2; float aux3; do{ printf("Digite quantos valores voc deseja que sejam calculados: "); do{ scanf("%d", &n); if(n <= 1){printf("\aO nmero mnimo de valores 2! Digite novamente!\n");} }while(n <= 1); printf("Digite o 1 valor: "); scanf("%d", &val1); printf("Digite o 2 valor: "); scanf("%d", &val2); aux = soma(val1,val2); aux1 = sub(val1,val2); aux2 = mult(val1,val2); aux3 = divi(val1,val2); for(i = 2; i < n; i++){ printf("Digite o %d valor: ", i+1); scanf("%d", &val1); aux = soma(aux, val1); aux1 = sub(aux1,val1); aux2 = mult(aux2,val1); aux3 = divi(aux3,val1); } printf("\nSOMA = %d\n", aux); printf("SUBTRAO = %d\n", aux1); printf("MULTIPLICAO = %d\n", aux2); printf("DIVISO = %f\n", aux3); printf("\nDeseja rodar o programa de novo ? S/N "); fflush(stdin);resp = getch();system("cls"); }while(resp == 'S' || resp == 's'); } #endif // ex3 #ifdef ex4 /*4. Aproveitando o programa anterior inclua a selecao das operacoes aritmeticas para transforma-lo em uma calculadora. (utilize o comando switch).*/ int soma(int a, int b) { return a+b; } int sub(int a, int b) { return a-b; } int mult(int a, int b) { return a*b; } float divi(float a, float b) { return (float)a/(float)b; } void main() { setlocale(LC_ALL, "portuguese"); char resp; int i, n, val1, val2; int aux, aux1, aux2; float aux3; do{ printf("Digite quantos valores voc deseja que sejam calculados: "); do{ scanf("%d", &n); if(n == 1){printf("\aO nmero mnimo de valores 2! Digite novamente!\n");} }while(n == 1); printf("Digite o 1 valor: "); scanf("%d", &val1); printf("Digite o 2 valor: "); scanf("%d", &val2); aux = soma(val1,val2); aux1 = sub(val1,val2); aux2 = mult(val1,val2); aux3 = divi(val1,val2); for(i = 2; i < n; i++){ printf("Digite o %d valor: ", i+1); scanf("%d", &val1); aux = soma(aux, val1); aux1 = sub(aux1,val1); aux2 = mult(aux2,val1); aux3 = divi(aux3,val1); } printf("\nPressione 1 para ver a soma destes valores\n"); printf("Pressione 2 para ver a subtrao destes valores\n"); printf("Pressione 3 para ver a multiplicao destes valores\n"); printf("Pressione 4 para ver a diviso destes valores\n"); val2 = getch(); refazer: switch(val2) { case '1': printf("\nSOMA = %d\n", aux); break; case '2': printf("\nSUBTRAO = %d\n", aux1); break; case '3': printf("\nMULTIPLICAO = %d\n", aux2); break; case '4': printf("\nDIVISO = %g\n", aux3); break; default: printf("\aEsse nmero no indica nenhuma operao, escolha outra!\n"); val2 = getch(); goto refazer; } printf("\nDeseja rodar o programa de novo ? S/N "); fflush(stdin);resp = getch();system("cls"); }while(resp == 'S' || resp == 's'); } #endif // ex4 #ifdef ex5 /*5. Escreva um programa que receba na funcao main() 2 strings de ate' 10 caracteres. Escreva as funcoes que compare estas 2 strings e retorne se sao IGUAIS 1 e se DIFERENTES 0. Declare as strings como variavel global.*/ char str1[11], str2[11]; int cmpstr(char str1[], char str2[]) { int i, igual; for(i = 0, igual = 0; str1[i] != '\0' || str2[i] != '\0'; i++){ if(str1[i] == str2[i]){ igual++; } } if(igual == i){ return 1; }else{ return 0;} } void main() { setlocale(LC_ALL, "portuguese"); char resp; int comparacao; do{ printf("Digite duas strings de at 10 caracteres para compar-las\n"); printf("Primeira String: "); scanf("%s", &str1); printf("Segunda String: "); scanf("%s", &str2); comparacao = cmpstr(str1, str2); if(comparacao == 1){ printf("\nAs strings so iguais!\n"); }else{ printf("\nAs strings so diferentes!\n");} printf("\nDeseja rodar o programa de novo ? S/N "); resp = getch();system("cls"); }while(resp == 'S' || resp == 's'); } #endif // ex5
C
#include<stdio.h> #include<string.h> int calc(int a, int b, char ch) { switch(ch) { case '+': return a+b; case '-': return a-b; case '*': return a*b; case '/': return a/b; default: return 0; } return 0; } void write_file () { FILE *fp = fopen("1.txt", "w"); fputs("10+10=\n",fp); fputs("10-10=\n",fp); fputs("10*10=\n",fp); fputs("10/10=\n",fp); fputs("10+5=\n",fp); fputs("10-5=\n",fp); fputs("10*3=\n",fp); fputs("10/2=\n",fp); fclose(fp); } void read_file () { char temp[1024]; FILE *fp = fopen("1.txt", "r"); char buf[1024]; while(1) { memset( buf, 0, sizeof(buf) ); fgets(buf, sizeof(buf), fp); if(strlen(buf) > 0) { int a,b; char ch; sscanf(buf, "%d%c%d=\n", &a, &ch, &b); sprintf(buf, "%d %c %d = %d\n", a, ch, b, calc(a,b,ch) ); printf("%s",buf); strcat(temp,buf); } if(feof(fp)) break; } fclose(fp); fp = fopen("1.txt", "w"); fputs(temp,fp); fclose(fp); } int main (int argc, char *argv[]) { write_file(); read_file(); return 0; }
C
#include <stdio.h> int main() { int sum = 0, num, success_input; printf("һ<q>"); success_input = scanf("%d",&num); while (success_input = 1) //ע!Ӧsuccess_input == 1 { sum += num; printf("һ<q>"); success_input = scanf("%d",&num); } printf("ܺ%d\n",sum); return 0; }
C
#include <stdio.h> main(){ int contador; contador=0; for(contador = 0; contador < 100000; contador++) { printf("%d\n", contador); } }
C
/*-----------------------------------------------------------------------*/ /* Low level disk I/O module skeleton for FatFs (C)ChaN, 2013 */ /*-----------------------------------------------------------------------*/ /* If a working storage control module is available, it should be */ /* attached to the FatFs via a glue function rather than modifying it. */ /* This is an example of glue functions to attach various exsisting */ /* storage control module to the FatFs module with a defined API. */ /*-----------------------------------------------------------------------*/ #include "base.h" #include "diskio.h" /* FatFs lower layer API */ #include "spi_flash.h" /* SPI Flash contorl */ /* Definitions of physical drive number for each media */ #define SPI_FLASH 0 /*-----------------------------------------------------------------------*/ /* Inidialize a Drive */ /*-----------------------------------------------------------------------*/ /* Physical drive nmuber (0..) */ DSTATUS disk_initialize(BYTE pdrv) { DSTATUS stat = 0; switch (pdrv) { case SPI_FLASH: SPI_Flash_Init(); return stat; default: break; } return STA_NOINIT; } /*-----------------------------------------------------------------------*/ /* Get Disk Status */ /*-----------------------------------------------------------------------*/ /* Physical drive nmuber (0..) */ DSTATUS disk_status(BYTE pdrv) { DSTATUS stat = 0; switch (pdrv) { case SPI_FLASH: return stat; default: break; } return STA_NOINIT; } /*-----------------------------------------------------------------------*/ /* Read Sector(s) */ /*-----------------------------------------------------------------------*/ /* Physical drive nmuber (0..) */ /* Data buffer to store read data */ /* Sector address (LBA) */ /* Number of sectors to read (1..128) */ DRESULT disk_read(BYTE pdrv, BYTE *buff, DWORD sector, UINT count) { DRESULT res = RES_PARERR; switch (pdrv) { case SPI_FLASH: SPI_Flash_Read(sector << 12, buff, count << 12); res = RES_OK; break; default: break; } return res; } /*-----------------------------------------------------------------------*/ /* Write Sector(s) */ /*-----------------------------------------------------------------------*/ /* Physical drive nmuber (0..) */ /* Data to be written */ /* Sector address (LBA) */ /* Number of sectors to write (1..128) */ #if _USE_WRITE DRESULT disk_write(BYTE pdrv, const BYTE *buff, DWORD sector, UINT count) { DRESULT res = RES_PARERR; UINT i; switch (pdrv) { case SPI_FLASH: for (i = 0; i < count; i++) { SPI_Flash_SectorErase((sector + i) << 12); } SPI_Flash_Write(sector << 12, buff, count << 12); res = RES_OK; break; default: break; } return res; } #endif //_USE_WRITE /*-----------------------------------------------------------------------*/ /* Miscellaneous Functions */ /*-----------------------------------------------------------------------*/ /* Physical drive nmuber (0..) */ /* Control code */ /* Buffer to send/receive control data */ #if _USE_IOCTL DRESULT disk_ioctl(BYTE pdrv, BYTE cmd, void *buff) { DRESULT res = RES_PARERR; switch (pdrv) { case SPI_FLASH: switch (cmd) { case CTRL_SYNC: res = RES_OK; break; case GET_BLOCK_SIZE: *(DWORD *)buff = SPI_FLASH_SECTOR_SIZE; res = RES_OK; break; case GET_SECTOR_COUNT: *(DWORD *)buff = SPI_FLASH_SECTOR_COUNT; res = RES_OK; break; case GET_SECTOR_SIZE: *(WORD *)buff = SPI_FLASH_SECTOR_SIZE; res = RES_OK; break; default: break; } break; default: break; } return res; } #endif //_USE_IOCTL
C
/* ======= TYPEDEF ======= -Similar to the symbolic name */ #include <stdio.h> typedef int* INT_POINTER; //synonim typedef struct date DATE; struct date { int day; int month; int year; }; struct person { char firstname[11]; char surname[21]; struct date DOB; }; main() { int *p1; int *p2; //same as below INT_POINTER p1; INT_POINTER p2; }
C
#include "app/plane.h" #include "app/airline.h" #include "communication/plane.h" #include <stdlib.h> #define CHECK_EXIT(r) {if((r) == -1) {print_error("Read invalid message in plane\n");pthread_exit(0);}} #define echo(msg) mprintf("[%d] "msg"\n", self->plane->id) #define SafeActionWithClean(block, onexit) { \ if (MessageTypeEnd == message_queue_peek(self->queue)) { \ onexit; \ pthread_exit(0); \ } \ block; \ } #define SafeAction(block) SafeActionWithClean(block, {}) #define SafeExit(block) SafeAction(CHECK_EXIT(block)) static int unload_stock(struct PlaneThread* self); void run_plane(struct PlaneThread* self) { int destinations[5], distances[5]; size_t len; pthread_setcancelstate(PTHREAD_CANCEL_ENABLE, NULL); pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL); echo("Preparing to start"); while (self->done == 0 && comm_step(self) != -1) { echo("Waking for phase 1"); if (self->plane->distance == 0) { SafeExit(unload_stock(self)); } SafeAction(app_airline_plane_ready()); if (self->done) { echo("I unloaded everything, so I'm bialing"); break; } echo("Waiting for phase2..."); SafeExit(comm_continue(self)); if (self->plane->distance == 0) { len = 5; SafeExit(comm_check_destinations(self, destinations, distances, &len)); if (len == 0) { echo("Done early dude!"); self->done = 1; } else { mprintf("[%d] Goint from %d to %d with distance %d\n", self->plane->id, self->plane->cityId, *destinations, *distances); self->plane->cityId = *destinations; self->plane->distance = *distances; } } else { self->plane->distance--; } SafeAction(app_airline_plane_ready()); } self->done = 1; } int unload_stock(struct PlaneThread* self) { int* stockDelta = NULL; Vector* stocks = self->plane->stocks; size_t stockLen = getVectorSize(stocks); stockDelta = malloc(sizeof(int) * stockLen); if (stockDelta == NULL) { free(stockDelta); return -1; } SafeActionWithClean({ if (comm_unload_stock(self, stockDelta) == -1) { free(stockDelta); return -1; } }, { free(stockDelta); }); int done = 1; for (size_t i = 0; i < stockLen; i++) { Stock* stock = (Stock*) getFromVector(stocks, i); stock->amount = stockDelta[i]; if (stock->amount > 0) { done = 0; } else if (stock->amount < 0) { print_error("Got negative stock when unloading\n"); return -1; } } free(stockDelta); if (done) { self->done = 1; } return 0; }
C
/*Matrix addition,subtraction and multiplication Program*/ #include<stdio.h> void add( int a1[2][2], int a2[2][2]); void subtract(int a1[2][2], int a2[2][2]); void multiply(int a1[2][2], int a2[2][2]); int main() { int arr1[2][2], arr2[2][2]; int i,j; /* take input in both the array */ printf("Enter first array "); for( i=0 ; i<2 ; i++ ){ for( j=0 ; j<2 ; j++ ) scanf("%d",&arr1[i][j]);} printf("Enter second array "); for( i=0 ; i<2 ; i++ ){ for( j=0 ; j<2 ; j++ ) scanf("%d",&arr2[i][j]);} add(arr1, arr2); subtract(arr1, arr2); multiply(arr1, arr2); getch(); } add(int a1[2][2],int a2[2][2]) { int result[2][2]; int i,j; for( i=0 ; i<2 ; i++ ){ for( j=0 ; j<2 ; j++ ) result[i][j]=a1[i][j]+a2[i][j]; } /* Print output matrix*/ printf("\nAddition of array is "); for( i=0 ; i<2 ; i++ ){ for( j=0 ; j<2 ; j++ ) printf("%d\t",result[i][j]); } } subtract(int a1[2][2],int a2[2][2]) { int result[2][2]; int i,j; for( i=0 ; i<2 ; i++ ){ for( j=0 ; j<2 ; j++ ) result[i][j]=a1[i][j]-a2[i][j]; } /* Print output matrix*/ printf("\nSubtraction of array is "); for( i=0 ; i<2 ; i++ ){ for( j=0 ; j<2 ; j++ ) printf("%d\t",result[i][j]); } } multiply(int a1[2][2],int a2[2][2]) { int result[2][2]; int i,j,k; for( i=0 ; i<2 ; i++ ){ for( j=0 ; j<2 ; j++ ){ result[i][j]=0; for( k=0 ; k<2 ; k++ ){ result[i][j]+= (a1[i][k]*a2[k][j]); } } } /* Print output matrix*/ printf("\nMultiplication of array is "); for( i=0 ; i<2 ; i++ ){ for( j=0 ; j<2 ; j++ ) printf("%d\t",result[i][j]); } }
C
// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. #include <openenclave/host.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include "run_u.h" int main(int argc, const char* argv[]) { oe_result_t r; oe_enclave_t* enclave = NULL; const oe_enclave_type_t type = OE_ENCLAVE_TYPE_SGX; const uint32_t flags = OE_ENCLAVE_FLAG_DEBUG; int retval; if (argc != 2) { fprintf(stderr, "Usage: %s ENCLAVE_PATH\n", argv[0]); return 1; } r = oe_create_run_enclave(argv[1], type, flags, NULL, 0, &enclave); if (r != OE_OK) { fprintf(stderr, "%s: oe_create_echo_enclave(): %u\n", argv[0], r); exit(1); } r = run_ecall(enclave, &retval); if (r != OE_OK) { fprintf(stderr, "%s: echo_ecall(): %u\n", argv[0], r); exit(1); } if (retval != 0) { fprintf(stderr, "%s: bad retval=%d\n", argv[0], retval); exit(1); } r = oe_terminate_enclave(enclave); if (r != OE_OK) { fprintf(stderr, "%s: oe_terminate_enclave(): %u\n", argv[0], r); exit(1); } printf("=== passed test (%s)\n", argv[1]); return 0; }
C
#include<stdio.h> #include<string.h> #include<cs50.h> int main() { // Character string of curtain size char text[100]; int j=0; // Taking input for text while(text[j-1] != '\n') { if( text[j-1] == '\b') { text[j-1] = '\0'; j = j-2; } text[j] = getchar(); j++; } text[j] = '\0'; //this will store encrypted string char coded[j]; coded[j] = '\0'; // Convert the text int k = 0; //this will encrypt the text string for(int i = 0 ; i < j ; i++) { if ( (text[i] >= 65 && text[i] <= 90) || (text[i] >= 97 && text[i] <= 122) ) { if( k == 0 ) { if (text[i] >= 65 && text[i] <= 90) coded[i] = ((1 + (text[i] - 65)) % 26) + 65; else coded[i] = ((1 + (text[i] - 97)) % 26) + 97; k = 1; } else if( k == 1) { coded[i] = text[i]; k = 2; } else { if (text[i] >= 65 && text[i] <= 90) coded[i] = ((25 + (text[i] - 65)) % 26) + 65; else coded[i] = ((25 + (text[i] - 97)) % 26) + 97; k = 0; } } else coded[i] = text[i]; } printf("Text = %s",text); printf("Coded = %s",coded); return 0; }
C
#include "labData_2D.h" /*-----------------------------------------------------------------------------*/ /* Fichier source pour la création, l'affichage et le mise à jour du tableau 2D*/ /*-----------------------------------------------------------------------------*/ /*Fonction qui va initialiser notre tableau en 2D à partir du tableau en 1D renvoyé par getlabyrinth()*/ char** init_lab(char *labData,t_joueur p1,t_joueur p2,t_joueur tresor,int sizeX, int sizeY) { //Variables utiles pour les boucles for int i,j; //Initialisation du tableau en 2D char** tabData; tabData = (char**) malloc(sizeY*sizeof(char*)); for (i=0;i<sizeY;i++) tabData[i] = (char*) malloc(sizeX*sizeof(char)); //On parcourt notre tableau en 2D for (i=0;i<sizeY;i++) { for (j=0;j<sizeX;j++) { //Si nous arrivons sur une coordonné d'un joueur ou du tresor, on insert le caractère correspondant à sa position if((i==p1.y && j==p1.x) || (i==p2.y && j==p2.x) || (i==sizeY/2 && j==sizeX/2)) { if((i==p1.y && j==p1.x)) tabData[i][j]=JOUEUR; else if((i==p2.y && j==p2.x)) tabData[i][j]=ADVER; else if((i==tresor.y && j==tresor.x)) tabData[i][j]=TRESOR; } //Sinon on ajoute la case correspondante au tableau en 1D else { tabData[i][j] = labData[i*sizeX+j]; //printf("%d|",tabData[i][j]); } } printf("\n"); } return tabData; } /*Fonction qui va nous permettre d'afficher le labyrinth avec des 0 et des 1 pour que l'on puisse comprendre nos différents bug*/ void affichage_2D(char** labData_2D,t_joueur p1,t_joueur p2,t_joueur tresor,int sizeX,int sizeY) { //Variables utiles pour les boucles for int i,j; //On parcourt le tableau en 2D for(i=0;i<sizeY;i++) { for(j=0;j<sizeX;j++) { //Si nous sommes sur une position d'un joueur ou du tresor on affiche le caractère correspondant if(i==p1.y && j==p1.x) printf(">|"); else if(i==p2.y && j==p2.x) printf("@|"); else if(i==tresor.y && j==tresor.x) printf("T|"); //Sinon on affiche juste la case (0 ou 1) else printf("%d|",labData_2D[i][j]); } printf("\n"); } } /*Fonction qui va mettre le tableau en 2D à jour après des déplacements ou rotations*/ void maj_lab(char **labData_2D,int mv,int val,t_joueur* p1,t_joueur* p2,t_joueur* tresor,int sizeX,int sizeY, int player) { //Variable utile pour les boucles for int i; //Variable de sauvegarde du premier caractère lorsque l'on bouge une ligne ou une colone char temp; /*Selon le mouvement nous effectuons la mise à jour*/ switch(mv) { /*Bouger une ligne vers la gauche*/ case 0: if (p2->y == val) //Si l'adversaire est sur la ligne { labData_2D[p2->y][p2->x] = 0; //On remplace le caractère par 0 //On modifie la coordonnée du joueur if (p2 -> x == 0) p2->x = sizeX-1; else p2->x--; } if (tresor->y == val) //Si le trésor est sur la ligne { labData_2D[tresor->y][tresor->x] = 0; //On remplace le caractère par 0 //On modifie la coordonnée du tresor if (tresor->x == 0) tresor->x = sizeX-1; else tresor->x--; } if (p1->y == val) //Si on est sur la ligne { labData_2D[p1->y][p1->x] = 0; //On remplace le caractère par 0 //On modifie la coordonnée du joueur if (p1->x == 0) p1->x = sizeX-1; else p1->x--; } temp = labData_2D[val][0]; //On sauvegarde le premier caractère de la ligne //On parcourt la ligne pour remettre les caractères correspondant au bonne position dans notre tableau for(i=0;i<sizeX-1;i++) labData_2D[val][i]=labData_2D[val][i+1]; labData_2D[val][sizeX-1]=temp; labData_2D[p1->y][p1->x]=JOUEUR; labData_2D[p2->y][p2->x]=ADVER; labData_2D[tresor->y][tresor->x]=TRESOR; break; /*Bouger une ligne vers la droite*/ case 1: if (p2->y == val) //Si l'adversaire est sur la ligne { labData_2D[p2->y][p2->x] = 0; //On remplace le caractère par 0 //On modifie la coordonnée du joueur if (p2->x == sizeX-1) p2->x = 0; else p2->x++; } if (tresor->y == val) //Si le tresor est sur la ligne { labData_2D[tresor->y][tresor->x] = 0; //On remplace le caractère par 0 //On modifie la coordonnée du tresor if (tresor->x == sizeX-1) tresor->x = 0; else tresor->x++; } if (p1->y == val) // Si on est sur la ligne { labData_2D[p1->y][p1->x] = 0; //On remplace le caractère par 0 //On modifie la coordonnée du joueur if (p1->x == sizeX-1) p1->x = 0; else p1->x++; } //On sauvegarde le premier caractère de la ligne temp = labData_2D[val][sizeX-1]; //On parcourt la ligne pour remettre les caractères correspondant au bonne position dans notre tableau for(i=sizeX-1;i>0;i--) labData_2D[val][i]=labData_2D[val][i-1]; labData_2D[val][0]=temp; labData_2D[p1->y][p1->x]=JOUEUR; labData_2D[p2->y][p2->x]=ADVER; labData_2D[tresor->y][tresor->x] = TRESOR; break; /*Bouger une colonne vers le haut*/ case 2: if (p2->x == val) // Si l'adversaire est sur la colone { labData_2D[p2->y][p2->x] = 0; //On remplace le caractère par 0 //On modifie la coordonnée du joueur if (p2 -> y == 0) p2->y = sizeY-1; else p2->y--; } if (tresor->x == val) // Si le trésor est sur la colone { labData_2D[tresor->y][tresor->x] = 0; //On remplace le caractère par 0 //On modifie la coordonnée du tresor if (tresor->y == 0) tresor->y = sizeY-1; else tresor->y--; } if (p1->x == val) // Si on est sur la colone { labData_2D[p1->y][p1->x] = 0; //On remplace le caractère par 0 //On modifie la coordonnée du joueur if (p1->y == 0) p1->y = sizeY-1; else p1->y--; } //On sauvegarde le premier caractère de la colone temp = labData_2D[0][val]; //On parcourt la ligne pour remettre les caractères correspondant au bonne position dans notre tableau for(i=0;i<sizeY-1;i++) labData_2D[i][val]=labData_2D[i+1][val]; labData_2D[sizeY-1][val]=temp; labData_2D[p1->y][p1->x]=JOUEUR; labData_2D[p2->y][p2->x]=ADVER; labData_2D[tresor->y][tresor->x]=TRESOR; break; /*Bouger une colonne vers le bas*/ case 3: if (p2->x == val) // Si l'adversaire est sur la colone { labData_2D[p2->y][p2->x] = 0; //On remplace le caractère par 0 //On modifie la coordonnée du joueur if (p2 -> y == sizeY-1) p2->y = 0; else p2->y++; } if (tresor->x == val) // Si le trésor est sur la colone { labData_2D[tresor->y][tresor->x] = 0; //On remplace le caractère par 0 //On modifie la coordonnée du tresor if (tresor->y == sizeY-1) tresor->y = 0; else tresor->y++; } if (p1->x == val) // Si on est sur la colone { labData_2D[p1->y][p1->x] = 0; //On remplace le caractère par 0 //On modifie la coordonnée du joueur if (p1->y == sizeY-1) p1->y = 0; else p1->y++; } //On sauvegarde le premier caractère de la colone temp = labData_2D[sizeY-1][val]; //On parcourt la ligne pour remettre les caractères correspondant au bonne position dans notre tableau for(i=sizeY-1;i>0;i--) labData_2D[i][val]=labData_2D[i-1][val]; labData_2D[0][val]=temp; labData_2D[p1->y][p1->x]=JOUEUR; labData_2D[p2->y][p2->x]=ADVER; labData_2D[tresor->y][tresor->x]=TRESOR; break; /*Déplacement vers le haut*/ case 4: if (player == 1) //Si c'est l'adversaire qui joue { labData_2D[p2->y][p2->x] = 0; //On remplace la position par un 0 car si un joueur y était c'est que ce n'était pas un mur (1) if (p2->y == 0) p2->y = sizeY-1; //Si le joueur est sur un bord else p2->y --; labData_2D[p2->y][p2->x] = ADVER; //On met le caractère du joueur à la nouvelle position dans le tableau } else //Sinon c'est nous qui jouons { labData_2D[p1->y][p1->x] = 0; //On remplace la position par un 0 car si un joueur y était c'est que ce n'était pas un mur (1) if (p1->y == 0) p1->y = sizeY-1; //Si le joueur est sur un bord else p1->y --; labData_2D[p1->y][p1->x] = JOUEUR; //On met le caractère du joueur à la nouvelle position dans le tableau } break; /*Déplacement vers la bas*/ case 5: if (player == 1) //Si c'est l'adversaire qui joue { labData_2D[p2->y][p2->x] = 0; //On remplace la position par un 0 car si un joueur y était c'est que ce n'était pas un mur (1) if (p2->y == sizeY-1) p2->y = 0; //Si le joueur est sur un bord else p2->y ++; labData_2D[p2->y][p2->x] = ADVER; //On met le caractère du joueur à la nouvelle position dans le tableau } else //Sinon c'est nous qui jouons { labData_2D[p1->y][p1->x] = 0; //On remplace la position par un 0 car si un joueur y était c'est que ce n'était pas un mur (1) if (p1->y == sizeY-1) p1->y = 0; //Si le joueur est sur un bord else p1->y ++; labData_2D[p1->y][p1->x] = JOUEUR; //On met le caractère du joueur à la nouvelle position dans le tableau } break; /*Déplacement vers la gauche*/ case 6: if (player == 1) //Si c'est l'adversaire qui joue { labData_2D[p2->y][p2->x] = 0; //On remplace la position par un 0 car si un joueur y était c'est que ce n'était pas un mur (1) if (p2->x == 0) p2->x = sizeX-1; //Si le joueur est sur un bord else p2->x --; labData_2D[p2->y][p2->x] = ADVER; //On met le caractère du joueur à la nouvelle position dans le tableau } else //Sinon c'est nous qui jouons { labData_2D[p1->y][p1->x] = 0; //On remplace la position par un 0 car si un joueur y était c'est que ce n'était pas un mur (1) if (p1->x == 0) p1->x = sizeX-1; //Si le joueur est sur un bord else p1->x --; labData_2D[p1->y][p1->x] = JOUEUR; //On met le caractère du joueur à la nouvelle position dans le tableau } break; /*Déplacement vers la droite*/ case 7: if (player == 1) //Si c'est l'adversaire qui joue { labData_2D[p2->y][p2->x] = 0; //On remplace la position par un 0 car si un joueur y était c'est que ce n'était pas un mur (1) if (p2->x == sizeX-1) p2->x = 0; //Si le joueur est sur un bord else p2->x ++; labData_2D[p2->y][p2->x] = ADVER; //On met le caractère du joueur à la nouvelle position dans le tableau } else //Sinon c'est nous qui jouons { labData_2D[p1->y][p1->x] = 0; //On remplace la position par un 0 car si un joueur y était c'est que ce n'était pas un mur (1) if (p1->x == sizeX-1) p1->x = 0; //Si le joueur est sur un bord else p1->x ++; labData_2D[p1->y][p1->x] = JOUEUR; //On met le caractère du joueur à la nouvelle position dans le tableau } break; }
C
#include<stdio.h> void main() { //һЩҪõIJ int number,i,j,temp; //ֵʼ i=0; //һ16λŶʼΪ0 int array[16] = {0}; printf("please input a number:"); scanf("%d",&number); temp = number; //%2 while(temp != 0) { array[i] = temp % 2; //ģ2㣬ֵ temp = temp / 2; i++; } // for (j = 15; j >= 0; j--) { printf("%d", array[j]); if (j % 4 ==0 ){ printf(" "); } } }
C
/* bluepp 2014-06-21 2014-07-23 May the force be with me! Problem: Reverse Linked List II Source: https://oj.leetcode.com/problems/reverse-linked-list-ii/ Notes: Reverse a linked list from position m to n. Do it in-place and in one-pass. For example: Given 1->2->3->4->5->NULL, m = 2 and n = 4, return 1->4->3->2->5->NULL. Note: Given m, n satisfy the following condition: 1 <= m <= n <= length of list. Solution: in-place & one-pass. */ ListNode *reverseBetween(ListNode *head, int m, int n) { ListNode dummy(0); dummy.next = head; ListNode *prev = &dummy; for (int i = 0; i < m-1; i++) { prev = prev->next; } ListNode *pCurr = prev->next; ListNode *pEnd = pCurr; ListNode *pprev = NULL; for(int i = 0; i <= n-m; i++) { ListNode *pNext = pCurr->next; pCurr->next = pprev; pprev = pCurr; pCurr = pNext; } prev->next = pprev; pEnd->next = pCurr; return dummy.next; }
C
/****************************************************************************** * Copyright (C) 2017 by Alex Fosdick - University of Colorado * * Redistribution, modification or use of this software in source or binary * forms is permitted as long as the files maintain this copyright. Users are * permitted to modify this and use it to learn about the field of embedded * software. Alex Fosdick and the University of Colorado are not liable for any * misuse of this material. * *****************************************************************************/ /** * @file data.c * @brief Convertion between integer and ASCII * * This implementation file provides an abstraction of converting between integer * and ASCII string. * * @author Alex Fosdick * @date April 1 2017 * */ #include "data.h" #include "memory.h" #include <stdbool.h> #include "platform.h" uint8_t my_itoa(int32_t data, uint8_t * ptr, uint32_t base){ int length = 1; uint8_t * temp_ptr = ptr; uint32_t temp = (uint32_t)((data < 0) ? data*(-1): data); *(temp_ptr++) = 0; do { uint8_t rem = temp % base; *(temp_ptr++) = (rem > 9)? (rem + 65): (rem + 48); temp /= base; length++; } while (temp != 0); if (data < 0){ *(temp_ptr++) = 45; length++; } my_reverse(ptr, length); return length; } int32_t my_atoi(uint8_t * ptr, uint8_t digits, uint32_t base){ int32_t data = 0; uint8_t temp = 0; bool isSigned = false; for (int i = 0; i < digits-1; i++) { temp = *(ptr++); data *= base; if (temp == 45) { isSigned = true; } else if (temp != 0) { data += (temp-((temp >= 65)?65:48)); } } if (isSigned) data *= -1; return data; }
C
/* * misc.h * * Created on: May 29, 2016 * Author: Aymeric Genet */ #ifndef MISC_H_ #define MISC_H_ #define MAX_SAMPLE_DIGIT 6 #include "math.h" #include <stdio.h> /* * Initializes the reading of a file containing random elements. Typical uses * include "/dev/random" and "/dev/urandom". * * @return 1 (true) if opening the file was successful, 0 (false) othwerise */ int init_random(char * path); /* * Reads 4 random bytes from the file initiated by init_random() and writes it * in dest. * WARNING : must call init_random() beforehand, or the function blocks. * * @param dest The destination for the random bytes * @return 1 (true) if reading the file was successful, 0 (false) otherwise */ int read_random(math_t * dest); /* * Reads 4 random bytes from the file initiated by init_random() and writes a * random floating between [0, 1] in dest. * WARNING : must call init_random() beforehand, or the function blocks. * * @param dest The destination for the random double * @return 1 (true) if reading the file was successful, 0 (false) otherwise */ int read_drandom(double * dest); /* * Closes the reading of the file initiated by init_random(). * * @return 1 (true) if closing the file was successful, 0 (false) othwerise */ int close_random(); /* * Opens a persistent table T^l containing samples for sample reduction. * * @param file File to be read after opening * @param path Path to a persistent table T^l * @return 1 (true) if opening the file was successful, 0 (false) otherwise */ int open_table(FILE ** file, char * path); /* * Reads next sample from file and puts it into res. * * @param res Vector containing the sample read * @param file File to be read * @return 1 (true) if reading was successful, 0 (false) otherwise */ int read_sample(vec_t res, FILE * file, long q, int n); /* * Appends a sample in a file. * * @param file File in which sample has to be appended * @param vec Sample to be appended * @param n Size of the sample * @return 1 (true) if appending the sample was successful, 0 (false) otherwise */ int append_sample(FILE * file, vec_t vec, int n); /* * Closes the file to the persistent table T^l. * * @param file File to close * @return 1 (true) if closing the file was successful, 0 (false) othwerise */ int close_table(FILE ** file); #endif /* MISC_H_ */
C
#include<stdio.h> #define MAX 5 int main() { int i,j; int space=0; /*run loop (parent loop) till number of rows*/ for(i=MAX;i>0;i--) { /*print first set of stars*/ for(j=0;j< i;j++) { printf("*"); } for(j=0;j< space;j++) { printf(" "); } /*print second set of stars*/ for(j=0;j< i;j++) { printf("*"); } printf("\n"); space+=2; } return 0; }
C
#include <stdio.h> #include <stdlib.h> #include <time.h> #include <string.h> #include <math.h> #include "ManipSeqSimple.h" // Affiche la chaine de caractères seq de longueur lg void AfficheSeq(char seq[], int lg){ int i; for (i=0; i<lg; i++) { printf("%c", seq[i]); } printf("\n"); } // Affiche la chaine de caractères seq de longueur lg void AfficheSeqBornes(char seq[], int debut, int fin){ int i; for (i=debut; i<fin-1; i++) { printf("%c", seq[i]); } printf("\n"); } // Remplie la chaine de caractère seq de lg nucléotides tirés aléatoirement void InitSeqAlea(char seq[], int lg){ int i; char bases[5] = "ATGC\0"; srand(time(NULL)); for (i=0; i<lg; i++) { seq[i] = bases[rand()%4]; } seq[lg] = '\0'; } // Retourne la proportion en GC dans la séquence seq de longeur lg float GC(char seq[], int lg){ float GC=0; int i; for (i=0; i<lg; i++) { if ( seq[i] == 'G' || seq[i] == 'C' ) // si une base de la seq est un G ou C { GC += 1; } } return GC/lg; } // retourne 1 si codon start ; retourne 0 si codon stop // *seq -> pointeur de la première base du codon int estStart(char *seq){ char codon[4]; memcpy(codon, seq, 3); codon[3] = '\0'; if (strcmp(codon, "ATG") == 0) // retourne 0 si les chaines sont identiques { return 1; } else { return 0;} } int estStop(char *seq){ char codon[4]; memcpy(codon, seq, 3); codon[3] = '\0'; if ( strcmp(codon, "TAA")== 0 \ || strcmp(codon, "TAG")== 0 \ || strcmp(codon, "TGA")== 0) // retourne 0 si les chaines sont identiques { return 1; } else { return 0;} } char Nt_Complementaire(char nt){ switch (nt){ case 'A': return 'T'; break; case 'T': return 'A'; break; case 'G': return 'C'; break; case 'C': return 'G'; break; default : return '\0'; break; } } int compteGC3en3(char *seq, int lgSeq){ int comptGC=0, i; for (i=0; i<lgSeq; i+=3){ if (seq[i]== 'G' || seq[i]== 'C'){ comptGC+=1; } } return comptGC; } float calcChi2Conformite(char *seq, int lg, float GCGlobal ){ float chi2=0,GCpos3, GCth, ATth,ATpos3; GCth = GCGlobal*lg; // effectif de GC théorique à une position donné du codon ATth = lg - GCth; GCth /=3; ATth /=3; GCpos3 = compteGC3en3((seq),lg); ATpos3 = lg/3 - GCpos3; //printf("GCth : %f, ATth : %f\n",GCth,ATth); //printf("GCpos3 : %f, ATpos3 : %f\n",GCpos3,ATpos3); chi2 = pow((GCpos3 - GCth),2)/ GCth + \ pow((ATpos3 - ATth),2)/ GCth; return chi2; // alpha = 0.05 ddl = 1; chi2 = 3.84 } /* int main (){ int lg = 100 +1; //ne pas oublier le \0 à la fin d'une chaine de caractères char seq[lg]; float propor_GC; InitSeqAlea (seq, lg); AfficheSeq(seq,lg); propor_GC = GC (seq,lg); float Chi2; Chi2 = calcChi2Conformite(seq, lg, propor_GC); // printf("Chi2 : %f \n", Chi2); return 0; } */
C
#include<stdio.h> #include<stdlib.h> #include<string.h> #include<sqlite3.h> static int callback(void *not_used, int argc, char **argv, char **col_name) { static print_head = 0; int i; #if 1 if(0 == print_head) { for(i = 0; i < argc; i++) { printf("%s\t",col_name[i]); } printf("\n"); print_head = 1; } #endif for(i = 0; i < argc; i++) { printf("%s\t",argv[i]?argv[i]:"NULL"); //printf("%s\t",argv[0]); } printf("\n"); return 0; } int main(int argc, char *argv[]) { sqlite3 *db = NULL; char *err_msg = NULL; int rc = sqlite3_open("score_mgr.db",&db); if(rc != SQLITE_OK) { fprintf(stderr,"open falied %s\n",sqlite3_errmsg(db)); } else { fprintf(stderr,"open database successful\n"); } char *sql_select_student = (char *)malloc(100); memset(sql_select_student,0,100); sprintf(sql_select_student,"select name,age from %s;",argv[1]); rc = sqlite3_exec(db, sql_select_student, callback, 0, &err_msg); if(SQLITE_OK != rc) { fprintf(stderr,"sql err : %s\n", err_msg); sqlite3_free(err_msg); } else { fprintf(stderr, "table query successfully\n"); } sqlite3_close(db); return 0; }
C
#include <stdio.h> #include <stdlib.h> #include <string.h> struct street { int from, to, number; } streets[2048]; int comp[64]; int use[64]; int count; void print() { int i, j, k; struct street s; for(i = 0; i < count; i++) streets[i].number = i + 1; for(i = 0; i < count; i++) { j = rand() % count; k = rand() % count; s = streets[j]; streets[j] = streets[k]; streets[k] = s; } for(i = 0; i < count; i++) printf("%d %d %d\n", streets[i].from + 1, streets[i].to + 1, streets[i].number); printf("0 0\n"); } int find(int i) { int l,p=i; while(comp[i]!=i)i=comp[i]; while(p!=i){ l=p; p=comp[p]; comp[l]=i; } return i; } void add(int f, int t) { streets[count].from = f; streets[count].to = t; count++; comp[find(f)] = find(t); use[f]++; use[t]++; } void main() { int k, i, m, b; printf("1 2 1\n"); printf("2 3 2\n"); printf("3 1 6\n"); printf("1 2 5\n"); printf("2 3 3\n"); printf("3 1 4\n"); printf("0 0\n"); printf("1 2 1\n"); printf("2 3 2\n"); printf("1 3 3\n"); printf("2 4 4\n"); printf("0 0\n"); printf("1 1 1\n"); printf("0 0\n"); printf("1 1 1\n"); printf("1 1 2\n"); printf("0 0\n"); printf("1 2 1\n"); printf("2 3 2\n"); printf("1 3 3\n"); printf("2 4 4\n"); printf("2 4 5\n"); printf("0 0\n"); for(k = 30; k >= 0; k--) { count = 0; m = 1 + rand() % (1 + rand() % 44); memset(use, 0, sizeof(use[0]) * m); for(i = 0; i < m; i++) comp[i] = i; for(i = 1 + rand() % (1 + rand() % (1 + (m * m) / 3)); i >= 0; i--) add(rand() % m, rand() % m); for(i = 1; i < m; i++) if(find(i-1) != find(i)) add(comp[i-1], comp[i]); for(i = rand() % (1 + rand() % (1995 - count)); i >= 0; i--) add(rand() % m, rand() % m); if(rand() & 7) { b = -1; for(i = 0; i < m; i++) { if(use[i] & 1) { if(b != -1) { add(b, i); b = -1; } else b = i; } } } print(); } printf("0 0\n"); }
C
#include <stdio.h> #include <stdlib.h> #include <time.h> typedef enum { false, true } bool; void swapInt(int *a, int *b){ int tmp = *a; *a = *b; *b = tmp; } void bubbleSort(int *arr, int n){ if (n == 1) return; bool swapped = false; for (int i = 0; i < n - 1; ++i) { if (arr[i] > arr[i + 1]){ swapInt(arr + i, arr + i + 1); swapped = true; } } if (swapped){ bubbleSort(arr, n - 1); } } int main(int argc, char const *argv[]) { int arr[] = {6,6,7,420,32,69,45,2,789,5,46}; int length = sizeof(arr)/sizeof(arr[0]); clock_t begin,end; begin = clock(); bubbleSort(arr, length); end = clock(); printf("Temps de tri: %f sec\n", (double) (end - begin) / CLOCKS_PER_SEC); for (int i = 0; i < length; i++){ printf("%d ", arr[i]); } return 0; }
C
/* getchʹʾ ṩVisual C++MS-Windows/MS-DOS */ #include <conio.h> #include <ctype.h> #include <stdio.h> int main(void) { int ch; int retry; do { printf("밴"); ch = getch(); printf("\nµļ%cֵ%d\n", isprint(ch) ? ch : ' ', ch); printf("һΣYN"); retry = getch(); if (isprint(retry)) putch(retry); putchar('\n'); } while (retry == 'Y' || retry == 'y'); return 0; }
C
#include <GL/gl.h> #include <GL/glu.h> #include <GL/glut.h> #include <stdio.h> #include <math.h> #include <stdlib.h> #include <string.h> /* Initialize variables needed for animation */ float spinX = 0.0; float spinY = 0.0; float zoomIn = 0.0; float zoomOut = 0.0; /* Initialize material property and light source. */ void myinit(void) { // Light Properties GLfloat light_ambient[] = {0.0, 0.0, 0.0, 1.0}; GLfloat light_diffuse[] = {1.0, 1.0, 1.0, 1.0}; GLfloat light_specular[] = {1.0, 1.0, 1.0, 1.0}; GLfloat light_position[] = {100.0, 100.0, 100.0, 0.0}; //material properties GLfloat mat_specular[] = {0.5, 0.5, 0.5, 1.0}; GLfloat mat_shininess[]= {30.0}; glLightfv(GL_LIGHT0, GL_AMBIENT, light_ambient); glLightfv(GL_LIGHT0, GL_DIFFUSE, light_diffuse); glLightfv(GL_LIGHT0, GL_SPECULAR, light_specular); glLightfv(GL_LIGHT0, GL_POSITION, light_position); // Material Properties glMaterialfv(GL_FRONT, GL_SPECULAR, mat_specular); glMaterialfv(GL_FRONT, GL_SHININESS, mat_shininess); // Enable Various Components glEnable(GL_COLOR_MATERIAL); glEnable(GL_LIGHT0); glEnable(GL_DEPTH_TEST); glEnable(GL_LIGHTING); // Transparency feature glEnable(GL_BLEND); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); //Enable color material glColorMaterial(GL_FRONT,GL_DIFFUSE); } void animation() { spinY += 3.0; } void stopAnimation() { spinY = 0.0; } //key functions void keyboard(unsigned char key, int x, int y) { switch(key) { case 'x': spinX += 10.0; break; case 'X': spinY += 10.0; break; case 'Y': spinY += 10.0; break; case 'y': spinY += 10.0; break; case 'Z': zoomIn += 5.0; break; case 'z': zoomOut -= 5.0; break; case 'F': spinX += 50.0; break; case 'f': spinX += 50.0; break; case 'S': spinX += 0.1; break; case 's': spinX += 0.1; break; case 'T': stopAnimation(); break; case 't': stopAnimation(); break; case 27: exit(0); break; } } //Simulator Toy void toy() { glPushMatrix(); // Green Torus glTranslatef(0.0, -1.5, -1.5); glRotatef(90.0, 1.0, 0.0, 0.0); glColor3f(0.0, 0.5, 0.0); glutSolidTorus(0.275, 0.85, 15, 20); glPopMatrix(); glPushMatrix(); // Blue Torus glTranslatef(0.0, -1.0, -1.5); glRotatef(90.0, 1.0, 0.0, 0.0); glColor3f(0.0, 0.0, 1.0); glutSolidTorus(0.275, 0.75, 12, 17); glPopMatrix(); glPushMatrix(); // Red Torus glTranslatef(0.0, -0.55, -1.5); glRotatef(90.0, 1.0, 0.0, 0.0); glColor3f(1.0, 0.0, 0.0); glutSolidTorus(0.275, 0.65, 9, 14); glPopMatrix(); glPushMatrix(); // Pink Torus glTranslatef(0.0, -0.1, -1.5); glRotatef(90.0, 1.0, 0.0, 0.0); glColor3f(1.0, 0.0, 1.0); glutSolidTorus(0.275, 0.55, 9, 14); glPopMatrix(); glPushMatrix(); // yellow Torus glTranslatef(0.0, 0.35, -1.5); glRotatef(90.0, 1.0, 0.0, 0.0); glColor3f(1.0, 1.0, 0.0); glutSolidTorus(0.275, 0.45, 9, 14); glPopMatrix(); glPushMatrix(); // orange Torus glTranslatef(0.0, 0.75, -1.5); glRotatef(90.0, 1.0, 0.0, 0.0); glColor3f(1.0, 0.5, 0.0); glutSolidTorus(0.275, 0.35, 9, 14); glPopMatrix(); glPushMatrix(); // Tall Yellow Box glTranslatef( 0.0, -3, -1.5); glRotatef(45.0, 0.0, 1.0, 0.0); glScalef(1.0, 6.0, 1.0); glColor3f(1.0, 1.0, 0.0); glutSolidCube(0.5); glPopMatrix(); glPushMatrix(); // Tall Yellow Box glTranslatef( 0.0, 0.0, -1.5); glRotatef(45.0, 0.0, 1.0, 0.0); glScalef(1.0, 6.0, 1.0); glColor3f(1.0, 1.0, 0.0); glutSolidCube(0.5); glPopMatrix(); glPushMatrix(); // Flat Blue Box glTranslatef( 0.0, -2.0, -1.5); glRotatef(45.0, 0.0, 1.0, 0.0); glScalef(1.0, 0.2, 1.0); glColor3f(0.4, 0.5, 1.0); glutSolidCube(2.0); glPopMatrix(); glPushMatrix(); // Red Ball glTranslatef(0.0, 2.3, -1.5); glColor4f(1.0, 0.0, 0.0, 0.3); glutSolidSphere(0.85, 20, 10); glPopMatrix(); } /* Draw various things */ void display() { glLoadIdentity(); gluPerspective( 40.0, 1.0 , 0.1, 120.0); glMatrixMode(GL_MODELVIEW); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glClearColor(0.0,0.0,0.0,1.0); glLoadIdentity(); gluLookAt(0.0, 0.0, 20.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0); glPushMatrix(); //animation spinX += 0.0; spinY += 0.0; glPopMatrix(); glPushMatrix(); glRotatef(20.0, 1.0, 0.0, 0.0); glRotatef(spinY, 0.0, 1.0, 0.0); glRotatef(spinX, 1.0, 0.0, 0.0); glTranslatef(0.0,0.0,zoomIn); glTranslatef(0.0,0.0,zoomOut); //PYRAMIDS glPushMatrix(); //pyramids glTranslatef(2.0,0.0,-8.0); glRotatef(-30.0,0.0,0.0,1.0); glScalef(5.0,5.0,5.0); glColor3f(0.1,0.0,0.0); glutSolidTetrahedron(); glPopMatrix(); glPushMatrix(); //pyramids glTranslatef(-4.0,0.0,-8.0); glRotatef(-30.0,0.0,0.0,1.0); glScalef(5.0,5.0,5.0); glColor3f(0.1,0.0,0.0); glutSolidTetrahedron(); glPopMatrix(); glPushMatrix(); //pyramids glTranslatef(-2.0,0.0,-8.0); glRotatef(-30.0,0.0,0.0,1.0); glScalef(5.0,5.0,5.0); glColor3f(0.1,0.0,0.0); glutSolidTetrahedron(); glPopMatrix(); glPushMatrix(); //pyramids glTranslatef(-6.0,0.0,-8.0); glRotatef(-30.0,0.0,0.0,1.0); glScalef(5.0,5.0,5.0); glColor3f(0.1,0.0,0.0); glutSolidTetrahedron(); glPopMatrix(); glPushMatrix(); //pyramids glTranslatef(4.0,0.0,-8.0); glRotatef(-30.0,0.0,0.0,1.0); glScalef(5.0,5.0,5.0); glColor3f(0.1,0.0,0.0); glutSolidTetrahedron(); glPopMatrix(); glPushMatrix(); //pyramids glTranslatef(0.0,0.0,-8.0); glRotatef(-30.0,0.0,0.0,1.0); glScalef(5.0,5.0,5.0); glColor3f(0.1,0.0,0.0); glutSolidTetrahedron(); glPopMatrix(); glPushMatrix(); //pyramids glTranslatef(-8.0,0.0,-8.0); glRotatef(-30.0,0.0,0.0,1.0); glScalef(5.0,5.0,5.0); glColor3f(0.1,0.0,0.0); glutSolidTetrahedron(); glPopMatrix(); glPushMatrix(); //pyramids glTranslatef(6.0,0.0,-8.0); glRotatef(-30.0,0.0,0.0,1.0); glScalef(5.0,5.0,5.0); glColor3f(0.1,0.0,0.0); glutSolidTetrahedron(); glPopMatrix(); //SNOWMAN glPushMatrix(); //biggest sphere glTranslatef(3.0,-3.0,1.5); glColor3f(1.0,1.0,1.0); glutSolidSphere(1.0,20,30); glPopMatrix(); glPushMatrix(); //medium sphere glTranslatef(2.9,-1.5,1.5); glColor3f(1.0,1.0,1.0); glutSolidSphere(0.75,20,30); glPopMatrix(); glPushMatrix(); //smallest sphere sphere glTranslatef(2.85,-0.5,1.5); glColor3f(1.0,1.0,1.0); glutSolidSphere(0.45,20,30); glPopMatrix(); glPushMatrix(); // one eye glTranslatef(2.8, -0.3, 1.9); glRotatef(90.0, 0.0, 0.0, 0.0); glColor3f(0.0, 0.0, 0.0); glutSolidTorus(0.025, 0.05, 9, 14); glPopMatrix(); glPushMatrix(); // second eye glTranslatef(3.0, -0.3, 1.88); glRotatef(90.0, 0.0, 0.0, 0.0); glColor3f(0.0, 0.0, 0.0); glutSolidTorus(0.025, 0.05, 9, 14); glPopMatrix(); glPushMatrix(); // nose glTranslatef(2.9, -0.4, 1.9); glRotatef(90.0, 0.0, 0.0, 0.0); glColor3f(1.0, 0.5, 0.0); glutSolidCone(0.05, 0.5, 9, 14); glPopMatrix(); //PENGUIN glPushMatrix(); //body glTranslatef(-3.5,-3.0,1.5); glColor3f(0.0,0.0,0.0); glutSolidSphere(1.0,20,30); glScalef(0.0,0.0,0.25); glPopMatrix(); glPushMatrix(); //face glTranslatef(-3.5,-2.15,1.5); glColor3f(0.0,0.0,0.0); glutSolidSphere(0.75,20,30); glPopMatrix(); glPushMatrix(); //body glTranslatef(-3.5,-3.0,2.05); glColor3f(1.0,1.0,1.0); glutSolidSphere(0.65,20,30); glPopMatrix(); glPushMatrix(); //left eye glTranslatef(-3.55,-1.75,1.95); glColor3f(1.0,1.0,1.0); glutSolidSphere(0.2,20,30); glPopMatrix(); glPushMatrix(); //right eye glTranslatef(-3.25,-1.75,1.9); glColor3f(1.0,1.0,1.0); glutSolidSphere(0.2,20,30); glPopMatrix(); glPushMatrix(); // left pupil glTranslatef(-3.55, -1.65, 2.14); glRotatef(90.0, 0.0, 0.0, 0.0); glColor3f(0.0, 0.0, 0.0); glutSolidTorus(0.025, 0.05, 9, 14); glPopMatrix(); glPushMatrix(); // right pupil glTranslatef(-3.2, -1.65, 2.1); glRotatef(90.0, 0.0, 0.0, 0.0); glColor3f(0.0, 0.0, 0.0); glutSolidTorus(0.025, 0.05, 9, 14); glPopMatrix(); glPushMatrix(); // nose glTranslatef(-3.375, -1.85, 2.12); glRotatef(90.0, 0.0, 0.0, 0.0); glColor3f(1.0, 0.5, 0.0); glutSolidCone(0.1, 0.5, 9, 14); glPopMatrix(); glPushMatrix(); // left hand glTranslatef(-4.2,-2.8,2.0); glRotatef(-45.0, 0.0, 1.0, 0.0); glColor3f(1.0, 0.5, 0.0); glutSolidCone(0.15, 0.85, 9, 14); glPopMatrix(); glPushMatrix(); // right hand glTranslatef(-2.7,-2.8,1.9); glRotatef(45.0, 0.0, 1.0, 0.0); glColor3f(1.0, 0.5, 0.0); glutSolidCone(0.15, 0.85, 9, 14); glPopMatrix(); glPopMatrix(); toy(); glFlush(); glutSwapBuffers(); glutPostRedisplay(); } void myReshape(int w, int h) { glViewport(0, 0, w, h); glMatrixMode(GL_PROJECTION); glLoadIdentity(); gluPerspective(40.0, (GLfloat) h / (GLfloat) w , 0.1, 60.0); glMatrixMode(GL_MODELVIEW); } int main(int argc, char **argv) { glutInit(&argc, argv); printf("KEY COMMANDS\n"); printf("------------------------------------\n"); printf("Zoom in : Z\n"); printf("Zoom Out : z\n"); printf("Rotation about X-axis : X or x\n"); printf("Animation : A or a\n"); printf("Animation faster : F or f\n"); printf("Animation slower: S or s\n"); printf("Pause animation : T or t\n"); printf("Continue Animation : C or c\n"); printf("Flat shaded polygonization : p\n"); printf("Smooth shaded polygonization : P\n"); printf("------------------------------------\n"); glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB | GLUT_DEPTH ); glutInitWindowPosition(0, 0); glutInitWindowSize(800, 800); glutCreateWindow("Random Display"); glutReshapeFunc(myReshape); glutDisplayFunc(display); glutKeyboardFunc(keyboard); glutIdleFunc(display); myinit(); glutMainLoop(); return 0; }
C
#include<stdio.h> int main() { int l; int b; int m; float f; int a; printf("enter the numeber of length \n"); scanf("%d\n",&l); f=l*b; printf("the value of leangth in meeter is %d \n",m); printf("enter the numeber of breath\n"); scanf("%d\n",&b); m=0.305*f; printf("the vale of b in mis %d\n",m); }
C
void ft_putchar(char c); int g_countW; int g_countL; char g_text; char g_space; char g_dash; char g_space1; char g_vertical; void ft_length(int x) { while (g_countL < x) { if (g_countL % x == 0) { ft_putchar(g_text); g_countL++; if (g_countL == x) { ft_putchar(g_space); } } else if (g_countL % x == x -1) { ft_putchar(g_text); ft_putchar(g_space); g_countL++; } else { ft_putchar(g_dash); g_countL++; } } } void ft_length_mid(int x) { while (g_countL < x) { if (g_countL % x == 0) { ft_putchar(g_vertical); g_countL++; if (g_countL == x) { ft_putchar(g_space); } } else if (g_countL % x == x -1) { ft_putchar(g_vertical); ft_putchar(g_space); g_countL++; } else { ft_putchar(g_space1); g_countL++; } } } void ft_width(int x, int y) { while(g_countW < y) { if (g_countW % y == 0) { g_countL = 0; ft_length(x); g_countW++; } else if (g_countW % y == y - 1) { g_countL = 0; ft_length(x); g_countW++; } else { g_countL = 0; ft_length_mid(x); g_countW++; } } } void ft_rush(int x, int y) { g_text = 'o'; g_space = '\n'; g_dash = '-'; g_countL = 0; g_countW = 0; g_space1 = ' '; g_vertical = '|'; ft_width(x, y); }
C
/** @file AzElPa.h * @brief Function prototypes for the calculation of * azimuth, elevation and partials from local tangent coordinates. * * This header file contains the prototypes for the calculation of * azimuth, elevation and partials from local tangent coordinates. * * @author Miguel Alonso Angulo. * @bug No known bugs. */ #ifndef _AZELPA_ #define _AZELPA_ /** @brief Calculation of azimuth, elevation and partials from local * tangent coordinates. * * @param [in] s Topocentric local tangent coordinates (East-North-Zenith frame). * @param [out] A Azimuth [rad]. * @param [out] E Elevation [rad]. * @param [out] dAds Partials of azimuth w.r.t. s. * @param [out] dEds Partials of elevation w.r.t. s. */ void AzElPa(double *s, double *Az, double *El, double **dAds, double **dEds); #endif
C
#include <stdio.h> #include <ctype.h> #include "graph.h" #include "judge.h" #include "minePopulation.h" #include <stdbool.h> #include <math.h> /* int hash (char query[],int width,int height){ char queryLow[100]; char row[100]; int length=0; int coloumn; for (int i = 0; query[i]; i++) { queryLow[i] = tolower(query[i]); length++; } if (queryLow[0]>= 'a' && queryLow[0]<='z'){ for(int i=0;query[i]>= 'a' && query[i]<='z';i++){ row[i]=query[i]; } for(int i=length-1;query[i]>= '1' && query[i]<='9';i++){ coloumn } } } */ bool validateCol(int col, int width) { return col >= 0 && col <= width; } bool validateRow(int row, int height) { return row >= 0 && row <= height; } int hash(char query[], int width, int height) { /*Getting the vertex number from the input*/ char queryLow[100]; int rows = 0; int coloumns = 0; int length = 0; int vertex = 0; /*Lowering all the characters*/ for (int i = 0; query[i]; i++) { queryLow[i] = tolower(query[i]); length++; //calculating The query length if (queryLow[i] >= 'a' && queryLow[i] <= 'z') { rows++; } } //printf("length is %d\n",length); if (queryLow[0] >= 'a' && queryLow[0] <= 'z') { for (int i = 0; queryLow[i] >= 'a' && queryLow[i] <= 'z'; i++) { //calculating the vertex number of the first cell in the row of the query cell vertex = vertex + ceil((queryLow[i] - 'a') * width * (pow(26, rows - 1 - i))); } for (int i = rows; i < length; i++) { //adding the number of coloumns coloumns += ceil(pow(10, length - i - 1)*(queryLow[i] - '0')); } coloumns--; if (validateCol(coloumns, width) == false) { //validate the columns to be in the range [0,width] printf("This cell doesn't exist\n"); scanCell(width, height); } vertex += coloumns;//adding the columns to the vertex return vertex; } } char scanQuery(void) { /*scanning a query from the user*/ char query = "\n"; printf("Enter Your query:\n[open,flag,question,unmark,save game,load game]\n[o,f,q,,u,s,l]\n"); while (getchar() != '\n'); fflush(stdin); scanf("%c", &query); char queryLow = tolower(query); resetAlarm(); while (query == "\n" || query == " " || query == '\0') { scanf("%c", &query); queryLow = tolower(query); resetAlarm(); } //printf("the query scanned %c\n", query); char queries[] = {'o', 'f', 'q', 'u', 's', 'l'}; int queriesNumber = 5; for (int i = 0; i < queriesNumber; i++) { if (queryLow == queries[i]) { return queryLow; } } if (query != '\n') { printf("This query doesn't exist\n"); } return scanQuery(); } bool validateCell(int n, int v) { if (v >= n && v >= 0) { return false; } return true; } int scanCell(int width, int height) { /*Scan the cell from the user and return the value of the vertex from hash*/ char cell[10]; printf("print the cell:\n"); while (getchar() != '\n'); scanf("%s", &cell); resetAlarm(); printf("%c is incluseive %d\n ", cell[1], !(cell[1] >= 'a' && cell[1] <= 'Z')); while (cell[1] == '\0' || cell[2] == '\0' || !(cell[0] >= 'a' && cell[0] <= 'Z') || !(cell[1] >= 'a' && cell[1] <= 'Z')) { //checking the cell on the format [a-Z][a-Z][0-9]* printf("Enter an appropriate cell as the instructions dictates\n"); scanf("%s", &cell); resetAlarm(); } return hash(cell, width, height); } void takeInput(judge_t *judge) { char query; char cell[10]; query = scanQuery(); // scan action if (query == 's' || query == 'l') { goto action; } printf("print the cell:\n"); while (getchar() != '\n'); scanf("%s", &cell);// scan the cell resetAlarm(); while (cell[1] == '\0' || cell[2] == '\0' || !(cell[0] >= 'A' && cell[0] <= 'z') || !(cell[1] >= 'A' && cell[1] <= 'z')) { //validating the proper format of the cell printf("Enter an appropriate cell as the instructions dictates\n"); fflush(stdin); scanf("%s", &cell); resetAlarm(); } graph_p grid = getGraph(judge); int height = grid->height; int width = grid->width; int v = hash(cell, width, height) ;// get the vertex number while (!validateCell(judge->grid->num_vertices, v)) { printf("This cell doesn't exist. More focus would help. The clock is ticking.\nprint the cell:\n"); while (getchar() != '\n'); scanf("%s", &cell); resetAlarm(); v = hash(cell, width, height); } if (getGraph(judge)->startingNode == -1) { //First cell to open getGraph(judge)->startingNode = v; getMinePosition(getGraph(judge), getGraph(judge)->startingNode); } judge->moves++; action: switch (query) { /*Taking an appropriate action */ case 'o': openCell(judge, grid, v); checkWin(judge); break; case 'f': flagCell(grid, v); checkWin(judge); break; case 'q': questionCell(grid, v); break; case 'u': unmark(grid, v); break; case 's': if (judge->grid->startingNode==-1){ printf("The game has not started yet!\n You can Not Save!"); takeInput(judge); break; } saveFile(judge); break; case 'l': openFile(judge); break; } return; }
C
int main() { int i = 0; int j = 123; double a = 1.5; float b = 2.2; double c = a + b; // 3.7 double d = b - a; // 0.7 double e = b / a; // 1.4666666666666666666666666666667 double f = a * b; // 3.3 double g = j + a; // 124.5 double h = j + b; // 125.2 //printf("c: %e d: %e e: %e f: %e g: %e h: %e\r\n", c, d, e, f, g, h); if ((3.7 - c) > 0.1) { goto Error; } else { i = 1; } // With doubles, 0.0 works, with floats not if ((0.7 - d) > 0.0) { goto Error; } else { i = 2; } if ((1.47 - e) > 0.1) { goto Error; } else { i = 3; } if ((3.3 - f) > 0.0) { goto Error; } else { i = 4; } if ((123.5 - g) > 0.0) { goto Error; } else { i = 5; } double x = 125.2 - h; if (x > 0.0) { goto Error; } else { i = 6; } //printf("%s", "Alles passte!\r\n"); return 0; Error: //printf("ERROR %i", i); return -1; }
C
#include "sort.h" /** * insertion_sort_list - Function that ordered doubly linked list, * that oredered acsending * @list: Paremeter doubly linked lict * Return - None */ void insertion_sort_list(listint_t **list) { listint_t *forward = NULL, *backward = NULL, *a = NULL, *b = NULL, *c = NULL, *d = NULL; if (list == NULL || (*list) == NULL || (*list)->next == NULL) return; forward = *list; while (forward != NULL) { backward = forward; while (backward != NULL && backward->prev != NULL && backward->prev->n > backward->n) { a = backward->prev->prev; b = backward->prev; c = backward; d = backward->next; if (a) a->next = c; c->next = b; b->next = d; if (d) d->prev = b; b->prev = c; c->prev = a; if (*list == b) *list = c; print_list(*list); } forward = forward->next; } }
C
#include "List.h" #include <stdlib.h> #include <stdbool.h> #include <stdio.h> typedef struct ListElement { int value; int frequency; struct ListElement* next; } ListElement; typedef struct List { ListElement* head; } List; bool isEmpty(List* list) { return (list == NULL || list->head == NULL); } int getTheValue(List *list) { if (isEmpty(list)) { return -INT_MAX; } return list->head->value; } int getFrequency(List* list) { if (isEmpty(list)) { return -INT_MAX; } return list->head->frequency; } void nextItem(List* list) { if (!isEmpty(list)) { list->head = list->head->next; } } List* makeList(void) { return calloc(1, sizeof(List)); } void addItem(List* list, const int value) { if (list == NULL) { list = makeList(); } ListElement* newElement = malloc(sizeof(ListElement)); if (newElement == NULL) { return; } if (list->head == NULL) { newElement->value = value; newElement->frequency = 1; newElement->next = NULL; list->head = newElement; return; } ListElement* pointer = list->head; while (pointer->next != NULL && pointer->next->value <= value) { pointer = pointer->next; } if (pointer->value == value) { pointer->frequency++; free(newElement); return; } newElement->value = value; newElement->frequency = 1; if (pointer == list->head && pointer->value > value) { newElement->next = list->head; list->head = newElement; return; } newElement->next = pointer->next; pointer->next = newElement; } bool removeValue(List* list, const int value) { if (isEmpty(list)) { return true; } ListElement* pointer = list->head; if (pointer->value == value) { list->head = list->head->next; free(pointer); return false; } while (pointer->next != NULL && pointer->next->value != value) { pointer = pointer->next; } if (pointer->next == NULL && pointer->value != value) { return true; } if (pointer->next != NULL) { ListElement* oldElement = pointer->next; pointer->next = pointer->next->next; free(oldElement); } else { pointer = NULL; } return false; } void freeList(List** list) { while (!isEmpty(*list)) { removeValue(*list, (*list)->head->value); } free(*list); *list = NULL; } void printList(List *list) { if (isEmpty(list)) { printf("List is empty\n"); return; } printf("Number - frequency\n"); ListElement* pointer = list->head; while (pointer != NULL) { printf("%i - %i\n", pointer->value, pointer->frequency); pointer = pointer->next; } }
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* deal_with_map_directory.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: dacuvill <marvin@42.fr> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2020/02/25 22:47:02 by dacuvill #+# #+# */ /* Updated: 2020/04/18 21:45:05 by damien ### ########.fr */ /* */ /* ************************************************************************** */ #include <sys/types.h> #include <dirent.h> #include <fcntl.h> #include <unistd.h> #include "libft.h" char *get_map_name(int map_to_show, char *dir_path) { DIR *directory; struct dirent *maps; directory = NULL; maps = NULL; if (!(directory = opendir(dir_path))) return (NULL); while ((maps = readdir(directory))) { if (map_to_show == 0 && maps->d_name[0] != '.') { closedir(directory); return (maps->d_name); } if (maps->d_name[0] != '.') --map_to_show; } closedir(directory); return (NULL); } int count_maps(int *first, char *dir_path) { int nbmaps; DIR *directory; struct dirent *maps; directory = NULL; maps = NULL; nbmaps = 0; if (!(directory = opendir(dir_path))) return (-1); while ((maps = readdir(directory))) if (maps->d_name[0] != '.') ++nbmaps; (*first)++; closedir(directory); return (nbmaps); }
C
#ifndef TURBOISO_H #define TURBOISO_H struct MatchingOrderPair { vector<NECNode*>* q; ULONG score; }; struct RankingPair { QueryNode* v; double score; }; /* * Sorts for min-pq. TODO : verify min pq not max pq */ struct CompareRankingPair { bool operator()(const RankingPair* p1, const RankingPair* p2) { return p1->score > p2->score; } }; /* * Min PQ for matching order. * */ struct CompareMatchingOrder { bool operator()(const MatchingOrderPair* m1, const MatchingOrderPair* m2) { return m1->score > m2->score; } }; /* * Sorting for NEC eval order */ struct CompareNEC { bool operator()(const pair<NECNode*, UINT>* p1, pair<NECNode*, UINT>* p2) { return p1->second < p2->second; } }; /* * Used when BFS-ing through query graph. * A node's parent might not be reachable from BFS on the node's chidren alone. * When children BFS queue runs out, BFS through parent's BFS queue. */ struct AncestorEquivalentClass { QueryNode* v; QueryNode* child; }; struct CRNode { // Encapsulates the 'v' prior node vector<VERTEX> candidate_data_nodes; // Ptrs to CRNode of adjacent NEC vertex, with current CRNode assignment as // a prior (2nd level map has domain = current CR's data vertexx) unordered_map<NECNode*, unordered_map<VERTEX, CRNode*> > children; unordered_map<NECNode*, unordered_map<VERTEX, CRNode*> > parents; }; struct CRTree { CRNode* root; unordered_map<NECNode*, unordered_set<CRNode*> > candidate_regions; }; typedef priority_queue<MatchingOrderPair*, vector<MatchingOrderPair*>, CompareMatchingOrder> MatchingOrderPq; #endif
C
/* /osxptb/trunk/PsychSourceGL/Source/OSX/Eyelink/EyelinkMessage.c PROJECTS: Eyelink AUTHORS: f.w.cornelissen@rug.nl fwc E.Peters@ai.rug.nl emp PLATFORMS: All. HISTORY: 15/06/06 fwc Adapted from early alpha version by emp. 19-06-11 mk Refactored to share parser with other functions. TARGET LOCATION: Eyelink.mexmac resides in: EyelinkToolbox */ #include "PsychEyelink.h" static char useString[] = "[status =] Eyelink('Message', 'formatstring', [...])"; static char synopsisString[] = "link message formatting use just like printf()\n" " Only chars and ints allowed in arguments!\n" "returns any send error"; static char seeAlsoString[] = ""; /* ROUTINE: EYELINKmessage PURPOSE: uses int eyemsg_printf(char *fmt, ...) This sends a text message to the Eyelink tracker, which timestamps it and writes it to the EDF data file. Messages are useful for recording trail conditions, subject responses. or the time of important events. This function is used with the same formatting methods as printf(), allowing numbers to be included. Avoid"\n" at end of messages. RETURNS: 0 if OK, else errorcode. */ PsychError EyelinkMessage(void) { int status = -1; // All sub functions should have these two lines PsychPushHelp(useString, synopsisString, seeAlsoString); if(PsychIsGiveHelp()){PsychGiveHelp();return(PsychError_none);}; // Check to see if the user supplied superfluous arguments PsychErrorExit(PsychRequireNumInputArgs(1)); PsychErrorExit(PsychCapNumOutputArgs(1)); // Verify eyelink is up and running EyelinkSystemIsConnected(); EyelinkSystemIsInitialized(); status = eyemsg_printf(PsychEyelinkParseToString(1)); /* if there is an output variable available, assign eyecmd_printf status to it. */ PsychCopyOutDoubleArg(1, FALSE, status); return(PsychError_none); }
C
//http://code.kx.com/wiki/Cookbook/ExtendingWithC#High_Precision_wall_time_on_Linux #include"k.h" #include<time.h> //this is the version from the kx wiki //K x param is not used as this is going to be nilladic function K getTime(K x){ struct timespec ts; clock_gettime(CLOCK_REALTIME,&ts); R ktj(-KP,(ts.tv_sec-10957*86400)*1000000000LL+ts.tv_nsec);} //other experiments with different clock K getTimeMonotic(K x){ struct timespec ts; clock_gettime(CLOCK_MONOTONIC,&ts); R ktj(-KP,(ts.tv_sec-10957*86400)*1000000000LL+ts.tv_nsec); } K getTimeTweaked(K x){ struct timespec ts; clock_gettime(CLOCK_REALTIME,&ts); R ktj(-KP,(ts.tv_sec-946684800)*1000000000LL+ts.tv_nsec); } K getTimeMonTweaked(K x){ struct timespec ts; clock_gettime(CLOCK_MONOTONIC,&ts); R ktj(-KP,(ts.tv_sec-946684800)*1000000000LL+ts.tv_nsec); } K getTOD(K x){ struct timespec ts; gettimeofday(&ts, NULL); R ktj(-KP,(ts.tv_sec-10957*86400)*1000000000LL+ts.tv_nsec); }