language
large_stringclasses
1 value
text
stringlengths
9
2.95M
C
/* lists.h -*- mode:c; coding:utf-8; -*- * * Copyright (c) 2010-2021 Takashi Kato <ktakashi@ymail.com> * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED * TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef SAGITTARIUS_LISTS_H_ #define SAGITTARIUS_LISTS_H_ #include "sagittarius/platform.h" SG_CDECL_BEGIN /** Construct a pair. @param car the first part @param cdr the second part @return a pair object */ SG_EXTERN SgObject Sg_Cons(SgObject car, SgObject cdr); /** Check if given object is a pair. @param obj an object @return 1 obj is a pair, 0 obj is not a pair */ SG_EXTERN int Sg_IsPair(SgObject obj); /** Get the first part of the given pair. @param obj a pair object @return the first part of the pair */ SG_EXTERN SgObject Sg_Car(SgObject obj); /** Get the second part of the given pair. @param obj a pair object @return the second part of the pair */ SG_EXTERN SgObject Sg_Cdr(SgObject obj); /** Get the length of the given list. If the return value is negative, then the given obj is not a list. @param obj @return 0>= length of the pair -1 dotted list -2 circular list */ SG_EXTERN long Sg_Length(SgObject obj); /** Converts given object array to a list. @param array an array of objects @param nelts number of array elements @return a list */ SG_EXTERN SgObject Sg_ArrayToList(SgObject *array, int nelts); /** Concatenates the given list of list into one list. This is the same as (apply append '((...) (...) ...)). @param args a list of list. @return a list */ SG_EXTERN SgObject Sg_Append(SgObject args); /** Returns a reversed list. @param list a list @return a newly create list with reversed elements. */ SG_EXTERN SgObject Sg_Reverse(SgObject list); SG_CDECL_END #endif /* SAGITTARIUS_LISTS_H_ */
C
#pragma once #include "LinearAlgebra.h" // 󸡵ƽ inline double square(double x) { return x * x; } // ʾĽṹ struct ClosedInterval { ClosedInterval(double x) : left(x), right(x) {} ClosedInterval(double left, double right) : left(left), right(right) { #ifdef _DEBUG if (left > right) throw "߲ܱұߴ"; #endif } ClosedInterval &operator+=(const ClosedInterval &other) { this->left += other.left; this->right += other.right; } ClosedInterval &operator-=(const ClosedInterval &other) { this->left -= other.right; this->right -= other.left; } bool contain(const ClosedInterval &other) const { return this->left <= other.left && this->right >= other.right; } bool contain(double x) const { return this->left <= x && this->right >= x; } double mid() const { return (left + right) / 2; } double length() const { return right - left; } double left, right; }; inline ClosedInterval operator+(const ClosedInterval &a, const ClosedInterval &b) { return ClosedInterval(a.left + b.left, a.right + b.right); } inline ClosedInterval operator-(const ClosedInterval &a, const ClosedInterval &b) { return ClosedInterval(a.left - b.right, a.right - b.left); } inline ClosedInterval operator-(const ClosedInterval &a) { return ClosedInterval(-a.right, -a.left); } inline bool operator==(const ClosedInterval &a, const ClosedInterval &b) { return a.left == b.left && a.right == b.right; } inline bool operator!=(const ClosedInterval &a, const ClosedInterval &b) { return a.left != b.left || a.right != b.right; } inline bool intersect(const ClosedInterval &a, const ClosedInterval &b) { return a.left <= b.right && a.right >= b.left; } // ʾάĽṹ struct ClosedRegion2D { ClosedRegion2D(const MapVector &v) : x(v.x, v.x), y(v.y, v.y) {} ClosedRegion2D(const MapPoint &p) : x(p.x, p.x), y(p.y, p.y) {} ClosedRegion2D(const ClosedInterval &x, const ClosedInterval &y) : x(x), y(y) {} ClosedRegion2D(double x, double y) : x(x, x), y(y, y) {} ClosedRegion2D(const MapVector &v_left, const MapVector &v_right) : x(v_left.x, v_right.x), y(v_left.y, v_right.y) {} ClosedRegion2D(const MapPoint &p_left, const MapPoint &p_right) : x(p_left.x, p_right.x), y(p_left.y, p_right.y) {} ClosedRegion2D(double x_left, double x_right, double y_left, double y_right) : x(x_left, x_right), y(y_left, y_right) {} bool contain(const ClosedRegion2D &other) const { return x.contain(other.x) && y.contain(other.y); } bool contain(const MapVector &v) const { return x.contain(v.x) && y.contain(v.y); } bool contain(const MapPoint &p) const { return x.contain(p.x) && y.contain(p.y); } double area() const { return x.length() * y.length(); } ClosedInterval x, y; }; inline ClosedRegion2D operator-(const ClosedRegion2D &a) { return ClosedRegion2D(-a.x, -a.y); } inline bool operator==(const ClosedRegion2D &a, const ClosedRegion2D &b) { return a.x == b.x && a.y == b.y; } inline bool operator!=(const ClosedRegion2D &a, const ClosedRegion2D &b) { return a.x != b.x || a.y != b.y; } inline bool intersect(const ClosedRegion2D &a, const ClosedRegion2D &b) { return intersect(a.x, b.x) && intersect(a.y, b.y); }
C
#include <stdio.h> int main () { printf("Detta program räknar ut vilka tal som är burrtal, dvs. tal som innehåller en viss siffra eller är jämt delbar med den. Ange önskad burrsiffra:\n"); int burrsiffra; scanf("%d", &burrsiffra); int j; for (j = 1; j < 100; j++){ if (j % burrsiffra == 0){ printf("burr ");} else if(j - 10 * (j / 10) == burrsiffra){ printf("burr ");} else { printf("%d ", j);} } return 0; }
C
#include<stdio.h> int main(void) { int a , b , soma , parcial , resultado; a = 0; b = 1; soma = 0; resultado = 0; while(soma <= 4000000){ a = b; b = soma; parcial = soma; if(soma % 2 ==0) resultado += parcial; soma = a + b; } printf("A soma de todos os elementos da serie de fibonnaci menor que 4 milhoes e %d\n",resultado); return 0; }
C
#include<stdio.h> //将数字转化为二进制方法 int main() { int a,j,i,m,n; int s[6]; a=0; for(;a<64;a++) { i=a%2,j=a/2; for(m=0;m<6;m++) { s[m]=i; i=j%2,j=j/2; } for(n=5;n>=0;n--) { printf("%d",s[n]); } printf("\n"); } return 0; }
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* buffer.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: jsandsla <jsandsla@student.21-school.ru> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2021/01/06 12:46:01 by jsandsla #+# #+# */ /* Updated: 2021/01/07 17:22:07 by jsandsla ### ########.fr */ /* */ /* ************************************************************************** */ #include "private.h" #include <unistd.h> #include <stdlib.h> int tkz_buffer_expand(t_tkz_buf *buf, int at_least) { int new_cap; void *new_mem; new_cap = buf->cap * 2; if (new_cap < at_least) new_cap = at_least; if (new_cap <= 0) new_cap = 16; new_mem = malloc(new_cap); if (new_mem) { if (buf->mem) { tkz_memcpy(new_mem, buf->mem + buf->start, buf->len); free(buf->mem); } buf->mem = new_mem; buf->cap = new_cap; buf->start = 0; } return (!!new_mem ? TKZ_SUCCESS : TKZ_ERROR_MALLOC_NULL_RETURN); } int tkz_write_buffer_str(t_tkz_buf *buf, const char *str, int len) { int error; error = TKZ_SUCCESS; if (buf->start + buf->len + len > buf->cap) error = tkz_buffer_expand(buf, buf->len + len); if (!tkz_is_error(error)) { tkz_memcpy(buf->mem + buf->start + buf->len, (void *)str, len); buf->len += len; } return (error); } int tkz_buffer_read_command(t_tkz *tkz, t_tkz_buf *buf) { int error; error = TKZ_SUCCESS; while (!tkz_is_error(error) && !tkz_is_buffer_closed(buf)) { error = tkz_read_buffer(buf); if (error == TKZ_ERROR_UNISTD_READ_EOF && buf->len > 0) { tkz->flags |= TKZ_FLAG_UNEXPECTED_EOF; error = TKZ_SUCCESS; break ; } if (buf->len > 0 && tkz_is_wp(tkz_buffer_view_char(buf, 0))) tkz->flags |= TKZ_FLAG_WS_AT_START; } if (!tkz_is_error(error)) tkz_buffer_skip_whitespaces(buf); return (error); } int tkz_read_buffer(t_tkz_buf *buf) { int ret; int error; char bufmem[64]; if (buf->len > 0 && buf->start > 0) tkz_memcpy(buf->mem, buf->mem + buf->start, buf->len); buf->start = 0; error = TKZ_SUCCESS; if (buf->fd >= 0) { while (!tkz_is_error(error) && !tkz_is_buffer_closed(buf)) { ret = read(buf->fd, bufmem, sizeof(bufmem)); if (ret < 0) return (TKZ_ERROR_UNISTD_READ_NEGATIVE_RETURN); if (ret == 0) return (TKZ_ERROR_UNISTD_READ_EOF); error = tkz_write_buffer_str(buf, bufmem, ret); } } return (buf->fd >= 0 ? error : TKZ_ERROR_INVALID_FD); }
C
/* ** my_atoi.c for raytracer1 in /home/Cyriack/Projects/MUL_2016/lol/raytracer1/raytracer1/raytracer1 ** ** Made by Lucas Le Ray ** Login <Cyriack@epitech.net> ** ** Started on Sun Mar 19 21:16:48 2017 Lucas Le Ray ** Last update Sun May 28 22:01:42 2017 Thery Fouchter */ #include "raytracer.h" float my_atof(char *s) { float value; int i; int dec; int neg; i = -1; value = 0.0; dec = 0; neg = 0; if (s[0] == '-' && i++) neg = 1; while (s[++i] && s[i] <= '9' && s[i] >= '0') value = value * 10.0 + (s[i] - 48); if (s[i] == '.') while (s[++i] && s[i] <= '9' && s[i] >= '0') { value = value * 10.0 + (s[i] - 48); dec++; } while (dec-- > 0) value *= 0.1; neg == 1 ? (value *= -1) : (value = value); return (value); } int my_atoi(char *s) { int mul; int sign; int i; mul = 0; sign = 1; i = 0; if (s == NULL) return (0); if (s[0] == '-') { sign *= -1; i++; } while (s[i] && (s[i] >= '0' && s[i] <= '9')) { mul = (mul * 10) + (s[i] - 48); i++; } mul *= sign; return (mul); }
C
#include <stdio.h> #include <stdlib.h> int main (int argc, char** argv) { char character; printf("Entrez un caractere svp "); scanf("%c", &character); printf("%d", character); return 0; }
C
#include "lexer.h" char *stringLiterals[stringLiteralsSize] = {NULL}; int nowStringLiteralsNum = 0; char checkSingleletterReserved(char p) { // Punctutor. static char spuncts[] = {'+', '-', '*', '/', '>', '<', ';', '=', '(', ')', '[', ']', '{', '}', ',', '&', '"'}; for(int i = 0; i < sizeof(spuncts) / sizeof(char); i++) { if(p == spuncts[i]) return spuncts[i]; } return 0; } char *checkMultiletterReserved(char *p) { // Keyword. static char *mkeywords[] = {"return", "if", "else", "while", "int", "char", "sizeof"}; for(int i = 0; i < sizeof(mkeywords) / sizeof(*mkeywords); i++) { if(!strncmp(p, mkeywords[i], strlen(mkeywords[i])) && !isalnum(p[strlen(mkeywords[i])]) && p[strlen(mkeywords[i])] != '_') return mkeywords[i]; } // Punctutor. static char *mpuncts[] = {"==", "<=", ">="}; for(int i = 0; i < sizeof(mpuncts) / sizeof(*mpuncts); i++) { if(!strncmp(p, mpuncts[i], strlen(mpuncts[i]))) return mpuncts[i]; } return NULL; } // If next token is expected reserved word, read token and return true. Otherwise return false. bool consume(char *op) { if(nowToken->kind != TK_RESERVED || strlen(op) != nowToken->len || strncmp(nowToken->str, op, nowToken->len)) return false; nowToken = nowToken->next; return true; } // If next token's kind is expected kind. Otherwise return false. Token *consumeKind(TokenKind kind) { if(nowToken->kind != kind) return NULL; Token *oldToken = nowToken; nowToken = nowToken->next; return oldToken; } // If next token is expected reserved word, read token. Otherwise output error. void expect(char *op) { if(nowToken->kind != TK_RESERVED || strlen(op) != nowToken->len || strncmp(nowToken->str, op, nowToken->len)) { if(nowToken->kind == TK_NUM) printf("%d\n", nowToken->val); else printf("%.*s\n", nowToken->len, nowToken->str); error(nowToken->str, "'%s'ではありません。", op); } nowToken = nowToken->next; } // If next token is number token, read token and return the value. Otherwise output error. int expectNumber() { if(nowToken->kind != TK_NUM) error(nowToken->str, "数ではありません。"); int val = nowToken->val; nowToken = nowToken->next; return val; } // If next token is identifier token, read token and return the token pointer. Otherwise return NULL. Token *consumeIdentifier() { if(nowToken->kind != TK_IDENT) return NULL; Token *oldToken = nowToken; nowToken = nowToken->next; return oldToken; } // If next token is identifier token ,read token and return the token pointer. Otherwise output error. Token *expectIdentifier() { if(nowToken->kind != TK_IDENT) error(nowToken->str, "識別子ではありません。"); Token *oldToken = nowToken; nowToken = nowToken->next; return oldToken; } // Check EOF. bool isEOF() { return nowToken->kind == TK_EOF; } // Make new token and connect the token to current. Token *newToken(TokenKind kind, Token *current, char *str, int len) { Token *token = calloc(1, sizeof(Token)); token->kind = kind; token->str = str; token->len = len; current->next = token; return token; } // Make new string token and connect the token to current. // Arg "str" has to null end. Token *newStringToken(Token *current, char *str) { Token *token = calloc(1, sizeof(Token)); token->kind = TK_STR; token->str = str; token->len = strlen(str); current->next = token; token->val = nowStringLiteralsNum; return token; } // Show token lists. void printTokens() { Token *token = nowToken; printf("----------- Tokens ---------------\n"); while(token) { if(token->kind == TK_NUM) printf("%d\n", token->val); else if(token->kind == TK_EOF) printf("EOF\n"); else printf("%.*s\n", token->len, token->str); token = token->next; } printf("----------------------------------\n"); } // Show string literals. void printStringLiterals() { printf("----------- String ---------------\n"); for(int i = 0; i < nowStringLiteralsNum; i++) printf("%s len: %ld\n", stringLiterals[i], strlen(stringLiterals[i])); printf("----------------------------------\n"); } // Lexer. Token *lexer(char *p) { Token head; head.next = NULL; Token *current = &head; while(*p) { // Skip space. if(isspace(*p)) { p++; continue; } // Skip line comment. if(!strncmp(p, "//", 2)) { p += 2; while(*p != '\n') p++; continue; } // Skipt block comment. if(!strncmp(p, "/*", 2)) { char *q = strstr(p + 2, "*/"); if(!q) error(p, "コメントが閉じられていません。"); p = q + 2; continue; } // Multi letter reserved. ex) "<=", ">=" char *ch = checkMultiletterReserved(p); if(ch) { int len = strlen(ch); if(!strncmp(ch, "return", 6)) { current = newToken(TK_RETURN, current, p, len); } else if(!strncmp(ch, "if", 2)) { current = newToken(TK_IF, current, p, len); } else if(!strncmp(ch, "else", 4)) { current = newToken(TK_ELSE, current, p, len); } else if(!strncmp(ch, "while", 5)) { current = newToken(TK_WHILE, current, p, len); } else if(!strncmp(ch, "sizeof", 6)) { current = newToken(TK_SIZEOF, current, p, len); } else { current = newToken(TK_RESERVED, current, p, len); } p += len; continue; } char c = checkSingleletterReserved(*p); // string literal if(c == '"') { p++; char *s = p; do { c = *p++; } while(c != '"'); int len = p - s - 1; stringLiterals[nowStringLiteralsNum] = (char *)malloc(sizeof(char) * len + 1); memcpy(stringLiterals[nowStringLiteralsNum], s, len); current = newStringToken(current, stringLiterals[nowStringLiteralsNum]); nowStringLiteralsNum++; continue; } if(c != 0) { current = newToken(TK_RESERVED, current, p++, 1); continue; } if(isalpha(*p) || *p == '_') { char *q = p++; while(isalnum(*p) || *p == '_') p++; current = newToken(TK_IDENT, current, q, p - q); continue; } if(isdigit(*p)) { current = newToken(TK_NUM, current, p, 0); current->val = strtol(p, &p, 10); continue; } error(p, "'%c': 不明な入力です。", *p); } newToken(TK_EOF, current, p, 1); return head.next; }
C
#include <stdio.h> int main() { printf("abcdefg" "1234567\n"); /* 1. output: abcdefg1234567 2. notes: 若 printf 中的两个字符串如上相连(不加逗号),输出时会连起来 */ printf("abcdefg\ 1234567\n"); /* 1. output: abcdefg 1234567 2. notes: 若 printf 中一对双引号内的字符串要换行,可加上反斜杠 \ 这样会代入第二行的空格,若想不带空格,第二行可以顶格写 */ return 0; }
C
#include <windows.h> #include <winioctl.h> #include <stdio.h> #include <ftapi.h> void __cdecl main( int argc, char** argv ) { TCHAR dosDriveName[10]; HANDLE h; BOOL b; PARTITION_INFORMATION partInfo; DWORD bytes; DISK_GEOMETRY geometry; LONGLONG newSectors; if (argc != 2) { printf("usage: %s drive:\n", argv[0]); return; } if (argv[1][1] != ':' || argv[1][2] != 0) { printf("usage: %s drive:\n", argv[0]); return; } wsprintf(dosDriveName, TEXT("\\\\.\\%c:"), argv[1][0]); h = CreateFile(dosDriveName, GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, INVALID_HANDLE_VALUE); if (h == INVALID_HANDLE_VALUE) { printf("Can't open, failed with %d\n", GetLastError()); return; } b = DeviceIoControl(h, IOCTL_DISK_GET_PARTITION_INFO, NULL, 0, &partInfo, sizeof(partInfo), &bytes, NULL); if (!b) { printf("Can't read partition info, failed with %d\n", GetLastError()); return; } b = DeviceIoControl(h, IOCTL_DISK_GET_DRIVE_GEOMETRY, NULL, 0, &geometry, sizeof(geometry), &bytes, NULL); if (!b) { printf("Can't read geometry info, failed with %d\n", GetLastError()); return; } newSectors = partInfo.PartitionLength.QuadPart/geometry.BytesPerSector; b = DeviceIoControl(h, FSCTL_EXTEND_VOLUME, &newSectors, sizeof(newSectors), NULL, 0, &bytes, NULL); if (b) { printf("File system extended successfully.\n"); } else { printf("File system extension failed.\n"); } }
C
#include <fcntl.h> #include <stdio.h> #include <sys/stat.h> #include <sys/mman.h> #include <stdlib.h> #include <assert.h> #include <string.h> #include <zconf.h> // // Created by Pavel on 31/10/2018. // int main(){ char* new_string = "This is a nice day"; int fd = open("/Users/Pavel/programs/OSs/git/week11/ex1.txt", O_RDWR); size_t size = strlen(new_string); lseek(fd, size-1, SEEK_SET); write(fd, "r", 1); char *string = mmap(NULL, size+1, PROT_READ|PROT_WRITE, MAP_SHARED, fd, 0); memcpy(string, new_string, size); munmap(string, size+1); close(fd); return 0; }
C
/* Wil Deering, November 12 2018, CSCI 2132, A5 This program takes in a specified number of strings of digits, and checks to see if the string passes Luhn's checksum, printing whether it does or not */ #include <stdio.h> int luhn_checksum(int len, int a[]); int main(){ int trials,i; scanf("%d",&trials); getchar(); for(i=0; i < trials; i++){ char ch[51]; int n = 0, m; scanf("%50s",&ch); while(ch[n] != '\0'){ n+=1; } int a[n]; for(m = 0; m < n; m++) { a[m] = ch[m] - '0';} if(luhn_checksum(n, a)) printf("PASS\n"); else printf("FAIL\n"); } } int luhn_checksum(int len, int a[]){ int i, sum =0; for(i = 0; i < len; i++){ if((len+i)%2 == 0){ a[i] = 2*a[i]; int o = a[i]/10; a[i] = o + a[i]-(o*10); } sum += a[i]; } if(sum%10 == 0) return 1; else return 0; }
C
/* * PIC.c * * Created on: 14.07.2012 * Author: pascal */ #include "pic.h" #include "util.h" #include "display.h" //Master #define PIC_MASTER_COMMAND 0x20 #define PIC_MASTER_DATA 0x21 #define PIC_MASTER_IMR 0x21 //Slave #define PIC_SLAVE_COMMAND 0xA0 #define PIC_SLAVE_DATA 0xA1 #define PIC_SLAVE_IMR 0xA1 //EOI #define EOI 0x20 /* * Intitialisiert den PIC */ void pic_Init() { //IRQs fangen bei Interrupt 32 an pic_Remap(32); //Maskiere alle nicht gebrauchten IRQs (alle ausser PS/2 Port 1 und 2) pic_MaskIRQ(0b1110111111111000); SysLog("PIC", "Initialisierung abgeschlossen"); } /* * Initialisiert den PIC auf eine bestimmte Interruptnummer * Parameter: Interrupt = Nummer des Interrupts, an den der IRQ 0 sein soll (vielfaches von 8) */ void pic_Remap(uint8_t Interrupt) { //Master PIC outb(PIC_MASTER_COMMAND, 0x11); //0x11 bedeuted, dass wir Initialisieren wollen und es //zwei PICs gibt outb(PIC_MASTER_DATA, Interrupt); //Interruptnummer senden outb(PIC_MASTER_DATA, 0x04); //Interruptnummer des Slaves übergeben (Bit-Maske) outb(PIC_MASTER_DATA, 0x01); //Wir befinden uns im 8086-Mode //Slave PIC outb(PIC_SLAVE_COMMAND, 0x11); //0x11 bedeuted, dass wir Initialisieren wollen und es //zwei PICs gibt outb(PIC_SLAVE_DATA, Interrupt + 8);//Interruptnummer senden outb(PIC_SLAVE_DATA, 2); //Interruptnummer des Slaves übergeben outb(PIC_SLAVE_DATA, 0x01); //Wir befinden uns im 8086-Mode } /* * Maskiert einzelne IRQs (deaktiviert sie) * Parameter: Mask = Bitmaske (0 = entsprechender IRQ aktiviert) */ void pic_MaskIRQ(uint16_t Mask) { outb(PIC_MASTER_IMR, (uint8_t)Mask); outb(PIC_SLAVE_IMR, (uint8_t)Mask >> 8); } /* * Sendet den EOI (End of Interrupt) an den PIC * Parameter: irq = IRQ-Nummer */ void pic_SendEOI(uint8_t irq) { outb(PIC_MASTER_COMMAND, EOI); if(irq > 7) outb(PIC_SLAVE_COMMAND, EOI); }
C
#ifndef MERGE_H #define MERGE_H #include <fcntl.h> #include <math.h> #include <pthread.h> #include <stdio.h> #include <stdlib.h> #include <sys/stat.h> #include <sys/types.h> #include <sys/wait.h> #include <time.h> #include <unistd.h> #define THREAD_MAX 4 // maximum number of threads depending upon cores #define PROCESS_MAX 4 int *divideArray; // for mergeSort function int *mergeArray; // for merge function int mSizeArray[THREAD_MAX] = {-1}; // size of different partitions (i.e 4 different divisions) int increment[THREAD_MAX] = {0}; // arrays that will be used to increment merge array for merge function int divideThreadNumber = 0; // for getting appropiate partition int divideProcessNumber = 0; // for getting appropiate partition int fd[PROCESS_MAX][2]; // fileDiscripters that will be used for implementing pipes #include "data.h" void merge(int __original[], int __left[], int __right[], int __llength, int __rlength) { int i = 0, j = 0, k = 0; while (i < __llength && j < __rlength) { if (__left[i] <= __right[j]) { __original[k] = __left[i]; k++; i++; } else { __original[k] = __right[j]; k++; j++; } } while (i < __llength) { __original[k] = __left[i]; i++; k++; } while (j < __rlength) { __original[k] = __right[j]; j++; k++; } } void mergeSort(int __array[], int n) { if (n < 2) { return; } else { int mid = ceil((float)n / 2); int leftArr[mid]; int rightArr[n - mid]; for (int i = 0; i < mid; i++) { leftArr[i] = __array[i]; } for (int i = mid; i < n; i++) { rightArr[i - mid] = __array[i]; } mergeSort(leftArr, mid); mergeSort(rightArr, n - mid); merge(__array, leftArr, rightArr, mid, n - mid); } } void *msThread(void *__args) { int factor = divideThreadNumber++; mergeSort(divideArray, mSizeArray[factor]); divideArray += mSizeArray[factor]; } // function that performs merge-sort on 4 different partitions void *mergingThread(void *__args) { int first = divideThreadNumber++; int second = divideThreadNumber++; merge((int *)__args, mergeArray + (increment[first]), mergeArray + (increment[second]), mSizeArray[first], mSizeArray[second]); } // function that forms 2 arrays i.e. firstHalf and secondHalf void mergeSortThread() { printf("\n=====================\n"); printf("SORTING USING THREAD\n"); printf("=====================\n"); divideArray = mergeTDataArray; mergeArray = mergeTDataArray; pthread_t threads[THREAD_MAX]; clock_t start; start = clock(); int mid = ceil((float)numberOfElements / 2); int firstHalf[mid]; int secondHalf[numberOfElements - mid]; for (int i = 0; i < THREAD_MAX; i++) { pthread_create(&threads[i], NULL, msThread, (void *)NULL); } // 4 threads will run in parallel each working on a single different partition for (int i = 0; i < THREAD_MAX; i++) { pthread_join(threads[i], NULL); } // joining threads /* The four different parts will be combined into 2 (firstHalf and secondHalf) and then completely merged into a single array */ divideThreadNumber = 0; /* merging 4 partitions into 2 i.e. firstHalf and secondHalf via threads */ pthread_create(&threads[0], NULL, mergingThread, &firstHalf); pthread_create(&threads[1], NULL, mergingThread, &secondHalf); pthread_join(threads[0], NULL); pthread_join(threads[1], NULL); /* merging firstHalf and secondHalf into original mergeTDataArray */ merge(mergeTDataArray, firstHalf, secondHalf, mid, numberOfElements - mid); // printf("\nElements after sorting:\n"); // for (int i = 0; i < numberOfElements; i++) { // printf("%d ", mergeTDataArray[i]); // } // printf("\n"); start = clock() - start; printf("\nTime taken for sorting using threads: %f seconds\n", (float)start / CLOCKS_PER_SEC); } void msProcess() { int factor = divideProcessNumber, tempArray[mSizeArray[factor]]; mergeSort(divideArray, mSizeArray[factor]); for (int i = 0; i < mSizeArray[factor]; i++) { tempArray[i] = divideArray[i]; } write(fd[factor][1], &tempArray, mSizeArray[factor] * sizeof(int)); } // function that performs merge-sort on 4 different partitions void mergeSortProcess() { printf("\n=====================\n"); printf("SORTING USING PROCESS\n"); printf("=====================\n"); pid_t process[PROCESS_MAX]; divideArray = mergePDataArray; mergeArray = mergePDataArray; /* Arrays below are for each process that will contain sorted partitions */ int process1Array[mSizeArray[0]]; int process2Array[mSizeArray[1]]; int process3Array[mSizeArray[2]]; int process4Array[mSizeArray[3]]; int mid = ceil((float)numberOfElements / 2); int firstHalf[mid]; int secondHalf[numberOfElements - mid]; clock_t start; start = clock(); for (int i = 0; i < PROCESS_MAX; i++) { pipe(fd[i]); } // partitions being sorted using processes process[0] = fork(); if (process[0] == 0) { msProcess(); exit(0); } else if (process[0] > 0) { process[1] = fork(); divideArray += mSizeArray[divideProcessNumber]; divideProcessNumber++; if (process[1] == 0) { msProcess(); exit(0); } else if (process[1] > 0) { process[2] = fork(); divideArray += mSizeArray[divideProcessNumber]; divideProcessNumber++; if (process[2] == 0) { msProcess(); exit(0); } else if (process[2] > 0) { process[3] = fork(); divideArray += mSizeArray[divideProcessNumber]; divideProcessNumber++; if (process[3] == 0) { msProcess(); exit(0); } } } wait(NULL); /* reading from pipes */ read(fd[0][0], &process1Array, mSizeArray[0] * sizeof(int)); read(fd[1][0], &process2Array, mSizeArray[1] * sizeof(int)); read(fd[2][0], &process3Array, mSizeArray[2] * sizeof(int)); read(fd[3][0], &process4Array, mSizeArray[3] * sizeof(int)); // merging 4 different partition arrays into firstHalf and secondHalf in parallel process[0] = fork(); if (process[0] == 0) { merge(firstHalf, process1Array, process2Array, mSizeArray[0], mSizeArray[1]); write(fd[0][1], &firstHalf, mid * sizeof(int)); exit(0); } else if (process[0] > 0) { process[1] = fork(); if (process[1] == 0) { merge(secondHalf, process3Array, process4Array, mSizeArray[2], mSizeArray[3]); write(fd[1][1], &secondHalf, (numberOfElements - mid) * sizeof(int)); exit(0); } wait(NULL); // reading from pipes read(fd[0][0], &firstHalf, mid * sizeof(int)); read(fd[1][0], &secondHalf, (numberOfElements - mid) * sizeof(int)); // merging firstHalf and secondHalf into original mergePDataArray merge(mergePDataArray, firstHalf, secondHalf, mid, numberOfElements - mid); // printf("\nElements after sorting:\n"); // for (int i = 0; i < numberOfElements; i++) { // printf("%d ", mergePDataArray[i]); // } // printf("\n"); } start = clock() - start; printf("\nTime taken for sorting using process: %f seconds\n", (float)start / CLOCKS_PER_SEC); } } #endif
C
//Tyler Watson 260867260 #include <stdio.h> #include <stdlib.h> #include <ctype.h> int main(int argc, char **argv) { int size; //initialize size variable if (argc > 1) { //true if there are arguments with the script command if (atoi(argv[1]) <= 0) { //check if arg is greater than 0 printf("%s", "An incorrect triangle size was inputted. The size must be greater than 0 and an integer number. Syntax: ./triangles SIZE\n"); return 1; } if (atoi(argv[1]) > 0) { //if arg is greater than 0 then change size to the arg size = atoi(argv[1]); } } else { //if no arguments puts("Please input a number greater than 0."); scanf("%d", &size); //wait for input if(size<=0) { //if input is less than 0 throw error printf("%s", "An incorrect triangle size was inputted. The size must be greater than 0 and an integer number. Syntax: ./triangles SIZE\n"); return 1; } } int i; for(i=0; i<=size; i++) { //for loop to display triangle int j; for(j=0; j<size-i; j++) printf(" "); //for loop to display first spaces for(j=0; j<i; j++) printf("*"); //for loop to display * puts("\n"); //new line } return 0; }
C
#include<stdio.h> struct data{ /*structure containing data of students*/ char name[100]; char roll_no[100]; int age; int marks; }; int main() { int n; scanf("%d\n", &n); /*input the number of students*/ struct data array[n]; /*array of structure*/ for(int i = 0; i < n; i++) /*input the details of students*/ { scanf("%s", array[i].name); scanf("%s", array[i].roll_no); scanf("%d", &array[i].age); scanf("%d", &array[i].marks); } for(int i = 0; i < n; i++) /*print the details of students*/ { printf("%s\n", array[i].name); printf("%s\n", array[i].roll_no); printf("%d\n", array[i].age); printf("%d\n", array[i].marks); } return 0; }
C
#include <stdio.h> #include <unistd.h> #include <stdlib.h> /* abort 函数:给自己发送异常终止信号 6) SIGABRT 信号,终止并产生core文件 void abort(void); 该函数无返回 */ int main() { printf("当前进程pid=%d\r\n", getpid()); abort(); return 0; }
C
#include "lists.h" #include <string.h> /** * *add_dnodeint - adds a node to a linked list head * @head: linked list head * @n: int element of the linked list * Return: number of elements */ dlistint_t *add_dnodeint(dlistint_t **head, const int n) { dlistint_t *new_node; new_node = malloc(sizeof(dlistint_t)); if (new_node == NULL) { free(new_node); return (NULL); } new_node->n = n; new_node->next = *head; new_node->prev = NULL; *head = new_node; return (new_node); }
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* sh_perror.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: jmartel <jmartel@student.42.fr> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2019/04/13 14:41:27 by jmartel #+# #+# */ /* Updated: 2019/06/11 14:19:04 by jmartel ### ########.fr */ /* */ /* ************************************************************************** */ #include "sh_21.h" int sh_perror(const char *error, const char *suffix) { if (suffix && *suffix) ft_dprintf(2, "%s%s: %s : %s%s\n", SH_ERR_COLOR, SH_NAME, error, suffix, COLOR_END); else ft_dprintf(2, "%s%s: %s%s\n", SH_ERR_COLOR, SH_NAME, error, COLOR_END); return (FAILURE); } int sh_perror_err(const char *error, const char *suffix) { sh_perror(error, suffix); return (ERROR); } void *sh_perrorn(const char *error, const char *suffix) { sh_perror(error, suffix); return (NULL); } int sh_perror_err_fd(int fd, const char *error, const char *suffix) { sh_perror_fd(fd, error, suffix); return (ERROR); } void *sh_perrorn_fd(int fd, const char *error, const char *suffix) { sh_perror_fd(fd, error, suffix); return (NULL); }
C
#include "CommandsPm.h" #include "String.h" #include "LinkedList.h" #include "HashTable.h" #include "Object.h" #include "Pessoa.h" #include "Quadra.h" #include "Endereco.h" #include <stdio.h> void commandInsertPessoa( Cidade *cidade, char *line ){ char cpf[STRING_SIZE], nome[STRING_SIZE], sobrenome[STRING_SIZE], sexo, nasc[STRING_SIZE]; Pessoa *pessoa; sscanf( line, "p %s %s %s %c %s", cpf, nome, sobrenome, &sexo, nasc ); if( searchCidadePessoaCpf( cidade, cpf ) != NULL ){ fputs( line, stderr ); fprintf( stderr, "\tPessoa de cpf %s ja inserida na cidade.\n\n", cpf ); return; } if( sexo != 'M' && sexo != 'F' ){ fputs( line, stderr ); fprintf( stderr, "\tSexo invalido.\n\n" ); return; } pessoa = createPessoa( cpf, nome, sobrenome, sexo, nasc ); insertHashTable( getCidadePessoas(cidade), cpf, pessoa ); } void commandMorador( Cidade *cidade, char *line ){ char cpf[STRING_SIZE], cep[STRING_SIZE], face, compl[STRING_SIZE]; int num; Pessoa *pessoa; Endereco *endereco; sscanf( line, "m %s %s %c %d %s", cpf, cep, &face, &num, compl ); pessoa = searchCidadePessoaCpf( cidade, cpf ); if( pessoa == NULL ){ fputs( line, stderr ); fprintf( stderr, "\tPessoa de cpf %s nao encontrada.\n\n", cpf ); return; } if( searchCidadeQuadraCep( cidade, cep ) == NULL ){ fputs( line, stderr ); fprintf( stderr, "\tQuadra de cep %s nao encontrada.\n\n", cep ); return; } if( checkFace(face) ){ fputs( line, stderr ); fprintf( stderr, "\tFace invalida.\n\n" ); return; } if( getPessoaEndereco(pessoa) ){ destroyEndereco(cidadeRemoveMorador(cidade, pessoa)); } endereco = createEndereco( cep, face, num, compl ); cidadeInsertMorador( cidade, pessoa, endereco ); }
C
struct strt { int Length; }; int main() { struct strt *acts = (struct strt *)malloc(sizeof(struct strt)); acts->Length = 3; struct strt *act_implicit = &*acts; act_implicit->Length = 4; struct strt temp = *acts; struct strt *act_explicit = &temp; act_explicit->Length = 5; sparrow_print(acts); sparrow_print(act_implicit); sparrow_print(act_explicit); sparrow_print(acts->Length); sparrow_print(act_implicit->Length); sparrow_print(act_explicit->Length); return 0; }
C
#ifndef MYREADELF_H #define MYREADELF_H /*-----------------------------------------------------------------*/ #include "myreadelf_module.h" /*-----------------------------------------------------------------*/ enum flag_num{ FLAG_H, FLAG__help, FLAG_h, FLAG__file_header, FLAG_x, FLAG__hex_dump, FLAG_FILE }; // typedef struct flag_arg{ enum flag_num num; char* str; }flag_arg; // typedef struct arg_action{ enum flag_num num; char* option; struct arg_action* next; }arg_action; /*-----------------------------------------------------------------*/ char USAGE[] = "Usage: readelf <option(s)> fichier(s)-elf\n" " Afficher les informations à propos du contenu du format des fichiers ELF\n" " Options are:\n" " -H --help Afficher l'aide-mémoire\n" " -h --file-header Display the ELF file header\n" " -x --hex-dump=<number|name>\n" " Dump the contents of section <number|name> as bytes\n"; char** ELF_FILES; int count_files = 0; flag_arg flag_H = {FLAG_H,"-H"}; flag_arg flag_help = {FLAG__help,"--help"}; flag_arg flag_h = {FLAG_h,"-h"}; flag_arg flag__file_header = {FLAG__file_header,"--file-header"}; flag_arg flag_x = {FLAG_x,"-x"}; flag_arg flag__hex_dump = {FLAG__hex_dump,"--hex-dump"}; /*-----------------------------------------------------------------*/ arg_action* parse_arg(int , char** ); arg_action* new_action(); /*-----------------------------------------------------------------*/ #endif
C
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ /* * File: power.c * Author: Simply Enoch * * Created on October 21, 2019, 8:37 AM */ #include <stdio.h> #include <stdlib.h> double power(double, int); int main(int argc, char** argv) { float x; int n; printf("Enter the value of x: "); scanf("%f", &x); printf("Enter the value of n: "); scanf("%d", &n); printf("%.3f raised to the power of %d is %.8f", x, n, power(x, n)); return (EXIT_SUCCESS); } double power(double x, int n) { int i; double product = 1.0; for (i = 1; i <= n; i++) product *= x; return product; }
C
#include <stdio.h> typedef struct listas { int info; struct listas *next; } Lista_t; Lista_t * InsCodaCrea(Lista_t *t,int num); Lista_t * InsTesta(Lista_t *t, Lista_t *n); Lista_t * InvertiLista(Lista_t *t); void StampaLista(Lista_t *t); int main() { Lista_t *testa = NULL; Lista_t *n; int num; printf("=============== CARICAMENTO DELLA LISTA CON InsCodaCrea ===============\n\n"); printf("Inserisci un numero della lista (termina con 0): "); scanf("%d",&num); while (num) { testa = InsCodaCrea(testa,num); printf("Inserisci un numero della lista (termina con 0): "); scanf("%d",&num); } printf("\nLa lista creata con InsCodaCrea e': "); StampaLista(testa); testa = InvertiLista(testa); printf("\n\nLa lista invertita e': "); StampaLista(testa); printf("\n\n"); system("Pause"); } Lista_t * InsCodaCrea(Lista_t *t,int num) { Lista_t *n,*p; if ( n = (Lista_t *) malloc(sizeof(Lista_t)) ) { n->info = num; n->next = NULL; if ( t == NULL ) return n; for(p=t; p->next!=NULL; p=p->next) ; p->next = n; return t; } else printf("\n\nMemoria esaurita!"); } Lista_t * InsTesta(Lista_t *t, Lista_t *n) { if (n!=NULL) n->next=t; t=n; return t; } Lista_t * InvertiLista(Lista_t *t) { Lista_t *h=NULL; Lista_t *p; //printf("\n\n"); while( t!=NULL ) { /*if ( t!=NULL ) printf("*t = %d t.info = %d t.next = %d\n",t,t->info,t->next); else printf("*t = %d\n",t); printf("*p = %d p.info = %d p.next = %d\n",p,p->info,p->next); if ( h!=NULL ) printf("*h = %d h.info = %d h.next = %d\n\n",h,h->info,h->next); else printf("*h = %d\n\n",h); */ p=t; t=t->next; /*if ( t!=NULL ) printf("*t = %d t.info = %d t.next = %d\n",t,t->info,t->next); else printf("*t = %d\n",t); printf("*p = %d p.info = %d p.next = %d\n",p,p->info,p->next); if ( h!=NULL ) printf("*h = %d h.info = %d h.next = %d\n\n\n",h,h->info,h->next); else printf("*h = %d\n\n\n",h); */ h=InsTesta(h,p); } return h; } void StampaLista (Lista_t *t) { while (t) { printf("%d ",t->info); t = t->next; } }
C
#include <stdio.h> int main() { char a; char t, T; int f=0; while(1) { scanf("%c", &a); if(a=='*') {break;} if(a<95) { T=a; t=a+32; } else { T=a-32; t=a; } while(1) { scanf("%c", &a); if(a=='\n') {break;} else if(a==' ') { scanf("%c", &a); if((a!=t) && (a!=T)) { f=1; } } } if(f==0) { printf("Y\n"); } else { printf("N\n"); f=0; } } return 0; }
C
/* ************************************************************************** */ /* */ /* :::::::: */ /* ft_itoa.c :+: :+: */ /* +:+ */ /* By: aaugusti <aaugusti@student.codam.nl> +#+ */ /* +#+ */ /* Created: 2020/10/29 14:15:59 by aaugusti #+# #+# */ /* Updated: 2020/10/29 14:15:59 by aaugusti ######## odam.nl */ /* */ /* ************************************************************************** */ #include <stddef.h> #include "libft.h" #include <stdlib.h> #include <limits.h> /* ** Get the amount of bytes needed to store the result of itoa. */ static int ft_itoa_numlen(int n) { int res; res = 0; if (n < 0) { n *= -1; res++; } while (n > 0) { n /= 10; res++; } return (res); } /* ** Check for the two edgecases and handle those. */ static char *ft_itoa_exception(int n) { if (n) return (ft_strdup("-2147483648")); return (ft_strdup("0")); } /* ** Allocate the right amount of memory for the result string and zero-temrinate ** the string. */ static char *ft_itoa_get_mem(size_t len) { char *res; res = (char *)malloc(len); if (res == NULL) return (NULL); res[len - 1] = '\0'; return (res); } /* ** Convert an integer into a string. Returns NULL if the allocation failed. */ char *ft_itoa(int n) { int n_len; int is_neg; char *res; int i; if (n == INT_MIN || n == 0) return (ft_itoa_exception(n)); n_len = ft_itoa_numlen(n); res = ft_itoa_get_mem((size_t)n_len + 1); if (res == NULL) return (NULL); is_neg = n < 0; if (is_neg) { *res = '-'; n *= -1; } i = 0; while (i < n_len - is_neg) { res[n_len - 1 - i] = (char)(n % 10 + '0'); n /= 10; i++; } return (res); }
C
#include <stdlib.h> #include <stdio.h> #include <poll.h> #include <ctype.h> #include <unist.ih> #include "mbconsole.h" // TODO? uint32_t* argv[]) int extra_debug = 0; void exe_test(uint32_t argc, char* argv[]){ printf("TEST OK\n"); } void exe_parse(uint32_t argc, char* argv[]){ printf("Parsed %d args\n", argc); for (uint32_t i = 0; i < argc; i++){ printf("%d | %s\n", argc, argv[i]); } } void exe_echo(uint32_t argc, char* argv[]){ for (uint32_t i = 0; i < argc; i++) { printf("%s ", argv[i]); } printf("\n"); } void exe_exit(uint32_t argc, char* argv[]){ printf("exit"); printf("\n"); exit(0); } console_executable exes[] = { {"test", &exe_test}, {"parse", &exe_parse}, {"echo", &exe_echo}, {"exit", &exe_exit}, }; console_executable_table exe_table = { exes, sizeof(exes)/sizeof(exes[0])}; int main(void){ console_set_exe_table(&exe_table); system ("/bin/stty raw"); while (true) { struct pollfd fds; /* watch stdin for input */ fds.fd = STDIN_FILENO; fds.events = POLLIN; // /* watch stdout for ability to write */ // fds.fd = STDOUT_FILENO; // fds.events = POLLOUT; int ret; if (ret = poll(&fds, 1, 1000) == -1) { perror("polling stdin returned -1 - err"); return(1); } /* // 0 is also our nice FDS descriptor else if (ret == 0) { perror("polling stdin returned 0 - timeout no character to read"); } */ else if (fds.revents & POLLIN) { int fd = STDIN_FILENO; size_t n; char b[100]; n = read(fd, b, sizeof(b)); for (uint32_t i = 0; i < n; i++) { const char c = b[i]; printf("getchar() = %c\n", isprint(c) ? c : 'x'); console_interrupt_handler_with_char(c); } } else if (fds.revents & POLLHUP) { printf("POLLHUP\n"); } else if (fds.revents & POLLERR) { printf("POLLERR\n"); } else if (fds.revents & POLLNVAL) { } if (extra_debug) { printf("revents: %08x\n", fds.revents); printf("POLLIN: %08x\n", POLLIN); } fds.revents = 0; console_exec(); } } #if EXAMPLE #include <stdio.h> #include <unistd.h> #include <sys/poll.h> #define TIMEOUT 5 int main (void) { struct pollfd fds[2]; int ret; /* watch stdin for input */ fds[0].fd = STDIN_FILENO; fds[0].events = POLLIN; /* watch stdout for ability to write */ fds[1].fd = STDOUT_FILENO; fds[1].events = POLLOUT; ret = poll(fds, 2, TIMEOUT * 1000); if (ret == -1) { perror ("poll"); return 1; } if (!ret) { printf ("%d seconds elapsed.\n", TIMEOUT); return 0; } if (fds[0].revents & POLLIN) printf ("stdin is readable\n"); if (fds[1].revents & POLLOUT) printf ("stdout is writable\n"); return 0; #endif
C
/* * All memory allocation functions are here */ #include <stdlib.h> #include <stdbool.h> #include <stddef.h> #include <stdalign.h> #include <string.h> #include <kernel/mm.h> #include <kernel/sched.h> #include <kernel/sync.h> #include <kernel/panic.h> #define CANARY 0xCAFEBABE /* Chunck anatomy: * * chunck_marker_start_t (free? + usable size) * padding? for alignment * USEABLE MEMORY * chunck_marker_end_t (usable size) * padding? for alignment */ // at the begining of each chunck typedef struct chunck_marker_start { bool free; size_t size; // of available memory, don't forget to add sizeof chunck_marker_start_t + sizeof chunck_marker_end at the end } chunck_marker_start_t; typedef struct chunck_marker_end { size_t size; // of available memory, see above uint32_t canary; } chunck_marker_end_t; static const size_t max_align = alignof( max_align_t); static size_t aligned_size(const size_t size) { size_t modulo = size%max_align; return size + (modulo!=0 ? max_align-modulo : 0); } /* Puts chunck_marker_start_t and chunck_marker_end_t. * insertion_point and useable_size must already be aligned. */ static void mark_chunck(const uintptr_t insertion_point, const size_t useable_size, const bool isFree) { chunck_marker_start_t* start = (chunck_marker_start_t*)insertion_point; start->free = isFree; start->size = useable_size; chunck_marker_end_t* end = (chunck_marker_end_t*)(insertion_point + useable_size + aligned_size(sizeof(chunck_marker_start_t))); end->size = useable_size; end->canary = CANARY; } void* malloc( size_t size ) { if(size == 0) { return NULL; } //FIXME const for useable_size + start_size + end_size? size_t useable_size = aligned_size(size); const size_t start_size = aligned_size(sizeof(chunck_marker_start_t)); const size_t end_size = aligned_size(sizeof(chunck_marker_end_t)); mm_ring_info_t* info = current_process_control_block()->mm_info->kernel_info; uintptr_t best_ptr = 0; chunck_marker_start_t* last_marker = NULL; size_t best_size; semaphore_acquire(&info->heap_semaphore); uintptr_t ptr = info->heap_start; while(ptr < info->heap_end) { last_marker = (chunck_marker_start_t*)ptr; if(last_marker->free && last_marker->size >= useable_size && (best_ptr == 0 || last_marker->size < best_size)) { // found a better match best_ptr = ptr; best_size = last_marker->size; if(last_marker->size == useable_size) { // and we can't find a better one break; } } ptr += last_marker->size + start_size + end_size; } if(best_ptr != 0) { if(best_size > useable_size + start_size + end_size) { // split it uintptr_t free_chunck_insertion_point = best_ptr + useable_size + start_size + end_size; size_t free_chunck_size = best_size - useable_size - start_size - end_size; mark_chunck(free_chunck_insertion_point, free_chunck_size, true); } else { // use the sligthly bigger size useable_size = best_size; } // use it mark_chunck(best_ptr, useable_size, false); semaphore_release(&info->heap_semaphore); return (void*)(best_ptr + start_size); } else { // need to allocate some more memory uintptr_t insertion_point; size_t free_size; if(last_marker == NULL || !last_marker->free) { // we must start at the begining of a new page insertion_point = info->heap_end; free_size = 0; } else { // let's merge with the last free chunck insertion_point = (uintptr_t)last_marker; free_size = last_marker->size + start_size + end_size; } while(free_size < useable_size + start_size + end_size) { // increase the heap // TODO check we don't overwrite the stack uintptr_t new_page = mm_alloc_physical_page(true); if(new_page == 0) { panic("failed to increase heap size (alloc)"); } if(mm_map_page(new_page, info->heap_end)) { panic("failed to increase heap size (map)"); } info->heap_end += MM_PAGE_SIZE; free_size += MM_PAGE_SIZE; } if(free_size > useable_size + 2*start_size + 2*end_size) { // split it uintptr_t free_chunck_insertion_point = insertion_point + useable_size + start_size + end_size; size_t free_chunck_size = free_size - useable_size - 2*start_size - 2*end_size; mark_chunck(free_chunck_insertion_point, free_chunck_size, true); } else { // use the sligthly bigger size useable_size = free_size - start_size - end_size; } mark_chunck(insertion_point, useable_size, false); semaphore_release(&info->heap_semaphore); return (void*)(insertion_point + start_size); } } void free( void* ptr ) { if(ptr == NULL) { return; } mm_ring_info_t* info = current_process_control_block()->mm_info->kernel_info; const size_t start_size = aligned_size(sizeof(chunck_marker_start_t)); const size_t end_size = aligned_size(sizeof(chunck_marker_end_t)); chunck_marker_start_t* start = (chunck_marker_start_t*)(ptr - start_size); chunck_marker_end_t* end = (chunck_marker_end_t*)(ptr + start->size); if(end->canary != CANARY) { panic("Dead heap canary"); } semaphore_acquire(&info->heap_semaphore); start->free = true; // merge with chuncks before/after chunck_marker_start_t* start_after = (chunck_marker_start_t*)(ptr + start->size + end_size); if((uintptr_t)start_after < info->heap_end && start_after->free) { mark_chunck((uintptr_t)start, start->size + start_after->size + start_size + end_size, true); } chunck_marker_end_t* end_before = (chunck_marker_end_t*)(ptr - start_size - end_size); if((uintptr_t)end_before > info->heap_start) { if(end_before->canary != CANARY) { panic("Dead heap canary"); } chunck_marker_start_t* start_before = (chunck_marker_start_t*)(ptr - start_size - end_size - end_before->size - start_size); if(start_before->free) { mark_chunck((uintptr_t)start_before, start->size + start_before->size + start_size + end_size, true); } } semaphore_release(&info->heap_semaphore); } void* realloc (void* ptr, size_t size) { void* destptr = NULL; if(size != 0) { destptr = malloc(size); } if(destptr != NULL && ptr != NULL) { //get the size of the initial memory block const size_t start_size = aligned_size(sizeof(chunck_marker_start_t)); chunck_marker_start_t* start = (chunck_marker_start_t*)(ptr - start_size); size_t init_size = start->size; size_t length_to_copy = size < init_size ? size : init_size; memcpy(destptr, ptr, length_to_copy); free(ptr); } return destptr; }
C
#include <stdio.h> int main(void) { int n = 0, n2 = 0; printf("TABLE OF MULTIPLES OF 5 AND THEIR TRIANGULAR NUMBERS\n\n"); printf(" M TN \n"); printf("--- ----\n"); while(n % 5 == 0, n <= 50) { n2 = n * (n + 1) / 2; printf("%2i %i\n", n, n2); n = n + 5; } return 0; }
C
#ifndef POSITION_H #define POSITION_H struct Position { int x, y; bool operator<(const Position &position) const; bool operator==(const Position &position) const; Position operator+(const Position &position) const; Position operator-(const Position &position) const; }; #endif
C
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <conio.h> #include <ctype.h> #include "proveedores.h" #include "productos.h" #include "informes.h" #include "input.h" void ordenarProd(eProducto prod[], int cantidad) { int j, k; eProducto aux; for (j=0; j<cantidad-1; j++) { for(k=j+1; k<cantidad; k++) { if (prod[j].importe < prod[k].importe){ aux = prod[j]; prod[j] = prod[k]; prod[k] = aux; } else if (prod[j].importe == prod[k].importe) { if (strcmp(prod[j].descripcion, prod[k].descripcion) > 0) { aux = prod[j]; prod[j] = prod[k]; prod[k] = aux; } } } } } void informarProd(eProducto prod[], int cantidad, eProveedor prov[]) { char seguir='s'; char auxOpcion[1]; int opcion=0; int validado, i; int hayDatos = 0; system("cls"); for(i = 0; i < cantidad; i++) { if(prod[i].estado == 1) { hayDatos = 1; break; } } if(hayDatos == 1) { while(seguir=='s') { printf("1- Total y Promedio de Importes y cuantos productos lo superan\n"); printf("2- Total y Promedio de Importes y cuantos productos NO lo superan\n"); printf("3- Cantidad Productos STOCK menos o igual a 10\n"); printf("4- Cantidad Productos STOCK mayor a 10\n\n"); printf("5- Volver al menu principal\n\n"); do { fflush(stdin); scanf("%s", auxOpcion); validado = validaNumero(auxOpcion); } while(validado == 0); opcion = atoi(auxOpcion); switch(opcion) { case 1: system("cls"); calculaPromedio(prod, cantidad, opcion); break; case 2: system("cls"); calculaPromedio(prod, cantidad, opcion); break; case 3: system("cls"); calculaCantidad(prod, cantidad, opcion, prov); break; case 4: system("cls"); calculaCantidad(prod, cantidad, opcion, prov); break; case 5: seguir = 'n'; system("cls"); break; } } } else { printf("No hay datos que mostrar.\n\n"); } } void listarProd(eProducto prod[], int cantidad, eProveedor prov[]) { char seguir='s'; char auxOpcion[2]; int opcion=0; int validado, i; int hayDatos = 0; system("cls"); for(i = 0; i < cantidad; i++) { if(prod[i].estado == 1) { hayDatos = 1; break; } } if(hayDatos == 1) { while(seguir=='s') { int flag = 0, codigo; printf("1- Listar ordenados\n"); printf("2- Productos cuya cantidad es menor o igual a 10\n"); printf("3- Productos cuya cantidad es mayor a 10\n"); printf("4- Productos que superan el promedio de importes\n"); printf("5- Productos que no superan el promedio de importes\n"); printf("6- Proveedores cuyos productos es menor o igual a 10\n"); printf("7- Productos provistos por cada proveedor\n"); printf("8- Productos provistos por determinado proveedor\n"); printf("9- Proveedor con mas productos y sus productos\n"); printf("10- Proveedor con menos productos y sus productos\n"); printf("11- Proveedor con el producto mas caro y el producto\n"); printf("12- Proveedor con el producto mas barato y el producto\n"); printf("13- Volver al menu principal\n\n"); do { fflush(stdin); scanf("%s", auxOpcion); validado = validaNumero(auxOpcion); } while(validado == 0); opcion = atoi(auxOpcion); switch(opcion) { case 1: system("cls"); ordenarProd(prod, cantidad); printf("Listado de Productos:\n\nCodigo\tDescripcion\tImporte\tCantidad\n"); for(i=0; i<cantidad; i++){ if(prod[i].estado == 1){ toStringProd(prod[i]); } } printf("\n"); break; case 2: system("cls"); flag = 0; for (i=0; i<cantidad; i++){ if(prod[i].estado == 1){ if(prod[i].cant <= 10){ if (flag == 0){ printf("Listado de Productos:\n\nCodigo\tDescripcion\tImporte\tCantidad\n"); flag = 1; } toStringProd(prod[i]); } } } printf("\n"); break; case 3: system("cls"); flag = 0; for (i=0; i<cantidad; i++){ if(prod[i].estado == 1){ if(prod[i].cant > 10){ if (flag == 0){ printf("Listado de Productos:\n\nCodigo\tDescripcion\tImporte\tCantidad\n"); flag = 1; } toStringProd(prod[i]); } } } printf("\n"); break; case 4: system("cls"); printf("Listado de Productos:\n\nCodigo\tDescripcion\tImporte\tCantidad\n"); calculaPromedio(prod, cantidad, opcion); printf("\n"); break; case 5: system("cls"); printf("Listado de Productos:\n\nCodigo\tDescripcion\tImporte\tCantidad\n"); calculaPromedio(prod, cantidad, opcion); printf("\n"); break; case 6: system("cls"); printf("Listado de Proveedores:\n\nCodigo\tDescripcion\n"); calculaCantidad(prod, cantidad, opcion, prov); printf("\n"); break; case 7: system("cls"); printf("Listado de Productos:\n\nCodigo\tDescripcion\tImporte\tCantidad\tProveedor\n"); listaProductosProveedores(prod, cantidad, prov); printf("\n"); break; case 8: system("cls"); int cont = 0, j; printf("Ingrese el codigo de proveedor a listar:\n"); scanf("%d", &codigo); for(i=0; i<cantidad; i++) { if(prov[i].codigo == codigo && codigo != 0) { for(j=0; j<cantidad; j++) { if(prod[j].codProv == prov[i].codigo) { cont++; } } if(cont > 0) { printf("Listado de Productos:\n\nCodigo\tDescripcion\tImporte\tCantidad\tProveedor\n"); listaProveedor(prod, cantidad, prov[i]); flag = 1; break; } else { printf("Dicho proveedor no tiene productos\n"); flag = 1; } } } if(flag == 0) { printf("No existe proveedor con ese codigo.\n"); } printf("\n"); break; case 9: system("cls"); listaMayMenProv(prod, cantidad, opcion, prov); printf("\n"); break; case 10: system("cls"); listaMayMenProv(prod, cantidad, opcion, prov); printf("\n"); break; case 11: system("cls"); calculaPrecio(prod, cantidad, opcion, prov); break; case 12: system("cls"); calculaPrecio(prod, cantidad, opcion, prov); break; case 13: seguir = 'n'; system("cls"); break; default: system("cls"); printf("Opcion no valida.\n\n"); break; } } } else { printf("No hay datos que mostrar.\n\n"); } } void calculaPromedio(eProducto prod[], int cantidad, int opcion) { float importeTotal = 0, promedio = 0; int cantProdsMay = 0, cantProdsMen = 0, cantImportes = 0, i; for(i=0; i<cantidad; i++){ if(prod[i].estado == 1){ importeTotal = importeTotal + prod[i].importe; cantImportes++; } } promedio = importeTotal / cantImportes; for(i=0; i<cantidad; i++){ if(prod[i].estado == 1){ if(prod[i].importe > promedio){ if(opcion == 4) { toStringProd(prod[i]); } cantProdsMay++; } if(prod[i].importe < promedio){ if(opcion == 5) { toStringProd(prod[i]); } cantProdsMen++; } } } if(opcion == 1) { printf("Importe Total: %.2f\nPromedio Importes: %.2f\nProductos con importe mayor al promedio: %d\n\n", importeTotal, promedio, cantProdsMay); } else if (opcion == 2) { printf("Importe Total: %.2f\nPromedio Importes: %.2f\nProductos con importe menor al promedio: %d\n\n", importeTotal, promedio, cantProdsMen); } } void calculaCantidad(eProducto prod[], int cantidad, int opcion, eProveedor prov[]) { int cantProdsMen = 0, cantProdsMay = 0, i, j; for(i=0; i<cantidad; i++){ if(prod[i].estado == 1) { if(prod[i].cant <= 10){ if(opcion == 6) { for(j=0; j<cantidad; j++) { if(prov[j].codigo == prod[i].codProv) { toStringProv(prov[j]); break; } } } cantProdsMen++; } if(prod[i].cant > 10){ cantProdsMay++; } } } if (opcion == 3) { printf("Cantidad de productos con stock menor o igual a 10: %d\n\n", cantProdsMen); } else if (opcion == 4) { printf("Cantidad de productos con stock mayor a 10: %d\n\n", cantProdsMay); } } void toStringProd(eProducto prod) { printf("%d\t%s\t\t%.2f\t%d\n", prod.codigo, prod.descripcion, prod.importe, prod.cant); } void toStringProv(eProveedor prov) { printf("%d\t%s\n", prov.codigo, prov.descripcion); } void listaProductosProveedores(eProducto prod[], int cantidad, eProveedor prov[]) { int i, j; for(i=0; i<cantidad; i++) { for(j=0; j<cantidad; j++) { if(prod[i].codProv == prov[j].codigo) { printf("%d\t%s\t\t%.2f\t%d\t\t%s\n", prod[i].codigo, prod[i].descripcion, prod[i].importe, prod[i].cant, prov[j].descripcion); break; } } } } void listaProveedor(eProducto prod[], int cantidad, eProveedor prov) { int i; for(i=0; i<cantidad; i++) { if(prod[i].codProv == prov.codigo) { printf("%d\t%s\t\t%.2f\t%d\t\t%s\n", prod[i].codigo, prod[i].descripcion, prod[i].importe, prod[i].cant, prov.descripcion); } } } void listaProductosxProveedor(eProducto prod, int cantidad, eProveedor prov) { printf("%d\t%s\t\t%.2f\t%d\t\t%s\n", prod.codigo, prod.descripcion, prod.importe, prod.cant, prov.descripcion); } void calculaPrecio(eProducto prod[], int cantidad, int opcion, eProveedor prov[]) { int i, j, masCaro, masBarato, flag = 0, indexCaroProd = 0, indexBaratoProd = 0, indexCaroProv = 0, indexBaratoProv = 0; for(i=0; i<cantidad; i++){ if(prod[i].estado == 1) { if(flag==0) { masCaro = prod[i].importe; masBarato = prod[i].importe; indexCaroProd = i; indexBaratoProd = i; flag = 1; } if(prod[i].importe > masCaro) { for(j=0; j<cantidad; j++) { if(prov[j].codigo == prod[i].codProv) { indexCaroProv = j; break; } } masCaro = prod[i].importe; indexCaroProd = i; } if(prod[i].importe < masBarato && prod[i].importe > 0) { for(j=0; j<cantidad; j++) { if(prov[j].codigo == prod[i].codProv) { indexBaratoProv = j; break; } } masBarato = prod[i].importe; indexBaratoProd = i; } } } if (opcion == 11) { printf("Listado de Productos:\n\nCodigo\tDescripcion\tImporte\tCantidad\tProveedor\n"); listaProductosxProveedor(prod[indexCaroProd], cantidad, prov[indexCaroProv]); printf("\n"); } else if (opcion == 12) { printf("Listado de Productos:\n\nCodigo\tDescripcion\tImporte\tCantidad\tProveedor\n"); listaProductosxProveedor(prod[indexBaratoProd], cantidad, prov[indexBaratoProv]); printf("\n"); } } void listaMayMenProv(eProducto prod[], int cantidad, int opcion, eProveedor prov[]) { int i, j, flag = 0, flag2 = 0, indexMayorProv, indexMenorProv, mayorProv, menorProv, totProv = 0; for(i=0; i<cantidad; i++) { for(j=0; j<cantidad; j++) { if(prod[j].estado == 1) { if(prov[i].codigo == prod[j].codProv) { if(flag == 0) { indexMayorProv = i; indexMenorProv = i; flag = 1; } totProv++; } } } if(flag2 == 0 && totProv > 0) { mayorProv = totProv; menorProv = totProv; flag2 = 1; } if(totProv > mayorProv) { indexMayorProv = i; } if(totProv < menorProv && totProv > 0) { indexMenorProv = i; } totProv = 0; } if(opcion == 9) { printf("Proveedor con mas Productos:\n\nCodigo\tDescripcion\tImporte\tCantidad\tProveedor\n"); listaProveedor(prod, cantidad, prov[indexMayorProv]); } else if(opcion == 10) { printf("Proveedor con menos Productos:\n\nCodigo\tDescripcion\tImporte\tCantidad\tProveedor\n"); listaProveedor(prod, cantidad, prov[indexMenorProv]); } }
C
// //////////////////////////////////////////////////////////////// // // Project: Pipes in Unix // Author: Christopher Anzalone // File: pipes.c // // \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\ // // Description: // // The pipes program replicates the behavior of the pipes // command (|) in a unix shell. This command takes the output // of one process, and makes it the input for another. To // achieve this, this C program creates a pipe using the // pipe() function. It then creates two child processes using // fork(). The fork operation is one that creates a copy of // the parent process, creating a child process. It is a // system call in the kernel that is used for process creation // in Unix systems. Child 1 redirects its output from stdout // to the write end of the pipe and executes the command // "ls -al" using the execlp() function. Child 2 redirects its // input from stdin to the read end of the pipe and executes // the "sort -n -k 5" command. The parent process waits for // its children processes to finish executing before it // terminates. // // //////////////////////////////////////////////////////////////// #include <sys/types.h> #include <stdio.h> #include <unistd.h> #include <string.h> #include <stdlib.h> #include <sys/wait.h> #define READ_END 0 #define WRITE_END 1 int main() { pid_t pid; int fd[2]; int status; /* create pipe */ if (pipe(fd) == -1) { fprintf(stderr, "Pipe failed."); return 1; } /* fork first child */ pid = fork(); if (pid < 0) { fprintf(stderr, "Fork call 1 has failed"); return 1; } else if (pid == 0) { /* close unused side of pipe */ if ( close(fd[READ_END]) == -1 ) { fprintf(stderr, "close call failed"); return 1; } /* redirect standard output to write-end of pipe */ if ( dup2(fd[WRITE_END], STDOUT_FILENO) == -1 ) { fprintf(stderr, "dup2 call failed"); return 1; } /* execute process "ls" with "ls -al" */ if ( execlp("ls", "ls", "-al", NULL) == -1 ) { fprintf(stderr, "execlp call failed"); return 1; } /* close write-end of pipe (to avoid hanging) */ if ( close(fd[WRITE_END]) == -1) { fprintf(stderr, "close call failed"); return 1; } } else { /* fork second child */ pid = fork(); if (pid < 0) { fprintf(stderr, "Fork call 2 has failed"); return 1; } else if (pid == 0) { /* close unused side of pipe */ if ( close(fd[WRITE_END]) == -1 ) { fprintf(stderr, "close call failed"); return 1; } /* redirect standard input to read-end of pipe */ if ( dup2(fd[READ_END], STDIN_FILENO) == -1) { fprintf(stderr, "dup2 call failed"); return 1; } /* execute process "sort" with "sort -n -k 5" */ if ( execlp("sort", "sort", "-n", "-k", "5", NULL) == -1) { fprintf(stderr, "execlp call failed"); return 1; } /* close read-end of pipe (to avoid hanging) */ if ( close(fd[READ_END]) == -1 ) { fprintf(stderr, "close call failed"); return 1; } } else { wait(&status); } } return 0; }
C
#ifndef __FAMILY_TREE_H #define __FAMILY_TREE_H #include <stdio.h> #include <stdlib.h> #include <string.h> #include <assert.h> #ifdef __cplusplus extern "C" { #endif #ifdef __GNUC__ #pragma GCC diagnostic ignored "-Wpragmas" #pragma GCC diagnostic ignored "-Wunknown-pragmas" #pragma GCC diagnostic ignored "-pedantic" #pragma GCC diagnostic ignored "-Wpedantic" #pragma GCC diagnostic ignored "-Wzero-length-array" #pragma GCC diagnostic ignored "-Wcast-qual" #pragma GCC diagnostic ignored "-Wcast-align" #pragma GCC diagnostic ignored "-Wsign-compare" #pragma GCC diagnostic ignored "-Wsign-conversion" #pragma GCC diagnostic ignored "-Wconversion" #endif #define FAMILY_TREE_MALLOC(size) malloc(size) #define FAMILY_TREE_REALLOC(ptr, size) realloc(ptr, size) #define FAMILY_TREE_FREE(ptr) free(ptr) #define FAMILY_TREE_ASSERT(cond) assert(cond) #define FAMILY_TREE_TRACE(...) // fprintf( stderr, "TRACE: <" __FILE__ ":" XSTRING(__LINE__) "> " ), fprintf( stderr, __VA_ARGS__ ), fprintf( stderr, "\r\n" ) typedef struct __family_tree family_tree_t; struct __family_tree { family_tree_t *next, *prev; ///< sibling family_tree_t *child; ///< pointer to first child unsigned char data[0]; ///< custom data(variable length) }; #define FAMILY_TREE_NODE(data) ((family_tree_t *)((char *)(data) - sizeof(family_tree_t))) #define FAMILY_TREE_DATA(node) ((void *)((char *)(node) + sizeof(family_tree_t))) #define FAMILY_TREE_PREV(node) ((node)->prev) #define FAMILY_TREE_NEXT(node) ((node)->next) #define FAMILY_TREE_CHILD(node) ((node)->child) #define FAMILY_TREE_PARENT(node) (FAMILY_TREE_PREV(node)) /* Valid only when OPRMEM_ISHEAD(mem). */ #define FAMILY_TREE_ISROOT(node) (!FAMILY_TREE_PARENT(node)) #define FAMILY_TREE_ISFIRST(node) (FAMILY_TREE_NEXT(FAMILY_TREE_PREV(node)) != (node)) #define FAMILY_TREE_ISLAST(node) (!FAMILY_TREE_NEXT(node)) /** * @brief Create an family_tree_t * * @param size, size of custom data area. * @return pointer to `family_tree_t`, NULL if failed to allocate memory. * */ family_tree_t *family_tree_create( size_t size ); /** * @brief Destory the xlog-tree * * @param tree(*), xlog-tree to destory. * hook, called before destory tree node; NULL, do nothing. * */ void family_tree_destory( family_tree_t *tree, void ( *hook )( family_tree_t * ) ); /** * @brief Resize the family_tree_t * * @param node(*), object to resize(SAME AS family_tree_create if `node` is NULL). * @param size, new size of custom data area. * @return pointer to `family_tree_t`, NULL if failed to allocate memory. * */ family_tree_t *family_tree_resize( family_tree_t *node, size_t size ); /** * @brief Get parent of the family_tree_t * * @param node, Non-NULL family_tree_t * @return pointer to parent of `family_tree_t`, NULL if root node. * */ family_tree_t *family_tree_parent( const family_tree_t *node ); /** * @brief Set parent of the family_tree_t * * @param node(*), Non-NULL family_tree_t * @param parent(*), parent of `node`(NULL if to remove node from old tree) * */ void family_tree_set_parent( family_tree_t *node, family_tree_t *parent ); /** * @brief Steal node to another tree. * * @param node(*), family_tree_t to move. * @param parent(*), destnation parent. * */ void family_tree_steal( family_tree_t *node, family_tree_t *parent ); /** * @brief Traverse family_tree_t tree * * @param node, root node of tree to traverse. * @param func, function to traver node tree. * @param savaptr(*)(Non-NULL), saveptr to avoid access the same node. * */ void family_tree_traverse( const family_tree_t *node, void ( *func )( const family_tree_t * ), family_tree_t const **saveptr ); #if 0 /** * @brief Get degree of the node * * @param node, family_tree_t. * */ int family_tree_degree( const family_tree_t *node ); /** * @brief Get depth of the tree * * @param node, root node of tree. * */ int family_tree_depth( const family_tree_t *node ); /** * @brief Get children number * * @param node, root node of tree. * */ int family_tree_get_child_number( const family_tree_t *node ); /** * @brief Get sibling number * * @param node, family_tree_t. * */ int family_tree_get_sibling_number( const family_tree_t *node ); #endif #ifdef __cplusplus } #endif #endif
C
/************************************************************************************************** * * File Name: id_node.h * * Author: Reed Terdal * * Created for CS344 on: 10/09/2019 * * Purpose: Header that provides access to functions for manipulating ID nodes. * **************************************************************************************************/ #ifndef JOTT_INTERPRETTER_ID_NODE_H #define JOTT_INTERPRETTER_ID_NODE_H #include <glib.h> #include "Token.h" #include "ids.h" /** * This struct represents an ID in the parse/syntax tree, including the ID name and type. */ typedef struct id_node { GString * id; Type type; }id_node; /** * @brief This function takes in an ID token and creates an id_node. * @param idToken[IN] The token to create an id_node for, must be type t_id. * @return The new id_node. */ id_node * create_id_node(Token * idToken); /** * @brief This function creates a JSON representation of the provided id_node. * @param idNode[IN] The id_node to create a JSON representation for. * @return The JSON formatted string. */ GString * id_node_to_json(id_node * idNode); /** * @brief This function is a destructor responsible for freeing any memory for the provided id_node. * @param idNode[IN/OUT] The id_node to free. */ void destroy_id_node(id_node * idNode); #endif //JOTT_INTERPRETTER_ID_NODE_H
C
#include "holberton.h" #include <stdlib.h> /** * _strdup - function that returns a pointer to a newly allocated space in * memory, which contains a copy of the string given as a parameter. *@str : array. * Return: pointer to a new string , NULL if str = NULL , on success eturns a * pointer to the duplicated string */ char *_strdup(char *str) { int i = 0, len = 0; char *p; if (str == NULL) return (NULL); while (str[len] != '\0') len++; len++; p = malloc(len * sizeof(char)); if (p == NULL) return (NULL); for (i = 0 ; i <= len ; i++) p[i] = str[i]; return (p); }
C
/// file: mirsa_genkeys.c /// description: /// reads commandline arguments and checks the flag and returns messages based on the commandline ///and it creates random prime numbers and pass it to the function in mirsa_lib.h to create oup and pvt keys as well as files for those keys /// ////// author: Gayathri Kanagaraj gk4045 /// since: 2020 /// // // // // // // // // // // // // // // // // // // // // // // // // #include <stdio.h> #include "mirsa_lib.h" #include <getopt.h> #include <stdlib.h> // bool type #include <limits.h> #include <string.h> #include <time.h> #include <ctype.h> #include <stdbool.h> /// output a usage message/ to stderr, standard error. /// Use when the program has an incomplete command line. /// @param message NUL-terminated C string to print void usage( char message[]) { fprintf( stderr, "%s", message ); } /// output a note message to stderr, standard error. /// Use when the program has an incomplete command line. /// @param message NUL-terminated C string to print void error( char message[]) { fprintf( stderr, "%s", message); } ///readFile function reads Primes.txt file, allocates memory for the ///unsigned long int array and stores values to the array. /// @return pointer - unsigned long int pointer stored with prime numbers unsigned long int* readFile(){ unsigned long int *array; FILE *fp; fp =fopen("Primes.txt","r"); int a=0; int str; if(fp == NULL){ perror("Error"); } int i =0; while(fscanf(fp,"%d",&str)!= EOF){ if(i==0){ array = malloc(sizeof(unsigned long int) *str); } if(i>0){ array[a]= str; a++; } i++; } fclose(fp); return array; } ///generates random prime numbers ///@param array - array of prime numbers ///@param seed - seed value to benerate random prime number /// @return uint64_t prime number void seedGen(unsigned long int *array, int seed,uint64_t *p,uint64_t *q){ srand(seed); int randomIndex =rand()%100; *p=array[randomIndex]; randomIndex =rand()%100; *q=array[randomIndex]; } ///generates random prime numbers ///@param array - array of prime numbers ///@param t - time_t value to benerate random prime number /// @return uint64_t prime number void tGen(unsigned long int *array, time_t t,uint64_t *p,uint64_t *q){ srand(t); int randomIndex =rand()%100; *p=array[randomIndex]; randomIndex =rand()%100; *q=array[randomIndex]; } ///generates key file name with .pvt at the end ///@param user - character array to store the generated file name ///@param keyname - char pointer for the keyname void makePvtFileName(char user[],const char* keyname){ strcpy(user,keyname); strcat(user,".pvt"); } ///generates key file name with .pub at the end ///@param user - character array to store the generated file name ///@param keyname - char pointer for the keyname void makePubFileName(char user[],const char* keyname){ strcpy(user,keyname); strcat(user,".pub"); } /// output a note message to stderr, standard error. /// Use when the program has an incomplete command line. /// @param argc number of command line arguments /// @param argv array of values of command line argument /// @return int EXIT-SUCCESS if successful completiion or EXIT _ERROR for for error. int main(int argc, char * argv[]) { if(argc >=1){ int opt; int seed; time_t t=0; int a =0; char keyname[513]; if(argc == 1){ usage("missing test count\n"); usage("usage: mirsa_genkeys [-hv] [-k keyname] [-s seed]\n"); exit( EXIT_FAILURE ); } while((opt=getopt(argc,argv,"hvk:s:"))!= -1){ switch (opt){ case 'h': usage("\nusage: mirsa_genkeys [-hv] [-k keyname] [-s seed]\n"); return (EXIT_SUCCESS); break; case 'v': mr_verbose(1); break; case 'k': if(optarg != NULL){ strcpy(keyname,optarg); } else{ } break; case 's': if(optarg){ if(isdigit(*optarg)){ seed =atoi(optarg); a +=1; } else{ error("error: invalid seed value"); printf(" '%s'.\n",optarg); usage("usage: mirsa_genkeys [-hv] [-k keyname] [-s seed]\n"); return (EXIT_FAILURE); break; } } break; case '?': if(optopt =='k'){ usage("usage: mirsa_genkeys [-hv] [-k keyname] [-s seed]\n"); return (EXIT_FAILURE); } if(optopt == 's'){ usage("usage: mirsa_genkeys [-hv] [-k keyname] [-s seed]\n"); return (EXIT_FAILURE); } break; default: printf("missing test count"); usage("usage: mirsa_genkeys [-hv] [-k keyname] [-s seed]\n"); exit( EXIT_FAILURE ); } } for(; optind<argc;optind++){ error("error: extra argument: "); printf("'%s'.\n",argv[optind]); usage("usage: mirsa_genkeys [-hv] [-k keyname] [-s seed]\n"); return(EXIT_FAILURE); } unsigned long int *array = readFile(); uint64_t p=0; uint64_t q=0; int result =0; if(a>0){ seedGen(array,seed,&p,&q); if(p ==q){ seedGen(array,seed,&p,&q); } result = mr_make_keys(p,q,keyname); for(int i =0; i<3; i++){ if(result==99){ seedGen(array,seed,&p,&q); result = mr_make_keys(p,q,keyname); if(i ==2){ fprintf(stderr,"error: mr_make_keys: overflow. no keyset for <%lu, %lu>.\n",p, q); break; } } else{ break; } } } else{ tGen(array,t,&p,&q); if(p ==q){ tGen(array,t,&p,&q); } result = mr_make_keys(p,q,keyname); for(int i =0; i<3; i++){ if(result==99){ tGen(array,t,&p,&q); result = mr_make_keys(p,q,keyname); if(i ==2){ fprintf(stderr,"error: mr_make_keys: overflow. no keyset for <%lu, %lu>.\n",p, q); break; } } else{ break; } } } if(array!=NULL){ free(array); } char publickey[strlen(keyname)+5]; char privatekey[strlen(keyname)+5]; makePubFileName(publickey,keyname); makePvtFileName(privatekey,keyname); key_t *publicKey; key_t *privateKey; if(result){ publicKey = mr_read_keyfile(publickey); privateKey =mr_read_keyfile(privatekey); } else{ fprintf(stderr,"error: mr_make_keys: failed to generate keyset.\n"); } if(publicKey !=NULL){ free(publicKey); } if(publicKey !=NULL){ free(privateKey); } return (EXIT_SUCCESS); } else{ return (EXIT_FAILURE); } }
C
#include <stdio.h> #include <stdlib.h> #define SIZE 1024*1024*300 int main(void) { int temp1, temp2; int *arr = (int *)malloc((SIZE)*sizeof(int)); int i = SIZE; temp1 = clock(); for (; i > 0; --i) { arr[i] = i; } temp2 = clock(); printf("elapsed = %d\n", temp2-temp1); }
C
/******************************************************************************* * Copyright (C) 2020 Dale Alleshouse (AKA Hideous Humpback Freak) * dale@alleshouse.net https://hideoushumpbackfreak.com/ * * This file is subject to the terms and conditions defined in the 'LICENSE' * file, which is part of this source code package. ******************************************************************************/ #include "selection_sort.h" #include <stdbool.h> #include <string.h> #include "sort_instrumentation.h" static void Swap(const size_t kSize, void* x, void* y) { char n[kSize]; INSTRUMENTED_MEMCPY(n, x, kSize, kSize); INSTRUMENTED_MEMCPY(x, y, kSize, kSize); INSTRUMENTED_MEMCPY(y, n, kSize, kSize); } ResultCode SelectionSort(const size_t n, const size_t size, void* arr, const sort_strategy comparator) { if (arr == NULL || comparator == NULL) return kNullParameter; if (n == 0 || size == 0) return kArgumentOutOfRange; for (size_t i = 0; i < n - 1; i++) { size_t lowest_index = i; for (size_t j = i + 1; j < n; j++) { void* jth = (char*)arr + (j * size); void* lowest = (char*)arr + (lowest_index * size); int result = comparator(jth, lowest); if (result < 0) lowest_index = j; } if (i != lowest_index) { void* ith = (char*)arr + (i * size); void* lowest = (char*)arr + (lowest_index * size); Swap(size, ith, lowest); } } return 0; }
C
#include "syscall.h" void printhex(int a); int main(int argc, char *argv[]) { char *temp; int i; enableInterrupts(); printString("Printing arguments:\n\r"); temp = "argc: 0\n\r"; temp[6] += argc; printString(temp); temp = "argv[0]: "; for (i = 0; i < argc; i++) { temp[5] = 0x30 + i; printString(temp); printString(argv[i]); printString("\n\r"); } // printhex(&argv); // for (argc = 0; argc < 0xe5; argc++) { // printhex(*((char*)(&argc) + argc)); // printString(" "); // printhex((char*)(&argc) + argc); // getKeypress(&temp); // printString("\n\r"); // } terminate(); } void printhex(int a) { char arr[5]; int temp; temp = (a & 0xf000) >> 12; if(temp > 9) { temp = temp - 9 + 0x10; } arr[0] = 0x30 + temp; temp = (a & 0xf00) >> 8; if(temp > 9) { temp = temp - 9 + 0x10; } arr[1] = 0x30 + temp; temp = (a & 0xf0) >> 4; if(temp > 9) { temp = temp - 9 + 0x10; } arr[2] = 0x30 + temp; temp = (a & 0xf); if(temp > 9) { temp = temp - 9 + 0x10; } arr[3] = 0x30 + temp; arr[4] = 0; printString(arr); }
C
#define _CRT_SECURE_NO_WARNINGS 1 //#include<stdio.h> // ////int fib(int x)//ʹõݹЧʹڵʱӦȡ ѭķʽ ////{ //// if(x==1||x==2) //// return 1; //// else //// return fib(x-1)+fib(x-2); ////} //int fib(int n) //{ // int a = 1; // int b = 1; // int c = 1; // while(n>2) // { // c = a+b; // a = b; // b = c; // n--;//Ҫѭֹ // } // return c; //} // //int main() //{ // int x = 0; // int ret = 0; // printf("Please input a num:\n"); // scanf("%d",&x); // ret = fib(x); // printf("fib(%d)=%d\n",x,ret); // return 0; // //TDD //}
C
/* Дефинирайте пойнтер и опитайте да отпечатате стойността му на конзолата (%р) с printf. Какво се визуализира? */ #include <stdio.h> int main(){ int * pi; printf("%p\n", pi); // prints the address of the pointer itself return 0; }
C
#include <stdbool.h> #include <stdio.h> #include <stdlib.h> #include "binary_tree.h" binary_tree* new_binary_tree() { // Allocate memory for a new binary tree binary_tree* t = (binary_tree*) malloc(sizeof(binary_tree)); t->size = 0; return t; } node* new_node() { node* n = (node*) malloc(sizeof(node)); n->val = 0; return n; } void binary_tree_add(binary_tree *t, int i) { // TODO } void binary_tree_remove(binary_tree *t, int i) { // TODO } bool binary_tree_contains(binary_tree *t, int i) { // TODO return false; } int binary_tree_size(binary_tree *t) { // TODO return 0; } void print_node(node *n) { printf("( "); if (n->left != NULL) { print_node(n->left); } printf("%d ", n->val); if (n->right != NULL) { print_node(n->right); } printf(" )"); } void binary_tree_print(binary_tree *t) { if (t->root != NULL) { print_node(t->root); } } void free_binary_tree(binary_tree *t) { // TODO }
C
/****************************************************************************** * Filename: ts_length.c * Created on: Mar 8, 2010 * Author: jeremiah * Description: 打印TS各PID的时间长度 * ******************************************************************************/ #include <stdio.h> #include <stdint.h> #define TS_SYNC_BYTE 0x47 #define TS_PACKET_SIZE 188 typedef struct { unsigned pid; double clock_begin; double clock_end; } pid_t; pid_t pid_array[8191]; // 裤子说一个ts最多有8191个pid。那就建立一个8191的数组。 unsigned char buf[TS_PACKET_SIZE]; void get_length(unsigned char* pkt); void store_pid(unsigned pid, double clock); int main(int argc, char **argv) { if (argc < 2) { fprintf(stderr, "please use %s <file_name>/n", argv[0]); return 1; } FILE *fp = fopen(argv[1], "rb"); if (!fp) { perror("fopen"); return 1; } fseek(fp, 0, SEEK_END); int size = ftell(fp); rewind(fp); printf("file size %v \n",size); while (size > 0) { int read_size = fread(buf, 1, sizeof(buf), fp); /*每次读取188*/ printf("read %d every time \n",read_size); size -= read_size; get_length(buf); } int i; for (i = 0; i < 8191; i++) { if (pid_array[i].pid != 0) { printf("PID:0x%x length:%fs/n", pid_array[i].pid, pid_array[i].clock_end - pid_array[i].clock_begin); } else { break; } } return 0; } void get_length(unsigned char* pkt) { // Sanity check: Make sure we start with the sync byte: if (pkt[0] != TS_SYNC_BYTE) { fprintf(stderr, "Missing sync byte! \n"); return; } // If this packet doesn't contain a PCR, then we're not interested in it: uint8_t const adaptation_field_control = (pkt[3] & 0x30) >> 4; if (adaptation_field_control != 2 && adaptation_field_control != 3) { printf("this packet adaptation_field_control err \n"); return; } // there's no adaptation_field uint8_t const adaptation_field_length = pkt[4]; if (adaptation_field_length == 0) { printf("this packet has no adaptation_field_length \n"); return; } // no PCR uint8_t const pcr_flag = pkt[5] & 0x10; if (pcr_flag == 0) { printf("this packet has no pcr \n"); return; } // yes, we get a pcr uint32_t pcr_base_high = (pkt[6] << 24) | (pkt[7] << 16) | (pkt[8] << 8) | pkt[9]; printf("yes ,we got a pcr %d",pcr_base_high); // caculate the clock double clock = pcr_base_high / 45000.0; if ((pkt[10] & 0x80)) { clock += 1 / 90000.0; // add in low-bit (if set) } unsigned short pcr_extra = ((pkt[10] & 0x01) << 8) | pkt[11]; clock += pcr_extra / 27000000.0; unsigned pid = ((pkt[1] & 0x1F) << 8) | pkt[2]; printf("we got a pid %ld and clock %d \n",pid,clock); store_pid(pid, clock); } void store_pid(unsigned pid, double clock) { int i; for (i = 0; i < 8191; i++) { if (pid == pid_array[i].pid) { break; } } if (i == 8191) { for (i = 0; i < 8191; i++) { if (pid_array[i].pid == 0) { break; } } pid_array[i].pid = pid; pid_array[i].clock_begin = clock; } else { pid_array[i].clock_end = clock; } }
C
#include <stdio.h> #include <stdlib.h> #include <string.h> #include "skip.h" #define MAX_SIZE 3 #define MAX2 2 void skip(char *x, int m, char *y, int n) { int i, j; List ptr, z[ASIZE]; printf("skip start\n"); memset(z, 0, ASIZE * sizeof(List)); for (i = 0; i < m; i++) { ptr = malloc(sizeof(struct _cell)); if (ptr == NULL) { fprintf(stderr, "malloc failed\n"); exit(EXIT_FAILURE); } ptr->element = i; ptr->next = z[x[i]]; z[x[i]] = ptr; } /* searching */ for (j = m - 1; j < n; j += m) for (ptr = z[y[j]]; ptr != NULL; ptr = ptr->next) if (memcmp(x, y + j - ptr->element, m) == 0) printf("%d\n", j - ptr->element); printf("skip end\n"); } int main() { char s[] = "hello world"; char c[] = "wor"; skip(c, sizeof(c)-1, s, sizeof(s)-1); return 0; }
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* hash_table_api.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: cseguier <cseguier@student.42.fr> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2020/02/26 01:35:26 by cseguier #+# #+# */ /* Updated: 2020/03/06 06:08:09 by cseguier ### ########.fr */ /* */ /* ************************************************************************** */ #include "../includes/hash_table.h" static void free_content(char **content) { free(*content); *content = NULL; } static void free_node(t_ht **node) { free(*node); *node = NULL; } static void delete_list(t_ht **collision_list) { t_ht *node; t_ht *node_to_free; char *to_free; node = *collision_list; node_to_free = NULL; to_free = NULL; while (node) { to_free = node->room_name; node_to_free = node; node = node->next; if (to_free) free_content(&to_free); if (node_to_free) free_node(&node_to_free); } *collision_list = NULL; } int hash_table_delete(t_hthandle *t_hthandler) { int size; int i; char *to_free; t_ht *collision_list; i = -1; size = t_hthandler->capacity * 100; collision_list = NULL; while (++i < size) { to_free = t_hthandler->hash_table[i].room_name; collision_list = t_hthandler->hash_table[i].next; if (to_free) free_content(&to_free); if (collision_list) delete_list(&collision_list); } free(t_hthandler->hash_table); return (1); } /* ** Get the data from the hashtable ** {Input} : Take the control structure, the key of the item ** And the string to get in case of collision ** {Return} : the string if everything went well ** And NULL if shit goes wrong */ t_ht *hash_table_get(t_hthandle *t_hthandler, char *to_get) { t_ht *hash_table; t_ht *store; size_t key; store = NULL; key = ht_hash(to_get) % t_hthandler->modulo; hash_table = &t_hthandler->hash_table[key]; if (hash_table->key == -1) return (NULL); if (ht_find_match_store(hash_table, to_get, &store)) return (store); return (NULL); }
C
#include <stdio.h> #include<limits.h> int main() { int i, j, a, n, k[20]; scanf("%d", &n); for (i = 0; i < n; i++) { scanf("%d", &k[i]); } for (i = 0; i < n; i++) { for (j = i + 1; j < n; j++) { if (k[i] > k[j]) a = k[i]; k[i] = k[j]; k[j] = a; if (k[i] == k[j]) k[j] == INT_MIN; } } printf("%d",k[j]); return 0; }
C
#include <stdio.h> #include <stdlib.h> void swap(int *, int *); int main(int argc, char *argv[]) { int a = 10, b = 20; printf ("main()主函式呼叫swap()函式前,a位址的內容(%x)=%d\n", &a, a); printf ("main()主函式呼叫swap()函式前,b位址的內容(%x)=%d\n", &b, b); swap(&a, &b); printf ("回main()後,a位址的內容(%x)=%d\n", &a, a); printf ("回main()後,b位址的內容(%x)=%d\n", &b, b); return 0; } void swap(int *x, int *y){ int temp; printf ("進入swap()函式交換前,x位址的內容(%x)=%d\n", x, *x); printf ("進入swap()函式交換前,y位址的內容(%x)=%d\n\n", y, *y); temp = *x; *x = *y; *y = temp; printf ("進入swap()函式內交換後,x位址的內容(%x)=%d\n", x, *x); printf ("進入swap()函式內交換後,y位址的內容(%x)=%d\n", y, *y); }
C
#include<stdio.h> #include<conio.h> int main() { int n,i,a[100]; for(i=0;i<10;i++) { scanf("%d",&a[i]); } n=a[0]; for(i=0;i<10;i++) { if(a[i]>n) n=a[i]; } printf("%d is greatest",n); getch(); return 0; }
C
#include <stdio.h> #include <stdlib.h> //ʵ #define MAXSIZE 100 typedef int ElemType; typedef int Status; typedef struct SNode { ElemType Data[MAXSIZE]; int Top ; }*Stack; //ѹջ void Push(Stack PtrS,ElemType item) { if(PtrS->Top == MAXSIZE - 1) { printf("ջ\n"); return ; } else { PtrS->Data[++(PtrS->Top)] = item; return; } } //ջ ElemType Pop(Stack PtrS) { if(PtrS->Top == -1) { printf("ջ"); return -1; } else { return (PtrS->Data[PtrS->Top--]); } } int main() { int n ,i; struct SNode S; Stack pS = &S ; pS->Top = -1; printf("һ \n"); scanf("%d" ,&n); Push(pS,n); printf("һ \n"); scanf("%d" ,&n); printf("ջ\n"); Push(pS,n); for(i = 0; i <= pS->Top ; i++) printf("%d\t",pS->Data[i]); printf("\n"); printf("ջ\n"); Pop(pS); for(i = 0; i <= pS->Top ; i++) printf("%d\t",pS->Data[i]); printf("\n"); return 0; }
C
#define NULL ((void*)0) typedef unsigned long size_t; // Customize by platform. typedef long intptr_t; typedef unsigned long uintptr_t; typedef long scalar_t__; // Either arithmetic or pointer type. /* By default, we understand bool (as a convenience). */ typedef int bool; #define false 0 #define true 1 /* Forward declarations */ /* Type definitions */ struct stat {int dummy; } ; typedef int /*<<< orphan*/ pathbuf ; typedef int /*<<< orphan*/ int64 ; /* Variables and functions */ scalar_t__ ENOENT ; int /*<<< orphan*/ ERROR ; int MAXPGPATH ; int /*<<< orphan*/ NIL ; char* TABLESPACE_VERSION_DIRECTORY ; int /*<<< orphan*/ _tarWriteHeader (char*,int /*<<< orphan*/ *,struct stat*,int) ; int /*<<< orphan*/ ereport (int /*<<< orphan*/ ,int /*<<< orphan*/ ) ; int /*<<< orphan*/ errcode_for_file_access () ; int /*<<< orphan*/ errmsg (char*,char*) ; scalar_t__ errno ; scalar_t__ lstat (char*,struct stat*) ; scalar_t__ sendDir (char*,int /*<<< orphan*/ ,int,int /*<<< orphan*/ ,int) ; int /*<<< orphan*/ snprintf (char*,int,char*,char*,char*) ; int /*<<< orphan*/ strlen (char*) ; int64 sendTablespace(char *path, bool sizeonly) { int64 size; char pathbuf[MAXPGPATH]; struct stat statbuf; /* * 'path' points to the tablespace location, but we only want to include * the version directory in it that belongs to us. */ snprintf(pathbuf, sizeof(pathbuf), "%s/%s", path, TABLESPACE_VERSION_DIRECTORY); /* * Store a directory entry in the tar file so we get the permissions * right. */ if (lstat(pathbuf, &statbuf) != 0) { if (errno != ENOENT) ereport(ERROR, (errcode_for_file_access(), errmsg("could not stat file or directory \"%s\": %m", pathbuf))); /* If the tablespace went away while scanning, it's no error. */ return 0; } size = _tarWriteHeader(TABLESPACE_VERSION_DIRECTORY, NULL, &statbuf, sizeonly); /* Send all the files in the tablespace version directory */ size += sendDir(pathbuf, strlen(path), sizeonly, NIL, true); return size; }
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* printf_conv.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: gmayweat <gmayweat@42.fr> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2020/12/18 23:30:14 by gmayweat #+# #+# */ /* Updated: 2021/01/18 19:34:21 by gmayweat ### ########.fr */ /* */ /* ************************************************************************** */ #include "libftprintf.h" ssize_t ft_putchar(t_prarg *s_box) { char c; ssize_t n; n = 0; if (!s_box->width) s_box->width = 1; if (s_box->conv == 'c') c = va_arg(s_box->args, int); else c = '%'; if (c == '%' && s_box->zero) n += ft_printnch(s_box->width - 1, '0', &s_box->width); if (!s_box->minus) n += ft_printnch(s_box->width - 1, ' ', &s_box->width); n += write(1, &c, 1); if (s_box->minus) n += ft_printnch(s_box->width - 1, ' ', 0); return (n); } ssize_t ft_putstr(t_prarg *s_box) { ssize_t n; char *s; n = 0; s = va_arg(s_box->args, char*); if (!s) s = "(null)\0"; else if (!s[0]) s = "\0"; if (!s_box->is_acc || s_box->acc > (ssize_t)ft_strlen(s)) s_box->acc = ft_strlen(s); if (!s_box->minus) n += ft_printnch(s_box->width - s_box->acc, ' ', &s_box->width); n += write(1, s, s_box->acc); if (s_box->minus) n += ft_printnch(s_box->width - s_box->acc, ' ', 0); return (n); } ssize_t ft_putint(t_prarg *s_box) { ssize_t n; char *s; s = ft_itoa(va_arg(s_box->args, int)); if (s_box->bonf) s = ft_bonusflags(&s, s_box); if (s_box->bonf || s[0] == '-') n = ft_printnegnbr(s, s_box); else n = ft_printposnbr(s, s_box); free(s); return (n); } ssize_t ft_putuint(t_prarg *s_box) { ssize_t n; char *s; if (s_box->conv == 'u') s = ft_itoa(va_arg(s_box->args, unsigned int)); else s = ft_dextohex(va_arg(s_box->args, unsigned int), s_box->conv); if (s_box->bonf) s = ft_bonusflags(&s, s_box); if (s_box->bonf) n = ft_printnegnbr(s, s_box); else n = ft_printposnbr(s, s_box); free(s); return (n); } ssize_t ft_putpoint(t_prarg *s_box) { char *s; ssize_t n; n = 0; s = ft_dextohex(va_arg(s_box->args, unsigned long int), 'x'); if (s_box->is_acc && !s_box->acc && s[0] == '0') { free(s); s = ft_calloc(1, sizeof(char)); } if (!s_box->minus) n += ft_printnch(s_box->width - ft_strlen(s) - 2, ' ', &s_box->width); n += write(1, "0x", 2); s_box->width -= 2 + ft_strlen(s); n += write(1, s, ft_strlen(s)); if (s_box->minus) n += ft_printnch(s_box->width, ' ', &s_box->width); free(s); return (n); }
C
#include <stdio.h> #define hasNulByte(x) ((x - 0x01010101) & ~x & 0x80808080) #define SW (sizeof (int) / sizeof (char)) int xstrlen (const char *s) { const char *p; int d; p = s - 1; do { p++; if ((((int) p) & (SW - 1)) == 0) { do { d = *((int *) p); p += SW; } while (!hasNulByte (d)); p -= SW; } } while (*p != 0); return p - s; } int main(int argc, char** argv){ if (argc==1) return 1; printf("len:%d\n",xstrlen(argv[1])); return 0; }
C
/* * Simple app to read/write into a custom IP in PL via /dev/mem physical memory * interface ( Based on Kjans Tsotnep's app ) * To compile for arm: make ARCH=arm CROSS_COMPILE=arm-linux-gnueabihf- */ #include <stdio.h> #include <stdlib.h> //standard lib #include <unistd.h> //to get pagesize #include <fcntl.h> //file control: open #include <sys/mman.h> //to use mmap int main(int argc, char *argv[]) { /* References: http://man7.org/linux/man-pages/man2/mmap.2.html http://man7.org/linux/man-pages/man4/mem.4.html http://linux.die.net/man/3/sysconf http://man7.org/linux/man-pages/man2/open.2.html http://man7.org/linux/man-pages/man2/getpagesize.2.html http://stackoverflow.com/questions/3023909/what-is-the-trick-in-paddress-page-size-1-to-get-the-pages-base-address http://www.slideshare.net/vitlic/linux-memory */ printf("\nYury Malyshev\n"); if (argc < 3) { printf("\n"); printf("Usage: ./devmemdriver\n"); printf(" or: ./devmemdriver MEM_ADDR r\n"); printf(" or: ./devmemdriver MEM_ADDR w VALUE\n"); printf("If executed without arguments, these usage instructions will be displayed.\n"); printf("Valid arguments are:\n"); printf(" MEM_ADDR This argument, stored into argv[1], specifies the memory\n"); printf(" address into/from which the command will be executed.\n"); printf(" This argument can be provided either as a decimal or\n"); printf(" hexadecimal value.\n"); printf(" r or w This argument, stored into argv[2], specifies if data\n"); printf(" should be read (r) or written (w) from/into the specified\n"); printf(" memory address.\n"); printf(" VALUE In the case of a writing command, this argument, stored\n"); printf(" into argv[2], specifies the value to be stored into the\n"); printf(" specified memory address.\n"); printf("Execution examples:\n"); printf(" ./devmemdriver\n"); printf(" ./devmemdriver 0x43C0000C r\n"); printf(" ./devmemdriver 0x43C00000 w 8\n"); printf(" ./devmemdriver 1136656384 w 8\n"); //0x43C00000 ??? printf("\n"); } else { // read address from the user input. (If input is in hexadecimal, it // converts it to decimal. unsigned address = strtoul(argv[1], NULL, 0); // read character if it's read or write char direction = *argv[2]; // read value to be written // ? int value = (direction == 'w') ? atoi(argv[3]) : 0; // open /dev/mem file int fd = open ("/dev/mem", O_RDWR); if (fd < 1) { perror(argv[0]); return -1; } // Can't read /dev/mem // get architecture specific page size unsigned pageSize = sysconf(_SC_PAGESIZE); // in this approach, the memory page offset must be considered for // accesing the registers unsigned offset = (address & (~(pageSize-1))); /* offset of the registers from the page/base address 0 - Reg 0 4 - Reg 1 8 - Reg 2 12 - Reg 3 */ unsigned registerOffset = address - offset; // pointer to the virtual address space, where physical memory will // be mapped void *ptr; /********************************************************************** * TASK 1: Write a SINGLE LINE COMMAND to map the physical memory * * into this program's virtual address space. Point to the * * starting address of the new mapping with the 'ptr' pointer * * (already declared above) * ********************************************************************** * HINT 0: We should let the kernel choose the virtual (page-aligned) * * address at which the mapping will be created. * * HINT 1: For this task, we should map an amount of Bytes according * * to all the registers of our IP * **********************************************************************/ // WRITE YOUR SINGLE LINE COMMAND IN HERE ////////////////////////////// //void *mmap(void *addr, size_t length, int prot, int flags, // int fd, off_t offset); ptr = mmap(NULL, sizeof(unsigned)*4/*0x0010000*/, (PROT_READ | PROT_WRITE), MAP_SHARED, fd, offset); //////////////////////////////////////////////////////////////////////// if (direction == 'r') { // reading value from device register value = *((unsigned *)(ptr + registerOffset)); printf("> From address 0x%08X, read value: %d\n", address, value); } else { /****************************************************************** * TASK 2: Write a SINGLE LINE COMMAND that into the specified * * register of our IP * ****************************************************************** * HINT 0: You can base your code on the syntax used for reading * ******************************************************************/ // WRITE YOUR SINGLE LINE COMMAND IN HERE ////////////////////////// *((unsigned *)(ptr + registerOffset)) = value; //////////////////////////////////////////////////////////////////// } // delete mapping munmap(ptr, pageSize); } return 0; }
C
#include <stdio.h> #include <stdlib.h> //Bài tập 20: Nhập tháng và hiển thị số ngày tương ứng //Yêu cầu bài tập C này là nhập một tháng bất kỳ trong năm và sau đó hiển thị số ngày trong tháng đó int main() { int thang; printf("nhap thang trong nam: "); scanf("%d",&thang); switch (thang) { case 1: case 3: case 5: case 7: case 8: case 10: case 12: { printf("thang co 31 ngay."); }break; case 4: case 6: case 9: case 11: { printf("thang co 30 ngay."); }break; case 2: { printf("thang co 28 ngay (29 ngay neu la nam nhuan)."); }break; } return 0; }
C
/* Chris Nutter * Austin Kim * * Programming Assignment 3 * CPSC 351-04 */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include <pthread.h> // mutex pthread_mutex_t mutex; // Linked list node typedef int value_t; typedef struct Node { value_t data; struct Node *next; } StackNode; // Stack function declarations void push (value_t v, StackNode **top); value_t pop (StackNode **top); int is_empty(StackNode *top); /* -------------------------------------------------------------------------- */ // packed argument for thread starters typedef struct { StackNode ** top; int thread_num; } Package; // assignment function decls void push_m (value_t v, StackNode **top, int thread_num); value_t pop_m (StackNode **top, int thread_num); void print_stack(StackNode * top); void write_row(int idx, char * action); void write_header(); void * testStack(void * arg); void handle_args(int, char **); // globals int NUM_THREADS = 200; int ITERATIONS = 500; static int testing = 0; FILE * csv; int main(int argc, char ** argv) { handle_args(argc, argv); StackNode *top = NULL; pthread_mutex_init(&mutex, NULL); pthread_t workers[NUM_THREADS]; pthread_attr_t attrs[NUM_THREADS]; if (testing == 1) { csv = fopen("log.csv", "w"); write_header(); } // create args Package * packages = (Package*) malloc(sizeof(Package) * NUM_THREADS); for (int i = 0; i < NUM_THREADS; i++) { packages[i].top = &top; packages[i].thread_num = i; } // create threads for (int i = 0; i < NUM_THREADS; i++) { pthread_attr_init(attrs + i); pthread_create(workers + i, attrs + i, testStack, &packages[i]); } // wait for threads for (int i = 0; i < NUM_THREADS; i++) { pthread_join(workers[i], NULL); } pthread_mutex_destroy(&mutex); if (testing == 1) fclose(csv); // cleanup args free(packages); return 0; } // Stack function definitions void push(value_t v, StackNode **top) { StackNode * new_node = malloc(sizeof(StackNode)); new_node->data = v; pthread_mutex_lock(&mutex); new_node->next = *top; *top = new_node; pthread_mutex_unlock(&mutex); } void push_m(value_t v, StackNode **top, int thread_num) { StackNode * new_node = malloc(sizeof(StackNode)); new_node->data = v; pthread_mutex_lock(&mutex); new_node->next = *top; *top = new_node; if (thread_num >= 0 && testing == 1) write_row(thread_num, "push"); pthread_mutex_unlock(&mutex); } value_t pop(StackNode **top) { pthread_mutex_lock(&mutex); if (is_empty(*top)) { printf("stack empty!\n"); pthread_mutex_unlock(&mutex); return (value_t)0; } value_t data = (*top)->data; StackNode * temp = *top; *top = (*top)->next; free(temp); pthread_mutex_unlock(&mutex); return data; } value_t pop_m(StackNode **top, int thread_num) { pthread_mutex_lock(&mutex); if (is_empty(*top)) { printf("stack empty!\n"); return (value_t)0; } value_t data = (*top)->data; StackNode * temp = *top; *top = (*top)->next; free(temp); if (thread_num >= 0 && testing == 1) write_row(thread_num, "POP"); pthread_mutex_unlock(&mutex); return data; } int is_empty(StackNode *top) { if (top == NULL) return 1; else return 0; } void print_stack(StackNode * top) { pthread_mutex_lock(&mutex); printf("Current stack: "); while (top != NULL) { printf("%d ", top->data); top = top->next; } printf("\n"); pthread_mutex_unlock(&mutex); } void * testStack(void * arg) { Package * packed = (Package *)arg; StackNode ** top = packed->top; int thread_num = packed->thread_num; for (value_t i = 0; i < ITERATIONS; i++) { if (testing == 1) { push_m(i, top, thread_num); pop_m(top, thread_num); push_m(i, top, thread_num); pop_m(top, thread_num); push_m(i, top, thread_num); pop_m(top, thread_num); } else { push(thread_num, top); pop(top); push(thread_num, top); pop(top); push(thread_num, top); pop(top); } if (testing == 1 && NUM_THREADS <= 10) { print_stack(*top); } } pthread_exit(0); } void write_row(int idx, char * action) { for (int i = 0; i < idx; i++) { fprintf(csv, ","); } fprintf(csv, "%s", action); for (int i = idx; i < NUM_THREADS - 1; i++) { fprintf(csv, ","); } fprintf(csv, "\n"); } void write_header() { fprintf(csv, "%s", "thread_0"); for (int i = 1; i < NUM_THREADS; i++) { fprintf(csv, ",thread_%d", i); } fprintf(csv, "\n"); } void handle_args(int argc, char ** argv) { if (argc > 2) { printf("%s: too many arguments\n", argv[0]); exit(1); } for (int i = 1; i < argc; i++) { if (strcmp(argv[i], "--help") == 0 || strcmp(argv[i], "-h") == 0) { printf("Usage: %s [OPTION]\n" "A thread-safe stack in action.\n" "Running '%s' WITHOUT '-d, --demo' will spawn 200 threads as per homework specs.\n\n" "Optional arguments:\n" " -d, --demo Run this program in demo mode with a small number of threads.\n" " This mode writes a timeline of events to 'log.csv' in the enclosing dir.\n" " -f, --force Run all 200 threads, 500 iterations, AND generate the 'log.csv' file.\n" " That's at least 120MB of pure text. PLEASE think twice before doing this.\n" " -n, --normal Run this program in normal mode (no 'log.csv'). This is the default behavior.\n" " -h, --help Display this help message\n", argv[0], argv[0]); exit(0); } else if (strcmp(argv[i], "--demo") == 0 || strcmp(argv[i], "-d") == 0) { testing = 1; NUM_THREADS = 10; ITERATIONS = 5; } else if (strcmp(argv[i], "--force") == 0 || strcmp(argv[i], "-f") == 0) { testing = 1; } else if (strcmp(argv[i], "--normal") == 0 || strcmp(argv[i], "-n") == 0) { // do nothing: default } else { printf("%s: unrecognized argument '%s'\n", argv[0], argv[i]); exit(1); } } }
C
#include <stdio.h> int main() { char as[] = "\\0\0"; int i = 0; do { switch(as[i++]) { printf("%d\n",sizeof(++i)); / /* This statement will never get executed because cases are actually jump labels like go to labels. So this line is skipped and we go directly to the appropriate case label. */ case '\\' : printf("A\n"); break; case 0 : printf("B\n"); break; default : printf("C\n"); break; } } while(i<3); return 0; }
C
/* ** get_args.c for minishell1 in /home/manass_j/rendu/PSU_2015_minishell1 ** ** Made by jonathan manassen ** Login <manass_j@epitech.net> ** ** Started on Fri Jan 15 13:01:06 2016 jonathan manassen ** Last update Sat Jun 4 17:36:34 2016 jonathan manassen */ #include <stdlib.h> #include "my.h" #include "./include/get_execute.h" int check_str_space(char *str, int i) { while (str[i] != '\0') { if (str[i] != ' ') return (0); i = i + 1; } return (1); } char **get_command_tab(char **exe, char *str, int k, int j) { int i; int l; i = 0; while (str[i]) { l = 0; if (check_str_space(str, i) == 1) return (exe); while (str[i++] == ' ') j = i; while (str[i] != ' ' && str[i] != '\0') i = i + 1; if ((exe[k] = malloc(sizeof(char*) * (i - j + 1))) == NULL) exit(0); while (j < i) exe[k][l++] = str[j++]; exe[k][l] = '\0'; k = k + 1; } return (exe); } char **get_command(char *str) { int i; int j; char **exe; i = -1; j = 0; if (str == NULL || str[0] == '\0') return (NULL); while (str[++i]) if (str[i] == ' ' && str[i + 1] != ' ' && str[i + 1] != '\0') j = j + 1; if (str[0] == ' ') j = j - 1; if ((exe = malloc(sizeof(char**) * (j + 2))) == NULL) exit(0); exe = get_command_tab(exe, str, 0, 0); exe[j + 1] = NULL; return (exe); } char **get_path_tab(char **path, char *str, int k, int j) { int i; int l; i = 0; while (str[i] && str[i] != '=') i = i + 1; while (str[i]) { l = 0; while (str[++i] && str[i] == ':'); j = i; while (str[i] != ':' && str[i] != '\0') i = i + 1; if (i != j) { ((path[k] = malloc(sizeof(char*) * (i - j + 1))) == NULL) ? exit(0) : 0; while (j < i) path[k][l++] = str[j++]; path[k][l] = '\0'; k = k + 1; } } path[k] = NULL; return (path); } char **get_path(char *str) { int i; int j; char **path; j = 0; i = -1; while (++i <= 5) if (str[i] == '\0') return (NULL); i = -1; while (str[++i]) if (str[i] == ':' && str[i + 1] != ':' && str[i + 1] != '\0') j = j + 1; if (str[5] == ':') j = j - 1; if ((path = malloc(sizeof(char**) * (j + 2))) == NULL) exit(0); path = get_path_tab(path, str, 0, 0); return (path); }
C
#include<stdio.h> #include<stdlib.h> int a(int n){ int i,f=0; if(n==2) return 1; for (i=2;i<n;i++){ f+=(n%i==0); } if(f==0) return 1; else return 0; } int main(){ int n; scanf("%d",&n); n++; while(a(n)!=1){ n++; } printf("%d",n); system("PAUSE"); return 0;}
C
#include <stdio.h> #include <stdlib.h> #include <conio.h> #include <windows.h> #include <math.h> void contur_1(double R1, double R2, double L, double C, double W); void contur_2(double R1, double R2, double L, double C, double W); void contur_3(double R1, double R2, double L, double C, double W); void contur_4(double R1, double R2, double L, double C, double W); double f1, f2, df; double R, R1, R2; double L, C; double F, W; struct Complex { double dod1, dod2 } X; int main() { printf("This program calculates complex resistance.\n"); getch(); do { system("cls"); int contur, counter; int m, n, ek; void (*p) (double, double, double, double, double); printf("Enter number of contour from 1 to 4.\n"); scanf("%d", &contur); if(getchar() != '\n') { printf("Error! Do not enter rational numbers or symbols.\n"); fflush(stdin); getch(); continue; } if(contur != 1 && contur != 2 && contur != 3 && contur != 4) { printf("Error! Enter numbers from 1 to 4.\n"); getch(); continue; } m = 0; while(m == 0) { printf("Enter first and second value of frequency (Hz) in range (0; 1000].\n"); scanf("%lf %lf", &f1, &f2); if(getchar() != '\n') { printf("Error! Do not enter symbols.\n"); fflush(stdin); continue; } if(f1 > f2) { printf("Error! First value shouldn't be more than second.\n"); continue; } if(f1<= 0 || f2 <= 0 || f1 > 1000 || f2 > 1000) { printf("Error! Value is out of range.\n"); continue; } if((f1 > 0 && f1 < 1e-6) ||(f1 > 0 && f1 < 1e-6) ) { printf("Error! Try again.\n"); getch();\ continue; } m++; } while(m == 1) { printf("Enter step of frequency's change.\n"); scanf("%lf", &df); if(getchar() != '\n') { printf("Error! Do not enter symbols.\n"); fflush(stdin); getch(); continue; } if(df <= 0) { printf("Error! Step should be more than zero.\n"); getch(); continue; } if(df > 0 && df < 1e-6) { printf("Error! Step should be more than 1-6\n"); getch(); continue; } m++; } while(m == 2) { ek = 0; if(contur == 1 || contur == 2) { printf("Enter first resistance(Om) in range (0; 1000].\n"); } else { printf("Enter first resistance (Om) in range (0; 1000].\n"); ek = 1; } scanf("%lf", &R1); if(getchar() != '\n') { printf("Error! Do not enter symbols.\n"); fflush(stdin); getch(); continue; } if(R1 > 1000 || R1 <= 0 ) { printf("Error! Value is out of range.\n"); continue; } if(R1 > 0 && R1 < 1e-6) { printf("Error! Value should be more than 1-6\n"); getch(); continue; } if(ek == 1) do { n = 0; printf("Enter second resistance(Om) in range (0; 1000].\n"); scanf("%lf", &R2); if(getchar() != '\n') { printf("Error! Do not enter symbols.\n"); fflush(stdin); getch(); continue; } if(R2 > 1000 || R2 <= 0 ) { printf("Error! Value is out of range.\n"); continue; } if(R1 > 0 && R1 < 1e-6) { printf("Error! Value should be more than 1-6\n"); getch(); continue; } n++; } while(n = 0); m++; } while(m == 3) { printf("Enter inductance (Gn) in range (0; 1000].\n"); scanf("%lf", &L); if(getchar() != '\n') { printf("Error! Do not enter symbols.\n"); fflush(stdin); getch(); continue; } if(L > 1000 || L <= 0 ) { printf("Error! Value is out of range.\n"); continue; } if(L > 0 && L < 1e-6) { printf("Error! Value should be more than 1-6\n"); getch(); continue; } m++; } while(m == 4) { printf("Enter capacity (mcF) in range (0; 1000].\n"); scanf("%lf", &C); if(getchar() != '\n') { printf("Error! Do not enter symbols.\n"); fflush(stdin); getch(); continue; } if(C > 1000 || C <= 0 ) { printf("Error! Value is out of range.\n"); continue; } if(C > 0 && C < 1e-6) { printf("Error! Value should be more than 1-6\n"); getch(); continue; } m++; } switch(contur) { case 1: p = contur_1; break; case 2: p = contur_2; break; case 3: p = contur_3; break; case 4: p = contur_4; break; } F = 1. / (2. * M_PI * sqrt(L * C)); W = 1 / sqrt(L * C); p(R1, R2, L, C, W); printf("_______________________________________________________________________________________________________"); printf("The resonant frequency: %g Complex resistance: %g + i*%g\n", F, X.dod1, X.dod2); printf("_______________________________________________________________________________________________________"); printf("\t\t\t\t\tComplex resistance\t\t\t\n"); printf("_______________________________________________________________________________________________________"); do { W = 2 * M_PI * f1; p(R1, R2, L, C, W); printf("%lf\t\t\t\t%g + i*%g\t\n", f1, X.dod1, X.dod2); f1 += df; counter++; if(counter%10==0) { printf("\n\n\t------Press any key to continue.------\n\n"); getch(); } } while(f1 <= f2); printf("_______________________________________________________________________________________________________"); getch(); system("cls"); printf("If you want to continue, please press any key, otherwise - press \"ESC\".\n"); } while(getch() != 27); } void contur_1(double R1, double R2, double L, double C, double W) { double a, b, c, d; a = L / C; b = -R1 / (W * C); c = R1; d = W * L - 1 / (W * C); X.dod1 = (a * c + b * d) / (pow(c, 2) + pow(d, 2)); X.dod2 = (b * c - a * d) / (pow(c, 2) + pow(d, 2)); } void contur_2 (double R1, double R2, double L, double C, double W) { double a, b, c, d; a = L /C; b = R1 / (W * C); c = R1; d = W * L - 1 / (W * C); X.dod1 = (a * c + b * d) / (pow(c, 2) + pow(d, 2)); X.dod2 = (b * c - a * d) / (pow(c, 2) + pow(d, 2)); } void contur_3 (double R1, double R2, double L, double C, double W) { double a, b, c, d; a = R1 * R2; b = R1 * (W * L - 1 / (W * C)); c = R1 + R2; d = W * L - 1 / (W * C); X.dod1 = (a * c + b * d) / (pow(c, 2) + pow(d, 2)); X.dod2 = (b * c - a * d) / (pow(c, 2) + pow(d, 2)); } void contur_4 (double R1, double R2, double L, double C, double W) { double a, b, c, d; a = R1 * R2 + L / C; b = (W * L * R1) - R2 / (W * C); c = R1 + R2; d = W * L - 1 / (W * C); X.dod1 = (a * c + b * d) / (pow(c, 2) + pow(d, 2)); X.dod2 = (b * c - a * d) / (pow(c, 2) + pow(d, 2)); }
C
#include <stdio.h> #include <stdlib.h> #include <time.h> #include <sys/types.h> #include <unistd.h> #include <signal.h> struct tms { clock_t tms_utime; /* user time */ clock_t tms_stime; /* system time */ clock_t tms_cutime; /* user time of children */ clock_t tms_cstime; /* system time of children */ }; int main() { time_t start; time_t end; pid_t processID; pid_t pProcessID; pid_t PID; int status; int child; struct tms before; struct tms after; times(&before); time(&start); printf("Start: %ld\n", start); PID = fork(); if(PID == 0) { //Child pProcessID = getppid(); processID = getpid(); printf("PPID: %d ", pProcessID); printf("PID: %d\n", processID); exit(0); } else if(PID >= 1) { //Parent child = waitpid(0, &status, WUNTRACED); pProcessID = getppid(); processID = getpid(); printf("PPID: %d ", pProcessID); printf("PID: %d ", processID); printf("CPID: %d ", child); printf("RETVAL: %d\n", status); } else { printf("Error"); } times(&after); int elapsedutime = (int)(after.tms_utime-before.tms_utime); int elapsedstime = (int)(after.tms_stime-before.tms_stime); int elapsedcutime = (int)(after.tms_cutime-before.tms_cutime); int elapsedcstime = (int)(after.tms_cstime-before.tms_cstime); printf("USER: %d,\t",elapsedutime); printf("SYS: %d\n",elapsedstime); printf("CSUSER: %d,\t",elapsedcutime); printf("CSYS: %d\n",elapsedcstime); time(&end); printf("STOP: %ld\n", end); return 0; }
C
/* * * CATDSP * * Opens the the sound card (ie. /dev/dsp) sets the sample rate and * sends audio out to STDOUT. * * Copyright (C) 2000 Timothy Pozar pozar@lns.com * * 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., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * * Patched up to catdsp+.c by drt@un.bewaff.net * * $Id: catdsp+.c,v 1.1 2001/07/10 20:47:33 robotnik Exp $ * */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include <fcntl.h> #include <sys/ioctl.h> /*#include <machine/soundcard.h>*/ #include <sys/soundcard.h> #include <errno.h> #define TRUE 1 #define FALSE 0 #define RATE 32000 void banner(); char *device=NULL; int main(int argc, char **argv) { int stereo = TRUE; int rate = RATE; long seconds = -1; int gotmask, len, test; int devfh; int i=0; char buf[BUFSIZ]; char c; while ((c=getopt(argc,argv,"d:r:msh")) != EOF) { switch(c) { case 'D': case 'd': device = optarg; break; case 'R': case 'r': rate = atoi(optarg); break; case 'M': case 'm': stereo = 0; break; case 'S': case 's': seconds = atoi(optarg); break; case 'H': case 'h': banner(); return 0; } } if (!device) device = "/dev/dsp"; if ((devfh = open(device, O_RDONLY)) == -1) { fprintf(stderr,"opening device %s: %s",device,strerror(errno)); return 1; } /* What formats does this device support? */ if(ioctl(devfh, SNDCTL_DSP_GETFMTS, &gotmask) == -1) { perror("get dsp mask"); return -1; } /* Set the number or channels (ie mono vs. stereo)... Always set stereo/mono first before sample rate. See http://www.4front-tech.com/pguide/audio.html for details. */ test = stereo; if(ioctl(devfh, SNDCTL_DSP_STEREO, &stereo) == -1) { perror("Tried to set dsp to mono or stereo"); exit(1); } if (stereo != test) { if(stereo) fprintf(stderr,"Tried to set dsp to mono but it only supports stereo.\n"); else fprintf(stderr,"Tried to set dsp to stereo but it only supports mono.\n"); exit(1); } /* Set the sample rate... */ test = rate; if(ioctl( devfh, SNDCTL_DSP_SPEED, &test) == -1){ perror("set sample rate"); exit(1); } if(rate != test){ printf("Could not set the sample rate to: \"%i\". \"%i\" was returned\n", rate, test); } /* read the device and copy to stdout (1) ... */ while((len = read(devfh, &buf, BUFSIZ))>0) { /* this is much to hackish - we should use SIGALRM */ i += len / ((1 + stereo) * 2); if(i >= rate) { i -= rate; seconds--; } if(seconds == 0) return 0; if(write(1, &buf, len) == -1) { perror("Trouble writing to STDOUT."); return -1; } } return 0; } void banner() { printf("catdsp: Set \"%s\" sample rate and stereo/mono mode,\n",device); printf(" and then read the device and send it to STDOUT.\n"); printf(" -d device Sets device name. Default is \"%s\".\n",device); printf(" -m Sets device to run in mono. Default is stereo.\n"); printf(" -r rate Sets device sample rate. Default is \"%d\"",RATE); printf(" -s S Reads just S seconds of audio, then quit\n"); return; }
C
/* query.h Header file for the query engine Project name: Tiny Search Engine Component name: Query This file contains functin declarations for query.c Primary Author: Kevin Farmer Date Created: 5/18/15 ======================================================================*/ #ifndef QUERY_H #define QUERY_H // ---------------- Prerequisites e.g., Requires "math.h" #include "../../util/tseutil.h" // ---------------- Constants // ---------------- Structures/Types // ---------------- Public Variables // ---------------- Prototypes/Macros /* *@index: a valid index, from indexFromFile() *@line: a search line *@dir: the directory where corresponding crawler files are located * *Takes in a query and displays links by relevance * */ int processQuery(HashTable *index, char *line, char *dir); /* *@line: the input to be checked * * Checks the line for invalid input * * Returns 1 if line is invalid, 0 otherwise */ int checkLine(const char *line); /* *@index: a valid index *@word: the word to find in the index * * Returns the given WordNode for a word, or NULL if non-existant */ WordNode * findWordNode(HashTable *index, char *word); /* *@index: creates an orList of WordNodes *@inputList: a list of words and OR operators * *Creates an orList from the input list by processing all of the and operators * *Returns a list of WordNodes that the OR operator must be performed on */ List * createOrList(HashTable *index, List *inputList); /* *@orList: a list of WordNodes that the OR operator must be performed on * * Processes the orList, creating a single combined list * * Returns a list of DocumentNodes for the given query */ List * processOrList(List *orList); /* *@node1: an existing WordNode *@node2: an existing WordNode * * Performs the AND operator on the two nodes * * Returns a single WordNode with a new DocumentNode List */ WordNode * processAND(WordNode *node1, WordNode *node2); /* *@list1: a List of DocumentNodes *@list2: a List of DocumentNodes * * Combines the two lists into a single list based on the OR operator * * Returns the combined list of DocumentNodes */ List * processOR(List *list1, List *list2); /* *@curWord: the WordNode to be copied * * Makes a copy of the given WordNode * * Returns a pointer to the newly made copy */ WordNode * copyWordNode(WordNode *curWord); /* *@docList: a List of DocumentNodes to be sorted * * Sorts the docList from low to high frequency */ void sortDocs(List *docList); /* *@docId: the id of the desired file *@dir: the directory the file is located in * * Retrieves the url from the given file * * Returns the found url, or NULL if an error occured */ char * getFileUrl(int docId, char *dir); #endif // QUERY_H
C
#include <stdio.h> #include <stdlib.h> int multiply ( int a, int b) { return (a*b); } void afficherlettre (char*prenom) { printf("coucou %s", prenom); int nb1= 2; int nb2= 3; int result= multiply (nb1, nb2); printf("%d,",result); }
C
#include <stdio.h> /* main() c, k state = out while c = getchar != EOF if state == in if c == * if k = getchar == / state = out remove c, k else remove c else if char == \ putchar c = getchar putchar continue else if char == / k = getchar if k == * remove c, k state = in else putchar */ void remove_char(int c); int main() { int c; int k; int state; state = 0; while ((c = getchar()) != EOF) { if (state == 1) { if (c == '*') { if ((k = getchar()) == '/') { state = 0; } remove_char(c); remove_char(k); } else { remove_char(c); } } else if (c == '\\') { putchar(c); c = getchar(); putchar(c); } else if (c == '/') { k = getchar(); if (k == '*') { remove_char(c); remove_char(k); state = 1; } } else { putchar(c); } } return 0; } void remove_char(int c) { printf(""); }
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 */ typedef struct TYPE_2__ TYPE_1__ ; /* Type definitions */ struct TYPE_2__ {char const* str; } ; struct attr_hash {int hashcode; TYPE_1__ u; struct attr_hash* next; } ; /* Variables and functions */ int RTL_HASH_SIZE ; int /*<<< orphan*/ attr_hash_add_string (int,char*) ; struct attr_hash** attr_hash_table ; int /*<<< orphan*/ hash_obstack ; int /*<<< orphan*/ memcpy (char*,char const*,int) ; char* obstack_alloc (int /*<<< orphan*/ ,int) ; int /*<<< orphan*/ strncmp (char const*,char const*,int) ; __attribute__((used)) static char * attr_string (const char *str, int len) { struct attr_hash *h; int hashcode; int i; char *new_str; /* Compute the hash code. */ hashcode = (len + 1) * 613 + (unsigned) str[0]; for (i = 1; i < len; i += 2) hashcode = ((hashcode * 613) + (unsigned) str[i]); if (hashcode < 0) hashcode = -hashcode; /* Search the table for the string. */ for (h = attr_hash_table[hashcode % RTL_HASH_SIZE]; h; h = h->next) if (h->hashcode == -hashcode && h->u.str[0] == str[0] && !strncmp (h->u.str, str, len)) return h->u.str; /* <-- return if found. */ /* Not found; create a permanent copy and add it to the hash table. */ new_str = obstack_alloc (hash_obstack, len + 1); memcpy (new_str, str, len); new_str[len] = '\0'; attr_hash_add_string (hashcode, new_str); return new_str; /* Return the new string. */ }
C
/* 1. Write a program which accept N number from user and increase by 1 if it is divisible by 3 and increase by 2 if it is divisible by 3 and 5. Input : 12 3 65 15 3 30 Output : 13 4 1 17 4 32 */ void Increase(int *, int); void Display(int *,int);
C
/** drive.c * * A simple program to drive the create using the keyboard. * * Author: Nathan Sprague * * * This file is part of COIL. * * COIL 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 3 of the License, or * (at your option) any later version. * * COIL 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 COIL. If not, see <http://www.gnu.org/licenses/>. * */ #include <createoi.h> #include <libIMU.h> #include <stdlib.h> #include <stdio.h> #include <curses.h> #include <math.h> #define MAX(a,b) (a > b? a : b) #define MIN(a,b) (a < b? a : b) int main(int argv, char* argc[]) { if (argv < 4) { fprintf(stderr, "Usage: drive /dev/ttyO0 /dev/ttyUSB0 heading\n"); exit(1); } int not_done = 1; float heading_cmd = atoi(argc[3]); float yaw = 0; float yaw_err = 0; float speed_cmd = 0; float speed_mag = 0; float turn_radius = 1; float Kp_yaw = 2; startOI_MT (argc[1]); startIMU_MT (argc[2]); yaw = getYaw(); //int tollerance = 2; //+-2 deg float yaw_count = 1.0; while(yaw == 0) {//wait for initialization usleep(1000); yaw = getYaw(); } while(not_done) { yaw = getYaw(); yaw_err = heading_cmd - yaw; //printf("Count : %.0f\n", yaw_count); printf("Yaw : %.2f\n", yaw); printf("Yaw Error: %.2f\n\n", yaw_err); speed_cmd = -Kp_yaw*yaw_err; speed_mag = speed_cmd; turn_radius = 1; if(speed_cmd < 0) { speed_mag = -1*speed_cmd; turn_radius = -1;} if (speed_mag > 100) { speed_mag = 100; } if (abs(yaw_err) < 0.5 ) { speed_mag = 0; turn_radius = 0; } drive(speed_mag,turn_radius); //printf("Speed Mag: %.2f\n", speed_mag); //printf("Turn Rad : %.2f\n\n", turn_radius); yaw_count = yaw_count + 1; usleep(250); } stopOI_MT(); stopIMU_MT(); }
C
/* ** EPITECH PROJECT, 2018 ** my_printf.c ** File description: ** Recode my_printf function (see man 3 printf) */ #include <stdarg.h> #include <stdlib.h> #include "my_printf.h" #include "my.h" #include "./utils/flags.h" #include "./handle_args/parse_redirect.h" int my_printf(char const *src, ...) { va_list args; int return_val = 0; size_t gflags = 0; va_start(args, src); for (int i = 0; src[i] != '\0'; i++) { if (src[i] == '%') return_val += handle_args(src, &i, args, &gflags); else return_val += my_putchar(src[i]); } va_end(args); return (compute_gflag(return_val, gflags)); }
C
#include "log.h" #include "structs.h" #include <psp2/kernel/clib.h> #define println(fmt, ...) sceClibPrintf(fmt"\n",##__VA_ARGS__) #define println_vec3(fmt, vec3) sceClibPrintf(fmt); log_Vec3(vec3); sceClibPrintf("\n") #define println_vec4(fmt, vec4) sceClibPrintf(fmt); log_Vec4(vec4); sceClibPrintf("\n") /** * @brief Prints the content of a memory range to the console * * @param start Start address * @param len Number of bytes to print */ void LogMemoryRange(void* start, size_t len) { if (start == NULL || !len) return; uint8_t* ptr = (uint8_t*)start; size_t qqwordsDumpNum = len / 32; //Number of quad-qwords (4 * 8-byte = 32-byte "words") to dump size_t remainingLen = len - (qqwordsDumpNum * 32); //Remaining amount of bytes sceClibPrintf("Going to dump %d bytes (expected %d) starting at address 0x%08X.\n", qqwordsDumpNum*32 + remainingLen, len, (uintptr_t)ptr); //First, print all qqwords size_t curOffset = 0; for (size_t i = 0; i < qqwordsDumpNum; i++, curOffset += 32){ sceClibPrintf("0x%08X : %02hhX%02hhX%02hhX%02hhX %02hhX%02hhX%02hhX%02hhX %02hhX%02hhX%02hhX%02hhX %02hhX%02hhX%02hhX%02hhX\n", (uintptr_t)&ptr[curOffset], ptr[curOffset], ptr[curOffset+1], ptr[curOffset+2], ptr[curOffset+3], ptr[curOffset+4], ptr[curOffset+5], ptr[curOffset+6], ptr[curOffset+7], ptr[curOffset+8], ptr[curOffset+9], ptr[curOffset+10], ptr[curOffset+11], ptr[curOffset+12], ptr[curOffset+13], ptr[curOffset+14], ptr[curOffset+15], ptr[curOffset+16], ptr[curOffset+17], ptr[curOffset+18], ptr[curOffset+19], ptr[curOffset+20], ptr[curOffset+21], ptr[curOffset+22], ptr[curOffset+23], ptr[curOffset+24], ptr[curOffset+25], ptr[curOffset+26], ptr[curOffset+27], ptr[curOffset+28], ptr[curOffset+29], ptr[curOffset+30], ptr[curOffset+31] ); } //Then, print the remaining bytes sceClibPrintf("0x%08X : ", (uintptr_t)&ptr[curOffset]); for (size_t i = 0; i < remainingLen; i++, curOffset++){ sceClibPrintf("%02hhX", ptr[curOffset + i]); if ((curOffset+1) % 4) sceClibPrintf(" "); } sceClibPrintf("\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 */ typedef struct TYPE_3__ TYPE_1__ ; /* Type definitions */ typedef int /*<<< orphan*/ git_index ; struct TYPE_3__ {size_t index; int /*<<< orphan*/ path; } ; /* Variables and functions */ unsigned int ARRAY_SIZE (TYPE_1__*) ; int /*<<< orphan*/ TEST_INDEX_PATH ; int /*<<< orphan*/ cl_assert (int) ; int /*<<< orphan*/ cl_git_pass (int /*<<< orphan*/ ) ; int /*<<< orphan*/ git_index_find (size_t*,int /*<<< orphan*/ *,int /*<<< orphan*/ ) ; int /*<<< orphan*/ git_index_free (int /*<<< orphan*/ *) ; int /*<<< orphan*/ git_index_open (int /*<<< orphan*/ **,int /*<<< orphan*/ ) ; TYPE_1__* test_entries ; void test_index_tests__find_in_existing(void) { git_index *index; unsigned int i; cl_git_pass(git_index_open(&index, TEST_INDEX_PATH)); for (i = 0; i < ARRAY_SIZE(test_entries); ++i) { size_t idx; cl_assert(!git_index_find(&idx, index, test_entries[i].path)); cl_assert(idx == test_entries[i].index); } git_index_free(index); }
C
/* * This file defines six functions that support the optional printing * of debugging messages: * printDebug: prints messages only when debugging is turned on * debug_on: turns debugging on * debug_off: turns debugging off * debug_restore: restores the previous debugging state, as it was * before the most recent call to debug_on or debug_off. * debug_is_on: returns 1 if debugging is on, 0 if it is off * override_debug_changes: deactivate future calls to debug_on, * debug_off, and debug_restore, freezing the * debugging state in its current state * * The file also defines a number of internal data values and helper * functions to support the six functions described above. */ #include <stdarg.h> #include <stdio.h> #include <stdlib.h> #include <memory.h> #include "printFuncs.h" /* Define the internal DEBUG variable shared by functions in this file. */ static const char DEBUG_DEFAULT_VALUE = 0; static char OVERRIDE_DEBUG_CHANGES = 0; static char DEBUG = 0; /* Not all compilers will accept DEBUG_DEFAULT_VALUE. */ /* Define the internal DEBUG stack and the functions that operate on it. */ static char * debugStack = NULL; static unsigned debugStackCapacity = 0; static unsigned debugStackNumEntries = 0; static void debug_push(void); static char debug_pop(void); static int resizeDebugStack (void); static const char * ERROR = "Error: cannot allocate space in memory.\n"; /** * void printDebug(const char * restrict_format, ...) * * This function prints a debugging message to standard output (stdout), * but only if debugging is currently turned on. Debugging can be * turned on and off using the debug_on(), debug_off(), and * debug_restore() functions. * * Parameters: * The parameters to printDebug are modeled on those to printf, * consisting of a format and various other arguments as specified * in the format. * * Output: * This function prints its output to standard output (stdout). * */ void printDebug(const char * restrict_format, ...) { if ( ! DEBUG ) return; /* The following code allows us to call printf with the variable * parameters that were passed to printDebug. */ va_list ap; va_start(ap, restrict_format); (void) vprintf(restrict_format, ap); va_end(ap); } /** * void debug_on(void) * * Turns debugging on. * */ void debug_on(void) { if ( ! OVERRIDE_DEBUG_CHANGES ) { debug_push(); DEBUG = 1; } } /** * void debug_off(void) * * Turns debugging off. * */ void debug_off(void) { if ( ! OVERRIDE_DEBUG_CHANGES ) { debug_push(); DEBUG = 0; } } /** * void debug_restore(void) * * Restores the DEBUG state to its previous value. Once the debugging * state has been restored to its initial state, additional calls to * <code>debug_restore()</code> will have no effect until * <code>debug_on()</code> or <code>debug_off()</code> is called again. * */ void debug_restore(void) { if ( ! OVERRIDE_DEBUG_CHANGES ) { DEBUG = debug_pop(); } } /** * int debug_is_on(void) * * Returns 1 if debugging is currently on, 0 if debugging is currently off. * */ int debug_is_on(void) { return DEBUG; } /** * void override_debug_changes(void) * * Overrides future attempts to change the debug state, freezing it to * its current state (whatever that is). * */ void override_debug_changes(void) { OVERRIDE_DEBUG_CHANGES = 1; } /** * void debug_push(void) * * Pushes the current debug state onto the stack. * */ static void debug_push(void) { if ( debugStack == NULL || debugStackNumEntries <= debugStackCapacity ) resizeDebugStack(); debugStack[debugStackNumEntries++] = DEBUG; } /** * void debug_pop(void) * * Pops and returns the most recent debug state from the stack. If * there was no value on the stack, returns the DEBUG_DEFAULT_VALUE. * */ static char debug_pop(void) { if ( debugStackNumEntries > 0 ) return debugStack[--debugStackNumEntries]; return DEBUG_DEFAULT_VALUE; } static int resizeDebugStack (void) /* Postcondition: debug stack now has the capacity to hold a * longer history of debug states. * Returns 1 if everything went OK; 0 if there was a memory * allocation error */ { int newSize; char * newStack; /* Handle initial case of new stack. */ if ( debugStack == NULL || debugStackCapacity == 0 ) { debugStackNumEntries = 0; newSize = 20; } else newSize = debugStackCapacity * 2; /* Create a new stack of the specified size. */ debugStackCapacity = newSize * sizeof(*newStack); if ((newStack = malloc (debugStackCapacity)) == NULL) { printError ("%s", ERROR); return 0; /* fatal error: couldn't allocate memory */ } /* Move contents of old stack to new stack; free old stack. */ if ( debugStack ) /* if there were entries */ { (void) memcpy (newStack, debugStack, debugStackNumEntries); free (debugStack); } /* The new debug stack is ready to use. */ debugStack = newStack; return 1; }
C
#include <stdint.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <search.h> typedef struct { int count; char* key; } Entry; typedef struct { intptr_t sz; intptr_t cap; Entry* entries; } VecEntry; int cmp_by_freq(const void* p, const void* q) { const Entry* x = p; const Entry* y = q; return x->count - y->count; } int table_init(VecEntry* v, int initial_capacity) { Entry* entries = malloc(initial_capacity * sizeof(Entry)); if (!entries) { fprintf(stderr, "table_init: Not memory\n"); return -1; } *v = (VecEntry){ .sz = 0, .cap = initial_capacity, .entries = entries }; int initial_htable_size = 1 + ((v->cap * 5) / 4); int error = hcreate(initial_htable_size) == 0; if (error) { fprintf(stderr, "table_init: hcreate error\n"); } return error; } Entry* table_get(const VecEntry* v, int i) { if (i >= v->sz) { return NULL; } return &v->entries[i]; } int table_duplicate(VecEntry* table) { table->cap *= 2; table->entries = realloc(table->entries, table->cap * sizeof(Entry)); if (!table->entries) { fprintf(stderr, "table_duplicate: mem error\n"); return -1; } hdestroy(); int error = hcreate(1+((table->cap * 5) / 4)) == 0; if (error) { fprintf(stderr, "table_duplicate: hcreate error\n"); return error; } ENTRY e; for (intptr_t i = 0; i < table->sz; ++i) { Entry* entry = table_get(table, i); if (!entry|| !entry->key) { fprintf(stderr, "table_duplicate: error entry not found\n"); return -1; } char* k = strdup(entry->key); if (!k) { fprintf(stderr, "table_duplicate: mem error\n"); return -1; } e = (ENTRY){ .key=k, .data=(void*)i} ; ENTRY* ep = hsearch(e, ENTER); if (!ep) { fprintf(stderr, "table_duplicate: hsearch error\n"); return -1; } } return 0; } int table_add_symbol(VecEntry* table, char* word) { intptr_t count = -1; char* w1 = strdup(word); if (!w1) { fprintf(stderr, "table_add_symbol: mem error\n"); return -1; } ENTRY e = { .key = w1, .data = (void*)count }; ENTRY* ep = hsearch(e, ENTER); if (!ep) { // unexpected, table size should be grater than htable size + 1 fprintf(stderr, "table is full and could not be duplicated.\n"); return -1; } intptr_t index = (intptr_t)ep->data; if (index < 0) { // new entry if (table->sz >= table->cap) { int error = table_duplicate(table); if (error) { fprintf(stderr, "table_add_symbol: error duplicating\n"); return error; } char* w2 = strdup(word); if (!w2) { fprintf(stderr, "table_add_symbol: mem error\n"); return -1; } e.key = w2; ep = hsearch(e, ENTER); if (!ep) { // unexpected, table size should be grater than htable size + 1 fprintf(stderr, "table is full and could not be duplicated.\n"); return -1; } } index = table->sz++; if (!ep) { fprintf(stderr, "WTH??\n"); exit(1); } ep->data = (void*)index; char* w3 = strdup(word); if (!w3) { fprintf(stderr, "table_add_symbol: mem error\n"); return -1; } table->entries[index] = (Entry){ .key = w3, .count = 1 }; } else { ++table->entries[index].count; free(w1); } return 0; } int count_words (VecEntry* symbols, char* filename) { FILE *fp; if ((fp = fopen(filename, "r"))) { unsigned long nlines = 0; char* line = NULL; size_t len = 0; ssize_t read; const char* delimiters = " \t\n"; while ((read = getline(&line, &len, fp)) != -1) { char* token = strtok(line, delimiters); while(token) { int error = table_add_symbol(symbols, token); if (error) { return error; } token = strtok(NULL, delimiters); } nlines++; } fclose(fp); } return fp == NULL; } int main (int argc, char ** argv) { if (argc < 2) printf("Uso: %s FILE [FILE ...]\n", argv[0]); // void* tree = NULL; const int initial_capacity = 30; VecEntry symbols; table_init(&symbols, initial_capacity); for (int i = 1; i < argc; i++) { char* fname = argv[i]; int error = count_words(&symbols, fname); if (error) { fprintf(stderr, "error counting words in %s\n", fname); return -1; } } hdestroy(); //qsort(symbols.entries, symbols.sz, sizeof(Entry), cmp_by_freq); for (int i = 0; i < symbols.sz; ++i) { Entry* e = table_get(&symbols, i); if (e) { printf("%s: %d\n", e->key, e->count); free(e->key); } } return 0; }
C
#include <stdio.h> #include <stdlib.h> #include <string.h> #include "ringbuffer.h" /*initializes the buffer, placing pointers to beginning of buffer*/ void init_buffer(struct buffer_type *b, unsigned char *buffer, int buffer_size){ b->head = buffer; b->tail = buffer; b->beginning = buffer; b->end = buffer + BUFFER_SIZE - 1; } /*refresh buffer*/ void empty_buffer(struct buffer_type *b){ b->tail=b->head; } /*check buffer status*/ int get_buffer_state(struct buffer_type *b, error_type *err){ int len = 0; unsigned char *tail = b->tail; if(b->head == b->tail-1||(b->head == b->end && b->tail == b->beginning)){ *err = BUFFER_FULL; len = BUFFER_SIZE -1; } else if(b->tail == b->head){ *err = EMPTY_BUFFER; len = 0; } else if(b->head > b->end || b->tail > b->end|| b->tail < b->beginning || b->head < b->beginning){ *err = POINTER_ERROR; len = -1; }else if (b->tail < b->end){ if(tail != b->head){ while(tail != b->head){ if(tail == b->end){ b->tail == b->beginning; } else{ tail++; } len++; *err = OK; } } } return len; } /*adding character to buffer *function will return * amount of character in buffer * -1 in error conditon, err for more info*/ int add_char_to_buffer(struct buffer_type *b, unsigned char c, error_type *err){ int num = get_buffer_state(b, err); //check buffer state if(*err==POINTER_ERROR || *err == BUFFER_OVER_FLOW || *err == BUFFER_FULL){ return -1; }else{ *(b->head)=c; if(b->head != b->end){ b->head++; } else{ b->head = b->beginning; } num++; return num; } } /*getting one character from buffer * function will return * character read from buffer * -1 - in error condition, err more info of error*/ char get_char_from_buffer(struct buffer_type *b, error_type *err){ *err = OK; unsigned char c = 0; int state = get_buffer_state(b, err); if(*err != EMPTY_BUFFER && *err != POINTER_ERROR){ if(b->tail + 1 <= b->head){ c = *b->tail; b->tail++; } else if(b->tail + 1 == b->end ){ c = *b->tail; b->tail = b->beginning; } else if(b->tail == b->head){ *err = EMPTY_BUFFER; c = -1; } }else{ c = -1; } return c; } /*list character from buffer*/ int print_buffer(struct buffer_type b, error_type *err){ int len = 0; if(*err!=EMPTY_BUFFER && *err!=POINTER_ERROR){ if(b.tail != b.head){ while(b.tail != b.head){ if(b.tail +1 == b.end){ b.tail = b.beginning; }else{ b.tail++; } len++; } } else if (b.tail == b.head){ *err = EMPTY_BUFFER; len = 0; } } else{ len=-1; } return len; }
C
// UCLA CS 111 Lab 1 command interface #include <stdbool.h> //#include "command-internals.h" typedef struct command *command_t; typedef struct command_stream *command_stream_t; /* Create a command stream from GETBYTE and ARG. A reader of the command stream will invoke GETBYTE (ARG) to get the next byte. GETBYTE will return the next input byte, or a negative number (setting errno) on failure. */ command_stream_t make_command_stream (int (*getbyte) (void *), void *arg); /* Read a command from STREAM; return it, or NULL on EOF. If there is an error, report the error and exit instead of returning. */ command_t read_command_stream (command_stream_t stream); /* Print a command to stdout, for debugging. */ void print_command (command_t); /* Execute a command. Use "time travel" if the flag is set. */ void execute_command (command_t, bool); void execute_command_stream (command_stream_t, bool); /* Return the exit status of a command, which must have previously been executed. Wait for the command, if it is not already finished. */ int command_status (command_t); //////////////////////////////////////////////////////////// // CHAR_STREAM //////////////////////////////////////////////////////////// typedef struct char_stream { char c, last; int (*get_next_byte) (void *); void *get_next_byte_argument; } *char_stream_t; // Returns the character currently looked at by a char_stream_t char char_stream_current(char_stream_t cst); // Initializes the stream by setting the initial char void char_stream_init (char_stream_t cst); // set the stream's char to the next character char char_stream_read(char_stream_t cst); //////////////////////////////////////////////////////////// // TOKENS //////////////////////////////////////////////////////////// typedef enum token_type { AND, OR, SEQ, PIPE, WORD, IN, OUT, OPEN_PAREN, CLOSE_PAREN, NEWLINE // && || ; | " " < > ( ) \n } token_type_t; typedef struct token { enum token_type type; char *string; struct token *next; } *token_t; typedef struct token_node { token_t token; struct token_node *next; } *token_node_t; typedef struct token_stream { token_node_t head, tail; } *token_stream_t; // Add a token to the token stream by making it the new tail void token_stream_add (token_stream_t, token_t); // Read a token from the stream and pop it from the head token_t token_stream_read (token_stream_t); // Read the head token without popping it token_t token_stream_current (token_stream_t); // Remove the head token and free it void token_stream_free_head (token_stream_t); // Free the memory of an arbitrary token void free_token (token_t); //////////////////////////////////////////////////////////// // LEXER //////////////////////////////////////////////////////////// // Check to see if a character is regular (non-special) bool is_regular_char(char); //Convert a char_stream into a stream of tokens token_stream_t char_stream_to_token_stream (char_stream_t); // Print out the tokens for testing void print_tokens(token_stream_t); //////////////////////////////////////////////////////////// // PARSER //////////////////////////////////////////////////////////// typedef struct command_node { command_t com; struct command_node *next; } *command_node_t; int precedence(token_type_t); command_t restructure(command_t); //Parsing helper functions: command_t parse_sequence_command(token_stream_t); command_t parse_andor_command(token_stream_t); command_t parse_pipe_command(token_stream_t); command_t parse_subshell_command(token_stream_t); command_t parse_simple_command(token_stream_t); void parse_file_redirection(token_stream_t, command_t); //NEED TO ADD STUFF HERE
C
/// Mostre na tela somente /// saida o valor resulta [0][0] = 21 #include <stdio.h> #include <stdlib.h> int main(void){ // executa e mostra na tela ///int i, j, tamanho, valorResultado[4][1]; int i,j, tamX, tamY, valorResultado[4][2]; tamX = sizeof(valorResultado[4][2]); tamY = 2; printf("%d \n", tamY); valorResultado[0][0] = 21; valorResultado[1][0] = 3; valorResultado[2][0] = 22; valorResultado[3][0] = 1; valorResultado[0][1] = 99; valorResultado[1][1] = 88; valorResultado[2][1] = 77; valorResultado[3][1] = 55; ///for(i=(tamanho-1);i>=0;i--){ ///printf("%d \n",valorResultado[i][2]); for(i=0;i<tamY;i++){ for(j=0;j<tamX;j++){ printf("valorResultado [%d][%d] = %d \n",i, j, valorResultado[j][i]); //printf("valor[%d]= %d \n",j,valor[i][1]); } } system("pause"); /// para o sistema return(0); /// enter }
C
#include <stdio.h> #include <string.h> #include <stdlib.h> int main (void) { char origen[45] = ".:hola:hello:xd"; char *dest = malloc(sizeof(char *)); char *ja = NULL; dest = strtok(origen, ":"); while (dest) { printf("%s\n", ""); printf("%p\n", dest); dest = strtok(NULL, ":"); } return 0; }
C
/* ======================================== * * Copyright YOUR COMPANY, THE YEAR * All Rights Reserved * UNPUBLISHED, LICENSED SOFTWARE. * * CONFIDENTIAL AND PROPRIETARY INFORMATION * WHICH IS THE PROPERTY OF your company. * * ======================================== */ #include "usbserialprotocol.h" #define RECV_OK 0 #define RECV_ER 1 #define RDY_MSG_RECV "READY" #define RDY_MSG_NORM "CARD_N" #define RDY_MSG_PROV "CARD_P" #define RDY_BAD "BAD" #define GO_MSG "GO" uint8 getValidByte() { uint8 retval = 0u; while(UART_SpiUartGetRxBufferSize() < 1); // wait for byte retval = UART_UartGetByte(); return retval; } uint8_t* getValidBytes(int size) { uint8_t retval[size]; for(int i = 0; i < size; i++){ while(UART_SpiUartGetRxBufferSize() < 1); // wait for byte retval[i] = UART_UartGetByte(); } return retval; } struct verificationPacket{ uint8_t[256] encryptedRandNum; uint8_t[256] signature; } struct onionPacket{ uint8_t[512] outerLayer; uint8_t[256] signature; } verificationPacket readVerify(){ verificationPacket result; result.encryptedRandNum = getValidBytes(256); result.signature = getValidBytes(256); return result } onionPacket readOnion(){ onionPacket result; result.outerLayer = getValidBytes(512); result.signature = getValidBytes(256); return result } int pushMessage(const uint8 data[], uint8 size) { int i; UART_UartPutChar(size); for (i = 0; i < size; i++) { UART_UartPutChar(data[i]); } return RECV_OK; } uint8 pullMessage(uint8 data[]) { int i, len; len = getValidByte(); for (i = 0; i < len; i++) { data[i] = getValidByte(); } return len; } /* * generic PSoC synchronization protocol: * * 1) ATM -> "READY" -> PSoC * 2) if bad: PSoC -> received bad message -> ATM; goto 1) * if good: PSoC -> PSoC name (prov/norm) -> ATM * 3) ATM -> "GO" -> PSoC * 4) if bad: goto 1) */ void syncConnection(int prov) { uint8 message[32]; // marco-polo with bank until connection is in sync do { pullMessage(message); // 1) if (strcmp((char*)message, RDY_MSG_RECV)) { pushMessage(message, strlen((char*)message)); // 2) bad strcpy((char*)message, RDY_BAD); } else if (prov) { pushMessage((uint8*)RDY_MSG_PROV, strlen(RDY_MSG_PROV)); // 2) good prov pullMessage(message); // 3) } else { pushMessage((uint8*)RDY_MSG_NORM, strlen(RDY_MSG_NORM)); // 2) good norm pullMessage(message); // 3 } } while (strcmp((char*)message, GO_MSG)); // 4) } /* [] END OF FILE */
C
#include "libmx.h" int mx_get_substr_index(const char *str, const char *sub) { char *res; int i; int j; if (!str || !sub) { return -2; } i = mx_strlen(str); res = mx_strstr(str, sub); if (res == NULL) return -1; j = i - mx_strlen(res); return j; }
C
#include<stdio.h> struct shape { double length; double width; }; int findPerimeter(struct shape R); int findArea(struct shape R); main() { struct shape z; printf("Enter length of rectangle: "); scanf("%lf",&z.length); printf("Enter area of rectangle: "); scanf("%lf",&z.width); printf(" Area of the rectangle: %d\n",findArea(z)); printf(" Perimeter of the rectangle: %d\n",findPerimeter(z)); } int findPerimeter(struct shape R) { return 2*(int)(R.length+R.width); } int findArea(struct shape R) { return (int)R.length*R.width; }
C
/* ** EPITECH PROJECT, 2018 ** my_showstr.c ** File description: ** simon-perraud */ #include "../../include/my.h" int my_showstr(char const *str, int lenght) { for (int i = 0; i < lenght; i++) { if (str[i] == 0) { write(1, "\\", 1); write(1, "0", 1); } else if (str[i] == 10) { write(1, "\\", 1); write(1, "n", 1); } else my_put_nbr(str[i], 1); write(1, " ", 1); } write(1, "\n", 1); return (0); }
C
#include "appheader.h" int main(int argc, char const *argv[]) { //system("sh readconfig.sh"); FILE * fp=popen("sh readconfig.sh","r"); if(fp==NULL) { perror("popen:"); exit(-1); } char buf[1024]; bzero(buf,sizeof(buf)); fread(buf,sizeof(buf)-1,1,fp); //printf("%s",buf); char *p=buf; int counter=0; while(*p!='\0') { if(*p==' ') { *p='\0'; counter++; } p++; } counter++; //printf("%d\n",counter); char**ipbuf=(char**)malloc(counter*sizeof(char*)); int i; for(i=0;i<counter;i++) { ipbuf[i]=(char*)malloc(20*sizeof(char)); //bzero(ipbuf[i],sizeof(ipbuf[i])); } p=buf; int len=strlen(p); i=0; while(len>0) { //printf("%s\n",p); strcpy(ipbuf[i],p); p=p+len+1; len=strlen(p); i++; } // printf("%s\n",ipbuf[0]); // printf("%s\n",ipbuf[1]); // printf("%s\n",ipbuf[2]); // printf("%s\n",ipbuf[3]); // printf("%s\n",ipbuf[4]); for(i=0;i<5;i++) { printf("%s\n",ipbuf[i]); } return 0; }
C
#include<stdio.h> #include<math.h> #include<string.h> #define size 100012000 char ch[size]; void seive() { int i,j,m,n,root; root=sqrt(size); memset(ch,'1',sizeof(ch)); ch[0]='0'; ch[1]='0'; for(i=2;i<=root;i++) { if(ch[i]=='1') {for(j=2;i*j<=size;j++) ch[i*j]='0'; } } } int main() { seive(); double i,j,a,b; while(scanf("%lf %lf",&a,&b)==2) { double m=0,n=0,k; int sum; double res,rek; for(i=a;i<=b;i++) { sum=(i*i)+i+41; if(ch[sum]=='1') m++; else n++; res=((m*100)/(m+n));} printf("%0.2lf\n",res); } return 0; }
C
/* SPDX-License-Identifier: 0BSD */ #ifndef MINIFLAC_PADDING_H #define MINIFLAC_PADDING_H #include <stdint.h> #include "common.h" #include "bitreader.h" /* a padding block is supposed to be all zero bytes so * there's not a point in reading but - but who knows, * maybe somebody decides to do something weird with * padding blocks and shove data in there? */ typedef struct miniflac_padding_s miniflac_padding_t; struct miniflac_padding_s { uint32_t len; /* length of data */ uint32_t pos; /* current byte */ }; /* note: len is set outside of padding block functions */ #ifdef __cplusplus extern "C" { #endif MINIFLAC_PRIVATE void miniflac_padding_init(miniflac_padding_t* padding); MINIFLAC_PRIVATE MINIFLAC_RESULT miniflac_padding_read_length(miniflac_padding_t* padding, miniflac_bitreader_t* br, uint32_t* length); MINIFLAC_PRIVATE MINIFLAC_RESULT miniflac_padding_read_data(miniflac_padding_t* padding, miniflac_bitreader_t* br, uint8_t* output, uint32_t length, uint32_t* outlen); #ifdef __cplusplus } #endif #endif
C
/* * Revision Control Information * * $Source: /users/pchong/CVS/sis/stamina/mimi/read_fsm.c,v $ * $Author: pchong $ * $Revision: 1.2 $ * $Date: 2005/03/08 01:07:23 $ * */ #include <stdio.h> #include "user.h" #include "util.h" #include "struct.h" #include "global.h" char *item[5]; void line_parser(); NLIST **hash_initial(); NLIST *install(); STATE *install_state(); static FILE *fp_temp; read_fsm(fp_input) FILE *fp_input; { register i; char line[MAXSTRLEN]; NLIST **state_hash; /* a hash table stores state name */ char pstate_name[50]; /* the name of present state */ char nstate_name[50]; /* the name of next state */ STATE *pstate_ptr; /* pointer to STATE structure */ STATE *nstate_ptr; /* pointer to STATE structure */ EDGE *edge_ptr; /* pointer to EDGE structure */ EDGE *search_edge; EDGE *p_star_ptr; int p_star = 0; /* flag indicating p_state is a star */ int n_star = 0; /* flag indicating n_state is a star */ static int edge_index = 0; /* a counter when saving edges */ static char buffer[] = "/tmp/STMXXXXXX"; int sfd; p_star_ptr=NIL(EDGE); /*** *** allocate memory for hash_table: "state_hash" with *** size of number of states. *** note that the hashsize = num_st. ***/ sfd = mkstemp(buffer); if(sfd == -1) { panic("cannot open temp file"); } fp_temp = fdopen(sfd, "w+"); unlink(buffer); /* write information to the file */ user.stat.reset = 0; while ( fgets(line, MAXSTRLEN, fp_input ) != NULL ) { fputs(line,fp_temp); line_parser(line); if ((item[0] == NULL ) || (item[0][0] == '#')) continue; /* ignore blank lines */ if (item[0][0] == '.') { switch (item[0][1]) { case 's': num_st = atoi(item[1]); if ( (state_hash = hash_initial(num_st)) == NIL(NLIST *) ) { panic("ALLOC hash"); } /*** *** allocate memory for **states, and **edges. ***/ if ( (states = ALLOC(STATE *, num_st)) == NIL(STATE *) ) { panic("ALLOC state"); } break; case 'r': if ((strcmp(item[1], "*") != 0) && (strcmp(item[1],"ANY") != 0)) { if (!(install_state(item[1],state_hash,num_st))) panic("install fail"); } user.stat.reset = 1; break; case 'p': num_product = atoi(item[1]); if ( (edges = ALLOC(EDGE *, num_product )) == NIL(EDGE *) ) { panic("ALLOC edge"); } break; case 'i': num_pi = atoi(item[1]); break; case 'o': num_po = atoi(item[1]); break; case 'e': item[0] = NULL; default: break; } if (item[0] == NULL) break; else continue; } (void) sprintf (pstate_name, "%s", item[1]); (void) sprintf (nstate_name, "%s", item[2]); /* * taking care of "stars": * a "*" either in the present state * or in the next state field will be * considered as a don't care state * on that transition edge. */ if ((strcmp(pstate_name, "*") != 0) && (strcmp(pstate_name,"ANY") != 0)) { pstate_ptr = install_state(pstate_name,state_hash,num_st); if ( pstate_ptr == NIL(STATE) ) { panic("failed to install a state."); } } else { p_star = 1; /* flag on */ } if ((strcmp(nstate_name, "*") != 0 ) && (strcmp(nstate_name,"ANY") != 0)) { nstate_ptr = install_state(nstate_name,state_hash,num_st); if ( nstate_ptr == NIL(STATE) ) { panic("failed to install a state"); } } else { n_star = 1; /* flag on */ } /*** *** allocate the memory for a EDGE. ***/ if ( (edge_ptr = ALLOC (EDGE, 1)) == NIL(EDGE) ) { panic("ALLOC edge"); } edge_ptr->next = NIL(EDGE); edges[edge_index] = edge_ptr; /* save the address of new edge*/ edge_index++; if (!(edge_ptr->input =ALLOC ( char, num_pi + 1 ))) { panic("ALLOC input"); } (void) strcpy (edge_ptr->input, item[0]); if (!(edge_ptr->output=ALLOC( char, num_po + 1))) { panic("ALLOC edge output"); } (void) strcpy (edge_ptr->output, item[3]); edge_ptr->n_star = n_star; edge_ptr->p_star = p_star; if ( p_star != 0 ) { /* p_state is a star on this edge */ edge_ptr->p_state = NIL(STATE); /* a null pointer */ p_star = 0; /* reset flag p_star to 0 */ if (p_star_ptr) { search_edge = p_star_ptr; while (search_edge->next) search_edge=search_edge->next; search_edge->next=edge_ptr; } else p_star_ptr = edge_ptr; /* I don't need this kind information */ } else { edge_ptr->p_state = pstate_ptr; if (pstate_ptr->edge != NIL(EDGE)) { search_edge = pstate_ptr->edge; while (search_edge->next != NIL(EDGE)) search_edge = search_edge->next; search_edge->next = edge_ptr; } else pstate_ptr->edge = edge_ptr; } if ( n_star !=0 ) { /* n_state is a star on this edge */ edge_ptr->n_state = NIL(STATE); /* a null pointer */ n_star = 0; /* reset flag n_star to 0 */ } else { edge_ptr->n_state = nstate_ptr; } } if (access_n_state() != num_st) { num_st=access_n_state(); /* (void) fprintf(stderr,"Incorrect .s statement %d\n",num_st); */ } /* for (i=0; i<num_st; i++) if (!states[i]->edge) printf("### Total redundant state\n"); */ /* Expand current state don't care */ while (p_star_ptr) { for (i=0; i<num_st; i++) { search_edge=states[i]->edge; if (!search_edge) { if (!(search_edge=ALLOC(EDGE,1))) panic("read_fsm2"); MEMCPY(search_edge,p_star_ptr,sizeof(EDGE)); search_edge->p_state=states[i]; search_edge->next = NIL(EDGE); } else { while (search_edge->next) search_edge=search_edge->next; if (!(search_edge->next=ALLOC(EDGE,1))) panic("read_fsm2"); MEMCPY(search_edge->next,p_star_ptr,sizeof(EDGE)); search_edge->next->p_state=states[i]; search_edge->next->next = NIL(EDGE); } } p_star_ptr=p_star_ptr->next; } #ifdef DEBUG (void) printf("XXXXXXXXXXXXXXXXXXXXXXX HASH XXXXXXXXXXXXXXXXXXXXXXX\n"); (void) hash_dump(state_hash, num_st); (void) printf("XXXXXXXXXXXXXXXXXXXXXXX HASH XXXXXXXXXXXXXXXXXXXXXXX\n"); #endif /*** *** dump the states. ***/ #ifdef DEBUG (void) printf("XXXXXXXXXXXXXXXXXXXXXXX STATE XXXXXXXXXXXXXXXXXXXXXXX\n"); (void) dump_states(); (void) printf("XXXXXXXXXXXXXXXXXXXXXXX STATE XXXXXXXXXXXXXXXXXXXXXXX\n"); #endif /*** *** dump the edges. ***/ #ifdef DEBUG (void) printf("XXXXXXXXXXXXXXXXXXXXXXX EDGE XXXXXXXXXXXXXXXXXXXXXXX\n"); (void) dump_edges(); (void) printf("XXXXXXXXXXXXXXXXXXXXXXX EDGE XXXXXXXXXXXXXXXXXXXXXXX\n"); #endif } /* * parse input line. */ void line_parser(line_buf) register char *line_buf; { register char ch; int count; count = 0; while (ch = *line_buf) { /* * Note that the value of return character '\n' is 10 * which is smaller than the value of space ' ',32, . * And note that 'x' is a charater, but "x" is a string * of single charater. * This note is only for my own reference. */ if (ch <= ' ') { line_buf++; continue; } item[count] = line_buf; count++; line_buf++; while ( (ch = *line_buf) && ch > ' ' ) line_buf++; if (ch != 0) { *line_buf = '\0'; line_buf++; } } item[count] = 0; } flushout() { char line[MAXSTRLEN]; FILE *out; if (user.oname) out = fopen(user.oname,"w"); else out = stdout; fflush(fp_temp); rewind(fp_temp); while (fgets(line,MAXSTRLEN,fp_temp) != NULL) { fprintf(out,"%s",line); } }
C
#include<stdio.h> #define TAM 10 void alimenta_matriz(int vet[TAM]){ for(int i=0;i<TAM; i++){ printf("Posicao %d: ", i+1); scanf("%d", &vet[i]); } } void main(){ int vet1[TAM], vet2[TAM], vet3[TAM]; printf("--Vetor 01--\n"); alimenta_matriz(vet1); printf("--Vetor 02--\n"); alimenta_matriz(vet2); printf("--Vetor Resultante--\n"); for(int i=0;i<TAM; i++){ vet3[i] = vet1[i]*vet2[i]; printf("[%d] * [%d] = %d\n", vet1[i], vet2[i], vet3[i]); } }
C
/* Name: Nabeeh Kandalaft Course: EGR 226 Date: September-15-2018 Project: LCD Header File File: LCD.h Description: This is a header file for the 4x16 LCD that contains C function declarations, macro definitions, and global variables to be shared between several source files. | MSP432 PINS | P4.0 -> LCD D4 P4.1 -> LCD D5 P4.2 -> LCD D6 P4.3 -> LCD D7 P4.4 -> LCD E P4.5 -> LCD RS */ #ifndef LCD_H_ #define LCD_H_ //#include "driverlib.h" //For use with driverlib. #include "msp.h" #include <stdint.h> #define EN BIT4 //Pin P4.4 on any PORT. #define RS BIT5 //Pin P4.5 on any PORT. #define DATA 0x0F //Pins P4.0-3 on any PORT. /* | Commands | */ #define CLEAR 0x01 /* | Functions | */ void SysTick_initialization(void); void delay_ms(volatile uint32_t ms_delay); void delay_us(volatile uint32_t us_delay); void lcdInit (); //Clear LCD. void lcdClear(); //Initialize LCD. void lcdTriggerEN(); //Trigger enable. void lcdWriteData(unsigned char data); //Send data (Characters). void lcdWriteCmd (unsigned char cmd); //Send commands. void lcdSetText(char * text, int x, int y); //Write string. void lcdSetInt (int val, int x, int y); //Write integer. void Door_Menu(); void Motor_Menu(); void Lights_Menu(); void Main_Menu(); #endif /* LCD_H_ */
C
// // CharType.h // wordseg // // Created by Windoze on 12-2-9. // Copyright (c) 2012 0d0a.com. All rights reserved. // #ifndef wordseg_CharType_h #define wordseg_CharType_h #include <unicode/uchar.h> typedef enum _CharType { CT_SEPERATOR, // Seperators, whitespaces, punctuations, anything consider as a word-break. CT_MARKER, // something like accent marks CT_NUMBER, CT_LATIN, CT_CJK, CT_UNKNOWN // Max } CharType; inline bool is_CJK(UChar32 c) { UBlockCode bc=ublock_getCode(c); return (u_charType(c)==U_OTHER_LETTER) && ( (bc==UBLOCK_CJK_UNIFIED_IDEOGRAPHS) || (bc==UBLOCK_CJK_UNIFIED_IDEOGRAPHS_EXTENSION_A) || (bc==UBLOCK_CJK_COMPATIBILITY_IDEOGRAPHS) || (bc==UBLOCK_CJK_UNIFIED_IDEOGRAPHS_EXTENSION_B) || (bc==UBLOCK_CJK_UNIFIED_IDEOGRAPHS_EXTENSION_C) || (bc==UBLOCK_CJK_UNIFIED_IDEOGRAPHS_EXTENSION_D) || (bc==UBLOCK_CJK_COMPATIBILITY_IDEOGRAPHS_SUPPLEMENT) ); } inline bool is_seperator(UChar32 c) { int8_t ct=u_charType(c); return (ct==U_SPACE_SEPARATOR) || (ct==U_LINE_SEPARATOR) || (ct==U_PARAGRAPH_SEPARATOR) || (ct==U_CONTROL_CHAR) || (ct==U_FORMAT_CHAR) || (ct==U_PRIVATE_USE_CHAR) || (ct==U_SURROGATE) || (ct==U_DASH_PUNCTUATION) || (ct==U_START_PUNCTUATION) || (ct==U_END_PUNCTUATION) || (ct==U_CONNECTOR_PUNCTUATION) || (ct==U_OTHER_PUNCTUATION) || (ct==U_MATH_SYMBOL) || (ct==U_CURRENCY_SYMBOL) || (ct==U_MODIFIER_SYMBOL) || (ct==U_OTHER_SYMBOL) || (ct==U_INITIAL_PUNCTUATION) || (ct==U_FINAL_PUNCTUATION); } inline bool is_number(UChar32 c) { int8_t ct=u_charType(c); return (ct==U_DECIMAL_DIGIT_NUMBER) || (ct==U_LETTER_NUMBER) || (ct==U_OTHER_NUMBER); } inline bool is_latin(UChar32 c) { UBlockCode bc=ublock_getCode(c); return ( (u_charType(c)==U_UPPERCASE_LETTER) || (u_charType(c)==U_LOWERCASE_LETTER) || (u_charType(c)==U_OTHER_LETTER) ) && ( (bc==UBLOCK_BASIC_LATIN) || (bc==UBLOCK_LATIN_1_SUPPLEMENT) || (bc==UBLOCK_LATIN_EXTENDED_A) || (bc==UBLOCK_LATIN_EXTENDED_B) ); } inline bool is_marker(UChar32 c) { int8_t ct=u_charType(c); return (ct==U_NON_SPACING_MARK) || (ct==U_ENCLOSING_MARK) || (ct==U_COMBINING_SPACING_MARK); } inline CharType get_char_type(UChar32 c) { if(is_latin(c)) return CT_LATIN; if(is_number(c)) return CT_NUMBER; if(is_seperator(c)) return CT_SEPERATOR; if(is_marker(c)) return CT_MARKER; if(is_CJK(c)) return CT_CJK; // Anything unknown consider as a seperator return CT_SEPERATOR; } #endif
C
#include <stdio.h> #include <stdlib.h> #include <unistd.h> /* Please read readme.txt for deeper understanding of how code works. *No dependencies Compiled using GNU GCC Compiler This is a Complete C program which has individual functions defined for all operations This is equivalent to a MIPS compiler which has branch not taken and stall logics This takes an input.txt file which should be in working directory location only********* and return an output.txt file in the same executable location. This will tells what is current working directory */ /*-------------------------------Global variables----------------------------------------------*/ static int loopValue=0; // This will give PC_NUM value of where NEXT: keyword is there so starts with 0 int countStalls=0,bnezTracker[3]={0},flag_tabs=0,branched_flag=0; static int numberOfCodeLines=1; // 1 because at EOF program will exit so adding last line by giving default value static int stallArray[20]={0}; int print_output[1000][1000]={{0,0}}; // Output array which is used for printing O/p in particular format static int row=0,coloumn=0; FILE *op; /*--------------------------------Structures definitions------------------------------------*/ typedef struct cycle_flag { int IF1_flag; int IF2_flag; int ID_flag; int EX_flag; int MEM1_flag; int MEM2_flag; int MEM3_flag; int WB_flag; }cycle_flag; // To check the status of the instruction pipeline this structure is needed typedef struct instr { int operation; int target_operand; int computed_value; int first_operand; int second_operand; }instr; // This is similar to OPCODE which i defined for this compiler /*------------------------------structure declarations-------------------------*/ cycle_flag test_cycle[50]={{0}}; instr instruction[50]={{0}}; instr decoded_instruction={0}; /*----------------------- All Function declarations---------------------------*/ /*-------------------------Instruction pipeline functions----------------------*/ void IF1(int program_counter[50][4],int registers[],int memorys[],int pc_num); void IF2(int program_counter[50][4],int registers[],int memorys[],int pc_num); void ID(int program_counter[50][4],int registers[],int memorys[],int pc_num); void EX(int program_counter[50][4],int registers[],int memorys[],int pc_num); void MEM1(int program_counter[50][4],int registers[],int memorys[],int pc_num); void MEM2(int program_counter[50][4],int registers[],int memorys[],int pc_num); void MEM3(int program_counter[50][4],int registers[],int memorys[],int pc_num); void WB(int program_counter[50][4],int registers[],int memorys[],int pc_num); /*-------------------------Input file reading functions------------------------*/ void register_values(int rep, int mep, int registers[],char *buffer); void memory_values(int mep, int cep, int memorys[],char *buffer); void code_read(int cep,int last, int program_counter[50][4], char *buffer, int pc_num); /*--------------------------To handle stall------------------------------------*/ int ifEqual(int pc_num); /*--------------------------To print Registers and memory values---------------*/ void print_registers(int registers[]); void print_memorys(int memorys[]); void print_PC(int program_counter[50][4]); /*--------------------------Functions to handle output file printing-----------*/ void print_output_function(); void print_tabs(int pc_num); void branch_tabs(int pc_num); /*------------Support functions for register, memory and code read-------------*/ int isAlpha(char *buffer, int position); int isNumber(char *buffer, int position); int isR(char *buffer, int position); int isHash(char *buffer, int position); int isBracket(char *buffer, int position); int cal_three_registers(int values[],int j); int cal_three_registers1(int values[],int j); int main(int argc, char *argv[]) { //local variables for main static char * buffer = 0; int i=0,k=0,exec_location=0,next_iter=1; char cwd[1024]; int pc_num=0; long int end_of_file=0; static int register_flag=0,memory_flag=0,code_flag=0, registers[32]={0}, memorys[999]={0},program_counter[500][4]={{0,0,0,0}}; int memory_end_position=0,register_end_position=0, code_end_position=0; long length; getcwd(cwd, sizeof(cwd)); printf("\n******Please place input.txt file in the following Current Working Directory location: \"%s\"******\n",cwd); printf("\nDid you have the input.txt file in the Current Working Directory?\nEnter\n 1-Yes\n 2-No"); scanf("%d",&exec_location); if(exec_location==1) { FILE *fp = fopen("input.txt","r"); op = fopen("output.txt","w"); // File read in to a character array for convenient processing using FILE* pointer if(fp) { printf("\nInput.txt opened successfully\n"); printf("processing...\n"); printf("\n******output.txt file is at: %s\\output.txt\n\n",cwd); fseek(fp,0L,SEEK_END); length = ftell(fp); fseek(fp,0,SEEK_SET); buffer = calloc(1,length+1); if(buffer) { fread(buffer,1,length,fp); } fclose(fp); } else { printf("Error in file opening, please keep input file in the same location where executable is\n"); return 0; } /*if (buffer!=NULL) // Used for debugging { printf("%s\n",buffer); }*/ //Flags to check if the file has Registers, memory and code keywords for(i=0;i<=length;i++){ if(buffer[i-2]=='E'&&buffer[i-1]=='R'&&buffer[i]=='S'){ register_flag=1; register_end_position=i+1; } if(buffer[i-2]=='O'&&buffer[i-1]=='R'&&buffer[i]=='Y'){ memory_flag=1; memory_end_position=i+2; } if(buffer[i-2]=='O'&&buffer[i-1]=='D'&&buffer[i]=='E'){ code_flag=1; code_end_position=i+2; } } end_of_file=length; if(memory_flag==1&&register_flag==1&&code_flag==1) { register_values(register_end_position,memory_end_position,registers,buffer); //Function to read input file into registers array memory_values(memory_end_position,code_end_position,memorys,buffer); //Function to read input file into memorys array code_read(code_end_position,end_of_file,program_counter,buffer,pc_num); //Function to read input file code to Program counter array in the format of opcode for(pc_num=0;pc_num<numberOfCodeLines;pc_num++) // Processing all code lines { if(program_counter[pc_num][0]!=0) //No operation's opcode is zero { if(flag_tabs>0){ // To check for any stalls and to include spaces helped for printing o/p for(i=0;i<2*flag_tabs;i++) { //printf("\ta"); print_output[row][coloumn]=12; coloumn++; } } int q=pc_num; if(branched_flag==0){ // To check if branching is done or not to know that is the relative position to print the next instruction for(q=0;q<pc_num;q++) { //printf("\t"); print_output[row][coloumn]=12; coloumn++; } }else { for(q=0;q<bnezTracker[1]+4+k;q++) { //printf("\td"); print_output[row][coloumn]=12; coloumn++; } k++; } if(program_counter[pc_num][0]==9&&registers[program_counter[pc_num][1]]!=0) // 9=BNEZ operation opcode { // Flag is 1 if branching take place IF1(program_counter,registers,memorys,pc_num); if(branched_flag==1&&bnezTracker[2]<bnezTracker[1]){ row++; }else{ row++;coloumn=0; } branched_flag=1; for(q=0;q<pc_num+1;q++) { // printf("\t"); print_output[row][coloumn]=12; coloumn++; } branch_tabs(pc_num); //Help function to print half executed instructions which are flushed due to "branch taken" pc_num=program_counter[pc_num][3]-1; // To jump to instruction after successful branching } else { IF1(program_counter,registers,memorys,pc_num); // To execute instructions for failed branching and normal instructions } row++; coloumn=0; } } } else { printf("File doesn't have one or more REGISTERS or MEMORY or CODE Keywords"); } print_output_function(); // Function which takes care of printing into output.txt file print_registers(registers); // To print final register values into output file print_memorys(memorys); // To print final memory values into output file fclose(fp); fclose(op); /*printf("Do you want to run program for another iteration? Then\n\n"); printf("Please backup output.txt file generated as re-running this program erases contents in old file\n"); printf("\nIf you still want to continue\nEnter\n 1-Yes\n 2-No\n\n"); scanf("%d",&next_iter);*/ }//End IF which checks whether the file is in exec location or not /*else{ printf("Please place input.txt at %s\n",cwd); return 0; }*/ printf("Thank you...Have a great day\n"); return 0; } //End main /*----------------------------Instruction pipeline logic which has branch forwarding using instr struct's---------------------*/ void IF1(int program_counter[500][4],int registers[],int memorys[],int pc_num) { test_cycle[pc_num].IF1_flag=1; //printf("I%d-IF1\t",pc_num); print_output[row][coloumn]=1; coloumn++; IF2(program_counter,registers,memorys,pc_num); } void IF2(int program_counter[500][4],int registers[],int memorys[],int pc_num) { int i=0; if(test_cycle[pc_num].IF1_flag==1&&pc_num<numberOfCodeLines) { instruction[pc_num].operation=program_counter[pc_num][0]; instruction[pc_num].target_operand=program_counter[pc_num][1]; instruction[pc_num].first_operand=program_counter[pc_num][2]; instruction[pc_num].second_operand=program_counter[pc_num][3]; test_cycle[pc_num].IF2_flag = 1; for(i=0;i<20;i++){ if(pc_num-2==stallArray[i]&&pc_num-2!=0){ //printf("stall\tstall\t"); print_output[row][coloumn]=99; coloumn++; print_output[row][coloumn]=99; coloumn++; flag_tabs++; break; } } //printf("I%d-IF2\t",pc_num); print_output[row][coloumn]=2; coloumn++; ID(program_counter,registers,memorys,pc_num); //printf("\n"); } } void ID(int program_counter[500][4],int registers[],int memorys[],int pc_num) { int i=0; if(test_cycle[pc_num].IF2_flag==1) { test_cycle[pc_num].ID_flag = 1; for(i=0;i<20;i++){ if(pc_num-1==stallArray[i]&&pc_num-1!=0){ //printf("stall\tstall\t"); print_output[row][coloumn]=99; coloumn++; print_output[row][coloumn]=99; coloumn++; break; } } //printf("I%d-ID\t",pc_num); print_output[row][coloumn]=3; coloumn++; decoded_instruction.operation=instruction[pc_num].operation; decoded_instruction.target_operand=instruction[pc_num].target_operand; switch(instruction[pc_num].operation) { case 1: { //printf("load- displacement "); decoded_instruction.first_operand=instruction[pc_num].first_operand; decoded_instruction.second_operand=registers[instruction[pc_num].second_operand]; break; } case 2: { //printf("load- Immediate "); decoded_instruction.first_operand=instruction[pc_num].first_operand; decoded_instruction.second_operand=instruction[pc_num].second_operand; break; } case 3: { //printf("Store- displacement "); decoded_instruction.first_operand=instruction[pc_num].first_operand; decoded_instruction.second_operand=registers[instruction[pc_num].second_operand]; break; } case 4: { // printf("Store- Immediate "); decoded_instruction.first_operand=instruction[pc_num].first_operand; decoded_instruction.second_operand=instruction[pc_num].second_operand; break; } case 5: { //printf("ADD reg "); decoded_instruction.first_operand=registers[instruction[pc_num].first_operand]; decoded_instruction.second_operand=registers[instruction[pc_num].second_operand]; break; } case 6: { //printf("ADD imm "); decoded_instruction.first_operand=registers[instruction[pc_num].first_operand]; decoded_instruction.second_operand=instruction[pc_num].second_operand; break; } case 7: { //printf("sub reg "); decoded_instruction.first_operand=registers[instruction[pc_num].first_operand]; decoded_instruction.second_operand=registers[instruction[pc_num].second_operand]; break; } case 8: { //printf("sub imm "); decoded_instruction.first_operand=registers[instruction[pc_num].first_operand]; decoded_instruction.second_operand=instruction[pc_num].second_operand; break; } }//end switch EX(program_counter,registers,memorys,pc_num); }//end if }//end ID void EX(int program_counter[500][4],int registers[],int memorys[],int pc_num) { if(test_cycle[pc_num].ID_flag==1) { test_cycle[pc_num].EX_flag=1; //printf("instruction[pc_num].operation:%d\n",instruction[pc_num].operation); int cat=ifEqual(pc_num); if(cat>0){ //printf("capt:%d",cat); stallArray[countStalls]=pc_num; countStalls++; //printf("stall\t"); //printf("stall\t"); print_output[row][coloumn]=99; coloumn++; print_output[row][coloumn]=99; coloumn++; } // printf("I%d-EX\t",pc_num); print_output[row][coloumn]=4; coloumn++; switch(instruction[pc_num].operation) { case 5: { //printf("DADD- Register addr mode "); instruction[pc_num].computed_value=decoded_instruction.first_operand+decoded_instruction.second_operand; break; // return instruction[pc_num].computed_value; } case 6: { // printf("DADD- IMM addr mode "); instruction[pc_num].computed_value=decoded_instruction.first_operand+decoded_instruction.second_operand; //return instruction[pc_num].computed_value; break; } case 7: { // printf("sub- Register addr mode "); instruction[pc_num].computed_value=decoded_instruction.first_operand-decoded_instruction.second_operand; // return instruction[pc_num].computed_value; break; } case 8: { //printf("sub- IMM addr mode "); instruction[pc_num].computed_value=decoded_instruction.first_operand-decoded_instruction.second_operand; //return instruction[pc_num].computed_value; break; } case 9: { if(registers[instruction[pc_num].target_operand]!=0) { //printf("***BNEZ "); bnezTracker[0]=1; // used to check if code has bnez bnezTracker[1]=pc_num; // to keep track of which line bnez triggered bnezTracker[2]=loopValue; // To where it needs to be branched //printf("I%d-MEM1\tI%d-MEM2\tI%d-MEM3\tI%d-WB",pc_num,pc_num,pc_num,pc_num); // pc_num=loopValue-1; //printf("PC num: %d ",pc_num); //printf("\n"); } break; } }//End Switch MEM1(program_counter,registers,memorys,pc_num); // return instruction[pc_num].computed_value; }//End IF } // End EX void MEM1(int program_counter[500][4],int registers[],int memorys[],int pc_num) { if(test_cycle[pc_num].EX_flag==1) { test_cycle[pc_num].MEM1_flag = 1; //printf("I%d-MEM1\t",pc_num); print_output[row][coloumn]=5; coloumn++; MEM2(program_counter,registers,memorys,pc_num); } } void MEM2(int program_counter[500][4],int registers[],int memorys[],int pc_num) { if(test_cycle[pc_num].MEM1_flag==1) { test_cycle[pc_num].MEM2_flag = 1; //printf("I%d-MEM2\t",pc_num); print_output[row][coloumn]=6; coloumn++; switch(instruction[pc_num].operation) { case 1: { //printf("load- displacement "); instruction[pc_num].computed_value=decoded_instruction.first_operand+decoded_instruction.second_operand; registers[decoded_instruction.target_operand]=memorys[instruction[pc_num].computed_value]; break; } case 2: { // printf("load- Immediate "); instruction[pc_num].computed_value=decoded_instruction.first_operand+decoded_instruction.second_operand; registers[decoded_instruction.target_operand]=memorys[instruction[pc_num].computed_value]; break; } case 3: { // printf("Store- displacement "); instruction[pc_num].computed_value=decoded_instruction.first_operand+decoded_instruction.second_operand; memorys[instruction[pc_num].computed_value]=registers[decoded_instruction.target_operand]; break; } case 4: { //printf("Store- Immediate "); instruction[pc_num].computed_value=decoded_instruction.first_operand+decoded_instruction.second_operand; memorys[instruction[pc_num].computed_value]=registers[decoded_instruction.target_operand]; break; } }//end switch MEM3(program_counter,registers,memorys,pc_num); }//end if }//end mem2 void MEM3(int program_counter[500][4],int registers[],int memorys[],int pc_num) { if(test_cycle[pc_num].MEM2_flag==1) { test_cycle[pc_num].MEM3_flag = 1; //printf("I%d-MEM3\t",pc_num); print_output[row][coloumn]=7; coloumn++; WB(program_counter,registers,memorys,pc_num); } } void WB(int program_counter[500][4],int registers[],int memorys[],int pc_num) { if(test_cycle[pc_num].MEM3_flag==1) { test_cycle[pc_num].WB_flag = 1; //printf("I%d-WB\t",pc_num); print_output[row][coloumn]=8; coloumn++; switch(instruction[pc_num].operation) { case 5: { //printf("DADD- Register addr mode "); registers[instruction[pc_num].target_operand]=instruction[pc_num].computed_value; break; } case 6: { //printf("DADD- IMM addr mode "); registers[instruction[pc_num].target_operand]=instruction[pc_num].computed_value; break; } case 7: { //printf("sub- Register addr mode "); registers[instruction[pc_num].target_operand]=instruction[pc_num].computed_value; break; } case 8: { //printf("sub- IMM addr mode "); registers[instruction[pc_num].target_operand]=instruction[pc_num].computed_value; break; } } //END Switch }//End IF }//END WB //-------------------------------------------------------------------------------------- // ----------------------------Function to detect stall--------------------------------- int ifEqual(int pc_num){ // Function to check if stall is necessary or not int flag=0; if(pc_num>0&&instruction[pc_num-1].operation<5&&instruction[pc_num].operation>4&&instruction[pc_num].operation<9) { //printf("--kbc %d",pc_num); if(instruction[pc_num-1].target_operand==instruction[pc_num].target_operand) { flag=1; } if(instruction[pc_num-1].target_operand==instruction[pc_num].first_operand) { flag=2; } if(instruction[pc_num-1].target_operand==instruction[pc_num].second_operand) { flag=3; } if(instruction[pc_num-1].second_operand==instruction[pc_num].target_operand) { flag=4; } if(instruction[pc_num-1].second_operand==instruction[pc_num].first_operand) { flag=5; } if(instruction[pc_num-1].second_operand==instruction[pc_num].second_operand) { flag=6; } }else if(pc_num>0&&instruction[pc_num-1].operation>0&&instruction[pc_num-1].operation<3&&instruction[pc_num].operation<5) { if(instruction[pc_num-1].target_operand==instruction[pc_num].target_operand) { flag=7; } if(instruction[pc_num-1].target_operand==instruction[pc_num].second_operand) { flag=8; } } else if(pc_num>0&&instruction[pc_num].operation==9&&instruction[pc_num-1].operation>4&&instruction[pc_num-1].operation<3){ if(instruction[pc_num-1].target_operand==instruction[pc_num].target_operand) { flag=9; } } return flag; } /* -------------------------------------------------------------------------------------------- **** Register Read***** -------------------------------------------------------------------------------------------- */ void register_values(int rep, int mep, int registers[],char *buffer){ // Function to read input to registers int values[200]={0},i=0,j=0,k=0, index=0, r_flag=0; while((rep)<mep-5) { if( (buffer[rep]=='R') ) { if((buffer[rep+2]==' ')){ index=buffer[rep+1]-'0'; i=rep+1; }else { index=(buffer[rep+1]-'0')*10+(buffer[rep+2]-'0'); i=rep+2; } while(buffer[i]!='\n') { if(((buffer[i]-'0')>=0)&&((buffer[i]-'0')<=9)&&(buffer[i]!='\n')) { // printf("%c\n",buffer[i]); values[j]=buffer[i]-'0'; // printf("values[%d]--%d\n",j,values[j]); j++; } i++; } registers[index]=cal_three_registers(values,j); //printf("index:%d,registers[index]=%d\n",index,registers[index]); // break; } rep++; } while(buffer[k]=='R') { k=i; if(buffer[k]=='R') { r_flag=1; // printf("flag:%d\n",r_flag); //break; } k++; } if(r_flag!=1){ return; } else{ rep=k; register_values(rep,mep,registers,buffer); } } //End register read /* -------------------------------------------------------------------------------------------- **** Memory Read***** -------------------------------------------------------------------------------------------- */ void memory_values(int mep, int cep, int memorys[],char *buffer) { int values[200]={0},i=0,j=0,k=0,index=0, m_flag=0; while((mep)<cep-5) { if( (buffer[mep]-'0')>=0&& (buffer[mep]-'0')<=9) //first digit encountered is MEP { if((buffer[mep+1]==' ')) { index=buffer[mep]-'0'; i=mep+1; }else if((buffer[mep+2]==' ')&&((buffer[mep+1]-'0')>=0)&&((buffer[mep+1]-'0')<=9)) { index=(buffer[mep]-'0')*10+(buffer[mep+1]-'0'); i=mep+2; }else if(buffer[mep+3]==' ') { index=(buffer[mep]-'0')*100+(buffer[mep+1]-'0')*10+(buffer[mep+2]-'0'); i=mep+3; } mep=i+1; while(buffer[i]!='\n') { if(((buffer[i]-'0')>=0)&&((buffer[i]-'0')<=9)&&(buffer[i]!='\n')) { values[j]=buffer[i]-'0'; j++; } i++; } mep=i; memorys[index]=cal_three_registers1(values,j); } mep++; } while((buffer[k]-'0')>=0&&((buffer[k]-'0')<=9)) { k=i; if((buffer[k]-'0')>=0&&((buffer[k]-'0')<=9)) { m_flag=1; } k++; } if(m_flag!=1){ return; } else{ mep=k; memory_values(mep,cep,memorys,buffer); } } // End Memory Read /* -------------------------------------------------------------------------------------------- **** Code Read***** -------------------------------------------------------------------------------------------- */ void code_read(int cep,int last, int program_counter[500][4], char *buffer, int pc_num) { // static int i=0; int j=0,immediateFlag=0,ifImmediate=0,addValue=0; int itterator=0,itterator1=0,countLines=0; //printf("\n\n--------------------------------------------------------------------------\n\n"); if(pc_num==0) //Logic to know which line does "loop:" exist { itterator=cep; while(buffer[itterator]) // To place the marker at the first alphabet after "CODE" keyword { if(isAlpha(buffer,itterator)) { break; } itterator++; } itterator1=itterator; while(buffer[itterator]) // check through the lines and when it encounters "loop:" while will be broke and will be updated to global variable { if(buffer[itterator]=='\n') { countLines++; } if(buffer[itterator]=='N'&&buffer[itterator+1]=='E'&&buffer[itterator+2]=='X'&&buffer[itterator+3]=='T'&&buffer[itterator+4]==':') { loopValue=countLines; break; } itterator++; } while(buffer[itterator1]) // to count number of code lines are there in input file, used to print PC { if(buffer[itterator1]=='\n') { numberOfCodeLines++; } itterator1++; } //printf("loop: line is at %d\n",loopValue); //printf("Number of code lines %d\n",numberOfCodeLines); } while(buffer[cep]) //Run through line by line using recursive calls { if(buffer[cep]=='B'&&buffer[cep+1]=='N'&&buffer[cep+2]=='E'&&buffer[cep+3]=='Z') { program_counter[pc_num][0]=9; while(buffer[cep]!='\n'&&buffer[cep]!='\0') { if(isR(buffer,cep)) { program_counter[pc_num][1]= isNumber(buffer,cep+1); //printf("pc[%d][%d]=%d\n",pc_num,j,program_counter[pc_num][j]); } cep++; } program_counter[pc_num][2]=pc_num; program_counter[pc_num][3]=loopValue; for(j=0;j<4;j++) { //printf("%d\t",program_counter[pc_num][j]); } pc_num++; code_read(cep+1,last,program_counter,buffer,pc_num); } //Bnez ends if(buffer[cep]=='D'&&buffer[cep+1]=='A'&&buffer[cep+2]=='D'&&buffer[cep+3]=='D') { // dadd((cep+5),buffer); //sending location of char after space //printf("DADD found\n"); immediateFlag=0; ifImmediate=cep; while(buffer[ifImmediate]!='\n'&&buffer[ifImmediate]!='\0') //Check immediate case { if(buffer[ifImmediate]=='#') { immediateFlag=1; //printf("found imm\n"); } ifImmediate++; } if(!immediateFlag) //if instruction is not immediate { program_counter[pc_num][0]=5; j=1; while(buffer[cep]!='\n'&&buffer[cep]!='\0') { if(isR(buffer,cep)) { program_counter[pc_num][j]= isNumber(buffer,cep+1); //printf("pc[%d][%d]=%d\n",pc_num,j,program_counter[pc_num][j]); j++; } cep++; } while(buffer[cep]!='\n') { cep++; } for(j=0;j<4;j++){ //printf("%d\t",program_counter[pc_num][j]); } pc_num++; code_read(cep+1,last,program_counter,buffer,pc_num); } if(immediateFlag) //if instruction is not immediate { program_counter[pc_num][0]=6; j=1; while(buffer[cep]!='\n'&&buffer[cep]!='\0') { if(isR(buffer,cep)||isHash(buffer,cep)) { program_counter[pc_num][j]= isNumber(buffer,cep+1); //printf("pc[%d][%d]=%d\n",pc_num,j,program_counter[pc_num][j]); j++; } cep++; } while(buffer[cep]!='\n') { cep++; } for(j=0;j<4;j++){ //printf("%d\t",program_counter[pc_num][j]); } pc_num++; code_read(cep+1,last,program_counter,buffer,pc_num); } break; } //DADD ends else if(buffer[cep]=='S'&&buffer[cep+1]=='U'&&buffer[cep+2]=='B') { //printf("sub found\n"); immediateFlag=0; ifImmediate=cep; while(buffer[ifImmediate]!='\n'&&buffer[ifImmediate]!='\0') //Check immediate case { if(buffer[ifImmediate]=='#') { immediateFlag=1; //printf("found imm\n"); } ifImmediate++; } if(!immediateFlag) //if instruction is not immediate { program_counter[pc_num][0]=7; j=1; while(buffer[cep]!='\n'&&buffer[cep]!='\0') { if(isR(buffer,cep)){ program_counter[pc_num][j]= isNumber(buffer,cep+1); //printf("pc[%d][%d]=%d\n",pc_num,j,program_counter[pc_num][j]); j++; } cep++; } /*program_counter[pc_num][1]= buffer[cep+6]-'0'; program_counter[pc_num][2]= buffer[cep+10]-'0'; program_counter[pc_num][3]= buffer[cep+14]-'0';*/ while(buffer[cep]!='\n') { cep++; } for(j=0;j<4;j++){ //printf("%d\t",program_counter[pc_num][j]); } pc_num++; code_read(cep+1,last,program_counter,buffer,pc_num); } else if(immediateFlag) //if instruction is not immediate { program_counter[pc_num][0]=8; j=1; while(buffer[cep]!='\n'&&buffer[cep]!='\0') { if(isR(buffer,cep)||isHash(buffer,cep)) { program_counter[pc_num][j]= isNumber(buffer,cep+1); //printf("pc[%d][%d]=%d\n",pc_num,j,program_counter[pc_num][j]); j++; } cep++; } while(buffer[cep]!='\n') { cep++; } for(j=0;j<4;j++){ //printf("%d\t",program_counter[pc_num][j]); } pc_num++; code_read(cep+1,last,program_counter,buffer,pc_num); } break; } //SUB ends else if(buffer[cep]=='S'&&buffer[cep+1]=='D') { //printf("sd found\n"); immediateFlag=0; ifImmediate=cep; while(buffer[ifImmediate]!='\n'&&buffer[ifImmediate]!='\0') //Check immediate case { if(buffer[ifImmediate]=='#') { immediateFlag=1; //printf("found imm\n"); } ifImmediate++; } if(!immediateFlag) //If instr not in immediate addressing mode it is in displacement mode { program_counter[pc_num][0]=3; j=1; addValue=cep+4; while(buffer[cep]!='\n'&&j<4&&buffer[cep]!='\0') { if(isR(buffer,cep)) { program_counter[pc_num][j]= isNumber(buffer,cep+1); //printf("pc[%d][%d]=%d\n",pc_num,j,program_counter[pc_num][j]); j=j+2; } cep++; } while(!isBracket(buffer,addValue)) { if(buffer[addValue]==' ') { program_counter[pc_num][2]=isNumber(buffer,addValue+1); //passing the value after space character } addValue++; } while(buffer[cep]!='\n') { cep++; } for(j=0;j<4;j++) { //printf("%d\t",program_counter[pc_num][j]); } pc_num++; code_read(cep+1,last,program_counter,buffer,pc_num); } else if(immediateFlag) //if instruction is immediate addressing mode { program_counter[pc_num][0]=4; j=1; while(buffer[cep]!='\n'&&buffer[cep]!='\0') { if(isR(buffer,cep)||isHash(buffer,cep)) { program_counter[pc_num][j]= isNumber(buffer,cep+1); //printf("pc[%d][%d]=%d\n",pc_num,j,program_counter[pc_num][j]); j=j+2; } cep++; } while(buffer[cep]!='\n') { cep++; } for(j=0;j<4;j++) { //printf("%d\t",program_counter[pc_num][j]); } pc_num++; code_read(cep+1,last,program_counter,buffer,pc_num); } break; } //SD ends else if(buffer[cep]=='L'&&buffer[cep+1]=='D') { //printf("LD found\n"); immediateFlag=0; ifImmediate=cep; while(buffer[ifImmediate]!='\n'&&buffer[ifImmediate]!='\0') //Check immediate case { if(buffer[ifImmediate]=='#') { immediateFlag=1; //printf("found imm\n"); } ifImmediate++; } if(!immediateFlag) //If instr not in immediate addressing mode it is in displacement mode { program_counter[pc_num][0]=1; j=1; addValue=cep+4; while(buffer[cep]!='\n'&&j<4&&buffer[cep]!='\0') { if(isR(buffer,cep)) { program_counter[pc_num][j]= isNumber(buffer,cep+1); //printf("pc[%d][%d]=%d\n",pc_num,j,program_counter[pc_num][j]); j=j+2; } cep++; } while(!isBracket(buffer,addValue)) { if(buffer[addValue]==' ') { program_counter[pc_num][2]=isNumber(buffer,addValue+1); //passing the value after space character } addValue++; } while(buffer[cep]!='\n') { cep++; } for(j=0;j<4;j++) { //printf("%d\t",program_counter[pc_num][j]); } pc_num++; code_read(cep+1,last,program_counter,buffer,pc_num); } else if(immediateFlag) //if instruction is immediate addressing mode { program_counter[pc_num][0]=2; j=1; while(buffer[cep]!='\n'&&buffer[cep]!='\0') { if(isR(buffer,cep)||isHash(buffer,cep)) { program_counter[pc_num][j]= isNumber(buffer,cep+1); //printf("pc[%d][%d]=%d\n",pc_num,j,program_counter[pc_num][j]); j=j+2; } cep++; } while(buffer[cep]!='\n') { cep++; } for(j=0;j<4;j++) { //printf("%d\t",program_counter[pc_num][j]); } pc_num++; code_read(cep+1,last,program_counter,buffer,pc_num); } break; } //End LD cep++; } // End Main While } // End Code read //----------------------------------------------------------------------------- /*------------------------------------Printing Arrays Logic-------------------------*/ void print_registers(int registers[]) { int i; fprintf(op,"\n\nREGISTERS\n"); for(i=0;i<32;i++) { if(registers[i]>0) { fprintf(op,"R%d %d\n",i,registers[i]); } } } void print_memorys(int memorys[]) { int i; fprintf(op,"\nMEMORY\n"); for(i=0;i<999;i++) { if(memorys[i]>0) { fprintf(op,"%d %d\n",i,memorys[i]); } } } void print_PC(int program_counter[500][4]) { int i=0,j=0; //printf("\n\n-----------------------------------------------------------\n\n"); for(i=0;i<numberOfCodeLines;i++) { printf("\n"); for(j=0;j<4;j++) { printf("%d\t",program_counter[i][j]); } } } //----------------------------------------------------------------------------- //-----------------Functions used for printing--------------------------------- void print_output_function(){ // Function which takes care of printing into output.txt file int i=0,j=0,data_flag=0; for(j=0;j<1000;j++) { data_flag=0; for(i=0;i<1000;i++) // TO check if data existed in a column { if(print_output[i][j]>0&&print_output[i][j]<100) { data_flag=1; } } if(data_flag==1) { fprintf(op,"\nC#%d ",j+1); for(i=0;i<1000;i++) { if(print_output[i][j]!=0) { switch(print_output[i][j]) { case 1: { fprintf(op,"I%d-IF1 ",i+1); break; } case 2: { fprintf(op,"I%d-IF2 ",i+1); break; } case 3: { fprintf(op,"I%d-ID ",i+1); break; } case 4: { fprintf(op,"I%d-EX ",i+1); break; } case 5: { fprintf(op,"I%d-MEM1 ",i+1); break; } case 6: { fprintf(op,"I%d-MEM2 ",i+1); break; } case 7: { fprintf(op,"I%d-MEM3 ",i+1); break; } case 8: { fprintf(op,"I%d-WB ",i+1); break; } case 99: { fprintf(op,"STALL "); break; } }//Switch end }//If end }//all row read for loop } }// All column read for loop } // end function /*-----------------------------------------------------------------------------------------*/ /*-------------------------- Support Functions for printing--------------------------------*/ void print_tabs(int pc_num) { int i=0; for(i=0;i<pc_num+2*flag_tabs;i++) { //printf("\t"); print_output[row][coloumn]=12; coloumn++; } } void branch_tabs(int pc_num) { int i=0; if(numberOfCodeLines-pc_num-1!=0) { for(i=0;i<2*flag_tabs;i++) { //printf("\t"); print_output[row][coloumn]=12; coloumn++; } //printf("I%d-IF1\tI%d-IF2\tI%d-ID\n",pc_num+1,pc_num+1,pc_num+1); print_output[row][coloumn]=1; coloumn++; print_output[row][coloumn]=2; coloumn++; print_output[row][coloumn]=3; coloumn++; } if(numberOfCodeLines-pc_num==3) { if(branched_flag==1&&bnezTracker[2]<bnezTracker[1]) { row++; }else{ row++;coloumn=0; } print_tabs(pc_num); //printf("\t\tI%d-IF1\tI%d-IF2\n",pc_num+2,pc_num+2,pc_num+2); print_output[row][coloumn]=12; coloumn++; print_output[row][coloumn]=12; coloumn++; print_output[row][coloumn]=1; coloumn++; print_output[row][coloumn]=2; coloumn++; }else if(numberOfCodeLines-pc_num>3) { if(branched_flag==1&&bnezTracker[2]<bnezTracker[1]){ row++; }else{ row++;coloumn=0; } print_tabs(pc_num); //printf("\t\tI%d-IF1\tI%d-IF2\n",pc_num+2,pc_num+2); print_output[row][coloumn]=12; coloumn++; print_output[row][coloumn]=12; coloumn++; print_output[row][coloumn]=1; coloumn++; print_output[row][coloumn]=2; coloumn++; row++;coloumn=0; print_tabs(pc_num); //printf("\t\t\tI%d-IF1\n",pc_num+3); print_output[row][coloumn]=12; coloumn++; print_output[row][coloumn]=12; coloumn++; print_output[row][coloumn]=12; coloumn++; print_output[row][coloumn]=1; coloumn++; } } /*----------------------------------------------------------------------------------------------*/ /*--------------------------**** Support Functions for code read****-----------------------------*/ int isAlpha(char *buffer, int position) //support function for code read to check if there is an alphabet { int flag=0; if(buffer[position]>='A'&&buffer[position]<='Z') { flag=1; } return flag; } int isNumber(char *buffer, int position) //support function for code read to check if there is a number { int number=0; while((buffer[position]-'0'>=0&&buffer[position]-'0'<=9)) { number=number*10+(buffer[position]-'0'); //printf("number-%d\n",number); position++; } position++; return number; } int isR(char *buffer, int position) { int flag=0; if(buffer[position]=='R') { flag=1; } return flag; } int isHash(char *buffer, int position) { int flag=0; if(buffer[position]=='#') { flag=1; } return flag; } int isBracket(char *buffer, int position) { int flag=0; if(buffer[position]=='(') { flag=1; } return flag; } /*------------------------------------------------------------------------------------------------*/ /*---------------------------------------- support functions for register and memory read---------*/ int cal_three_registers1(int values[],int j) // Support function for memory read { int i=0,return_value=0; static int q=1; for(i=q-1;i<j;i++) { //printf("values[%d]=%d\n",i,values[i]); return_value=return_value*10+values[i]; } q=i+1; //printf("Final: %d\n",return_value); return return_value; } int cal_three_registers(int values[],int j) // support function tO calc register value and send to register read function { int i=0,return_value=0; static int q=1; for(i=q;i<j;i++) { //printf("values[%d]=%d\n",i,values[i]); return_value=return_value*10+values[i]; } q=i+1; //printf("Final: %d\n",return_value); return return_value; }
C
#include "criptografia.h" void* multiplicacao(void* parametros) { Parameters_multiplicacao *p = (Parameters_multiplicacao *) parametros; printf("Thread Multiplicacao %d iniciou.\n", p->coluna); for (int i = 0; i < p->num_linhas; i++) for (int j = 0; j < 4; j++) p->matriz_codigo[i][p->coluna] += p->matriz_texto[i][j] * p->criptografia[j][p->coluna]; printf("Thread Multiplicacao %d terminou.\n",p->coluna); } int **cria_matriz(int n_linhas) { int **matriz; // aloca um vetor de "linhas" ponteiros para linhas matriz = malloc (n_linhas * sizeof (int*)); // aloca cada uma das linhas (vetores de COL inteiros) for (int i=0; i < n_linhas; i++){ matriz[i] = malloc (4 * sizeof (int)); for (int k = 0; k < 4; k++) matriz[i][k] = 0; } return matriz; } void destroi_matriz(int **matriz, int n_linhas) { // libera a memória da matriz for (int i = 0; i < n_linhas; i++) free (matriz[i]); free (matriz); } p_vetor cria_vetor() { p_vetor v = malloc(sizeof(Array)); v->array_first = NULL; v->array_last = NULL; v->size = 0; return v; } p_vetor inseri_dado(p_vetor vetor, char dado) { p_no p = malloc(sizeof(No)); if (vetor->size == 0) { vetor->array_first = p; vetor->array_last = p; vetor->size += 1; p->c = dado; p->next = NULL; return vetor; } else { vetor->array_last->next = p; vetor->array_last = p; p->c = dado; p->next = NULL; vetor->size += 1; return vetor; } } void destroi_vetor(p_vetor vetor) { p_no p; while (vetor->array_first != NULL) { p = vetor->array_first; vetor->array_first = p->next; free(p); } free(vetor); } void* transforma_texto(void* texto){ parameters_transforma_texto *p = (parameters_transforma_texto *) texto; p_no s = p->mensagem->array_first; for (int i = 0; i < p->caracter_inicial; i++) { s = s->next; } for (int k = p->caracter_inicial; k < p->caracter_final; k++){ p->matriz_resultado[k/4][k%4] = (int) s->c; s = s->next; } }
C
/* ** EPITECH PROJECT, 2018 ** str ** File description: ** lstr_append */ #include "str.h" /** * Appends the specifed string to this string. * * **Does directly modify the original string.** **/ char *lstr_append(char *this, const char *str) { char *ret; if (this == NULL || str == NULL) return (NULL); ret = calloc(strlen(this) + strlen(str) + 1, sizeof(char)); if (ret == NULL) return (NULL); ret = strcat(strcpy(ret, this), str); free(this); return (ret); }
C
/* ** EPITECH PROJECT, 2021 ** MyRPG ** File description: ** Draws the rest of the inventory */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include "Rpg/rpg.h" static inline bool is(sfSprite *s, rpg_t *game) { if (sprite_is_hover(s, get_mouse_pos_vec2f(game->wind)) && game->inventory.mouse_left == PRESS) return (true); return (false); } extern void rpg_inventory_draw_cursor(rpg_t *g) { sfVector2i v = sfMouse_getPositionRenderWindow(g->wind); if (g->inventory.item_selected.name == NULL) return; set_item_texture_rect(g->inventory.sprite, &g->inventory.item_selected); sfSprite_setPosition(g->inventory.sprite, (sfVector2f){v.x, v.y}); sfRenderWindow_drawSprite(g->wind, g->inventory.sprite, NULL); } static void rpg_draw_equipemnt_on_click_behaviour(rpg_t *g, unsigned int i) { item_t tmp; char *sel_name = g->inventory.item_selected.name; char *eq_name = g->inventory.equipement[i].name; if (is(g->inventory.container, g) && sel_name && eq_name) { rpg_copy_item(&tmp, g->inventory.item_selected); rpg_destroy_item(&g->inventory.item_selected); rpg_copy_item(&g->inventory.item_selected, g->inventory.equipement[i]); rpg_copy_item(&g->inventory.equipement[i], tmp); rpg_destroy_item(&tmp); } if (is(g->inventory.container, g) && !sel_name && eq_name) { rpg_copy_item(&g->inventory.item_selected, g->inventory.equipement[i]); rpg_destroy_item(&g->inventory.equipement[i]); g->inventory.mouse_left = HOLD; } if (is(g->inventory.container, g) && sel_name && !eq_name) { rpg_copy_item(&g->inventory.equipement[i], g->inventory.item_selected); rpg_destroy_item(&g->inventory.item_selected); g->inventory.item_selected.name = NULL; } } extern void rpg_draw_equipement(rpg_t *g) { int tooltip = -1; for (unsigned int i = 0; i != 4; i++) { sfSprite_setPosition(g->inventory.container, (sfVector2f){320 * SL(g), (320 + i * 64) * SL(g)}); sfSprite_setPosition(g->inventory.sprite, (sfVector2f){320 * SL(g), (320 + i * 64) * SL(g)}); sfRenderWindow_drawSprite(g->wind, g->inventory.container, NULL); rpg_draw_equipemnt_on_click_behaviour(g, i); if (g->inventory.equipement[i].name != NULL) { set_item_texture_rect( g->inventory.sprite, &g->inventory.equipement[i]); sfRenderWindow_drawSprite(g->wind, g->inventory.sprite, NULL); } if (sprite_is_hover( g->inventory.container, get_mouse_pos_vec2f(g->wind))) tooltip = i; } if (tooltip != -1 && g->inventory.equipement[tooltip].name != NULL) rpg_inventory_draw_items_tooltip(g, &g->inventory.equipement[tooltip]); } extern void rpg_inventory_clean_cursor(rpg_t *g) { if (g->inventory.mouse_left == PRESS && g->inventory.item_selected.name) { rpg_add_item_to_inventory(g, g->inventory.item_selected); g->inventory.item_selected.name = NULL; } }
C
#include <stdio.h> int main(void) { int digit, in, power, temp; int repeat, ri; scanf("%d", &repeat); for(ri = 1; ri <= repeat; ri++){ scanf("%d", &in); /*---------*/ printf("\n"); } }
C
#include <stdio.h> int main() { int nr1, nr2; int *ptr; nr1 = 1; nr2 = 2; ptr = &nr1; printf("\n"); printf("nr1 has the value %d and is stored at %p\n", nr1, &nr1); printf("nr2 has the value %d and is stored at %p\n", nr2, &nr2); printf("ptr has the value %d and is stored at %p\n", ptr, &ptr); printf("The value of the integer pointed to by ptr is %d\n", *ptr); return 0; }
C
#include <stdio.h> #include <string.h> int main(void) { int n; int i; int ch; char name[1000]; while((ch = getchar()) != EOF) { name[i] = ch; i++; } n = strlen(name); for(i = 0; i < n; i++) putchar(name[i]); return 0; }
C
#define MAXSIZE 20 typedef int ElemType; typedef struct { ElemType data[MAXSIZE]; int length; }sqlist; Status ListInsert(sqlist *L,int i,ElemType e){ int n; if (i >= L->length || length == MAXSIZE) return ERROR; if (i<1) return ERROR; for (n = L->length;n>=i;n--){ L->data[n] = l->data[n-1]; } L->data[i-1] = e; L->length++; return OK; }
C
#include <stdlib.h> #include <stdio.h> static int ft_check_symbol_nb(char *line) { int i; int p; int d; i = 0; p = 0; d = 0; while (line[i]) { if (line[i] == '.') p++; if (line[i] == '#') d++; i++; } if (p == 12 && d == 4) return (0); return (-1); } static int ft_check_shape(char **tab) { int i; int j; int s; j = 0; i = 0; s = 0; while (j < 4) { while ((i <= 3) && (tab[j][i])) { if ((i < 3) && tab[j][i] == '#' && tab[j][i + 1] == '#') s++; if ((i > 0) && tab[j][i] == '#' && tab[j][i - 1] == '#') s++; if ((j > 0) && tab[j][i] == '#' && tab[j - 1][i] == '#') s++; if ((j < 3) && tab[j][i] == '#' && tab[j + 1][i] == '#') s++; i++; } i = 0; j++; } if (s == 6 || s == 8) return (1); return (-1); } int main(int ac, char **av) { char **tab; tab = malloc(sizeof(char*) * 4); tab[0] = "...#"; tab[1] = "...#"; tab[2] = "...#"; tab[3] = "...#"; printf("%d",ft_check_shape(tab)); return (0); }
C
/* # probe.c: Code for probing protocols # # Copyright (C) 2007-2012 Yves Rutschle # # 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. # # The full text for the General Public License is here: # http://www.gnu.org/licenses/gpl.html */ #define _GNU_SOURCE #include <stdio.h> #include <regex.h> #include <ctype.h> #include "probe.h" static int is_ssh_protocol(const char *p, int len, struct proto*); static int is_openvpn_protocol(const char *p, int len, struct proto*); static int is_tinc_protocol(const char *p, int len, struct proto*); static int is_xmpp_protocol(const char *p, int len, struct proto*); static int is_http_protocol(const char *p, int len, struct proto*); static int is_tls_protocol(const char *p, int len, struct proto*); static int is_true(const char *p, int len, struct proto* proto) { return 1; } /* Table of protocols that have a built-in probe */ static struct proto builtins[] = { /* description service saddr probe */ { "ssh", "sshd", NULL, is_ssh_protocol}, { "openvpn", NULL, NULL, is_openvpn_protocol }, { "tinc", NULL, NULL, is_tinc_protocol }, { "xmpp", NULL, NULL, is_xmpp_protocol }, { "http", NULL, NULL, is_http_protocol }, { "ssl", NULL, NULL, is_tls_protocol }, { "tls", NULL, NULL, is_tls_protocol }, { "anyprot", NULL, NULL, is_true } }; static struct proto *protocols; static char* on_timeout = "ssh"; struct proto* get_builtins(void) { return builtins; } int get_num_builtins(void) { return ARRAY_SIZE(builtins); } /* Sets the protocol name to connect to in case of timeout */ void set_ontimeout(const char* name) { int res = asprintf(&on_timeout, "%s", name); CHECK_RES_DIE(res, "asprintf"); } /* Returns the protocol to connect to in case of timeout; * if not found, return the first protocol specified */ struct proto* timeout_protocol(void) { struct proto* p = get_first_protocol(); for (; p && strcmp(p->description, on_timeout); p = p->next); if (p) return p; return get_first_protocol(); } /* returns the first protocol (caller can then follow the *next pointers) */ struct proto* get_first_protocol(void) { return protocols; } void set_protocol_list(struct proto* prots) { protocols = prots; } /* From http://grapsus.net/blog/post/Hexadecimal-dump-in-C */ #define HEXDUMP_COLS 16 void hexdump(const char *mem, unsigned int len) { unsigned int i, j; for(i = 0; i < len + ((len % HEXDUMP_COLS) ? (HEXDUMP_COLS - len % HEXDUMP_COLS) : 0); i++) { /* print offset */ if(i % HEXDUMP_COLS == 0) printf("0x%06x: ", i); /* print hex data */ if(i < len) printf("%02x ", 0xFF & mem[i]); else /* end of block, just aligning for ASCII dump */ printf(" "); /* print ASCII dump */ if(i % HEXDUMP_COLS == (HEXDUMP_COLS - 1)) { for(j = i - (HEXDUMP_COLS - 1); j <= i; j++) { if(j >= len) /* end of block, not really printing */ putchar(' '); else if(isprint(mem[j])) /* printable char */ putchar(0xFF & mem[j]); else /* other char */ putchar('.'); } putchar('\n'); } } } /* Is the buffer the beginning of an SSH connection? */ static int is_ssh_protocol(const char *p, int len, struct proto *proto) { if (len < 4) return PROBE_AGAIN; return !strncmp(p, "SSH-", 4); } /* Is the buffer the beginning of an OpenVPN connection? * * Code inspired from OpenVPN port-share option; however, OpenVPN code is * wrong: users using pre-shared secrets have non-initialised key_id fields so * p[3] & 7 should not be looked at, and also the key_method can be specified * to 1 which changes the opcode to P_CONTROL_HARD_RESET_CLIENT_V1. * See: * http://www.fengnet.com/book/vpns%20illustrated%20tunnels%20%20vpnsand%20ipsec/ch08lev1sec5.html * and OpenVPN ssl.c, ssl.h and options.c */ static int is_openvpn_protocol (const char*p,int len, struct proto *proto) { int packet_len; if (len < 2) return PROBE_AGAIN; packet_len = ntohs(*(uint16_t*)p); return packet_len == len - 2; } /* Is the buffer the beginning of a tinc connections? * (protocol is undocumented, but starts with "0 " in 1.0.15) * */ static int is_tinc_protocol( const char *p, int len, struct proto *proto) { if (len < 2) return PROBE_AGAIN; return !strncmp(p, "0 ", 2); } /* Is the buffer the beginning of a jabber (XMPP) connections? * (Protocol is documented (http://tools.ietf.org/html/rfc6120) but for lazy * clients, just checking first frame containing "jabber" in xml entity) * */ static int is_xmpp_protocol( const char *p, int len, struct proto *proto) { if (len < 6) return PROBE_AGAIN; return memmem(p, len, "jabber", 6) ? 1 : 0; } static int probe_http_method(const char *p, int len, const char *opt) { if (len < strlen(opt)) return PROBE_AGAIN; return !strncmp(p, opt, len); } /* Is the buffer the beginning of an HTTP connection? */ static int is_http_protocol(const char *p, int len, struct proto *proto) { int res; /* If it's got HTTP in the request (HTTP/1.1) then it's HTTP */ if (memmem(p, len, "HTTP", 4)) return PROBE_MATCH; #define PROBE_HTTP_METHOD(opt) if ((res = probe_http_method(p, len, opt)) != PROBE_NEXT) return res /* Otherwise it could be HTTP/1.0 without version: check if it's got an * HTTP method (RFC2616 5.1.1) */ PROBE_HTTP_METHOD("OPTIONS"); PROBE_HTTP_METHOD("GET"); PROBE_HTTP_METHOD("HEAD"); PROBE_HTTP_METHOD("POST"); PROBE_HTTP_METHOD("PUT"); PROBE_HTTP_METHOD("DELETE"); PROBE_HTTP_METHOD("TRACE"); PROBE_HTTP_METHOD("CONNECT"); #undef PROBE_HTTP_METHOD return PROBE_NEXT; } static int is_tls_protocol(const char *p, int len, struct proto *proto) { if (len < 3) return PROBE_AGAIN; /* TLS packet starts with a record "Hello" (0x16), followed by version * (0x03 0x00-0x03) (RFC6101 A.1) * This means we reject SSLv2 and lower, which is actually a good thing (RFC6176) */ return p[0] == 0x16 && p[1] == 0x03 && ( p[2] >= 0 && p[2] <= 0x03); } static int regex_probe(const char *p, int len, struct proto *proto) { regex_t **probe = proto->data; regmatch_t pos = { 0, len }; for (; *probe && regexec(*probe, p, 0, &pos, REG_STARTEND); probe++) /* try them all */; return (probe != NULL); } /* * Read the beginning of data coming from the client connection and check if * it's a known protocol. * Return PROBE_AGAIN if not enough data, or PROBE_MATCH if it succeeded in * which case cnx->proto is set to the appropriate protocol. */ int probe_client_protocol(struct connection *cnx) { char buffer[BUFSIZ]; struct proto *p; int n; n = read(cnx->q[0].fd, buffer, sizeof(buffer)); /* It's possible that read() returns an error, e.g. if the client * disconnected between the previous call to select() and now. If that * happens, we just connect to the default protocol so the caller of this * function does not have to deal with a specific failure condition (the * connection will just fail later normally). */ if (n > 0) { int res = PROBE_NEXT; defer_write(&cnx->q[1], buffer, n); for (p = cnx->proto; p && res == PROBE_NEXT; p = p->next) { if (! p->probe) continue; if (verbose) fprintf(stderr, "probing for %s\n", p->description); cnx->proto = p; res = p->probe(cnx->q[1].begin_deferred_data, cnx->q[1].deferred_data_size, p); } if (res != PROBE_NEXT) return res; } if (verbose) fprintf(stderr, "all probes failed, connecting to first protocol: %s\n", protocols->description); /* If none worked, return the first one affected (that's completely * arbitrary) */ cnx->proto = protocols; return PROBE_MATCH; } /* Returns the structure for specified protocol or NULL if not found */ static struct proto* get_protocol(const char* description) { int i; for (i = 0; i < ARRAY_SIZE(builtins); i++) { if (!strcmp(builtins[i].description, description)) { return &builtins[i]; } } return NULL; } /* Returns the probe for specified protocol: * parameter is the description in builtins[], or "regex" * */ T_PROBE* get_probe(const char* description) { struct proto* p = get_protocol(description); if (p) return p->probe; /* Special case of "regex" probe (we don't want to set it in builtins * because builtins is also used to build the command-line options and * regexp is not legal on the command line)*/ if (!strcmp(description, "regex")) return regex_probe; return NULL; }
C
/* hw3-main.c (v1.1) */ #include <stdio.h> #include <stdlib.h> #include <unistd.h> int next_thread_id; /* initialize to 1 */ int max_squares; /* initialize to 0 */ char *** dead_end_boards; /* initialize as array of NULL pointers of size 4 */ /* write the simulate() function and place all of your code in hw3.c */ int simulate( int argc, char * argv[] ); int main( int argc, char * argv[] ) { next_thread_id = 1; max_squares = 0; dead_end_boards = calloc( 4, sizeof( char ** ) ); if ( dead_end_boards == NULL ) { perror( "calloc() failed" ); return EXIT_FAILURE; } int rc = simulate( argc, argv ); /* on Submitty, there will be more code here that validates the global variables at this point... */ // int m = atoi( argv[1] ); // int n = atoi( argv[2] ); // int dead_end_boards_index = ...; /* this is set per each test case */ // for ( int i = 0 ; i < dead_end_boards_index ; i++ ) // { // for ( int j = 0 ; j < m ; j++ ) free( dead_end_boards[i][j] ); // free( dead_end_boards[i] ); // } // free( dead_end_boards ); return rc; } #if 0 bash$ a.out 3 4 0 0 4 S... (*** this diagram is incomplete ***) .... .... (*** this diagram is one possibility ***) / \ THREAD 1 / \ THREAD 2 / \ S3.. S... ..1. .... 2... .1.. / \ \ THREAD 3 / \ THREAD 4 \ / \ \ S36. S3.. etc. ..14 ..1. 25.. 2.4. / \ \ THREAD 5 / \ THREAD 6 \ / \ \ S369 S369 etc. 7a14 b814 258b 25a7 if we instead run hw3 code in NO_PARALLEL mode... S... (*** this diagram is incomplete ***) .... .... (*** this diagram is the only possibility ***) / \ ^^^^ THREAD 1 / \ THREAD 12 / \ S3.. S... ..1. .... 2... .1.. / \ \ THREAD 2 / \ THREAD 5 \ / \ \ TO DO: verify that THREAD 12 is correct S36. S3.. etc. ..14 ..1. TO DO: how many child threads do you end 25.. 2.4. up with (what is next_thread_id at / \ \ the end...) THREAD 3 / \ THREAD 4 \ / \ \ S369 S369 etc. 7a14 b814 258b 25a7 #endif
C
/* E3.c */ #include <stdio.h> #include <math.h> #include <stdlib.h> #include "E3_func.h" #define PI 3.141592653589 /* Main program */ int main() { // Task 1: calculate the integral for different N integral_uniform(); // Task 2: calculate the integral for different N using importance sampling integral_sine(); // Task 3: calculate the integral for different N using importance sampling integral_metropolis(); printf("Done! \n"); }